diff --git a/accounts/templates/accounts/email_otp_form.html b/accounts/templates/accounts/email_otp_form.html
index da7277f0..f7cb28ec 100644
--- a/accounts/templates/accounts/email_otp_form.html
+++ b/accounts/templates/accounts/email_otp_form.html
@@ -21,9 +21,9 @@
{% endblock %}
+{% block script %}{% endblock %}
diff --git a/vmbackups/templates/vmbackups/target.html b/vmbackups/templates/vmbackups/target.html
index 4f4691bf..aed671a4 100644
--- a/vmbackups/templates/vmbackups/target.html
+++ b/vmbackups/templates/vmbackups/target.html
@@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
+{% load static %}
{% load bootstrap_icons %}
{% load django_bootstrap5 %}
{% load operations %}
@@ -74,3 +75,4 @@
{% endif %}
{% endblock %}
+{% block script %}{% endblock %}
diff --git a/vmbackups/templates/vmbackups/target_new.html b/vmbackups/templates/vmbackups/target_new.html
index 8bf520ae..7659a37f 100644
--- a/vmbackups/templates/vmbackups/target_new.html
+++ b/vmbackups/templates/vmbackups/target_new.html
@@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
+{% load static %}
{% load bootstrap_icons %}
{% load django_bootstrap5 %}
@@ -14,9 +15,12 @@
{% endblock %}
+{% block script %}{% endblock %}
diff --git a/vmbackups/tests/test_form_pages.py b/vmbackups/tests/test_form_pages.py
new file mode 100644
index 00000000..9abe5434
--- /dev/null
+++ b/vmbackups/tests/test_form_pages.py
@@ -0,0 +1,39 @@
+"""The backup forms as a page shows them: a list's empty choice says to choose, a field's
+label is not repeated in it, and a pool field offers the chosen compute's pools."""
+from django.contrib.auth import get_user_model
+from django.test import TestCase
+from django.urls import reverse
+from lxml import html
+
+
+class FormPageTests(TestCase):
+ def setUp(self):
+ self.client.force_login(get_user_model().objects.create_superuser("fp-admin", "fp@example.com", "pw"))
+
+ def test_a_new_target_s_form(self):
+ page = html.fromstring(self.client.get(reverse("vmbackups:target_new")).content)
+ self.assertEqual(page.xpath("//select[@name='compute']/option[1]/text()"), ["Choose…"])
+ self.assertEqual(page.xpath("//input[@name='name']/@placeholder"), [])
+ (pool,) = page.xpath("//input[@name='pool']")
+ self.assertEqual(pool.get("data-pools"), reverse("vmbackups:pools", args=[0]) + "?types=dir,netfs")
+
+ def test_a_compute_s_file_pools_are_listed_with_their_types(self):
+ from types import SimpleNamespace
+ from unittest.mock import patch
+
+ from computes.models import Compute
+
+ host = Compute.objects.create(name="fp-host", hostname="192.0.2.12", login="", password="", type=4)
+ xml = lambda kind: SimpleNamespace(XMLDesc=lambda flags: f"")
+ pools = {"nfs": (xml("netfs"), "/n"), "local": (xml("dir"), "/l"), "disk": (xml("fs"), "/f")}
+ with patch("vmbackups.views.wvmConnect") as connect:
+ connect.return_value.file_pools.return_value = pools
+ listed = lambda query="": self.client.get(reverse("vmbackups:pools", args=[host.pk]) + query).json()
+ self.assertEqual([p["name"] for p in listed()], ["disk", "local", "nfs"])
+ self.assertEqual(listed("?types=dir,netfs"), [{"name": "local", "type": "dir"}, {"name": "nfs", "type": "netfs"}])
+
+ def test_a_new_schedule_s_form_asks_which_vms_first(self):
+ page = html.fromstring(self.client.get(reverse("vmbackups:policy_new")).content)
+ self.assertEqual(page.xpath("//input[@name='scope']/@value"), ["compute", "instances", "tag"])
+ self.assertEqual(page.xpath("//input[@name='scope'][@checked]/@value"), ["compute"])
+ self.assertEqual(page.xpath("//*[@data-scope]/@data-scope"), ["compute", "instances", "tag"])
diff --git a/vmbackups/tests/test_policies.py b/vmbackups/tests/test_policies.py
index c3ac0185..28229f17 100644
--- a/vmbackups/tests/test_policies.py
+++ b/vmbackups/tests/test_policies.py
@@ -34,7 +34,7 @@ class PolicyPageTests(TestCase):
return self.client.post(reverse("vmbackups:policy_new"), data)
def test_a_schedule_of_chosen_vms(self):
- response = self.post(instances=[self.vm1.pk])
+ response = self.post(scope="instances", instances=[self.vm1.pk])
policy = BackupPolicy.objects.get()
# back to the list, which says it is saved: the schedule's page is its edit form
self.assertRedirects(response, reverse("vmbackups:policies"), fetch_redirect_response=False)
@@ -44,34 +44,41 @@ class PolicyPageTests(TestCase):
self.assertTrue(Logs.objects.filter(message__contains="Backup schedule nightly").exists())
def test_a_schedule_of_a_compute(self):
- self.post(compute=self.c1.pk)
+ self.post(scope="compute", compute=self.c1.pk)
self.assertEqual(BackupPolicy.objects.get().compute, self.c1)
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.post(scope="tag", 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):
+ def test_the_vms_chosen_are_those_of_the_scope_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}):
+ for fields in ({}, {"scope": "compute"}, {"scope": "tag", "compute": self.c1.pk}):
with self.subTest(fields):
response = self.post(**fields)
self.assertEqual(response.status_code, 200)
- self.assertContains(response, "Choose a compute, VMs or a tag: one of them")
+ self.assertContains(response, "Choose the VMs to back up" if fields else "This field is required")
self.assertFalse(BackupPolicy.objects.exists())
+ # a VM gone from another scope's (hidden) field is no error
+ self.post(scope="compute", compute=self.c1.pk, instances=[99999])
+ self.assertEqual(BackupPolicy.objects.get().compute, self.c1)
+ BackupPolicy.objects.all().delete()
+ # a choice left in another scope's field is not saved
+ self.post(scope="instances", instances=[self.vm1.pk], compute=self.c1.pk, tag=prod.pk)
+ policy = BackupPolicy.objects.get()
+ self.assertEqual((list(policy.instances.all()), policy.compute, policy.tag), ([self.vm1], None, None))
def test_vms_on_a_host_without_the_target_are_refused(self):
- response = self.post(instances=[self.vm3.pk])
+ response = self.post(scope="instances", instances=[self.vm3.pk])
self.assertContains(response, "has no storage pool on h2")
- response = self.post(compute=self.c2.pk)
+ response = self.post(scope="compute", 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.assertContains(self.post(scope="tag", 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):
@@ -84,10 +91,10 @@ class PolicyPageTests(TestCase):
self.assertTrue(new.xpath("//input[@name='name']"))
def test_keep_and_full_every_at_least_one(self):
- self.assertEqual(self.post(instances=[self.vm1.pk], keep="0").status_code, 200)
- self.assertEqual(self.post(instances=[self.vm1.pk], full_every="0").status_code, 200)
+ self.assertEqual(self.post(scope="instances", instances=[self.vm1.pk], keep="0").status_code, 200)
+ self.assertEqual(self.post(scope="instances", instances=[self.vm1.pk], full_every="0").status_code, 200)
self.assertFalse(BackupPolicy.objects.exists())
- self.post(instances=[self.vm1.pk], full_every="7")
+ self.post(scope="instances", instances=[self.vm1.pk], full_every="7")
self.assertEqual(BackupPolicy.objects.get().full_every, 7)
def schedule(self):
@@ -104,7 +111,7 @@ class PolicyPageTests(TestCase):
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", "keep_weekly": "4",
- "keep_monthly": "6", "full_every": "1", "instances": [self.vm1.pk]})
+ "keep_monthly": "6", "full_every": "1", "scope": "instances", "instances": [self.vm1.pk]})
policy.refresh_from_db()
self.assertEqual((policy.time, policy.keep, policy.keep_weekly, policy.keep_monthly, policy.enabled),
(datetime.time(3, 30), 3, 4, 6, False))
diff --git a/vmbackups/urls.py b/vmbackups/urls.py
index c3bef27f..2a19005b 100644
--- a/vmbackups/urls.py
+++ b/vmbackups/urls.py
@@ -16,6 +16,7 @@ urlpatterns = [
path("schedules//", views.policy, name="policy"),
path("targets/", views.targets, name="targets"),
path("targets/new/", views.target_new, name="target_new"),
+ path("computes//pools/", views.pools, name="pools"),
path("targets//", views.target, name="target"),
path("vm//create/", views.create, name="create"),
]
diff --git a/vmbackups/views.py b/vmbackups/views.py
index 2480f7ca..9b37395c 100644
--- a/vmbackups/views.py
+++ b/vmbackups/views.py
@@ -7,6 +7,7 @@ from django.db import transaction
from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Count
+from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
@@ -14,8 +15,10 @@ from django.views.decorators.http import require_POST
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext_noop
from libvirt import libvirtError
+from lxml import etree
from admin.decorators import superuser_only
+from computes.models import Compute
from instances.jobs import unprotected
from instances.models import Instance, InstanceTombstone
from instances.views import get_instance
@@ -194,6 +197,22 @@ def create(request, instance_id):
return redirect(page)
+@superuser_only
+def pools(request, compute_id):
+ """The compute's active pools that keep disks as files (vrtManager file_pools: where a restore
+ copies them), each with its type, for a form's pool suggestions (pool_choices.js); ?types=dir,netfs
+ keeps those types only. Read as they are, not refreshed; none from a host not reached."""
+ compute = get_object_or_404(Compute, pk=compute_id)
+ types = request.GET.get("types", "").split(",")
+ try:
+ found = [{"name": name, "type": etree.fromstring(pool.XMLDesc(0)).get("type")}
+ for name, (pool, _path) in wvmConnect(compute.hostname, compute.login, compute.password,
+ compute.type).file_pools().items()]
+ except libvirtError:
+ found = []
+ return JsonResponse([p for p in sorted(found, key=lambda p: p["name"]) if not types[0] or p["type"] in types], safe=False)
+
+
@superuser_only
def index(request):
"""Every backup, newest first; filtered by VM name, target and state."""
diff --git a/webvirtcloud/bootstrap.py b/webvirtcloud/bootstrap.py
index b9707382..011d7470 100644
--- a/webvirtcloud/bootstrap.py
+++ b/webvirtcloud/bootstrap.py
@@ -1,12 +1,26 @@
"""django-bootstrap5's field renderer, marking only the fields in error."""
+from django.db.models.fields import BLANK_CHOICE_DASH
+from django.forms import ModelChoiceField
+from django.utils.translation import gettext_lazy as _
from django_bootstrap5.renderers import FieldRenderer as BootstrapFieldRenderer
+DASH = BLANK_CHOICE_DASH[0][1]
+
class FieldRenderer(BootstrapFieldRenderer):
"""A sent form marks its fields in error red and leaves the others as
they were: a green "valid" mark on a form that was not saved reads as if
- it had been."""
+ it had been. A list's empty choice says to choose, not Django's dashes."""
+
+ def __init__(self, field, **kwargs):
+ super().__init__(field, **kwargs)
+ form_field = getattr(field, "field", None) # the form's field, its own copy for this form
+ if isinstance(form_field, ModelChoiceField):
+ if form_field.empty_label == DASH:
+ form_field.empty_label = _("Choose…")
+ elif any(label == DASH for _value, label in getattr(form_field, "choices", ())):
+ form_field.choices = [(value, _("Choose…") if label == DASH else label) for value, label in form_field.choices]
def get_server_side_validation_classes(self):
return "is-invalid" if self.field_errors else ""
diff --git a/webvirtcloud/settings.py b/webvirtcloud/settings.py
index ba81da6d..d38210d3 100644
--- a/webvirtcloud/settings.py
+++ b/webvirtcloud/settings.py
@@ -250,7 +250,8 @@ USE_I18N = True
USE_TZ = True
# a sent form marks only its fields in error (django-bootstrap5 marks the others green)
-BOOTSTRAP5 = {"field_renderers": {"default": "webvirtcloud.bootstrap.FieldRenderer"}}
+# a field's label is above it, not again in it
+BOOTSTRAP5 = {"field_renderers": {"default": "webvirtcloud.bootstrap.FieldRenderer"}, "set_placeholder": False}
STATIC_URL = "/static/"