From 2e3ffba851bf5c7cf27d9f98828e3620e18cf2b3 Mon Sep 17 00:00:00 2001 From: catborise Date: Thu, 19 Nov 2026 14:52:38 +0300 Subject: [PATCH] fix(backups): a schedule of every VM of a compute reads the host's VMs The schedule took a compute's VMs from the database, which learns of a VM made with virsh only when a page reads the host. When its time comes, the compute's own schedule task reads the host first, once a day per compute and day; the new VM is backed up a pass later. refresh_instance_database now says whether it synchronized: a host that did not answer, was busy or failed is read again at the next pass, and the known VMs are backed up meanwhile. A host in maintenance is not read. --- computes/tests/test_operation_locks.py | 6 ++- computes/utils.py | 5 +- vmbackups/schedule.py | 25 +++++++-- vmbackups/tests/test_schedule.py | 71 ++++++++++++++++++++++++-- 4 files changed, 95 insertions(+), 12 deletions(-) diff --git a/computes/tests/test_operation_locks.py b/computes/tests/test_operation_locks.py index efa42cf4..90007e05 100644 --- a/computes/tests/test_operation_locks.py +++ b/computes/tests/test_operation_locks.py @@ -138,9 +138,13 @@ class ComputeConcurrencyTestCase(TransactionTestCase): compute.status = True claims.admit({claims.compute_key(compute.id): Claim.EXCLUSIVE}, holder="other") - refresh_instance_database(compute) + self.assertIsNone(refresh_instance_database(compute)) # not synchronized: the caller may try again self.assertEqual(Instance.objects.filter(compute=compute).count(), 1) mock_proxy.wvm.listAllDomains.assert_called_once() # the pre-check's read; no reconcile + Claim.objects.all().delete() + self.assertIs(refresh_instance_database(compute), True) # synchronized + self.assertEqual(Instance.objects.filter(compute=compute).count(), 0) + self.assertIs(refresh_instance_database(compute), True) # already matching def _reconcile_compute(self, name, domains): """A compute whose database differs from libvirt (a VM libvirt no diff --git a/computes/utils.py b/computes/utils.py index 7701c9a1..851a9567 100644 --- a/computes/utils.py +++ b/computes/utils.py @@ -184,6 +184,8 @@ def refresh_instance_database(compute): UserInstance permission relationships (matched by UUID). - If libvirt is unreachable (connection/network error), the database is left untouched to avoid false deletions. + True when the database matches the host's VMs afterwards; None when it was + not synchronized (host not answering, busy or changed meanwhile). """ compute_pk = getattr(compute, "pk", getattr(compute, "id", None)) if not compute_pk: @@ -202,7 +204,7 @@ def refresh_instance_database(compute): cutoff = timezone.now() - timedelta(days=retention) if (dict(Instance.objects.filter(compute_id=compute_pk).values_list("uuid", "name")) == host_domains and not InstanceTombstone.objects.filter(removed__lt=cutoff).exists()): - return + return True try: # The compute shared: VM operations and jobs on it go on; changes of @@ -260,6 +262,7 @@ def refresh_instance_database(compute): ) if created and not Instance.objects.filter(uuid=uuid).exclude(compute=compute).exists(): _restore(inst) + return True except claims.Busy: logger.debug("Compute %s is busy; not synchronized now", compute_pk) return diff --git a/vmbackups/schedule.py b/vmbackups/schedule.py index 1b546425..35a7f481 100644 --- a/vmbackups/schedule.py +++ b/vmbackups/schedule.py @@ -15,6 +15,7 @@ from django.utils.translation import gettext_noop as _ from libvirt import libvirtError from computes.models import Compute +from computes.utils import refresh_instance_database from operations import claims, jobs from operations.models import Operation from operations.utils import safe_text, said, say @@ -36,14 +37,20 @@ RETRY_AFTER = datetime.timedelta(hours=1) # a deletion or check that failed is THREADS = 64 _pool = ThreadPoolExecutor(THREADS, thread_name_prefix="wvc-schedule") _tasks = {} # compute id -> the future of its last task +_read = set() # (compute id, local day) whose VMs an "every VM of" schedule has read from the host def run_schedules(now=None): now = now or timezone.now() due = {} # compute id -> [(policy, vm, day)] - for policy in BackupPolicy.objects.filter(enabled=True).select_related("owner"): + # computes whose VMs an "every VM of" schedule reads from the host first, once a day: a VM made + # with virsh is in the database only once a page has read the host (its backup comes a pass later) + read = {} + for policy in BackupPolicy.objects.filter(enabled=True).select_related("owner", "compute"): for day, start in occurrences(policy, now): open_ = now < start + WINDOW + if open_ and policy.compute_id and (policy.compute_id, day) not in _read and not policy.compute.maintenance: + read[policy.compute_id] = day done = set(BackupRun.objects.filter(policy=policy, day=day).values_list("instance_id", flat=True)) for vm in policy.vms(): if vm.pk in done: @@ -53,10 +60,10 @@ def run_schedules(now=None): _record(policy, vm, day, BackupRun.SKIPPED, say(IN_MAINTENANCE if in_maintenance else NOT_STARTED)) elif not in_maintenance: # deferred while the window lasts due.setdefault(vm.compute_id, []).append((policy.pk, vm.pk, day, start)) - for compute_id, items in due.items(): + for compute_id in due.keys() | read.keys(): task = _tasks.get(compute_id) if task is None or task.done(): - _tasks[compute_id] = _pool.submit(_submit_all, compute_id, items) + _tasks[compute_id] = _pool.submit(_submit_all, compute_id, due.get(compute_id, []), read.get(compute_id)) retain() check_targets(now) @@ -84,11 +91,19 @@ def _active_superuser(user): return user is not None and user.is_active and user.is_superuser -def _submit_all(compute_id, items): +def _submit_all(compute_id, items, read_day=None): """One compute's due backups, one after another, each checked again as it comes: the task may have waited for a thread. A busy target or an - unreachable host is tried again at the next pass.""" + unreachable host is tried again at the next pass. With read_day, the host's + VMs are read into the database first; a read that did not sync them is + tried again at the next pass.""" try: + compute = Compute.objects.filter(pk=compute_id, maintenance_since__isnull=True).first() if read_day else None + try: + if compute is not None and refresh_instance_database(compute): + _read.add((compute_id, read_day)) + except Exception: # the backups of the VMs known still go + logger.exception("Reading the VMs of compute %s for its backup schedule failed", compute_id) for policy_id, vm_id, day, start in items: _submit(policy_id, vm_id, day, start) finally: diff --git a/vmbackups/tests/test_schedule.py b/vmbackups/tests/test_schedule.py index d07f43a2..f22767fd 100644 --- a/vmbackups/tests/test_schedule.py +++ b/vmbackups/tests/test_schedule.py @@ -40,21 +40,21 @@ class Inline: self.hold = False self.queued = [] - def submit(self, fn, compute_id, items): + def submit(self, fn, compute_id, *args): future = Future() if compute_id in self.pending: return future # never done: a hung host if self.hold: - self.queued.append((fn, compute_id, items, future)) + self.queued.append((fn, compute_id, args, future)) return future - fn(compute_id, items) + fn(compute_id, *args) future.set_result(None) return future def run_queued(self, now): with patch("django.utils.timezone.now", return_value=now): - for fn, compute_id, items, future in self.queued: - fn(compute_id, items) + for fn, compute_id, args, future in self.queued: + fn(compute_id, *args) future.set_result(None) @@ -88,6 +88,8 @@ class ScheduleTests(TransactionTestCase): target_pool.info.return_value = [2, 1 << 40, 0, 1 << 40] for name, value in (("vmbackups.schedule._pool", self.pool), ("vmbackups.schedule._tasks", {}), + ("vmbackups.schedule._read", set()), + ("vmbackups.schedule.refresh_instance_database", MagicMock(return_value=True)), ("vmbackups.jobs.wvmBackup", MagicMock(return_value=self.proxy)), ("vmbackups.jobs.target_pool", MagicMock(return_value=target_pool))): patcher = patch(name, value) @@ -301,6 +303,65 @@ class ScheduleTests(TransactionTestCase): self.pass_at(at(2026, 11, 17, 3, 1)) self.assertEqual(sorted(BackupRun.objects.values_list("instance__name", flat=True)), ["vm1", "vm2"]) + def host_schedule(self, time=datetime.time(3), name="host", created=at(2026, 11, 17)): + whole = BackupPolicy.objects.create(name=name, target=self.target, compute=self.c1, time=time, keep=1, + owner=self.admin) + BackupPolicy.objects.filter(pk=whole.pk).update(created_at=created) + return whole + + def test_a_compute_schedule_reads_the_host_s_vms_once_a_day(self): + # a VM made with virsh is in the database only once a page read the host: the schedule reads it itself + self.host_schedule() + BackupPolicy.objects.filter(pk=self.policy.pk).update(enabled=False) + + def made_outside(compute): + Instance.objects.get_or_create(compute=compute, name="virsh-vm", uuid="71717171-0000-4000-8000-000000000009") + return True + + with patch("vmbackups.schedule.refresh_instance_database", side_effect=made_outside) as refresh: + self.pass_at(at(2026, 11, 17, 2, 59)) + self.assertEqual(refresh.call_count, 0) # not before its time + for minute in range(4): # one copy at a time per target + self.pass_at(at(2026, 11, 17, 3, minute)) + self.finish_all() + self.assertEqual(refresh.call_count, 1) + self.assertEqual(refresh.call_args.args[0].pk, self.c1.pk) + self.assertEqual(sorted(BackupRun.objects.values_list("instance__name", flat=True)), ["virsh-vm", "vm1", "vm2"]) + + def test_a_read_that_did_not_sync_is_tried_again_and_the_known_vms_still_go(self): + self.host_schedule() + BackupPolicy.objects.filter(pk=self.policy.pk).update(enabled=False) + # not answering or busy (None), then failing outright: the known VMs are backed up meanwhile + with patch("vmbackups.schedule.refresh_instance_database", side_effect=[None, RuntimeError("db"), True]) as refresh: + for minute in range(4): + self.pass_at(at(2026, 11, 17, 3, minute)) + self.finish_all() + self.assertEqual(refresh.call_count, 3) + self.assertEqual(sorted(BackupRun.objects.values_list("instance__name", flat=True)), ["vm1", "vm2"]) + + def test_two_schedules_across_midnight_read_the_host_once_each(self): + self.host_schedule(datetime.time(23), "late", at(2026, 11, 16)) + self.host_schedule(datetime.time(1), "early", at(2026, 11, 16)) + BackupPolicy.objects.filter(pk=self.policy.pk).update(enabled=False) + with patch("vmbackups.schedule.refresh_instance_database", return_value=True) as refresh: + self.pass_at(at(2026, 11, 16, 23, 0)) + for minute in range(3): + self.pass_at(at(2026, 11, 17, 1, minute)) + self.assertEqual(refresh.call_count, 2) + + def test_a_host_in_maintenance_is_not_read(self): + self.host_schedule() + Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 17)) + with patch("vmbackups.schedule.refresh_instance_database", return_value=True) as refresh: + self.pass_at(at(2026, 11, 17, 3, 0)) + # nor one put in maintenance while its task waited for a thread + Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=None) + self.pool.hold = True + self.pass_at(at(2026, 11, 17, 3, 1)) + Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 17, 3, 1)) + self.pool.run_queued(at(2026, 11, 17, 3, 1)) + self.assertEqual(refresh.call_count, 0) + def test_a_hung_host_stops_no_other_hosts_schedule(self): vm3 = Instance.objects.create(compute=self.c2, name="vm3", uuid="71717171-0000-4000-8000-000000000003") other = BackupTarget.objects.create(name="nfs2", checked_at=at(2026, 11, 17))