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

feat(vmbackups): schedules back VMs up daily, keep the newest, check targets

The worker's periodic pass (about once a minute) runs the schedules:

- Each enabled schedule's VMs are backed up once a local day, from the
  schedule's time for 6 hours, as its owner. A late time's window goes
  on after midnight; a time a spring-forward gap skips falls an hour
  later, a repeated autumn time is its first. A run row per schedule,
  VM row and day, and a submission key made from them, keep a worker
  that stopped between the job and its row from backing a VM up twice.
- A busy target (one copy at a time) or an unreachable host is tried
  again at the next pass; a host in maintenance is waited for. A VM not
  started within the window, a VM that cannot be backed up (TPM) and a
  schedule whose owner is no longer an active superuser get a run row
  saying why. Times passed before a schedule was made are not run.
- Each compute's submissions are a task of their own: a hung host stops
  no other compute's schedules.
- Retention: each schedule's ready backups of a VM beyond keep, oldest
  first, one deletion a target at a time. The deletion checks again,
  before it changes anything, that the backup is still beyond keep.
  Backups by hand and backups of removed VMs are left alone.
- Each target is checked once a day by a backup.check job holding it: a
  ready backup with a file gone, its manifest included, becomes missing
  (restore refused, delete allowed); one whose files are back is ready
  again. A pool no compute reaches marks nothing.
- A scheduled backup carries the end of its window: one that waited
  past it for a worker slot, or whose host went into maintenance
  meanwhile, ends without starting (checked after the host answered).

The jobs on a target alone (delete, read back, check) hold its computes
too, shared: the worker counts a job's hosts by these, so a hung host
takes no more than its share of the slots.
This commit is contained in:
catborise 2026-11-17 10:23:31 +03:00
parent 1219a37cc4
commit 819cdada69
7 changed files with 894 additions and 97 deletions

View file

@ -22,7 +22,7 @@ from instances.jobs import PAUSED_FROZEN, THAW_FAILED, _instance, _log, _snapsho
from instances.utils import get_random_mac_address
from instances.models import Instance
from operations import claims
from operations.jobs import Cancelled, Kind, Outcome, Plan, register
from operations.jobs import Cancelled, Kind, Outcome, Plan, register, register_periodic
from operations.models import Claim, Operation
from operations.utils import safe_text, say
from vrtManager import util
@ -190,8 +190,9 @@ class CreateBackup(Kind):
def normalize(self, raw):
return {"instance": int(raw["instance"]), "target": int(raw["target"]),
"frozen": str(raw.get("frozen", "")).lower() in ("1", "true", "on"),
# the schedule that asked for it, if one did
"policy": int(raw["policy"]) if raw.get("policy") else None}
# the schedule that asked for it, if one did, and the end of its window
"policy": int(raw["policy"]) if raw.get("policy") else None,
"deadline": parse_datetime(raw["deadline"]).isoformat() if raw.get("deadline") else None}
def plan(self, user, params):
_superuser(user)
@ -213,6 +214,14 @@ class CreateBackup(Kind):
def run(self, op, ctx):
instance, target, row, proxy, pool, plan = _checked(op)
if op.params.get("policy"):
# after the host's checks, which may have waited for it: a schedule's backup starts in its window,
# and on no host gone into maintenance (one by hand may)
if op.params.get("deadline") and timezone.now() > parse_datetime(op.params["deadline"]):
raise util.OperationError(_("The schedule's window ended before the backup could start"))
if instance.compute._in_maintenance_now():
raise util.OperationError(_("%(compute)s went into maintenance before the scheduled backup could "
"start"), compute=instance.compute.name)
status = proxy.get_status()
live = status != VIR_DOMAIN_SHUTOFF
names = backup_file_names(op.intent["backup"], plan["disks"], bool(plan["nvram"]))
@ -437,10 +446,31 @@ def _target_pool(target):
raise util.OperationError(_("No compute of backup target %(target)s reaches its storage pool"), target=target.name)
def _target_claims(target):
"""A job on a target alone: the target, and its computes shared, which
the worker counts so a hung host takes no more than its share of slots."""
keys = {claims.compute_key(compute_id): Claim.SHARED
for compute_id in target.pools.values_list("compute_id", flat=True)}
keys[claims.backup_target_key(target.pk)] = Claim.EXCLUSIVE
return keys
def _backup(params):
return Backup.objects.select_related("target").get(uuid=params["backup"])
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)."""
policy = BackupPolicy.objects.filter(pk=policy_id).first()
if policy is None or backup.policy_id != policy.pk or backup.instance_id is None:
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:]
@register
class DeleteBackup(Kind):
"""The manifest goes first, so the target no longer holds a complete
@ -450,7 +480,9 @@ class DeleteBackup(Kind):
label = _("Delete backup")
def normalize(self, raw):
return {"backup": str(UUID(str(raw["backup"])))}
# retention: the schedule whose keep the backup is beyond, when the schedule asks
return {"backup": str(UUID(str(raw["backup"]))),
"retention": int(raw["retention"]) if raw.get("retention") else None}
def plan(self, user, params):
_superuser(user)
@ -458,8 +490,7 @@ class DeleteBackup(Kind):
if backup.state == Backup.CREATING:
raise util.OperationError(_("This backup is being made; cancel its job to stop it"))
return Plan(
claims={claims.backup_key(backup.uuid): Claim.EXCLUSIVE,
claims.backup_target_key(backup.target_id): Claim.EXCLUSIVE},
claims={claims.backup_key(backup.uuid): Claim.EXCLUSIVE, **_target_claims(backup.target)},
resource=claims.backup_key(backup.uuid),
label=f"{backup.target.name}/{backup.vm_name}",
intent={"compute": backup.compute_name, "vm": backup.vm_name, "uuid": backup.vm_uuid,
@ -469,6 +500,8 @@ class DeleteBackup(Kind):
def run(self, op, ctx):
_superuser(op.user)
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"))
_conn, pool = _target_pool(backup.target)
ctx.record_intent(deleting=True)
return self._delete(backup, pool)
@ -697,7 +730,7 @@ class ImportBackups(Kind):
def plan(self, user, params):
_superuser(user)
target = BackupTarget.objects.get(pk=params["target"])
return Plan(claims={claims.backup_target_key(target.pk): Claim.EXCLUSIVE},
return Plan(claims=_target_claims(target),
resource=claims.backup_target_key(target.pk), label=target.name, intent={"target": target.name})
def run(self, op, ctx):
@ -744,3 +777,51 @@ class ImportBackups(Kind):
def log_entry(self, op, state):
message = f"Backup target {op.intent['target']}: backups read"
return "-", "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})"
@register
class CheckTarget(Kind):
"""A target's backups checked against its pool: a ready backup with a
file gone (its manifest too) becomes missing, a missing one whose files
are all there ready again. A pool no compute reaches marks nothing."""
name = "backup.check"
label = _("Check backup target")
def normalize(self, raw):
return {"target": int(raw["target"])}
def plan(self, user, params):
_superuser(user)
target = BackupTarget.objects.get(pk=params["target"])
return Plan(claims=_target_claims(target),
resource=claims.backup_target_key(target.pk), label=target.name, intent={"target": target.name})
def run(self, op, ctx):
_superuser(op.user)
target = BackupTarget.objects.get(pk=op.params["target"])
_conn, pool = _target_pool(target)
pool.refresh(0)
present = set(pool.listVolumes())
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
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
Backup.objects.filter(pk=backup.pk, state=backup.state).update(state=state)
BackupTarget.objects.filter(pk=target.pk).update(checked_at=timezone.now())
if missing:
return {"warning": say(_("Files of these backups are missing from the target: %(backups)s"),
backups=", ".join(missing))}
return {}
def log_entry(self, op, state):
message = f"Backup target {op.intent['target']}: checked"
return "-", "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})"
from .schedule import run_schedules # noqa: E402 (it submits this module's kinds)
register_periodic(run_schedules)

183
vmbackups/schedule.py Normal file
View file

@ -0,0 +1,183 @@
"""Backup schedules, run by the worker about once a minute (its periodic
tasks): each schedule's VMs backed up once a local day within WINDOW of its
time, each VM's backups of the schedule beyond keep deleted, and each target
checked once a day. The jobs run as the schedule's owner."""
import datetime
import logging
from concurrent.futures import ThreadPoolExecutor
from django.contrib.auth import get_user_model
from django.db import close_old_connections
from django.core.exceptions import PermissionDenied
from django.utils import timezone
from django.utils.translation import gettext_noop as _
from libvirt import libvirtError
from computes.models import Compute
from operations import claims, jobs
from operations.models import Operation
from operations.utils import safe_text
from vrtManager.util import ConnectionFailed
from .models import Backup, BackupPolicy, BackupRun, BackupTarget
logger = logging.getLogger(__name__)
WINDOW = datetime.timedelta(hours=6) # a run is admitted this long after its time, else skipped
NOT_STARTED = _("Not started within 6 hours of its time")
IN_MAINTENANCE = _("The host was in maintenance")
NO_OWNER = _("The schedule's owner is no longer an active superuser")
RETRY_AFTER = datetime.timedelta(hours=1) # a deletion or check that failed is tried again after this
# each compute's submissions in a task of their own, at most one a compute: with a thread for every
# compute, hung hosts take no thread a healthy host's task needs (threads start only when needed)
THREADS = 64
_pool = ThreadPoolExecutor(THREADS, thread_name_prefix="wvc-schedule")
_tasks = {} # compute id -> the future of its last task
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"):
for day, start in occurrences(policy, now):
open_ = now < start + WINDOW
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:
continue
in_maintenance = Compute.objects.filter(pk=vm.compute_id, maintenance_since__isnull=False).exists()
if not open_:
_record(policy, vm, day, BackupRun.SKIPPED, 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():
task = _tasks.get(compute_id)
if task is None or task.done():
_tasks[compute_id] = _pool.submit(_submit_all, compute_id, items)
retain()
check_targets(now)
def occurrences(policy, now):
"""(local day, instant) of the schedule's times yesterday and today that
have come and are not older than the schedule: a late time's window goes
on after midnight. A time a spring-forward gap skips falls an hour later
(zoneinfo, fold 0); a time repeated in autumn is its first."""
zone = timezone.get_default_timezone()
today = timezone.localtime(now, zone).date()
for day in (today - datetime.timedelta(days=1), today):
# in UTC: the window is real hours, also on a day the clocks change
start = datetime.datetime.combine(day, policy.time, tzinfo=zone).astimezone(datetime.timezone.utc)
if policy.created_at <= start <= now:
yield day, start
def _record(policy, vm, day, state, note="", operation=None):
BackupRun.objects.get_or_create(policy=policy, instance=vm, day=day,
defaults={"state": state, "note": note[:255], "operation": operation})
def _active_superuser(user):
return user is not None and user.is_active and user.is_superuser
def _submit_all(compute_id, items):
"""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."""
try:
for policy_id, vm_id, day, start in items:
_submit(policy_id, vm_id, day, start)
finally:
close_old_connections() # a thread of the pool: its connection is its own
def _submit(policy_id, vm_id, day, start):
policy = BackupPolicy.objects.select_related("owner").filter(pk=policy_id, enabled=True).first()
now = timezone.now()
if policy is None or now >= start + WINDOW or (day, start) not in set(occurrences(policy, now)):
return # disabled, deleted or its time moved meanwhile, or its window ended: the next pass decides
vm = policy.vms().filter(pk=vm_id).first()
if vm is None or BackupRun.objects.filter(policy=policy, instance=vm, day=day).exists():
return
if Compute.objects.filter(pk=vm.compute_id, maintenance_since__isnull=False).exists():
return
if not _active_superuser(policy.owner):
_record(policy, vm, day, BackupRun.FAILED, NO_OWNER)
return
# the same key for the same run: a worker stopped before the row was written gets the same job back
key = f"bk-{policy.pk}-{vm.pk}-{day:%Y%m%d}"
raw = {"instance": vm.pk, "target": policy.target_id, "frozen": policy.frozen, "policy": policy.pk,
"deadline": (start + WINDOW).isoformat()} # a job that waited past it for a worker slot does not start
try:
op = jobs.submit("backup.create", policy.owner, raw, key)
except (claims.Busy, ConnectionFailed):
return
except (libvirtError, PermissionDenied, jobs.SubmissionConflict) as err: # it would be refused again
_record(policy, vm, day, BackupRun.FAILED, safe_text(str(err) or type(err).__name__))
return
except Exception as err:
logger.error("schedule %s: backup of %s not submitted: %s", policy.name, vm.name, safe_text(err))
return
_record(policy, vm, day, BackupRun.SUBMITTED, operation=op)
def _attempt_key(base):
"""The submission key of the next attempt of a job named base: the
running or ended one's own, so it is not submitted twice; a new one an
hour after a failed or cancelled one; None before that."""
attempts = Operation.objects.filter(submission_key__startswith=f"{base}-")
last = attempts.order_by("-created_at").first()
if last is None:
return f"{base}-0"
if last.state not in (Operation.FAILED, Operation.CANCELLED):
return last.submission_key
if last.finished_at and timezone.now() - last.finished_at < RETRY_AFTER:
return None
return f"{base}-{attempts.count()}"
def retain():
"""Each schedule's ready backups of a VM beyond keep, 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():
if len(rows) > policy.keep:
tried.add(policy.target_id)
if (key := _attempt_key(f"rt-{rows[-1].uuid.hex}")) is None:
break
try:
jobs.submit("backup.delete", policy.owner, {"backup": str(rows[-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))
break
def check_targets(now):
"""A backup.check job for each target not checked today, as the first
active superuser; a busy target is checked at a later pass."""
today = timezone.localtime(now).date()
user = get_user_model().objects.filter(is_superuser=True, is_active=True).order_by("pk").first()
if user is None:
return
for target in BackupTarget.objects.filter(pools__isnull=False).distinct():
if target.checked_at and timezone.localtime(target.checked_at).date() >= today:
continue
if (key := _attempt_key(f"ck-{target.pk}-{today:%Y%m%d}")) is None:
continue
try:
jobs.submit("backup.check", user, {"target": target.pk}, key)
except Exception as err:
logger.info("target %s: check waits: %s", target.name, safe_text(err))

View file

@ -0,0 +1,463 @@
"""Backup schedules: the worker's periodic pass submits each VM's backup once
a day within its window, deletes what is beyond keep, checks targets."""
import datetime
from concurrent.futures import Future
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import libvirt
from django.contrib.auth import get_user_model
from django.test import TransactionTestCase, override_settings
from appsettings.settings import get_settings
from computes.models import Compute
from instances.models import Instance
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.models import Backup, BackupFile, BackupPolicy, BackupRun, BackupTarget, BackupTargetPool
from vrtManager.util import OperationError
UTC = datetime.timezone.utc
WORKER = "wvc-test:1:a"
def at(*args):
return datetime.datetime(*args, tzinfo=UTC)
class Inline:
"""The pool of per-compute tasks, run at once; pending: computes whose task still runs;
queued: tasks held until run_queued (busy threads)."""
def __init__(self):
self.pending = set()
self.hold = False
self.queued = []
def submit(self, fn, compute_id, items):
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))
return future
fn(compute_id, items)
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)
future.set_result(None)
def proxy():
p = MagicMock()
p.get_status.return_value = libvirt.VIR_DOMAIN_SHUTOFF
p.backup_plan.return_value = {"definition": "<domain/>", "disks": [], "nvram": None, "left_out": []}
return p
@override_settings(TIME_ZONE="UTC")
class ScheduleTests(TransactionTestCase):
def setUp(self):
get_settings()
self.admin = get_user_model().objects.create_superuser("sc_admin", "a@example.com", "pw")
self.c1 = Compute.objects.create(name="h1", hostname="192.0.2.71", login="u", password="p", type=1)
self.c2 = Compute.objects.create(name="h2", hostname="192.0.2.72", login="u", password="p", type=1)
self.vm1 = Instance.objects.create(compute=self.c1, name="vm1", uuid="71717171-0000-4000-8000-000000000001")
self.vm2 = Instance.objects.create(compute=self.c1, name="vm2", uuid="71717171-0000-4000-8000-000000000002")
self.target = BackupTarget.objects.create(name="nfs1", checked_at=at(2026, 11, 17, 0, 0))
BackupTargetPool.objects.create(target=self.target, compute=self.c1, pool="b1", pool_uuid="u")
BackupTargetPool.objects.create(target=self.target, compute=self.c2, pool="b1", pool_uuid="u")
self.policy = BackupPolicy.objects.create(name="nightly", target=self.target, time=datetime.time(2, 0), keep=2,
owner=self.admin)
BackupPolicy.objects.filter(pk=self.policy.pk).update(created_at=at(2026, 11, 17))
self.policy.refresh_from_db()
self.policy.instances.add(self.vm1)
self.pool = Inline()
self.proxy = proxy()
target_pool = MagicMock()
target_pool.info.return_value = [2, 1 << 40, 0, 1 << 40]
for name, value in (("vmbackups.schedule._pool", self.pool),
("vmbackups.schedule._tasks", {}),
("vmbackups.jobs.wvmBackup", MagicMock(return_value=self.proxy)),
("vmbackups.jobs.target_pool", MagicMock(return_value=target_pool))):
patcher = patch(name, value)
patcher.start()
self.addCleanup(patcher.stop)
def pass_at(self, now):
"""A pass of the worker at now, its tasks run then too."""
with patch("django.utils.timezone.now", return_value=now):
schedule.run_schedules(now)
def creates(self):
return list(Operation.objects.filter(kind="backup.create").order_by("created_at"))
def finish_all(self):
for op in Operation.objects.filter(state__in=Operation.ACTIVE):
jobs.finish(op, jobs.Outcome(Operation.SUCCEEDED))
def test_due_at_its_time_not_before(self):
self.pass_at(at(2026, 11, 17, 1, 59))
self.assertEqual(self.creates(), [])
self.pass_at(at(2026, 11, 17, 2, 0))
op = self.creates()[0]
self.assertEqual(op.params, {"instance": self.vm1.pk, "target": self.target.pk, "frozen": False,
"policy": self.policy.pk, "deadline": "2026-11-17T08:00:00+00:00"})
self.assertEqual(op.username, "sc_admin")
run = BackupRun.objects.get()
self.assertEqual((run.instance, run.day, run.state, run.operation), (self.vm1, datetime.date(2026, 11, 17),
BackupRun.SUBMITTED, op))
def test_a_backup_that_waited_past_its_window_does_not_start(self):
from operations.jobs import Context
from vmbackups.jobs import CreateBackup
self.pass_at(at(2026, 11, 17, 7, 59))
op = self.creates()[0]
acquire(WORKER, "wvc-test")
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER)
op.refresh_from_db()
with patch("django.utils.timezone.now", return_value=at(2026, 11, 17, 8, 1)): # it waited for a slot
with self.assertRaisesMessage(OperationError, "window ended"):
CreateBackup().run(op, Context(op, SimpleNamespace(identity=WORKER)))
self.assertFalse(Backup.objects.exists())
self.proxy.copy_disk_offline.assert_not_called()
def started(self, now, op):
from operations.jobs import Context
from vmbackups.jobs import CreateBackup
acquire(WORKER, "wvc-test")
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER)
op.refresh_from_db()
with patch("django.utils.timezone.now", return_value=now):
CreateBackup().run(op, Context(op, SimpleNamespace(identity=WORKER)))
def test_a_scheduled_backup_whose_host_went_into_maintenance_does_not_start(self):
self.pass_at(at(2026, 11, 17, 2, 0))
Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 17, 2, 1))
with self.assertRaisesMessage(OperationError, "maintenance"):
self.started(at(2026, 11, 17, 2, 2), self.creates()[0])
self.assertFalse(Backup.objects.exists())
def test_the_window_is_checked_again_after_the_host_answered(self):
self.pass_at(at(2026, 11, 17, 7, 59))
# the host answers the checks only after the window ended
self.proxy.backup_plan.side_effect = lambda: patch_now.start() or {
"definition": "<domain/>", "disks": [], "nvram": None, "left_out": []}
patch_now = patch("django.utils.timezone.now", return_value=at(2026, 11, 17, 8, 30))
self.addCleanup(patch.stopall)
with self.assertRaisesMessage(OperationError, "window ended"):
self.started(at(2026, 11, 17, 7, 59, 30), self.creates()[0])
self.assertFalse(Backup.objects.exists())
def test_once_a_day(self):
self.pass_at(at(2026, 11, 17, 2, 0))
self.finish_all()
self.pass_at(at(2026, 11, 17, 3, 0))
self.assertEqual(len(self.creates()), 1)
self.pass_at(at(2026, 11, 18, 2, 1))
self.assertEqual(len(self.creates()), 2)
def test_a_worker_stopped_between_the_job_and_its_run_row_submits_no_second_job(self):
self.pass_at(at(2026, 11, 17, 2, 0))
BackupRun.objects.all().delete() # the row was never written
self.pass_at(at(2026, 11, 17, 2, 1))
self.assertEqual(len(self.creates()), 1)
self.assertEqual(BackupRun.objects.get().operation, self.creates()[0])
def test_a_busy_target_is_tried_again_and_the_vms_go_one_after_another(self):
self.policy.instances.add(self.vm2)
self.pass_at(at(2026, 11, 17, 2, 0))
self.assertEqual(BackupRun.objects.count(), 1) # the target admits one copy
self.pass_at(at(2026, 11, 17, 2, 1))
self.assertEqual(BackupRun.objects.count(), 1) # still busy
self.finish_all()
self.pass_at(at(2026, 11, 17, 2, 30))
self.assertEqual(BackupRun.objects.count(), 2)
def test_a_host_in_maintenance_is_deferred_then_skipped(self):
Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 16))
self.pass_at(at(2026, 11, 17, 2, 0))
self.assertEqual(BackupRun.objects.count(), 0)
self.pass_at(at(2026, 11, 17, 8, 1))
run = BackupRun.objects.get()
self.assertEqual(run.state, BackupRun.SKIPPED)
self.assertIn("maintenance", run.note)
self.assertEqual(self.creates(), [])
def test_maintenance_ended_inside_the_window(self):
Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 16))
self.pass_at(at(2026, 11, 17, 2, 0))
Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=None)
self.pass_at(at(2026, 11, 17, 4, 0))
self.assertEqual(BackupRun.objects.get().state, BackupRun.SUBMITTED)
def test_a_day_the_worker_was_down_is_skipped_not_caught_up(self):
self.pass_at(at(2026, 11, 18, 9, 0)) # down from before 02:00 on the 17th
self.assertEqual(sorted(BackupRun.objects.values_list("day", "state")),
[(datetime.date(2026, 11, 17), BackupRun.SKIPPED), (datetime.date(2026, 11, 18), BackupRun.SKIPPED)])
self.assertEqual(self.creates(), [])
def test_a_run_not_started_in_its_window_is_skipped(self):
self.pass_at(at(2026, 11, 17, 8, 1)) # the worker was down from before 02:00
run = BackupRun.objects.get()
self.assertEqual(run.state, BackupRun.SKIPPED)
self.assertIn("6 hours", run.note)
self.assertEqual(self.creates(), [])
def test_a_new_schedule_does_not_skip_the_times_before_it(self):
BackupPolicy.objects.filter(pk=self.policy.pk).update(created_at=at(2026, 11, 17, 10))
self.pass_at(at(2026, 11, 17, 10, 1))
self.assertEqual(BackupRun.objects.count(), 0)
self.pass_at(at(2026, 11, 18, 2, 0))
self.assertEqual(BackupRun.objects.get().day, datetime.date(2026, 11, 18))
def test_a_late_schedule_still_runs_after_midnight(self):
BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(23, 0))
self.pass_at(at(2026, 11, 18, 1, 0)) # the worker came back after midnight
self.assertEqual(BackupRun.objects.get().day, datetime.date(2026, 11, 17))
self.assertEqual(len(self.creates()), 1)
def test_a_task_that_waited_for_a_thread_checks_again_before_it_submits(self):
self.pool.hold = True
self.pass_at(at(2026, 11, 17, 2, 0))
BackupPolicy.objects.filter(pk=self.policy.pk).update(enabled=False)
self.pool.run_queued(at(2026, 11, 17, 2, 5))
self.assertEqual(self.creates(), [])
BackupPolicy.objects.filter(pk=self.policy.pk).update(enabled=True)
self.pool.queued.clear()
self.pass_at(at(2026, 11, 17, 7, 59))
self.pool.run_queued(at(2026, 11, 17, 8, 1)) # its window ended while it waited
self.assertEqual(self.creates(), [])
def test_a_task_that_waited_while_the_time_was_moved_does_not_submit(self):
self.pool.hold = True
self.pass_at(at(2026, 11, 17, 2, 0))
BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(5, 0))
self.pool.run_queued(at(2026, 11, 17, 2, 1))
self.assertEqual(self.creates(), [])
self.assertEqual(BackupRun.objects.count(), 0)
def test_the_target_jobs_hold_the_targets_computes(self):
from operations.models import Claim
BackupTarget.objects.filter(pk=self.target.pk).update(checked_at=at(2026, 11, 16))
schedule.check_targets(at(2026, 11, 17, 9))
op = Operation.objects.get(kind="backup.check")
# the worker counts a job's hosts by these: a hung host takes no more than its share of the slots
self.assertEqual(set(Claim.objects.filter(operation=op, resource__startswith="compute:")
.values_list("resource", "mode")),
{(f"compute:{self.c1.pk}", Claim.SHARED), (f"compute:{self.c2.pk}", Claim.SHARED)})
for backup in self.backups(*[Backup.READY] * 3):
pass
jobs.finish(op, jobs.Outcome(Operation.SUCCEEDED))
schedule.retain()
delete = Operation.objects.get(kind="backup.delete")
self.assertTrue(Claim.objects.filter(operation=delete, resource=f"compute:{self.c1.pk}").exists())
def test_an_owner_who_is_no_superuser_fails_the_run(self):
get_user_model().objects.filter(pk=self.admin.pk).update(is_superuser=False)
self.pass_at(at(2026, 11, 17, 2, 0))
run = BackupRun.objects.get()
self.assertEqual(run.state, BackupRun.FAILED)
self.assertIn("owner", run.note)
def test_a_vm_that_cannot_be_backed_up_fails_once_with_the_reason(self):
self.proxy.backup_plan.side_effect = OperationError("%(vm)s has TPM state; TPM backups come later", vm="vm1")
self.pass_at(at(2026, 11, 17, 2, 0))
self.pass_at(at(2026, 11, 17, 2, 1))
run = BackupRun.objects.get()
self.assertEqual((run.state, run.note), (BackupRun.FAILED, "vm1 has TPM state; TPM backups come later"))
def test_an_unreachable_host_is_tried_again(self):
from vrtManager.util import ConnectionFailed
with patch("vmbackups.jobs.wvmBackup", side_effect=ConnectionFailed("Cannot connect to %(host)s", host="h1")):
self.pass_at(at(2026, 11, 17, 2, 0))
self.assertEqual(BackupRun.objects.count(), 0)
self.pass_at(at(2026, 11, 17, 2, 1))
self.assertEqual(BackupRun.objects.get().state, BackupRun.SUBMITTED)
def test_a_compute_schedule_takes_its_vms_now(self):
whole = BackupPolicy.objects.create(name="host", target=self.target, compute=self.c1, time=datetime.time(3),
keep=1, owner=self.admin)
BackupPolicy.objects.filter(pk=whole.pk).update(created_at=at(2026, 11, 17))
BackupPolicy.objects.filter(pk=self.policy.pk).update(enabled=False)
self.pass_at(at(2026, 11, 17, 3, 0))
self.finish_all()
self.pass_at(at(2026, 11, 17, 3, 1))
self.assertEqual(sorted(BackupRun.objects.values_list("instance__name", flat=True)), ["vm1", "vm2"])
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))
BackupTargetPool.objects.create(target=other, compute=self.c2, pool="b2", pool_uuid="u2")
policy = BackupPolicy.objects.create(name="other", target=other, time=datetime.time(2), keep=1, owner=self.admin)
BackupPolicy.objects.filter(pk=policy.pk).update(created_at=at(2026, 11, 17))
policy.instances.add(vm3)
self.pool.pending.add(self.c1.pk) # its first task never ends
self.pass_at(at(2026, 11, 17, 2, 0))
self.pass_at(at(2026, 11, 17, 2, 1))
self.assertEqual(list(BackupRun.objects.values_list("instance__name", flat=True)), ["vm3"])
@override_settings(TIME_ZONE="Europe/Berlin")
def test_a_time_in_the_spring_forward_gap_runs_an_hour_later_once(self):
BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(2, 30), created_at=at(2026, 3, 29))
# 2026-03-29 02:30 does not exist in Berlin: 03:30 local, 01:30 UTC
self.pass_at(at(2026, 3, 29, 1, 29))
self.assertEqual(BackupRun.objects.count(), 0)
self.pass_at(at(2026, 3, 29, 1, 31))
self.assertEqual(BackupRun.objects.get().day, datetime.date(2026, 3, 29))
@override_settings(TIME_ZONE="Europe/Berlin")
def test_the_window_is_six_real_hours_on_a_clock_change_day(self):
BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(2, 30), created_at=at(2026, 3, 29))
self.pass_at(at(2026, 3, 29, 7, 0)) # 5.5 h after 01:30 UTC
self.assertEqual(BackupRun.objects.get().state, BackupRun.SUBMITTED)
def test_the_schedule_pool_has_a_thread_for_each_compute(self):
self.assertGreaterEqual(schedule.THREADS, 32)
@override_settings(TIME_ZONE="Europe/Berlin")
def test_a_time_repeated_in_autumn_runs_once(self):
BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(2, 30), created_at=at(2026, 10, 25))
# 2026-10-25 02:30 is 00:30 and 01:30 UTC; the first is the schedule's
self.pass_at(at(2026, 10, 25, 0, 31))
self.finish_all()
self.pass_at(at(2026, 10, 25, 1, 31))
self.assertEqual(len(self.creates()), 1)
# -- retention -------------------------------------------------------
def backups(self, *states, policy=True, instance=None):
made = []
for number, state in enumerate(states):
b = Backup.objects.create(target=self.target, instance=instance or self.vm1, vm_uuid=self.vm1.uuid,
vm_name="vm1", compute_name="h1", state=state,
policy=self.policy if policy else None)
Backup.objects.filter(pk=b.pk).update(created_at=at(2026, 11, 10 + number))
made.append(b)
return made
def deletes(self):
return list(Operation.objects.filter(kind="backup.delete").order_by("created_at"))
def test_retention_deletes_the_oldest_beyond_keep_one_at_a_time(self):
oldest, older, _new, _newest = self.backups(*[Backup.READY] * 4)
schedule.retain()
(op,) = self.deletes()
self.assertEqual(op.params, {"backup": str(oldest.uuid), "retention": self.policy.pk})
schedule.retain() # the target is busy with that deletion
self.assertEqual(len(self.deletes()), 1)
self.finish_all()
Backup.objects.filter(pk=oldest.pk).delete()
schedule.retain()
self.assertEqual(self.deletes()[-1].params["backup"], str(older.uuid))
def test_a_failed_deletion_is_tried_again_an_hour_later(self):
oldest, *_rest = self.backups(*[Backup.READY] * 3)
schedule.retain()
(op,) = self.deletes()
jobs.finish(op, jobs.Outcome(Operation.FAILED))
schedule.retain()
self.assertEqual(len(self.deletes()), 1) # not every minute
Operation.objects.filter(pk=op.pk).update(finished_at=op.finished_at - datetime.timedelta(minutes=61))
schedule.retain()
self.assertEqual(len(self.deletes()), 2)
self.assertEqual(self.deletes()[-1].params["backup"], str(oldest.uuid))
def test_retention_keeps_keep_ready_backups_when_the_newest_failed(self):
self.backups(Backup.READY, Backup.READY, Backup.FAILED)
schedule.retain()
self.assertEqual(self.deletes(), [])
def test_retention_leaves_backups_by_hand_and_of_removed_vms(self):
self.backups(Backup.READY, Backup.READY, policy=False)
self.backups(Backup.READY, Backup.READY, Backup.READY)
Backup.objects.filter(policy=self.policy).update(instance=None) # the VM row is gone
schedule.retain()
self.assertEqual(self.deletes(), [])
def run_delete(self, backup):
op = jobs.submit("backup.delete", self.admin, {"backup": str(backup.uuid), "retention": self.policy.pk},
"key-retain-0001")
acquire(WORKER, "wvc-test")
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER)
op.refresh_from_db()
return op, Context(op, SimpleNamespace(identity=WORKER))
@patch("vmbackups.jobs._target_pool")
def test_a_retention_deletion_checks_again_before_it_deletes(self, target_pool):
oldest, *_rest = self.backups(*[Backup.READY] * 3)
op, ctx = self.run_delete(oldest)
BackupPolicy.objects.filter(pk=self.policy.pk).update(keep=5) # raised meanwhile
with self.assertRaisesMessage(OperationError, "no longer beyond"):
DeleteBackup().run(op, ctx)
target_pool.assert_not_called()
self.assertTrue(Backup.objects.filter(pk=oldest.pk, state=Backup.READY).exists())
op.refresh_from_db()
self.assertFalse(op.effects_started)
# -- target check ------------------------------------------------------
def test_a_target_is_checked_once_a_day(self):
BackupTarget.objects.filter(pk=self.target.pk).update(checked_at=at(2026, 11, 16, 9))
schedule.check_targets(at(2026, 11, 17, 9))
schedule.check_targets(at(2026, 11, 17, 9, 1))
(op,) = Operation.objects.filter(kind="backup.check")
self.assertEqual(op.params, {"target": self.target.pk})
def test_a_failed_check_is_tried_again_an_hour_later(self):
BackupTarget.objects.filter(pk=self.target.pk).update(checked_at=at(2026, 11, 16, 9))
schedule.check_targets(at(2026, 11, 17, 9))
(op,) = Operation.objects.filter(kind="backup.check")
jobs.finish(op, jobs.Outcome(Operation.FAILED))
schedule.check_targets(at(2026, 11, 17, 9, 1))
self.assertEqual(Operation.objects.filter(kind="backup.check").count(), 1)
Operation.objects.filter(pk=op.pk).update(finished_at=op.finished_at - datetime.timedelta(minutes=61))
schedule.check_targets(at(2026, 11, 17, 10, 5))
self.assertEqual(Operation.objects.filter(kind="backup.check").count(), 2)
def run_check(self, names):
op = jobs.submit("backup.check", self.admin, {"target": self.target.pk}, "key-check-0001")
acquire(WORKER, "wvc-test")
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER)
op.refresh_from_db()
pool = MagicMock()
pool.listVolumes.return_value = names
with patch("vmbackups.jobs._target_pool", return_value=(MagicMock(), pool)):
return CheckTarget().run(op, Context(op, SimpleNamespace(identity=WORKER)))
def test_the_check_marks_missing_files_and_files_back(self):
whole, gone = self.backups(Backup.READY, Backup.READY)
for b in (whole, gone):
BackupFile.objects.create(backup=b, role=BackupFile.DISK, dev="vda", volume=f"{b.prefix}-vda.qcow2")
present = [f"{whole.prefix}-vda.qcow2", f"{whole.prefix}-manifest.json", f"{gone.prefix}-vda.qcow2"]
result = self.run_check(present) # gone's manifest is not there
self.assertEqual(Backup.objects.get(pk=gone.pk).state, Backup.MISSING)
self.assertEqual(Backup.objects.get(pk=whole.pk).state, Backup.READY)
self.assertIn("vm1", result["warning"][0]["values"]["backups"])
self.assertIsNotNone(BackupTarget.objects.get(pk=self.target.pk).checked_at)
Operation.objects.all().delete()
self.run_check([*present, f"{gone.prefix}-manifest.json"])
self.assertEqual(Backup.objects.get(pk=gone.pk).state, Backup.READY)
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")
with patch("vmbackups.jobs._target_pool", side_effect=OperationError("No compute reaches %(t)s", t="nfs1")):
with self.assertRaises(OperationError):
CheckTarget().run(op, Context(op, SimpleNamespace(identity=WORKER)))
self.assertEqual(Backup.objects.get(pk=backup.pk).state, Backup.READY)
def test_the_pass_runs_from_the_worker(self):
self.assertIn(schedule.run_schedules, jobs.PERIODIC)