mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 17:36:05 +00:00
feat(instances): free a running VM's unused disk space with the guest agent
The Disks tab of a running VM gets "Free unused space": a job (instance.fstrim) has the guest agent trim each mounted file system (guest-fstrim, 30 minutes at most) and lists what each one trimmed. A disk passes the trim to its image file only with the discard mode unmap: the tab and the job say when no disk of the running VM has it, and where to set it (the disk's device details, from the next start).
This commit is contained in:
parent
d6cee18434
commit
8625d6250a
17 changed files with 367 additions and 5 deletions
|
|
@ -1663,6 +1663,59 @@ class ForceOffVM(_Power):
|
|||
return dom is None or not dom.isActive()
|
||||
|
||||
|
||||
@register
|
||||
class TrimVM(Kind):
|
||||
"""Has a running VM's guest agent trim the free space of its file systems (guest-fstrim): a disk whose
|
||||
discard mode is unmap passes it on, and its image file shrinks. Trimming again is harmless."""
|
||||
|
||||
name = "instance.fstrim"
|
||||
label = gettext_noop("Free unused space")
|
||||
time_limit = 1800 # the agent's wait (FSTRIM_TIMEOUT): over time is only noted
|
||||
|
||||
def normalize(self, raw):
|
||||
return {"instance": int(raw["instance"])}
|
||||
|
||||
def validate(self, user, params):
|
||||
if not user.is_superuser: # as the Disks tab's other superuser controls
|
||||
raise PermissionDenied
|
||||
|
||||
def plan(self, user, params):
|
||||
return _vm_plan(params)
|
||||
|
||||
def precheck(self, op, ctx):
|
||||
if op.user is None or not (op.user.is_active and op.user.is_superuser): # still, when it runs
|
||||
raise PermissionDenied
|
||||
if _instance(op.params["instance"]).compute_id != op.intent["compute"]:
|
||||
raise util.OperationError(MOVED)
|
||||
|
||||
def run(self, op, ctx):
|
||||
instance = _instance(op.params["instance"])
|
||||
proxy = instance.proxy
|
||||
if proxy.get_status() != 1:
|
||||
raise util.OperationError(gettext_noop("The VM is not running"))
|
||||
if not proxy.is_agent_ready():
|
||||
raise util.OperationError(gettext_noop("The guest agent is not connected"))
|
||||
ctx.record_intent(trimming=True) # the guest is asked from here
|
||||
trimmed = proxy.fstrim()
|
||||
if trimmed and all(fs["error"] for fs in trimmed): # the guest refused every file system
|
||||
raise util.OperationError(gettext_noop("No file system was trimmed: %(errors)s"),
|
||||
errors="; ".join(f"{fs['path']}: {fs['error']}" for fs in trimmed))
|
||||
result = {"trimmed": trimmed}
|
||||
if not instance.discard_unmap:
|
||||
result["warning"] = say(NO_DISCARD)
|
||||
return result
|
||||
|
||||
def reconcile(self, op):
|
||||
return Outcome(Operation.FAILED, error=say(gettext_noop(
|
||||
"The job stopped before the guest answered; trimming again is harmless")))
|
||||
|
||||
def log_entry(self, op, state):
|
||||
return _log(op, state, "free unused space")
|
||||
|
||||
|
||||
NO_DISCARD = _("No disk of the running VM has the discard mode unmap: its image files keep their size. Set it in "
|
||||
"a disk's device details; it takes effect at the VM's next start.")
|
||||
|
||||
VM_FAULT = _("VM fault: %(vm)s")
|
||||
VM_FAULT_TEXT = _("%(vm)s on %(host)s: %(reason)s")
|
||||
|
||||
|
|
|
|||
|
|
@ -79,6 +79,11 @@ class Instance(models.Model):
|
|||
def disks(self) -> list[dict]:
|
||||
return self.proxy.get_disk_devices()
|
||||
|
||||
@property
|
||||
def discard_unmap(self) -> bool:
|
||||
"""Whether a disk of the running definition passes the guest's trim to its image (discard unmap)."""
|
||||
return any(disk.get("discard") == "unmap" for disk in self.disks)
|
||||
|
||||
@cached_property
|
||||
def info(self) -> list | None:
|
||||
"""virDomainGetInfo, read once: state, max memory KiB, memory KiB, vCPUs, CPU time.
|
||||
|
|
|
|||
|
|
@ -293,6 +293,15 @@
|
|||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% if instance.status == 1 and request.user.is_superuser %}
|
||||
{# the guest agent trims its file systems' free space; a disk passes it to its image only with discard unmap #}
|
||||
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2 small mt-3">
|
||||
<span class="text-body-secondary">{% if instance.discard_unmap %}{% trans "Free space the guest no longer uses in the image files." %}{% else %}{% trans "No disk has the discard mode unmap while the VM runs: trimming frees no space in its image files. Set it in a disk's device details; it takes effect at the next start." %}{% endif %}</span>
|
||||
<form action="{% url 'instances:fstrim' instance.id %}" method="post">{% csrf_token %}{% submission_key %}
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary"{% if not instance.guest_agent_ready %} disabled title="{% trans "The guest agent is not connected" %}"{% endif %}>{% trans "Free unused space" %}</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if instance.pcie_slots %}
|
||||
{# a PCIe machine gives each virtio disk and network device a slot; a running VM gets no new one #}
|
||||
{% with total=instance.pcie_slots.0 free=instance.pcie_slots.1 next=instance.config_pcie_slots %}
|
||||
|
|
|
|||
105
instances/tests/test_fstrim.py
Normal file
105
instances/tests/test_fstrim.py
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
"""Free unused space: the guest agent trims each mounted file system (instance.fstrim); a disk passes it to its
|
||||
image only with the discard mode unmap, which the Disks tab and the job say when no disk has it."""
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.test import TransactionTestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from computes.models import Compute
|
||||
from instances.jobs import TrimVM
|
||||
from instances.models import Instance
|
||||
from operations.jobs import Context
|
||||
from operations.models import Operation, acquire
|
||||
from operations.utils import words
|
||||
from vrtManager import instance as vrt_instance
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
|
||||
def disk(discard):
|
||||
return {"dev": "vda", "discard": discard}
|
||||
|
||||
|
||||
class FstrimTestCase(TransactionTestCase):
|
||||
def setUp(self):
|
||||
self.admin = get_user_model().objects.create_superuser("ft-admin", "ft@example.com", "pw")
|
||||
self.client.force_login(self.admin)
|
||||
compute = Compute.objects.create(name="ft-host", hostname="192.0.2.81", login="", password="", type=4)
|
||||
self.vm = Instance.objects.create(compute=compute, name="ft-vm", uuid="81818181-0000-4000-8000-000000000001")
|
||||
self.proxy = MagicMock(**{"get_status.return_value": 1, "is_agent_ready.return_value": True,
|
||||
"get_disk_devices.return_value": [disk("unmap")],
|
||||
"fstrim.return_value": [{"path": "/", "trimmed": 1 << 30, "error": None}]})
|
||||
patch.object(Instance, "proxy", property(lambda vm: self.proxy)).start()
|
||||
self.addCleanup(patch.stopall)
|
||||
|
||||
def queue_and_run(self):
|
||||
response = self.client.post(reverse("instances:fstrim", args=[self.vm.pk]), {"submission_key": "key-fstrim01"})
|
||||
self.assertRedirects(response, reverse("instances:instance", args=[self.vm.pk]) + "#disks",
|
||||
fetch_redirect_response=False)
|
||||
op = Operation.objects.get(kind="instance.fstrim")
|
||||
acquire("wvc-test:1:a", "wvc-test")
|
||||
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker="wvc-test:1:a")
|
||||
op.refresh_from_db()
|
||||
ctx = Context(op, SimpleNamespace(identity="wvc-test:1:a"))
|
||||
TrimVM().precheck(op, ctx)
|
||||
return TrimVM().run(op, ctx)
|
||||
|
||||
def test_the_job_returns_what_each_file_system_trimmed(self):
|
||||
self.assertEqual(self.queue_and_run(), {"trimmed": [{"path": "/", "trimmed": 1 << 30, "error": None}]})
|
||||
|
||||
def test_without_discard_unmap_the_job_warns_that_the_images_keep_their_size(self):
|
||||
self.proxy.get_disk_devices.return_value = [disk("default")]
|
||||
result = self.queue_and_run()
|
||||
self.assertIn("image files keep their size", words(result["warning"]))
|
||||
|
||||
def test_the_job_fails_when_the_guest_trims_no_file_system(self):
|
||||
self.proxy.fstrim.return_value = [{"path": "/", "trimmed": None, "error": "not supported"}]
|
||||
with self.assertRaisesMessage(OperationError, "No file system was trimmed: /: not supported"):
|
||||
self.queue_and_run()
|
||||
self.assertTrue(Operation.objects.get().effects_started) # recovery knows the guest was asked
|
||||
|
||||
def test_only_a_superuser_still_active_trims(self):
|
||||
owner = get_user_model().objects.create_user("ft-owner", "o@example.com", "pw")
|
||||
self.client.force_login(owner)
|
||||
self.assertEqual(self.client.post(reverse("instances:fstrim", args=[self.vm.pk]),
|
||||
{"submission_key": "key-fstrim02"}).status_code, 403)
|
||||
self.client.force_login(self.admin)
|
||||
self.client.post(reverse("instances:fstrim", args=[self.vm.pk]), {"submission_key": "key-fstrim03"})
|
||||
op = Operation.objects.get()
|
||||
self.admin.is_superuser = False
|
||||
self.admin.save()
|
||||
op.refresh_from_db()
|
||||
with self.assertRaises(PermissionDenied):
|
||||
TrimVM().precheck(op, None)
|
||||
|
||||
def test_a_vm_not_running_or_without_an_agent_is_refused(self):
|
||||
self.proxy.get_status.return_value = 5
|
||||
with self.assertRaisesMessage(OperationError, "not running"):
|
||||
self.queue_and_run()
|
||||
self.proxy.fstrim.assert_not_called()
|
||||
|
||||
def test_the_job_page_lists_each_file_system(self):
|
||||
op = Operation.objects.create(kind="instance.fstrim", user=self.admin, username="ft-admin", resource="r",
|
||||
resource_label="ft-host/ft-vm", state=Operation.SUCCEEDED, result={"trimmed": [
|
||||
{"path": "/", "trimmed": 1 << 30, "error": None},
|
||||
{"path": "/boot", "trimmed": None, "error": "not supported"}]})
|
||||
page = self.client.get(reverse("operations:job", args=[op.pk])).content.decode()
|
||||
self.assertInHTML("<li class=\"text-break\"><code>/</code> 1\xa0GiB</li>", page)
|
||||
self.assertInHTML("<li class=\"text-break\"><code>/boot</code> not supported</li>", page)
|
||||
|
||||
|
||||
class AgentFstrimTestCase(TransactionTestCase):
|
||||
def test_the_agent_answer_is_read_per_path(self):
|
||||
answer = {"paths": [{"path": "/", "trimmed": 4096, "minimum": 0}, {"path": "/boot", "error": "not supported"},
|
||||
{"path": "C:\\"}, "garbage", {"trimmed": 1}]}
|
||||
dom = MagicMock()
|
||||
proxy = SimpleNamespace(instance=dom, ping_agent=lambda: None)
|
||||
with patch.object(vrt_instance, "qemuAgentCommand", return_value=json.dumps({"return": answer})) as command:
|
||||
paths = vrt_instance.wvmInstance.fstrim(proxy)
|
||||
self.assertEqual(paths, [{"path": "/", "trimmed": 4096, "error": None},
|
||||
{"path": "/boot", "trimmed": None, "error": "not supported"},
|
||||
{"path": "C:\\", "trimmed": None, "error": None}])
|
||||
self.assertEqual(command.call_args.args[2], vrt_instance.FSTRIM_TIMEOUT) # not the 10 s of other agent calls
|
||||
|
|
@ -178,6 +178,16 @@ class PendingEditsTestCase(TestCase):
|
|||
doc = self.page(get_pcie_slots=(None, None))
|
||||
self.assertFalse(doc.xpath("//form[@action=$a]", a=reverse("instances:add_pcie_slots", args=[self.instance.id])))
|
||||
|
||||
def test_the_disks_tab_frees_unused_space_of_a_running_vm_and_says_when_no_disk_passes_it_on(self):
|
||||
url = reverse("instances:fstrim", args=[self.instance.id])
|
||||
for discard, said in (("default", "trimming frees no space"), ("unmap", "Free space the guest no longer uses")):
|
||||
with self.subTest(discard=discard):
|
||||
doc = self.page(live=[{**disk("vda", "default", ""), "discard": discard}])
|
||||
(form,) = doc.xpath("//form[@action=$a]", a=url)
|
||||
self.assertIn(said, form.getparent().text_content())
|
||||
self.assertTrue(form.xpath(".//input[@name='submission_key']/@value")) # the job needs it
|
||||
self.assertFalse(self.page(status=5).xpath("//form[@action=$a]", a=url)) # the agent of a running VM trims
|
||||
|
||||
def test_the_clone_form_lists_the_persistent_devices(self):
|
||||
nic = {"type": "network", "mac": "52:54:10:00:00:01", "nic": "default", "state": "up", "model": "virtio",
|
||||
"ipv4": None, "ipv6": None, "filterref": "", "target": "", "inbound": [], "outbound": []}
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ urlpatterns = [
|
|||
path("<int:pk>/detach_vol/", views.detach_vol, name="detach_vol"),
|
||||
path("<int:pk>/add_cdrom/", views.add_cdrom, name="add_cdrom"),
|
||||
path("<int:pk>/add_pcie_slots/", views.add_pcie_slots, name="add_pcie_slots"),
|
||||
path("<int:pk>/fstrim/", views.fstrim, name="fstrim"),
|
||||
path("<int:pk>/detach_cdrom/<str:dev>/", views.detach_cdrom, name="detach_cdrom"),
|
||||
path("<int:pk>/unmount_iso/", views.unmount_iso, name="unmount_iso"),
|
||||
path("<int:pk>/mount_iso/", views.mount_iso, name="mount_iso"),
|
||||
|
|
|
|||
|
|
@ -1616,6 +1616,24 @@ def add_pcie_slots(request, pk):
|
|||
return _back(request, pk, "disks")
|
||||
|
||||
|
||||
@require_POST
|
||||
@superuser_only
|
||||
def fstrim(request, pk):
|
||||
"""Queue a trim of the running VM's file systems (instance.fstrim): the job panel shows it."""
|
||||
get_instance(request.user, pk)
|
||||
try:
|
||||
op = jobs.submit("instance.fstrim", request.user, {"instance": pk}, request.POST.get("submission_key", ""))
|
||||
except claims.Busy as busy:
|
||||
messages.error(request, busy_message(busy, request.user))
|
||||
except jobs.SubmissionConflict as err:
|
||||
messages.error(request, str(err))
|
||||
except libvirtError as err:
|
||||
messages.error(request, error_text(request, err))
|
||||
else:
|
||||
jobs.remember_job(request, op)
|
||||
return _back(request, pk, "disks")
|
||||
|
||||
|
||||
@require_POST
|
||||
@superuser_only
|
||||
@serialize_instance_mutation
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue