mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 09:26:03 +00:00
feat: a Tags page and tags in the API
Administration gets a Tags page: each tag with how many VMs and hosts have it, renamed (on the VMs, hosts and removed VMs that keep it) or deleted (taken off all of them). Both are logged. The API gives a VM's and a host's tags by name, read only, and its VM and host lists take ?tag= for those with a tag.
This commit is contained in:
parent
11b447f681
commit
f4051213fb
15 changed files with 508 additions and 163 deletions
|
|
@ -12,6 +12,7 @@ from django.utils.translation import gettext_lazy as _
|
|||
from accounts.forms import UniqueEmailMixin
|
||||
from accounts.models import UserAttributes, UserInstance
|
||||
from appsettings.settings import app_settings
|
||||
from computes.models import Tag
|
||||
from instances.models import Instance
|
||||
|
||||
from .models import Permission
|
||||
|
|
@ -49,6 +50,15 @@ def permission_rows(field):
|
|||
return rows
|
||||
|
||||
|
||||
class TagForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Tag
|
||||
fields = ["name"]
|
||||
|
||||
def clean_name(self):
|
||||
return self.cleaned_data["name"].strip().lower()
|
||||
|
||||
|
||||
class GroupForm(forms.ModelForm):
|
||||
permissions = forms.ModelMultipleChoiceField(
|
||||
widget=forms.CheckboxSelectMultiple,
|
||||
|
|
|
|||
40
admin/templates/admin/tag_list.html
Normal file
40
admin/templates/admin/tag_list.html
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
{% load bootstrap_icons %}
|
||||
|
||||
{% block title %}{% trans "Tags" %}{% endblock %}
|
||||
|
||||
{% block page_heading %}{% trans "Tags" %}{% endblock page_heading %}
|
||||
|
||||
{% block content %}
|
||||
<p class="text-body-secondary">{% trans "The tags of VMs and hosts. A tag is made when it is first given, on a VM's Options tab or a host's form." %}</p>
|
||||
{% if not tags %}
|
||||
<div class="alert alert-info shadow-sm">{% bs_icon 'info-circle' %} {% trans "No tags yet" %}</div>
|
||||
{% else %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover align-middle" data-sortable>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{% trans "Tag" %}</th>
|
||||
<th scope="col" data-sort-method="number">{% trans "VMs" %}</th>
|
||||
<th scope="col" data-sort-method="number">{% trans "Hosts" %}</th>
|
||||
<th scope="col" data-sort-method="none"><span class="visually-hidden">{% trans "Actions" %}</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for tag in tags %}
|
||||
<tr>
|
||||
<td><span class="badge text-bg-light border">{% bs_icon 'tag' %} {{ tag }}</span></td>
|
||||
<td>{{ tag.vm_count }}</td>
|
||||
<td>{{ tag.host_count }}</td>
|
||||
<td class="text-end text-nowrap">
|
||||
<a class="btn btn-sm btn-outline-secondary" href="{% url 'admin:tag_update' tag.id %}">{% trans "Rename" %}</a>
|
||||
<a class="btn btn-sm btn-outline-danger" href="{% url 'admin:tag_delete' tag.id %}">{% trans "Delete" %}</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock content %}
|
||||
69
admin/tests/test_tags.py
Normal file
69
admin/tests/test_tags.py
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
"""Superusers rename and delete the tags of VMs and hosts."""
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from computes.models import Compute, Tag
|
||||
from instances.models import Instance, InstanceTombstone
|
||||
from logs.models import Logs
|
||||
|
||||
|
||||
class TagAdminTests(TestCase):
|
||||
def setUp(self):
|
||||
self.client.force_login(User.objects.create_superuser("tg-admin", "tg@example.com", "pw"))
|
||||
self.prod = Tag.objects.create(name="prod")
|
||||
compute = Compute.objects.create(name="tg", hostname="192.0.2.7", login="u", password="p", type=1)
|
||||
compute.tags.add(self.prod)
|
||||
Instance.objects.create(compute=compute, name="vm", uuid="12345678-0000-0000-0000-00000000dd01").tags.add(self.prod)
|
||||
self.tombstone = InstanceTombstone.objects.create(uuid="12345678-0000-0000-0000-00000000dd02", name="gone",
|
||||
tags=["prod", "db"])
|
||||
|
||||
def messages(self):
|
||||
return list(Logs.objects.filter(message__startswith="Tag").order_by("id").values_list("message", flat=True))
|
||||
|
||||
def test_the_list_counts_each_tag_s_vms_and_hosts(self):
|
||||
response = self.client.get(reverse("admin:tag_list"))
|
||||
self.assertEqual([(t.name, t.vm_count, t.host_count) for t in response.context["tags"]], [("prod", 1, 1)])
|
||||
|
||||
def test_a_rename_keeps_the_tag_on_its_vms_hosts_and_removed_vms(self):
|
||||
self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": "Live"})
|
||||
self.prod.refresh_from_db()
|
||||
self.assertEqual(self.prod.name, "live")
|
||||
self.assertEqual(self.prod.instances.count(), 1)
|
||||
self.tombstone.refresh_from_db()
|
||||
self.assertEqual(self.tombstone.tags, ["live", "db"])
|
||||
self.assertEqual(self.messages(), ["Tag prod: rename to live"])
|
||||
|
||||
def test_a_name_taken_or_bad_is_refused(self):
|
||||
Tag.objects.create(name="db")
|
||||
for name in ("DB", "two words"):
|
||||
with self.subTest(name):
|
||||
response = self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": name})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(response.context["form"].errors)
|
||||
self.prod.refresh_from_db()
|
||||
self.assertEqual(self.prod.name, "prod")
|
||||
|
||||
def test_a_delete_takes_it_off_everything(self):
|
||||
self.assertContains(self.client.get(reverse("admin:tag_delete", args=[self.prod.pk])), "1 VM and 1 host")
|
||||
self.client.post(reverse("admin:tag_delete", args=[self.prod.pk]))
|
||||
self.assertFalse(Tag.objects.exists())
|
||||
self.assertFalse(Instance.objects.get(name="vm").tags.exists())
|
||||
self.assertEqual(self.messages(), ["Tag prod: delete"])
|
||||
|
||||
def test_a_deleted_name_made_again_is_not_given_to_a_vm_that_returns(self):
|
||||
self.client.post(reverse("admin:tag_delete", args=[self.prod.pk]))
|
||||
self.tombstone.refresh_from_db()
|
||||
self.assertEqual(self.tombstone.tags, ["db"])
|
||||
|
||||
def test_the_same_name_is_no_rename(self):
|
||||
self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": "PROD"})
|
||||
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]),
|
||||
reverse("admin:tag_delete", args=[self.prod.pk])):
|
||||
self.assertEqual(self.client.post(url, {"name": "x"}).status_code, 403)
|
||||
self.assertEqual(Tag.objects.get().name, "prod")
|
||||
|
|
@ -18,4 +18,7 @@ urlpatterns = [
|
|||
path("logs/export.xlsx", views.logs_export, name="logs_export"),
|
||||
path("removed-vms/", views.tombstone_list, name="tombstone_list"),
|
||||
path("removed-vms/<int:pk>/delete/", views.tombstone_delete, name="tombstone_delete"),
|
||||
path("tags/", views.tag_list, name="tag_list"),
|
||||
path("tags/<int:pk>/update/", views.tag_update, name="tag_update"),
|
||||
path("tags/<int:pk>/delete/", views.tag_delete, name="tag_delete"),
|
||||
]
|
||||
|
|
|
|||
|
|
@ -16,8 +16,10 @@ from django.shortcuts import get_object_or_404, redirect, render
|
|||
from django.utils import timezone
|
||||
from django.utils.http import url_has_allowed_host_and_scheme, urlencode
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.utils.translation import ngettext
|
||||
from django.views.decorators.http import require_POST
|
||||
from django.views.decorators.debug import sensitive_post_parameters
|
||||
from computes.models import Tag
|
||||
from instances.models import InstanceTombstone
|
||||
from instances.report import workbook
|
||||
from logs.audit import audit, changed_fields, snapshot
|
||||
|
|
@ -463,3 +465,57 @@ def tombstone_delete(request, pk):
|
|||
"consequence": _("Its owners no longer get the VM back if its UUID shows up again.")},
|
||||
)
|
||||
|
||||
|
||||
|
||||
@superuser_only
|
||||
def tag_list(request):
|
||||
"""The tags of VMs and hosts, with how many of each have them."""
|
||||
tags = Tag.objects.annotate(vm_count=Count("instances", distinct=True), host_count=Count("computes", distinct=True))
|
||||
return render(request, "admin/tag_list.html", {"tags": list(tags)})
|
||||
|
||||
|
||||
def _retag_removed_vms(old, new):
|
||||
"""The removed VMs' kept tag old named new, or dropped with None: a name
|
||||
made again later must not go to them. Under the ownership lock (computes.utils.forget)."""
|
||||
for tombstone in InstanceTombstone.objects.all():
|
||||
if old in tombstone.tags:
|
||||
if new:
|
||||
tombstone.tags = [new if name == old else name for name in tombstone.tags]
|
||||
else:
|
||||
tombstone.tags = [name for name in tombstone.tags if name != old]
|
||||
tombstone.save(update_fields=["tags"])
|
||||
|
||||
|
||||
@superuser_only
|
||||
def tag_update(request, pk):
|
||||
tag = get_object_or_404(Tag, pk=pk)
|
||||
old = tag.name
|
||||
form = forms.TagForm(request.POST or None, instance=tag)
|
||||
if request.method == "POST" and form.is_valid():
|
||||
if form.cleaned_data["name"] != old:
|
||||
with audit(request, None, f"Tag {old}", f"rename to {form.cleaned_data['name']}"), transaction.atomic():
|
||||
lock_ownership()
|
||||
current = Tag.objects.values_list("name", flat=True).get(pk=pk) # another rename may have come first
|
||||
form.save()
|
||||
_retag_removed_vms(current, tag.name)
|
||||
return redirect("admin:tag_list")
|
||||
return render(request, "common/form.html", {"form": form, "title": _("Rename tag %(tag)s") % {"tag": old}})
|
||||
|
||||
|
||||
@superuser_only
|
||||
def tag_delete(request, pk):
|
||||
tag = get_object_or_404(Tag, pk=pk)
|
||||
if request.method == "POST":
|
||||
with audit(request, None, f"Tag {tag.name}", "delete"), transaction.atomic():
|
||||
lock_ownership()
|
||||
tag.delete()
|
||||
_retag_removed_vms(tag.name, None)
|
||||
messages.success(request, _("Tag %(tag)s deleted") % {"tag": tag.name})
|
||||
return redirect("admin:tag_list")
|
||||
vms, hosts = tag.instances.count(), tag.computes.count()
|
||||
return render(request, "common/confirm_delete.html", {
|
||||
"object": tag,
|
||||
"consequence": _("It is taken off %(vms)s and %(hosts)s.") % {
|
||||
"vms": ngettext("%(count)s VM", "%(count)s VMs", vms) % {"count": vms},
|
||||
"hosts": ngettext("%(count)s host", "%(count)s hosts", hosts) % {"count": hosts}},
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue