fix(backups): preserve restore sources across services
Build and publish Docker image / build-and-publish (push) Failing after 2m35s

This commit is contained in:
wfalkowski committed 2026-10-28 09:24:18 +00:00
1 parent ae4b230ee9
commit aa50f96cff
2 files changed
+289 -35

No files matched your search

+45 -4
View File
@@ -26,11 +26,35 @@ class BackupRestoreTests(unittest.TestCase):
f"{self.server_id}-rootdisk",
)
def test_managed_services_use_data_claim(self):
self.assertEqual(
websocket_service._backup_pvc_name({"id": self.server_id, "type": "website"}),
f"{self.server_id}-data",
def test_all_non_vps_services_use_their_data_claim(self):
for server_type in ("website", "database", "game"):
with self.subTest(server_type=server_type):
self.assertEqual(
websocket_service._backup_pvc_name({"id": self.server_id, "type": server_type}),
f"{self.server_id}-data",
)
def test_backup_source_claim_name_is_stable_and_kubernetes_safe(self):
source_name = websocket_service._backup_source_pvc_name(self.backup_id)
self.assertEqual(source_name, "ah-bkp-backuprestoretestsnapshot")
self.assertLessEqual(len(source_name), 63)
def test_restore_claim_can_clone_from_another_pvc(self):
claim = websocket_service._build_snapshot_restore_pvc(
f"{self.server_id}-restore",
"user-test",
"5Gi",
"longhorn",
["ReadWriteOnce"],
"PersistentVolumeClaim",
"ah-bkp-source",
self.server_id,
self.backup_id,
)
self.assertEqual(claim.spec.data_source.kind, "PersistentVolumeClaim")
self.assertIsNone(claim.spec.data_source.api_group)
self.assertEqual(claim.spec.data_source.name, "ah-bkp-source")
self.assertEqual(claim.metadata.labels["backup-id"], self.backup_id)
def test_backup_list_returns_rows_after_access_check(self):
sent = []
@@ -169,6 +193,19 @@ class BackupRestoreTests(unittest.TestCase):
name="restored-volume",
)
def test_restored_longhorn_volume_rejects_failed_clone(self):
volume = {
"status": {
"state": "detached",
"restoreRequired": False,
"cloneStatus": {"state": "failed", "error": "source volume is missing"},
},
}
api = Mock(get_namespaced_custom_object=Mock(return_value=volume))
with patch.object(websocket_service, "custom_objects_api", new=api):
with self.assertRaisesRegex(Exception, "source volume is missing"):
asyncio.run(websocket_service._wait_for_longhorn_restore("restored-volume"))
def test_vps_restore_materializes_snapshot_before_deleting_original_disk(self):
sent = []
pvc_spec = {
@@ -219,6 +256,9 @@ class BackupRestoreTests(unittest.TestCase):
patch.object(websocket_service, "v1") as v1_api,
patch.object(websocket_service, "stop_server", return_value=True),
patch.object(websocket_service, "start_server", return_value=True),
patch.object(websocket_service, "_ensure_backup_source_pvc", new=AsyncMock(return_value="ah-bkp-source")),
patch.object(websocket_service, "_wait_for_server_stopped", new=AsyncMock()),
patch.object(websocket_service, "_wait_for_server_ready", new=AsyncMock()),
patch.object(websocket_service, "_wait_for_data_volume_absent", new=AsyncMock()),
patch.object(websocket_service, "_wait_for_data_volume_ready", new=AsyncMock()),
patch.object(
@@ -248,6 +288,7 @@ class BackupRestoreTests(unittest.TestCase):
self.backup_id,
pvc_spec,
data_volume_name=stage_name,
source_pvc_name="ah-bkp-source",
),
)
stage_creation_index = next(
+244 -31
View File
@@ -2702,6 +2702,11 @@ def _backup_pvc_name(server):
return f"{server['id']}-rootdisk" if server.get('type') == 'vps' else f"{server['id']}-data"
def _backup_source_pvc_name(backup_id):
"""Give each backup an independent PVC so later restores retain their source."""
return f"ah-bkp-{backup_id.replace('-', '')}"
def _get_backup_record(server_id, backup_id):
with database_connection() as conn:
cursor = conn.cursor()
@@ -2813,7 +2818,7 @@ def _build_vps_restore_data_volume(
async def _wait_for_longhorn_restore(volume_name, timeout_seconds=BACKUP_OPERATION_TIMEOUT_SECONDS):
"""Do not start a workload until Longhorn has completed snapshot restoration."""
"""Wait for both snapshot cloning and restore work to finish."""
for _ in range(timeout_seconds // 2):
volume = custom_objects_api.get_namespaced_custom_object(
group='longhorn.io', version='v1beta2', namespace='longhorn-system',
@@ -2822,12 +2827,135 @@ async def _wait_for_longhorn_restore(volume_name, timeout_seconds=BACKUP_OPERATI
status = volume.get('status', {})
if status.get('robustness') == 'faulted' or status.get('state') == 'faulted':
raise Exception(f"Longhorn volume {volume_name} is faulted during restore")
if status.get('restoreRequired') is False:
clone_status = status.get('cloneStatus') or {}
clone_state = str(clone_status.get('state') or '').lower().replace('-', '_')
if clone_state == 'failed':
reason = clone_status.get('error') or f"Longhorn volume {volume_name} failed to clone its restore source"
raise Exception(reason)
clone_ready = not clone_state or clone_state in ('completed', 'complete', 'succeeded')
if status.get('restoreRequired') is False and clone_ready:
return
await asyncio.sleep(2)
raise TimeoutError(f"Longhorn volume {volume_name} did not finish restoring in time")
def _build_snapshot_restore_pvc(
name, namespace, size, storage_class, access_modes, source_kind, source_name,
server_id, backup_id,
):
if source_kind == 'VolumeSnapshot':
data_source = client.V1TypedLocalObjectReference(
api_group='snapshot.storage.k8s.io', kind=source_kind, name=source_name,
)
else:
data_source = client.V1TypedLocalObjectReference(
kind=source_kind, name=source_name,
)
return client.V1PersistentVolumeClaim(
metadata=client.V1ObjectMeta(
name=name,
namespace=namespace,
labels={'app': server_id, 'backup-id': backup_id, 'managed-by': 'anchorhost'},
),
spec=client.V1PersistentVolumeClaimSpec(
access_modes=access_modes,
resources=client.V1VolumeResourceRequirements(requests={'storage': size}),
storage_class_name=storage_class,
data_source=data_source,
),
)
async def _wait_for_server_ready(server, namespace, timeout_seconds=BACKUP_OPERATION_TIMEOUT_SECONDS):
"""Wait until the restored VM or every server container is ready."""
server_id = server['id']
if server.get('type') == 'vps':
ready = await asyncio.to_thread(k8s_manager.wait_for_vm_ready, namespace, server_id, timeout_seconds)
if not ready:
raise TimeoutError(f"Restored VPS {server_id} did not become ready in time")
return
for _ in range(timeout_seconds // 2):
pods = v1.list_namespaced_pod(namespace, label_selector=f'app={server_id}').items
if pods and all(
pod.status.phase == 'Running'
and pod.status.container_statuses
and all(container.ready for container in pod.status.container_statuses)
for pod in pods
):
return
await asyncio.sleep(2)
raise TimeoutError(f"Restored server {server_id} did not become ready in time")
async def _wait_for_server_stopped(server, namespace, timeout_seconds=BACKUP_OPERATION_TIMEOUT_SECONDS):
server_id = server['id']
if server.get('type') == 'vps':
for _ in range(timeout_seconds // 2):
status = await asyncio.to_thread(k8s_manager.get_vm_status, namespace, server_id)
if status.get('runStrategy') == 'Halted' and status.get('phase') == 'Stopped':
return
await asyncio.sleep(2)
raise TimeoutError("The VPS is still shutting down; its storage was not changed")
for _ in range(timeout_seconds // 2):
pods = v1.list_namespaced_pod(namespace, label_selector=f"app={server_id}").items
if not pods:
return
await asyncio.sleep(2)
raise TimeoutError("The server is still shutting down; its storage was not changed")
async def _ensure_backup_source_pvc(server, namespace, backup_id, snapshot, pvc_spec):
"""Materialize and retain a backup-owned copy before replacing a live PVC."""
server_id = server['id']
source_name = _backup_source_pvc_name(backup_id)
if server.get('type') == 'vps':
try:
source_volume = custom_objects_api.get_namespaced_custom_object(
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
plural='datavolumes', name=source_name,
)
labels = source_volume.get('metadata', {}).get('labels', {})
if labels.get('app') != server_id or labels.get('backup-id') != backup_id:
raise Exception(f"A conflicting backup source volume {source_name} already exists")
except ApiException as error:
if error.status != 404:
raise
custom_objects_api.create_namespaced_custom_object(
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
plural='datavolumes',
body=_build_vps_restore_data_volume(
server_id, namespace, backup_id, pvc_spec,
data_volume_name=source_name,
),
)
await _wait_for_data_volume_ready(source_name, namespace)
source_pvc = await _wait_for_pvc_bound(source_name, namespace)
else:
try:
source_pvc = v1.read_namespaced_persistent_volume_claim(source_name, namespace)
labels = source_pvc.metadata.labels or {}
if labels.get('app') != server_id or labels.get('backup-id') != backup_id:
raise Exception(f"A conflicting backup source claim {source_name} already exists")
except ApiException as error:
if error.status != 404:
raise
v1.create_namespaced_persistent_volume_claim(
namespace=namespace,
body=_build_snapshot_restore_pvc(
source_name, namespace, pvc_spec['resources']['requests']['storage'],
pvc_spec.get('storageClassName'), pvc_spec.get('accessModes') or ['ReadWriteOnce'],
'VolumeSnapshot', backup_id, server_id, backup_id,
),
)
source_pvc = await _wait_for_pvc_bound(source_name, namespace)
if not source_pvc.spec.volume_name:
raise Exception(f"Backup source claim {source_name} is not bound to a volume")
await _wait_for_longhorn_restore(source_pvc.spec.volume_name)
return source_name
async def handle_get_backups(client_id, data):
"""List backups for a server the requester is allowed to manage."""
client_info = connected_clients.get(client_id)
@@ -2920,6 +3048,43 @@ async def handle_create_backup(client_id, data):
try:
if server.get('image') == 'minecraft':
await execute_minecraft_save_all(server_id)
source_name = _backup_source_pvc_name(backup_id)
if server.get('type') == 'vps':
source_volume = custom_objects_api.get_namespaced_custom_object(
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
plural='datavolumes', name=pvc_name,
)
source_pvc_spec = source_volume.get('spec', {}).get('pvc')
if not source_pvc_spec:
raise Exception("The VPS disk is not managed by a supported DataVolume")
custom_objects_api.create_namespaced_custom_object(
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
plural='datavolumes',
body=_build_vps_restore_data_volume(
server_id, namespace, backup_id, source_pvc_spec,
data_volume_name=source_name, source_pvc_name=pvc_name,
),
)
await _wait_for_data_volume_ready(source_name, namespace)
source_pvc = await _wait_for_pvc_bound(source_name, namespace)
else:
source_spec = {
'resources': {'requests': {'storage': pvc.spec.resources.requests['storage']}},
'storageClassName': pvc.spec.storage_class_name,
'accessModes': pvc.spec.access_modes or ['ReadWriteOnce'],
}
v1.create_namespaced_persistent_volume_claim(
namespace=namespace,
body=_build_snapshot_restore_pvc(
source_name, namespace, source_spec['resources']['requests']['storage'],
source_spec['storageClassName'], source_spec['accessModes'],
'PersistentVolumeClaim', pvc_name, server_id, backup_id,
),
)
source_pvc = await _wait_for_pvc_bound(source_name, namespace)
if not source_pvc.spec.volume_name:
raise Exception(f"Backup source claim {source_name} is not bound to a volume")
await _wait_for_longhorn_restore(source_pvc.spec.volume_name)
snapshot_obj = {
'apiVersion': 'snapshot.storage.k8s.io/v1',
'kind': 'VolumeSnapshot',
@@ -2930,7 +3095,7 @@ async def handle_create_backup(client_id, data):
},
'spec': {
'volumeSnapshotClassName': BACKUP_SNAPSHOT_CLASS,
'source': {'persistentVolumeClaimName': pvc_name},
'source': {'persistentVolumeClaimName': source_name},
},
}
custom_objects_api.create_namespaced_custom_object(
@@ -3006,7 +3171,7 @@ async def handle_delete_backup(client_id, data):
return
try:
namespace, _ = get_server_access_and_namespace(server_id, user_id)
namespace, server = get_server_access_and_namespace(server_id, user_id)
backup = _get_backup_record(server_id, backup_id)
if not backup:
raise Exception("Backup not found for this server")
@@ -3027,6 +3192,34 @@ async def handle_delete_backup(client_id, data):
except ApiException as legacy_error:
if legacy_error.status != 404:
raise
source_name = _backup_source_pvc_name(backup_id)
if server.get('type') == 'vps':
try:
source_volume = custom_objects_api.get_namespaced_custom_object(
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
plural='datavolumes', name=source_name,
)
labels = source_volume.get('metadata', {}).get('labels', {})
if labels.get('app') != server_id or labels.get('backup-id') != backup_id:
raise Exception(f"Refusing to delete conflicting backup source volume {source_name}")
custom_objects_api.delete_namespaced_custom_object(
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
plural='datavolumes', name=source_name,
)
await _wait_for_data_volume_absent(source_name, namespace)
except ApiException as error:
if error.status != 404:
raise
try:
source_pvc = v1.read_namespaced_persistent_volume_claim(source_name, namespace)
labels = source_pvc.metadata.labels or {}
if labels.get('app') != server_id or labels.get('backup-id') != backup_id:
raise Exception(f"Refusing to delete conflicting backup source claim {source_name}")
v1.delete_namespaced_persistent_volume_claim(source_name, namespace)
await _wait_for_pvc_absent(source_name, namespace)
except ApiException as error:
if error.status != 404:
raise
with database_connection() as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM backups WHERE id = ? AND server_id = ?', (backup_id, server_id))
@@ -3071,6 +3264,7 @@ async def handle_restore_backup(client_id, data):
raise Exception("This restore point is not ready to use")
pvc_name = _backup_pvc_name(server)
backup_source_name = _backup_source_pvc_name(backup_id)
old_data_volume = None
if server.get('type') == 'vps':
old_data_volume = custom_objects_api.get_namespaced_custom_object(
@@ -3084,6 +3278,12 @@ async def handle_restore_backup(client_id, data):
storage_size = old_pvc.spec.resources.requests['storage']
storage_class = old_pvc.spec.storage_class_name
access_modes = old_pvc.spec.access_modes or ['ReadWriteOnce']
pvc_spec = {
'resources': {'requests': {'storage': storage_size}},
'storageClassName': storage_class,
'accessModes': access_modes,
}
await _ensure_backup_source_pvc(server, namespace, backup_id, snapshot, pvc_spec)
async def notify_progress(message):
await send_message(client_id, {
@@ -3094,21 +3294,15 @@ async def handle_restore_backup(client_id, data):
if not stop_server(server_id, user_id):
raise Exception("The server could not be stopped; its storage was not changed")
logger.info("Waiting for server %s pods to stop before restoring", server_id)
for _ in range(BACKUP_OPERATION_TIMEOUT_SECONDS // 2):
pods = v1.list_namespaced_pod(namespace, label_selector=f"app={server_id}")
if not pods.items:
break
await asyncio.sleep(2)
else:
raise TimeoutError("The server is still shutting down; its storage was not changed")
logger.info("Waiting for server %s workloads to stop before restoring", server_id)
await _wait_for_server_stopped(server, namespace)
await notify_progress('Recreating volume from backup...')
staging_name = f'{server_id}-restore-{backup_id[:8]}'
if old_data_volume:
# Longhorn stores CSI snapshots on their source volume. CDI's clone
# from a snapshot still needs that source volume while it materializes
# the restored disk, so never delete the current disk first.
staging_name = f'{server_id}-restore-{backup_id[:8]}'
try:
staging_volume = custom_objects_api.get_namespaced_custom_object(
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
@@ -3141,7 +3335,7 @@ async def handle_restore_backup(client_id, data):
plural='datavolumes',
body=_build_vps_restore_data_volume(
server_id, namespace, backup_id, data_volume_pvc_spec,
data_volume_name=staging_name,
data_volume_name=staging_name, source_pvc_name=backup_source_name,
),
)
await _wait_for_data_volume_ready(staging_name, namespace)
@@ -3175,20 +3369,37 @@ async def handle_restore_backup(client_id, data):
)
await _wait_for_data_volume_ready(pvc_name, namespace)
else:
try:
stage_pvc = v1.read_namespaced_persistent_volume_claim(staging_name, namespace)
stage_labels = stage_pvc.metadata.labels or {}
if stage_labels.get('app') != server_id or stage_labels.get('backup-id') != backup_id:
raise Exception(f"A conflicting restore staging claim {staging_name} already exists")
except ApiException as error:
if error.status != 404:
raise
v1.create_namespaced_persistent_volume_claim(
namespace=namespace,
body=_build_snapshot_restore_pvc(
staging_name, namespace, storage_size, storage_class, access_modes,
'PersistentVolumeClaim', backup_source_name, server_id, backup_id,
),
)
stage_pvc = await _wait_for_pvc_bound(staging_name, namespace)
if not stage_pvc.spec.volume_name:
raise Exception("Staged restore claim is bound without a Longhorn volume")
await _wait_for_longhorn_restore(stage_pvc.spec.volume_name)
# Keep the backup-owned source claim alive. Longhorn CSI snapshots
# live on their source volume and become unusable if it is deleted.
v1.delete_namespaced_persistent_volume_claim(pvc_name, namespace)
await _wait_for_pvc_absent(pvc_name, namespace)
pvc_body = client.V1PersistentVolumeClaim(
metadata=client.V1ObjectMeta(name=pvc_name),
spec=client.V1PersistentVolumeClaimSpec(
access_modes=access_modes,
resources=client.V1VolumeResourceRequirements(requests={'storage': storage_size}),
storage_class_name=storage_class,
data_source=client.V1TypedLocalObjectReference(
api_group='snapshot.storage.k8s.io', kind='VolumeSnapshot', name=backup_id,
),
v1.create_namespaced_persistent_volume_claim(
namespace=namespace,
body=_build_snapshot_restore_pvc(
pvc_name, namespace, storage_size, storage_class, access_modes,
'PersistentVolumeClaim', staging_name, server_id, backup_id,
),
)
v1.create_namespaced_persistent_volume_claim(namespace=namespace, body=pvc_body)
restored_pvc = await _wait_for_pvc_bound(pvc_name, namespace)
if not restored_pvc.spec.volume_name:
raise Exception("Restored claim is bound without a Longhorn volume")
@@ -3197,13 +3408,15 @@ async def handle_restore_backup(client_id, data):
await notify_progress('Restore finished. Starting server...')
if not start_server(server_id, user_id):
raise Exception("Files were restored, but the server could not be started. Start it from Overview.")
if old_data_volume:
await _wait_for_server_ready(server, namespace)
if staging_name:
try:
custom_objects_api.delete_namespaced_custom_object(
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
plural='datavolumes', name=staging_name,
)
await _wait_for_data_volume_absent(staging_name, namespace)
if old_data_volume:
custom_objects_api.delete_namespaced_custom_object(
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
plural='datavolumes', name=staging_name,
)
await _wait_for_data_volume_absent(staging_name, namespace)
try:
v1.delete_namespaced_persistent_volume_claim(staging_name, namespace)
except ApiException as error:
@@ -3212,7 +3425,7 @@ async def handle_restore_backup(client_id, data):
await _wait_for_pvc_absent(staging_name, namespace)
except Exception:
logger.warning("Could not clean up restore staging claim %s", staging_name, exc_info=True)
await notify_progress('Restoration completed successfully. Server is starting.')
await notify_progress('Restoration completed successfully. Server is ready.')
logger.info("Successfully restored backup %s for server %s", backup_id, server_id)
except Exception as error:
logger.exception("Error restoring backup %s for server %s", backup_id, server_id)