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

feat(instances): a protected VM is not deleted nor restored over

A superuser turns a VM's protection on or off on its Settings tab, not while
a job holds the VM (a deletion or a restore over it that runs would not
stop). While it is on, its deletion (page, API, a queued job at its start)
and a restore of a backup over it are refused; the Destroy tab, the destroy
page and the restore page say so. A VM moved outside the panel keeps it.
The API shows the flag read-only.
This commit is contained in:
catborise 2026-11-19 21:45:57 +03:00
parent 57e90e0d27
commit adb4231db7
21 changed files with 706 additions and 491 deletions

View file

@ -49,6 +49,7 @@ WebVirtCloud and `virt-manager`/`virsh` can manage the same libvirt host **concu
* SSH public key and root password management (guest agent for a running VM, gstfsd for a shut-off one)
* Finding VMs by IP or MAC address, and a VM report as an Excel file
* Tags on VMs and hosts, set by superusers: the lists filter by them, Bulk Migrate chooses VMs by them and a backup schedule backs up every VM with a chosen tag (templates left out)
* Protected VMs, set by superusers on the VM's Settings tab: not deleted and not restored over until the protection is turned off
* An audit log of who changed what, with its result
* Cloud-init datasource interface (OpenStack metadata compatible) and NoCloud seed media
* REST API — OpenAPI 3.0 (Swagger & ReDoc), with API tokens

View file

@ -37,7 +37,7 @@ class OwnershipTestCase(TestCase):
compute.proxy.wvm.listAllDomains.return_value = [Domain(n, u) for n, u in domains]
def owned_vm(self, compute):
vm = Instance.objects.create(compute=compute, name="vm", uuid=UUID, is_template=True)
vm = Instance.objects.create(compute=compute, name="vm", uuid=UUID, is_template=True, protected=True)
UserInstance.objects.create(instance=vm, user=self.owner, is_change=True, is_vnc=True)
return vm
@ -77,6 +77,7 @@ class OwnershipTestCase(TestCase):
refresh_instance_database(self.host_a) # gone from A: it moved to B
self.assertEqual(self.ownership(self.host_b), (True, [(self.owner, True, False, True)]))
self.assertTrue(Instance.objects.get(compute=self.host_b).protected)
self.assertFalse(Instance.objects.filter(compute=self.host_a).exists())
self.assertEqual(self.rows(), [("-", "host-a", f"VM vm ({UUID}): owners moved to host-b")])

View file

@ -87,7 +87,8 @@ def _log(inst, what):
def move_ownership(source, target):
"""Give target the owners, tags, template flag, backups and schedules of source; a user's rights are merged."""
"""Give target the owners, tags, template and protected flags, 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():
@ -106,9 +107,11 @@ def move_ownership(source, target):
if getattr(ui, flag):
setattr(existing, flag, True)
existing.save()
if source.is_template and not target.is_template:
target.is_template = True
target.save(update_fields=["is_template"])
flags = [flag for flag in ("is_template", "protected") if getattr(source, flag) and not getattr(target, flag)]
for flag in flags:
setattr(target, flag, True)
if flags:
target.save(update_fields=flags)
def forget(inst):

View file

@ -12,7 +12,8 @@ class InstanceSerializer(serializers.ModelSerializer):
class Meta:
model = Instance
fields = ["id", "compute", "name", "uuid", "is_template", "created", "drbd", "tags"]
fields = ["id", "compute", "name", "uuid", "is_template", "protected", "created", "drbd", "tags"]
read_only_fields = ["protected"] # a superuser changes it on the VM's page
# what a VM's device dicts tell of the host: its files and pools
@ -66,6 +67,7 @@ class InstanceDetailsSerializer(serializers.ModelSerializer):
"title",
"description",
"is_template",
"protected",
"created",
"drbd",
"arch",

View file

@ -73,6 +73,14 @@ def _vm_plan(params):
MOVED = _("The VM moved to another compute after the job was queued")
def unprotected(instance):
"""instance, unless it is protected: not deleted nor restored over."""
if instance.protected:
raise util.OperationError(_("%(vm)s is protected: a superuser turns its protection off on its Settings tab "
"first"), vm=instance.name)
return instance
def _checked_proxy(op):
"""In the worker: the user may still change the VM, and it did not move."""
instance = _authorized(op.user, op.params["instance"])
@ -1467,7 +1475,7 @@ class DeleteInstance(Kind):
"delete_nvram": bool(raw.get("delete_nvram"))}
def validate(self, user, params):
_deletable(user, params["instance"])
unprotected(_deletable(user, params["instance"]))
def plan(self, user, params):
instance = _instance(params["instance"])
@ -1478,7 +1486,7 @@ class DeleteInstance(Kind):
intent={"compute": instance.compute_id, "uuid": instance.uuid, "name": instance.name})
def precheck(self, op, ctx):
if _deletable(op.user, op.params["instance"]).compute_id != op.intent["compute"]:
if unprotected(_deletable(op.user, op.params["instance"])).compute_id != op.intent["compute"]:
raise util.OperationError(MOVED)
def run(self, op, ctx):

View file

@ -0,0 +1,18 @@
# Generated by Django 5.2.18 on 2026-11-19 18:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instances', '0018_tags'),
]
operations = [
migrations.AddField(
model_name='instance',
name='protected',
field=models.BooleanField(default=False, verbose_name='protected'),
),
]

View file

@ -33,6 +33,8 @@ class Instance(models.Model):
name = models.CharField(_("name"), max_length=255, db_index=True)
uuid = models.CharField(_("uuid"), max_length=36, db_index=True)
is_template = models.BooleanField(_("is template"), default=False)
# not deleted nor restored over until a superuser turns it off (instances.jobs.unprotected)
protected = models.BooleanField(_("protected"), 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"))

View file

@ -9,6 +9,10 @@
{% block content %}
<p class="small">{% trans "The VM's definition, saved state and snapshot records are removed. A running VM is forced off first; what the guest has not written to disk is lost." %}</p>
{% if instance.protected %}
<div class="alert alert-warning" role="status">{% trans "This VM is protected: an administrator turns its protection off on the Settings tab first." %}</div>
<a class="btn btn-secondary" href="{% url 'instances:instance' instance.id %}">{% trans "Cancel" %}</a>
{% else %}
<form action="{% url 'instances:destroy' instance.id %}" method="post" id="delete_form">{% csrf_token %}{% submission_key %}
<fieldset class="mb-3">
<legend class="h6">{% trans "What should happen to the files?" %}</legend>
@ -53,4 +57,5 @@
<button class="btn btn-danger" type="submit" name="delete">{% trans "Destroy VM" %}</button>
</div>
</form>
{% endif %}
{% endblock content %}

View file

@ -5,7 +5,9 @@
<div class="card">
<div class="card-body">
<p class="small text-body-secondary mb-2">{% trans "Destroy" %} · {{ state.0 }}</p>
{% if can_delete %}
{% if instance.protected %}
<p class="mb-0">{% trans "This VM is protected: an administrator turns its protection off on the Settings tab first." %}</p>
{% elif can_delete %}
<a href="{% url 'instances:destroy' instance.id %}" class="btn btn-danger mb-2">{% trans "Review destruction" %}</a>
<p class="small text-body-secondary mb-0">{% trans "The next page shows what goes and lets you keep the disk files." %}</p>
{% else %}

View file

@ -919,6 +919,15 @@
{% if not request.user.is_superuser and not request.user.is_staff %}{% trans "Only administrators and staff can change this." %}
{% elif instance.status != 5 %}{% trans "Shut the VM down to change this." %}{% endif %}</p>
</form>
<form class="border-top mt-3 pt-3" action="{% url 'instances:set_protected' instance.id %}" method="post">{% csrf_token %}
<div class="form-check form-switch mb-1">
<input class="form-check-input" type="checkbox" role="switch" name="protected" value="True" id="protected" aria-describedby="protected-help"
{% if instance.protected %}checked{% endif %}{% if not request.user.is_superuser %} disabled{% endif %} data-submit-on-change>
<label class="form-check-label" for="protected">{% trans "Protected" %}</label>
</div>
<p class="small text-body-secondary mb-0" id="protected-help">{% trans "A protected VM is not deleted and no backup is restored over it." %}
{% if not request.user.is_superuser %}{% trans "Only administrators can change this." %}{% endif %}</p>
</form>
</div>
{% if tags_form %}
<div class="list-group-item p-3 p-md-4">

View file

@ -66,6 +66,24 @@ class DestroyOrderTestCase(TransactionTestCase):
(f"compute:{self.instance.compute_id}", "exclusive"), (f"instance:{UUID}", "exclusive")})
self.assertEqual(self.proxy.mock_calls, [])
def test_a_protected_vm_is_not_deleted(self):
Instance.objects.filter(pk=self.instance.pk).update(protected=True)
response = self.client.post(reverse("instances:destroy", args=[self.instance.id]),
{"submission_key": "key-destroy01"}, follow=True)
self.assertContains(response, "destroy-vm is protected")
url = f"/api/v1/computes/{self.instance.compute_id}/instances/{self.instance.id}/"
response = self.client.delete(url, {"submission_key": "key-api00003"}, content_type="application/json")
self.assertContains(response, "destroy-vm is protected", status_code=400)
self.assertFalse(Operation.objects.exists())
# protected after the delete was queued: refused before any effect
Instance.objects.filter(pk=self.instance.pk).update(protected=False)
op = self.queue()
Instance.objects.filter(pk=self.instance.pk).update(protected=True)
self.proxy.reset_mock() # what the pages read
with self.assertRaisesMessage(OperationError, "destroy-vm is protected"):
self.run_job(op)
self.assertEqual(self.proxy.mock_calls, [])
def test_backup_checkpoints_go_with_the_vm(self):
# libvirt refuses to undefine a VM that has checkpoints without this flag
self.run_job(self.queue())

View file

@ -0,0 +1,57 @@
"""A protected VM: only a superuser turns its protection on or off; while on, the VM is not deleted nor
restored over (refusals in test_destroy and vmbackups.tests.test_restore_over)."""
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from accounts.models import UserInstance
from instances.models import Instance
from operations import claims
from operations.models import Claim
from instances.tests import test_pending_edits
from logs.models import Logs
class ProtectedTestCase(TestCase):
setUp = test_pending_edits.PendingEditsTestCase.setUp
page = test_pending_edits.PendingEditsTestCase.page # the VM page with its host faked
def test_only_a_superuser_turns_it_on_and_off(self):
url = reverse("instances:set_protected", args=[self.instance.id])
owner = get_user_model().objects.create_user("pr_owner", password="x", is_staff=True)
UserInstance.objects.create(instance=self.instance, user=owner, is_change=True, is_delete=True)
self.client.force_login(owner)
self.assertEqual(self.client.post(url, {"protected": "True"}).status_code, 403)
self.assertFalse(Instance.objects.get(pk=self.instance.pk).protected)
self.client.force_login(get_user_model().objects.get(username="pe-admin"))
self.client.post(url, {"protected": "True"})
self.assertTrue(Instance.objects.get(pk=self.instance.pk).protected)
self.client.post(url, {})
self.assertFalse(Instance.objects.get(pk=self.instance.pk).protected)
self.assertEqual([m.split(": ")[-1] for m in Logs.objects.filter(instance="pe-vm").order_by("pk").values_list("message", flat=True)],
["protect", "unprotect"])
def test_the_page_tells_it_and_offers_no_deletion(self):
doc = self.page()
(switch,) = doc.xpath("//input[@id='protected']")
self.assertIsNone(switch.get("checked"))
self.assertTrue(doc.xpath("//a[@href=$a]", a=reverse("instances:destroy", args=[self.instance.id])))
Instance.objects.filter(pk=self.instance.pk).update(protected=True)
doc = self.page()
(switch,) = doc.xpath("//input[@id='protected']")
self.assertIsNotNone(switch.get("checked"))
self.assertFalse(doc.xpath("//a[@href=$a]", a=reverse("instances:destroy", args=[self.instance.id])))
self.assertIn("This VM is protected", doc.text_content())
def test_not_changed_while_a_job_holds_the_vm(self):
# a deletion or a restore over it that runs would not stop
claims.admit({claims.instance_key(self.instance.uuid): Claim.EXCLUSIVE}, holder="192.0.2.30:1:1")
self.client.post(reverse("instances:set_protected", args=[self.instance.id]), {"protected": "True"})
self.assertFalse(Instance.objects.get(pk=self.instance.pk).protected)
def test_the_destroy_page_offers_no_form(self):
Instance.objects.filter(pk=self.instance.pk).update(protected=True)
page = self.client.get(reverse("instances:destroy", args=[self.instance.id]))
self.assertContains(page, "This VM is protected")
self.assertNotContains(page, 'id="delete_form"')

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_protected/", views.set_protected, name="set_protected"),
path("<int:pk>/set_tags/", views.set_tags, name="set_tags"),
path(
"<int:pk>/getvvfile/", views.getvvfile, name="getvvfile"

View file

@ -2543,6 +2543,18 @@ def set_template(request, pk):
return _back(request, pk, "options")
@require_POST
@superuser_only
@serialize_instance_mutation # not while a deletion or a restore over it runs: it would not stop them
def set_protected(request, pk):
"""Turns a VM's protection against deletion and a restore over it on or off."""
instance = get_instance(request.user, pk)
protected = bool(request.POST.get("protected"))
with audit_vm(request, instance, "protect" if protected else "unprotect"):
Instance.objects.filter(pk=instance.pk).update(protected=protected)
return _back(request, pk, "options")
def keyfile_value(value):
"""value as a GLib key file (the .vv file) reads it back: a backslash,
a line break or a leading space would change it."""

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

@ -24,7 +24,8 @@ from libvirt import (VIR_DOMAIN_PAUSED, VIR_DOMAIN_RUNNING, VIR_DOMAIN_SHUTOFF,
from accounts.models import UserAttributes
from appsettings.settings import app_settings
from computes.models import Compute
from instances.jobs import MOVED, PAUSED_FROZEN, THAW_FAILED, _instance, _log, _snapshot_free_space, record_vm, vm_claims
from instances.jobs import (MOVED, PAUSED_FROZEN, THAW_FAILED, _instance, _log, _snapshot_free_space, record_vm, unprotected,
vm_claims)
from instances.utils import QUOTA_UNVERIFIED, paths_used_on_other_computes, QUOTA_UNVERIFIED_TEXT, check_user_quota, get_random_mac_address, quota_message
from instances.models import Instance
from operations import alerts, claims
@ -1222,6 +1223,7 @@ class RestoreOver(Kind):
_may_use(user)
raise util.OperationError(_("The backup's VM is no longer in the panel; restore it as a new VM"))
_may_use(user, instance, backup.target)
unprotected(instance)
_target_row(backup.target, instance.compute)
proxy = _proxy(instance)
over = _over_plan(backup, proxy, owner=not user.is_superuser)
@ -1238,6 +1240,9 @@ class RestoreOver(Kind):
"time": timezone.localtime(backup.created_at).strftime("%Y-%m-%d %H:%M")},
)
def precheck(self, op, ctx):
unprotected(_instance(_backup(op.params).instance_id)) # protected since it was queued
def run(self, op, ctx):
backup = _backup(op.params)
instance = _instance(backup.instance_id)

View file

@ -17,6 +17,7 @@ from lxml import etree
from appsettings.settings import get_settings
from computes.models import Compute
from django.urls import reverse
from instances.models import Instance
from operations import jobs
from operations.jobs import Context
@ -193,6 +194,20 @@ class RestoreOverTests(TransactionTestCase):
with self.assertRaisesMessage(OperationError, "Shut the VM down"):
self.submit()
def test_a_protected_vm_is_not_restored_over(self):
Instance.objects.filter(pk=self.backup.instance_id).update(protected=True)
with self.assertRaisesMessage(OperationError, "vm1 is protected"):
self.submit()
self.client.force_login(self.admin)
page = self.client.get(reverse("vmbackups:restore_over", args=[self.backup.uuid]))
self.assertContains(page, "vm1 is protected")
self.assertNotContains(page, 'name="submission_key"') # no form
Instance.objects.filter(pk=self.backup.instance_id).update(protected=False)
op = self.submit()
Instance.objects.filter(pk=self.backup.instance_id).update(protected=True) # after it was queued
with self.assertRaisesMessage(OperationError, "vm1 is protected"):
RestoreOver().precheck(op, Context(op, SimpleNamespace(identity=WORKER)))
def test_a_vm_with_snapshots_is_refused(self):
self.proxy.instance.snapshotNum.return_value = 2
with self.assertRaisesMessage(OperationError, "snapshots"):

View file

@ -16,6 +16,7 @@ from django.utils.translation import gettext_noop
from libvirt import libvirtError
from admin.decorators import superuser_only
from instances.jobs import unprotected
from instances.models import Instance
from instances.views import get_instance
from logs.audit import audit
@ -299,7 +300,7 @@ def restore_over(request, uuid):
return redirect("operations:job", op.pk)
over, problem = None, None
try:
proxy = _proxy(backup.instance)
proxy = _proxy(unprotected(backup.instance))
over = _over_plan(backup, proxy, owner=not request.user.is_superuser)
names = _over_names(backup, proxy, over)
except (OperationError, libvirtError) as err: