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

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.
This commit is contained in:
catborise 2026-11-25 09:26:01 +03:00
parent f2b6be5fa8
commit c5a04e040d
15 changed files with 108 additions and 50 deletions

Binary file not shown.

View file

@ -13298,11 +13298,6 @@ msgstr "Yedeklendi"
msgid "Running"
msgstr "Çalışıyor"
#: vmbackups/models.py:88
msgctxt "backup run"
msgid "Started"
msgstr "Başlatıldı"
#: vmbackups/templates/vmbackups/policies.html:17
#: vmbackups/templates/vmbackups/policy.html:13
#, python-format
@ -13342,11 +13337,6 @@ msgstr "%(n)s yedeklendi"
msgid "%(n)s running"
msgstr "%(n)s çalışıyor"
#: vmbackups/views.py:360
#, python-format
msgid "%(n)s started"
msgstr "%(n)s başlatıldı"
#: vmbackups/views.py:360
#, python-format
msgid "%(n)s failed"
@ -13356,3 +13346,7 @@ msgstr "%(n)s başarısız"
#, python-format
msgid "%(n)s skipped"
msgstr "%(n)s atlandı"
#: vmbackups/models.py:15
msgid "The job was cancelled"
msgstr "İş iptal edildi"

Binary file not shown.

View file

@ -11375,11 +11375,6 @@ msgstr "Резервну копію створено"
msgid "Running"
msgstr "Виконується"
#: vmbackups/models.py:88
msgctxt "backup run"
msgid "Started"
msgstr "Розпочато"
#: vmbackups/models.py:89 vmbackups/templates/vmbackups/policy.html:38
msgid "Skipped"
msgstr "Пропущено"
@ -11987,11 +11982,6 @@ msgstr "Створено резервних копій: %(n)s"
msgid "%(n)s running"
msgstr "Виконується: %(n)s"
#: vmbackups/views.py:360
#, python-format
msgid "%(n)s started"
msgstr "Запущено: %(n)s"
#: vmbackups/views.py:360
#, python-format
msgid "%(n)s failed"
@ -13448,3 +13438,7 @@ msgstr "Локальний хост"
#: webvirtcloud/settings.py:351
msgid "All interfaces"
msgstr "Усі інтерфейси"
#: vmbackups/models.py:15
msgid "The job was cancelled"
msgstr "Завдання скасовано"

Binary file not shown.

View file

@ -12431,11 +12431,6 @@ msgstr "已备份"
msgid "Running"
msgstr "运行中"
#: vmbackups/models.py:88
msgctxt "backup run"
msgid "Started"
msgstr "已开始"
#: vmbackups/templates/vmbackups/policies.html:17
#: vmbackups/templates/vmbackups/policy.html:13
#, python-format
@ -12474,11 +12469,6 @@ msgstr "%(n)s 台已备份"
msgid "%(n)s running"
msgstr "%(n)s 台运行中"
#: vmbackups/views.py:360
#, python-format
msgid "%(n)s started"
msgstr "%(n)s 台已开始"
#: vmbackups/views.py:360
#, python-format
msgid "%(n)s failed"
@ -12488,3 +12478,7 @@ msgstr "%(n)s 台失败"
#, python-format
msgid "%(n)s skipped"
msgstr "%(n)s 台已跳过"
#: vmbackups/models.py:15
msgid "The job was cancelled"
msgstr "作业已取消"

View file

@ -378,5 +378,7 @@ td .tag-more {
.run-failed::after { content: "\00d7"; color: #fff; font-size: .75rem; font-weight: 700; line-height: 1; }
.run-days .run-failed::after { font-size: .625rem; }
.run-skipped { border-color: var(--bs-secondary-color); }
.run-running, .run-started { border-color: var(--bs-info); background: linear-gradient(90deg, var(--bs-info) 50%, transparent 50%); }
.run-running { border-color: var(--bs-info); background: linear-gradient(90deg, var(--bs-info) 50%, transparent 50%); }
.run-none { background: var(--bs-secondary-bg); }
/* high contrast themes would drop the marks' colours, which carry their meaning */
@media (forced-colors: active) { .run-mark { forced-color-adjust: none; } }

View file

@ -1,6 +1,17 @@
from django.apps import AppConfig
from django.db.models.signals import pre_delete
def keep_job_end(sender, instance, **kwargs):
from .models import BackupRun
BackupRun.keep_job_end(instance)
class VmbackupsConfig(AppConfig):
name = "vmbackups"
verbose_name = "Backups"
def ready(self):
# the job history drops ended jobs (operations.worker.housekeeping); a schedule's run keeps how its job went
pre_delete.connect(keep_job_end, sender="operations.Operation")

View file

@ -0,0 +1,18 @@
# Generated by Django 5.2.18 on 2026-11-25 06:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vmbackups', '0010_keep_weekly_monthly'),
]
operations = [
migrations.AlterField(
model_name='backuprun',
name='state',
field=models.CharField(choices=[('submitted', 'submitted'), ('skipped', 'skipped'), ('failed', 'failed'), ('succeeded', 'succeeded')], max_length=16),
),
]

View file

@ -4,7 +4,7 @@ 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 pgettext_lazy
from django.utils.translation import gettext_noop
from computes.models import Compute, Tag
from instances.models import Instance
@ -12,6 +12,9 @@ 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."""
@ -81,12 +84,11 @@ class BackupPolicy(models.Model):
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")]
# what came of it, its job's end included (outcome)
SUCCEEDED, RUNNING, STARTED = "succeeded", "running", "started"
OUTCOMES = {SUCCEEDED: _("Backed up"), RUNNING: _("Running"), STARTED: pgettext_lazy("backup run", "Started"), FAILED: _("Failed"),
SKIPPED: _("Skipped")}
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")
@ -101,11 +103,9 @@ class BackupRun(models.Model):
@classmethod
def outcome_of(cls, state, job_state):
"""Skipped or failed; else as its job went, or started once the job is gone from the job history (None)."""
"""Its state; a submitted run's as its job goes."""
if state != cls.SUBMITTED:
return state
if job_state is None:
return cls.STARTED
if job_state == Operation.SUCCEEDED:
return cls.SUCCEEDED
return cls.RUNNING if job_state in Operation.ACTIVE else cls.FAILED
@ -118,6 +118,25 @@ class BackupRun(models.Model):
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}")

View file

@ -21,7 +21,7 @@
{% for policy in policies %}
<tr>
<td class="text-nowrap"><a href="{% url 'vmbackups:policy' policy.id %}">{{ policy.name }}</a></td>
<td class="text-nowrap"><span class="run-days">{% for day in policy.history %}<span class="run-mark run-{{ day.outcome|default:"none" }}" role="img" title="{{ day.day|date:"Y-m-d" }}: {{ day.text|default:_("no run") }}" aria-label="{{ day.day|date:"Y-m-d" }}: {{ day.text|default:_("no run") }}"></span>{% endfor %}</span></td>
<td class="text-nowrap"><a class="run-days" href="{% url 'vmbackups:policy' policy.id %}">{% for day in policy.history %}<span class="run-mark run-{{ day.outcome|default:"none" }}" role="img" title="{{ day.day|date:"Y-m-d" }}: {{ day.text|default:_("no run") }}" aria-label="{{ day.day|date:"Y-m-d" }}: {{ day.text|default:_("no run") }}"></span>{% endfor %}</a></td>
<td>{% if policy.compute %}{% blocktrans with compute=policy.compute.name %}Every VM of {{ compute }}{% endblocktrans %}{% elif policy.tag %}{% blocktrans with tag=policy.tag.name %}VMs tagged {{ tag }}{% endblocktrans %}{% else %}{% blocktrans count counter=policy.vm_count %}{{ counter }} VM{% plural %}{{ counter }} VMs{% endblocktrans %}{% endif %}</td>
<td>{{ policy.target.name }}</td>
<td>{{ policy.time|time:"H:i" }}</td>

View file

@ -51,7 +51,7 @@
<span class="run-mark run-{{ run.outcome }}" aria-hidden="true"></span>
<span class="text-nowrap">{{ run.day|date:"Y-m-d" }}</span>
<a href="{% url 'instances:instance' run.instance_id %}">{{ run.instance.name }}</a>
<span class="text-body-secondary">{{ run.outcome_label }}{% if run.note %}: {{ run.note|words }}{% elif run.operation.error %}: {{ run.operation.error|words }}{% endif %}</span>
<span class="text-body-secondary">{{ run.outcome_label }}{% if run.reason %}: {{ run.reason|words }}{% endif %}</span>
{% if run.operation_id %}<a class="ms-1" href="{% url 'operations:job' run.operation_id %}">{% trans "Job" %}</a>{% endif %}
</li>
{% endfor %}

View file

@ -152,15 +152,17 @@ class PolicyPageTests(TestCase):
self.add_run(policy, self.vm1, 1, job_state=Operation.SUCCEEDED)
self.add_run(policy, self.vm3, 1, job_state=Operation.FAILED)
self.add_run(policy, self.vm1, 0, job_state=Operation.RUNNING)
self.add_run(policy, self.vm3, 0) # its job gone from the job history
self.add_run(policy, self.vm3, 0, job_state=Operation.SUCCEEDED)
page = lxml_html.fromstring(self.client.get(reverse("vmbackups:policies")).content)
marks = page.xpath("//span[contains(@class, 'run-days')]/span")
strip = page.xpath("//a[contains(@class, 'run-days')]") # one link to the schedule, for touch and keyboard
self.assertEqual(strip[0].get("href"), reverse("vmbackups:policy", args=[policy.pk]))
marks = strip[0].xpath("./span")
self.assertEqual(len(marks), 14)
yesterday = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
self.assertEqual((marks[-2].get("class"), marks[-2].get("title")),
("run-mark run-failed", f"{yesterday}: 1 failed, 1 backed up"))
self.assertEqual(marks[-1].get("class"), "run-mark run-running")
self.assertTrue(marks[-1].get("title").endswith(": 1 running, 1 started"))
self.assertTrue(marks[-1].get("title").endswith(": 1 running, 1 backed up"))
self.assertEqual(marks[0].get("class"), "run-mark run-none")
def test_delete_keeps_the_backups(self):

View file

@ -38,7 +38,32 @@ class PolicyModelTests(TestCase):
self.assertEqual(outcome(BackupRun.SUBMITTED, Operation.RUNNING), BackupRun.RUNNING)
for job_state in (Operation.FAILED, Operation.CANCELLED, Operation.UNCERTAIN): # no backup came of it
self.assertEqual(outcome(BackupRun.SUBMITTED, job_state), BackupRun.FAILED)
self.assertEqual(outcome(BackupRun.SUBMITTED), BackupRun.STARTED) # its job is gone from the job history
def test_a_run_keeps_what_its_job_came_to_when_the_job_history_drops_the_job(self):
from django.utils import timezone
from operations.utils import say
from operations.worker import housekeeping
old = timezone.now() - datetime.timedelta(days=400)
runs = {}
for n, (job_state, error) in enumerate([(Operation.SUCCEEDED, []), (Operation.FAILED, say("Disk %(d)s gone", d="vda")),
(Operation.CANCELLED, [])]):
job = Operation.objects.create(kind="backup.create", username="pm_admin", submission_key=str(n), resource="r",
state=job_state, error=error, finished_at=old)
vm = Instance.objects.create(compute=self.compute, name=f"k{n}", uuid=f"61616161-0000-4000-8000-00000000010{n}")
runs[job_state] = BackupRun.objects.create(policy=self.policy, instance=vm, day=datetime.date(2026, 11, 17),
state=BackupRun.SUBMITTED, operation=job)
self.assertEqual(runs[Operation.CANCELLED].reason, say("The job was cancelled")) # a job cancelled without an error
housekeeping()
self.assertFalse(Operation.objects.exists())
for run in runs.values():
run.refresh_from_db()
self.assertEqual((runs[Operation.SUCCEEDED].outcome, runs[Operation.SUCCEEDED].note), (BackupRun.SUCCEEDED, []))
self.assertEqual((runs[Operation.FAILED].outcome, runs[Operation.FAILED].reason),
(BackupRun.FAILED, say("Disk %(d)s gone", d="vda")))
self.assertEqual((runs[Operation.CANCELLED].outcome, runs[Operation.CANCELLED].reason),
(BackupRun.FAILED, say("The job was cancelled")))
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",

View file

@ -355,10 +355,9 @@ def restore_disk(request, uuid):
HISTORY_DAYS = 14 # the days a schedule's runs are shown for
# a day of a schedule on the list is marked as the first of these its runs came to
WORST_FIRST = (BackupRun.FAILED, BackupRun.SKIPPED, BackupRun.RUNNING, BackupRun.STARTED, BackupRun.SUCCEEDED)
WORST_FIRST = (BackupRun.FAILED, BackupRun.SKIPPED, BackupRun.RUNNING, BackupRun.SUCCEEDED)
DAY_COUNTS = {BackupRun.SUCCEEDED: _("%(n)s backed up"), BackupRun.RUNNING: _("%(n)s running"),
BackupRun.STARTED: _("%(n)s started"), BackupRun.FAILED: _("%(n)s failed"),
BackupRun.SKIPPED: _("%(n)s skipped")}
BackupRun.FAILED: _("%(n)s failed"), BackupRun.SKIPPED: _("%(n)s skipped")}
def history_days():