mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 08:56:07 +00:00
fix(ui): forms ask one thing at a time, offer the host's pools and say less twice
- A backup schedule asks Which VMs first (a compute's, chosen VMs or a tag's) and shows that one field only (policy_scope.js); the other two are not read, so a choice left in them is neither saved nor an error. - A backup target's, a restore's and a disk restore's storage pool field offers the chosen compute's active file pools, the ones a restore copies into (a target's: directory and NFS only), from vmbackups.views.pools, which reads them without a refresh (pool_choices.js); a name can still be typed and is checked as before. - A field's label is no longer repeated inside it as a placeholder, and a list's empty choice says Choose… instead of Django's dashes (webvirtcloud.bootstrap.FieldRenderer). - The schedule, target, e-mail OTP and VM delete forms put Cancel and their main button at the right, as the other forms do.
This commit is contained in:
parent
7359fbb147
commit
4881c3cd3e
23 changed files with 228 additions and 69 deletions
|
|
@ -21,9 +21,9 @@
|
|||
</form>
|
||||
</div>
|
||||
<div class="card-footer">
|
||||
<div class="mb-0 float-end">
|
||||
<a class="btn btn-primary" href="#" data-history-back>{% bs_icon 'arrow-left' %} {% trans "Cancel" %}</a>
|
||||
<button type="submit" form="create-update" class="btn btn-success">
|
||||
<div class="d-flex justify-content-end gap-2">
|
||||
<a class="btn btn-outline-secondary" href="#" data-history-back>{% trans "Cancel" %}</a>
|
||||
<button type="submit" form="create-update" class="btn btn-primary">
|
||||
{% bs_icon 'envelope-open' %} {% trans "Send" %}
|
||||
</button>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@
|
|||
{% endif %}
|
||||
<div class="border-top pt-3 d-flex flex-wrap align-items-center gap-2">
|
||||
<span class="small text-danger me-auto">{% trans "This cannot be undone." %}</span>
|
||||
<a class="btn btn-secondary" href="{% url 'instances:instance' instance.id %}">{% trans "Cancel" %}</a>
|
||||
<a class="btn btn-outline-secondary" href="{% url 'instances:instance' instance.id %}">{% trans "Cancel" %}</a>
|
||||
<button class="btn btn-danger" type="submit" name="delete">{% trans "Destroy VM" %}</button>
|
||||
</div>
|
||||
</form>
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -10522,14 +10522,6 @@ msgstr "Yedek hedefi"
|
|||
msgid "Every VM of a compute"
|
||||
msgstr "Bir sunucunun bütün sanal makineleri"
|
||||
|
||||
#: vmbackups/forms.py:83
|
||||
msgid "Or these VMs"
|
||||
msgstr "Ya da bu sanal makineler"
|
||||
|
||||
#: vmbackups/forms.py:83
|
||||
msgid "Or every VM with a tag"
|
||||
msgstr "Ya da bir etiketin bütün sanal makineleri"
|
||||
|
||||
#: vmbackups/forms.py:83 vmbackups/templates/vmbackups/policies.html:17
|
||||
msgid "Daily at"
|
||||
msgstr "Her gün saat"
|
||||
|
|
@ -10577,10 +10569,6 @@ msgstr ""
|
|||
"1: her yedek tamdır. 1'den büyükse aradaki yedekler yalnızca değişenleri "
|
||||
"kopyalar (qcow2 diskli, çalışan VM'ler)."
|
||||
|
||||
#: vmbackups/forms.py:109
|
||||
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:119 vmbackups/jobs.py:115
|
||||
#, python-format
|
||||
msgid "Backup target %(target)s has no storage pool on %(compute)s"
|
||||
|
|
@ -13162,3 +13150,19 @@ msgstr "Oturumunuz kapandı: bu sayfa artık güncellenmiyor."
|
|||
#: templates/base.html
|
||||
msgid "Sign in again"
|
||||
msgstr "Yeniden giriş yapın"
|
||||
|
||||
#: vmbackups/forms.py
|
||||
msgid "These VMs"
|
||||
msgstr "Bu sanal makineler"
|
||||
|
||||
#: vmbackups/forms.py
|
||||
msgid "Every VM with a tag"
|
||||
msgstr "Bir etiketin bütün sanal makineleri"
|
||||
|
||||
#: vmbackups/forms.py
|
||||
msgid "Which VMs"
|
||||
msgstr "Hangi sanal makineler"
|
||||
|
||||
#: vmbackups/forms.py
|
||||
msgid "Choose the VMs to back up"
|
||||
msgstr "Yedeklenecek sanal makineleri seçin"
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -9904,14 +9904,6 @@ msgstr "备份目标"
|
|||
msgid "Every VM of a compute"
|
||||
msgstr "某计算节点的所有虚拟机"
|
||||
|
||||
#: vmbackups/forms.py:83
|
||||
msgid "Or these VMs"
|
||||
msgstr "或这些虚拟机"
|
||||
|
||||
#: vmbackups/forms.py:83
|
||||
msgid "Or every VM with a tag"
|
||||
msgstr "或带某个标签的所有虚拟机"
|
||||
|
||||
#: vmbackups/forms.py:83 vmbackups/templates/vmbackups/policies.html:17
|
||||
msgid "Daily at"
|
||||
msgstr "每天时间"
|
||||
|
|
@ -9956,10 +9948,6 @@ msgid ""
|
|||
"(running VMs with qcow2 disks)."
|
||||
msgstr "1:每次备份都是完整备份。大于 1 时,中间的备份只复制变化的部分(适用于使用 qcow2 磁盘的运行中虚拟机)。"
|
||||
|
||||
#: vmbackups/forms.py:109
|
||||
msgid "Choose a compute, VMs or a tag: one of them"
|
||||
msgstr "选择一个计算节点、若干虚拟机或一个标签:只选其一"
|
||||
|
||||
#: vmbackups/forms.py:119 vmbackups/jobs.py:115
|
||||
#, python-format
|
||||
msgid "Backup target %(target)s has no storage pool on %(compute)s"
|
||||
|
|
@ -12333,3 +12321,19 @@ msgstr "您已退出登录:此页面不再更新。"
|
|||
#: templates/base.html
|
||||
msgid "Sign in again"
|
||||
msgstr "重新登录"
|
||||
|
||||
#: vmbackups/forms.py
|
||||
msgid "These VMs"
|
||||
msgstr "这些虚拟机"
|
||||
|
||||
#: vmbackups/forms.py
|
||||
msgid "Every VM with a tag"
|
||||
msgstr "带有某标签的所有虚拟机"
|
||||
|
||||
#: vmbackups/forms.py
|
||||
msgid "Which VMs"
|
||||
msgstr "哪些虚拟机"
|
||||
|
||||
#: vmbackups/forms.py
|
||||
msgid "Choose the VMs to back up"
|
||||
msgstr "请选择要备份的虚拟机"
|
||||
|
|
|
|||
|
|
@ -1,8 +0,0 @@
|
|||
<?xml version="1.0" ?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-left" viewBox="0 0 16 16">
|
||||
|
||||
|
||||
<path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/>
|
||||
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 342 B |
|
|
@ -1,12 +1,21 @@
|
|||
from django import forms
|
||||
from django.urls import reverse
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from computes.models import Compute
|
||||
from instances.models import Instance
|
||||
|
||||
from vrtManager.backup import TARGET_TYPES
|
||||
|
||||
from .models import BackupPolicy, BackupTarget
|
||||
|
||||
|
||||
def offer_pools(field, types=()):
|
||||
"""The pool field offers the chosen compute's active file pools (of these types), as
|
||||
pool_choices.js reads them (views.pools); a name can still be typed."""
|
||||
field.widget.attrs["data-pools"] = reverse("vmbackups:pools", args=[0]) + "?types=" + ",".join(types)
|
||||
|
||||
|
||||
class TargetPoolForm(forms.Form):
|
||||
"""A compute's storage pool for a target; computes that have one already are not offered."""
|
||||
|
||||
|
|
@ -15,6 +24,7 @@ class TargetPoolForm(forms.Form):
|
|||
|
||||
def __init__(self, *args, target=None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
offer_pools(self.fields["pool"], TARGET_TYPES)
|
||||
if target is not None:
|
||||
self.fields["compute"].queryset = Compute.objects.exclude(backuptargetpool__target=target)
|
||||
|
||||
|
|
@ -45,6 +55,7 @@ class RestoreForm(forms.Form):
|
|||
super().__init__(*args, **kwargs)
|
||||
self.fields["compute"].queryset = Compute.objects.filter(backuptargetpool__target=backup.target).order_by("name")
|
||||
self.fields["name"].initial = f"{backup.vm_name}-restored"
|
||||
offer_pools(self.fields["pool"])
|
||||
if backup.instance_id: # the VM's host, when it has the target's pool
|
||||
self.fields["compute"].initial = self.fields["compute"].queryset.filter(instance=backup.instance_id).first()
|
||||
if place: # a VM owner's: the VM's compute and pool, shown on the page
|
||||
|
|
@ -63,6 +74,7 @@ class RestoreDiskForm(forms.Form):
|
|||
super().__init__(*args, **kwargs)
|
||||
disks = list(backup.files.filter(role="disk").order_by("dev"))
|
||||
self.fields["dev"].choices = [(d.dev, d.dev) for d in disks]
|
||||
offer_pools(self.fields["pool"])
|
||||
self.fields["compute"].queryset = Compute.objects.filter(backuptargetpool__target=backup.target).order_by("name")
|
||||
if backup.instance_id: # the VM's host, when it has the target's pool
|
||||
self.fields["compute"].initial = self.fields["compute"].queryset.filter(instance=backup.instance_id).first()
|
||||
|
|
@ -72,15 +84,19 @@ class RestoreDiskForm(forms.Form):
|
|||
|
||||
|
||||
class PolicyForm(forms.ModelForm):
|
||||
"""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)."""
|
||||
"""A backup schedule: a compute's VMs, chosen VMs or a tag's VMs, as scope says, all on
|
||||
hosts that have a pool of its target (a tag's: those that have it now). The fields of
|
||||
the other two are not read: a choice left in them is not saved."""
|
||||
|
||||
SCOPES = {"compute": _("Every VM of a compute"), "instances": _("These VMs"), "tag": _("Every VM with a tag")}
|
||||
scope = forms.ChoiceField(label=_("Which VMs"), choices=SCOPES.items(), widget=forms.RadioSelect, initial="compute")
|
||||
|
||||
class Meta:
|
||||
model = BackupPolicy
|
||||
fields = ["name", "target", "compute", "instances", "tag", "time", "keep", "keep_weekly", "keep_monthly", "full_every",
|
||||
fields = ["name", "target", "scope", "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"),
|
||||
labels = {"name": _("Name"), "target": _("Backup target"), "compute": _("Compute"),
|
||||
"instances": _("VMs"), "tag": _("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")}
|
||||
|
|
@ -89,6 +105,15 @@ class PolicyForm(forms.ModelForm):
|
|||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
if self.is_bound: # the other scopes' fields, hidden, are not read: a VM deleted meanwhile is no error there
|
||||
self.data = self.data.copy()
|
||||
for name in ("compute", "instances", "tag"):
|
||||
if name != self.data.get("scope"):
|
||||
self.data.pop(name, None)
|
||||
if self.instance.tag_id:
|
||||
self.fields["scope"].initial = "tag"
|
||||
elif self.instance.pk and not self.instance.compute_id:
|
||||
self.fields["scope"].initial = "instances"
|
||||
self.fields["instances"].queryset = Instance.objects.filter(is_template=False).select_related("compute").order_by(
|
||||
"name")
|
||||
self.fields["instances"].label_from_instance = lambda vm: f"{vm.name} ({vm.compute.name})"
|
||||
|
|
@ -104,10 +129,11 @@ class PolicyForm(forms.ModelForm):
|
|||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
scope = data.get("scope")
|
||||
if scope and not data.get(scope):
|
||||
self.add_error(scope, _("Choose the VMs to back up"))
|
||||
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:
|
||||
if target is not None and (compute or vms or tag):
|
||||
if compute:
|
||||
hosts = {compute}
|
||||
elif tag:
|
||||
|
|
|
|||
12
vmbackups/static/vmbackups/policy_scope.js
Normal file
12
vmbackups/static/vmbackups/policy_scope.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
// A backup schedule's Which VMs: only the field of the choice made shows (vmbackups.forms.PolicyForm).
|
||||
(function () {
|
||||
var choices = document.querySelectorAll("input[name='scope']");
|
||||
function show() {
|
||||
var chosen = document.querySelector("input[name='scope']:checked");
|
||||
document.querySelectorAll("[data-scope]").forEach(function (field) {
|
||||
field.hidden = !chosen || field.dataset.scope !== chosen.value;
|
||||
});
|
||||
}
|
||||
choices.forEach(function (choice) { choice.addEventListener("change", show); });
|
||||
show();
|
||||
})();
|
||||
23
vmbackups/static/vmbackups/pool_choices.js
Normal file
23
vmbackups/static/vmbackups/pool_choices.js
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
// A form's storage pool field (data-pools: compute 0's pool list, vmbackups.views.pools) offers
|
||||
// the pools of the compute chosen in the same form. A name can still be typed: the server checks it
|
||||
// as before. An answer for a compute no longer chosen is left out.
|
||||
document.querySelectorAll("input[data-pools]").forEach(function (input) {
|
||||
var compute = input.form.elements.compute;
|
||||
if (!compute) return;
|
||||
var list = document.createElement("datalist");
|
||||
list.id = input.id + "-choices";
|
||||
input.after(list);
|
||||
input.setAttribute("list", list.id);
|
||||
input.setAttribute("autocomplete", "off");
|
||||
function offer() {
|
||||
var asked = compute.value;
|
||||
list.replaceChildren();
|
||||
if (!asked) return;
|
||||
$.getJSON(input.dataset.pools.replace("/0/", "/" + encodeURIComponent(asked) + "/")).done(function (pools) {
|
||||
if (compute.value !== asked) return;
|
||||
list.replaceChildren.apply(list, pools.map(function (pool) { return new Option(pool.name); }));
|
||||
});
|
||||
}
|
||||
compute.addEventListener("change", offer);
|
||||
offer();
|
||||
});
|
||||
|
|
@ -53,4 +53,5 @@
|
|||
{% block script %}
|
||||
<script src="{% static 'js/tom-select.complete.min.js' %}"></script>
|
||||
<script src="{% static 'js/searchable_select.js' %}"></script>
|
||||
<script src="{% static 'vmbackups/policy_scope.js' %}"></script>
|
||||
{% endblock %}
|
||||
|
|
|
|||
|
|
@ -4,11 +4,14 @@
|
|||
{% bootstrap_form_errors form type="non_fields" %}
|
||||
{% bootstrap_field form.name %}
|
||||
{% bootstrap_field form.target %}
|
||||
<div class="row g-2">
|
||||
<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>
|
||||
{# one of the three, as Which VMs says; policy_scope.js shows its field only #}
|
||||
<fieldset class="mb-3">
|
||||
<legend class="form-label fs-6">{{ form.scope.label }}</legend>
|
||||
{% bootstrap_field form.scope show_label=False wrapper_class="" %}
|
||||
</fieldset>
|
||||
<div data-scope="compute">{% bootstrap_field form.compute %}</div>
|
||||
<div data-scope="instances">{% bootstrap_field form.instances %}</div>
|
||||
<div data-scope="tag">{% bootstrap_field form.tag %}</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.full_every %}</div>
|
||||
|
|
@ -21,6 +24,8 @@
|
|||
{% 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 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>
|
||||
<div class="d-flex justify-content-end gap-2">
|
||||
<a class="btn btn-outline-secondary" href="{% url 'vmbackups:policies' %}">{% trans "Cancel" %}</a>
|
||||
<button type="submit" class="btn btn-primary">{% trans "Save" %}</button>
|
||||
</div>
|
||||
</form>
|
||||
|
|
|
|||
|
|
@ -15,4 +15,5 @@
|
|||
{% block script %}
|
||||
<script src="{% static 'js/tom-select.complete.min.js' %}"></script>
|
||||
<script src="{% static 'js/searchable_select.js' %}"></script>
|
||||
<script src="{% static 'vmbackups/policy_scope.js' %}"></script>
|
||||
{% endblock %}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
{% load bootstrap_icons %}
|
||||
{% load django_bootstrap5 %}
|
||||
{% load operations %}
|
||||
|
|
@ -22,3 +23,4 @@
|
|||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block script %}<script src="{% static 'vmbackups/pool_choices.js' %}"></script>{% endblock %}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
{% load bootstrap_icons %}
|
||||
{% load django_bootstrap5 %}
|
||||
{% load operations %}
|
||||
|
|
@ -21,3 +22,4 @@
|
|||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block script %}<script src="{% static 'vmbackups/pool_choices.js' %}"></script>{% endblock %}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
{% load bootstrap_icons %}
|
||||
{% load django_bootstrap5 %}
|
||||
{% load operations %}
|
||||
|
|
@ -74,3 +75,4 @@
|
|||
</form>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
{% block script %}<script src="{% static 'vmbackups/pool_choices.js' %}"></script>{% endblock %}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
{% load bootstrap_icons %}
|
||||
{% load django_bootstrap5 %}
|
||||
|
||||
|
|
@ -14,9 +15,12 @@
|
|||
<form method="post">
|
||||
{% csrf_token %}
|
||||
{% bootstrap_form form %}
|
||||
<button type="submit" class="btn btn-primary">{% bs_icon 'plus' %} {% trans "Add" %}</button>
|
||||
<a class="btn btn-outline-secondary ms-1" href="{% url 'vmbackups:targets' %}">{% trans "Cancel" %}</a>
|
||||
<div class="d-flex justify-content-end gap-2">
|
||||
<a class="btn btn-outline-secondary" href="{% url 'vmbackups:targets' %}">{% trans "Cancel" %}</a>
|
||||
<button type="submit" class="btn btn-primary">{% bs_icon 'plus' %} {% trans "Add" %}</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block script %}<script src="{% static 'vmbackups/pool_choices.js' %}"></script>{% endblock %}
|
||||
|
|
|
|||
39
vmbackups/tests/test_form_pages.py
Normal file
39
vmbackups/tests/test_form_pages.py
Normal file
|
|
@ -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"<pool type='{kind}'/>")
|
||||
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"])
|
||||
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ urlpatterns = [
|
|||
path("schedules/<int:policy_id>/", views.policy, name="policy"),
|
||||
path("targets/", views.targets, name="targets"),
|
||||
path("targets/new/", views.target_new, name="target_new"),
|
||||
path("computes/<int:compute_id>/pools/", views.pools, name="pools"),
|
||||
path("targets/<int:target_id>/", views.target, name="target"),
|
||||
path("vm/<int:instance_id>/create/", views.create, name="create"),
|
||||
]
|
||||
|
|
|
|||
|
|
@ -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."""
|
||||
|
|
|
|||
|
|
@ -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 ""
|
||||
|
|
|
|||
|
|
@ -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/"
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue