diff --git a/doc/behavior-changes.md b/doc/behavior-changes.md index b7a900d2..fab22611 100644 --- a/doc/behavior-changes.md +++ b/doc/behavior-changes.md @@ -33,6 +33,7 @@ What an update from an older version changes for operators and users. To run the - On a running VM the edit forms show the settings as they will be at the next start, so saving an edit no longer reverts another pending change. - External snapshots need libvirt 9.9 or newer on the computes. libvirt 9.10 (openEuler 24.03 LTS) refuses to revert a snapshot taken without memory of a running or paused VM ("Invalid target domain state 'disk-snapshot'"); 11.10 reverts it. A VM's snapshots form one chain: after a revert, delete the newer snapshots before taking another. An internal snapshot is reverted only on a shut-off VM. Snapshot names no longer get an `s1.` prefix. A snapshot an older version took of a UEFI VM can only be deleted, not reverted. On NFS, the qemu user needs write access to the image directory to remove merged snapshot files. - A superuser limits a disk's I/O (IOPS and MiB/s, reads and writes together) under its Device details on the Disks tab; a running VM gets the limit at once. +- **Free unused space** on a running VM's Disks tab (superusers) has its guest agent trim each file system (`guest-fstrim`, a job that lists what each one trimmed). Only a disk with the discard mode `unmap` (Device details, from the VM's next start; Settings > Disk Discard for new disks) passes it to its image file, which then shrinks; the tab says when no disk has it. - A storage volume a VM still needs (a disk, a backing file or a snapshot's file) is not deleted; deleting a VM with its files keeps a file another compute's VM or volume uses at the same path, and is refused before the VM is stopped when one of the other computes cannot be reached. A pool's page names the VMs of its host that use each volume and lists those the host does not use. - A VM that vanishes from its compute, or whose compute is deleted, keeps its owners, tags, protection and schedules for `INSTANCE_OWNERSHIP_RETENTION_DAYS` (30) in case the same UUID comes back, and its backups are linked to it again; superusers manage these records on the "Removed VMs" page. - The Logs page records who changed what (computes, users, groups, VM owners, settings, SSH keys, host networks, pools, volumes, interfaces, secrets and network filters), every login, failed login and lockout, and every page or API call answered 401 or 403 to a signed-in user or a request with credentials, with the address and the result (a VM hidden with 404 is not logged). diff --git a/doc/permissions.md b/doc/permissions.md index 1c15abcf..bbd40b74 100644 --- a/doc/permissions.md +++ b/doc/permissions.md @@ -24,7 +24,7 @@ WebVirtCloud combines three kinds of access rights: | Clone | ✅ | ✅ | `is_change` and `instances.clone_instances` (templates: viewing the template is enough) | templates only, with `instances.clone_instances` | | Delete the VM, with its disk files when chosen | ✅ | ✅ | `is_delete` | ❌ | | Disks and media (add, attach, edit, detach, delete volumes; CD-ROM/ISO) | ✅ | ❌ | — | ❌ | -| Network interfaces, host devices (PCI/USB), boot options, vCPU hotplug, autostart, guest agent, video, RNG, TPM, crash and hang action, disk I/O limits, suspend/resume, migrate, disk moves, protection, raw XML, owners | ✅ | ❌ | — | ❌ | +| Network interfaces, host devices (PCI/USB), boot options, vCPU hotplug, autostart, guest agent, video, RNG, TPM, crash and hang action, disk I/O limits, free unused space (fstrim), suspend/resume, migrate, disk moves, protection, raw XML, owners | ✅ | ❌ | — | ❌ | | Set tags (owners and `view_instances` see them) | ✅ | ❌ | — | ❌ | | Backups: back up (within the backup quota), restore over the VM or as a new VM (within the VM quota), into and from targets open to VM owners | ✅ | ✅ | `is_change` and `instances.backup_instances` | ❌ | | Delete a backup one took by hand (not a schedule's) on a target open to VM owners | ✅ | ✅ | `instances.backup_instances` (ownership not needed) | ❌ | diff --git a/instances/jobs.py b/instances/jobs.py index ac193739..b9b96065 100644 --- a/instances/jobs.py +++ b/instances/jobs.py @@ -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") diff --git a/instances/models.py b/instances/models.py index b827ffac..a6956ce9 100644 --- a/instances/models.py +++ b/instances/models.py @@ -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. diff --git a/instances/templates/instances/settings_tab.html b/instances/templates/instances/settings_tab.html index 6a85bd1b..b994f77f 100644 --- a/instances/templates/instances/settings_tab.html +++ b/instances/templates/instances/settings_tab.html @@ -293,6 +293,15 @@ {% endfor %} + {% 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 #} +
+ {% 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 %} +
{% csrf_token %}{% submission_key %} + +
+
+ {% 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 %} diff --git a/instances/tests/test_fstrim.py b/instances/tests/test_fstrim.py new file mode 100644 index 00000000..ecf976f2 --- /dev/null +++ b/instances/tests/test_fstrim.py @@ -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("
  • / 1\xa0GiB
  • ", page) + self.assertInHTML("
  • /boot not supported
  • ", 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 diff --git a/instances/tests/test_pending_edits.py b/instances/tests/test_pending_edits.py index 32cffb0f..00af8f8a 100644 --- a/instances/tests/test_pending_edits.py +++ b/instances/tests/test_pending_edits.py @@ -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": []} diff --git a/instances/urls.py b/instances/urls.py index 28b7d10d..5e3a883d 100755 --- a/instances/urls.py +++ b/instances/urls.py @@ -40,6 +40,7 @@ urlpatterns = [ path("/detach_vol/", views.detach_vol, name="detach_vol"), path("/add_cdrom/", views.add_cdrom, name="add_cdrom"), path("/add_pcie_slots/", views.add_pcie_slots, name="add_pcie_slots"), + path("/fstrim/", views.fstrim, name="fstrim"), path("/detach_cdrom//", views.detach_cdrom, name="detach_cdrom"), path("/unmount_iso/", views.unmount_iso, name="unmount_iso"), path("/mount_iso/", views.mount_iso, name="mount_iso"), diff --git a/instances/views.py b/instances/views.py index a5a1d633..3fdb9ed6 100755 --- a/instances/views.py +++ b/instances/views.py @@ -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 diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index 72c1e168..d5434b00 100644 Binary files a/locale/tr/LC_MESSAGES/django.mo and b/locale/tr/LC_MESSAGES/django.mo differ diff --git a/locale/tr/LC_MESSAGES/django.po b/locale/tr/LC_MESSAGES/django.po index 96881e5f..0000d45e 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -13358,3 +13358,51 @@ msgstr "Sanal makine arızası: %(vm)s" #: instances/jobs.py:1667 msgid "%(vm)s on %(host)s: %(reason)s" msgstr "%(host)s üzerindeki %(vm)s: %(reason)s" + +#: instances/jobs.py:1672 instances/templates/instances/settings_tab.html:301 +msgid "Free unused space" +msgstr "Kullanılmayan alanı boşalt" + +#: instances/jobs.py:1696 instances/templates/instances/settings_tab.html:301 +msgid "The guest agent is not connected" +msgstr "Konuk ajanı bağlı değil" + +#: instances/jobs.py:1704 +msgid "The job stopped before the guest answered; trimming again is harmless" +msgstr "İş, konuk yanıt vermeden durdu; yeniden boşaltmanın zararı yok" + +#: instances/jobs.py:1710 +msgid "" +"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." +msgstr "" +"Çalışan sanal makinenin hiçbir diskinde diskard modu unmap değil: imaj " +"dosyaları boyutunu korur. Bunu bir diskin aygıt ayrıntılarından ayarlayın; " +"sanal makinenin bir sonraki başlatılışında geçerli olur." + +#: instances/templates/instances/settings_tab.html:299 +msgid "Free space the guest no longer uses in the image files." +msgstr "Konuğun artık kullanmadığı alanı imaj dosyalarında boşaltır." + +#: instances/templates/instances/settings_tab.html:299 +msgid "" +"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." +msgstr "" +"Sanal makine çalışırken hiçbir diskin diskard modu unmap değil: boşaltma imaj" +" dosyalarında yer açmaz. Bunu bir diskin aygıt ayrıntılarından ayarlayın; bir" +" sonraki başlatılışta geçerli olur." + +#: operations/templates/operations/job.html:68 +msgid "Trimmed" +msgstr "Boşaltılan" + +#: operations/templates/operations/job.html:70 +msgid "trimmed" +msgstr "boşaltıldı" + +#: instances/jobs.py:1701 +msgid "No file system was trimmed: %(errors)s" +msgstr "Hiçbir dosya sistemi boşaltılmadı: %(errors)s" diff --git a/locale/uk/LC_MESSAGES/django.mo b/locale/uk/LC_MESSAGES/django.mo index 152b5a83..147c6d3d 100644 Binary files a/locale/uk/LC_MESSAGES/django.mo and b/locale/uk/LC_MESSAGES/django.mo differ diff --git a/locale/uk/LC_MESSAGES/django.po b/locale/uk/LC_MESSAGES/django.po index b3629637..484147b9 100644 --- a/locale/uk/LC_MESSAGES/django.po +++ b/locale/uk/LC_MESSAGES/django.po @@ -13450,3 +13450,55 @@ msgstr "Збій ВМ: %(vm)s" #: instances/jobs.py:1667 msgid "%(vm)s on %(host)s: %(reason)s" msgstr "ВМ %(vm)s на хості %(host)s: %(reason)s" + +#: instances/jobs.py:1672 instances/templates/instances/settings_tab.html:301 +msgid "Free unused space" +msgstr "Звільнити невикористаний простір" + +#: instances/jobs.py:1696 instances/templates/instances/settings_tab.html:301 +msgid "The guest agent is not connected" +msgstr "Гостьовий агент не під’єднано" + +#: instances/jobs.py:1704 +msgid "The job stopped before the guest answered; trimming again is harmless" +msgstr "" +"Завдання зупинилося до відповіді гостьової системи; повторне звільнення нічим" +" не шкодить" + +#: instances/jobs.py:1710 +msgid "" +"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." +msgstr "" +"Жоден диск запущеної ВМ не має режиму discard unmap: файли образів зберігають" +" свій розмір. Задайте його у відомостях про пристрій диска; він набуде " +"чинності під час наступного запуску ВМ." + +#: instances/templates/instances/settings_tab.html:299 +msgid "Free space the guest no longer uses in the image files." +msgstr "" +"Звільняє у файлах образів простір, який гостьова система більше не " +"використовує." + +#: instances/templates/instances/settings_tab.html:299 +msgid "" +"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." +msgstr "" +"Поки ВМ працює, жоден диск не має режиму discard unmap: звільнення не зменшує" +" файли образів. Задайте його у відомостях про пристрій диска; він набуде " +"чинності під час наступного запуску." + +#: operations/templates/operations/job.html:68 +msgid "Trimmed" +msgstr "Звільнено" + +#: operations/templates/operations/job.html:70 +msgid "trimmed" +msgstr "звільнено" + +#: instances/jobs.py:1701 +msgid "No file system was trimmed: %(errors)s" +msgstr "Жодну файлову систему не звільнено: %(errors)s" diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index 0ab2074e..2abe3d20 100644 Binary files a/locale/zh/LC_MESSAGES/django.mo and b/locale/zh/LC_MESSAGES/django.mo differ diff --git a/locale/zh/LC_MESSAGES/django.po b/locale/zh/LC_MESSAGES/django.po index 8dc250ef..8e5954cc 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -12490,3 +12490,45 @@ msgstr "虚拟机故障:%(vm)s" #: instances/jobs.py:1667 msgid "%(vm)s on %(host)s: %(reason)s" msgstr "%(host)s 上的 %(vm)s:%(reason)s" + +#: instances/jobs.py:1672 instances/templates/instances/settings_tab.html:301 +msgid "Free unused space" +msgstr "释放未使用空间" + +#: instances/jobs.py:1696 instances/templates/instances/settings_tab.html:301 +msgid "The guest agent is not connected" +msgstr "客户机代理未连接" + +#: instances/jobs.py:1704 +msgid "The job stopped before the guest answered; trimming again is harmless" +msgstr "作业在客户机应答前停止;再次修剪无害" + +#: instances/jobs.py:1710 +msgid "" +"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." +msgstr "运行中的虚拟机没有任何磁盘的 Discard 模式为 unmap:其镜像文件大小不变。请在磁盘的设备详情中设置;虚拟机下次启动时生效。" + +#: instances/templates/instances/settings_tab.html:299 +msgid "Free space the guest no longer uses in the image files." +msgstr "释放客户机不再使用的镜像文件空间。" + +#: instances/templates/instances/settings_tab.html:299 +msgid "" +"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." +msgstr "虚拟机运行时没有任何磁盘的 Discard 模式为 unmap:修剪不会释放其镜像文件中的空间。请在磁盘的设备详情中设置;下次启动时生效。" + +#: operations/templates/operations/job.html:68 +msgid "Trimmed" +msgstr "已修剪" + +#: operations/templates/operations/job.html:70 +msgid "trimmed" +msgstr "已修剪" + +#: instances/jobs.py:1701 +msgid "No file system was trimmed: %(errors)s" +msgstr "没有文件系统被修剪:%(errors)s" diff --git a/operations/templates/operations/job.html b/operations/templates/operations/job.html index 08774ad2..97dddbcf 100644 --- a/operations/templates/operations/job.html +++ b/operations/templates/operations/job.html @@ -21,7 +21,7 @@
    {% trans "User" %}: {{ job.username }}
    - {% if job.phase or op.progress_total or job.cancellable or job.error or job.result.open or job.result.links or job.result.warning or job.result.left_behind or job.resolution %} + {% if job.phase or op.progress_total or job.cancellable or job.error or job.result.open or job.result.links or job.result.warning or job.result.left_behind or job.result.trimmed or job.resolution %}
    {% if job.phase or job.cancellable %}
    @@ -64,6 +64,12 @@ {% if job.result.warning %} {% endif %} + {% if job.result.trimmed %} +

    {% trans "Trimmed" %}

    +
      + {% for fs in job.result.trimmed %}
    • {{ fs.path }} {% if fs.error %}{{ fs.error }}{% elif fs.trimmed is None %}{% trans "trimmed" %}{% else %}{{ fs.trimmed|binary_size }}{% endif %}
    • {% endfor %} +
    + {% endif %} {% if job.result.left_behind %}

    {% trans "Left behind" %}

      diff --git a/vrtManager/instance.py b/vrtManager/instance.py index 352d5bf1..941c2d23 100644 --- a/vrtManager/instance.py +++ b/vrtManager/instance.py @@ -103,6 +103,7 @@ USAGE_MAX_WINDOW = 30 USAGE_STATS = VIR_DOMAIN_STATS_CPU_TOTAL | VIR_DOMAIN_STATS_BLOCK | VIR_DOMAIN_STATS_INTERFACE # seconds the guest agent has to set a password or add a key AGENT_TIMEOUT = 10 +FSTRIM_TIMEOUT = 1800 # a guest trims each file system's free space: minutes on a large one # libvirt's values; bindings built against older libvirt (Ubuntu 24.04's) lack # the names, and the code comes from the host's libvirtd VIR_ERR_AGENT_COMMAND_TIMEOUT = 112 @@ -719,14 +720,14 @@ def disk_source(disk): tuple(tuple(sorted(host.attrib.items())) for host in source.findall("host"))) -def agent_command(dom, command, arguments=None): - """The answer of one guest agent command that waits AGENT_TIMEOUT seconds +def agent_command(dom, command, arguments=None, timeout=AGENT_TIMEOUT): + """The answer of one guest agent command that waits timeout seconds at most: libvirt's own calls for it wait for a hung agent indefinitely, and the domain's agent timeout is shared by every agent call.""" request = {"execute": command} if arguments is not None: request["arguments"] = arguments - return json.loads(qemuAgentCommand(dom, json.dumps(request), AGENT_TIMEOUT, 0))["return"] + return json.loads(qemuAgentCommand(dom, json.dumps(request), timeout, 0))["return"] def agent_interfaces(dom): @@ -2978,6 +2979,17 @@ class wvmInstance(wvmConnect): def abort_backup(self): self.instance.abortJob() + def fstrim(self): + """Has the guest agent trim the free space of each mounted file system, waiting + FSTRIM_TIMEOUT seconds at most: [{"path", "trimmed": bytes or None, "error": text or None}]. + The image files shrink only for disks whose discard mode is unmap.""" + self.ping_agent() + answer = agent_command(self.instance, "guest-fstrim", timeout=FSTRIM_TIMEOUT) + paths = answer.get("paths") if isinstance(answer, dict) else None + return [{"path": str(p["path"]), "trimmed": p.get("trimmed") if type(p.get("trimmed")) is int else None, + "error": str(p["error"]) if p.get("error") else None} + for p in paths or [] if isinstance(p, dict) and p.get("path")] + def ping_agent(self): """A frozen or dead agent fails here in AGENT_TIMEOUT seconds. The freeze that follows is libvirt's, without a timeout: a timed freeze