1
0
Fork 0
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:
catborise 2026-11-25 10:51:41 +03:00
parent d6cee18434
commit 8625d6250a
17 changed files with 367 additions and 5 deletions

View file

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

View file

@ -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) | ❌ |

View file

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

View file

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

View file

@ -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 %}

View 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

View file

@ -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": []}

View file

@ -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"),

View file

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

Binary file not shown.

View file

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

Binary file not shown.

View file

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

Binary file not shown.

View file

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

View file

@ -21,7 +21,7 @@
</div>
<div class="small text-body-secondary mt-1">{% trans "User" %}: {{ job.username }}</div>
</div>
{% 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 %}
<div class="card-body pb-0">
{% if job.phase or job.cancellable %}
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
@ -64,6 +64,12 @@
{% if job.result.warning %}
<div class="alert alert-warning text-break" role="alert">{{ job.result.warning }}</div>
{% endif %}
{% if job.result.trimmed %}
<h2 class="h6">{% trans "Trimmed" %}</h2>
<ul class="list-unstyled mb-3">
{% for fs in job.result.trimmed %}<li class="text-break"><code>{{ fs.path }}</code> {% if fs.error %}{{ fs.error }}{% elif fs.trimmed is None %}{% trans "trimmed" %}{% else %}{{ fs.trimmed|binary_size }}{% endif %}</li>{% endfor %}
</ul>
{% endif %}
{% if job.result.left_behind %}
<h2 class="h6">{% trans "Left behind" %}</h2>
<ul class="list-unstyled mb-3">

View file

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