controller: report and stop every installed VNC backend

Greptile P1 (security): with both stacks installed, selection keyed only off
wayvnc's unit and config. If RealVNC was the one running, status reported VNC
as off and stop targeted wayvnc — leaving the screen remotely accessible while
the UI claimed VNC was off. Reproduced on 10.0.0.8: RealVNC serving on 5900
reported as running=false.

Now every installed backend is reported with its own active state: status is on
when any backend runs and names the one actually serving, and stop stops all
running backends. wayvnc is still preferred for starting.

Greptile P2 (latency): both units are probed in a single multi-unit
`systemctl show`, and the status dict no longer re-probes, so VNC adds one
subprocess to /api/stats rather than three.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-07-29 17:17:27 -06:00 • committed by lrnselfreliance
parent 2328524ab2
commit 5313ab57ef
3 changed files with 310 additions and 130 deletions

View file

@ -745,6 +745,36 @@ async def _unit_properties(unit: str, *properties: str) -> dict | None:
)
async def _units_properties(units: list[str], *properties: str) -> list[dict] | None:
"""
Read the same systemd properties for several units in one `systemctl show` call.
Output is one blank-line-separated block per unit, in the order asked for.
Batching matters because these probes run on every /api/stats request.
Returns one dict per unit, or None when systemctl itself failed.
"""
proc = await asyncio.create_subprocess_exec(
"systemctl", "show", *units, f"--property={','.join(properties)}",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=5)
if proc.returncode != 0:
return None
blocks = []
for block in stdout.decode().strip().split("\n\n"):
blocks.append(dict(
line.split("=", 1) for line in block.strip().splitlines() if "=" in line
))
# Pad so callers can index by unit even if systemd reported fewer blocks.
while len(blocks) < len(units):
blocks.append({})
return blocks
async def _systemctl_unit(action: str, unit: str, label: str) -> dict:
"""Run `systemctl <start|stop> <unit>` and report the result."""
if is_docker_mode():
@ -978,18 +1008,17 @@ REALVNC_UNIT = "vncserver-x11-serviced.service"
VNC_PORT = 5900
async def _unit_is_loaded(unit: str) -> bool:
"""Whether systemd knows about a unit."""
properties = await _unit_properties(unit, "LoadState")
return bool(properties) and properties.get("LoadState") == "loaded"
async def get_vnc_backend() -> tuple[str | None, str | None, str | None]:
async def get_vnc_backends() -> tuple[list[dict], str | None]:
"""
Pick the VNC backend to control.
List the usable VNC backends in preference order, with their current state.
Prefers wayvnc (Raspberry Pi OS uses Wayland), falling back to RealVNC.
Both stacks can be installed at once and *either* can be running — a user may
have started RealVNC through raspi-config. Reporting only the preferred
backend would claim "VNC is off" while the other one is still serving the
screen, so every installed backend is reported and `stop_vnc()` stops all of
the running ones.
Prefers wayvnc (Raspberry Pi OS uses Wayland) when choosing what to start.
Deliberately does not copy `raspi-config`'s live-compositor probe
(`pgrep labwc || pgrep wayfire`), which reports X11 — and would therefore pick
RealVNC — whenever the desktop happens to be stopped.
@ -997,28 +1026,45 @@ async def get_vnc_backend() -> tuple[str | None, str | None, str | None]:
Never raises: a host without systemd simply has no VNC backend.
Returns:
(unit, name, reason) where reason explains an absent backend
(backends, reason) where each backend is {"unit", "name", "active"} and
reason explains an empty list
"""
unavailable = "VNC not supported or systemctl unavailable"
try:
wayvnc_loaded = await _unit_is_loaded(WAYVNC_UNIT)
if wayvnc_loaded and WAYVNC_CONFIG.is_file():
return WAYVNC_UNIT, "wayvnc", None
if await _unit_is_loaded(REALVNC_UNIT):
return REALVNC_UNIT, "realvnc", None
properties = await _units_properties([WAYVNC_UNIT, REALVNC_UNIT], "LoadState", "ActiveState")
except (asyncio.TimeoutError, OSError):
return None, None, "VNC not supported or systemctl unavailable"
return [], unavailable
if properties is None:
return [], unavailable
wayvnc_properties, realvnc_properties = properties[0], properties[1]
backends = []
wayvnc_loaded = wayvnc_properties.get("LoadState") == "loaded"
if wayvnc_loaded and WAYVNC_CONFIG.is_file():
backends.append({
"unit": WAYVNC_UNIT,
"name": "wayvnc",
"active": wayvnc_properties.get("ActiveState") == "active",
})
if realvnc_properties.get("LoadState") == "loaded":
backends.append({
"unit": REALVNC_UNIT,
"name": "realvnc",
"active": realvnc_properties.get("ActiveState") == "active",
})
if backends:
return backends, None
if wayvnc_loaded:
# Installed but unconfigured; starting it would fail its own condition.
return None, None, f"wayvnc is installed but not configured ({WAYVNC_CONFIG} is missing)"
return None, None, "No VNC server installed"
return [], f"wayvnc is installed but not configured ({WAYVNC_CONFIG} is missing)"
return [], "No VNC server installed"
async def get_vnc_status() -> VncStatus:
"""
Get the VNC server status from whichever backend is installed.
Get the VNC server status; on when *any* installed backend is running.
Returns:
VncStatus enum value
@ -1026,23 +1072,11 @@ async def get_vnc_status() -> VncStatus:
if is_docker_mode():
return VncStatus.unknown
try:
unit, _, _ = await get_vnc_backend()
if unit is None:
return VncStatus.unavailable
properties = await _unit_properties(unit, "ActiveState")
if properties is None:
return VncStatus.unknown
return VncStatus.on if properties.get("ActiveState") == "active" else VncStatus.off
except asyncio.TimeoutError:
return VncStatus.unknown
except FileNotFoundError:
backends, _ = await get_vnc_backends()
if not backends:
return VncStatus.unavailable
except OSError:
return VncStatus.unknown
return VncStatus.on if any(backend["active"] for backend in backends) else VncStatus.off
async def get_vnc_status_dict() -> dict:
@ -1050,27 +1084,39 @@ async def get_vnc_status_dict() -> dict:
Get VNC status as a dict for API responses.
Returns dict matching VncStatusResponse schema:
running: bool - Whether the VNC server is currently running
running: bool - Whether any VNC server is currently running
available: bool - Whether a usable VNC server is installed
desktop_running: bool - Whether the desktop VNC would serve is running
can_start: bool - Whether VNC can be started right now
reason: Optional[str] - Why VNC is unavailable or cannot be started
backend: Optional[str] - "wayvnc" or "realvnc"
backend: Optional[str] - The running backend, else the preferred one
port: int - Port the VNC server listens on
"""
status = await get_vnc_status()
_, backend, unavailable_reason = await get_vnc_backend()
if is_docker_mode():
return {
"running": False,
"available": False,
"desktop_running": False,
"can_start": False,
"reason": "Not available in Docker mode",
"backend": None,
"port": VNC_PORT,
}
backends, unavailable_reason = await get_vnc_backends()
desktop_running = await get_desktop_status() == DesktopStatus.on
running = status == VncStatus.on
available = status in (VncStatus.on, VncStatus.off)
active = [backend for backend in backends if backend["active"]]
running = bool(active)
available = bool(backends)
# VNC serves the desktop session, so there is nothing to show without it.
can_start = available and desktop_running
# Name whichever backend is actually serving, so the UI cannot report wayvnc
# while RealVNC is the one running.
backend = (active or backends)[0]["name"] if backends else None
reason = None
if status == VncStatus.unknown:
reason = "VNC not supported or systemctl unavailable"
elif status == VncStatus.unavailable:
if not available:
reason = unavailable_reason or "No VNC server installed"
elif not desktop_running:
reason = "The Desktop must be running to use VNC"
@ -1103,8 +1149,8 @@ async def start_vnc() -> dict:
if is_docker_mode():
return {"success": False, "error": "Not available in Docker mode"}
unit, _, reason = await get_vnc_backend()
if unit is None:
backends, reason = await get_vnc_backends()
if not backends:
return {"success": False, "error": reason or "No VNC server installed"}
if await get_desktop_status() != DesktopStatus.on:
@ -1114,12 +1160,16 @@ async def start_vnc() -> dict:
"precondition_failed": True,
}
return await _systemctl_unit("start", unit, "VNC")
return await _systemctl_unit("start", backends[0]["unit"], "VNC")
async def stop_vnc() -> dict:
"""
Stop the VNC server.
Stop every running VNC server.
All running backends are stopped, not just the preferred one: leaving the
other stack serving while the Controller reports VNC as off would keep the
screen remotely accessible.
Always allowed, even with the desktop stopped, so a running VNC server can
never be left on with no way to turn it off.
@ -1130,11 +1180,22 @@ async def stop_vnc() -> dict:
if is_docker_mode():
return {"success": False, "error": "Not available in Docker mode"}
unit, _, reason = await get_vnc_backend()
if unit is None:
backends, reason = await get_vnc_backends()
if not backends:
return {"success": False, "error": reason or "No VNC server installed"}
return await _systemctl_unit("stop", unit, "VNC")
# Nothing running: still issue a stop so the call stays idempotent.
units = [backend["unit"] for backend in backends if backend["active"]] or [backends[0]["unit"]]
errors = []
for unit in units:
result = await _systemctl_unit("stop", unit, "VNC")
if not result.get("success"):
errors.append(f"{unit}: {result.get('error')}")
if errors:
return {"success": False, "error": "; ".join(errors)}
return {"success": True}
GOVERNOR_MAP = {

View file

@ -37,7 +37,7 @@ from controller.lib.admin import (
get_desktop_status_dict,
start_desktop,
stop_desktop,
get_vnc_backend,
get_vnc_backends,
get_vnc_status,
get_vnc_status_dict,
start_vnc,
@ -1329,55 +1329,103 @@ def _ok_proc() -> mock.AsyncMock:
return proc
class TestGetVncBackend:
"""wayvnc is preferred over RealVNC, and must actually be configured."""
def _multi_show_proc(*blocks: str, returncode: int = 0) -> mock.AsyncMock:
"""A mocked multi-unit `systemctl show`: one blank-line-separated block per unit."""
proc = mock.AsyncMock()
proc.communicate.return_value = ("\n\n".join(blocks).encode(), b"")
proc.returncode = returncode
return proc
def _backends_proc(wayvnc="loaded", wayvnc_active="inactive",
realvnc="loaded", realvnc_active="inactive") -> mock.AsyncMock:
return _multi_show_proc(
f"LoadState={wayvnc}\nActiveState={wayvnc_active}",
f"LoadState={realvnc}\nActiveState={realvnc_active}",
)
class TestGetVncBackends:
"""Both stacks can be installed, and either can be running."""
@pytest.mark.asyncio
async def test_prefers_wayvnc_when_configured(self):
"""A loaded, configured wayvnc wins even when RealVNC is also installed."""
with mock.patch("asyncio.create_subprocess_exec", return_value=_show_proc("LoadState=loaded\n")):
async def test_probes_both_units_in_one_call(self):
"""One `systemctl show` for both units; these probes run on every /api/stats."""
with mock.patch("asyncio.create_subprocess_exec", return_value=_backends_proc()) as mock_exec:
with mock.patch("controller.lib.admin.WAYVNC_CONFIG") as config:
config.is_file.return_value = True
unit, name, reason = await get_vnc_backend()
backends, reason = await get_vnc_backends()
assert unit == "wayvnc.service"
assert name == "wayvnc"
mock_exec.assert_called_once()
assert "wayvnc.service" in mock_exec.call_args.args
assert "vncserver-x11-serviced.service" in mock_exec.call_args.args
assert [b["name"] for b in backends] == ["wayvnc", "realvnc"]
assert reason is None
@pytest.mark.asyncio
async def test_falls_back_to_realvnc_when_wayvnc_unconfigured(self):
"""An unconfigured wayvnc must not be chosen; RealVNC is used instead."""
with mock.patch("asyncio.create_subprocess_exec", return_value=_show_proc("LoadState=loaded\n")):
async def test_wayvnc_is_preferred_for_starting(self):
"""wayvnc comes first, so it is what start_vnc() uses."""
with mock.patch("asyncio.create_subprocess_exec", return_value=_backends_proc()):
with mock.patch("controller.lib.admin.WAYVNC_CONFIG") as config:
config.is_file.return_value = True
backends, _ = await get_vnc_backends()
assert backends[0]["unit"] == "wayvnc.service"
@pytest.mark.asyncio
async def test_reports_each_backend_active_state(self):
"""A running RealVNC must be reported even though wayvnc is preferred."""
proc = _backends_proc(realvnc_active="active")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
with mock.patch("controller.lib.admin.WAYVNC_CONFIG") as config:
config.is_file.return_value = True
backends, _ = await get_vnc_backends()
assert backends[0] == {"unit": "wayvnc.service", "name": "wayvnc", "active": False}
assert backends[1] == {"unit": "vncserver-x11-serviced.service", "name": "realvnc", "active": True}
@pytest.mark.asyncio
async def test_skips_unconfigured_wayvnc(self):
"""An unconfigured wayvnc is not usable; RealVNC is."""
with mock.patch("asyncio.create_subprocess_exec", return_value=_backends_proc()):
with mock.patch("controller.lib.admin.WAYVNC_CONFIG") as config:
config.is_file.return_value = False
unit, name, reason = await get_vnc_backend()
backends, reason = await get_vnc_backends()
assert unit == "vncserver-x11-serviced.service"
assert name == "realvnc"
assert [b["name"] for b in backends] == ["realvnc"]
assert reason is None
@pytest.mark.asyncio
async def test_reports_unconfigured_wayvnc_when_alone(self):
"""wayvnc installed but unconfigured, with no RealVNC, explains itself."""
procs = [_show_proc("LoadState=loaded\n"), _show_proc("LoadState=not-found\n")]
with mock.patch("asyncio.create_subprocess_exec", side_effect=procs):
proc = _backends_proc(realvnc="not-found")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
with mock.patch("controller.lib.admin.WAYVNC_CONFIG") as config:
config.is_file.return_value = False
unit, name, reason = await get_vnc_backend()
backends, reason = await get_vnc_backends()
assert unit is None
assert name is None
assert backends == []
assert "not configured" in reason
@pytest.mark.asyncio
async def test_reports_nothing_installed(self):
"""Neither backend installed is reported plainly."""
with mock.patch("asyncio.create_subprocess_exec", return_value=_show_proc("LoadState=not-found\n")):
unit, name, reason = await get_vnc_backend()
proc = _backends_proc(wayvnc="not-found", realvnc="not-found")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
backends, reason = await get_vnc_backends()
assert unit is None
assert backends == []
assert reason == "No VNC server installed"
@pytest.mark.asyncio
async def test_survives_missing_systemctl(self):
"""A host without systemd simply has no VNC backend."""
with mock.patch("asyncio.create_subprocess_exec", side_effect=FileNotFoundError()):
backends, reason = await get_vnc_backends()
assert backends == []
assert reason
@pytest.mark.asyncio
async def test_does_not_probe_the_compositor(self):
"""Backend choice must not depend on a running compositor.
@ -1385,10 +1433,10 @@ class TestGetVncBackend:
raspi-config uses `pgrep labwc` to decide Wayland-vs-X11, which reports X11
whenever the desktop is stopped and would pick the wrong backend.
"""
with mock.patch("asyncio.create_subprocess_exec", return_value=_show_proc("LoadState=loaded\n")) as mock_exec:
with mock.patch("asyncio.create_subprocess_exec", return_value=_backends_proc()) as mock_exec:
with mock.patch("controller.lib.admin.WAYVNC_CONFIG") as config:
config.is_file.return_value = True
await get_vnc_backend()
await get_vnc_backends()
for call in mock_exec.call_args_list:
assert "pgrep" not in call.args[0]
@ -1404,59 +1452,85 @@ class TestGetVncStatus:
assert await get_vnc_status() == VncStatus.unknown
@pytest.mark.asyncio
@pytest.mark.parametrize("active_state,expected", [
("active", VncStatus.on),
("inactive", VncStatus.off),
("failed", VncStatus.off),
@pytest.mark.parametrize("backends,expected", [
([{"unit": "u", "name": "wayvnc", "active": True}], VncStatus.on),
([{"unit": "u", "name": "wayvnc", "active": False}], VncStatus.off),
# A running RealVNC counts even though wayvnc is preferred and stopped.
([{"unit": "a", "name": "wayvnc", "active": False},
{"unit": "b", "name": "realvnc", "active": True}], VncStatus.on),
([], VncStatus.unavailable),
])
async def test_maps_active_state(self, active_state, expected):
"""ActiveState of the chosen unit decides on/off."""
procs = [_show_proc("LoadState=loaded\n"), _show_proc(f"ActiveState={active_state}\n")]
async def test_on_when_any_backend_runs(self, backends, expected):
"""Any running backend means VNC is on."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("asyncio.create_subprocess_exec", side_effect=procs):
with mock.patch("controller.lib.admin.WAYVNC_CONFIG") as config:
config.is_file.return_value = True
assert await get_vnc_status() == expected
@pytest.mark.asyncio
async def test_unavailable_without_a_backend(self):
"""No installed backend reports unavailable."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("asyncio.create_subprocess_exec", return_value=_show_proc("LoadState=not-found\n")):
assert await get_vnc_status() == VncStatus.unavailable
with mock.patch("controller.lib.admin.get_vnc_backends", return_value=(backends, None)):
assert await get_vnc_status() == expected
class TestGetVncStatusDict:
"""The status dict gates starting on the desktop being up."""
@staticmethod
def _backends(wayvnc_active=False, realvnc_active=None):
backends = [{"unit": "wayvnc.service", "name": "wayvnc", "active": wayvnc_active}]
if realvnc_active is not None:
backends.append({"unit": "realvnc.service", "name": "realvnc", "active": realvnc_active})
return backends
@pytest.mark.asyncio
@pytest.mark.parametrize("vnc,desktop_up,running,available,can_start", [
(VncStatus.on, True, True, True, True),
(VncStatus.off, True, False, True, True),
(VncStatus.off, False, False, True, False), # desktop stopped: cannot start
(VncStatus.on, False, True, True, False), # running, but could not be started now
(VncStatus.unavailable, True, False, False, False),
(VncStatus.unknown, True, False, False, False),
@pytest.mark.parametrize("vnc_active,desktop_up,running,can_start", [
(True, True, True, True),
(False, True, False, True),
(False, False, False, False), # desktop stopped: cannot start
(True, False, True, False), # running, but could not be started now
])
async def test_flags(self, vnc, desktop_up, running, available, can_start):
async def test_flags(self, vnc_active, desktop_up, running, can_start):
"""running/available/can_start reflect VNC and desktop state."""
desktop = DesktopStatus.on if desktop_up else DesktopStatus.off
with mock.patch("controller.lib.admin.get_vnc_status", return_value=vnc):
with mock.patch("controller.lib.admin.get_vnc_backend", return_value=("u", "wayvnc", None)):
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=(self._backends(wayvnc_active=vnc_active), None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=desktop):
result = await get_vnc_status_dict()
assert result["running"] is running
assert result["available"] is available
assert result["available"] is True
assert result["can_start"] is can_start
assert result["desktop_running"] is desktop_up
assert result["port"] == 5900
@pytest.mark.asyncio
async def test_names_the_running_backend(self):
"""The UI must not be told wayvnc while RealVNC is the one serving."""
backends = self._backends(wayvnc_active=False, realvnc_active=True)
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backends", return_value=(backends, None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.on):
result = await get_vnc_status_dict()
assert result["running"] is True
assert result["backend"] == "realvnc"
@pytest.mark.asyncio
async def test_unavailable_reports_reason(self):
"""No backend installed is reported as unavailable, with the reason."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=([], "No VNC server installed")):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.on):
result = await get_vnc_status_dict()
assert result["available"] is False
assert result["can_start"] is False
assert result["reason"] == "No VNC server installed"
assert result["backend"] is None
@pytest.mark.asyncio
async def test_explains_a_stopped_desktop(self):
"""The reason should name the desktop when that is what blocks VNC."""
with mock.patch("controller.lib.admin.get_vnc_status", return_value=VncStatus.off):
with mock.patch("controller.lib.admin.get_vnc_backend", return_value=("u", "wayvnc", None)):
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=(self._backends(), None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.off):
result = await get_vnc_status_dict()
@ -1464,14 +1538,17 @@ class TestGetVncStatusDict:
class TestVncStartStop:
"""Starting requires a desktop; stopping never does."""
"""Starting requires a desktop; stopping never does, and stops every backend."""
WAYVNC = {"unit": "wayvnc.service", "name": "wayvnc", "active": False}
REALVNC = {"unit": "vncserver-x11-serviced.service", "name": "realvnc", "active": False}
@pytest.mark.asyncio
async def test_start_runs_systemctl_start(self):
"""With a desktop up, start should start the chosen unit and nothing else."""
async def test_start_uses_the_preferred_backend(self):
"""With a desktop up, start should start wayvnc and nothing else."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backend",
return_value=("wayvnc.service", "wayvnc", None)):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=([dict(self.WAYVNC), dict(self.REALVNC)], None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.on):
with mock.patch("asyncio.create_subprocess_exec", return_value=_ok_proc()) as mock_exec:
result = await start_vnc()
@ -1484,8 +1561,8 @@ class TestVncStartStop:
async def test_start_refused_when_desktop_stopped(self):
"""The gate lives here, not only in the UI, so curl callers get it too."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backend",
return_value=("wayvnc.service", "wayvnc", None)):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=([dict(self.WAYVNC)], None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.off):
with mock.patch("asyncio.create_subprocess_exec") as mock_exec:
result = await start_vnc()
@ -1495,12 +1572,54 @@ class TestVncStartStop:
assert "Desktop must be running" in result["error"]
mock_exec.assert_not_called()
@pytest.mark.asyncio
async def test_stop_stops_every_running_backend(self):
"""Otherwise the other stack keeps serving while the UI reports VNC off."""
backends = [dict(self.WAYVNC, active=True), dict(self.REALVNC, active=True)]
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backends", return_value=(backends, None)):
with mock.patch("asyncio.create_subprocess_exec", return_value=_ok_proc()) as mock_exec:
result = await stop_vnc()
assert result["success"] is True
stopped = [call.args[2] for call in mock_exec.call_args_list]
assert stopped == ["wayvnc.service", "vncserver-x11-serviced.service"]
@pytest.mark.asyncio
async def test_stop_targets_only_the_running_backend(self):
"""A stopped backend needs no stop; the running one must be stopped."""
backends = [dict(self.WAYVNC, active=False), dict(self.REALVNC, active=True)]
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backends", return_value=(backends, None)):
with mock.patch("asyncio.create_subprocess_exec", return_value=_ok_proc()) as mock_exec:
result = await stop_vnc()
assert result["success"] is True
stopped = [call.args[2] for call in mock_exec.call_args_list]
assert stopped == ["vncserver-x11-serviced.service"]
@pytest.mark.asyncio
async def test_stop_reports_a_backend_that_would_not_stop(self):
"""A VNC server left running must not be reported as stopped."""
backends = [dict(self.WAYVNC, active=True)]
failing = mock.AsyncMock()
failing.communicate.return_value = (b"", b"Job for wayvnc.service failed")
failing.returncode = 1
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backends", return_value=(backends, None)):
with mock.patch("asyncio.create_subprocess_exec", return_value=failing):
result = await stop_vnc()
assert result["success"] is False
assert "wayvnc.service" in result["error"]
@pytest.mark.asyncio
async def test_stop_allowed_with_desktop_stopped(self):
"""A running VNC must always be stoppable, or it could be stranded on."""
backends = [dict(self.WAYVNC, active=True)]
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backend",
return_value=("wayvnc.service", "wayvnc", None)):
with mock.patch("controller.lib.admin.get_vnc_backends", return_value=(backends, None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.off):
with mock.patch("asyncio.create_subprocess_exec", return_value=_ok_proc()) as mock_exec:
result = await stop_vnc()
@ -1514,8 +1633,8 @@ class TestVncStartStop:
async def test_never_enables_or_disables(self, func):
"""Runtime-only: VNC must not be persisted across reboots."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backend",
return_value=("wayvnc.service", "wayvnc", None)):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=([dict(self.WAYVNC, active=True)], None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.on):
with mock.patch("asyncio.create_subprocess_exec", return_value=_ok_proc()) as mock_exec:
await func()
@ -1529,8 +1648,8 @@ class TestVncStartStop:
async def test_reports_missing_backend(self, func):
"""Without a backend both actions explain themselves instead of failing obscurely."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_vnc_backend",
return_value=(None, None, "No VNC server installed")):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=([], "No VNC server installed")):
result = await func()
assert result["success"] is False

View file

@ -203,8 +203,8 @@ class TestVncEndpoints:
from unittest import mock
from controller.lib.admin import DesktopStatus
with mock.patch("controller.lib.admin.get_vnc_backend",
return_value=("wayvnc.service", "wayvnc", None)):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=([{"unit": "wayvnc.service", "name": "wayvnc", "active": False}], None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.off):
response = test_client.post("/api/vnc/start")
@ -220,8 +220,8 @@ class TestVncEndpoints:
mock_proc.communicate.return_value = (b"", b"")
mock_proc.returncode = 0
with mock.patch("controller.lib.admin.get_vnc_backend",
return_value=("wayvnc.service", "wayvnc", None)):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=([{"unit": "wayvnc.service", "name": "wayvnc", "active": False}], None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.on):
with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc) as mock_exec:
response = test_client.post("/api/vnc/start")
@ -240,8 +240,8 @@ class TestVncEndpoints:
mock_proc.communicate.return_value = (b"", b"")
mock_proc.returncode = 0
with mock.patch("controller.lib.admin.get_vnc_backend",
return_value=("wayvnc.service", "wayvnc", None)):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=([{"unit": "wayvnc.service", "name": "wayvnc", "active": True}], None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.off):
with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc) as mock_exec:
response = test_client.post("/api/vnc/stop")
@ -259,8 +259,8 @@ class TestVncEndpoints:
mock_proc.communicate.return_value = (b"", b"Job for wayvnc.service failed")
mock_proc.returncode = 1
with mock.patch("controller.lib.admin.get_vnc_backend",
return_value=("wayvnc.service", "wayvnc", None)):
with mock.patch("controller.lib.admin.get_vnc_backends",
return_value=([{"unit": "wayvnc.service", "name": "wayvnc", "active": False}], None)):
with mock.patch("controller.lib.admin.get_desktop_status", return_value=DesktopStatus.on):
with mock.patch("asyncio.create_subprocess_exec", return_value=mock_proc):
response = test_client.post("/api/vnc/start")