mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 01:16:10 +00:00
feat(vmbackups): restore, delete, retention, check and import know chains
An incremental backup is restored by copying its chain flat: every base's disk file is checked first, as the backup's own, and a chain whose base's row is gone is refused. A backup that a living backup builds on is not deleted, by hand or by retention: retention deletes a chain only once all of it is beyond keep, newest first; a failed backup holds no base. The target check marks a backup missing when a base's file is gone. Reading a target links each incremental backup to its base, read first, and leaves one without its base unread. Restoring over the VM forgets its checkpoints: its disks are replaced, and the next backup is full.
This commit is contained in:
parent
72e270a87e
commit
d856ccca68
12 changed files with 555 additions and 391 deletions
|
|
@ -525,7 +525,7 @@ def _beyond_keep(backup, policy_id):
|
|||
VM's ready backups beyond what it keeps (keep raised, or a newer one gone,
|
||||
since the deletion was queued)."""
|
||||
policy = BackupPolicy.objects.filter(pk=policy_id).first()
|
||||
if policy is None or backup.policy_id != policy.pk or backup.instance_id is None:
|
||||
if policy is None or backup.policy_id != policy.pk or backup.instance_id is None or backup.depended_on():
|
||||
return False
|
||||
ready = list(Backup.objects.filter(policy=policy, instance_id=backup.instance_id, state=Backup.READY)
|
||||
.order_by("-created_at").values_list("pk", flat=True))
|
||||
|
|
@ -550,6 +550,8 @@ class DeleteBackup(Kind):
|
|||
backup = _backup(params)
|
||||
if backup.state == Backup.CREATING:
|
||||
raise util.OperationError(_("This backup is being made; cancel its job to stop it"))
|
||||
if backup.depended_on():
|
||||
raise util.OperationError(_("Later backups depend on this one; delete them first"))
|
||||
return Plan(
|
||||
claims={claims.backup_key(backup.uuid): Claim.EXCLUSIVE, **_target_claims(backup.target)},
|
||||
resource=claims.backup_key(backup.uuid),
|
||||
|
|
@ -563,6 +565,8 @@ class DeleteBackup(Kind):
|
|||
backup = _backup(op.params)
|
||||
if op.params.get("retention") and not _beyond_keep(backup, op.params["retention"]):
|
||||
raise util.OperationError(_("The backup is no longer beyond what its schedule keeps; it is kept"))
|
||||
if backup.depended_on(): # made since the deletion was queued: the target claim now holds it off
|
||||
raise util.OperationError(_("Later backups depend on this one; delete them first"))
|
||||
_conn, pool = _target_pool(backup.target)
|
||||
ctx.record_intent(deleting=True)
|
||||
return self._delete(backup, pool)
|
||||
|
|
@ -622,6 +626,22 @@ def _check_files(conn, pool, files):
|
|||
raise util.OperationError(_("The backup's file %(name)s differs from the one written"), name=f["volume"])
|
||||
|
||||
|
||||
def _base_files(backup, dev=None):
|
||||
"""The disk files of the backups an incremental backup builds on (of
|
||||
the disk dev only, when given), checked as its own before a restore
|
||||
copies the chain flat. Refuses a chain whose base's row is gone."""
|
||||
files = []
|
||||
while True:
|
||||
if backup.parent_id is None:
|
||||
if backup.manifest.get("parent"):
|
||||
raise util.OperationError(_("The backup taken %(time)s builds on a backup that is gone"),
|
||||
time=timezone.localtime(backup.created_at).strftime("%Y-%m-%d %H:%M"))
|
||||
return files
|
||||
backup = backup.parent
|
||||
disks = backup.files.filter(role=BackupFile.DISK, **({"dev": dev} if dev else {}))
|
||||
files += disks.values("role", "volume", "capacity", "sha256")
|
||||
|
||||
|
||||
def _tpm_files(backup):
|
||||
"""The backup's TPM state files; a manifest read from a target names
|
||||
them: each is a file of the VM's state directory only."""
|
||||
|
|
@ -686,7 +706,7 @@ class RestoreBackup(Kind):
|
|||
raise util.OperationError(_("A VM named %(name)s exists on %(compute)s"), name=p["name"], compute=compute.name)
|
||||
row = _target_row(backup.target, compute)
|
||||
tpool = target_pool(conn, row.pool, row.pool_uuid)
|
||||
_check_files(conn, tpool, backup.files.values("role", "volume", "capacity", "sha256"))
|
||||
_check_files(conn, tpool, [*backup.files.values("role", "volume", "capacity", "sha256"), *_base_files(backup)])
|
||||
definition = get_file(conn, tpool, backup.files.get(role=BackupFile.DOMAIN).volume).decode()
|
||||
check_restore_host(conn, definition)
|
||||
pools = conn.file_pools()
|
||||
|
|
@ -866,7 +886,7 @@ class RestoreOver(Kind):
|
|||
raise util.OperationError(_("The VM's disks changed after the job was queued"))
|
||||
row = _target_row(backup.target, instance.compute)
|
||||
tpool = target_pool(proxy, row.pool, row.pool_uuid)
|
||||
_check_files(proxy, tpool, backup.files.values("role", "volume", "capacity", "sha256"))
|
||||
_check_files(proxy, tpool, [*backup.files.values("role", "volume", "capacity", "sha256"), *_base_files(backup)])
|
||||
_tpm_files(backup)
|
||||
disks = {f.dev: f for f in backup.files.filter(role=BackupFile.DISK)}
|
||||
pools = proxy.file_pools()
|
||||
|
|
@ -907,6 +927,8 @@ class RestoreOver(Kind):
|
|||
over = op.intent["over"]
|
||||
# a host booting mid-switch starts nothing: the old disks with the backup's NVRAM and TPM would not match
|
||||
proxy.instance.setAutostart(0)
|
||||
# the disks are replaced: their bitmaps are not the VM's any more, the next scheduled backup is full
|
||||
proxy.drop_checkpoint_metadata()
|
||||
if over["nvram"]:
|
||||
nvram = backup.files.filter(role=BackupFile.NVRAM).first()
|
||||
with proxy._nvram_pool() as nvram_pool:
|
||||
|
|
@ -1024,7 +1046,8 @@ class RestoreDisk(Kind):
|
|||
conn = _connect(compute)
|
||||
row = _target_row(backup.target, compute)
|
||||
tpool = target_pool(conn, row.pool, row.pool_uuid)
|
||||
_check_files(conn, tpool, [{"role": disk.role, "volume": disk.volume, "capacity": disk.capacity, "sha256": ""}])
|
||||
_check_files(conn, tpool, [{"role": disk.role, "volume": disk.volume, "capacity": disk.capacity, "sha256": ""},
|
||||
*_base_files(backup, disk.dev)])
|
||||
pools = conn.file_pools()
|
||||
if p["pool"] not in pools:
|
||||
raise util.OperationError(_("This host has no active directory storage pool %(pool)s"), pool=p["pool"])
|
||||
|
|
@ -1098,15 +1121,27 @@ class ImportBackups(Kind):
|
|||
_superuser(op.user)
|
||||
target = BackupTarget.objects.get(pk=op.params["target"])
|
||||
conn, pool = _target_pool(target)
|
||||
added, incomplete = 0, []
|
||||
added, incomplete, manifests = 0, [], []
|
||||
for name in manifest_names(pool):
|
||||
data = get_file(conn, pool, name)
|
||||
try:
|
||||
manifests.append((parse_datetime(json.loads(data)["created_at"]), name, data))
|
||||
except (ValueError, KeyError, TypeError):
|
||||
manifests.append((None, name, data)) # passed over below
|
||||
# oldest first: an incremental backup's base is read before it
|
||||
manifests.sort(key=lambda m: m[0].timestamp() if m[0] else 0)
|
||||
for _created_at, name, data in manifests:
|
||||
try:
|
||||
manifest = json.loads(data)
|
||||
if manifest["format"] != MANIFEST_FORMAT:
|
||||
raise ValueError(manifest["format"])
|
||||
if Backup.objects.filter(uuid=manifest["backup"]).exists():
|
||||
continue
|
||||
parent = None
|
||||
if manifest.get("parent"):
|
||||
parent = Backup.objects.filter(uuid=manifest["parent"]).first()
|
||||
if parent is None: # its base was not read: it cannot be restored
|
||||
raise ValueError(manifest["parent"])
|
||||
_check_files(conn, pool, manifest["files"])
|
||||
files = [{k: f[k] for k in ("role", "dev", "volume", "format", "capacity", "size", "sha256")}
|
||||
for f in manifest["files"]]
|
||||
|
|
@ -1114,7 +1149,8 @@ class ImportBackups(Kind):
|
|||
if created_at is None:
|
||||
raise ValueError(manifest["created_at"])
|
||||
fields = {"vm_uuid": vm["uuid"], "vm_name": vm["name"], "compute_name": manifest["compute"],
|
||||
"consistency": manifest["consistency"]}
|
||||
"consistency": manifest["consistency"], "parent": parent,
|
||||
"checkpoint": manifest.get("checkpoint") or ""}
|
||||
except (ValueError, KeyError, TypeError, util.OperationError):
|
||||
# cut short, not a manifest of the panel, or a file missing or changed: the others are still read
|
||||
incomplete.append(name)
|
||||
|
|
@ -1167,7 +1203,11 @@ class CheckTarget(Kind):
|
|||
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"}
|
||||
state = Backup.READY if needed <= present else Backup.MISSING
|
||||
try:
|
||||
needed |= {f["volume"] for f in _base_files(backup)} # a restore copies the chain flat
|
||||
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:
|
||||
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
|
||||
|
|
|
|||
|
|
@ -112,6 +112,10 @@ class Backup(models.Model):
|
|||
class Meta:
|
||||
ordering = ["-created_at"]
|
||||
|
||||
def depended_on(self):
|
||||
"""Whether a backup builds on this one: a failed one holds nothing."""
|
||||
return self.children.filter(state__in=(self.CREATING, self.READY, self.MISSING, self.DELETING)).exists()
|
||||
|
||||
@property
|
||||
def prefix(self):
|
||||
"""Every file of the backup in the target is named from its UUID only."""
|
||||
|
|
|
|||
|
|
@ -140,7 +140,8 @@ def _attempt_key(base):
|
|||
|
||||
|
||||
def retain():
|
||||
"""Each schedule's ready backups of a VM beyond keep, oldest first: one
|
||||
"""Each schedule's ready backups of a VM beyond keep that no backup
|
||||
builds on, oldest first: one
|
||||
deletion a target at a time (its claim admits one), the rest at the next
|
||||
passes. Backups by hand and those of removed VMs are left alone."""
|
||||
tried = set()
|
||||
|
|
@ -153,12 +154,14 @@ def retain():
|
|||
for backup in ready:
|
||||
groups.setdefault(backup.instance_id, []).append(backup)
|
||||
for rows in groups.values():
|
||||
if len(rows) > policy.keep:
|
||||
# a chain goes when all of it is beyond keep, newest first: only a backup nothing builds on is deleted
|
||||
beyond = [b for b in rows[policy.keep:] if not b.depended_on()]
|
||||
if beyond:
|
||||
tried.add(policy.target_id)
|
||||
if (key := _attempt_key(f"rt-{rows[-1].uuid.hex}")) is None:
|
||||
if (key := _attempt_key(f"rt-{beyond[-1].uuid.hex}")) is None:
|
||||
break
|
||||
try:
|
||||
jobs.submit("backup.delete", policy.owner, {"backup": str(rows[-1].uuid), "retention": policy.pk},
|
||||
jobs.submit("backup.delete", policy.owner, {"backup": str(beyond[-1].uuid), "retention": policy.pk},
|
||||
key)
|
||||
except Exception as err: # busy, or refused: the next pass looks again
|
||||
logger.info("schedule %s: retention waits: %s", policy.name, safe_text(err))
|
||||
|
|
|
|||
|
|
@ -85,6 +85,23 @@ class DeleteBackupTests(TransactionTestCase):
|
|||
with self.assertRaisesMessage(OperationError, "being made"):
|
||||
self.submit()
|
||||
|
||||
def test_a_backup_others_build_on_is_refused_until_they_go(self):
|
||||
child = Backup.objects.create(target=self.target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
|
||||
compute_name="h1", state=Backup.READY, parent=self.backup)
|
||||
with self.assertRaisesMessage(OperationError, "depend on this one"):
|
||||
self.submit()
|
||||
Backup.objects.filter(pk=child.pk).update(state=Backup.FAILED) # a failed one holds nothing
|
||||
self.run_job(self.submit())
|
||||
self.assertFalse(Backup.objects.filter(pk=self.backup.pk).exists())
|
||||
|
||||
def test_a_base_made_after_the_deletion_was_queued_is_kept(self):
|
||||
op = self.submit()
|
||||
Backup.objects.create(target=self.target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
|
||||
compute_name="h1", state=Backup.READY, parent=self.backup)
|
||||
with self.assertRaisesMessage(OperationError, "depend on this one"):
|
||||
self.run_job(op)
|
||||
self.assertEqual(self.removed, [])
|
||||
|
||||
def test_a_target_no_compute_reaches_is_refused(self):
|
||||
op = self.submit()
|
||||
with patch("vmbackups.jobs.target_pool", side_effect=OperationError("Storage pool %(pool)s is gone", pool="b1")):
|
||||
|
|
|
|||
|
|
@ -100,6 +100,34 @@ class ImportTests(TransactionTestCase):
|
|||
self.assertEqual(self.read(), {"added": 0})
|
||||
self.assertEqual(Backup.objects.count(), 2)
|
||||
|
||||
def test_a_chain_is_read_base_first_and_linked(self):
|
||||
base, top = sorted((self.a, self.b), reverse=True) # the base's manifest is listed last
|
||||
older = manifest(base)
|
||||
older["created_at"] = "2026-10-31T10:00:00+00:00"
|
||||
older["checkpoint"] = f"wvc-{base}"
|
||||
newer = manifest(top)
|
||||
newer["parent"] = base
|
||||
self.files[f"wvc-{base}-manifest.json"] = json.dumps(older).encode()
|
||||
self.files[f"wvc-{top}-manifest.json"] = json.dumps(newer).encode()
|
||||
self.assertEqual(self.read(), {"added": 2})
|
||||
self.assertEqual(Backup.objects.get(uuid=top).parent, Backup.objects.get(uuid=base))
|
||||
self.assertEqual(Backup.objects.get(uuid=base).checkpoint, f"wvc-{base}")
|
||||
|
||||
def test_a_time_without_a_zone_does_not_stop_the_others(self):
|
||||
odd = manifest(self.a)
|
||||
odd["created_at"] = "2026-11-01T10:00:00"
|
||||
self.files[f"wvc-{self.a}-manifest.json"] = json.dumps(odd).encode()
|
||||
self.assertGreaterEqual(self.read()["added"], 1)
|
||||
self.assertTrue(Backup.objects.filter(uuid=self.b).exists())
|
||||
|
||||
def test_an_incremental_backup_without_its_base_is_incomplete(self):
|
||||
lonely = manifest(self.a)
|
||||
lonely["parent"] = str(uuid4())
|
||||
self.files[f"wvc-{self.a}-manifest.json"] = json.dumps(lonely).encode()
|
||||
result = self.read()
|
||||
self.assertEqual(result["added"], 1)
|
||||
self.assertIn(f"wvc-{self.a}-manifest.json", result["warning"][0]["values"]["names"])
|
||||
|
||||
def test_a_manifest_with_a_missing_file_is_incomplete(self):
|
||||
del self.files[f"wvc-{self.b}-vda.qcow2"]
|
||||
self.files[f"wvc-{self.a}-domain.xml"] = b"<domain/>" # changed since it was written
|
||||
|
|
|
|||
|
|
@ -264,6 +264,25 @@ class RestoreTests(TransactionTestCase):
|
|||
op.refresh_from_db()
|
||||
self.assertEqual(RestoreBackup().reconcile(op).state, Operation.FAILED)
|
||||
|
||||
def test_an_incremental_backup_needs_its_whole_chain(self):
|
||||
base = Backup.objects.create(target=self.target, vm_uuid=self.backup.vm_uuid, vm_name="vm1", compute_name="h1",
|
||||
state=Backup.READY)
|
||||
BackupFile.objects.create(backup=base, role=BackupFile.DISK, dev="vda", volume=f"{base.prefix}-vda.qcow2",
|
||||
format="qcow2", capacity=GIB)
|
||||
Backup.objects.filter(pk=self.backup.pk).update(parent=base)
|
||||
seen = []
|
||||
self.tpool.storageVolLookupByName.side_effect = lambda name: (
|
||||
seen.append(name), (_ for _ in ()).throw(error(libvirt.VIR_ERR_NO_STORAGE_VOL))
|
||||
if name == f"{base.prefix}-vda.qcow2" else MagicMock(info=MagicMock(return_value=[0, GIB, GIB])))[1]
|
||||
with self.assertRaisesMessage(OperationError, f"{base.prefix}-vda.qcow2"):
|
||||
self.run_job(self.submit())
|
||||
self.storage.clone_volume.assert_not_called()
|
||||
|
||||
def test_a_chain_whose_base_is_gone_is_refused(self):
|
||||
Backup.objects.filter(pk=self.backup.pk).update(manifest={"parent": str(uuid4())})
|
||||
with self.assertRaisesMessage(OperationError, "builds on a backup that is gone"):
|
||||
self.run_job(self.submit())
|
||||
|
||||
def test_the_nvram_file_is_qemus(self):
|
||||
self.run_job(self.submit())
|
||||
self.assertEqual(self.conn.upload_volume.call_args.kwargs, {"owner": _owner(), "mode": "0600"})
|
||||
|
|
|
|||
|
|
@ -165,6 +165,11 @@ class RestoreOverTests(TransactionTestCase):
|
|||
self.assertTrue(op.intent["switching"])
|
||||
self.assertNotIn("/pool/vm1.qcow2", self.removed) # the old volume stays
|
||||
|
||||
def test_the_chain_ends(self):
|
||||
self.run_job(self.submit())
|
||||
# its disks are replaced: their bitmaps are not the VM's any more
|
||||
self.proxy.drop_checkpoint_metadata.assert_called_once_with()
|
||||
|
||||
def test_the_tpm_state_is_replaced(self):
|
||||
self.with_tpm()
|
||||
self.run_job(self.submit())
|
||||
|
|
|
|||
|
|
@ -363,6 +363,28 @@ class ScheduleTests(TransactionTestCase):
|
|||
schedule.retain()
|
||||
self.assertEqual(self.deletes()[-1].params["backup"], str(older.uuid))
|
||||
|
||||
def chained(self, *backups):
|
||||
for parent, child in zip(backups, backups[1:]):
|
||||
Backup.objects.filter(pk=child.pk).update(parent=parent)
|
||||
|
||||
def test_retention_deletes_a_chain_only_when_all_of_it_is_beyond_keep(self):
|
||||
# keep 2: a full, two incrementals on it, then a new full
|
||||
full, inc1, inc2, _new = self.backups(*[Backup.READY] * 4)
|
||||
self.chained(full, inc1, inc2)
|
||||
schedule.retain() # inc2 is kept, and inc1 and full are its base
|
||||
self.assertEqual(self.deletes(), [])
|
||||
(newest,) = self.backups(Backup.READY) # one more: inc2 is beyond keep too, and a leaf
|
||||
Backup.objects.filter(pk=newest.pk).update(created_at=at(2026, 11, 20))
|
||||
schedule.retain()
|
||||
self.assertEqual(self.deletes()[-1].params["backup"], str(inc2.uuid)) # newest first: each one a leaf
|
||||
|
||||
def test_a_failed_incremental_does_not_pin_its_base(self):
|
||||
oldest, _a, _b = self.backups(*[Backup.READY] * 3)
|
||||
(failed,) = self.backups(Backup.FAILED)
|
||||
Backup.objects.filter(pk=failed.pk).update(parent=oldest)
|
||||
schedule.retain()
|
||||
self.assertEqual(self.deletes()[-1].params["backup"], str(oldest.uuid))
|
||||
|
||||
def test_a_failed_deletion_is_tried_again_an_hour_later(self):
|
||||
oldest, *_rest = self.backups(*[Backup.READY] * 3)
|
||||
schedule.retain()
|
||||
|
|
@ -451,6 +473,14 @@ 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_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)
|
||||
for b in (base, top):
|
||||
BackupFile.objects.create(backup=b, role=BackupFile.DISK, dev="vda", volume=f"{b.prefix}-vda.qcow2")
|
||||
self.run_check([f"{base.prefix}-manifest.json", f"{top.prefix}-vda.qcow2", f"{top.prefix}-manifest.json"])
|
||||
self.assertEqual(Backup.objects.get(pk=top.pk).state, Backup.MISSING)
|
||||
|
||||
def test_a_check_that_reaches_no_pool_marks_nothing(self):
|
||||
(backup,) = self.backups(Backup.READY)
|
||||
op = jobs.submit("backup.check", self.admin, {"target": self.target.pk}, "key-check-0002")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue