1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 17:36:05 +00:00
webvirtcloud/vmbackups/models.py
catborise c5a04e040d fix(vmbackups): a schedule's run keeps how its job ended
The run history showed a run as "Started" once the job history (Job
Retention Days, which may be under 14) dropped its job. A run now takes
its job's end, and the reason it failed, when the job is deleted.

- A job cancelled without an error gives "The job was cancelled" as the
  run's reason on the schedule page.
- The Schedules list's 14-day strip is a link to the schedule, so touch
  and keyboard users reach the details its tooltips hold.
- The marks keep their colours in forced-colors (high contrast) mode.
2026-11-26 14:21:35 +03:00

220 lines
11 KiB
Python

import re
import uuid
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext_noop
from computes.models import Compute, Tag
from instances.models import Instance
from operations.models import Operation
from vrtManager.backup import backup_prefix
JOB_CANCELLED = gettext_noop("The job was cancelled")
class BackupTarget(models.Model):
"""Storage the backups go to: a pool on each compute that sees it."""
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
owners = models.BooleanField(default=False) # VM owners with the backup permission may use it
def __str__(self):
return self.name
def pool_on(self, compute):
return self.pools.filter(compute=compute).first()
class BackupTargetPool(models.Model):
"""The target's pool on one compute; its UUID is checked before each use,
so a pool replaced by another of the same name is refused. A removed
compute takes its pool row with it: the backups stay in the target."""
target = models.ForeignKey(BackupTarget, on_delete=models.CASCADE, related_name="pools")
compute = models.ForeignKey(Compute, on_delete=models.CASCADE)
pool = models.CharField(max_length=128)
pool_uuid = models.CharField(max_length=36)
class Meta:
constraints = [models.UniqueConstraint(fields=["target", "compute"], name="one_pool_per_target_and_compute")]
class BackupPolicy(models.Model):
"""A schedule: its VMs (those chosen, every VM of a compute, or every VM with a tag) 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")
# a tag a schedule backs up is not deleted: the schedule would back up nothing
tag = models.ForeignKey(Tag, on_delete=models.PROTECT, null=True, blank=True, related_name="backup_policies")
time = models.TimeField() # in the panel's time zone
keep = models.PositiveSmallIntegerField()
# also kept: the newest backup of each of the newest N weeks and months that have one (0: none)
keep_weekly = models.PositiveSmallIntegerField(default=0)
keep_monthly = models.PositiveSmallIntegerField(default=0)
full_every = models.PositiveSmallIntegerField(default=1) # a full backup every N; the others incremental
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 or a tag'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")
if self.tag_id:
return Instance.objects.filter(tags=self.tag_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, SUCCEEDED = "submitted", "skipped", "failed", "succeeded"
# succeeded and failed also once its job has ended and the job history drops the job (keep_job_end)
STATES = [(SUBMITTED, "submitted"), (SKIPPED, "skipped"), (FAILED, "failed"), (SUCCEEDED, "succeeded")]
RUNNING = "running" # what came of it, its job's end included (outcome)
OUTCOMES = {SUCCEEDED: _("Backed up"), RUNNING: _("Running"), FAILED: _("Failed"), SKIPPED: _("Skipped")}
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.JSONField(default=list) # messages (operations.utils.say), shown in the reader's language
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.UniqueConstraint(fields=["policy", "instance", "day"], name="one_run_per_day")]
@classmethod
def outcome_of(cls, state, job_state):
"""Its state; a submitted run's as its job goes."""
if state != cls.SUBMITTED:
return state
if job_state == Operation.SUCCEEDED:
return cls.SUCCEEDED
return cls.RUNNING if job_state in Operation.ACTIVE else cls.FAILED
@property
def outcome(self):
return self.outcome_of(self.state, self.operation.state if self.operation_id else None)
@property
def outcome_label(self):
return self.OUTCOMES[self.outcome]
@property
def reason(self):
"""Why it did not back up: its note, else its job's error."""
if self.note or not self.operation_id:
return self.note
if self.operation.state == Operation.CANCELLED and not self.operation.error:
from operations.utils import say # operations.utils imports the models
return say(JOB_CANCELLED)
return self.operation.error
@classmethod
def keep_job_end(cls, job):
"""Its runs keep what the job came to, which is gone with the job."""
for run in cls.objects.filter(operation=job, state=cls.SUBMITTED).select_related("operation"):
run.state = cls.SUCCEEDED if job.state == Operation.SUCCEEDED else cls.FAILED
run.note = run.reason
run.save(update_fields=["state", "note"])
UUID_IN_NAME = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
class Backup(models.Model):
CREATING, READY, FAILED, DELETING, MISSING = "creating", "ready", "failed", "deleting", "missing"
STATES = [(CREATING, "creating"), (READY, "ready"), (FAILED, "failed"), (DELETING, "deleting"), (MISSING, "missing")]
LIVING = (CREATING, READY, MISSING, DELETING) # its files are or will be in the target
OFFLINE, FROZEN, CRASH = "offline", "frozen", "crash"
CONSISTENCIES = [(OFFLINE, "offline"), (FROZEN, "frozen"), (CRASH, "crash-consistent")]
uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
target = models.ForeignKey(BackupTarget, on_delete=models.PROTECT, related_name="backups")
instance = models.ForeignKey(Instance, on_delete=models.SET_NULL, null=True, related_name="backups")
# kept when the VM row is gone
vm_uuid = models.CharField(max_length=36)
vm_name = models.CharField(max_length=255)
compute_name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
finished_at = models.DateTimeField(null=True)
state = models.CharField(max_length=16, choices=STATES, default=CREATING)
consistency = models.CharField(max_length=16, choices=CONSISTENCIES, blank=True)
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")
# an incremental backup's base; its disk files have the parent's as backing files
parent = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, related_name="children")
checkpoint = models.CharField(max_length=64, blank=True) # the VM's checkpoint made with it
# whose job made it: a VM owner's own backups count in their backup quota
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name="+")
prefix = models.CharField(max_length=128) # every file of the backup in the target begins with it and "-"
# its last verification (backup.verify) that read the files: when, and what it found wrong with them or
# with those of the backups it builds on (messages, operations.utils.say); empty: nothing
verified_at = models.DateTimeField(null=True)
damage = models.JSONField(default=list)
class Meta:
ordering = ["-created_at"]
@property
def being_made(self):
"""Its job still runs. One that ended uncertain (its host unreachable) leaves the row creating: it is
deleted like a failed one."""
return self.state == self.CREATING and self.operation_id is not None and self.operation.state in Operation.ACTIVE
def damaged_in_chain(self):
"""It, or the first backup it builds on, that a verification found damaged; None."""
backup, seen = self, set()
while backup is not None and not backup.damage and backup.pk not in seen: # a broken chain may loop
seen.add(backup.pk)
backup = backup.parent
return backup if backup is not None and backup.damage else None
def depended_on(self):
"""Whether a backup builds on this one: a failed one holds nothing."""
return self.children.filter(state__in=self.LIVING).exists()
def owns(self, name):
"""Whether the target's file name is one of this backup's: its prefix, then no other backup's UUID (a
VM may be named "<this prefix>-x", and its backups' files begin with this prefix too)."""
return name.startswith(self.prefix + "-") and not UUID_IN_NAME.search(name, len(self.prefix))
def save(self, *args, **kwargs):
if not self.prefix:
self.prefix = backup_prefix(self.vm_name, self.uuid)
super().save(*args, **kwargs)
class BackupFile(models.Model):
DISK, NVRAM, TPM, DOMAIN, MANIFEST = "disk", "nvram", "tpm", "domain", "manifest"
ROLES = [(DISK, "disk"), (NVRAM, "nvram"), (TPM, "tpm"), (DOMAIN, "domain"), (MANIFEST, "manifest")]
backup = models.ForeignKey(Backup, on_delete=models.CASCADE, related_name="files")
role = models.CharField(max_length=16, choices=ROLES)
dev = models.CharField(max_length=32, blank=True) # a disk's target, a TPM state file's name
volume = models.CharField(max_length=255)
format = models.CharField(max_length=16, blank=True)
capacity = models.BigIntegerField(default=0)
size = models.BigIntegerField(default=0)
sha256 = models.CharField(max_length=64, blank=True)