mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 17:36:05 +00:00
feat(instances): the VM page shows the VM's screen
A running or paused VM with a VNC or SPICE console shows its screen beside the summary (virDomainScreenshot, PNG), read again every 10 s while the page is in view; clicking it opens the console. It is for those who may open the console (the screen shows what the console does) and is left out while there is none to show, also on a host whose libvirt gives PPM. The VM list does not read screens: one a VM would cost too much.
This commit is contained in:
parent
8625d6250a
commit
d5cc696d73
18 changed files with 205 additions and 9 deletions
|
|
@ -11,12 +11,10 @@ from django.conf import settings
|
|||
from django.shortcuts import redirect, render
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from instances.models import Instance
|
||||
from instances.utils import can_open_console
|
||||
from instances.utils import can_open_console, novnc_unreachable
|
||||
from libvirt import libvirtError
|
||||
from operations.utils import safe_text
|
||||
from vrtManager.connection import CONN_TCP, CONN_TLS
|
||||
from vrtManager.instance import wvmInstance
|
||||
from vrtManager.util import is_loopback
|
||||
from webvirtcloud.middleware import error_text
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
|
@ -68,9 +66,8 @@ def console(request, compute_id, uuid):
|
|||
running = conn.instance.isActive()
|
||||
# novncd reaches a console that listens on its host's loopback only
|
||||
# through SSH (or on this host); the running VM's listener, as novncd sees it
|
||||
unreachable = instance.compute.type in (CONN_TCP, CONN_TLS) and bool(
|
||||
conn.get_console_socket() or is_loopback(conn.get_console_listener_addr())
|
||||
)
|
||||
unreachable = novnc_unreachable(instance.compute.type, conn.get_console_socket(),
|
||||
conn.get_console_listener_addr())
|
||||
except libvirtError as err:
|
||||
# the host or the VM could not be read: the page says that, not to check the console settings
|
||||
logger.warning("Console of %s on %s: %s", instance.name, instance.compute.name, safe_text(err))
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
- The VM page shows a running or paused VM's screen beside its summary, read again every 10 seconds, to those who may open its console; clicking it opens the console. It needs a VNC or SPICE console and a host whose libvirt gives screenshots as PNG (libvirt 9 and QEMU 7.1 or later); otherwise it is not shown.
|
||||
- **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.
|
||||
|
|
|
|||
|
|
@ -21,7 +21,8 @@
|
|||
data-opens-on="{% if instance.is_template and can_clone %}#clone{% endif %}"
|
||||
data-random-mac-url="{% url 'instances:random_mac_address' %}"
|
||||
{% if can_open_console and vdi_reachable %}data-vdi-url="{% url 'vdi_url' compute.id instance.name %}"{% endif %}>
|
||||
<div class="card-body p-3">
|
||||
<div class="card-body p-3 d-flex flex-wrap flex-md-nowrap gap-3">
|
||||
<div class="flex-grow-1" style="min-width: 0;">
|
||||
<div class="d-flex flex-wrap justify-content-between align-items-start gap-2">
|
||||
<div style="min-width: 0;">
|
||||
<div class="d-flex flex-wrap align-items-center gap-2">
|
||||
|
|
@ -88,6 +89,21 @@
|
|||
</div>
|
||||
{% endif %}
|
||||
</dl>
|
||||
</div>
|
||||
{% if show_screen %}
|
||||
{# the VM's screen, read by instance_page.js every few seconds and shown once one has come; opens the console where it can #}
|
||||
{% if screen_opens_console %}
|
||||
<button type="button" class="vm-screen" id="vm-screen" hidden data-url="{% url 'console' compute.id instance.uuid %}"
|
||||
data-window="console-{{ instance.uuid }}" data-screen-url="{% url 'instances:screen' instance.id %}"
|
||||
title="{% trans "Open console" %}">
|
||||
<img alt="{% blocktrans with name=instance.name %}Screen of {{ name }}{% endblocktrans %}">
|
||||
</button>
|
||||
{% else %}
|
||||
<div class="vm-screen" id="vm-screen" hidden data-screen-url="{% url 'instances:screen' instance.id %}">
|
||||
<img alt="{% blocktrans with name=instance.name %}Screen of {{ name }}{% endblocktrans %}">
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="card-footer p-1">
|
||||
{# p-1 inside the scroller keeps the focus ring from being clipped #}
|
||||
|
|
|
|||
|
|
@ -188,6 +188,22 @@ class PendingEditsTestCase(TestCase):
|
|||
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_summary_shows_the_screen_of_a_running_or_paused_vm_with_graphics(self):
|
||||
screen = "//*[@id='vm-screen']"
|
||||
url = reverse("instances:screen", args=[self.instance.id])
|
||||
reachable = {"get_console_type": ("vnc", "vnc"), "get_console_socket": (None, None),
|
||||
"get_console_listener_addr": ("0.0.0.0", "0.0.0.0")}
|
||||
for status in (1, 3):
|
||||
(element,) = self.page(status=status, **reachable).xpath(screen)
|
||||
# shown once its script has read a frame; a button that opens the console
|
||||
self.assertEqual((element.tag, element.get("hidden"), element.get("data-screen-url")), ("button", "", url))
|
||||
self.assertFalse(self.page(status=5, **reachable).xpath(screen))
|
||||
# a console the panel cannot open (loopback VNC on a TCP host, SPICE): the screen alone, not a button
|
||||
for console in ({**reachable, "get_console_listener_addr": ("127.0.0.1", "127.0.0.1")},
|
||||
{**reachable, "get_console_type": ("spice", "spice")}):
|
||||
(element,) = self.page(**console).xpath(screen)
|
||||
self.assertEqual((element.tag, element.get("data-window")), ("div", None))
|
||||
|
||||
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": []}
|
||||
|
|
|
|||
66
instances/tests/test_screen.py
Normal file
66
instances/tests/test_screen.py
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
"""The VM's screen on its page: a PNG from libvirt (virDomainScreenshot), for those who may open its console."""
|
||||
from unittest.mock import MagicMock, PropertyMock, patch
|
||||
|
||||
import libvirt
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from accounts.models import UserInstance
|
||||
from computes.models import Compute
|
||||
from instances.models import Instance
|
||||
from vrtManager.instance import wvmInstance
|
||||
|
||||
PNG = b"\x89PNG\r\n\x1a\nimage"
|
||||
|
||||
|
||||
class ScreenTestCase(TestCase):
|
||||
def setUp(self):
|
||||
self.admin = get_user_model().objects.create_superuser("sc-admin", "sc@example.com", "pw")
|
||||
compute = Compute.objects.create(name="sc-host", hostname="192.0.2.91", login="", password="", type=4)
|
||||
self.vm = Instance.objects.create(compute=compute, name="sc-vm", uuid="91919191-0000-4000-8000-000000000001")
|
||||
self.proxy = MagicMock(**{"screenshot.return_value": ("image/png", PNG)})
|
||||
patch.object(Instance, "proxy", property(lambda vm: self.proxy)).start()
|
||||
self.status = patch.object(Instance, "status", new_callable=PropertyMock, return_value=1).start()
|
||||
self.console = patch.object(Instance, "console_type", new_callable=PropertyMock, return_value="vnc").start()
|
||||
self.addCleanup(patch.stopall)
|
||||
|
||||
def get(self, user):
|
||||
self.client.force_login(user)
|
||||
return self.client.get(reverse("instances:screen", args=[self.vm.pk]))
|
||||
|
||||
def test_a_running_vm_s_screen_is_a_png_not_kept_by_the_browser(self):
|
||||
response = self.get(self.admin)
|
||||
self.assertEqual((response.status_code, response["Content-Type"], response.content), (200, "image/png", PNG))
|
||||
self.assertEqual(response["Cache-Control"], "no-store")
|
||||
|
||||
def test_only_those_who_may_open_the_console_see_it(self):
|
||||
viewer = get_user_model().objects.create_user("sc-viewer", "v@example.com", "pw")
|
||||
viewer.user_permissions.add(Permission.objects.get(codename="view_instances"))
|
||||
self.assertEqual(self.get(viewer).status_code, 403) # reads every VM, opens no console
|
||||
owner = get_user_model().objects.create_user("sc-owner", "o@example.com", "pw")
|
||||
UserInstance.objects.create(user=owner, instance=self.vm)
|
||||
self.assertEqual(self.get(owner).status_code, 200)
|
||||
|
||||
def test_no_screen_is_a_404(self):
|
||||
for status, console, answer in ((5, "vnc", None), (1, "", None), (1, "vnc", ("image/x-portable-pixmap", b"P6")),
|
||||
(1, "vnc", libvirt.libvirtError("no screen"))):
|
||||
with self.subTest(status=status, console=console, answer=answer):
|
||||
self.status.return_value, self.console.return_value = status, console
|
||||
self.proxy.screenshot.side_effect = [answer] if answer else None
|
||||
self.assertEqual(self.get(self.admin).status_code, 404)
|
||||
|
||||
|
||||
class ScreenshotCallTestCase(TestCase):
|
||||
def test_the_stream_is_read_whole_and_aborted_on_failure(self):
|
||||
proxy = MagicMock()
|
||||
stream = proxy.wvm.newStream.return_value
|
||||
proxy.instance.screenshot.return_value = "image/png"
|
||||
stream.recvAll.side_effect = lambda handler, buffer: [handler(stream, part, buffer) for part in (b"ab", b"cd")]
|
||||
self.assertEqual(wvmInstance.screenshot(proxy), ("image/png", b"abcd"))
|
||||
stream.finish.assert_called_once_with()
|
||||
proxy.instance.screenshot.side_effect = libvirt.libvirtError("gone")
|
||||
with self.assertRaises(libvirt.libvirtError):
|
||||
wvmInstance.screenshot(proxy)
|
||||
stream.abort.assert_called_once_with()
|
||||
|
|
@ -24,6 +24,7 @@ urlpatterns = [
|
|||
path("<int:pk>/destroy/", views.destroy, name="destroy"),
|
||||
path("<int:pk>/migrate/", views.migrate, name="migrate"),
|
||||
path("<int:pk>/status/", views.status, name="status"),
|
||||
path("<int:pk>/screen/", views.screen, name="screen"),
|
||||
path("<int:pk>/addresses/", views.nic_addresses, name="nic_addresses"),
|
||||
path("<int:pk>/stats/", views.stats, name="stats"),
|
||||
path("<int:pk>/osinfo/", views.osinfo, name="osinfo"),
|
||||
|
|
|
|||
|
|
@ -20,9 +20,9 @@ from libvirt import libvirtError
|
|||
from logs.audit import reason, write
|
||||
from operations.models import Operation
|
||||
from operations.utils import migration_bandwidth
|
||||
from vrtManager.connection import counted_thread, other_hosts, wvmConnect
|
||||
from vrtManager.connection import CONN_TCP, CONN_TLS, counted_thread, other_hosts, wvmConnect
|
||||
from vrtManager.instance import wvmInstance, wvmInstances
|
||||
from vrtManager.util import ConnectionFailed, HostBusy, message, vol_dev_type
|
||||
from vrtManager.util import ConnectionFailed, HostBusy, is_loopback, message, vol_dev_type
|
||||
|
||||
from .models import Instance
|
||||
from .states import state_reason
|
||||
|
|
@ -42,6 +42,13 @@ def can_open_console(user, instance):
|
|||
return UserInstance.objects.filter(instance=instance, user=user).exists()
|
||||
|
||||
|
||||
def novnc_unreachable(compute_type, socket, listener):
|
||||
"""Whether novncd cannot reach a VNC console: one that listens on its host's loopback or on a
|
||||
socket only, on a host the panel reaches over TCP or TLS (SSH tunnels to it, the socket type is
|
||||
on this host)."""
|
||||
return compute_type in (CONN_TCP, CONN_TLS) and bool(socket or is_loopback(listener))
|
||||
|
||||
|
||||
def get_clone_free_names(size=10):
|
||||
prefix = app_settings.CLONE_INSTANCE_DEFAULT_PREFIX
|
||||
free_names = []
|
||||
|
|
|
|||
|
|
@ -352,6 +352,12 @@ def _instance_page(request, pk, instance, compute):
|
|||
vdi_reachable = instance.console_type in ("vnc", "spice") and not util.is_loopback(instance.console_listener_address)
|
||||
# root's password and keys change in a shut-off VM's disk (gstfsd on the host), or through a running VM's agent
|
||||
guest_access_ready = instance.status == 5 or (instance.status == 1 and instance.guest_agent_ready)
|
||||
# its screen beside the summary: what the console shows, so for those who may open it
|
||||
show_screen = can_open_console and not instance.is_template and instance.status in (1, 3) \
|
||||
and instance.console_type in ("vnc", "spice")
|
||||
# clicked, it opens the console where the console page can: a VNC one novncd reaches
|
||||
screen_opens_console = show_screen and instance.console_type == "vnc" and not utils.novnc_unreachable(
|
||||
instance.compute.type, instance.proxy.get_console_socket(), instance.console_listener_address)
|
||||
# get_instance(perm_type="delete"): a template only for superusers and staff owners
|
||||
can_delete = request.user.is_superuser or bool(
|
||||
userinstance and userinstance.is_delete and (request.user.is_staff or not instance.is_template)
|
||||
|
|
@ -432,6 +438,8 @@ def _instance_page(request, pk, instance, compute):
|
|||
"can_manage_console": can_manage_console,
|
||||
"console_form": console_form,
|
||||
"can_open_console": can_open_console,
|
||||
"show_screen": show_screen,
|
||||
"screen_opens_console": screen_opens_console,
|
||||
"can_power": can_power,
|
||||
"can_delete": can_delete,
|
||||
"can_change": can_change,
|
||||
|
|
@ -471,6 +479,26 @@ def status(request, pk):
|
|||
return JsonResponse({"status": state, "reason": reason})
|
||||
|
||||
|
||||
def screen(request, pk):
|
||||
"""The VM's screen as a PNG, for the users who may open its console (utils.can_open_console):
|
||||
404 while it has none to show (not running or paused, no graphics, or a host whose libvirt
|
||||
gives no PNG)."""
|
||||
instance = get_instance(request.user, pk)
|
||||
if not utils.can_open_console(request.user, instance):
|
||||
raise PermissionDenied
|
||||
if instance.status not in (1, 3) or instance.console_type not in ("vnc", "spice"):
|
||||
raise Http404
|
||||
try:
|
||||
mime, data = instance.proxy.screenshot()
|
||||
except libvirtError:
|
||||
raise Http404 from None
|
||||
if mime != "image/png":
|
||||
raise Http404
|
||||
response = HttpResponse(data, content_type="image/png")
|
||||
response["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
|
||||
def nic_addresses(request, pk):
|
||||
"""The VM's addresses by MAC, which its page shows once it has loaded
|
||||
(vm_addresses.js): the guest agent may take its whole timeout. A host
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -13406,3 +13406,7 @@ 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"
|
||||
|
||||
#: instances/templates/instance.html:98
|
||||
msgid "Screen of %(name)s"
|
||||
msgstr "%(name)s ekranı"
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -13502,3 +13502,7 @@ msgstr "звільнено"
|
|||
#: instances/jobs.py:1701
|
||||
msgid "No file system was trimmed: %(errors)s"
|
||||
msgstr "Жодну файлову систему не звільнено: %(errors)s"
|
||||
|
||||
#: instances/templates/instance.html:98
|
||||
msgid "Screen of %(name)s"
|
||||
msgstr "Екран ВМ %(name)s"
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -12532,3 +12532,7 @@ msgstr "已修剪"
|
|||
#: instances/jobs.py:1701
|
||||
msgid "No file system was trimmed: %(errors)s"
|
||||
msgstr "没有文件系统被修剪:%(errors)s"
|
||||
|
||||
#: instances/templates/instance.html:98
|
||||
msgid "Screen of %(name)s"
|
||||
msgstr "%(name)s 的屏幕"
|
||||
|
|
|
|||
|
|
@ -382,3 +382,20 @@ td .tag-more {
|
|||
.run-none { background: var(--bs-secondary-bg); }
|
||||
/* high contrast themes would drop the marks' colours, which carry their meaning */
|
||||
@media (forced-colors: active) { .run-mark { forced-color-adjust: none; } }
|
||||
|
||||
/* the VM page's screen thumbnail (instance.html): the console's picture, a button that opens it */
|
||||
.vm-screen {
|
||||
display: block;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
max-width: 16rem;
|
||||
aspect-ratio: 4 / 3;
|
||||
overflow: hidden;
|
||||
background: #000;
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: var(--bs-border-radius);
|
||||
}
|
||||
.vm-screen[hidden] { display: none; }
|
||||
.vm-screen img { display: block; width: 100%; height: 100%; object-fit: contain; }
|
||||
.vm-screen:focus-visible { outline: 0; box-shadow: var(--bs-focus-ring-x, 0) var(--bs-focus-ring-y, 0) 0 var(--bs-focus-ring-width) var(--bs-focus-ring-color); }
|
||||
@media (min-width: 768px) { .vm-screen { flex: none; width: 13rem; align-self: flex-start; } }
|
||||
|
|
|
|||
|
|
@ -20,6 +20,25 @@
|
|||
if (element) element.addEventListener(event, handler);
|
||||
}
|
||||
|
||||
// the VM's screen: read now and every 10 s while the page is in view, one read at a time; a frame
|
||||
// replaces the shown one once it has fully come, and the screen is hidden while there is none
|
||||
var screen = document.getElementById("vm-screen");
|
||||
if (screen) {
|
||||
var shown = screen.querySelector("img");
|
||||
var reading = false;
|
||||
var read_screen = function () {
|
||||
if (reading || document.hidden) return;
|
||||
reading = true;
|
||||
var frame = new Image();
|
||||
frame.alt = shown.alt;
|
||||
frame.onload = function () { shown.replaceWith(frame); shown = frame; screen.hidden = false; reading = false; };
|
||||
frame.onerror = function () { screen.hidden = true; reading = false; };
|
||||
frame.src = screen.dataset.screenUrl + "?t=" + Date.now();
|
||||
};
|
||||
read_screen();
|
||||
setInterval(read_screen, 10000);
|
||||
}
|
||||
|
||||
// the guest OS details, read through the guest agent
|
||||
function load_osinfo() {
|
||||
var error = $('#osinfo-error');
|
||||
|
|
|
|||
|
|
@ -2979,6 +2979,21 @@ class wvmInstance(wvmConnect):
|
|||
def abort_backup(self):
|
||||
self.instance.abortJob()
|
||||
|
||||
def screenshot(self):
|
||||
"""The running or paused VM's screen as libvirt gives it: (MIME type, bytes); PNG from
|
||||
libvirt 9.x with QEMU 7.1 on, PPM before."""
|
||||
stream = self.wvm.newStream(0)
|
||||
try:
|
||||
mime = self.instance.screenshot(stream, 0, 0)
|
||||
data = bytearray()
|
||||
stream.recvAll(lambda _stream, chunk, buffer: buffer.extend(chunk), data)
|
||||
stream.finish()
|
||||
except libvirtError:
|
||||
with contextlib.suppress(libvirtError):
|
||||
stream.abort()
|
||||
raise
|
||||
return mime, bytes(data)
|
||||
|
||||
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}].
|
||||
|
|
|
|||
|
|
@ -105,6 +105,7 @@ POWER_AND_CONSOLE = {
|
|||
"compute-instance-powercycle",
|
||||
"compute-instance-forceoff",
|
||||
"instances:getvvfile",
|
||||
"instances:screen",
|
||||
# vdi_url is also allowed for owners, but answers 404 here because the
|
||||
# test compute is unreachable; see the console rule tests.
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue