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

feat: tags for VMs and hosts

One list of tag names (lower case letters, digits, dot, dash, underscore;
up to 32) given to VMs and hosts. A superuser sets a VM's tags on its
Options tab and a host's on its form; Tom Select suggests the tags there
are and makes a new one typed. The VM list, the VM page and the hosts list
show them as badges, to everyone who sees the VM or host.

A VM's tags stay with it: an out-of-band move adds them to those on the
new host's record, and a VM that leaves its host keeps them on the Removed
VMs page (a VM with only tags too) and gets them back when it returns.
Setting them is audited and held against the VM's move.
This commit is contained in:
catborise 2026-11-18 19:27:36 +03:00
parent 810abe7475
commit 149530f8df
26 changed files with 1202 additions and 778 deletions

View file

@ -8,7 +8,7 @@
{% block page_heading %}{% trans "Removed VMs" %}{% endblock page_heading %}
{% block content %}
<p class="text-body-secondary">{% trans "VMs that vanished from their compute. Their owners come back if the same UUID shows up again before the record expires." %}</p>
<p class="text-body-secondary">{% trans "VMs that vanished from their compute. Their owners and tags come back if the same UUID shows up again before the record expires." %}</p>
{% if not tombstones %}
<div class="alert alert-info shadow-sm">
{% bs_icon 'info-circle' %} {% trans "No removed VMs" %}
@ -21,11 +21,12 @@
</div>
<div class="list-group list-group-flush searchable">
{% for tombstone in tombstones %}
<div class="list-group-item py-3" data-search="{{ tombstone.name }} {{ tombstone.uuid }} {{ tombstone.host }} {{ tombstone.owner_names|join:' ' }}">
<div class="list-group-item py-3" data-search="{{ tombstone.name }} {{ tombstone.uuid }} {{ tombstone.host }} {{ tombstone.owner_names|join:' ' }} {{ tombstone.tags|join:' ' }}">
<div class="row g-2 align-items-center">
<div class="col-12 col-md-4">
<span class="fw-semibold text-break">{{ tombstone.name }}</span>
{% if tombstone.is_template %}<span class="badge text-bg-light border">{% trans "Template" %}</span>{% endif %}
{% include 'common/tag_badges.html' with tags=tombstone.tags %}
<div class="font-monospace small text-body-secondary text-break mt-1">{{ tombstone.uuid }}</div>
</div>
<div class="col-12 col-md-5 small">

View file

@ -21,6 +21,7 @@ class TombstoneTests(TestCase):
uuid=UUID,
name="ts-vm",
host="ts-host",
tags=["prod"],
owners=[
{"user": self.owner.id, "is_change": True, "is_delete": False, "is_vnc": True},
{"user": 999999, "is_change": False, "is_delete": False, "is_vnc": False},
@ -39,6 +40,7 @@ class TombstoneTests(TestCase):
self.assertContains(response, "ts-vm")
self.assertContains(response, UUID)
self.assertContains(response, "ts-owner")
self.assertContains(response, "prod")
self.assertContains(response, '<span class="fw-semibold">ts-host</span>', html=True)
def test_only_superusers_see_or_remove_them(self):

View file

@ -2,7 +2,7 @@ from django import forms
from django.utils.translation import gettext_lazy as _
from vrtManager.connection import CONN_SOCKET, CONN_SSH, CONN_TCP, CONN_TLS
from computes.models import Compute
from computes.models import TAG_NAME, Compute, Tag
from .validators import validate_hostname
@ -27,13 +27,64 @@ class KeepSecretsMixin:
return self.cleaned_data["gstfsd_key"] or self.instance.gstfsd_key
class TagsWidget(forms.SelectMultiple):
"""The tags there are and those given, to choose from or add to (Tom Select)."""
def __init__(self):
# Tom Select's line for a new name typed (searchable_select.js)
super().__init__(attrs={"data-tags": "", "data-add": _("Add tag %(tag)s")})
def optgroups(self, name, value, attrs=None):
self.choices = [(n, n) for n in sorted(set(Tag.objects.values_list("name", flat=True)) | set(value))]
return super().optgroups(name, value, attrs)
class TagsField(forms.Field):
"""Tag names, each once and in lower case; the tags are made when saved (Tag.named)."""
widget = TagsWidget
def __init__(self, **kwargs):
super().__init__(required=False, label=_("Tags"), **kwargs)
def to_python(self, value):
names = [str(name).strip().lower() for name in value or ()]
return list(dict.fromkeys(name for name in names if name))
def validate(self, value):
for name in value:
if len(name) > 32:
raise forms.ValidationError(_("A tag has at most 32 characters"))
TAG_NAME(name)
class TagsForm(forms.Form):
tags = TagsField()
class ComputeTagsMixin:
"""The compute's tags on its form."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["tags"] = TagsField()
if self.instance.pk:
self.initial["tags"] = list(self.instance.tags.values_list("name", flat=True))
def save(self, commit=True):
compute = super().save(commit)
if commit:
compute.tags.set(Tag.named(self.cleaned_data["tags"]))
return compute
SECRET_WIDGETS = {"password": forms.PasswordInput(), "gstfsd_key": forms.PasswordInput()}
DETAILS = {"details": _("Description")}
DETAILS_HELP = {"details": _("Shown on the hosts list")}
SASL_LABELS = {"login": _("SASL login"), "password": _("SASL password")} | DETAILS
class TcpComputeForm(KeepSecretsMixin, forms.ModelForm):
class TcpComputeForm(ComputeTagsMixin, KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_TCP
kind = "TCP"
about = _("libvirt over TCP, with a SASL login")
@ -44,10 +95,10 @@ class TcpComputeForm(KeepSecretsMixin, forms.ModelForm):
widgets = SECRET_WIDGETS
labels = SASL_LABELS
help_texts = DETAILS_HELP
exclude = ["type"]
exclude = ["type", "tags"]
class SshComputeForm(KeepSecretsMixin, forms.ModelForm):
class SshComputeForm(ComputeTagsMixin, KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_SSH
kind = "SSH"
about = _("libvirt over SSH, with the panel's SSH key")
@ -58,10 +109,10 @@ class SshComputeForm(KeepSecretsMixin, forms.ModelForm):
widgets = SECRET_WIDGETS
labels = {"login": _("SSH user")} | DETAILS
help_texts = DETAILS_HELP
exclude = ["password", "type"]
exclude = ["password", "type", "tags"]
class TlsComputeForm(KeepSecretsMixin, forms.ModelForm):
class TlsComputeForm(ComputeTagsMixin, KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_TLS
kind = "TLS"
about = _("libvirt over TLS, with certificates")
@ -72,10 +123,10 @@ class TlsComputeForm(KeepSecretsMixin, forms.ModelForm):
widgets = SECRET_WIDGETS
labels = SASL_LABELS
help_texts = DETAILS_HELP
exclude = ["type"]
exclude = ["type", "tags"]
class SocketComputeForm(KeepSecretsMixin, forms.ModelForm):
class SocketComputeForm(ComputeTagsMixin, KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_SOCKET
kind = _("Local")
about = _("the libvirt of the host the panel runs on, by its socket")

View file

@ -0,0 +1,29 @@
# Generated by Django 5.2.18 on 2026-11-18 16:21
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0011_maintenance_since'),
]
operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, unique=True, validators=[django.core.validators.RegexValidator('^[a-z0-9][a-z0-9._-]*\\Z', 'A tag is letters a-z, digits, dots, dashes and underscores, and begins with a letter or digit')], verbose_name='name')),
],
options={
'ordering': ['name'],
},
),
migrations.AddField(
model_name='compute',
name='tags',
field=models.ManyToManyField(blank=True, related_name='computes', to='computes.tag', verbose_name='tags'),
),
]

View file

@ -1,8 +1,9 @@
from ipaddress import ip_address
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.db import IntegrityError, transaction
from django.db.models import CharField, DateTimeField, IntegerField, Model, Q, UniqueConstraint
from django.db.models import CharField, DateTimeField, IntegerField, ManyToManyField, Model, Q, UniqueConstraint
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext_noop
@ -14,6 +15,27 @@ from vrtManager.connection import connection_manager
from vrtManager.hostdetails import wvmHostDetails
TAG_NAME = RegexValidator(r"^[a-z0-9][a-z0-9._-]*\Z",
_("A tag is letters a-z, digits, dots, dashes and underscores, and begins with a letter or digit"))
class Tag(Model):
"""A name given to VMs and hosts, kept in lower case: one name is one tag."""
name = CharField(_("name"), max_length=32, unique=True, validators=[TAG_NAME])
class Meta:
ordering = ["name"]
def __str__(self):
return self.name
@classmethod
def named(cls, names):
"""The tags of names, those not there yet made."""
return [cls.objects.get_or_create(name=name)[0] for name in names]
# what the panel connects to a compute with
ENDPOINT = ("hostname", "login", "password", "type")
@ -57,6 +79,7 @@ class Compute(Model):
# it is ready once none of its VMs runs (refuse_new_vms, refuse_start);
# since when: the host's bulk migrations from then on are its own
maintenance_since = DateTimeField(null=True, blank=True, editable=False)
tags = ManyToManyField(Tag, blank=True, related_name="computes", verbose_name=_("tags"))
class Meta:
constraints = [UniqueConstraint(fields=["host_uuid"], condition=~Q(host_uuid=""), name="one_compute_per_host")]

View file

@ -1,6 +1,7 @@
{% extends "base.html" %}
{% load django_bootstrap5 %}
{% load i18n %}
{% load static %}
{% block title %}{% if form.instance.pk %}{% trans "Edit host" %}{% else %}{% trans "Add host" %}{% endif %}{% endblock %}
@ -9,6 +10,8 @@
<span class="badge text-bg-light border align-middle fs-6">{{ form.kind }}</span>
{% endblock page_heading %}
{% block style %}<link href="{% static 'css/tom-select.bootstrap5.min.css' %}" rel="stylesheet">{% endblock %}
{% block content %}
<p class="text-body-secondary">{{ form.about }}</p>
<form method="post">
@ -24,6 +27,7 @@
{% if "login" in form.fields %}<div class="col-md-6">{% bootstrap_field form.login %}</div>{% endif %}
{% if "password" in form.fields %}<div class="col-md-6">{% bootstrap_field form.password %}</div>{% endif %}
<div class="col-12">{% bootstrap_field form.details %}</div>
<div class="col-12">{% bootstrap_field form.tags %}</div>
</div>
{# open when one of them is set or refused #}
<details class="border-top pt-3"{% if form.migration_address.value or form.migration_address.errors or form.gstfsd_key.errors %} open{% endif %}>
@ -47,3 +51,7 @@
</div>
</form>
{% endblock content %}
{% block script %}
<script src="{% static 'js/tom-select.complete.min.js' %}"></script>
<script src="{% static 'js/searchable_select.js' %}"></script>
{% endblock script %}

View file

@ -81,6 +81,7 @@
</div>
<div class="small text-body-secondary font-monospace mt-1">{{ compute.hostname }}</div>
{% if compute.details %}<div class="small text-body-secondary">{{ compute.details }}</div>{% endif %}
{% with tags=compute.tags.all %}{% if tags %}<div class="mt-1">{% include 'common/tag_badges.html' %}</div>{% endif %}{% endwith %}
{% if compute.status is not True %}
<div class="small text-danger">{{ compute.connection_error }}</div>
{% endif %}

107
computes/tests/test_tags.py Normal file
View file

@ -0,0 +1,107 @@
"""Tags of VMs and hosts: one list of names, kept with a VM that leaves its
host for a while or moves out of band, and set on the host form."""
from unittest.mock import MagicMock
from django import forms
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.utils import translation
from computes.forms import TagsField, TagsForm
from computes.models import Compute, Tag
from computes.tests.fakes import Domain, no_host_answers
from computes.utils import move_ownership, refresh_instance_database
from instances.models import Instance, InstanceTombstone
UUID = "55555555-5555-5555-5555-555555555555"
class TagsFieldTests(TestCase):
def test_names_are_kept_in_lower_case_once(self):
self.assertEqual(TagsField().clean(["Prod", "db", "prod"]), ["prod", "db"])
def test_a_name_is_letters_digits_and_dot_dash_underscore(self):
for bad in ("two words", "-lead", "ç", "x" * 33):
with self.subTest(bad), self.assertRaises(forms.ValidationError):
TagsField().clean([bad])
def test_the_box_tells_in_the_reader_s_language_what_a_new_name_adds(self):
with translation.override("tr"):
html = TagsForm().as_p()
self.assertIn('data-add="Etiket ekle: %(tag)s"', html)
def test_the_tags_are_made_when_saved(self):
Tag.objects.create(name="prod")
tags = Tag.named(["prod", "db"])
self.assertEqual(sorted(t.name for t in tags), ["db", "prod"])
self.assertEqual(Tag.objects.count(), 2)
class TagsFollowTheVmTests(TestCase):
def setUp(self):
self.prod, self.db = Tag.objects.create(name="prod"), Tag.objects.create(name="db")
self.host_a = self.compute("host-a")
self.host_b = self.compute("host-b")
def compute(self, name):
compute = Compute.objects.create(name=name, hostname=f"{name}.example", login="", password="", type=1)
compute.__dict__["proxy"] = MagicMock()
compute.__dict__["status"] = True
compute.proxy.wvm.listAllDomains.return_value = []
return compute
def tag_names(self, compute):
return sorted(Instance.objects.get(compute=compute, uuid=UUID).tags.values_list("name", flat=True))
def test_a_vm_with_tags_only_gets_them_back(self):
Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID).tags.add(self.prod)
refresh_instance_database(self.host_a) # undefined for a while
self.assertEqual(InstanceTombstone.objects.get(uuid=UUID).tags, ["prod"])
self.host_a.proxy.wvm.listAllDomains.return_value = [Domain("vm", UUID)]
refresh_instance_database(self.host_a)
self.assertEqual(self.tag_names(self.host_a), ["prod"])
def test_a_tag_deleted_meanwhile_is_not_given_back(self):
Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID).tags.add(self.prod, self.db)
refresh_instance_database(self.host_a)
self.db.delete()
self.host_b.proxy.wvm.listAllDomains.return_value = [Domain("vm", UUID)]
refresh_instance_database(self.host_b)
self.assertEqual(self.tag_names(self.host_b), ["prod"])
def test_a_move_adds_the_tags_to_those_already_there(self):
source = Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID)
source.tags.add(self.prod)
target = Instance.objects.create(compute=self.host_b, name="vm", uuid=UUID)
target.tags.add(self.db)
move_ownership(source, target)
self.assertEqual(self.tag_names(self.host_b), ["db", "prod"])
class HostTagsTests(TestCase):
def setUp(self):
self.client.force_login(get_user_model().objects.create_superuser("ht-admin", "ht@example.com", "pw"))
no_host_answers(self)
def test_the_host_form_sets_the_tags(self):
self.client.post(reverse("add_tcp_host"), {"name": "kvm1", "hostname": "192.0.2.1", "login": "wvc",
"password": "pw", "details": "", "tags": ["Rack-1", "gpu"]})
compute = Compute.objects.get(name="kvm1")
self.assertEqual(sorted(compute.tags.values_list("name", flat=True)), ["gpu", "rack-1"])
self.client.post(reverse("compute_update", args=[compute.id]),
{"name": "kvm1", "hostname": "192.0.2.1", "login": "wvc", "password": "", "details": ""})
self.assertFalse(compute.tags.exists())
def test_the_socket_form_has_them_too(self):
self.client.post(reverse("add_socket_host"), {"name": "local", "hostname": "localhost", "details": "",
"tags": ["lab"]})
self.assertEqual(list(Compute.objects.get(name="local").tags.values_list("name", flat=True)), ["lab"])
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")

View file

@ -7,7 +7,7 @@ from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import connection, transaction
from django.utils import timezone
from computes.models import ENDPOINT, Compute
from computes.models import ENDPOINT, Compute, Tag
from instances.models import Instance, InstanceTombstone
from logs.audit import write
from operations import claims
@ -87,7 +87,8 @@ def _log(inst, what):
def move_ownership(source, target):
"""Give target the owners, template flag, backups and schedules of source; a user's rights are merged."""
"""Give target the owners, tags, template flag, backups and schedules of source; a user's rights are merged."""
target.tags.add(*source.tags.all())
Backup.objects.filter(instance=source).update(instance=target)
for policy in source.backup_policies.all():
policy.instances.add(target)
@ -130,9 +131,10 @@ def _bury(inst):
{"user": ui.user_id, "is_change": ui.is_change, "is_delete": ui.is_delete, "is_vnc": ui.is_vnc}
for ui in UserInstance.objects.filter(instance=inst)
]
if owners or inst.is_template:
tags = list(inst.tags.values_list("name", flat=True))
if owners or inst.is_template or tags:
InstanceTombstone.objects.create(uuid=inst.uuid, name=inst.name, host=inst.compute.name,
is_template=inst.is_template, owners=owners)
is_template=inst.is_template, owners=owners, tags=tags)
_log(inst, "owners kept on the Removed VMs page")
else:
_log(inst, "left the panel (no owners)")
@ -152,6 +154,7 @@ def _restore(inst):
is_delete=owner["is_delete"],
is_vnc=owner["is_vnc"],
)
inst.tags.set(Tag.objects.filter(name__in=tombstone.tags))
if tombstone.is_template:
inst.is_template = True
inst.save(update_fields=["is_template"])

View file

@ -159,7 +159,7 @@ def read_hosts(computes):
def computes(request):
"""The computes, with what each has given its VMs, and the totals of the
ones the panel reaches."""
computes = list(Compute.objects.order_by("name"))
computes = list(Compute.objects.order_by("name").prefetch_related("tags"))
totals = {"hosts": len(computes), "connected": 0, "vms": 0, "running": 0,
"vcpus": 0, "cpus": 0, "assigned": 0, "memory": 0}
read_hosts(computes)

View file

@ -0,0 +1,24 @@
# Generated by Django 5.2.18 on 2026-11-18 16:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0012_tags'),
('instances', '0017_backup_permission'),
]
operations = [
migrations.AddField(
model_name='instance',
name='tags',
field=models.ManyToManyField(blank=True, related_name='instances', to='computes.tag', verbose_name='tags'),
),
migrations.AddField(
model_name='instancetombstone',
name='tags',
field=models.JSONField(default=list),
),
]

View file

@ -35,6 +35,7 @@ class Instance(models.Model):
is_template = models.BooleanField(_("is template"), default=False)
created = models.DateTimeField(_("created"), auto_now_add=True)
drbd = models.CharField(_("drbd"), max_length=24, default="None")
tags = models.ManyToManyField("computes.Tag", blank=True, related_name="instances", verbose_name=_("tags"))
objects = InstanceManager()
@ -407,9 +408,9 @@ class Instance(models.Model):
class InstanceTombstone(models.Model):
"""Ownership of a VM that disappeared from its compute.
"""Ownership and tags of a VM that disappeared from its compute.
Kept for INSTANCE_OWNERSHIP_RETENTION_DAYS so that the owners come back
Kept for INSTANCE_OWNERSHIP_RETENTION_DAYS so that they come back
when the same UUID shows up again, on this or another compute.
"""
@ -418,6 +419,7 @@ class InstanceTombstone(models.Model):
host = models.CharField(max_length=64, blank=True) # the compute's name: the compute may be deleted
is_template = models.BooleanField(default=False)
owners = models.JSONField(default=list) # [{"user": id, "is_change": .., "is_delete": .., "is_vnc": ..}]
tags = models.JSONField(default=list) # the names: a tag deleted meanwhile is not given back
removed = models.DateTimeField(auto_now_add=True)
def __str__(self):

View file

@ -8,7 +8,7 @@
{% block title %}{% trans "Instance" %} - {{ instance.name }}{% endblock %}
{% block style %}
{% if request.user.is_superuser and users %}<link href="{% static 'css/tom-select.bootstrap5.min.css' %}" rel="stylesheet">{% endif %}
{% if request.user.is_superuser %}<link href="{% static 'css/tom-select.bootstrap5.min.css' %}" rel="stylesheet">{% endif %}
{% endblock style %}
{% block page_header %}{% endblock page_header %}{# the card below has the heading #}
@ -29,6 +29,7 @@
{% vm_state instance.status as state %}
<span class="badge text-bg-{{ state.1 }}">{{ state.0 }}</span>
{% if instance.is_template %}<span class="badge text-bg-light border">{% trans "Template" %}</span>{% endif %}
{% include 'common/tag_badges.html' with tags=instance.tags.all %}
</div>
{% if instance.title %}<p class="text-body-secondary mb-1">{{ instance.title }}</p>{% endif %}
{% include 'instances/host_link.html' %}
@ -138,7 +139,7 @@
{% endblock %}
{% block script %}
{% if request.user.is_superuser and users %}{# Add owner's user list #}
{% if request.user.is_superuser %}{# the add-owner user list and the tags #}
<script src="{% static 'js/tom-select.complete.min.js' %}"></script>
<script src="{% static 'js/searchable_select.js' %}"></script>
{% endif %}

View file

@ -3,6 +3,7 @@
{# a VM's name, its title, and with owners its owners: the first as a badge, the others counted #}
<a class="fw-semibold text-break" href="{% url 'instances:instance' instance.id %}">{{ instance.name }}</a>
{% if instance.info and instance.title %}<div class="small text-body-secondary text-break">{{ instance.title }}</div>{% endif %}
{% with tags=instance.tags.all %}{% if tags %}<div class="mt-1">{% include 'common/tag_badges.html' %}</div>{% endif %}{% endwith %}
{% if owners %}
{% with users=instance.userinstance_set.all %}
{% if users %}

View file

@ -920,6 +920,18 @@
{% elif instance.status != 5 %}{% trans "Shut the VM down to change this." %}{% endif %}</p>
</form>
</div>
{% if tags_form %}
<div class="list-group-item p-3 p-md-4">
<h2 class="h6 mb-2" id="options-tags"><label for="{{ tags_form.tags.id_for_label }}">{% trans "Tags" %}</label></h2>
<form action="{% url 'instances:set_tags' instance.id %}" method="post">{% csrf_token %}
{{ tags_form.tags }}
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mt-2">
<span class="small text-body-secondary">{% trans "Choose a tag or type a new one. Owners see the tags but cannot change them." %}</span>
<button class="btn btn-primary" type="submit">{% trans "Save" %}</button>
</div>
</form>
</div>
{% endif %}
{% if request.user.is_superuser %}
<div class="list-group-item p-3 p-md-4" role="group" aria-labelledby="options-devices">
<div class="d-flex flex-wrap justify-content-between column-gap-3 mb-2">

View file

@ -285,8 +285,10 @@ class PendingEditsTestCase(TestCase):
# a search box for a list of every user (searchable_select.js)
self.assertEqual(doc.xpath("//select[@id='add-owner-user']/@data-searchable"), [""])
self.assertIn("/static/js/searchable_select.js", doc.xpath("//script/@src"))
User.objects.filter(username="pe-new").delete() # no one left to add: no search box to load
self.assertNotIn("/static/js/searchable_select.js", self.page().xpath("//script/@src"))
User.objects.filter(username="pe-new").delete() # no one left to add: the tags field still uses it
doc = self.page()
self.assertEqual(doc.xpath("//select[@name='tags']/@data-tags"), [""])
self.assertIn("/static/js/searchable_select.js", doc.xpath("//script/@src"))
def test_the_page_has_a_hidden_notice_for_a_host_that_stops_answering(self):
# instance_status.js shows it while the state poll fails

View file

@ -0,0 +1,54 @@
"""A VM's tags: set by a superuser on its page, shown to everyone who sees the VM."""
from unittest.mock import patch
from accounts.models import UserInstance
from computes.models import Compute, Tag
from django.contrib.auth import get_user_model
from django.template.loader import render_to_string
from django.test import TestCase
from django.urls import reverse
from instances.models import Instance
from logs.models import Logs
class VmTagsTests(TestCase):
def setUp(self):
User = get_user_model()
self.admin = User.objects.create_superuser("vt-admin", "vt@example.com", "pw")
self.owner = User.objects.create_user("vt-owner", password="pw")
compute = Compute.objects.create(name="vt", hostname="192.0.2.5", login="u", password="p", type=1)
self.vm = Instance.objects.create(compute=compute, name="vt-vm", uuid="12345678-0000-0000-0000-00000000bbbb")
UserInstance.objects.create(user=self.owner, instance=self.vm, is_change=True)
def post(self, user, tags):
self.client.force_login(user)
with patch("instances.models.wvmInstance"):
return self.client.post(reverse("instances:set_tags", args=[self.vm.id]), {"tags": tags})
def names(self):
return sorted(self.vm.tags.values_list("name", flat=True))
def test_a_superuser_sets_and_clears_them(self):
Tag.objects.create(name="prod")
self.post(self.admin, ["prod", "New-One"])
self.assertEqual(self.names(), ["new-one", "prod"])
self.post(self.admin, [])
self.assertEqual(self.names(), [])
self.assertEqual(list(Logs.objects.filter(message__startswith="VM").order_by("id").values_list("message", flat=True)),
["VM vt-vm: tags new-one, prod", "VM vt-vm: tags none"])
def test_a_bad_name_changes_nothing(self):
self.vm.tags.add(Tag.objects.create(name="prod"))
self.post(self.admin, ["two words"])
self.assertEqual(self.names(), ["prod"])
def test_an_owner_cannot_set_them(self):
self.assertEqual(self.post(self.owner, ["prod"]).status_code, 403)
self.assertEqual(self.names(), [])
self.assertFalse(Tag.objects.exists())
def test_the_vm_list_shows_them(self):
self.vm.tags.add(Tag.objects.create(name="prod"))
html = render_to_string("instance_name_cell.html", {"instance": self.vm})
self.assertIn("prod", html)

View file

@ -78,6 +78,7 @@ urlpatterns = [
path("<int:pk>/update_console/", views.update_console, name="update_console"),
path("<int:pk>/change_options/", views.change_options, name="change_options"),
path("<int:pk>/set_template/", views.set_template, name="set_template"),
path("<int:pk>/set_tags/", views.set_tags, name="set_tags"),
path(
"<int:pk>/getvvfile/", views.getvvfile, name="getvvfile"
), # no links to this one???

View file

@ -14,7 +14,8 @@ from ipaddress import ip_address
from accounts.models import UserInstance, UserSSHKey
from admin.decorators import superuser_only
from appsettings.settings import app_settings
from computes.models import Compute
from computes.forms import TagsForm
from computes.models import Compute, Tag
from computes.validators import validate_hostname, validate_login
from computes.utils import (
libvirt_compute_lock,
@ -96,14 +97,14 @@ def index(request):
if request.user.is_superuser and app_settings.VIEW_INSTANCES_LIST_STYLE == "grouped":
# each host's VMs by name: the database keeps no order of its own
prefetch_related_objects(computes, Prefetch("instance_set", queryset=Instance.objects.order_by("name")),
"instance_set__userinstance_set__user")
"instance_set__userinstance_set__user", "instance_set__tags")
instances = [inst for compute in computes for inst in compute.instance_set.all()]
elif show_hosts:
instances = list(Instance.objects.order_by("name").prefetch_related("userinstance_set__user"))
instances = list(Instance.objects.order_by("name").prefetch_related("userinstance_set__user", "tags"))
else:
instances = list(Instance.objects.filter(
userinstance__user=request.user
).order_by("name").prefetch_related("userinstance_set__user"))
).order_by("name").prefetch_related("userinstance_set__user", "tags"))
# other users get no host names or connection errors, only whether
# a host of their own VMs is down
own_hosts_down = any(c.status is not True for c in computes)
@ -398,6 +399,7 @@ def _instance_page(request, pk, instance, compute):
"compute": compute,
"computes": computes,
"users": users,
"tags_form": TagsForm(initial={"tags": [t.name for t in instance.tags.all()]}) if request.user.is_superuser else None,
"publickeys": publickeys,
"userinstance": userinstance,
"userinstances": userinstances,
@ -2391,6 +2393,23 @@ def add_owner(request, pk):
return _back(request, pk, "users")
@require_POST
@superuser_only
@serialize_instance_mutation
def set_tags(request, pk):
"""The VM's tags, those not there yet made; the VM held, so a move does not lose them."""
instance = get_instance(request.user, pk)
form = TagsForm(request.POST)
if not form.is_valid():
messages.error(request, " ".join(form.errors["tags"]))
return _back(request, pk, "options")
names = form.cleaned_data["tags"]
with audit_vm(request, instance, f"tags {', '.join(sorted(names)) or 'none'}"), transaction.atomic():
lock_ownership() # not while the VM's tags are kept or given back (computes.utils.forget)
instance.tags.set(Tag.named(names))
return _back(request, pk, "options")
# Buses for the empty CD-ROM of a new VM: fdc and virtio have no ejectable
# media, and libvirt refuses an empty usb disk.
CDROM_BUSES = ("ide", "sata", "scsi")

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

@ -0,0 +1,5 @@
<?xml version="1.0" ?>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-tag" viewBox="0 0 16 16">
<path d="M6 4.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m-1 0a.5.5 0 1 0-1 0 .5.5 0 0 0 1 0"/>
<path d="M2 1h4.586a1 1 0 0 1 .707.293l7 7a1 1 0 0 1 0 1.414l-4.586 4.586a1 1 0 0 1-1.414 0l-7-7A1 1 0 0 1 1 6.586V2a1 1 0 0 1 1-1m0 5.586 7 7L13.586 9l-7-7H2z"/>
</svg>

After

Width:  |  Height:  |  Size: 408 B

View file

@ -6,3 +6,17 @@ document.querySelectorAll("select[data-searchable]").forEach(function (select) {
onItemAdd: function () { this.blur(); },
});
});
// A <select multiple data-tags>: the tags there are, and a new one typed (the server checks it).
document.querySelectorAll("select[data-tags]").forEach(function (select) {
new TomSelect(select, {
create: true, persist: false, createFilter: /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/,
render: {
// the page's own words (data-add): the library's are English
option_create: function (data, escape) {
return '<div class="create">' + escape(select.dataset.add.replace("%(tag)s", data.input)) + "</div>";
},
no_results: null,
},
});
});

View file

@ -0,0 +1,2 @@
{% load bootstrap_icons %}{# tags: a VM's or host's tags (or their names), as badges #}
{% for tag in tags %}<span class="badge text-bg-light border">{% bs_icon 'tag' %} {{ tag }}</span>{% endfor %}