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

feat(vmbackups): a schedule shows how its last 14 days of backups went

The Schedules list marks each of the last 14 days by its worst run
(failed, skipped, running, backed up), the day's counts on hover. A
schedule's page opens with a grid of its VMs by day, each mark linking
to its job, and lists the runs that did not back up with their reason;
the settings form follows. A run's outcome now includes how its job
ended: before, every submitted run read "Backup job", a failed one too.
This commit is contained in:
catborise 2026-11-24 13:38:23 +03:00
parent 9809e5b79a
commit ab70ea2a62
11 changed files with 348 additions and 78 deletions

Binary file not shown.

View file

@ -11171,26 +11171,10 @@ msgstr "Bu zamanlama silinsin mi? Yedekleri tutulur."
msgid "Delete schedule"
msgstr "Zamanlamayı sil"
#: vmbackups/templates/vmbackups/policy.html:26
msgid "Runs"
msgstr "Çalışmalar"
#: vmbackups/templates/vmbackups/policy.html:30
msgid "Day"
msgstr "Gün"
#: vmbackups/templates/vmbackups/policy.html:37
msgid "Backup job"
msgstr "Yedekleme işi"
#: vmbackups/templates/vmbackups/policy.html:38
msgid "Skipped"
msgstr "Atlandı"
#: vmbackups/templates/vmbackups/policy.html:48
msgid "No run yet."
msgstr "Henüz çalışma yok."
#: vmbackups/templates/vmbackups/policy_form.html:13
#, python-format
msgid "Time zone: %(time_zone)s"
@ -13305,3 +13289,70 @@ msgstr "sağlandı"
#: accounts/templates/accounts/change_password_form.html:63
msgid "not met"
msgstr "sağlanmadı"
#: vmbackups/models.py:88 vmbackups/templates/vmbackups/policy.html:36
msgid "Backed up"
msgstr "Yedeklendi"
#: vmbackups/models.py:88 vmbackups/templates/vmbackups/policy.html:39
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
msgid "Last day"
msgid_plural "Last %(days)s days"
msgstr[0] "Son gün"
msgstr[1] "Son %(days)s gün"
#: vmbackups/templates/vmbackups/policies.html:24
msgid "no run"
msgstr "çalışma yok"
#: vmbackups/templates/vmbackups/policy.html:26
#, python-format
msgid "%(day)s, %(vm)s: %(outcome)s"
msgstr "%(day)s, %(vm)s: %(outcome)s"
#: vmbackups/templates/vmbackups/policy.html:40
msgid "No run"
msgstr "Çalışma yok"
#: vmbackups/templates/vmbackups/policy.html:43
msgid "The schedule has no VM."
msgstr "Zamanlamada sanal makine yok."
#: vmbackups/templates/vmbackups/policy.html:47
msgid "Not backed up"
msgstr "Yedeklenmedi"
#: vmbackups/views.py:359
#, python-format
msgid "%(n)s backed up"
msgstr "%(n)s yedeklendi"
#: vmbackups/views.py:359
#, python-format
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"
msgstr "%(n)s başarısız"
#: vmbackups/views.py:361
#, python-format
msgid "%(n)s skipped"
msgstr "%(n)s atlandı"

Binary file not shown.

View file

@ -10503,26 +10503,10 @@ msgstr "要删除此计划吗?其备份将保留。"
msgid "Delete schedule"
msgstr "删除计划"
#: vmbackups/templates/vmbackups/policy.html:26
msgid "Runs"
msgstr "运行记录"
#: vmbackups/templates/vmbackups/policy.html:30
msgid "Day"
msgstr "日期"
#: vmbackups/templates/vmbackups/policy.html:37
msgid "Backup job"
msgstr "备份作业"
#: vmbackups/templates/vmbackups/policy.html:38
msgid "Skipped"
msgstr "已跳过"
#: vmbackups/templates/vmbackups/policy.html:48
msgid "No run yet."
msgstr "还没有运行记录。"
#: vmbackups/templates/vmbackups/policy_form.html:13
#, python-format
msgid "Time zone: %(time_zone)s"
@ -12438,3 +12422,69 @@ msgstr "已满足"
#: accounts/templates/accounts/change_password_form.html:63
msgid "not met"
msgstr "未满足"
#: vmbackups/models.py:88 vmbackups/templates/vmbackups/policy.html:36
msgid "Backed up"
msgstr "已备份"
#: vmbackups/models.py:88 vmbackups/templates/vmbackups/policy.html:39
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
msgid "Last day"
msgid_plural "Last %(days)s days"
msgstr[0] "最近 %(days)s 天"
#: vmbackups/templates/vmbackups/policies.html:24
msgid "no run"
msgstr "未运行"
#: vmbackups/templates/vmbackups/policy.html:26
#, python-format
msgid "%(day)s, %(vm)s: %(outcome)s"
msgstr "%(day)s,%(vm)s:%(outcome)s"
#: vmbackups/templates/vmbackups/policy.html:40
msgid "No run"
msgstr "未运行"
#: vmbackups/templates/vmbackups/policy.html:43
msgid "The schedule has no VM."
msgstr "该计划没有虚拟机。"
#: vmbackups/templates/vmbackups/policy.html:47
msgid "Not backed up"
msgstr "未备份"
#: vmbackups/views.py:359
#, python-format
msgid "%(n)s backed up"
msgstr "%(n)s 台已备份"
#: vmbackups/views.py:359
#, python-format
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"
msgstr "%(n)s 台失败"
#: vmbackups/views.py:361
#, python-format
msgid "%(n)s skipped"
msgstr "%(n)s 台已跳过"

View file

@ -353,3 +353,30 @@ td .tag-more {
#main {
scroll-margin-top: 5rem;
}
/* a backup schedule's runs, a mark a day: filled backed up, crossed failed, hollow skipped, half running */
.run-days { display: inline-flex; gap: 2px; }
.run-mark {
display: inline-flex;
align-items: center;
justify-content: center;
width: .75rem;
height: .75rem;
border: 2px solid transparent;
border-radius: 3px;
vertical-align: middle;
text-decoration: none;
}
.run-grid .run-mark { width: 1.125rem; height: 1.125rem; }
.run-grid td, .run-grid th { padding: 2px; }
.run-grid-vm { max-width: 14rem; padding-right: .75rem !important; position: sticky; left: 0; background: var(--bs-body-bg); }
/* the grid scrolls on a phone starting at its newest day, at the right */
.run-grid-scroll { overflow-x: auto; direction: rtl; width: fit-content; max-width: 100%; }
.run-grid-scroll > table { direction: ltr; }
.run-succeeded { background: var(--bs-success); }
.run-failed { background: var(--bs-danger); }
.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-none { background: var(--bs-secondary-bg); }

View file

@ -3,6 +3,8 @@ 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 computes.models import Compute, Tag
from instances.models import Instance
@ -81,6 +83,10 @@ class BackupRun(models.Model):
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")}
policy = models.ForeignKey(BackupPolicy, on_delete=models.CASCADE, related_name="runs")
instance = models.ForeignKey(Instance, on_delete=models.CASCADE, related_name="backup_runs")
@ -93,6 +99,25 @@ class BackupRun(models.Model):
class Meta:
constraints = [models.UniqueConstraint(fields=["policy", "instance", "day"], name="one_run_per_day")]
@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)."""
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
@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]
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

@ -14,13 +14,14 @@
<div class="table-responsive mb-4">
<table class="table table-hover align-middle">
<thead>
<tr><th>{% trans "Name" %}</th><th>{% trans "VMs" %}</th><th>{% trans "Target" %}</th><th>{% trans "Daily at" %}</th>
<tr><th>{% trans "Name" %}</th><th>{% blocktrans count days=days|length %}Last day{% plural %}Last {{ days }} days{% endblocktrans %}</th><th>{% trans "VMs" %}</th><th>{% trans "Target" %}</th><th>{% trans "Daily at" %}</th>
<th class="text-end">{% trans "Backups kept" %}</th><th>{% trans "Full backup" %}</th><th>{% trans "State" %}</th></tr>
</thead>
<tbody>
{% for policy in policies %}
<tr>
<td><a href="{% url 'vmbackups:policy' policy.id %}">{{ policy.name }}</a></td>
<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>{% 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

@ -10,45 +10,64 @@
{% block page_heading %}<a href="{% url 'vmbackups:policies' %}">{% trans "Schedules" %}</a> / {{ policy.name }}{% endblock page_heading %}
{% block content %}
<p class="text-body-secondary">{% blocktrans with owner=policy.owner.username|default:"–" %}Its jobs run as {{ owner }}, who saved it last.{% endblocktrans %}</p>
<div class="row g-4">
<div class="col-lg-6">
<div class="card">
<div class="card-body">{% include "vmbackups/policy_form.html" %}</div>
</div>
<form method="post" class="mt-3">
{% csrf_token %}
<button type="submit" name="delete" value="1" class="btn btn-outline-danger"
data-confirm="{% trans "Delete this schedule? Its backups are kept." %}">{% bs_icon 'trash' %} {% trans "Delete schedule" %}</button>
</form>
</div>
<div class="col-lg-6">
<h2 class="h6">{% trans "Runs" %}</h2>
{% if runs %}
<div class="table-responsive">
<table class="table table-sm align-middle">
<thead><tr><th>{% trans "Day" %}</th><th>{% trans "VM" %}</th><th>{% trans "Result" %}</th></tr></thead>
<tbody>
{% for run in runs %}
<tr>
<td class="text-nowrap">{{ run.day|date:"Y-m-d" }}</td>
<td><a href="{% url 'instances:instance' run.instance_id %}">{{ run.instance.name }}</a></td>
<td>
{% if run.state == "submitted" %}{% if run.operation_id %}<a href="{% url 'operations:job' run.operation_id %}">{% trans "Backup job" %}</a>{% else %}{% trans "Started" %}{% endif %}
{% elif run.state == "skipped" %}<span class="badge text-bg-secondary">{% trans "Skipped" %}</span>
{% else %}<span class="badge text-bg-danger">{% trans "Failed" %}</span>{% endif %}
{% if run.note %}<div class="small text-body-secondary">{{ run.note|words }}</div>{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="text-body-secondary">{% trans "No run yet." %}</p>
{% endif %}
</div>
<h2 class="h5">{% blocktrans count days=days|length %}Last day{% plural %}Last {{ days }} days{% endblocktrans %}</h2>
{% if grid %}
<div class="run-grid-scroll mb-2">
<table class="align-middle run-grid">
<thead>
<tr><th scope="col" class="run-grid-vm"><span class="visually-hidden">{% trans "VM" %}</span></th>
{% for day in days %}<th scope="col" class="text-center fw-normal small text-body-secondary{% if forloop.last %} fw-semibold text-body{% endif %}" title="{{ day|date:"Y-m-d" }}">{{ day|date:"j" }}</th>{% endfor %}</tr>
</thead>
<tbody>
{% for vm, runs in grid %}
<tr>
<th scope="row" class="fw-normal text-truncate run-grid-vm"><a href="{% url 'instances:instance' vm.id %}">{{ vm.name }}</a></th>
{% for run in runs %}<td class="text-center">
{% if run %}{% blocktrans asvar mark with day=run.day|date:"Y-m-d" vm=vm.name outcome=run.outcome_label %}{{ day }}, {{ vm }}: {{ outcome }}{% endblocktrans %}
{% if run.operation_id %}<a class="run-mark run-{{ run.outcome }}" href="{% url 'operations:job' run.operation_id %}" title="{{ mark }}" aria-label="{{ mark }}"></a>
{% else %}<span class="run-mark run-{{ run.outcome }}" role="img" title="{{ mark }}" aria-label="{{ mark }}"></span>{% endif %}
{% else %}<span class="run-mark run-none" aria-hidden="true"></span>{% endif %}</td>{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
<p class="small text-body-secondary d-flex flex-wrap gap-3">
<span><span class="run-mark run-succeeded"></span> {% trans "Backed up" %}</span>
<span><span class="run-mark run-failed"></span> {% trans "Failed" %}</span>
<span><span class="run-mark run-skipped"></span> {% trans "Skipped" %}</span>
<span><span class="run-mark run-running"></span> {% trans "Running" %}</span>
<span><span class="run-mark run-none"></span> {% trans "No run" %}</span>
</p>
{% else %}
<p class="text-body-secondary">{% trans "The schedule has no VM." %}</p>
{% endif %}
{% if problems %}
<h2 class="h5 mt-4">{% trans "Not backed up" %}</h2>
<ul class="list-unstyled" id="run-problems">
{% for run in problems %}
<li class="py-2 border-bottom">
<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>
{% if run.operation_id %}<a class="ms-1" href="{% url 'operations:job' run.operation_id %}">{% trans "Job" %}</a>{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
<h2 class="h5 mt-4">{% trans "Settings" %}</h2>
<p class="text-body-secondary">{% blocktrans with owner=policy.owner.username|default:"–" %}Its jobs run as {{ owner }}, who saved it last.{% endblocktrans %}</p>
<div class="card" style="max-width: 48rem;">
<div class="card-body">{% include "vmbackups/policy_form.html" %}</div>
</div>
<form method="post" class="mt-3">
{% csrf_token %}
<button type="submit" name="delete" value="1" class="btn btn-outline-danger"
data-confirm="{% trans "Delete this schedule? Its backups are kept." %}">{% bs_icon 'trash' %} {% trans "Delete schedule" %}</button>
</form>
{% endblock %}
{% block script %}
<script src="{% static 'js/tom-select.complete.min.js' %}"></script>

View file

@ -12,6 +12,7 @@ from computes.models import Compute, Tag
from instances.models import Instance
from instances.tests.test_page_controls import PageControls
from logs.models import Logs
from operations.models import Operation
from operations.utils import say
from vmbackups.models import Backup, BackupPolicy, BackupRun, BackupTarget, BackupTargetPool
@ -119,6 +120,49 @@ class PolicyPageTests(TestCase):
self.assertContains(page, "Backup schedule nightly is saved.")
self.assertContains(page, "3 + 4 weekly + 6 monthly")
def add_run(self, policy, vm, days_ago, state=BackupRun.SUBMITTED, job_state=None, note=(), job_error=()):
day = datetime.date.today() - datetime.timedelta(days=days_ago)
job = job_state and Operation.objects.create(kind="backup.create", username="pp_admin", submission_key=f"{vm.pk}-{day}",
resource="r", state=job_state, error=list(job_error))
return BackupRun.objects.create(policy=policy, instance=vm, day=day, state=state, operation=job, note=list(note))
def test_the_runs_of_the_last_14_days(self):
policy = self.schedule()
self.add_run(policy, self.vm1, 0, job_state=Operation.SUCCEEDED)
failed = self.add_run(policy, self.vm1, 1, job_state=Operation.FAILED, job_error=say("The guest agent did not answer"))
self.add_run(policy, self.vm1, 2, BackupRun.SKIPPED, note=say("The host was in maintenance"))
self.add_run(policy, self.vm1, 14, BackupRun.FAILED) # before the 14 days
self.add_run(policy, self.vm1, -1, BackupRun.FAILED) # after them: the time zone moved west
self.add_run(policy, self.vm3, 3, job_state=Operation.SUCCEEDED) # a VM the schedule no longer backs up
page = lxml_html.fromstring(self.client.get(reverse("vmbackups:policy", args=[policy.pk])).content)
rows = page.xpath("//table[contains(@class, 'run-grid')]/tbody/tr")
self.assertEqual([row.xpath("string(th)") for row in rows], ["vm1", "vm3"])
marks = [mark.get("class").split()[1] for mark in rows[0].xpath(".//*[contains(@class, 'run-mark')]")]
self.assertEqual(marks, ["run-none"] * 11 + ["run-skipped", "run-failed", "run-succeeded"])
self.assertEqual(rows[0].xpath(".//a[contains(@class, 'run-failed')]/@href"),
[reverse("operations:job", args=[failed.operation_id])])
problems = [" ".join(item.text_content().split()) for item in page.xpath("//ul[@id='run-problems']/li")]
self.assertEqual(len(problems), 2)
self.assertIn("vm1 Failed: The guest agent did not answer", problems[0])
self.assertIn("vm1 Skipped: The host was in maintenance", problems[1])
def test_the_list_marks_a_day_by_its_worst_run(self):
policy = self.schedule()
policy.instances.add(self.vm3)
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
page = lxml_html.fromstring(self.client.get(reverse("vmbackups:policies")).content)
marks = page.xpath("//span[contains(@class, 'run-days')]/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.assertEqual(marks[0].get("class"), "run-mark run-none")
def test_delete_keeps_the_backups(self):
policy = self.schedule()
backup = Backup.objects.create(target=self.target, instance=self.vm1, vm_uuid=self.vm1.uuid, vm_name="vm1",

View file

@ -6,6 +6,7 @@ from django.test import TestCase
from computes.models import Compute
from instances.models import Instance
from operations.models import Operation
from vmbackups.models import Backup, BackupPolicy, BackupRun, BackupTarget
@ -24,6 +25,21 @@ class PolicyModelTests(TestCase):
with self.assertRaises(IntegrityError):
BackupRun.objects.create(policy=self.policy, instance=self.vm, day=datetime.date(2026, 11, 17))
def test_a_run_comes_to_what_its_job_did(self):
def outcome(state, job_state=None):
job = job_state and Operation.objects.create(kind="backup.create", username="pm_admin", submission_key=job_state,
resource="r", state=job_state)
return BackupRun(policy=self.policy, instance=self.vm, state=state, operation=job).outcome
self.assertEqual(outcome(BackupRun.SKIPPED), BackupRun.SKIPPED)
self.assertEqual(outcome(BackupRun.FAILED), BackupRun.FAILED)
self.assertEqual(outcome(BackupRun.SUBMITTED, Operation.SUCCEEDED), BackupRun.SUCCEEDED)
self.assertEqual(outcome(BackupRun.SUBMITTED, Operation.QUEUED), BackupRun.RUNNING)
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_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)

View file

@ -1,3 +1,5 @@
import datetime
from collections import Counter
from urllib.parse import urlencode
from django.contrib import messages
@ -33,7 +35,7 @@ from vrtManager.util import OperationError
from .forms import PolicyForm, RestoreDiskForm, RestoreForm, TargetForm, TargetPoolForm
from .jobs import _over_names, _over_plan, _proxy, _vm_pool
from .models import Backup, BackupPolicy, BackupTarget
from .models import Backup, BackupPolicy, BackupRun, BackupTarget
from .utils import inside_vm_pool, pending_deletes
@ -351,11 +353,39 @@ def restore_disk(request, uuid):
return render(request, "vmbackups/restore_disk.html", {"backup": backup, "form": form})
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)
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")}
def history_days():
"""The local days of the run history, the oldest first."""
today = timezone.localdate()
return [today - datetime.timedelta(days=n) for n in range(HISTORY_DAYS - 1, -1, -1)]
@superuser_only
def policies(request):
"""The backup schedules."""
"""The backup schedules, each with what its runs of each day came to."""
days = history_days()
counts = {} # (schedule id, day) -> Counter of outcomes
runs = (BackupRun.objects.filter(day__range=(days[0], days[-1])).order_by()
.values_list("policy_id", "day", "state", "operation__state").annotate(n=Count("id")))
for policy_id, day, state, job_state, n in runs:
counts.setdefault((policy_id, day), Counter())[BackupRun.outcome_of(state, job_state)] += n
rows = BackupPolicy.objects.select_related("target", "compute", "tag", "owner").annotate(vm_count=Count("instances"))
return render(request, "vmbackups/policies.html", {"policies": rows.order_by("name")})
rows = list(rows.order_by("name"))
for policy in rows:
policy.history = []
for day in days:
day_counts = counts.get((policy.pk, day), Counter())
worst = next((outcome for outcome in WORST_FIRST if day_counts[outcome]), None)
text = ", ".join(str(DAY_COUNTS[o] % {"n": day_counts[o]}) for o in WORST_FIRST if day_counts[o])
policy.history.append({"day": day, "outcome": worst, "text": text})
return render(request, "vmbackups/policies.html", {"policies": rows, "days": days})
@superuser_only
@ -391,6 +421,13 @@ def policy(request, policy_id):
form.save_m2m()
messages.success(request, _("Backup schedule %(name)s is saved.") % {"name": policy.name})
return redirect("vmbackups:policies")
runs = policy.runs.select_related("instance", "operation").order_by("-day", "instance__name")[:200]
return render(request, "vmbackups/policy.html", {"policy": policy, "form": form, "runs": runs,
"time_zone": settings.TIME_ZONE})
days = history_days()
runs = list(policy.runs.filter(day__range=(days[0], days[-1])).select_related("instance", "operation"))
cells = {vm: {} for vm in policy.vms()} # its VMs now, and those it ran for in these days
for run in runs:
cells.setdefault(run.instance, {})[run.day] = run
grid = [(vm, [vm_runs.get(day) for day in days]) for vm, vm_runs in sorted(cells.items(), key=lambda i: i[0].name)]
problems = sorted((run for run in runs if run.outcome in (BackupRun.FAILED, BackupRun.SKIPPED)),
key=lambda run: (run.day, run.instance.name), reverse=True)
return render(request, "vmbackups/policy.html", {"policy": policy, "form": form, "days": days, "grid": grid,
"problems": problems, "time_zone": settings.TIME_ZONE})