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

feat(instances): a superuser tags the VMs chosen on the VM list

Tagging many VMs took each one's Settings tab. The VM list's bulk form now
has, for a superuser, a tag box (every tag offered) with Add tag and Remove
tag: under the ownership lock the tag is checked as on the Settings tab,
made if new, and added to (or removed from) the chosen VMs that lack (or
have) it, each with its own log row. Enter in the tag box sends nothing (it
would press Start, the form's first button); only the two tag actions are
taken, and none of the chosen VMs left makes no tag.
This commit is contained in:
catborise 2026-11-20 12:37:26 +03:00
parent 640511cfd4
commit 5c169ca504
10 changed files with 540 additions and 338 deletions

View file

@ -71,6 +71,15 @@
<button type="submit" class="btn btn-outline-danger" name="action" value="force_off" disabled
data-confirm="{% trans "Force off the chosen VMs? They stop at once, as if unplugged, and may lose unsaved data." %}">{% trans "Force off" %}</button>
</div>
{% if request.user.is_superuser %}
{# tags are a superuser's, as on the VM's Settings tab #}
<div class="input-group input-group-sm w-auto">
<input class="form-control" type="text" name="tag" id="bulk-tag" list="bulk-tag-names" placeholder="{% trans "Tag" %}" aria-label="{% trans "Tag" %}" style="width: 9rem">
<datalist id="bulk-tag-names">{% for tag in tag_names %}<option value="{{ tag }}">{% endfor %}</datalist>
<button type="submit" class="btn btn-outline-primary" name="action" value="tag_add" formaction="{% url 'instances:bulk_tag' %}" disabled>{% trans "Add tag" %}</button>
<button type="submit" class="btn btn-outline-secondary" name="action" value="tag_remove" formaction="{% url 'instances:bulk_tag' %}" disabled>{% trans "Remove tag" %}</button>
</div>
{% endif %}
</form>
{% endif %}
<div id="filter-status" class="visually-hidden" role="status" data-text="{% trans "%(shown)s of %(all)s VMs match" %}"></div>

View file

@ -197,7 +197,7 @@ class BulkPowerTestCase(TransactionTestCase):
self.assertEqual(sorted(int(box.get("value")) for box in boxes), [vm.pk for vm in self.vms])
(form,) = page.xpath("//form[@id='bulk-power']")
self.assertEqual(form.get("action"), reverse("instances:bulk_power"))
self.assertEqual(form.xpath(".//button[@name='action']/@value"), ["start", "shutdown", "force_off"])
self.assertEqual(form.xpath(".//button[@name='action'][not(@formaction)]/@value"), ["start", "shutdown", "force_off"])
# an owner: a box on their own VM only
owner = get_user_model().objects.create_user("bp-lister", password="pw")
UserInstance.objects.create(instance=self.vms[1], user=owner)

View file

@ -0,0 +1,80 @@
"""A superuser adds a tag to, or removes it from, the VMs chosen on the VM
list, with a log row for each VM it changes; owners have no such buttons."""
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase
from django.urls import reverse
from lxml import html
from accounts.models import UserInstance
from computes.models import Compute, Tag
from instances.models import Instance
from logs.models import Logs
class BulkTagTestCase(TestCase):
def setUp(self):
self.client.force_login(get_user_model().objects.create_superuser("bt-admin", "bt@example.com", "pw"))
compute = Compute.objects.create(name="bt-host", hostname="127.0.0.1", login="", password="", type=4)
self.vms = [Instance.objects.create(compute=compute, name=f"bt-vm{n}", uuid=f"00000000-0000-4000-8000-00000000010{n}")
for n in (1, 2)]
# the list page asks each VM's host: not this machine's libvirt, whose last error would reach other tests
patch.object(Instance, "proxy", property(lambda vm: MagicMock(**{"get_status.return_value": 5}))).start()
self.addCleanup(patch.stopall)
def post(self, action, tag, vms):
self.client.cookies.pop("messages", None)
response = self.client.post(reverse("instances:bulk_tag"), {"action": action, "tag": tag,
"vm": [vm.pk for vm in vms]})
return [str(m) for m in get_messages(response.wsgi_request)]
def vm_tags(self):
return [sorted(vm.tags.values_list("name", flat=True)) for vm in self.vms]
def test_added_and_removed_with_a_row_for_each_vm_changed(self):
self.vms[0].tags.add(Tag.objects.create(name="web"))
self.assertEqual(self.post("tag_add", " Web ", self.vms), ["Tag web added to 1 VM"]) # vm1 had it
self.assertEqual(self.vm_tags(), [["web"], ["web"]])
self.assertEqual(self.post("tag_remove", "web", self.vms), ["Tag web removed from 2 VMs"])
self.assertEqual(self.vm_tags(), [[], []])
rows = list(Logs.objects.filter(instance__startswith="bt-vm").order_by("pk").values_list("instance", "message"))
self.assertEqual([(vm, message.split(": ")[-1]) for vm, message in rows],
[("bt-vm2", "tag web"), ("bt-vm1", "untag web"), ("bt-vm2", "untag web")])
def test_a_wrong_name_or_unknown_tag_is_refused(self):
self.assertEqual(self.post("tag_add", "", self.vms), ["Choose the VMs and write the tag"])
self.assertIn("A tag is letters a-z", self.post("tag_add", "no spaces", self.vms)[0])
self.assertEqual(self.post("tag_remvoe", "web", self.vms), ["Choose the VMs and write the tag"]) # no add
self.assertEqual(self.post("tag_remove", "none", self.vms), ["There is no tag none"])
self.assertEqual(self.vm_tags(), [[], []])
Instance.objects.filter(pk__in=[vm.pk for vm in self.vms]).delete()
self.assertEqual(self.post("tag_add", "fresh", self.vms), ["Choose the VMs and write the tag"]) # VMs gone
self.assertFalse(Tag.objects.exists()) # none made by a refusal
def test_owners_may_not(self):
owner = get_user_model().objects.create_user("bt-owner", password="pw")
UserInstance.objects.create(instance=self.vms[0], user=owner)
self.client.force_login(owner)
response = self.client.post(reverse("instances:bulk_tag"), {"action": "tag_add", "tag": "web", "vm": [self.vms[0].pk]})
self.assertEqual(response.status_code, 403)
with patch("instances.views.utils.vm_states", return_value={}), \
patch("instances.views.refresh_instance_database"), patch("instances.views.utils.read_list_rows"):
page = html.fromstring(self.client.get(reverse("instances:index")).content)
self.assertFalse(page.xpath("//button[@formaction]"))
def test_the_list_offers_them_to_a_superuser(self):
with patch("instances.views.utils.vm_states", return_value={}), \
patch("instances.views.refresh_instance_database"), patch("instances.views.utils.read_list_rows"):
page = html.fromstring(self.client.get(reverse("instances:index")).content)
(form,) = page.xpath("//form[@id='bulk-power']")
self.assertEqual(form.xpath(".//button[@formaction]/@value"), ["tag_add", "tag_remove"])
self.assertEqual(set(form.xpath(".//button[@formaction]/@formaction")), {reverse("instances:bulk_tag")})
self.assertTrue(form.xpath(".//input[@name='tag']"))
# every tag offered, also one no VM has
Tag.objects.create(name="hosts-only")
with patch("instances.views.utils.vm_states", return_value={}), \
patch("instances.views.refresh_instance_database"), patch("instances.views.utils.read_list_rows"):
page = html.fromstring(self.client.get(reverse("instances:index")).content)
self.assertEqual(page.xpath("//datalist[@id='bulk-tag-names']/option/@value"), ["hosts-only"])

View file

@ -13,6 +13,7 @@ urlpatterns = [
path("flavor/<int:pk>/delete/", views.flavor_delete, name="flavor_delete"),
path("<int:pk>/", views.instance, name="instance"),
path("bulk_power/", views.bulk_power, name="bulk_power"),
path("bulk_tag/", views.bulk_tag, name="bulk_tag"),
path("<int:pk>/poweron/", views.poweron, name="poweron"),
path("<int:pk>/powercycle/", views.powercycle, name="powercycle"),
path("<int:pk>/poweroff/", views.poweroff, name="poweroff"),

View file

@ -133,6 +133,8 @@ def index(request):
"tags": Tag.counts(instances),
"states_url": reverse("instances:states"), "vm_states": vm_states,
# the VMs this user may power (_power_instance): theirs, or every one for a superuser
# a superuser's bulk tag box offers every tag, as the Settings tab's picker
"tag_names": list(Tag.objects.order_by("name").values_list("name", flat=True)) if request.user.is_superuser else [],
"powerable": {i.pk for i in instances} if request.user.is_superuser else
set(UserInstance.objects.filter(user=request.user).values_list("instance_id", flat=True))},
)
@ -703,6 +705,45 @@ def _power_instance(user, pk):
BULK_POWER_MAX = 500
def _chosen_vms(request):
"""The VMs chosen on the VM list (its bulk form's boxes), as ids, each once."""
return list(dict.fromkeys(int(pk) for pk in request.POST.getlist("vm") if pk.isascii() and pk.isdigit() and len(pk) <= 10))
@require_POST
@superuser_only
def bulk_tag(request):
"""Adds a tag to, or removes it from, the VMs chosen on the VM list, as each VM's Settings tab
does: a log row for each VM changed, not while the VM's tags are kept or given back (forget)
nor while a tag is renamed or deleted (the tag checked under the same lock)."""
action, vms = request.POST.get("action"), _chosen_vms(request)
if action not in ("tag_add", "tag_remove") or not vms:
messages.error(request, _("Choose the VMs and write the tag"))
return redirect("instances:index")
remove, changed = action == "tag_remove", 0
with transaction.atomic():
lock_ownership()
form = TagsForm({"tags": [request.POST.get("tag", "")]})
instances = Instance.objects.filter(pk__in=vms).select_related("compute")
if not form.is_valid() or not form.cleaned_data["tags"] or not instances.exists():
messages.error(request, " ".join(form.errors.get("tags", [])) or _("Choose the VMs and write the tag"))
return redirect("instances:index")
(name,) = form.cleaned_data["tags"]
tag = Tag.objects.filter(name=name).first() if remove else Tag.named([name])[0]
if tag is None:
messages.error(request, _("There is no tag %(tag)s") % {"tag": name})
return redirect("instances:index")
# those it changes: with the tag to remove it from, without it to add it
for instance in instances.filter(tags=tag) if remove else instances.exclude(tags=tag):
with audit_vm(request, instance, f"{'untag' if remove else 'tag'} {name}"):
(instance.tags.remove if remove else instance.tags.add)(tag)
changed += 1
text = (ngettext("Tag %(tag)s removed from %(count)s VM", "Tag %(tag)s removed from %(count)s VMs", changed) if remove
else ngettext("Tag %(tag)s added to %(count)s VM", "Tag %(tag)s added to %(count)s VMs", changed))
messages.success(request, text % {"tag": name, "count": changed})
return redirect("instances:index")
@require_POST
def bulk_power(request):
"""Starts, shuts down or forces off the VMs chosen on the VM list: a job each
@ -712,7 +753,7 @@ def bulk_power(request):
from instances.jobs import POWER # instances.jobs imports this module
action, key = request.POST.get("action", ""), request.POST.get("submission_key", "")
vms = list(dict.fromkeys(int(pk) for pk in request.POST.getlist("vm") if pk.isascii() and pk.isdigit() and len(pk) <= 10))
vms = _chosen_vms(request)
if action not in POWER or not vms or not KEY_RE.fullmatch(key) or len(key) > 50:
messages.error(request, _("Choose the VMs you may power, and Start, Shut down or Force off"))
return redirect("instances:index")

Binary file not shown.

File diff suppressed because it is too large Load diff

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -39,6 +39,15 @@
later = setTimeout(update, 50);
}).observe(document.querySelector(".table-responsive") || document.body,
{attributes: true, attributeFilter: ["hidden", "class"], subtree: true});
// Enter in the tag box would send the form with its first button, Start: it sends nothing
var tagBox = document.getElementById("bulk-tag");
if (tagBox) {
tagBox.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
event.preventDefault();
}
});
}
form.addEventListener("submit", function () {
document.querySelectorAll("input[name='vm'][form='bulk-power']:checked").forEach(function (box) {
if (!box.getClientRects().length) {