From 57d4b61c6e8e4e7dd5c8bc32852ba7a95a1174a7 Mon Sep 17 00:00:00 2001 From: catborise Date: Wed, 18 Nov 2026 10:06:52 +0300 Subject: [PATCH] fix(vmbackups): fourth audit: missing incrementals, VM row changes - Retention counts keep in ready backups only and also deletes the missing ones older than the oldest kept: an incremental whose files were lost no longer pins its chain on the target forever. - When another row takes a VM's place (a migration the destination's VM list recorded first, or a move found by a sync), its backups, schedule membership and today's schedule runs move with its owners: owners keep their backups, retention and restore over still see them, and the VM is not backed up twice that night. --- computes/utils.py | 10 +++++++++- vmbackups/jobs.py | 21 +++++++++++++++------ vmbackups/schedule.py | 16 +++++++--------- vmbackups/tests/test_models.py | 21 +++++++++++++++++++++ vmbackups/tests/test_schedule.py | 20 +++++++++++++++++++- 5 files changed, 71 insertions(+), 17 deletions(-) diff --git a/computes/utils.py b/computes/utils.py index 48c3a194..1520d3c4 100644 --- a/computes/utils.py +++ b/computes/utils.py @@ -12,6 +12,7 @@ from instances.models import Instance, InstanceTombstone from logs.audit import write from operations import claims from operations.models import Claim +from vmbackups.models import Backup, BackupRun logger = logging.getLogger(__name__) @@ -86,7 +87,14 @@ def _log(inst, what): def move_ownership(source, target): - """Give target the owners and template flag of source; a user's rights are merged.""" + """Give target the owners, template flag, backups and schedules of source; a user's rights are merged.""" + Backup.objects.filter(instance=source).update(instance=target) + for policy in source.backup_policies.all(): + policy.instances.add(target) + taken = set(BackupRun.objects.filter(instance=target).values_list("policy_id", "day")) + for run in BackupRun.objects.filter(instance=source): # a schedule's run of the day: not taken twice + if (run.policy_id, run.day) not in taken: + BackupRun.objects.filter(pk=run.pk).update(instance=target) for ui in UserInstance.objects.filter(instance=source): existing = UserInstance.objects.filter(instance=target, user=ui.user).first() if existing is None: diff --git a/vmbackups/jobs.py b/vmbackups/jobs.py index 92fcce9b..064d1c00 100644 --- a/vmbackups/jobs.py +++ b/vmbackups/jobs.py @@ -586,16 +586,25 @@ def _backup(params): return Backup.objects.select_related("target").get(uuid=params["backup"]) +def beyond_keep(policy, instance_id): + """A schedule's backups of a VM beyond what it keeps, newest first: the + ready ones past keep, and the missing ones older than the oldest kept + (keep counts ready ones only; a missing one would pin its chain).""" + rows = list(Backup.objects.filter(policy=policy, instance_id=instance_id, state__in=(Backup.READY, Backup.MISSING)) + .order_by("-created_at")) + ready = [b for b in rows if b.state == Backup.READY] + if len(ready) <= policy.keep: + return [] + return [b for b in rows if b.created_at < ready[policy.keep - 1].created_at] + + def _beyond_keep(backup, policy_id): - """Whether the schedule still exists and the backup is still one of its - VM's ready backups beyond what it keeps (keep raised, or a newer one gone, - since the deletion was queued).""" + """Whether the schedule still exists and the backup is still 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 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)) - return backup.pk in ready[policy.keep:] + return backup.pk in {b.pk for b in beyond_keep(policy, backup.instance_id)} @register diff --git a/vmbackups/schedule.py b/vmbackups/schedule.py index b933eadf..ce42fa5c 100644 --- a/vmbackups/schedule.py +++ b/vmbackups/schedule.py @@ -20,6 +20,7 @@ from operations.models import Operation from operations.utils import safe_text from vrtManager.util import ConnectionFailed +from .jobs import beyond_keep from .models import Backup, BackupPolicy, BackupRun, BackupTarget logger = logging.getLogger(__name__) @@ -140,22 +141,19 @@ def _attempt_key(base): def retain(): - """Each schedule's ready backups of a VM beyond keep that no backup - builds on, oldest first: one + """Each schedule's 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() for policy in BackupPolicy.objects.select_related("owner"): if policy.target_id in tried or not _active_superuser(policy.owner): continue - ready = (Backup.objects.filter(policy=policy, state=Backup.READY, instance__isnull=False) - .order_by("instance_id", "-created_at")) - groups = {} - for backup in ready: - groups.setdefault(backup.instance_id, []).append(backup) - for rows in groups.values(): + vms = (Backup.objects.filter(policy=policy, state=Backup.READY, instance__isnull=False) + .values_list("instance_id", flat=True).distinct()) + for instance_id in vms: # 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()] + beyond = [b for b in beyond_keep(policy, instance_id) if not b.depended_on()] if beyond: tried.add(policy.target_id) if (key := _attempt_key(f"rt-{beyond[-1].uuid.hex}")) is None: diff --git a/vmbackups/tests/test_models.py b/vmbackups/tests/test_models.py index 9ddabd8b..ab5ea94f 100644 --- a/vmbackups/tests/test_models.py +++ b/vmbackups/tests/test_models.py @@ -1,3 +1,4 @@ +import datetime from uuid import UUID from django.db import IntegrityError @@ -56,3 +57,23 @@ class BackupModelTests(TestCase): def test_claim_keys(self): self.assertEqual(backup_target_key(3), "backup_target:3") self.assertEqual(backup_key("00000000-0000-4000-8000-000000000001"), "backup:00000000-0000-4000-8000-000000000001") + + def test_a_vm_whose_row_changes_keeps_its_backups_and_schedules(self): + # a migration the destination's VM list recorded first: that row takes the VM's place + from computes.utils import move_ownership + from vmbackups.models import BackupPolicy, BackupRun + + uuid = "11111111-1111-1111-1111-111111111111" + old = Instance.objects.create(compute=self.compute, name="vm1", uuid=uuid) + other = Compute.objects.create(name="h2", hostname="192.0.2.11", login="u", password="p", type=1) + new = Instance.objects.create(compute=other, name="vm1", uuid=uuid) + backup = self.backup(old) + policy = BackupPolicy.objects.create(name="nightly", target=self.target, time=datetime.time(2), keep=2) + policy.instances.add(old) + BackupRun.objects.create(policy=policy, instance=old, day=datetime.date(2026, 11, 18), state=BackupRun.SUBMITTED) + move_ownership(old, new) + old.delete() + backup.refresh_from_db() + self.assertEqual(backup.instance, new) + self.assertEqual(list(policy.instances.all()), [new]) + self.assertEqual(list(policy.runs.values_list("instance", flat=True)), [new.pk]) # not backed up twice tonight diff --git a/vmbackups/tests/test_schedule.py b/vmbackups/tests/test_schedule.py index f5c0d3b5..12171a58 100644 --- a/vmbackups/tests/test_schedule.py +++ b/vmbackups/tests/test_schedule.py @@ -17,7 +17,7 @@ from operations import jobs from operations.jobs import Context from operations.models import Operation, acquire from vmbackups import schedule -from vmbackups.jobs import CheckTarget, DeleteBackup +from vmbackups.jobs import CheckTarget, DeleteBackup, _beyond_keep from vmbackups.models import Backup, BackupFile, BackupPolicy, BackupRun, BackupTarget, BackupTargetPool from vrtManager.util import OperationError @@ -397,6 +397,24 @@ class ScheduleTests(TransactionTestCase): self.assertEqual(len(self.deletes()), 2) self.assertEqual(self.deletes()[-1].params["backup"], str(oldest.uuid)) + def test_a_missing_incremental_goes_with_its_chain(self): + # keep 2: a full and an incremental on it whose files are lost, then two new fulls + full, inc, new, newest = self.backups(Backup.READY, Backup.MISSING, Backup.READY, Backup.READY) + self.chained(full, inc) + schedule.retain() + (op,) = self.deletes() + self.assertEqual(op.params["backup"], str(inc.uuid)) + self.assertTrue(_beyond_keep(inc, self.policy.pk)) + self.finish_all() + Backup.objects.filter(pk=inc.pk).delete() + schedule.retain() + self.assertEqual(self.deletes()[-1].params["backup"], str(full.uuid)) + + def test_a_missing_backup_does_not_count_in_keep(self): + oldest, _missing, _newest = self.backups(Backup.READY, Backup.MISSING, Backup.READY) + schedule.retain() + self.assertEqual(self.deletes(), []) + def test_retention_keeps_keep_ready_backups_when_the_newest_failed(self): self.backups(Backup.READY, Backup.READY, Backup.FAILED) schedule.retain()