fix: use CSI snapshots for server backups
Build and publish Docker image / build-and-publish (push) Successful in 11s
Build and publish Docker image / build-and-publish (push) Successful in 11s
This commit is contained in:
1 parent
59afb2ed03
commit
b8be6ad2fb
4 files changed
+431
-201
No files matched your search
@@ -51,6 +51,20 @@ Build the image locally with:
|
|||||||
docker build -t anchorhost-backend:local .
|
docker build -t anchorhost-backend:local .
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Longhorn backups
|
||||||
|
|
||||||
|
Server backups use Kubernetes CSI `VolumeSnapshot` resources. The cluster must have the matching snapshot CRDs and controller installed, plus the `longhorn-snapshot` `VolumeSnapshotClass` in [`k8s/longhorn-snapshot-class.yaml`](k8s/longhorn-snapshot-class.yaml). Keep the external-snapshotter CRD/controller release aligned with the CSI snapshotter sidecar bundled with Longhorn. For the current Longhorn 1.9.0 setup, that version is v8.2.0.
|
||||||
|
|
||||||
|
On a cluster that does not provide the snapshot CRDs, install the CRDs from the pinned external-snapshotter release and apply the class:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl apply -k 'https://github.com/kubernetes-csi/external-snapshotter/client/config/crd?ref=v8.2.0'
|
||||||
|
kubectl apply -k 'https://github.com/kubernetes-csi/external-snapshotter/deploy/kubernetes/snapshot-controller?ref=v8.2.0'
|
||||||
|
kubectl apply -f k8s/longhorn-snapshot-class.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
The snapshot controller must also be running. Before upgrading Longhorn or the snapshotter, check the matching CRD/controller version in the Longhorn release documentation. A backup is only marked **Completed** after the CSI snapshot reports `readyToUse`; restores verify the snapshot and wait for Longhorn to finish restoring the volume before starting the server.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
| Variable | Purpose |
|
| Variable | Purpose |
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
apiVersion: snapshot.storage.k8s.io/v1
|
||||||
|
kind: VolumeSnapshotClass
|
||||||
|
metadata:
|
||||||
|
name: longhorn-snapshot
|
||||||
|
driver: driver.longhorn.io
|
||||||
|
deletionPolicy: Delete
|
||||||
|
parameters:
|
||||||
|
type: snap
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import AsyncMock, Mock, patch
|
||||||
|
|
||||||
|
from kubernetes.client.rest import ApiException
|
||||||
|
|
||||||
|
import websocket_service
|
||||||
|
|
||||||
|
|
||||||
|
class BackupRestoreTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.client_id = "backup-restore-test-client"
|
||||||
|
self.server_id = "backup-restore-test-server"
|
||||||
|
self.backup_id = "backup-restore-test-snapshot"
|
||||||
|
websocket_service.connected_clients[self.client_id] = {
|
||||||
|
"authenticated": True,
|
||||||
|
"user_id": "backup-restore-test-user",
|
||||||
|
}
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
websocket_service.connected_clients.pop(self.client_id, None)
|
||||||
|
|
||||||
|
def test_vps_uses_root_disk_claim(self):
|
||||||
|
self.assertEqual(
|
||||||
|
websocket_service._backup_pvc_name({"id": self.server_id, "type": "vps"}),
|
||||||
|
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_vps_restore_uses_cdi_snapshot_source_and_preserves_disk_request(self):
|
||||||
|
pvc_spec = {
|
||||||
|
"accessModes": ["ReadWriteOnce"],
|
||||||
|
"resources": {"requests": {"storage": "10Gi"}},
|
||||||
|
"storageClassName": "longhorn",
|
||||||
|
}
|
||||||
|
data_volume = websocket_service._build_vps_restore_data_volume(
|
||||||
|
self.server_id, "user-test", self.backup_id, pvc_spec
|
||||||
|
)
|
||||||
|
self.assertEqual(data_volume["spec"]["source"]["snapshot"], {
|
||||||
|
"name": self.backup_id,
|
||||||
|
"namespace": "user-test",
|
||||||
|
})
|
||||||
|
self.assertEqual(data_volume["spec"]["pvc"], pvc_spec)
|
||||||
|
|
||||||
|
def test_restore_refuses_missing_snapshot_before_stopping_server(self):
|
||||||
|
sent = []
|
||||||
|
|
||||||
|
async def capture_message(_client_id, message):
|
||||||
|
sent.append(message)
|
||||||
|
|
||||||
|
missing_snapshot = ApiException(status=404, reason="Not Found")
|
||||||
|
with (
|
||||||
|
patch.object(websocket_service, "send_message", new=AsyncMock(side_effect=capture_message)),
|
||||||
|
patch.object(websocket_service, "get_server_access_and_namespace", return_value=("user-test", {"id": self.server_id, "type": "vps"})),
|
||||||
|
patch.object(websocket_service, "_get_backup_record", return_value={"id": self.backup_id, "status": "Completed"}),
|
||||||
|
patch.object(websocket_service.k8s_manager, "connected", True),
|
||||||
|
patch.object(websocket_service, "custom_objects_api", new=Mock(get_namespaced_custom_object=Mock(side_effect=missing_snapshot))),
|
||||||
|
patch.object(websocket_service, "stop_server") as stop_server,
|
||||||
|
):
|
||||||
|
asyncio.run(websocket_service.handle_restore_backup(self.client_id, {
|
||||||
|
"serverId": self.server_id,
|
||||||
|
"backupId": self.backup_id,
|
||||||
|
}))
|
||||||
|
|
||||||
|
stop_server.assert_not_called()
|
||||||
|
self.assertTrue(any("restore point is unavailable" in m.get("error", "").lower() for m in sent))
|
||||||
|
|
||||||
|
def test_restore_waits_until_claim_is_actually_gone(self):
|
||||||
|
with (
|
||||||
|
patch.object(websocket_service, "v1", new=Mock(read_namespaced_persistent_volume_claim=Mock(return_value=object()))),
|
||||||
|
patch.object(websocket_service.asyncio, "sleep", new=AsyncMock()),
|
||||||
|
):
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
asyncio.run(websocket_service._wait_for_pvc_absent("server-rootdisk", "user-test", timeout_seconds=2))
|
||||||
|
|
||||||
|
def test_volume_snapshot_must_be_ready_before_backup_is_complete(self):
|
||||||
|
snapshot = {"status": {"readyToUse": True, "restoreSize": "5Gi"}}
|
||||||
|
api = Mock(get_namespaced_custom_object=Mock(return_value=snapshot))
|
||||||
|
with patch.object(websocket_service, "custom_objects_api", new=api):
|
||||||
|
result = asyncio.run(websocket_service._wait_for_volume_snapshot("user-test", self.backup_id))
|
||||||
|
self.assertEqual(result, snapshot)
|
||||||
|
api.get_namespaced_custom_object.assert_called_once_with(
|
||||||
|
group="snapshot.storage.k8s.io",
|
||||||
|
version="v1",
|
||||||
|
namespace="user-test",
|
||||||
|
plural="volumesnapshots",
|
||||||
|
name=self.backup_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_restored_longhorn_volume_must_finish_restoring(self):
|
||||||
|
volume = {"status": {"state": "attached", "restoreRequired": False, "robustness": "unknown"}}
|
||||||
|
api = Mock(get_namespaced_custom_object=Mock(return_value=volume))
|
||||||
|
with patch.object(websocket_service, "custom_objects_api", new=api):
|
||||||
|
asyncio.run(websocket_service._wait_for_longhorn_restore("restored-volume"))
|
||||||
|
api.get_namespaced_custom_object.assert_called_once_with(
|
||||||
|
group="longhorn.io",
|
||||||
|
version="v1beta2",
|
||||||
|
namespace="longhorn-system",
|
||||||
|
plural="volumes",
|
||||||
|
name="restored-volume",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
+299
-201
@@ -2694,8 +2694,130 @@ async def handle_update_minecraft_settings(client_id, data):
|
|||||||
logger.error(f"Error updating Minecraft settings: {e}")
|
logger.error(f"Error updating Minecraft settings: {e}")
|
||||||
await send_message(client_id, {'type': 'error', 'error': str(e)})
|
await send_message(client_id, {'type': 'error', 'error': str(e)})
|
||||||
|
|
||||||
|
BACKUP_SNAPSHOT_CLASS = "longhorn-snapshot"
|
||||||
|
BACKUP_OPERATION_TIMEOUT_SECONDS = 300
|
||||||
|
|
||||||
|
|
||||||
|
def _backup_pvc_name(server):
|
||||||
|
return f"{server['id']}-rootdisk" if server.get('type') == 'vps' else f"{server['id']}-data"
|
||||||
|
|
||||||
|
|
||||||
|
def _get_backup_record(server_id, backup_id):
|
||||||
|
with database_connection() as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute('SELECT * FROM backups WHERE id = ? AND server_id = ?', (backup_id, server_id))
|
||||||
|
row = cursor.fetchone()
|
||||||
|
return dict_from_row(row) if row else None
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_for_volume_snapshot(namespace, backup_id, timeout_seconds=BACKUP_OPERATION_TIMEOUT_SECONDS):
|
||||||
|
"""Wait until CSI reports a VolumeSnapshot ready for use."""
|
||||||
|
for _ in range(timeout_seconds // 2):
|
||||||
|
snapshot = custom_objects_api.get_namespaced_custom_object(
|
||||||
|
group="snapshot.storage.k8s.io",
|
||||||
|
version="v1",
|
||||||
|
namespace=namespace,
|
||||||
|
plural="volumesnapshots",
|
||||||
|
name=backup_id,
|
||||||
|
)
|
||||||
|
status = snapshot.get('status', {})
|
||||||
|
if status.get('error'):
|
||||||
|
raise Exception(status['error'].get('message') or f"Snapshot {backup_id} failed")
|
||||||
|
if status.get('readyToUse'):
|
||||||
|
return snapshot
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
raise TimeoutError(f"Snapshot {backup_id} did not become ready within {timeout_seconds} seconds")
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_for_pvc_absent(pvc_name, namespace, timeout_seconds=BACKUP_OPERATION_TIMEOUT_SECONDS):
|
||||||
|
"""Wait for PVC deletion to finish; never race a create against a terminating claim."""
|
||||||
|
for _ in range(timeout_seconds // 2):
|
||||||
|
try:
|
||||||
|
v1.read_namespaced_persistent_volume_claim(pvc_name, namespace)
|
||||||
|
except ApiException as error:
|
||||||
|
if error.status == 404:
|
||||||
|
return
|
||||||
|
raise
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
raise TimeoutError(f"Storage claim {pvc_name} is still present; refusing to create a conflicting claim")
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_for_pvc_bound(pvc_name, namespace, timeout_seconds=BACKUP_OPERATION_TIMEOUT_SECONDS):
|
||||||
|
for _ in range(timeout_seconds // 2):
|
||||||
|
pvc = v1.read_namespaced_persistent_volume_claim(pvc_name, namespace)
|
||||||
|
if pvc.status and pvc.status.phase == 'Bound':
|
||||||
|
return pvc
|
||||||
|
if pvc.status and pvc.status.phase in ('Lost', 'Failed'):
|
||||||
|
raise Exception(f"Restored storage claim entered {pvc.status.phase} state")
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
raise TimeoutError(f"Restored storage claim {pvc_name} did not become ready in time")
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_for_data_volume_absent(data_volume_name, namespace, timeout_seconds=BACKUP_OPERATION_TIMEOUT_SECONDS):
|
||||||
|
for _ in range(timeout_seconds // 2):
|
||||||
|
try:
|
||||||
|
custom_objects_api.get_namespaced_custom_object(
|
||||||
|
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
|
||||||
|
plural='datavolumes', name=data_volume_name,
|
||||||
|
)
|
||||||
|
except ApiException as error:
|
||||||
|
if error.status == 404:
|
||||||
|
return
|
||||||
|
raise
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
raise TimeoutError(f"DataVolume {data_volume_name} is still present; refusing to create a conflicting volume")
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_for_data_volume_ready(data_volume_name, namespace, timeout_seconds=BACKUP_OPERATION_TIMEOUT_SECONDS):
|
||||||
|
for _ in range(timeout_seconds // 2):
|
||||||
|
data_volume = custom_objects_api.get_namespaced_custom_object(
|
||||||
|
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
|
||||||
|
plural='datavolumes', name=data_volume_name,
|
||||||
|
)
|
||||||
|
status = data_volume.get('status', {})
|
||||||
|
if status.get('phase') == 'Succeeded':
|
||||||
|
return data_volume
|
||||||
|
if status.get('phase') == 'Failed':
|
||||||
|
reason = next((condition.get('message') for condition in status.get('conditions', []) if condition.get('message')), None)
|
||||||
|
raise Exception(reason or f"DataVolume {data_volume_name} failed to restore")
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
raise TimeoutError(f"DataVolume {data_volume_name} did not finish restoring in time")
|
||||||
|
|
||||||
|
|
||||||
|
def _build_vps_restore_data_volume(server_id, namespace, backup_id, pvc_spec):
|
||||||
|
return {
|
||||||
|
'apiVersion': 'cdi.kubevirt.io/v1beta1',
|
||||||
|
'kind': 'DataVolume',
|
||||||
|
'metadata': {
|
||||||
|
'name': f'{server_id}-rootdisk',
|
||||||
|
'namespace': namespace,
|
||||||
|
'labels': {'app': server_id, 'managed-by': 'anchorhost', 'server-type': 'vps'},
|
||||||
|
},
|
||||||
|
'spec': {
|
||||||
|
'source': {'snapshot': {'name': backup_id, 'namespace': namespace}},
|
||||||
|
'pvc': pvc_spec,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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."""
|
||||||
|
for _ in range(timeout_seconds // 2):
|
||||||
|
volume = custom_objects_api.get_namespaced_custom_object(
|
||||||
|
group='longhorn.io', version='v1beta2', namespace='longhorn-system',
|
||||||
|
plural='volumes', name=volume_name,
|
||||||
|
)
|
||||||
|
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:
|
||||||
|
return
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
raise TimeoutError(f"Longhorn volume {volume_name} did not finish restoring in time")
|
||||||
|
|
||||||
|
|
||||||
async def handle_get_backups(client_id, data):
|
async def handle_get_backups(client_id, data):
|
||||||
"""List backups for a server"""
|
"""List backups for a server the requester is allowed to manage."""
|
||||||
client_info = connected_clients.get(client_id)
|
client_info = connected_clients.get(client_id)
|
||||||
if not client_info or not client_info['authenticated']:
|
if not client_info or not client_info['authenticated']:
|
||||||
await send_message(client_id, {'type': 'error', 'error': 'Not authenticated'})
|
await send_message(client_id, {'type': 'error', 'error': 'Not authenticated'})
|
||||||
@@ -2707,23 +2829,46 @@ async def handle_get_backups(client_id, data):
|
|||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
get_server_access_and_namespace(server_id, client_info['user_id'])
|
||||||
with database_connection() as conn:
|
with database_connection() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute('SELECT * FROM backups WHERE server_id = ? ORDER BY created_at DESC', (server_id,))
|
cursor.execute('SELECT * FROM backups WHERE server_id = ? ORDER BY created_at DESC', (server_id,))
|
||||||
rows = cursor.fetchall()
|
backups = [dict_from_row(row) for row in cursor.fetchall()]
|
||||||
backups = [dict_from_row(row) for row in rows]
|
if k8s_manager.connected:
|
||||||
|
for backup in backups:
|
||||||
|
if backup.get('status') != 'Completed':
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
custom_objects_api.get_namespaced_custom_object(
|
||||||
|
group='snapshot.storage.k8s.io', version='v1', namespace=namespace,
|
||||||
|
plural='volumesnapshots', name=backup['id'],
|
||||||
|
)
|
||||||
|
except ApiException as snapshot_error:
|
||||||
|
if snapshot_error.status != 404:
|
||||||
|
raise
|
||||||
|
try:
|
||||||
|
custom_objects_api.get_namespaced_custom_object(
|
||||||
|
group='longhorn.io', version='v1beta2', namespace='longhorn-system',
|
||||||
|
plural='snapshots', name=backup['id'],
|
||||||
|
)
|
||||||
|
backup['status'] = 'Unavailable'
|
||||||
|
backup['unavailableReason'] = 'This older snapshot format cannot be restored by the current panel. Create a new backup before making changes.'
|
||||||
|
except ApiException as legacy_error:
|
||||||
|
if legacy_error.status != 404:
|
||||||
|
raise
|
||||||
|
backup['status'] = 'Failed'
|
||||||
|
backup['unavailableReason'] = 'The stored snapshot is missing and cannot be restored.'
|
||||||
|
cursor.execute('UPDATE backups SET status = ? WHERE id = ? AND server_id = ?',
|
||||||
|
('Failed', backup['id'], server_id))
|
||||||
|
conn.commit()
|
||||||
|
await send_message(client_id, {'type': 'backups_list', 'serverId': server_id, 'backups': backups})
|
||||||
|
except Exception as error:
|
||||||
|
logger.error("Error getting backups for %s: %s", server_id, error)
|
||||||
|
await send_message(client_id, {'type': 'error', 'serverId': server_id, 'error': str(error)})
|
||||||
|
|
||||||
await send_message(client_id, {
|
|
||||||
'type': 'backups_list',
|
|
||||||
'serverId': server_id,
|
|
||||||
'backups': backups
|
|
||||||
})
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error getting backups: {e}")
|
|
||||||
await send_message(client_id, {'type': 'error', 'error': str(e)})
|
|
||||||
|
|
||||||
async def handle_create_backup(client_id, data):
|
async def handle_create_backup(client_id, data):
|
||||||
"""Trigger a new backup for a server"""
|
"""Create a CSI VolumeSnapshot and persist it as a manual backup."""
|
||||||
client_info = connected_clients.get(client_id)
|
client_info = connected_clients.get(client_id)
|
||||||
if not client_info or not client_info['authenticated']:
|
if not client_info or not client_info['authenticated']:
|
||||||
await send_message(client_id, {'type': 'error', 'error': 'Not authenticated'})
|
await send_message(client_id, {'type': 'error', 'error': 'Not authenticated'})
|
||||||
@@ -2731,21 +2876,21 @@ async def handle_create_backup(client_id, data):
|
|||||||
|
|
||||||
user_id = client_info['user_id']
|
user_id = client_info['user_id']
|
||||||
server_id = data.get('serverId')
|
server_id = data.get('serverId')
|
||||||
backup_name = data.get('name', f"Manual Backup {datetime.now().strftime('%Y-%m-%d %H:%M')}")
|
|
||||||
|
|
||||||
if not server_id:
|
if not server_id:
|
||||||
await send_message(client_id, {'type': 'error', 'error': 'Server ID required'})
|
await send_message(client_id, {'type': 'error', 'error': 'Server ID required'})
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
|
||||||
# Get server info
|
|
||||||
server = get_server_by_id(server_id)
|
|
||||||
if not server:
|
|
||||||
raise Exception("Server not found")
|
|
||||||
|
|
||||||
backup_id = str(uuid.uuid4())
|
backup_id = str(uuid.uuid4())
|
||||||
|
backup_name = str(data.get('name') or '').strip() or f"Manual Backup {datetime.now().strftime('%Y-%m-%d %H:%M')}"
|
||||||
|
try:
|
||||||
|
namespace, server = get_server_access_and_namespace(server_id, user_id)
|
||||||
|
if not k8s_manager.connected:
|
||||||
|
raise Exception("Storage service is unavailable; backup was not created")
|
||||||
|
pvc_name = _backup_pvc_name(server)
|
||||||
|
pvc = v1.read_namespaced_persistent_volume_claim(pvc_name, namespace)
|
||||||
|
if not pvc.spec.volume_name:
|
||||||
|
raise Exception(f"Storage claim {pvc_name} is not bound to a volume")
|
||||||
|
|
||||||
# Insert into DB
|
|
||||||
with database_connection() as conn:
|
with database_connection() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute('''
|
cursor.execute('''
|
||||||
@@ -2754,125 +2899,62 @@ async def handle_create_backup(client_id, data):
|
|||||||
''', (backup_id, server_id, backup_name, 'Manual', 'In Progress', datetime.now()))
|
''', (backup_id, server_id, backup_name, 'Manual', 'In Progress', datetime.now()))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
# Notify client
|
|
||||||
await send_message(client_id, {
|
await send_message(client_id, {
|
||||||
'type': 'backup_status_updated',
|
'type': 'backup_status_updated', 'serverId': server_id,
|
||||||
'serverId': server_id,
|
'backup': {'id': backup_id, 'status': 'In Progress', 'name': backup_name}
|
||||||
'backup': {
|
|
||||||
'id': backup_id,
|
|
||||||
'status': 'In Progress',
|
|
||||||
'name': backup_name
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
# Start backup in background thread/task
|
|
||||||
async def run_backup():
|
async def run_backup():
|
||||||
try:
|
try:
|
||||||
server_type = server.get('type')
|
if server.get('image') == 'minecraft':
|
||||||
image = server.get('image')
|
|
||||||
k8s_name = server.get('k8s_name')
|
|
||||||
namespace = server.get('namespace')
|
|
||||||
|
|
||||||
# 1. Minecraft Consistency (RCON)
|
|
||||||
if image == 'minecraft':
|
|
||||||
await execute_minecraft_save_all(server_id)
|
await execute_minecraft_save_all(server_id)
|
||||||
|
|
||||||
# 2. Identify the PVC and Volume
|
|
||||||
# PVC is {server_id}-data for app/game servers, {server_id}-rootdisk for VPS
|
|
||||||
pvc_name = f"{server_id}-data"
|
|
||||||
if server_type == 'vps':
|
|
||||||
pvc_name = f"{server_id}-rootdisk"
|
|
||||||
|
|
||||||
# Get PVC to find volumeName
|
|
||||||
pvc = v1.read_namespaced_persistent_volume_claim(pvc_name, namespace)
|
|
||||||
volume_name = pvc.spec.volume_name
|
|
||||||
|
|
||||||
if not volume_name:
|
|
||||||
raise Exception(f"Could not find volume for PVC {pvc_name}")
|
|
||||||
|
|
||||||
# 3. Create Longhorn Snapshot
|
|
||||||
snapshot_obj = {
|
snapshot_obj = {
|
||||||
"apiVersion": "longhorn.io/v1beta2",
|
'apiVersion': 'snapshot.storage.k8s.io/v1',
|
||||||
"kind": "Snapshot",
|
'kind': 'VolumeSnapshot',
|
||||||
"metadata": {
|
'metadata': {
|
||||||
"name": backup_id,
|
'name': backup_id,
|
||||||
"namespace": "longhorn-system",
|
'namespace': namespace,
|
||||||
"labels": {
|
'labels': {'app': server_id, 'backup-id': backup_id},
|
||||||
"app": server_id,
|
},
|
||||||
"backup-id": backup_id
|
'spec': {
|
||||||
}
|
'volumeSnapshotClassName': BACKUP_SNAPSHOT_CLASS,
|
||||||
|
'source': {'persistentVolumeClaimName': pvc_name},
|
||||||
},
|
},
|
||||||
"spec": {
|
|
||||||
"volume": volume_name,
|
|
||||||
"createSnapshot": True
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
custom_objects_api.create_namespaced_custom_object(
|
custom_objects_api.create_namespaced_custom_object(
|
||||||
group="longhorn.io",
|
group='snapshot.storage.k8s.io', version='v1', namespace=namespace,
|
||||||
version="v1beta2",
|
plural='volumesnapshots', body=snapshot_obj,
|
||||||
namespace="longhorn-system",
|
|
||||||
plural="snapshots",
|
|
||||||
body=snapshot_obj
|
|
||||||
)
|
)
|
||||||
|
snapshot = await _wait_for_volume_snapshot(namespace, backup_id)
|
||||||
# Wait for snapshot to be ready
|
size = snapshot.get('status', {}).get('restoreSize', 'Unknown')
|
||||||
logger.info(f"Waiting for Longhorn snapshot {backup_id} to be ready...")
|
|
||||||
snapshot_ready = False
|
|
||||||
size = "Unknown"
|
|
||||||
for _ in range(30): # 60 seconds max
|
|
||||||
await asyncio.sleep(2)
|
|
||||||
snap = custom_objects_api.get_namespaced_custom_object(
|
|
||||||
group="longhorn.io",
|
|
||||||
version="v1beta2",
|
|
||||||
namespace="longhorn-system",
|
|
||||||
plural="snapshots",
|
|
||||||
name=backup_id
|
|
||||||
)
|
|
||||||
status = snap.get('status', {})
|
|
||||||
if status and status.get('readyToUse'):
|
|
||||||
snapshot_ready = True
|
|
||||||
# Use restoreSize (full volume size) instead of incremental size
|
|
||||||
size = status.get('restoreSize', 'Unknown')
|
|
||||||
logger.info(f"Longhorn snapshot {backup_id} is ready. Restore Size: {size}")
|
|
||||||
break
|
|
||||||
|
|
||||||
if not snapshot_ready:
|
|
||||||
raise Exception(f"Longhorn snapshot {backup_id} did not become ready in time")
|
|
||||||
|
|
||||||
# 4. Update DB
|
|
||||||
with database_connection() as conn:
|
with database_connection() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute('''
|
cursor.execute('UPDATE backups SET status = ?, completed_at = ?, size = ? WHERE id = ?',
|
||||||
UPDATE backups SET status = ?, completed_at = ?, size = ?
|
('Completed', datetime.now(), str(size), backup_id))
|
||||||
WHERE id = ?
|
|
||||||
''', ('Completed', datetime.now(), size, backup_id))
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
await send_message(client_id, {
|
await send_message(client_id, {
|
||||||
'type': 'backup_status_updated',
|
'type': 'backup_status_updated', 'serverId': server_id,
|
||||||
'serverId': server_id,
|
'backup': {'id': backup_id, 'status': 'Completed', 'size': str(size)},
|
||||||
'backup': {
|
|
||||||
'id': backup_id,
|
|
||||||
'status': 'Completed',
|
|
||||||
'size': size
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as error:
|
||||||
logger.error(f"Backup failed for {server_id}: {e}")
|
logger.exception("Backup failed for server %s", server_id)
|
||||||
with database_connection() as conn:
|
with database_connection() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute('UPDATE backups SET status = ? WHERE id = ?', ('Failed', backup_id))
|
cursor.execute('UPDATE backups SET status = ? WHERE id = ?', ('Failed', backup_id))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
await send_message(client_id, {
|
await send_message(client_id, {
|
||||||
'type': 'error',
|
'type': 'backup_status_updated', 'serverId': server_id,
|
||||||
'error': f"Backup failed: {str(e)}"
|
'backup': {'id': backup_id, 'status': 'Failed'},
|
||||||
|
})
|
||||||
|
await send_message(client_id, {
|
||||||
|
'type': 'error', 'serverId': server_id, 'backupId': backup_id,
|
||||||
|
'error': f"Backup failed: {error}",
|
||||||
})
|
})
|
||||||
|
|
||||||
asyncio.create_task(run_backup())
|
asyncio.create_task(run_backup())
|
||||||
|
except Exception as error:
|
||||||
except Exception as e:
|
logger.exception("Error triggering backup for server %s", server_id)
|
||||||
logger.error(f"Error triggering backup: {e}")
|
await send_message(client_id, {'type': 'error', 'serverId': server_id, 'error': str(error)})
|
||||||
await send_message(client_id, {'type': 'error', 'error': str(e)})
|
|
||||||
|
|
||||||
async def execute_minecraft_save_all(server_id):
|
async def execute_minecraft_save_all(server_id):
|
||||||
"""Send save-all command via RCON if server is running"""
|
"""Send save-all command via RCON if server is running"""
|
||||||
@@ -2912,35 +2994,35 @@ async def handle_delete_backup(client_id, data):
|
|||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Get namespace
|
|
||||||
namespace, _ = get_server_access_and_namespace(server_id, user_id)
|
namespace, _ = get_server_access_and_namespace(server_id, user_id)
|
||||||
|
backup = _get_backup_record(server_id, backup_id)
|
||||||
# Delete from Kubernetes (Longhorn Snapshot)
|
if not backup:
|
||||||
|
raise Exception("Backup not found for this server")
|
||||||
try:
|
try:
|
||||||
custom_objects_api.delete_namespaced_custom_object(
|
custom_objects_api.delete_namespaced_custom_object(
|
||||||
group="longhorn.io",
|
group='snapshot.storage.k8s.io', version='v1', namespace=namespace,
|
||||||
version="v1beta2",
|
plural='volumesnapshots', name=backup_id,
|
||||||
namespace="longhorn-system",
|
|
||||||
plural="snapshots",
|
|
||||||
name=backup_id
|
|
||||||
)
|
)
|
||||||
logger.info(f"✓ Deleted Longhorn Snapshot {backup_id}")
|
except ApiException as error:
|
||||||
except Exception as e:
|
if error.status != 404:
|
||||||
logger.warning(f"Could not delete Longhorn Snapshot {backup_id}: {e}")
|
raise
|
||||||
|
# Remove legacy Longhorn snapshots created before CSI snapshots were enabled.
|
||||||
|
try:
|
||||||
|
custom_objects_api.delete_namespaced_custom_object(
|
||||||
|
group='longhorn.io', version='v1beta2', namespace='longhorn-system',
|
||||||
|
plural='snapshots', name=backup_id,
|
||||||
|
)
|
||||||
|
except ApiException as legacy_error:
|
||||||
|
if legacy_error.status != 404:
|
||||||
|
raise
|
||||||
with database_connection() as conn:
|
with database_connection() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute('DELETE FROM backups WHERE id = ?', (backup_id,))
|
cursor.execute('DELETE FROM backups WHERE id = ? AND server_id = ?', (backup_id, server_id))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
await send_message(client_id, {'type': 'backup_deleted', 'serverId': server_id, 'backupId': backup_id})
|
||||||
await send_message(client_id, {
|
except Exception as error:
|
||||||
'type': 'backup_deleted',
|
logger.exception("Error deleting backup %s for server %s", backup_id, server_id)
|
||||||
'serverId': server_id,
|
await send_message(client_id, {'type': 'error', 'serverId': server_id, 'backupId': backup_id, 'error': str(error)})
|
||||||
'backupId': backup_id
|
|
||||||
})
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error deleting backup: {e}")
|
|
||||||
await send_message(client_id, {'type': 'error', 'error': str(e)})
|
|
||||||
|
|
||||||
async def handle_restore_backup(client_id, data):
|
async def handle_restore_backup(client_id, data):
|
||||||
"""Restore a backup to a server"""
|
"""Restore a backup to a server"""
|
||||||
@@ -2959,90 +3041,106 @@ async def handle_restore_backup(client_id, data):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
namespace, server = 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)
|
||||||
await send_message(client_id, {
|
if not backup or backup.get('status') != 'Completed':
|
||||||
'type': 'info',
|
raise Exception("This completed backup could not be found for this server")
|
||||||
'message': 'Restoration process started. Stopping server...'
|
if not k8s_manager.connected:
|
||||||
})
|
raise Exception("Storage service is unavailable; the server was not changed")
|
||||||
|
|
||||||
# 1. Stop server
|
|
||||||
stop_server(server_id, user_id)
|
|
||||||
|
|
||||||
if k8s_manager.connected:
|
|
||||||
# Wait for pods to be gone (Wait up to 60s)
|
|
||||||
logger.info(f"Waiting for pods of {server_id} to stop...")
|
|
||||||
for i in range(12):
|
|
||||||
pods = v1.list_namespaced_pod(namespace, label_selector=f"app={server_id}")
|
|
||||||
if not pods.items:
|
|
||||||
break
|
|
||||||
logger.info(f" ... {len(pods.items)} pods still running")
|
|
||||||
await asyncio.sleep(5)
|
|
||||||
|
|
||||||
# 2. Handle PVC restoration
|
|
||||||
pvc_name = f"{server_id}-data"
|
|
||||||
if server['type'] == 'vps': pvc_name = f"{server_id}-rootdisk"
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Get old PVC spec to preserve storage size and storage class
|
snapshot = custom_objects_api.get_namespaced_custom_object(
|
||||||
|
group='snapshot.storage.k8s.io', version='v1', namespace=namespace,
|
||||||
|
plural='volumesnapshots', name=backup_id,
|
||||||
|
)
|
||||||
|
except ApiException as error:
|
||||||
|
if error.status == 404:
|
||||||
|
raise Exception("This restore point is unavailable. Create a new backup before restoring again.") from error
|
||||||
|
raise
|
||||||
|
if not snapshot.get('status', {}).get('readyToUse'):
|
||||||
|
raise Exception("This restore point is not ready to use")
|
||||||
|
|
||||||
|
pvc_name = _backup_pvc_name(server)
|
||||||
|
old_data_volume = None
|
||||||
|
if server.get('type') == 'vps':
|
||||||
|
old_data_volume = custom_objects_api.get_namespaced_custom_object(
|
||||||
|
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
|
||||||
|
plural='datavolumes', name=pvc_name,
|
||||||
|
)
|
||||||
|
data_volume_pvc_spec = old_data_volume.get('spec', {}).get('pvc')
|
||||||
|
if not data_volume_pvc_spec:
|
||||||
|
raise Exception("The VPS disk is not managed by a supported DataVolume")
|
||||||
old_pvc = v1.read_namespaced_persistent_volume_claim(pvc_name, namespace)
|
old_pvc = v1.read_namespaced_persistent_volume_claim(pvc_name, namespace)
|
||||||
storage_size = old_pvc.spec.resources.requests['storage']
|
storage_size = old_pvc.spec.resources.requests['storage']
|
||||||
storage_class = old_pvc.spec.storage_class_name
|
storage_class = old_pvc.spec.storage_class_name
|
||||||
|
access_modes = old_pvc.spec.access_modes or ['ReadWriteOnce']
|
||||||
|
|
||||||
|
async def notify_progress(message):
|
||||||
await send_message(client_id, {
|
await send_message(client_id, {
|
||||||
'type': 'info',
|
'type': 'info', 'serverId': server_id, 'backupId': backup_id, 'message': message,
|
||||||
'message': 'Recreating volume from backup...'
|
|
||||||
})
|
})
|
||||||
|
|
||||||
# Delete old PVC
|
await notify_progress('Restoration process started. Stopping server...')
|
||||||
v1.delete_namespaced_persistent_volume_claim(pvc_name, namespace)
|
if not stop_server(server_id, user_id):
|
||||||
|
raise Exception("The server could not be stopped; its storage was not changed")
|
||||||
|
|
||||||
# Wait for PVC to be gone
|
logger.info("Waiting for server %s pods to stop before restoring", server_id)
|
||||||
for _ in range(12):
|
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")
|
||||||
|
|
||||||
|
await notify_progress('Recreating volume from backup...')
|
||||||
|
if old_data_volume:
|
||||||
|
custom_objects_api.delete_namespaced_custom_object(
|
||||||
|
group='cdi.kubevirt.io', version='v1beta1', namespace=namespace,
|
||||||
|
plural='datavolumes', name=pvc_name,
|
||||||
|
)
|
||||||
|
await _wait_for_data_volume_absent(pvc_name, namespace)
|
||||||
try:
|
try:
|
||||||
v1.read_namespaced_persistent_volume_claim(pvc_name, namespace)
|
v1.read_namespaced_persistent_volume_claim(pvc_name, namespace)
|
||||||
await asyncio.sleep(5)
|
v1.delete_namespaced_persistent_volume_claim(pvc_name, namespace)
|
||||||
except ApiException as e:
|
except ApiException as error:
|
||||||
if e.status == 404:
|
if error.status != 404:
|
||||||
break
|
raise
|
||||||
|
await _wait_for_pvc_absent(pvc_name, namespace)
|
||||||
# 3. Create new PVC from backup
|
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, data_volume_pvc_spec),
|
||||||
|
)
|
||||||
|
await _wait_for_data_volume_ready(pvc_name, namespace)
|
||||||
|
else:
|
||||||
|
v1.delete_namespaced_persistent_volume_claim(pvc_name, namespace)
|
||||||
|
await _wait_for_pvc_absent(pvc_name, namespace)
|
||||||
pvc_body = client.V1PersistentVolumeClaim(
|
pvc_body = client.V1PersistentVolumeClaim(
|
||||||
metadata=client.V1ObjectMeta(name=pvc_name),
|
metadata=client.V1ObjectMeta(name=pvc_name),
|
||||||
spec=client.V1PersistentVolumeClaimSpec(
|
spec=client.V1PersistentVolumeClaimSpec(
|
||||||
access_modes=["ReadWriteOnce"],
|
access_modes=access_modes,
|
||||||
resources=client.V1VolumeResourceRequirements(
|
resources=client.V1VolumeResourceRequirements(requests={'storage': storage_size}),
|
||||||
requests={"storage": storage_size}
|
|
||||||
),
|
|
||||||
storage_class_name=storage_class,
|
storage_class_name=storage_class,
|
||||||
data_source=client.V1TypedLocalObjectReference(
|
data_source=client.V1TypedLocalObjectReference(
|
||||||
api_group="longhorn.io",
|
api_group='snapshot.storage.k8s.io', kind='VolumeSnapshot', name=backup_id,
|
||||||
kind="Snapshot",
|
),
|
||||||
name=backup_id
|
),
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
v1.create_namespaced_persistent_volume_claim(namespace=namespace, body=pvc_body)
|
v1.create_namespaced_persistent_volume_claim(namespace=namespace, body=pvc_body)
|
||||||
logger.info(f"✓ Created new PVC {pvc_name} from backup {backup_id}")
|
restored_pvc = await _wait_for_pvc_bound(pvc_name, namespace)
|
||||||
|
if not restored_pvc.spec.volume_name:
|
||||||
except ApiException as e:
|
raise Exception("Restored claim is bound without a Longhorn volume")
|
||||||
if e.status == 404:
|
await _wait_for_longhorn_restore(restored_pvc.spec.volume_name)
|
||||||
raise Exception(f"PVC {pvc_name} not found")
|
|
||||||
raise e
|
|
||||||
else:
|
|
||||||
await asyncio.sleep(2) # Mock delay
|
|
||||||
|
|
||||||
# 4. Start server
|
|
||||||
start_server(server_id, user_id)
|
|
||||||
|
|
||||||
|
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.")
|
||||||
|
await notify_progress('Restoration completed successfully. Server is starting.')
|
||||||
|
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)
|
||||||
await send_message(client_id, {
|
await send_message(client_id, {
|
||||||
'type': 'info',
|
'type': 'error', 'serverId': server_id, 'backupId': backup_id, 'error': str(error),
|
||||||
'message': 'Restoration completed successfully. Server is starting.'
|
|
||||||
})
|
})
|
||||||
logger.info(f"✓ Successfully restored backup {backup_id} for server {server_id}")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error restoring backup: {e}")
|
|
||||||
await send_message(client_id, {'type': 'error', 'error': str(e)})
|
|
||||||
|
|
||||||
async def handle_change_server_version(client_id, data):
|
async def handle_change_server_version(client_id, data):
|
||||||
"""Handle change server version request - free of charge, billing date unchanged"""
|
"""Handle change server version request - free of charge, billing date unchanged"""
|
||||||
|
|||||||
Reference in new issue
Block a user