1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 17:36:05 +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

@ -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."""