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

feat: filter the VM and host lists by tag

The VM list and the hosts list get a tag list next to their search: the
rows with the tag chosen show, together with the search and the state.
It offers the tags of the rows listed only, so an owner sees the tags of
their own VMs, not the panel's. The state counts follow the tag, and the
chosen tag is remembered as the search and state are; Clear the filters
clears it too.
This commit is contained in:
catborise 2026-11-18 20:34:01 +03:00
parent 149530f8df
commit 11b447f681
15 changed files with 524 additions and 411 deletions

View file

@ -11,6 +11,7 @@
{% include 'create_comp_block.html' %}
{% if computes|length > 1 %}<a href="{% url 'balance' %}" class="btn btn-outline-primary mt-1 ms-1 float-end">{% trans "Balance" %}</a>{% endif %}
{% include 'search_block.html' %}
<div class="float-end m-1">{% include 'common/tag_filter.html' %}</div>
<h3 class="mb-3">{% trans "Computes" %}</h3>
</div>
</div>
@ -66,7 +67,7 @@
<tbody class="searchable">
{% for compute in computes %}
{% with given=compute.shown_capacity %}
<tr{% if compute.status is not True %} class="table-warning"{% endif %}>
<tr data-tags="{% for tag in compute.tags.all %}{{ tag }}{% if not forloop.last %} {% endif %}{% endfor %}"{% if compute.status is not True %} class="table-warning"{% endif %}>
<td class="py-3">
<div class="d-flex flex-wrap align-items-center gap-2">
<a class="fw-semibold" href="{% url 'overview' compute.id %}">{{ compute.name }}</a>

View file

@ -104,4 +104,7 @@ class HostTagsTests(TestCase):
def test_the_hosts_list_shows_them(self):
compute = Compute.objects.create(name="kvm1", hostname="192.0.2.1", login="wvc", password="pw", type=1)
compute.tags.add(Tag.objects.create(name="rack-1"))
self.assertContains(self.client.get(reverse("computes")), "rack-1")
response = self.client.get(reverse("computes"))
self.assertContains(response, "rack-1")
self.assertContains(response, '<option value="rack-1">rack-1</option>', html=True)
self.assertContains(response, 'data-tags="rack-1"')

View file

@ -179,7 +179,8 @@ def computes(request):
totals["assigned"] += given["assigned"]["all"]
totals["memory"] += given["memory"]
return render(request, "computes/list.html",
{"computes": computes, "totals": totals, "job_resource": claims.bulk_migrate_key()})
{"computes": computes, "totals": totals, "job_resource": claims.bulk_migrate_key(),
"tags": sorted({tag.name for compute in computes for tag in compute.tags.all()})})
@superuser_only

View file

@ -6,6 +6,7 @@
{% block page_heading_extra %}
<div class="d-flex flex-wrap justify-content-end gap-2 mt-1">
{% include 'common/tag_filter.html' %}
{# the list's search and the address search, as one control #}
<div class="input-group w-auto">
<input id="filter" class="form-control" type="text" placeholder="{% trans 'Search' %}" aria-label="{% trans 'Search' %}">
@ -66,7 +67,7 @@
{% if instances %}
{# table_filter.js shows it while no row matches #}
<div id="no-match" class="text-center text-body-secondary py-4" hidden>
{% trans "No VM matches the search and the state." %}
{% trans "No VM matches the filters." %}
<button type="button" class="btn btn-link" id="clear-filters">{% trans "Clear the filters" %}</button>
</div>
{% endif %}

View file

@ -59,7 +59,7 @@
</tr>
{% for instance in compute.instance_set.all %}
{# searched for its name, title and owners, not its buttons #}
<tr host="{{ compute.id }}" data-search="{{ instance.name }}{% if instance.info %} {{ instance.title }}{% endif %}{% for owner in instance.userinstance_set.all %} {{ owner.user }}{% endfor %}">
<tr host="{{ compute.id }}" data-tags="{% for tag in instance.tags.all %}{{ tag }}{% if not forloop.last %} {% endif %}{% endfor %}" data-search="{{ instance.name }}{% if instance.info %} {{ instance.title }}{% endif %}{% for owner in instance.userinstance_set.all %} {{ owner.user }}{% endfor %}">
<td></td>
<td>{% include 'instance_name_cell.html' with owners=True %}</td>
<td>

View file

@ -19,7 +19,7 @@
<tbody class="searchable">
{% for instance in instances %}
{# searched for its name, title, host and owners, not its buttons #}
<tr data-search="{{ instance.name }}{% if instance.info %} {{ instance.title }}{% endif %}{% if show_hosts %} {{ instance.compute.name }}{% for owner in instance.userinstance_set.all %} {{ owner.user }}{% endfor %}{% endif %}">
<tr data-tags="{% for tag in instance.tags.all %}{{ tag }}{% if not forloop.last %} {% endif %}{% endfor %}" data-search="{{ instance.name }}{% if instance.info %} {{ instance.title }}{% endif %}{% if show_hosts %} {{ instance.compute.name }}{% for owner in instance.userinstance_set.all %} {{ owner.user }}{% endfor %}{% endif %}">
<td>{% include 'instance_name_cell.html' with owners=show_hosts %}</td>
{% if show_hosts %}
<td>

View file

@ -19,8 +19,9 @@ function group(rows, host) {
return {dataset: host ? {host} : {}, querySelectorAll: (s) => (s === "tr, [data-search], [data-group-header]" ? rows : [])};
}
function page(groups, text, state, noMatch, extra = {}) {
// a list without a state list (state undefined) has no such element
// a list without a state list (state undefined) has no such element, nor one without tags a tag list
const inputs = {filter: {value: text}, "state-filter": state === undefined ? undefined : {value: state},
"tag-filter": extra.tag === undefined ? undefined : {value: extra.tag},
"no-match": noMatch, "filter-status": extra.status};
return {
getElementById: (id) => inputs[id],
@ -102,6 +103,25 @@ assert.strictEqual(counts[3].parentElement.hidden, false, "the chosen state stay
filterInstances(page([group(fleet)], "no-such-vm", "Active", undefined, {counts, status}));
assert.strictEqual(counts[0].parentElement.hidden, false, "All stays when nothing is found");
// the tag list: a row shows with the chosen tag among its own (data-tags), a whole name
const withTags = (row, tags) => Object.assign(row, {dataset: Object.assign(row.dataset, {tags})});
const tagged = [withTags(vm("web-1", "Active", "web-1"), "prod web"), withTags(vm("db-1", "Off", "db-1"), "prod"),
withTags(vm("web-2", "Active", "web-2"), "")];
filterInstances(page([group(tagged)], "", "", undefined, {tag: "prod"}));
assert.deepStrictEqual(visible(tagged), ["web-1", "db-1"]);
filterInstances(page([group(tagged)], "web", "", undefined, {tag: "prod"}));
assert.deepStrictEqual(visible(tagged), ["web-1"], "the search and the tag both apply");
filterInstances(page([group(tagged)], "", "", undefined, {tag: "pro"}));
assert.deepStrictEqual(visible(tagged), [], "a tag is a whole name");
filterInstances(page([group(tagged)], "", "", undefined, {tag: ""}));
assert.deepStrictEqual(visible(tagged), ["web-1", "db-1", "web-2"], "no tag chosen: all");
const tagCounts = [count(""), count("Active"), count("Off")];
filterInstances(page([group(tagged)], "", "Active", undefined, {tag: "prod", counts: tagCounts}));
assert.deepStrictEqual(tagCounts.map((c) => c.textContent), [2, 1, 1], "the state counts follow the tag");
const hostVms = [hostRow("host-a"), withTags(vm("web-1", "Active", "web-1"), "prod"), withTags(vm("db-1", "Active", "db-1"), "")];
filterInstances(page([group(hostVms, "host-a")], "host-a", "", undefined, {tag: "prod"}));
assert.deepStrictEqual(visible(hostVms), ["host-a", "web-1"], "a host's name and a tag: its VMs with the tag");
// a search is without case and accents in any language: "istanbul" finds "İSTANBUL"
const turkish = [vm("İSTANBUL-1", "Active"), vm("ankara", "Active"), vm("Şişli", "Off")];
filterInstances(page([group(turkish)], "istanbul", ""));
@ -113,16 +133,18 @@ assert.deepStrictEqual(visible(turkish), ["Şişli"]);
{
const vmModule = require("vm");
const fs = require("fs");
const stored = {"VMs_filter_state": "Off"};
const stored = {"VMs_filter_state": "Off", "VMs_filter_tag": "prod"};
const pill = (state) => ({dataset: {pillState: state}, classList: {toggle() {}}, setAttribute() {}});
const pillList = [pill(""), pill("Active"), pill("Off")];
const elements = {
filter: {value: "", hasAttribute: () => false, addEventListener() {}},
"state-filter": {value: "", addEventListener() {}},
"state-pills": {querySelectorAll: () => pillList, querySelector: () => pillList[0], addEventListener() {}},
"tag-filter": {value: "", options: [{value: ""}, {value: "prod"}], addEventListener() {}},
};
const doc = {title: "VMs", getElementById: (id) => elements[id], querySelectorAll: () => []};
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});
assert.strictEqual(elements["state-filter"].value, "Off");
assert.strictEqual(elements["tag-filter"].value, "prod", "the chosen tag is remembered too");
}

View file

@ -1,6 +1,8 @@
"""A VM's tags: set by a superuser on its page, shown to everyone who sees the VM."""
from unittest.mock import patch
from unittest.mock import PropertyMock, patch
from lxml import html as lxml_html
from accounts.models import UserInstance
from computes.models import Compute, Tag
@ -52,3 +54,38 @@ class VmTagsTests(TestCase):
self.vm.tags.add(Tag.objects.create(name="prod"))
html = render_to_string("instance_name_cell.html", {"instance": self.vm})
self.assertIn("prod", html)
class VmListTagFilterTests(TestCase):
def setUp(self):
User = get_user_model()
self.admin = User.objects.create_superuser("tf-admin", "tf@example.com", "pw")
self.owner = User.objects.create_user("tf-owner", password="pw")
compute = Compute.objects.create(name="tf", hostname="192.0.2.6", login="u", password="p", type=1)
mine = Instance.objects.create(compute=compute, name="mine", uuid="12345678-0000-0000-0000-00000000cc01")
other = Instance.objects.create(compute=compute, name="other", uuid="12345678-0000-0000-0000-00000000cc02")
UserInstance.objects.create(user=self.owner, instance=mine)
mine.tags.add(Tag.objects.create(name="web"), Tag.objects.create(name="prod"))
other.tags.add(Tag.objects.create(name="secret"))
def page(self, user):
self.client.force_login(user)
with patch("instances.views.refresh_instance_database"), \
patch("instances.views.utils.vm_states", return_value={}), \
patch("instances.views.utils.read_list_rows"), \
patch.object(Compute, "status", new_callable=PropertyMock, return_value=True):
return lxml_html.fromstring(self.client.get(reverse("instances:index")).content)
def test_the_tag_list_has_the_tags_of_the_vms_listed(self):
doc = self.page(self.admin)
self.assertEqual(doc.xpath("//select[@id='tag-filter']/option/@value"), ["", "prod", "secret", "web"])
self.assertEqual(doc.xpath("//tr[@data-tags]/@data-tags"), ["prod web", "secret"])
def test_an_owner_sees_only_the_tags_of_their_vms(self):
doc = self.page(self.owner)
self.assertEqual(doc.xpath("//select[@id='tag-filter']/option/@value"), ["", "prod", "web"])
self.assertEqual(doc.xpath("//tr[@data-tags]/@data-tags"), ["prod web"])
def test_no_tags_no_tag_list(self):
Tag.objects.all().delete()
self.assertEqual(self.page(self.admin).xpath("//select[@id='tag-filter']"), [])

View file

@ -129,6 +129,7 @@ def index(request):
"reachable_computes": [c for c in computes if c.status is True and c.ram_usage is not None],
"unreachable_computes": [c for c in computes if c.status is not True],
"states": [label for label, _color in STATES.values()] + [UNKNOWN[0]],
"tags": sorted({tag.name for instance in instances for tag in instance.tags.all()}),
"states_url": reverse("instances:states"), "vm_states": vm_states},
)

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

@ -4,15 +4,16 @@
// shows when its text contains the search, in any case: plain text, not a
// pattern. A row with data-search is searched in that text only, not in its
// buttons and menus. With a state list, the row's [data-state] must
// be the chosen state too. In a grouped list a search for a group's host
// be the chosen state too; with a tag list (#tag-filter), the chosen tag
// one of the row's data-tags (names split by spaces). In a grouped list a search for a group's host
// shows all of its rows, and its header row (data-group-header) shows while
// any of its rows does. A page's #no-match shows while no row does. The
// search is remembered for a day, per page, unless its box has data-forget.
//
// The instance list's state pills (#state-pills) set the state; each one's
// [data-count-state] counts the VMs of its state the search finds (its
// state left aside), "" all of them; a state's pill with none is hidden
// unless chosen; the chosen state is remembered as the search is, so that a
// state left aside, the tag not), "" all of them; a state's pill with none is hidden
// unless chosen; the chosen state and tag are remembered as the search is, so that a
// list the poll reloads keeps it. #filter-status tells screen readers how
// many VMs match, collapsed hosts' VMs too.
@ -26,6 +27,8 @@ function filterTable(doc) {
var text = fold(doc.getElementById("filter").value);
var states = doc.getElementById("state-filter");
var state = states ? states.value : "";
var tags = doc.getElementById("tag-filter");
var tag = tags ? tags.value : "";
var anyShown = false;
var counts = {"": 0}, vms = 0, shownVms = 0;
doc.querySelectorAll(".searchable").forEach(function (group) {
@ -39,7 +42,8 @@ function filterTable(doc) {
}
var mark = row.querySelector("[data-state]");
var searched = row.dataset.search !== undefined ? row.dataset.search : row.textContent;
var found = hostMatches || fold(searched).includes(text);
var found = (hostMatches || fold(searched).includes(text))
&& (!tag || (row.dataset.tags || "").split(" ").indexOf(tag) >= 0);
row.hidden = !((!state || (mark && mark.dataset.state === state)) && found);
shown = shown || !row.hidden;
if (mark) {
@ -107,6 +111,22 @@ if (typeof module !== "undefined") {
filterTable(document);
});
}
var tags = document.getElementById("tag-filter");
if (tags) {
try {
var keptTag = sessionStorage.getItem(key + "_tag") || "";
// a tag no row has any longer is not chosen
if (Array.prototype.some.call(tags.options, function (option) { return option.value === keptTag; })) {
tags.value = keptTag;
}
} catch (e) {
// storage turned off: all tags
}
tags.addEventListener("change", function () {
keep(tags.value, key + "_tag");
filterTable(document);
});
}
var pills = document.getElementById("state-pills");
function chooseState(pill) {
states.value = pill.dataset.pillState;
@ -142,6 +162,10 @@ if (typeof module !== "undefined") {
clear.addEventListener("click", function () {
search.value = "";
keep("");
if (tags) {
tags.value = "";
keep("", key + "_tag");
}
if (pills) {
chooseState(pills.querySelector('[data-pill-state=""]'));
} else if (states) {

View file

@ -0,0 +1,7 @@
{% load i18n %}{# tags: the names of the listed rows' tags; table_filter.js shows the rows with the one chosen #}
{% if tags %}
<select id="tag-filter" class="form-select w-auto" aria-label="{% trans "Tag" %}">
<option value="">{% trans "All tags" %}</option>
{% for tag in tags %}<option value="{{ tag }}">{{ tag }}</option>{% endfor %}
</select>
{% endif %}