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

feat(ui): what a job, a tag or a backup names links to its page

- A job's page and the Jobs list link what the job works on: a VM's
  page for who may see the VM (not when a copy on another host has its
  UUID); a host's, a backup target's, or the Computes page for a bulk
  migration, for a superuser (operations.views.link_resources). A
  backup's or a pool's job has none: a restore names the new VM, and a
  pool may be gone.
- The Tags page's VM and host counts open the VM list or the Computes
  page with that tag only: a list with that tag takes ?tag=name, and
  the address loses it (the rest stays), so the list's own reload keeps
  what is chosen afterwards. The bulk bar sends back to the list's path.
- A Backups row links its target, and a removed VM's badge the Removed
  VMs page while the VM is listed there.
This commit is contained in:
catborise 2026-11-21 23:05:15 +03:00
parent fb81e7adca
commit 2373d73b37
14 changed files with 154 additions and 12 deletions

View file

@ -31,8 +31,9 @@
{% for tag in tags %}
<tr data-search="{{ tag.name }}">
<td>{% include 'common/tag_badge.html' with tag=tag.name %}</td>
<td>{{ tag.vm_count }}</td>
<td>{{ tag.host_count }}</td>
{# the VM list or the Computes page, showing the tag's only #}
<td>{% if tag.vm_count %}<a href="{% url 'instances:index' %}?tag={{ tag.name|urlencode }}">{{ tag.vm_count }}</a>{% else %}0{% endif %}</td>
<td>{% if tag.host_count %}<a href="{% url 'computes' %}?tag={{ tag.name|urlencode }}">{{ tag.host_count }}</a>{% else %}0{% endif %}</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>

View file

@ -63,6 +63,7 @@ class LogsPageTests(TestCase):
self.assertEqual(self.rows(page)[0][1], log.date.strftime("%Y-%m-%d %H:%M:%S"))
def test_a_vm_row_links_the_vm_while_it_is_there(self):
# not its user or host: the row keeps their names, which another may take later
page = self.page(q="alice")
self.assertEqual(page.xpath("//tbody/tr/td/a/@href"), [reverse("instances:instance", args=[self.vm.pk])])
self.vm.delete()

View file

@ -139,6 +139,20 @@ class AdminTestCase(TestCase):
self.assertEqual(said(self.client.post(reverse("admin:tag_update", args=[tag.id]), {"name": "new-name"})),
["Tag old-name renamed to new-name"])
def test_a_tag_s_counts_link_its_vms_and_hosts(self):
from computes.models import Compute, Tag
from instances.models import Instance
host = Compute.objects.create(name="tg-host", hostname="192.0.2.8", login="", password="", type=4)
tag = Tag.objects.create(name="web")
Instance.objects.create(compute=host, name="tg-vm", uuid="00000000-0000-4000-8000-0000000000cc").tags.add(tag)
page = html.fromstring(self.client.get(reverse("admin:tag_list")).content)
self.assertEqual(page.xpath("//tbody//td/a[not(contains(@class, 'btn'))]/@href"), [reverse("instances:index") + "?tag=web"])
host.tags.add(tag)
page = html.fromstring(self.client.get(reverse("admin:tag_list")).content)
self.assertEqual(page.xpath("//tbody//td/a[not(contains(@class, 'btn'))]/@href"),
[reverse("instances:index") + "?tag=web", reverse("computes") + "?tag=web"])
def test_users(self):
response = self.client.get(reverse("admin:user_create"))
self.assertEqual(response.status_code, 200)

View file

@ -22,7 +22,7 @@
{# and shows this bar at the foot of the window while any is chosen #}
<form id="bulk-power" class="fixed-bottom bg-body border-top shadow-lg py-2" action="{% url 'instances:bulk_power' %}" method="post"
aria-label="{% trans "The chosen VMs" %}" hidden>{% csrf_token %}{% submission_key %}
<input type="hidden" name="next" value="{{ request.get_full_path }}">
<input type="hidden" name="next" value="{{ request.path }}">
<div class="container d-flex flex-wrap align-items-center gap-2">
<span class="fw-semibold me-2" id="bulk-power-count" data-text="{% trans "%(count)s chosen" %}"
data-too-many="{% blocktrans with max=bulk_max %}%(count)s chosen: at most {{ max }} at once{% endblocktrans %}" data-max="{{ bulk_max }}" aria-live="polite"></span>

View file

@ -176,13 +176,18 @@ function pillRow(values) {
addEventListener: (name, fn) => { row.click = fn; }};
return row;
}
// runs table_filter.js on a page of these elements, the stored values given; its document click listener
function run(elements, stored) {
// runs table_filter.js on a page of these elements, the stored values given, at an address with
// this query; its document click listener
let replaced = null;
function run(elements, stored, search = "") {
const listeners = {};
const doc = {title: "VMs", getElementById: (id) => elements[id], querySelectorAll: () => [],
addEventListener: (name, fn) => { listeners[name] = fn; }};
const storage = {getItem: (k) => stored[k] || null, setItem: (k, v) => { stored[k] = v; }, removeItem: (k) => { delete stored[k]; }};
vmModule.runInNewContext(fs.readFileSync(process.argv[2], "utf8"), {document: doc, sessionStorage: storage});
const window = {location: {search: search, pathname: "/instances/", hash: ""}};
const history = {replaceState: (state, title, url) => { replaced = url; }};
vmModule.runInNewContext(fs.readFileSync(process.argv[2], "utf8"),
{document: doc, sessionStorage: storage, window: window, history: history, URLSearchParams: URLSearchParams});
return listeners.click;
}
const listPage = () => ({
@ -192,6 +197,21 @@ const listPage = () => ({
"tag-filter": {value: ""},
"tag-pills": pillRow(["", "-", "prod", "web"]),
});
{
// a link to one tag's rows (the Tags page): that tag only, and the address loses it
const stored = {"VMs_filter": "db", "VMs_filter_state": "Off", "VMs_filter_tag": "prod"};
const elements = listPage();
run(elements, stored, "?tag=web&page=2");
assert.deepStrictEqual([elements.filter.value, elements["state-filter"].value, elements["tag-filter"].value], ["", "", "web"]);
assert.strictEqual(stored.VMs_filter, undefined, "the search is not kept either");
assert.strictEqual(replaced, "/instances/?page=2", "the address keeps the rest");
// a tag the list does not have: nothing is changed
replaced = null;
const other = listPage();
const kept = {"VMs_filter": "db"};
run(other, kept, "?tag=gone");
assert.deepStrictEqual([kept.VMs_filter, replaced], ["db", null]);
}
{
const stored = {"VMs_filter_state": "Off", "VMs_filter_tag": "prod"};
const elements = listPage();

View file

@ -15,7 +15,7 @@
<div class="card mb-3">
<div class="card-header">
<div class="d-flex flex-wrap align-items-center gap-2">
<span class="fw-semibold text-break me-auto">{{ job.resource_label }}</span>
<span class="fw-semibold text-break me-auto">{% include "operations/resource_link.html" with url=op.resource_url label=job.resource_label %}</span>
{% include "operations/state_badge.html" with state=op.state %}
</div>
<div class="small text-body-secondary mt-1">{% trans "User" %}: {{ job.username }}</div>

View file

@ -88,9 +88,9 @@
{% endif %}
<div class="small text-body-secondary">{{ op.created_at|date:"Y-m-d H:i:s T" }}{% if request.user.is_superuser %}<span class="d-md-none"> &middot; {{ row.username }}</span>{% endif %}</div>
{# below md the hidden columns show here #}
<div class="d-md-none small">{{ row.resource_label|wrap_at_slash }}</div>
<div class="d-md-none small">{% include "operations/resource_link.html" with url=op.resource_url label=row.resource_label %}</div>
</td>
<td class="d-none d-md-table-cell">{{ row.resource_label|wrap_at_slash }}</td>
<td class="d-none d-md-table-cell">{% include "operations/resource_link.html" with url=op.resource_url label=row.resource_label %}</td>
{% if request.user.is_superuser %}<td class="text-nowrap d-none d-md-table-cell">{{ row.username }}</td>{% endif %}
<td class="text-end">{% include "operations/state_badge.html" with state=op.state %}</td>
</tr>

View file

@ -0,0 +1 @@
{% load operations %}{# what a job works on, a link to its page where it has one (operations.views.link_resources) #}{% if url %}<a href="{{ url }}">{{ label|wrap_at_slash }}</a>{% else %}{{ label|wrap_at_slash }}{% endif %}

View file

@ -93,6 +93,37 @@ class JobsPageTestCase(TransactionTestCase):
Operation.objects.all().delete()
self.assertFalse(page().xpath("//form[@data-filter-form]"))
def test_a_job_links_what_it_works_on_to_who_may_see_it(self):
from types import SimpleNamespace
from accounts.models import UserInstance
from computes.models import Compute
from instances.models import Instance
from operations.views import link_resources
from vmbackups.models import BackupTarget
host = Compute.objects.create(name="lk-host", hostname="192.0.2.9", login="", password="", type=4)
vm = Instance.objects.create(compute=host, name="lk-vm", uuid="00000000-0000-4000-8000-0000000000aa")
target = BackupTarget.objects.create(name="lk-target")
resources = [f"instance:{vm.uuid}", f"compute:{host.pk}", f"pool:{host.pk}:default", f"backup_target:{target.pk}",
"bulk_migrate", "instance:00000000-0000-4000-8000-0000000000bb", "compute:999"]
ops = [SimpleNamespace(resource=r) for r in resources]
link_resources(self.admin, ops)
self.assertEqual([op.resource_url for op in ops], [
reverse("instances:instance", args=[vm.pk]), reverse("overview", args=[host.pk]),
None, reverse("vmbackups:target", args=[target.pk]), reverse("computes"), None, None])
# a copy of the VM on another host has its UUID: neither is linked
Instance.objects.create(compute=Compute.objects.create(name="lk-host2", hostname="192.0.2.10", login="", password="",
type=4), name="lk-vm", uuid=vm.uuid)
link_resources(self.admin, ops)
self.assertIsNone(ops[0].resource_url)
Instance.objects.filter(compute__name="lk-host2").delete()
# an owner: their VM's page only
UserInstance.objects.create(user=self.user, instance=vm)
ops = [SimpleNamespace(resource=r) for r in resources]
link_resources(self.user, ops)
self.assertEqual([op.resource_url for op in ops], [reverse("instances:instance", args=[vm.pk])] + [None] * 6)
def test_a_finished_job_opens_what_it_made(self):
from lxml import html as lxml_html

View file

@ -1,3 +1,4 @@
from collections import Counter
from urllib.parse import urlencode
from django.contrib import messages
@ -7,11 +8,16 @@ from django.core.paginator import Paginator
from django.db import Error as DatabaseError
from django.http import Http404, JsonResponse
from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST
from vrtManager.util import OperationError
from computes.models import Compute
from instances.models import Instance
from vmbackups.models import BackupTarget
from . import jobs as jobs_module
from .api.serializers import OperationSerializer
from .models import Operation, last_seen, worker_gone
@ -42,6 +48,7 @@ def jobs(request):
if value := request.GET.get(field):
qs = qs.filter(**{field: value})
page = Paginator(qs, 50).get_page(request.GET.get("page"))
link_resources(request.user, page.object_list)
# the model for its datetimes, the serialized job for its labels
rows = [(op, OperationSerializer(op, context={"request": request}).data) for op in page.object_list]
seen = last_seen()
@ -60,8 +67,44 @@ def jobs(request):
"page_query": urlencode({k: v for k, v in request.GET.items() if k != "page"})})
def link_resources(user, ops):
"""Gives each job the page of what it works on (op.resource_url, or None): a VM's for who may
see the VM (one of a UUID only: a copy on another host has it too); a host's, a backup
target's, or the Computes page for a bulk migration, for a superuser. A thing gone has none.
A backup's or a pool's job has none: a restore names the new VM, a pool may be gone."""
parts = [op.resource.partition(":")[::2] for op in ops]
named = lambda kind: [rest for each, rest in parts if each == kind]
seen_all = user.is_superuser or user.has_perm("instances.view_instances")
vms = Instance.objects.all() if seen_all else Instance.objects.filter(userinstance__user=user)
found = list(vms.filter(uuid__in=named("instance")).values_list("uuid", "pk"))
once = [uuid for uuid, n in Counter(uuid for uuid, _pk in found).items() if n == 1]
vm_of = {uuid: pk for uuid, pk in found if uuid in once}
hosts = targets = set()
if user.is_superuser:
hosts = {str(pk) for pk in Compute.objects.filter(pk__in=[r for r in named("compute") if r.isdigit()])
.values_list("pk", flat=True)}
targets = {str(pk) for pk in BackupTarget.objects.filter(pk__in=[r for r in named("backup_target") if r.isdigit()])
.values_list("pk", flat=True)}
for op, (kind, rest) in zip(ops, parts):
op.resource_url = _resource_url(kind, rest, vm_of, hosts, targets, user.is_superuser)
def _resource_url(kind, rest, vm_of, hosts, targets, superuser):
"""The page of a job's resource, kind:rest (operations.claims), among those link_resources found."""
if kind == "instance" and rest in vm_of:
return reverse("instances:instance", args=[vm_of[rest]])
if kind == "compute" and rest in hosts:
return reverse("overview", args=[rest])
if kind == "backup_target" and rest in targets:
return reverse("vmbackups:target", args=[rest])
if kind == "bulk_migrate" and superuser:
return reverse("computes")
return None
def job(request, pk):
op = _get(request.user, pk)
link_resources(request.user, [op])
kind = jobs_module.KINDS.get(op.kind)
return render(request, "operations/job.html",
{"job": OperationSerializer(op, context={"request": request}).data, "op": op,

View file

@ -191,6 +191,19 @@ if (typeof module !== "undefined") {
if (!tagPills) {
keep("", key + "_tag"); // no row has a tag: none is kept to come back later
}
// a link may ask for one tag's rows (the Tags page: ?tag=name): only that tag then, on a
// list that has it. The address loses it, so the list's own reload keeps what is chosen afterwards.
var query = new URLSearchParams(window.location.search);
if (query.has("tag") && chooseTag && chooseTag(query.get("tag"))) {
search.value = "";
keep("");
if (chooseState) {
chooseState("");
}
filterTable(document);
query.delete("tag");
history.replaceState(null, "", window.location.pathname + (query.size ? "?" + query : "") + window.location.hash);
}
document.addEventListener("click", function (event) {
var more = event.target.closest("[data-show-tags]");
if (more) {

View file

@ -60,10 +60,10 @@
<tr>
{# date and time wrap apart on a phone #}
<td class="text-nowrap">{{ backup.created_at|date:"Y-m-d" }}<br class="d-sm-none"><span class="d-none d-sm-inline"> </span>{{ backup.created_at|date:"H:i" }}
<div class="small text-body-secondary text-nowrap" title="{% trans "Target" %}">{{ backup.target.name }}</div></td>
<div class="small text-nowrap" title="{% trans "Target" %}"><a class="link-secondary" href="{% url 'vmbackups:target' backup.target_id %}">{{ backup.target.name }}</a></div></td>
<td style="max-width: min(12rem, 30vw);">{# a long name is cut, whole on hover #}
{% if backup.instance %}<a class="d-inline-block text-truncate mw-100 align-bottom" title="{{ backup.vm_name }}" href="{% url 'instances:instance' backup.instance.id %}">{{ backup.vm_name }}</a>
{% else %}<span class="d-inline-block text-truncate mw-100 align-bottom" title="{{ backup.vm_name }}">{{ backup.vm_name }}</span> <span class="badge text-bg-secondary">{% trans "removed" %}</span>{% endif %}
{% else %}<span class="d-inline-block text-truncate mw-100 align-bottom" title="{{ backup.vm_name }}">{{ backup.vm_name }}</span> {% if backup.tombstone %}<a class="badge text-bg-secondary" href="{% url 'admin:tombstone_list' %}">{% trans "removed" %}</a>{% else %}<span class="badge text-bg-secondary">{% trans "removed" %}</span>{% endif %}{% endif %}
<div class="small text-body-secondary text-truncate">{{ backup.compute_name }}{% if backup.policy %}, <a href="{% url 'vmbackups:policy' backup.policy_id %}" title="{% trans "Schedule" %}">{{ backup.policy.name }}</a>{% endif %}</div>
</td>
<td class="d-none d-md-table-cell">{% include "vmbackups/consistency.html" %}</td>

View file

@ -244,6 +244,19 @@ class IndexTests(TransactionTestCase):
self.assertNotIn(reverse("vmbackups:restore_over", args=[ready.uuid]),
page.xpath("//table[@id='backups']//a/@href"))
def test_a_row_links_its_target_and_a_removed_vm_listed_as_removed(self):
from instances.models import InstanceTombstone
links = lambda page: set(page.xpath("//table[@id='backups']//td//a[not(contains(@class, 'dropdown-item'))]/@href"))
self.client.force_login(self.admin)
page = lxml_html.fromstring(self.client.get(reverse("vmbackups:index")).content)
self.assertTrue({reverse("vmbackups:target", args=[self.t1.pk]), reverse("vmbackups:target", args=[self.t2.pk])}
<= links(page))
self.assertNotIn(reverse("admin:tombstone_list"), links(page)) # db1 is not on the Removed VMs page
InstanceTombstone.objects.create(uuid="u2", name="db1", host="h1")
page = lxml_html.fromstring(self.client.get(reverse("vmbackups:index")).content)
self.assertIn(reverse("admin:tombstone_list"), links(page))
def test_the_list_shows_fifty_a_page_and_keeps_the_filter(self):
vm = Instance.objects.get(name="web1")
for _n in range(60):

View file

@ -17,7 +17,7 @@ from libvirt import libvirtError
from admin.decorators import superuser_only
from instances.jobs import unprotected
from instances.models import Instance
from instances.models import Instance, InstanceTombstone
from instances.views import get_instance
from logs.audit import audit
from operations import claims, jobs
@ -209,6 +209,11 @@ def index(request):
rows = rows.filter(state=Backup.READY).exclude(damage=[])
# schedules add a backup of each VM a night: the list is read a page at a time, as the jobs are
page = Paginator(rows, 50).get_page(request.GET.get("page"))
# a removed VM's badge links to the Removed VMs page while it is listed there
removed = set(InstanceTombstone.objects.filter(uuid__in={b.vm_uuid for b in page if not b.instance_id})
.values_list("uuid", flat=True))
for backup in page:
backup.tombstone = backup.vm_uuid in removed
return render(request, "vmbackups/index.html", {
"rows": page.object_list, "page": page, "targets": BackupTarget.objects.order_by("name"),
"vm": vm, "target": target, "state": state, "pending_deletes": pending_deletes(),