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

feat(vmbackups): backup schedules' records; the worker runs the apps' periodic tasks

A backup schedule (BackupPolicy) names its VMs, chosen or every VM of a
compute at the time it runs (templates left out), a target, a daily time
in the panel's time zone, how many backups of each VM to keep (one at
least), whether frozen file systems are required, and the superuser its
jobs run as. A run (BackupRun) records one VM's backup of one day, keyed
by the VM's row, not its UUID, which two VM rows may share. A backup
keeps the schedule that made it; deleting the schedule keeps its
backups. A backup whose files are gone can be marked missing, and a
target keeps when it was last checked.

The worker runs the tasks apps register with register_periodic about
once a minute, on a thread of their own, one pass at a time, each
guarded: a pass stuck on a host takes no thread recovery or a cancel
needs, and one failing task stops none of the others. Nothing registers
one yet.

backup.create takes the schedule that asked for it; one deleted while
the job was queued leaves the backup without a schedule.
This commit is contained in:
catborise 2026-11-17 10:18:04 +03:00
parent 1123d7e8e5
commit 1219a37cc4
8 changed files with 242 additions and 6 deletions

View file

@ -70,6 +70,16 @@ def register(cls):
return cls
PERIODIC = []
def register_periodic(fn):
"""A task of an app (its jobs.py) that the worker runs about once a
minute, apart from the jobs: one pass of all such tasks at a time."""
PERIODIC.append(fn)
return fn
class Kind:
name = ""
label = ""

View file

@ -74,6 +74,25 @@ class WorkerTestCase(TransactionTestCase):
stuck.set()
self.assertTrue(wait_for(lambda: len(passes) > 1))
def test_the_apps_periodic_tasks_run_one_pass_at_a_time_and_a_failure_stops_none(self):
stuck, calls = threading.Event(), []
def failing():
calls.append("failing")
raise RuntimeError("broken")
def slow():
calls.append("slow")
stuck.wait(10)
with patch("operations.worker.PERIODIC_EVERY", 0), patch("operations.jobs.PERIODIC", [failing, slow]):
self.start()
self.assertTrue(wait_for(lambda: "slow" in calls))
time.sleep(0.5) # ten ticks: the pass still runs
self.assertEqual(calls, ["failing", "slow"])
stuck.set()
self.assertTrue(wait_for(lambda: calls.count("slow") > 1))
def test_a_stuck_host_takes_half_the_slots_and_one_progress_read(self):
fakes.STUCK[1] = threading.Event()
stuck = [self.job(1, n) for n in range(4)]

View file

@ -36,6 +36,7 @@ MAX_SLOTS = 16
PROGRESS_THREADS = 2
CONTROL_THREADS = 4
HOUSEKEEPING_EVERY = 600.0
PERIODIC_EVERY = 60.0 # the apps' periodic tasks (jobs.register_periodic): backup schedules
BACKOFF = (30, 60, 120, 300, 600)
WATCH_EVERY = 15
@ -110,8 +111,11 @@ class Worker:
self.control = ThreadPoolExecutor(CONTROL_THREADS, thread_name_prefix="wvc-control")
self.progress_pool = ThreadPoolExecutor(PROGRESS_THREADS, thread_name_prefix="wvc-progress")
self.recovery = Scheduler(self)
self._last = {"heartbeat": 0.0, "progress": 0.0, "housekeeping": 0.0}
self._last = {"heartbeat": 0.0, "progress": 0.0, "housekeeping": 0.0, "periodic": 0.0}
self.housekeeping = None # the future of the last housekeeping pass
# a thread of their own: a pass stuck on a host takes no thread recovery or a cancel needs
self.periodic_pool = ThreadPoolExecutor(1, thread_name_prefix="wvc-periodic")
self.periodic = None # the future of the last pass
# -- process ------------------------------------------------------------
@ -198,6 +202,10 @@ class Worker:
# one pass at a time: a pass stuck on a host (an upload's cleanup) holds one control thread, not all
if self.housekeeping is None or self.housekeeping.done():
self.housekeeping = self.control.submit(_guarded, housekeeping)
if now - self._last["periodic"] >= PERIODIC_EVERY:
self._last["periodic"] = now
if self.periodic is None or self.periodic.done():
self.periodic = self.periodic_pool.submit(_guarded, periodic)
def _mine(self, pks):
"""This worker's active jobs among pks; used only inside fenced."""
@ -406,6 +414,12 @@ def housekeeping():
logger.error("expiring job %s failed: %s", op.pk, utils.safe_text(err))
def periodic():
"""The apps' periodic tasks, each guarded: one failing stops none of the others."""
for task in list(jobs.PERIODIC):
_guarded(task)
class Scheduler:
def __init__(self, worker):
self.worker = worker

View file

@ -33,7 +33,7 @@ from vrtManager.instance import wvmInstance
from vrtManager.storage import wvmStorage
from vrtManager.instance import LIVE_CLONE_MIN_LIBVIRT
from .models import Backup, BackupFile, BackupTarget
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
@ -189,7 +189,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")}
"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}
def plan(self, user, params):
_superuser(user)
@ -216,8 +218,10 @@ class CreateBackup(Kind):
names = backup_file_names(op.intent["backup"], plan["disks"], bool(plan["nvram"]))
ctx.record_intent(live=live, plan=plan, names=names, pool=row.pool, pool_uuid=row.pool_uuid,
consistency=Backup.OFFLINE if not live else Backup.CRASH)
# a schedule deleted since the job was queued: the backup is kept, without it
policy = BackupPolicy.objects.filter(pk=op.params.get("policy")).first() if op.params.get("policy") else None
Backup.objects.create(uuid=op.intent["backup"], target=target, instance=instance, vm_uuid=instance.uuid,
vm_name=instance.name, compute_name=instance.compute.name, operation=op)
vm_name=instance.name, compute_name=instance.compute.name, operation=op, policy=policy)
ctx.set_phase(_("Copying disks"))
if live:
return self._run_live(op, ctx, proxy, pool, status)

View file

@ -0,0 +1,71 @@
# Generated by Django 5.2.18 on 2026-11-17 07:16
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0011_maintenance_since'),
('instances', '0016_vm_name_length'),
('operations', '0004_parent'),
('vmbackups', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name='backuptarget',
name='checked_at',
field=models.DateTimeField(null=True),
),
migrations.AlterField(
model_name='backup',
name='state',
field=models.CharField(choices=[('creating', 'creating'), ('ready', 'ready'), ('failed', 'failed'), ('deleting', 'deleting'), ('missing', 'missing')], default='creating', max_length=16),
),
migrations.CreateModel(
name='BackupPolicy',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=64, unique=True)),
('time', models.TimeField()),
('keep', models.PositiveSmallIntegerField()),
('frozen', models.BooleanField(default=False)),
('enabled', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('compute', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='computes.compute')),
('instances', models.ManyToManyField(blank=True, related_name='backup_policies', to='instances.instance')),
('owner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('target', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='policies', to='vmbackups.backuptarget')),
],
),
migrations.AddField(
model_name='backup',
name='policy',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='backups', to='vmbackups.backuppolicy'),
),
migrations.CreateModel(
name='BackupRun',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('day', models.DateField()),
('state', models.CharField(choices=[('submitted', 'submitted'), ('skipped', 'skipped'), ('failed', 'failed')], max_length=16)),
('note', models.CharField(blank=True, max_length=255)),
('created_at', models.DateTimeField(auto_now_add=True)),
('instance', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='backup_runs', to='instances.instance')),
('operation', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='operations.operation')),
('policy', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='runs', to='vmbackups.backuppolicy')),
],
),
migrations.AddConstraint(
model_name='backuppolicy',
constraint=models.CheckConstraint(condition=models.Q(('keep__gte', 1)), name='policy_keeps_one'),
),
migrations.AddConstraint(
model_name='backuprun',
constraint=models.UniqueConstraint(fields=('policy', 'instance', 'day'), name='one_run_per_day'),
),
]

View file

@ -1,5 +1,6 @@
import uuid
from django.conf import settings
from django.db import models
from computes.models import Compute
@ -12,6 +13,7 @@ class BackupTarget(models.Model):
name = models.CharField(max_length=64, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
checked_at = models.DateTimeField(null=True) # its last target check that ended
def __str__(self):
return self.name
@ -34,9 +36,56 @@ class BackupTargetPool(models.Model):
constraints = [models.UniqueConstraint(fields=["target", "compute"], name="one_pool_per_target_and_compute")]
class BackupPolicy(models.Model):
"""A schedule: its VMs (those chosen, or every VM of a compute) backed
up into its target once a day at its time, the newest keep of each VM
kept. Its jobs run as its owner, a superuser."""
name = models.CharField(max_length=64, unique=True)
target = models.ForeignKey(BackupTarget, on_delete=models.PROTECT, related_name="policies")
compute = models.ForeignKey(Compute, on_delete=models.CASCADE, null=True, blank=True)
instances = models.ManyToManyField(Instance, blank=True, related_name="backup_policies")
time = models.TimeField() # in the panel's time zone
keep = models.PositiveSmallIntegerField()
frozen = models.BooleanField(default=False)
enabled = models.BooleanField(default=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.CheckConstraint(condition=models.Q(keep__gte=1), name="policy_keeps_one")]
def __str__(self):
return self.name
def vms(self):
"""Its VMs now: a compute's are those it has at this moment, templates left out."""
if self.compute_id:
return Instance.objects.filter(compute_id=self.compute_id, is_template=False).order_by("name")
return self.instances.select_related("compute").order_by("name")
class BackupRun(models.Model):
"""A schedule's backup of one VM on one day: what it submitted, or why not."""
SUBMITTED, SKIPPED, FAILED = "submitted", "skipped", "failed"
STATES = [(SUBMITTED, "submitted"), (SKIPPED, "skipped"), (FAILED, "failed")]
policy = models.ForeignKey(BackupPolicy, on_delete=models.CASCADE, related_name="runs")
instance = models.ForeignKey(Instance, on_delete=models.CASCADE, related_name="backup_runs")
day = models.DateField() # the local day of the schedule's time
state = models.CharField(max_length=16, choices=STATES)
operation = models.ForeignKey(Operation, on_delete=models.SET_NULL, null=True)
note = models.CharField(max_length=255, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.UniqueConstraint(fields=["policy", "instance", "day"], name="one_run_per_day")]
class Backup(models.Model):
CREATING, READY, FAILED, DELETING = "creating", "ready", "failed", "deleting"
STATES = [(CREATING, "creating"), (READY, "ready"), (FAILED, "failed"), (DELETING, "deleting")]
CREATING, READY, FAILED, DELETING, MISSING = "creating", "ready", "failed", "deleting", "missing"
STATES = [(CREATING, "creating"), (READY, "ready"), (FAILED, "failed"), (DELETING, "deleting"), (MISSING, "missing")]
OFFLINE, FROZEN, CRASH = "offline", "frozen", "crash"
CONSISTENCIES = [(OFFLINE, "offline"), (FROZEN, "frozen"), (CRASH, "crash-consistent")]
@ -54,6 +103,7 @@ class Backup(models.Model):
size = models.BigIntegerField(default=0) # bytes in the target
manifest = models.JSONField(default=dict)
operation = models.ForeignKey(Operation, on_delete=models.SET_NULL, null=True)
policy = models.ForeignKey(BackupPolicy, on_delete=models.SET_NULL, null=True, related_name="backups")
class Meta:
ordering = ["-created_at"]

View file

@ -370,6 +370,30 @@ class CreateBackupTests(TransactionTestCase):
op.refresh_from_db()
self.assertEqual(CreateBackup().progress(op), (GIB, GIB))
def test_a_schedules_backup_is_linked_to_it_unless_it_was_deleted(self):
import datetime
from vmbackups.models import BackupPolicy
policy = BackupPolicy.objects.create(name="nightly", target=self.target, time=datetime.time(2), keep=2,
owner=self.admin)
op = jobs.submit("backup.create", self.admin, {"instance": self.vm.pk, "target": self.target.pk,
"policy": policy.pk}, "key-policy-0001")
acquire(WORKER, "wvc-test")
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER)
op.refresh_from_db()
self.run_job(op)
self.assertEqual(self.backup(op).policy, policy)
jobs.finish(op, jobs.Outcome(Operation.SUCCEEDED))
policy_pk = policy.pk
policy.delete() # while the next one is queued
op = jobs.submit("backup.create", self.admin, {"instance": self.vm.pk, "target": self.target.pk,
"policy": policy_pk}, "key-policy-0002")
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER)
op.refresh_from_db()
self.run_job(op)
self.assertIsNone(self.backup(op).policy)
def test_the_log_names_the_target_and_consistency(self):
op = self.submit()
self.run_job(op)

View file

@ -0,0 +1,44 @@
import datetime
from django.contrib.auth import get_user_model
from django.db import IntegrityError
from django.test import TestCase
from computes.models import Compute
from instances.models import Instance
from vmbackups.models import Backup, BackupPolicy, BackupRun, BackupTarget
class PolicyModelTests(TestCase):
def setUp(self):
self.admin = get_user_model().objects.create_superuser("pm_admin", "a@example.com", "pw")
self.compute = Compute.objects.create(name="h1", hostname="192.0.2.61", login="u", password="p", type=1)
self.vm = Instance.objects.create(compute=self.compute, name="vm1", uuid="61616161-0000-4000-8000-000000000001")
self.target = BackupTarget.objects.create(name="nfs1")
self.policy = BackupPolicy.objects.create(name="nightly", target=self.target, time=datetime.time(2, 0), keep=7,
owner=self.admin)
self.policy.instances.add(self.vm)
def test_one_run_per_policy_vm_and_day(self):
BackupRun.objects.create(policy=self.policy, instance=self.vm, day=datetime.date(2026, 11, 17))
with self.assertRaises(IntegrityError):
BackupRun.objects.create(policy=self.policy, instance=self.vm, day=datetime.date(2026, 11, 17))
def test_a_deleted_policy_keeps_its_backups(self):
backup = Backup.objects.create(target=self.target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
compute_name="h1", policy=self.policy, state=Backup.READY)
self.policy.delete()
backup.refresh_from_db()
self.assertIsNone(backup.policy)
def test_the_vms_of_a_policy(self):
Instance.objects.create(compute=self.compute, name="vm2", uuid="61616161-0000-4000-8000-000000000002")
Instance.objects.create(compute=self.compute, name="tpl", uuid="61616161-0000-4000-8000-000000000003",
is_template=True)
self.assertEqual([vm.name for vm in self.policy.vms()], ["vm1"])
whole = BackupPolicy.objects.create(name="host", target=self.target, compute=self.compute, time=datetime.time(3),
keep=3, owner=self.admin)
self.assertEqual([vm.name for vm in whole.vms()], ["vm1", "vm2"]) # the compute's VMs now, no template
def test_missing_state(self):
self.assertIn(Backup.MISSING, dict(Backup.STATES))