1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

feat(vmbackups): a schedule of every VM with a tag

A backup schedule backs up a compute's VMs, chosen VMs, or now every VM
with a tag: those that have it at each run, templates left out, so a VM
given the tag is backed up from the next day on. The form checks the
target's pools on the hosts of the tag's VMs now; a VM tagged later on a
host without one fails its run with that reason, as a compute's new VM
does. The schedules list says "VMs tagged prod".

A tag a schedule uses is not deleted: the Tags page says which schedules
back up its VMs.
This commit is contained in:
catborise 2026-11-18 21:31:39 +03:00
parent a492031d12
commit f8cb6f1e0f
15 changed files with 157 additions and 46 deletions

View file

@ -61,6 +61,16 @@ class TagAdminTests(TestCase):
self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": "PROD"})
self.assertEqual(self.messages(), [])
def test_a_tag_a_backup_schedule_uses_is_kept(self):
import datetime
from vmbackups.models import BackupPolicy, BackupTarget
BackupPolicy.objects.create(name="nightly", target=BackupTarget.objects.create(name="nfs"), tag=self.prod,
time=datetime.time(2), keep=3)
response = self.client.post(reverse("admin:tag_delete", args=[self.prod.pk]), follow=True)
self.assertContains(response, "The backup schedule nightly backs up its VMs")
self.assertTrue(Tag.objects.filter(name="prod").exists())
self.assertEqual(self.messages(), [])
def test_only_superusers(self):
self.client.force_login(User.objects.create_user("tg-user", password="pw"))
for url in (reverse("admin:tag_list"), reverse("admin:tag_update", args=[self.prod.pk]),

View file

@ -505,6 +505,12 @@ def tag_update(request, pk):
@superuser_only
def tag_delete(request, pk):
tag = get_object_or_404(Tag, pk=pk)
schedules = list(tag.backup_policies.values_list("name", flat=True))
if schedules: # it would back up nothing (models.PROTECT)
messages.error(request, ngettext("The backup schedule %(schedules)s backs up its VMs: change it first",
"The backup schedules %(schedules)s back up its VMs: change them first",
len(schedules)) % {"schedules": ", ".join(schedules)})
return redirect("admin:tag_list")
if request.method == "POST":
with audit(request, None, f"Tag {tag.name}", "delete"), transaction.atomic():
lock_ownership()

Binary file not shown.

View file

@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-18 18:18+0000\n"
"POT-Creation-Date: 2026-11-18 18:30+0000\n"
"PO-Revision-Date: 2020-11-04 12:00+0000\n"
"Last-Translator: catborise <muhammetalisag@gmail.com>, 2020\n"
"Language-Team: Turkish (https://www.transifex.com/catborise/teams/110663/tr/)\n"
@ -329,7 +329,7 @@ msgstr "Burada oturumunuz açık kalır; diğer oturumlarınız kapanır."
#: templates/common/confirm_delete.html:25 templates/common/form.html:27
#: virtsecrets/templates/create_secret_block.html:48
#: virtsecrets/templates/secrets.html:106
#: vmbackups/templates/vmbackups/policy_form.html:22
#: vmbackups/templates/vmbackups/policy_form.html:23
#: vmbackups/templates/vmbackups/target_new.html:18
msgid "Cancel"
msgstr "İptal"
@ -1328,24 +1328,36 @@ msgstr ""
msgid "Rename tag %(tag)s"
msgstr "%(tag)s etiketini yeniden adlandır"
#: admin/views.py:513
#: admin/views.py:510
#, python-format
msgid "The backup schedule %(schedules)s backs up its VMs: change it first"
msgid_plural ""
"The backup schedules %(schedules)s back up its VMs: change them first"
msgstr[0] ""
"%(schedules)s yedekleme zamanlaması bu etiketin sanal makinelerini "
"yedekliyor: önce onu değiştirin"
msgstr[1] ""
"%(schedules)s yedekleme zamanlamaları bu etiketin sanal makinelerini "
"yedekliyor: önce onları değiştirin"
#: admin/views.py:519
#, python-format
msgid "Tag %(tag)s deleted"
msgstr "%(tag)s etiketi silindi"
#: admin/views.py:518
#: admin/views.py:524
#, python-format
msgid "It is taken off %(vms)s and %(hosts)s."
msgstr "%(vms)s ve %(hosts)s üzerinden kaldırılır."
#: admin/views.py:519
#: admin/views.py:525
#, python-format
msgid "%(count)s VM"
msgid_plural "%(count)s VMs"
msgstr[0] "%(count)s sanal makine"
msgstr[1] "%(count)s sanal makine"
#: admin/views.py:520
#: admin/views.py:526
#, python-format
msgid "%(count)s host"
msgid_plural "%(count)s hosts"
@ -2601,7 +2613,7 @@ msgstr "hiçbiri"
#: networks/templates/network.html:337 networks/templates/network.html:379
#: networks/templates/network.html:406 networks/templates/network.html:445
#: nwfilters/templates/nwfilter.html:157 templates/common/form.html:28
#: vmbackups/templates/vmbackups/policy_form.html:21
#: vmbackups/templates/vmbackups/policy_form.html:22
msgid "Save"
msgstr "Kaydet"
@ -9905,6 +9917,10 @@ msgstr "Bir sunucunun bütün sanal makineleri"
msgid "Or these VMs"
msgstr "Ya da bu sanal makineler"
#: vmbackups/forms.py:82
msgid "Or every VM with a tag"
msgstr "Ya da bir etiketin bütün sanal makineleri"
#: vmbackups/forms.py:82 vmbackups/templates/vmbackups/policies.html:17
msgid "Daily at"
msgstr "Her gün saat"
@ -9934,15 +9950,15 @@ msgstr ""
"kopyalar (qcow2 diskli, çalışan VM'ler)."
#: vmbackups/forms.py:103
msgid "Choose a compute or VMs, not both"
msgstr "Bir sunucu ya da sanal makineler seçin, ikisini birden değil"
msgid "Choose a compute, VMs or a tag: one of them"
msgstr "Bir sunucu, sanal makineler ya da bir etiket seçin: yalnız birini"
#: vmbackups/forms.py:108 vmbackups/jobs.py:113
#: vmbackups/forms.py:113 vmbackups/jobs.py:113
#, python-format
msgid "Backup target %(target)s has no storage pool on %(compute)s"
msgstr "%(target)s yedek hedefinin %(compute)s üzerinde depolama havuzu yok"
#: vmbackups/forms.py:115
#: vmbackups/forms.py:120
msgid "Keep one backup at least"
msgstr "En az bir yedek tutun"
@ -10449,6 +10465,11 @@ msgstr "Tam yedek"
msgid "Every VM of %(compute)s"
msgstr "%(compute)s üzerindeki bütün sanal makineler"
#: vmbackups/templates/vmbackups/policies.html:24
#, python-format
msgid "VMs tagged %(tag)s"
msgstr "%(tag)s etiketli sanal makineler"
#: vmbackups/templates/vmbackups/policies.html:28
msgid "Every backup"
msgstr "Her yedek"
@ -10508,12 +10529,12 @@ msgstr "Atlandı"
msgid "No run yet."
msgstr "Henüz çalışma yok."
#: vmbackups/templates/vmbackups/policy_form.html:12
#: vmbackups/templates/vmbackups/policy_form.html:13
#, python-format
msgid "Time zone: %(time_zone)s"
msgstr "Saat dilimi: %(time_zone)s"
#: vmbackups/templates/vmbackups/policy_form.html:20
#: vmbackups/templates/vmbackups/policy_form.html:21
msgid ""
"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 "

Binary file not shown.

View file

@ -7,7 +7,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-18 18:18+0000\n"
"POT-Creation-Date: 2026-11-18 18:30+0000\n"
"PO-Revision-Date: \n"
"Last-Translator: \n"
"Language-Team: \n"
@ -324,7 +324,7 @@ msgstr "您在此处保持登录;您的其他会话将结束。"
#: templates/common/confirm_delete.html:25 templates/common/form.html:27
#: virtsecrets/templates/create_secret_block.html:48
#: virtsecrets/templates/secrets.html:106
#: vmbackups/templates/vmbackups/policy_form.html:22
#: vmbackups/templates/vmbackups/policy_form.html:23
#: vmbackups/templates/vmbackups/target_new.html:18
msgid "Cancel"
msgstr "取消"
@ -1286,23 +1286,30 @@ msgstr "若其 UUID 再次出现,其所有者将不再恢复对该虚拟机的
msgid "Rename tag %(tag)s"
msgstr "重命名标签 %(tag)s"
#: admin/views.py:513
#: admin/views.py:510
#, python-format
msgid "The backup schedule %(schedules)s backs up its VMs: change it first"
msgid_plural ""
"The backup schedules %(schedules)s back up its VMs: change them first"
msgstr[0] "备份计划 %(schedules)s 正在备份该标签的虚拟机:请先修改计划"
#: admin/views.py:519
#, python-format
msgid "Tag %(tag)s deleted"
msgstr "标签 %(tag)s 已删除"
#: admin/views.py:518
#: admin/views.py:524
#, python-format
msgid "It is taken off %(vms)s and %(hosts)s."
msgstr "它将从 %(vms)s 和 %(hosts)s 上移除。"
#: admin/views.py:519
#: admin/views.py:525
#, python-format
msgid "%(count)s VM"
msgid_plural "%(count)s VMs"
msgstr[0] "%(count)s 个虚拟机"
#: admin/views.py:520
#: admin/views.py:526
#, python-format
msgid "%(count)s host"
msgid_plural "%(count)s hosts"
@ -2483,7 +2490,7 @@ msgstr "无"
#: networks/templates/network.html:337 networks/templates/network.html:379
#: networks/templates/network.html:406 networks/templates/network.html:445
#: nwfilters/templates/nwfilter.html:157 templates/common/form.html:28
#: vmbackups/templates/vmbackups/policy_form.html:21
#: vmbackups/templates/vmbackups/policy_form.html:22
msgid "Save"
msgstr "保存"
@ -9336,6 +9343,10 @@ msgstr "某计算节点的所有虚拟机"
msgid "Or these VMs"
msgstr "或这些虚拟机"
#: vmbackups/forms.py:82
msgid "Or every VM with a tag"
msgstr "或带某个标签的所有虚拟机"
#: vmbackups/forms.py:82 vmbackups/templates/vmbackups/policies.html:17
msgid "Daily at"
msgstr "每天时间"
@ -9363,15 +9374,15 @@ msgid ""
msgstr "1:每次备份都是完整备份。大于 1 时,中间的备份只复制变化的部分(适用于使用 qcow2 磁盘的运行中虚拟机)。"
#: vmbackups/forms.py:103
msgid "Choose a compute or VMs, not both"
msgstr "请选择一个计算节点或若干虚拟机,不能同时选择"
msgid "Choose a compute, VMs or a tag: one of them"
msgstr "选择一个计算节点、若干虚拟机或一个标签:只选其一"
#: vmbackups/forms.py:108 vmbackups/jobs.py:113
#: vmbackups/forms.py:113 vmbackups/jobs.py:113
#, python-format
msgid "Backup target %(target)s has no storage pool on %(compute)s"
msgstr "备份目标 %(target)s 在 %(compute)s 上没有存储池"
#: vmbackups/forms.py:115
#: vmbackups/forms.py:120
msgid "Keep one backup at least"
msgstr "至少保留一个备份"
@ -9840,6 +9851,11 @@ msgstr "完整备份"
msgid "Every VM of %(compute)s"
msgstr "%(compute)s 的所有虚拟机"
#: vmbackups/templates/vmbackups/policies.html:24
#, python-format
msgid "VMs tagged %(tag)s"
msgstr "带 %(tag)s 标签的虚拟机"
#: vmbackups/templates/vmbackups/policies.html:28
msgid "Every backup"
msgstr "每次备份"
@ -9897,12 +9913,12 @@ msgstr "已跳过"
msgid "No run yet."
msgstr "还没有运行记录。"
#: vmbackups/templates/vmbackups/policy_form.html:12
#: vmbackups/templates/vmbackups/policy_form.html:13
#, python-format
msgid "Time zone: %(time_zone)s"
msgstr "时区:%(time_zone)s"
#: vmbackups/templates/vmbackups/policy_form.html:20
#: vmbackups/templates/vmbackups/policy_form.html:21
msgid ""
"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 "

View file

@ -72,14 +72,14 @@ class RestoreDiskForm(forms.Form):
class PolicyForm(forms.ModelForm):
"""A backup schedule: a compute's VMs or chosen VMs, all on hosts that
have a pool of its target."""
"""A backup schedule: a compute's VMs, chosen VMs or a tag's VMs, all on
hosts that have a pool of its target (a tag's: those that have it now)."""
class Meta:
model = BackupPolicy
fields = ["name", "target", "compute", "instances", "time", "keep", "full_every", "frozen", "enabled"]
fields = ["name", "target", "compute", "instances", "tag", "time", "keep", "full_every", "frozen", "enabled"]
labels = {"name": _("Name"), "target": _("Backup target"), "compute": _("Every VM of a compute"),
"instances": _("Or these VMs"), "time": _("Daily at"), "keep": _("Backups kept per VM"),
"instances": _("Or these VMs"), "tag": _("Or every VM with a tag"), "time": _("Daily at"), "keep": _("Backups kept per VM"),
"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"),
@ -98,11 +98,16 @@ class PolicyForm(forms.ModelForm):
def clean(self):
data = super().clean()
compute, vms, target = data.get("compute"), data.get("instances"), data.get("target")
if bool(compute) == bool(vms):
raise forms.ValidationError(_("Choose a compute or VMs, not both"))
compute, vms, tag, target = data.get("compute"), data.get("instances"), data.get("tag"), data.get("target")
if [bool(compute), bool(vms), bool(tag)].count(True) != 1:
raise forms.ValidationError(_("Choose a compute, VMs or a tag: one of them"))
if target is not None:
hosts = {compute} if compute else {vm.compute for vm in vms}
if compute:
hosts = {compute}
elif tag:
hosts = {vm.compute for vm in tag.instances.filter(is_template=False).select_related("compute")}
else:
hosts = {vm.compute for vm in vms}
for host in sorted(hosts, key=lambda c: c.name):
if target.pool_on(host) is None:
raise forms.ValidationError(_("Backup target %(target)s has no storage pool on %(compute)s"),

View file

@ -0,0 +1,20 @@
# Generated by Django 5.2.18 on 2026-11-18 18:22
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0012_tags'),
('vmbackups', '0007_backup_prefix'),
]
operations = [
migrations.AddField(
model_name='backuppolicy',
name='tag',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='backup_policies', to='computes.tag'),
),
]

View file

@ -4,7 +4,7 @@ import uuid
from django.conf import settings
from django.db import models
from computes.models import Compute
from computes.models import Compute, Tag
from instances.models import Instance
from operations.models import Operation
from vrtManager.backup import backup_prefix
@ -40,7 +40,7 @@ class BackupTargetPool(models.Model):
class BackupPolicy(models.Model):
"""A schedule: its VMs (those chosen, or every VM of a compute) backed
"""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."""
@ -48,6 +48,8 @@ class BackupPolicy(models.Model):
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()
full_every = models.PositiveSmallIntegerField(default=1) # a full backup every N; the others incremental
@ -63,9 +65,11 @@ class BackupPolicy(models.Model):
return self.name
def vms(self):
"""Its VMs now: a compute's are those it has at this moment, templates left out."""
"""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")

View file

@ -21,7 +21,7 @@
{% for policy in policies %}
<tr>
<td><a href="{% url 'vmbackups:policy' policy.id %}">{{ policy.name }}</a></td>
<td>{% if policy.compute %}{% blocktrans with compute=policy.compute.name %}Every VM of {{ compute }}{% endblocktrans %}{% else %}{% blocktrans count counter=policy.vm_count %}{{ counter }} VM{% plural %}{{ counter }} VMs{% endblocktrans %}{% endif %}</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>
<td class="text-end">{{ policy.keep }}</td>

View file

@ -5,8 +5,9 @@
{% bootstrap_field form.name %}
{% bootstrap_field form.target %}
<div class="row g-2">
<div class="col-md-5">{% bootstrap_field form.compute %}</div>
<div class="col-md-7">{% bootstrap_field form.instances %}</div>
<div class="col-md-4">{% bootstrap_field form.compute %}</div>
<div class="col-md-5">{% bootstrap_field form.instances %}</div>
<div class="col-md-3">{% bootstrap_field form.tag %}</div>
</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>

View file

@ -8,7 +8,7 @@ from django.test import TestCase
from django.urls import reverse
from lxml import html as lxml_html
from computes.models import Compute
from computes.models import Compute, Tag
from instances.models import Instance
from instances.tests.test_page_controls import PageControls
from logs.models import Logs
@ -46,12 +46,21 @@ class PolicyPageTests(TestCase):
self.post(compute=self.c1.pk)
self.assertEqual(BackupPolicy.objects.get().compute, self.c1)
def test_compute_or_vms_not_both_nor_neither(self):
for fields in ({}, {"compute": self.c1.pk, "instances": [self.vm1.pk]}):
def test_a_schedule_of_a_tag(self):
prod = Tag.objects.create(name="prod")
self.vm1.tags.add(prod)
self.post(tag=prod.pk)
self.assertEqual(BackupPolicy.objects.get().tag, prod)
self.assertContains(self.client.get(reverse("vmbackups:policies")), "VMs tagged prod")
def test_compute_vms_or_tag_one_only(self):
prod = Tag.objects.create(name="prod")
for fields in ({}, {"compute": self.c1.pk, "instances": [self.vm1.pk]}, {"compute": self.c1.pk, "tag": prod.pk},
{"instances": [self.vm1.pk], "tag": prod.pk}):
with self.subTest(fields):
response = self.post(**fields)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Choose a compute or VMs")
self.assertContains(response, "Choose a compute, VMs or a tag: one of them")
self.assertFalse(BackupPolicy.objects.exists())
def test_vms_on_a_host_without_the_target_are_refused(self):
@ -59,6 +68,9 @@ class PolicyPageTests(TestCase):
self.assertContains(response, "has no storage pool on h2")
response = self.post(compute=self.c2.pk)
self.assertContains(response, "has no storage pool on h2")
prod = Tag.objects.create(name="prod")
self.vm3.tags.add(prod)
self.assertContains(self.post(tag=prod.pk), "has no storage pool on h2") # the tag's VMs now
self.assertFalse(BackupPolicy.objects.exists())
def test_the_list_leads_to_the_new_schedule_page(self):
@ -151,8 +163,12 @@ class PolicyTabTests(PageControls, TestCase):
chosen.instances.add(self.instance)
BackupPolicy.objects.create(name="whole-host", target=target, compute=self.compute, time=datetime.time(3), keep=2,
owner=admin)
prod = Tag.objects.create(name="prod")
self.instance.tags.add(prod)
BackupPolicy.objects.create(name="tagged", target=target, tag=prod, time=datetime.time(4), keep=2, owner=admin)
with patch("vmbackups.utils.wvmBackup"):
self.controls(admin)
tab = lxml_html.fromstring(self.last_page).xpath("string(//div[@id='backups'])")
self.assertIn("chosen", tab)
self.assertIn("whole-host", tab)
self.assertIn("tagged", tab)

View file

@ -40,5 +40,17 @@ class PolicyModelTests(TestCase):
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_the_vms_of_a_tag_s_policy(self):
from computes.models import Tag
prod = Tag.objects.create(name="prod")
self.vm.tags.add(prod)
Instance.objects.create(compute=self.compute, name="tpl", uuid="61616161-0000-4000-8000-000000000004",
is_template=True).tags.add(prod)
tagged = BackupPolicy.objects.create(name="prod", target=self.target, tag=prod, time=datetime.time(3), keep=3,
owner=self.admin)
self.assertEqual([vm.name for vm in tagged.vms()], ["vm1"])
Instance.objects.create(compute=self.compute, name="vm0", uuid="61616161-0000-4000-8000-000000000005").tags.add(prod)
self.assertEqual([vm.name for vm in tagged.vms()], ["vm0", "vm1"]) # the VMs with it now
def test_missing_state(self):
self.assertIn(Backup.MISSING, dict(Backup.STATES))

View file

@ -71,6 +71,6 @@ def vm_tab(instance, user):
except libvirtError as err:
problem = str(err)
schedules = [] if owner else BackupPolicy.objects.filter(
Q(instances=instance) | Q(compute=instance.compute_id)).distinct().order_by("name")
Q(instances=instance) | Q(compute=instance.compute_id) | Q(tag__instances=instance)).distinct().order_by("name")
return {"rows": rows, "targets": targets, "problem": problem, "schedules": schedules,
"pending_deletes": pending_deletes()}

View file

@ -311,7 +311,7 @@ def restore_disk(request, uuid):
@superuser_only
def policies(request):
"""The backup schedules."""
rows = BackupPolicy.objects.select_related("target", "compute", "owner").annotate(vm_count=Count("instances"))
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")})