mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 17:36:05 +00:00
feat(backups): a schedule also keeps weekly and monthly backups
Besides the newest N backups of each VM, a schedule keeps the newest backup of each of the last N weeks and of the last N months that have one (panel time zone); 0 keeps none. The schedules list shows them.
This commit is contained in:
parent
adb4231db7
commit
2c0855cf64
13 changed files with 392 additions and 251 deletions
|
|
@ -77,9 +77,11 @@ class PolicyForm(forms.ModelForm):
|
|||
|
||||
class Meta:
|
||||
model = BackupPolicy
|
||||
fields = ["name", "target", "compute", "instances", "tag", "time", "keep", "full_every", "frozen", "enabled"]
|
||||
fields = ["name", "target", "compute", "instances", "tag", "time", "keep", "keep_weekly", "keep_monthly", "full_every",
|
||||
"frozen", "enabled"]
|
||||
labels = {"name": _("Name"), "target": _("Backup target"), "compute": _("Every VM of a compute"),
|
||||
"instances": _("Or these VMs"), "tag": _("Or every VM with a tag"), "time": _("Daily at"), "keep": _("Backups kept per VM"),
|
||||
"keep_weekly": _("Weekly backups kept"), "keep_monthly": _("Monthly backups kept"),
|
||||
"full_every": _("A full backup every N backups"),
|
||||
"frozen": _("Require frozen file systems"), "enabled": _("Enabled")}
|
||||
widgets = {"time": forms.TimeInput(attrs={"type": "time"}, format="%H:%M"),
|
||||
|
|
@ -93,6 +95,10 @@ class PolicyForm(forms.ModelForm):
|
|||
for name in ("keep", "full_every"):
|
||||
self.fields[name].validators.append(_min_one)
|
||||
self.fields[name].widget.attrs["min"] = 1
|
||||
for name in ("keep_weekly", "keep_monthly"):
|
||||
self.fields[name].widget.attrs["min"] = 0
|
||||
self.fields["keep_weekly"].help_text = _("Also the newest backup of each of the N newest weeks that have one; 0: none")
|
||||
self.fields["keep_monthly"].help_text = _("Also the newest backup of each of the N newest months that have one; 0: none")
|
||||
self.fields["full_every"].help_text = _("1: every backup is full. Above 1, the backups between copy only what "
|
||||
"changed (running VMs with qcow2 disks).")
|
||||
|
||||
|
|
|
|||
|
|
@ -606,14 +606,24 @@ def _backup(params):
|
|||
|
||||
def beyond_keep(policy, instance_id):
|
||||
"""A schedule's backups of a VM beyond what it keeps, newest first: the
|
||||
ready ones past keep, and the missing ones older than the oldest kept
|
||||
(keep counts ready ones only; a missing one would pin its chain)."""
|
||||
ready ones that are neither among the newest keep nor the newest of one
|
||||
of the newest keep_weekly weeks or keep_monthly months that have one (in
|
||||
the panel's time zone), and the missing ones older than the oldest of the
|
||||
newest keep (it keeps ready ones only; a missing one would pin its chain)."""
|
||||
rows = list(Backup.objects.filter(policy=policy, instance_id=instance_id, state__in=(Backup.READY, Backup.MISSING))
|
||||
.order_by("-created_at"))
|
||||
ready = [b for b in rows if b.state == Backup.READY]
|
||||
if len(ready) <= policy.keep:
|
||||
kept = ready[:policy.keep]
|
||||
for count, period in ((policy.keep_weekly, lambda day: day.isocalendar()[:2]),
|
||||
(policy.keep_monthly, lambda day: (day.year, day.month))):
|
||||
newest = {} # a period's first backup, newest first, is its newest
|
||||
for b in ready:
|
||||
newest.setdefault(period(timezone.localtime(b.created_at)), b)
|
||||
kept += list(newest.values())[:count]
|
||||
if len(ready) <= policy.keep: # fewer than keep: the missing ones stay too
|
||||
return []
|
||||
return [b for b in rows if b.created_at < ready[policy.keep - 1].created_at]
|
||||
oldest = ready[:policy.keep][-1].created_at
|
||||
return [b for b in rows if b not in kept and (b.state == Backup.READY or b.created_at < oldest)]
|
||||
|
||||
|
||||
def _beyond_keep(backup, policy_id):
|
||||
|
|
|
|||
23
vmbackups/migrations/0010_keep_weekly_monthly.py
Normal file
23
vmbackups/migrations/0010_keep_weekly_monthly.py
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
# Generated by Django 5.2.18 on 2026-11-19 18:47
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('vmbackups', '0009_backup_verify'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='backuppolicy',
|
||||
name='keep_monthly',
|
||||
field=models.PositiveSmallIntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='backuppolicy',
|
||||
name='keep_weekly',
|
||||
field=models.PositiveSmallIntegerField(default=0),
|
||||
),
|
||||
]
|
||||
|
|
@ -52,6 +52,9 @@ class BackupPolicy(models.Model):
|
|||
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)
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@
|
|||
<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>
|
||||
<td class="text-end">{{ policy.keep }}</td>
|
||||
<td class="text-end">{{ policy.keep }}{% if policy.keep_weekly %} {% blocktrans with n=policy.keep_weekly %}+ {{ n }} weekly{% endblocktrans %}{% endif %}{% if policy.keep_monthly %} {% blocktrans with n=policy.keep_monthly %}+ {{ n }} monthly{% endblocktrans %}{% endif %}</td>
|
||||
<td>{% if policy.full_every == 1 %}{% trans "Every backup" %}{% else %}{% blocktrans with n=policy.full_every %}Every {{ n }} backups{% endblocktrans %}{% endif %}</td>
|
||||
<td>{% if policy.enabled %}<span class="badge text-bg-success">{% trans "Enabled" %}</span>{% else %}<span class="badge text-bg-secondary">{% trans "Disabled" %}</span>{% endif %}</td>
|
||||
</tr>
|
||||
|
|
|
|||
|
|
@ -11,14 +11,16 @@
|
|||
</div>
|
||||
<div class="row g-2">
|
||||
<div class="col-sm-6">{% blocktrans asvar zone_help %}Time zone: {{ time_zone }}{% endblocktrans %}{% bootstrap_field form.time help_text=zone_help %}</div>
|
||||
<div class="col-sm-6">{% bootstrap_field form.keep %}</div>
|
||||
<div class="col-sm-6">{% bootstrap_field form.full_every %}</div>
|
||||
</div>
|
||||
<div class="row g-2">
|
||||
<div class="col-sm-6">{% bootstrap_field form.full_every %}</div>
|
||||
<div class="col-sm-4">{% bootstrap_field form.keep %}</div>
|
||||
<div class="col-sm-4">{% bootstrap_field form.keep_weekly %}</div>
|
||||
<div class="col-sm-4">{% bootstrap_field form.keep_monthly %}</div>
|
||||
</div>
|
||||
{% bootstrap_field form.frozen %}
|
||||
{% bootstrap_field form.enabled %}
|
||||
<p class="small text-body-secondary">{% trans "Each VM is backed up once a day, starting at the time; a VM that has not started within 6 hours waits for the next day. Older backups of each VM beyond the number kept are deleted, a chain of incremental backups once all of it is beyond; backups taken by hand are not." %}</p>
|
||||
<p class="small text-body-secondary">{% trans "Each VM is backed up once a day, starting at the time; a VM that has not started within 6 hours waits for the next day. Older backups of each VM beyond those kept are deleted, a chain of incremental backups once all of it is beyond; backups taken by hand are not." %}</p>
|
||||
<button type="submit" class="btn btn-primary">{% trans "Save" %}</button>
|
||||
<a class="btn btn-outline-secondary ms-1" href="{% url 'vmbackups:policies' %}">{% trans "Cancel" %}</a>
|
||||
</form>
|
||||
|
|
|
|||
|
|
@ -28,7 +28,8 @@ class PolicyPageTests(TestCase):
|
|||
BackupTargetPool.objects.create(target=self.target, compute=self.c1, pool="b1", pool_uuid="u")
|
||||
|
||||
def post(self, **fields):
|
||||
data = {"name": "nightly", "target": self.target.pk, "time": "02:00", "keep": "7", "full_every": "1", "enabled": "on",
|
||||
data = {"name": "nightly", "target": self.target.pk, "time": "02:00", "keep": "7", "keep_weekly": "0", "keep_monthly": "0",
|
||||
"full_every": "1", "enabled": "on",
|
||||
**fields}
|
||||
return self.client.post(reverse("vmbackups:policy_new"), data)
|
||||
|
||||
|
|
@ -102,11 +103,14 @@ class PolicyPageTests(TestCase):
|
|||
url = reverse("vmbackups:policy", args=[policy.pk])
|
||||
page = self.client.get(url)
|
||||
self.assertContains(page, "The host was in maintenance")
|
||||
self.client.post(url, {"name": "nightly", "target": self.target.pk, "time": "03:30", "keep": "3", "full_every": "1",
|
||||
"instances": [self.vm1.pk]})
|
||||
self.client.post(url, {"name": "nightly", "target": self.target.pk, "time": "03:30", "keep": "3", "keep_weekly": "4",
|
||||
"keep_monthly": "6", "full_every": "1", "instances": [self.vm1.pk]})
|
||||
policy.refresh_from_db()
|
||||
self.assertEqual((policy.time, policy.keep, policy.enabled), (datetime.time(3, 30), 3, False))
|
||||
self.assertContains(self.client.get(reverse("vmbackups:policies")), "Backup schedule nightly is saved.")
|
||||
self.assertEqual((policy.time, policy.keep, policy.keep_weekly, policy.keep_monthly, policy.enabled),
|
||||
(datetime.time(3, 30), 3, 4, 6, False))
|
||||
page = self.client.get(reverse("vmbackups:policies"))
|
||||
self.assertContains(page, "Backup schedule nightly is saved.")
|
||||
self.assertContains(page, "3 + 4 weekly + 6 monthly")
|
||||
|
||||
def test_delete_keeps_the_backups(self):
|
||||
policy = self.schedule()
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ from operations.utils import words
|
|||
from vmbackups import schedule
|
||||
from appsettings.models import AppSettings
|
||||
from operations.models import Alert
|
||||
from vmbackups.jobs import CheckTarget, DeleteBackup, _beyond_keep
|
||||
from vmbackups.jobs import CheckTarget, DeleteBackup, _beyond_keep, beyond_keep
|
||||
from vmbackups.models import Backup, BackupFile, BackupPolicy, BackupRun, BackupTarget, BackupTargetPool
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
|
|
@ -443,6 +443,38 @@ class ScheduleTests(TransactionTestCase):
|
|||
schedule.retain()
|
||||
self.assertEqual(self.deletes()[-1].params["backup"], str(older.uuid))
|
||||
|
||||
def test_retention_keeps_the_newest_of_each_week_and_month_too(self):
|
||||
# daily backups from 2026-09-28 to 2026-11-15; keep 2, 2 weekly, 3 monthly
|
||||
days = [at(2026, 9, 28, 12) + datetime.timedelta(days=n) for n in range(49)]
|
||||
for day in days:
|
||||
(backup,) = self.backups(Backup.READY)
|
||||
Backup.objects.filter(pk=backup.pk).update(created_at=day)
|
||||
BackupPolicy.objects.filter(pk=self.policy.pk).update(keep=2, keep_weekly=2, keep_monthly=3)
|
||||
self.policy.refresh_from_db()
|
||||
kept = {b.created_at.date() for b in Backup.objects.filter(policy=self.policy)} - {
|
||||
b.created_at.date() for b in beyond_keep(self.policy, self.vm1.pk)}
|
||||
self.assertEqual(sorted(kept), [
|
||||
datetime.date(2026, 9, 30), # September's newest
|
||||
datetime.date(2026, 10, 31), # October's
|
||||
datetime.date(2026, 11, 8), # the newest of the week before
|
||||
datetime.date(2026, 11, 14), datetime.date(2026, 11, 15), # the newest two (this week's and November's)
|
||||
])
|
||||
# a missing incremental before the newest two goes, though monthly ones are older: it pins its base
|
||||
(missing,) = self.backups(Backup.MISSING)
|
||||
Backup.objects.filter(pk=missing.pk).update(created_at=at(2026, 11, 10, 12))
|
||||
self.assertIn(missing, beyond_keep(self.policy, self.vm1.pk))
|
||||
|
||||
def test_a_missing_chain_goes_when_every_ready_backup_is_a_monthly_one(self):
|
||||
BackupPolicy.objects.filter(pk=self.policy.pk).update(keep=1, keep_monthly=2)
|
||||
self.policy.refresh_from_db()
|
||||
full, inc = self.backups(Backup.MISSING, Backup.MISSING)
|
||||
self.chained(full, inc)
|
||||
september, november = self.backups(Backup.READY, Backup.READY)
|
||||
for backup, day in ((september, at(2026, 9, 30, 12)), (full, at(2026, 10, 5, 12)), (inc, at(2026, 10, 6, 12)),
|
||||
(november, at(2026, 11, 15, 12))):
|
||||
Backup.objects.filter(pk=backup.pk).update(created_at=day)
|
||||
self.assertEqual(beyond_keep(self.policy, self.vm1.pk), [inc, full])
|
||||
|
||||
def test_retention_reads_each_vm_once(self):
|
||||
self.backups(*[Backup.READY] * 4)
|
||||
with patch("vmbackups.schedule.beyond_keep", return_value=[]) as beyond:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue