1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 17:36:05 +00:00

fix(vmbackups): fifth audit: offline copies, domain file mode, target check

- An offline backup is not published when the VM was started while its
  disks were copied (its NVRAM and TPM state would be newer than the
  disks); recovery does not publish it either.
- A cancel asked during the last disk of an offline copy is honoured:
  the copies are removed instead of the backup being published.
- The backup's domain definition is written 0600, as the TPM state is:
  it holds the graphics passwords.
- The daily target check does not mark missing a backup finished in the
  last 10 minutes: written through another compute, its files may not
  be listed yet by this one's NFS client.
This commit is contained in:
catborise 2026-11-18 12:19:13 +03:00
parent 57d4b61c6e
commit 132676a772
7 changed files with 366 additions and 310 deletions

View file

@ -1,5 +1,6 @@
"""Jobs of the vmbackups app (operations framework)."""
import datetime
import hashlib
import json
import os
@ -42,6 +43,7 @@ from .models import Backup, BackupFile, BackupPolicy, BackupTarget
MANIFEST_FORMAT = 1
NVRAM_READS = 3 # a running VM's NVRAM read after its backup, until it is the one read before
NVRAM_WAIT = 5 # seconds between those reads
CHECK_SETTLE = datetime.timedelta(minutes=10) # an NFS client lists another's new files within minutes
PROGRESS_EVERY = 2 # seconds between reads of a push backup's progress
@ -228,6 +230,9 @@ def _publish(op, proxy, pool):
manifest written and read back, then the row ready with its files.
Runs again in recovery: each upload replaces its volume."""
plan, names = op.intent["plan"], op.intent["names"]
if not op.intent["live"] and proxy.get_status() != VIR_DOMAIN_SHUTOFF:
# its NVRAM and TPM state would be newer than the disks copied
raise util.OperationError(_("The VM started while its disks were copied; back it up again"))
backup = Backup.objects.get(uuid=op.intent["backup"])
pool.refresh(0)
files = []
@ -247,7 +252,8 @@ def _publish(op, proxy, pool):
"sha256": put_file(proxy, pool, names["tpm"] + name, data, _owner(), mode="0600")})
definition = plan["definition"].encode()
files.append({"role": BackupFile.DOMAIN, "dev": "", "volume": names["domain"], "format": "", "capacity": len(definition),
"size": len(definition), "sha256": put_file(proxy, pool, names["domain"], definition, _owner())})
"size": len(definition), "sha256": put_file(proxy, pool, names["domain"], definition, _owner(),
mode="0600")}) # it has the graphics passwords
manifest = {
"format": MANIFEST_FORMAT,
"backup": str(backup.uuid),
@ -367,6 +373,10 @@ class CreateBackup(Kind):
except libvirtError as err: # libvirt answered: the copy failed and ended
ctx.record_intent(copy_result=[False, safe_text(err)], copying=None)
raise
op.refresh_from_db(fields=["cancel_requested"])
if op.cancel_requested: # asked during the last disk's copy
_discard(op, pool)
raise Cancelled
ctx.record_intent(copy_result=[True, ""])
ctx.set_phase(_("Writing the backup's files"))
return _publish(op, proxy, pool)
@ -1365,6 +1375,7 @@ class CheckTarget(Kind):
_conn, pool = _target_pool(target)
pool.refresh(0)
present = set(pool.listVolumes())
settled = timezone.now() - CHECK_SETTLE
missing = []
for backup in target.backups.filter(state__in=(Backup.READY, Backup.MISSING)).prefetch_related("files"):
needed = {f.volume for f in backup.files.all()} | {f"{backup.prefix}-manifest.json"}
@ -1373,6 +1384,8 @@ class CheckTarget(Kind):
state = Backup.READY if needed <= present else Backup.MISSING
except util.OperationError: # its base's row is gone
state = Backup.MISSING
if state == Backup.MISSING and backup.state == Backup.READY and (backup.finished_at or settled) > settled:
continue # just written through another compute: this one may not list its files yet (NFS)
if state == Backup.MISSING:
missing.append(f"{backup.vm_name} {timezone.localtime(backup.created_at):%Y-%m-%d %H:%M}")
# only from the state read: a deletion begun meanwhile is left alone

View file

@ -144,6 +144,7 @@ class CreateBackupTests(TransactionTestCase):
prefix = f"wvc-{op.intent['backup']}"
self.assertEqual(self.written, [f"{prefix}-tpm-tpm2-00.permall", f"{prefix}-domain.xml", f"{prefix}-manifest.json"])
self.assertEqual(self.modes[f"{prefix}-tpm-tpm2-00.permall"], "0600") # a secret
self.assertEqual(self.modes[f"{prefix}-domain.xml"], "0600") # its graphics passwords
tpm = self.backup(op).files.get(role=BackupFile.TPM)
self.assertEqual((tpm.dev, tpm.volume, tpm.size, tpm.sha256), ("tpm2-00.permall", f"{prefix}-tpm-tpm2-00.permall", 5, "sha"))
self.assertEqual(self.backup(op).manifest["tpm"], "copied")
@ -424,6 +425,27 @@ class CreateBackupTests(TransactionTestCase):
self.proxy.copy_disk_offline.assert_not_called()
self.assertEqual(self.backup(op).state, Backup.FAILED)
def test_an_offline_copy_cancelled_during_its_last_disk_is_not_kept(self):
op = self.submit()
self.proxy.copy_disk_offline.side_effect = lambda *a: Operation.objects.filter(pk=op.pk).update(cancel_requested=True)
with self.assertRaises(Cancelled):
self.run_job(op)
self.assertEqual(self.written, [])
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed)
self.assertEqual(self.backup(op).state, Backup.FAILED)
def test_a_vm_started_during_its_offline_copy_is_not_published(self):
# its NVRAM and TPM state would be newer than the disks copied
started = lambda *a: setattr(self.proxy.get_status, "return_value", libvirt.VIR_DOMAIN_RUNNING) # noqa: E731
self.proxy.copy_disk_offline.side_effect = started
op = self.interrupted(self.submit())
self.assertEqual(self.written, [])
outcome = CreateBackup().reconcile(op) # recovery does not publish it either
self.assertEqual(outcome.state, Operation.FAILED)
self.assertIn("started", str(outcome.error))
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed)
self.assertEqual(self.backup(op).state, Backup.FAILED)
def test_progress_counts_the_copied_disks(self):
op = self.submit()
self.run_job(op)

View file

@ -9,6 +9,7 @@ from unittest.mock import MagicMock, patch
import libvirt
from django.contrib.auth import get_user_model
from django.test import TransactionTestCase, override_settings
from django.utils import timezone
from appsettings.settings import get_settings
from computes.models import Compute
@ -490,6 +491,16 @@ class ScheduleTests(TransactionTestCase):
self.run_check([*present, f"{gone.prefix}-manifest.json"])
self.assertEqual(Backup.objects.get(pk=gone.pk).state, Backup.READY)
def test_a_backup_finished_minutes_ago_is_not_marked_missing(self):
# written through another compute: this one's NFS client may not list its files yet
(backup,) = self.backups(Backup.READY)
Backup.objects.filter(pk=backup.pk).update(finished_at=timezone.now() - datetime.timedelta(minutes=2))
self.run_check([])
self.assertEqual(Backup.objects.get(pk=backup.pk).state, Backup.READY)
Backup.objects.filter(pk=backup.pk).update(finished_at=timezone.now() - datetime.timedelta(minutes=20))
self.run_check([])
self.assertEqual(Backup.objects.get(pk=backup.pk).state, Backup.MISSING)
def test_an_incremental_backup_whose_base_file_is_gone_is_missing(self):
base, top = self.backups(Backup.READY, Backup.READY)
Backup.objects.filter(pk=top.pk).update(parent=base)