From 8f3ea30aab7d5719fa3307017c3dcbddfec191b9 Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Tue, 15 Sep 2026 16:50:58 +0200 Subject: [PATCH] Release environment and display stages 1.0.1 for Console updates --- stage-releases.json | 4 +- stage_env/STORAGE_HEALTH_CONTRACT.md | 26 +++ stage_env/iomatex-userdata-prepare | 2 +- stage_env/iomatex_storage_health.py | 9 +- stage_env/stage_env_install_no_pulse.sh | 20 ++- stage_env/test_storage_health.py | 82 +++++++++ stage_env/version.json | 2 +- stage_itscreen/display/README.md | 42 +++++ .../display/itscreen-display-hotplug.service | 21 +++ stage_itscreen/display/itscreen-display.conf | 1 + stage_itscreen/display/itscreen-display.py | 158 ++++++++++++++++++ stage_itscreen/install_display_hotplug.sh | 16 ++ stage_itscreen/stage_itscreen_install.sh | 27 +-- stage_itscreen/test_display_hotplug.py | 102 +++++++++++ stage_itscreen/version.json | 2 +- 15 files changed, 484 insertions(+), 30 deletions(-) create mode 100644 stage_itscreen/display/README.md create mode 100644 stage_itscreen/display/itscreen-display-hotplug.service create mode 100644 stage_itscreen/display/itscreen-display.conf create mode 100644 stage_itscreen/display/itscreen-display.py create mode 100644 stage_itscreen/install_display_hotplug.sh create mode 100644 stage_itscreen/test_display_hotplug.py diff --git a/stage-releases.json b/stage-releases.json index 7e15fae..01fc64f 100644 --- a/stage-releases.json +++ b/stage-releases.json @@ -2,7 +2,7 @@ "schema": 1, "stages": { "stage_env": { - "version": "1.0.0" + "version": "1.0.1" }, "stage_wifi": { "version": "1.0.0" @@ -23,7 +23,7 @@ "version": "1.0.0" }, "stage_itscreen": { - "version": "1.0.0" + "version": "1.0.1" }, "stage_reverse_tunnels": { "version": "1.0.0" diff --git a/stage_env/STORAGE_HEALTH_CONTRACT.md b/stage_env/STORAGE_HEALTH_CONTRACT.md index 588bed9..807a09e 100644 --- a/stage_env/STORAGE_HEALTH_CONTRACT.md +++ b/stage_env/STORAGE_HEALTH_CONTRACT.md @@ -23,6 +23,32 @@ The contract intentionally separates physical eMMC health from ext4 health: - `filesystem.status` reports filesystem errors and journal state separately from the physical eMMC score. +## Stage release 1.0.1: read-only and damaged userdata + +A read-only `/userdata` mount reports `filesystem.status=critical`, top-level +`status=critical`, and warning `userdata_read_only`, even when the superblock +says clean or eMMC lifetime telemetry is unavailable. The mount option +`errors=remount-ro` alone does not mean that the mount is currently read-only. + +The installer refuses to complete the storage stage when `/userdata` is +read-only, has recorded filesystem errors, or cannot be inspected. This check +also applies when `has_journal` is already present. An unclean unjournaled +filesystem requires offline backup and recovery; the installer must not log an +error and then mark the stage successfully completed. + +For a clean, error-free unjournaled filesystem, the existing one-shot boot +preparation remains responsible for offline `e2fsck -pf`, journal creation and +enabling subsequent boot checks in fstab. The installer explicitly reports +that protection is pending until reboot. It does not repair a mounted +filesystem, remount a failed filesystem read-write, restart the client in a +loop, or repeatedly run fsck in the background. + +This reduces exposure to interrupted writes and prevents false successful +installation reports; it cannot guarantee against failing storage or power +faults. Existing devices need this stage update and, if migration is armed, a +reboot. Devices already showing filesystem errors need separate offline +recovery first. + Consumers must treat unknown or missing fields as unavailable. They must not replace missing measurements with a healthy value. Additive fields may be introduced within schema v1; incompatible semantic changes require a new diff --git a/stage_env/iomatex-userdata-prepare b/stage_env/iomatex-userdata-prepare index 17c591f..61968c8 100644 --- a/stage_env/iomatex-userdata-prepare +++ b/stage_env/iomatex-userdata-prepare @@ -34,7 +34,7 @@ else set -e case "$fsck_rc" in 0|1) ;; - *) log "ERROR: preflight e2fsck failed with rc=$fsck_rc; filesystem was not modified"; exit "$fsck_rc" ;; + *) log "ERROR: preflight e2fsck failed with rc=$fsck_rc; journal migration stopped; offline inspection required"; exit "$fsck_rc" ;; esac tune2fs -j "$device" sync diff --git a/stage_env/iomatex_storage_health.py b/stage_env/iomatex_storage_health.py index f569c21..446a177 100644 --- a/stage_env/iomatex_storage_health.py +++ b/stage_env/iomatex_storage_health.py @@ -148,10 +148,11 @@ def main_contract(): if rc == 0: mount_options = stdout.strip() journal_enabled = "has_journal" in features if features else None + read_only = "ro" in mount_options.split(",") fs_has_errors = "error" in fs_state.lower() or bool(error_count) if not source: fs_status = "unavailable" - elif fs_has_errors: + elif fs_has_errors or read_only: fs_status = "critical" elif journal_enabled is False: fs_status = "attention" @@ -160,6 +161,8 @@ def main_contract(): pre_eol_status = {1: "normal", 2: "warning", 3: "urgent"}.get(pre_eol, "unknown") warnings = [] + if read_only: + warnings.append("userdata_read_only") if journal_enabled is False: warnings.append("userdata_journal_disabled") if fs_has_errors: @@ -168,7 +171,7 @@ def main_contract(): warnings.append("emmc_pre_eol_%s" % pre_eol_status) available = bool(mmc_root and mmc_root.exists()) - overall = "unavailable" if not available else ("critical" if fs_status == "critical" else "attention" if warnings else "ok") + overall = "critical" if fs_status == "critical" else ("attention" if warnings else "ok" if available else "unavailable") return { "schema_version": SCHEMA_VERSION, "available": available, @@ -195,7 +198,7 @@ def main_contract(): "mount_point": USERDATA_MOUNT, "source": source, "mounted": mounted, - "read_only": "ro" in mount_options.split(","), + "read_only": read_only, "type": "ext4" if source else "", "journal_enabled": journal_enabled, "state": fs_state, diff --git a/stage_env/stage_env_install_no_pulse.sh b/stage_env/stage_env_install_no_pulse.sh index 4610673..150601c 100644 --- a/stage_env/stage_env_install_no_pulse.sh +++ b/stage_env/stage_env_install_no_pulse.sh @@ -452,7 +452,7 @@ ensure_userdata_fstab_policy() { } configure_userdata_storage_contract() { - local device features state error_count + local device features state error_count metadata mount_options local marker="/var/lib/iomatex/storage/enable-userdata-journal" install -D -m 0755 -o root -g root \ @@ -499,23 +499,35 @@ EOF return 0 fi - features="$(tune2fs -l "$device" 2>/dev/null | awk -F: '/^Filesystem features:/{print $2}' || true)" + if ! metadata="$(tune2fs -l "$device" 2>/dev/null)"; then + log "ERROR: cannot inspect /userdata filesystem; storage protection is not verified" + return 1 + fi + state="$(printf '%s\n' "$metadata" | awk -F: '/^Filesystem state:/{sub(/^[[:space:]]+/, "", $2); print $2}')" + error_count="$(printf '%s\n' "$metadata" | awk -F: '/^FS Error count:/{gsub(/[[:space:]]/, "", $2); print $2}')" + mount_options="$(findmnt -n -o OPTIONS --mountpoint /userdata 2>/dev/null || true)" + if [[ ",$mount_options," == *,ro,* ]] || [[ "$state" == *error* ]] || [ "${error_count:-0}" != "0" ]; then + rm -f "$marker" + log "ERROR: /userdata requires offline backup and repair (state=${state:-unknown}, errors=${error_count:-unknown}, mount=${mount_options:-unmounted}); stage_env cannot complete" + return 1 + fi + features="$(printf '%s\n' "$metadata" | awk -F: '/^Filesystem features:/{print $2}')" if printf '%s\n' "$features" | grep -qw has_journal; then rm -f "$marker" log "Userdata ext4 journal already enabled" return 0 fi - state="$(tune2fs -l "$device" 2>/dev/null | awk -F: '/^Filesystem state:/{sub(/^[[:space:]]+/, "", $2); print $2}' || true)" - error_count="$(tune2fs -l "$device" 2>/dev/null | awk -F: '/^FS Error count:/{gsub(/[[:space:]]/, "", $2); print $2}' || true)" if [ "$state" = "clean" ] && [ "${error_count:-0}" = "0" ]; then : >"$marker" chmod 0600 "$marker" log "Clean unjournaled /userdata detected; safe offline journal migration armed for next boot" + log "Storage journal protection is pending: reboot is required to activate it" else rm -f "$marker" log "ERROR: /userdata is unjournaled and not clean (state=${state:-unknown}, errors=${error_count:-unknown}); automatic mutation refused" echo "[!] /userdata requires an offline backup and e2fsck; automatic journal migration was NOT armed" + return 1 fi } diff --git a/stage_env/test_storage_health.py b/stage_env/test_storage_health.py index c1fb195..66bc5cb 100644 --- a/stage_env/test_storage_health.py +++ b/stage_env/test_storage_health.py @@ -2,6 +2,9 @@ import importlib.util import pathlib import unittest +from unittest.mock import patch +import subprocess +import tempfile MODULE_PATH = pathlib.Path(__file__).with_name("iomatex_storage_health.py") @@ -25,5 +28,84 @@ class EmmcEstimateTest(unittest.TestCase): self.assertEqual("unknown", storage_health.score_label(None)) +class FilesystemHealthTest(unittest.TestCase): + def contract(self, options, state="clean"): + # No eMMC sysfs data: a known filesystem failure must still be critical. + with patch.object(storage_health, "find_userdata_source", return_value="/dev/test"), \ + patch.object(storage_health, "parent_mmc_device", return_value=None), \ + patch.object(storage_health, "parse_tune2fs", return_value={ + "Filesystem features": "has_journal extent", "Filesystem state": state}), \ + patch.object(storage_health.os.path, "ismount", return_value=True), \ + patch.object(storage_health, "run", return_value=(0, options, "")): + return storage_health.main_contract() + + def test_read_only_is_critical_even_with_clean_superblock(self): + report = self.contract("ro,relatime,errors=remount-ro") + self.assertEqual("critical", report["status"]) + self.assertIn("userdata_read_only", report["warnings"]) + + def test_remount_ro_policy_is_not_a_read_only_mount(self): + report = self.contract("rw,relatime,errors=remount-ro") + self.assertFalse(report["filesystem"]["read_only"]) + self.assertEqual("ok", report["filesystem"]["status"]) + + def test_ext4_error_is_critical_without_emmc_telemetry(self): + self.assertEqual("critical", self.contract("rw", "not clean with errors")["status"]) + + +class StorageInstallerTest(unittest.TestCase): + def run_contract(self, features, state, options, errors="0"): + source = MODULE_PATH.with_name("stage_env_install_no_pulse.sh").read_text() + body = "configure_userdata_storage_contract() {" + source.split( + "configure_userdata_storage_contract() {", 1)[1].split( + "\nappend_kernel_args_to_file()", 1)[0] + with tempfile.TemporaryDirectory() as directory: + # Exercise the real installer function, sandboxing all absolute writes + # and replacing device/system commands, never invoking disk repair. + for prefix in ("/var/lib/iomatex", "/etc/systemd/system", "/usr/local/sbin"): + body = body.replace(prefix, directory + prefix) + script = """ +set -euo pipefail +SCRIPT_DIR=/unused +log() { echo "$*"; } +install() { :; } +write_if_changed() { cat >/dev/null; } +readlink() { echo /dev/test; } +[() { if [[ "$1" == '-b' ]]; then return 0; fi; if [[ "$1 $2" == '! -b' ]]; then return 1; fi; builtin [ "$@"; } +tune2fs() { printf 'Filesystem features: %s\\nFilesystem state: %s\\nFS Error count: %s\\n' "$FEATURES" "$STATE" "$ERRORS"; } +findmnt() { echo "$OPTIONS"; } +""" + body + "\nconfigure_userdata_storage_contract\n" + import os + result = subprocess.run(["bash", "-c", script], text=True, capture_output=True, + env={**os.environ, "FEATURES": features, "STATE": state, + "OPTIONS": options, "ERRORS": errors}) + marker = pathlib.Path(directory + "/var/lib/iomatex/storage/enable-userdata-journal") + return result.returncode, marker.exists(), result.stdout + result.stderr + + def test_clean_unjournaled_disk_arms_one_shot_migration(self): + rc, armed, output = self.run_contract("extent", "clean", "rw") + self.assertEqual(0, rc, output) + self.assertTrue(armed) + + def test_healthy_journaled_disk_does_not_arm_repair(self): + rc, armed, output = self.run_contract("has_journal extent", "clean", "rw") + self.assertEqual(0, rc, output) + self.assertFalse(armed) + + def test_unsafe_disks_fail_even_when_journal_already_exists(self): + for state, options, errors in [("clean", "ro", "0"), + ("not clean with errors", "rw", "0"), + ("clean", "rw", "4")]: + with self.subTest(state=state, options=options, errors=errors): + rc, armed, output = self.run_contract("has_journal extent", state, options, errors) + self.assertNotEqual(0, rc, output) + self.assertFalse(armed) + + def test_unclean_unjournaled_disk_does_not_report_success(self): + rc, armed, output = self.run_contract("extent", "not clean", "rw") + self.assertNotEqual(0, rc, output) + self.assertFalse(armed) + + if __name__ == "__main__": unittest.main() diff --git a/stage_env/version.json b/stage_env/version.json index 1587a66..ca84e70 100644 --- a/stage_env/version.json +++ b/stage_env/version.json @@ -1,3 +1,3 @@ { - "version": "1.0.0" + "version": "1.0.1" } diff --git a/stage_itscreen/display/README.md b/stage_itscreen/display/README.md new file mode 100644 index 0000000..219abdc --- /dev/null +++ b/stage_itscreen/display/README.md @@ -0,0 +1,42 @@ +# HDMI after a headless boot — stage_itscreen 1.0.1 + +On the tested RK3566 Debian 11 Edge, Xorg starts without a monitor using a +1024x768 framebuffer. A later HDMI insertion is detected, but the output may +remain disabled. Activating the output with xrandr restores the picture and +the existing fullscreen client window adapts to the new geometry. + +`itscreen-display.py` is the common owner for the initial session check and +subsequent hotplug handling. It enables connected, inactive HDMI outputs at +1920x1080/60 when supported, otherwise the monitor's preferred mode. It leaves +active outputs, including operator-selected modes, untouched. Disconnection is +normal and never stops/restarts X11, the client, or the device. + +The systemd service subscribes to kernel DRM hotplug events via netlink. There +is no idle polling. Events are coalesced for one second (at most three seconds +per burst). X11 readiness checks have at most three additional attempts. Failed +mode activation is limited to one attempt per 30 seconds and requires a new +event to try again; successful activation does not delay a quick reconnect. +A shared flock prevents startup/event races. State lives only in /run and +resets on boot. The listener follows itscreen-x11 service stop/restart and +never activates the LightDM recovery desktop. Its own unexpected crashes have +a systemd restart limit of three starts per five minutes. + +The normal stage installer installs the helper, tmpfiles rule and service. +For a narrow live update of an existing appliance, run as root: + +```sh +bash stage_itscreen/install_display_hotplug.sh +``` + +This only restarts the listener, not the running X11/client. Full stage installs +also replace the session's old one-time mode forcing with this shared helper. +The narrow update does not claim a full stage installation receipt. + +Verify with `journalctl -u itscreen-display-hotplug` and +`DISPLAY=:0 XAUTHORITY=/run/itscreen/Xauthority xrandr --query` as root. +Removing HDMI must not fail the service. For physical validation boot without +HDMI and insert it after the client starts, then unplug/replug several times. +Client PID and itscreen-x11 NRestarts must stay unchanged. + +This change enables local video output. It does not yet add an MQTT message +or change the remote Devices → Interfaces → Video status contract. diff --git a/stage_itscreen/display/itscreen-display-hotplug.service b/stage_itscreen/display/itscreen-display-hotplug.service new file mode 100644 index 0000000..6d23129 --- /dev/null +++ b/stage_itscreen/display/itscreen-display-hotplug.service @@ -0,0 +1,21 @@ +[Unit] +Description=ITSCREEN HDMI activation on DRM hotplug +After=itscreen-x11.service +PartOf=itscreen-x11.service +StartLimitIntervalSec=300 +StartLimitBurst=3 + +[Service] +Type=simple +User=root +Group=itscreen +UMask=0007 +Environment=DISPLAY=:0 +Environment=XAUTHORITY=/run/itscreen/Xauthority +ExecStart=/usr/bin/python3 /usr/local/lib/itscreen/itscreen-display.py +Restart=on-failure +RestartSec=10 +TimeoutStopSec=10 + +[Install] +WantedBy=itscreen-x11.service diff --git a/stage_itscreen/display/itscreen-display.conf b/stage_itscreen/display/itscreen-display.conf new file mode 100644 index 0000000..25d662f --- /dev/null +++ b/stage_itscreen/display/itscreen-display.conf @@ -0,0 +1 @@ +d /run/itscreen-display 0770 root itscreen - diff --git a/stage_itscreen/display/itscreen-display.py b/stage_itscreen/display/itscreen-display.py new file mode 100644 index 0000000..4767233 --- /dev/null +++ b/stage_itscreen/display/itscreen-display.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Activate an idle HDMI output in the existing appliance X11 session. + +No polling while idle, no client/service restarts and no work in a udev rule. +The session startup and DRM event listener use the same locked reconciler. +""" +import argparse +import fcntl +import json +import os +from pathlib import Path +import re +import select +import socket +import subprocess +import time + +RUNTIME = Path('/run/itscreen-display') +DEBOUNCE = 1.0 +MAX_DEBOUNCE = 3.0 +COOLDOWN = 30.0 + + +def run(*args): + return subprocess.run(args, capture_output=True, text=True, timeout=8, + env={**os.environ, 'LC_ALL': 'C', + 'DISPLAY': os.environ.get('DISPLAY', ':0'), + 'XAUTHORITY': os.environ.get('XAUTHORITY', '/run/itscreen/Xauthority')}) + + +def outputs(text): + result = [] + current = None + for line in text.splitlines(): + match = re.match(r'^(HDMI\S*) (connected|disconnected)\b(.*)', line) + if match: + current = {'name': match[1], 'connected': match[2] == 'connected', + 'active': bool(re.search(r'\b\d+x\d+[+-]\d+[+-]\d+', match[3])), + 'fullhd60': False} + result.append(current) + elif line and not line[0].isspace(): + current = None + elif current and re.match(r'^\s+1920x1080\s', line): + current['fullhd60'] = any(abs(float(rate) - 60) < .01 + for rate in re.findall(r'\d+\.\d+', line)) + return result + + +def reconcile(state, now): + # Do not revive a stopped appliance or touch a LightDM recovery session. + if run('systemctl', 'is-active', '--quiet', 'itscreen-x11.service').returncode: + return 'waiting' + if not run('systemctl', 'is-active', '--quiet', 'lightdm.service').returncode: + return 'desktop' + query = run('xrandr', '--query') + if query.returncode: + return 'waiting' + connected = [item for item in outputs(query.stdout) if item['connected']] + if not connected: + return 'disconnected' + inactive = [item for item in connected if not item['active']] + if not inactive: + state.pop('retry_after', None) + return 'active' + if now < state.get('retry_after', 0): + return 'cooldown' + # Set before invoking xrandr; even an exception cannot create a retry storm. + state['retry_after'] = now + COOLDOWN + for item in inactive: + mode = ['--mode', '1920x1080', '--rate', '60'] if item['fullhd60'] else ['--auto'] + result = run('xrandr', '--output', item['name'], *mode) + if result.returncode: + print('HDMI activation failed; retries limited to once per 30 seconds', flush=True) + return 'failed' + print('Activated {} in existing X11 ({})'.format(item['name'], ' '.join(mode)), flush=True) + check = run('xrandr', '--query') + if check.returncode: + return 'waiting' + connected = [item for item in outputs(check.stdout) if item['connected']] + if not connected: + return 'disconnected' + if any(not item['active'] for item in connected): + return 'failed' + state.pop('retry_after', None) + return 'active' + + +def apply_once(): + os.umask(0o007) + with (RUNTIME / 'lock').open('a') as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return 'waiting' + path = RUNTIME / 'state.json' + try: + state = json.loads(path.read_text()) + except (FileNotFoundError, ValueError): + state = {} + try: + status = reconcile(state, time.monotonic()) + except (OSError, subprocess.TimeoutExpired) as exc: + print('Display check deferred: {}'.format(type(exc).__name__), flush=True) + status = 'waiting' + if status != state.get('status'): + print('Display state: ' + status, flush=True) + state['status'] = status + temp = path.with_suffix('.tmp') + temp.write_text(json.dumps(state) + '\n') + temp.replace(path) + return status + + +def is_hotplug(data, sender): + # NETLINK_KOBJECT_UEVENT group 1: only accept kernel-origin DRM hotplug. + fields = set(data.split(b'\0')) + return sender[0] == 0 and {b'SUBSYSTEM=drm', b'HOTPLUG=1', b'ACTION=change'} <= fields + + +def watch(): + with socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, 15) as events: + events.bind((os.getpid(), 1)) + deadline = time.monotonic() + DEBOUNCE + burst_start = time.monotonic() + retries = 0 + while True: + now = time.monotonic() + if deadline is not None and now >= deadline: + status = apply_once() + # Only bounded readiness retries; failures need a fresh event. + if status == 'waiting' and retries < 3: + retries += 1 + deadline = time.monotonic() + 2 + else: + deadline = None + burst_start = None + timeout = None if deadline is None else max(0, deadline - time.monotonic()) + readable, _, _ = select.select([events], [], [], timeout) + if not readable: + continue + data, sender = events.recvfrom(65536) + if not is_hotplug(data, sender): + continue + now = time.monotonic() + if burst_start is None: + burst_start = now + retries = 0 + deadline = min(now + DEBOUNCE, burst_start + MAX_DEBOUNCE) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--once', action='store_true') + args = parser.parse_args() + if args.once: + apply_once() + else: + watch() diff --git a/stage_itscreen/install_display_hotplug.sh b/stage_itscreen/install_display_hotplug.sh new file mode 100644 index 0000000..917d941 --- /dev/null +++ b/stage_itscreen/install_display_hotplug.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Also usable as a narrow live update; does not restart X11 or the client. +set -euo pipefail +[[ $EUID -eq 0 ]] || { echo 'Run as root' >&2; exit 1; } +src="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/display" +getent group itscreen >/dev/null +install -d -m 0755 /usr/local/lib/itscreen +install -m 0644 "$src/itscreen-display.py" /usr/local/lib/itscreen/itscreen-display.py +install -m 0644 "$src/itscreen-display-hotplug.service" /etc/systemd/system/itscreen-display-hotplug.service +install -m 0644 "$src/itscreen-display.conf" /etc/tmpfiles.d/itscreen-display.conf +systemd-tmpfiles --create /etc/tmpfiles.d/itscreen-display.conf +systemctl daemon-reload +systemctl enable itscreen-display-hotplug.service +if systemctl is-active --quiet itscreen-x11.service; then + systemctl restart itscreen-display-hotplug.service +fi diff --git a/stage_itscreen/stage_itscreen_install.sh b/stage_itscreen/stage_itscreen_install.sh index 0f469a7..80f396b 100755 --- a/stage_itscreen/stage_itscreen_install.sh +++ b/stage_itscreen/stage_itscreen_install.sh @@ -765,24 +765,9 @@ wait_for_x_ready() { } force_display_mode() { - if ! have xrandr; then - log "WARN: xrandr is not installed; cannot force display mode" - return 0 - fi - - if DISPLAY="$DISPLAY_VALUE" XAUTHORITY="$XAUTHORITY_VALUE" xrandr | grep -q "^HDMI-1 connected"; then - if DISPLAY="$DISPLAY_VALUE" XAUTHORITY="$XAUTHORITY_VALUE" xrandr | grep -q "1920x1080"; then - if DISPLAY="$DISPLAY_VALUE" XAUTHORITY="$XAUTHORITY_VALUE" xrandr --output HDMI-1 --mode 1920x1080 --rate 60 >/dev/null 2>&1; then - log "Display mode forced to HDMI-1 1920x1080@60" - else - log "WARN: failed to force HDMI-1 1920x1080@60" - fi - else - log "WARN: HDMI-1 connected but 1920x1080 mode is not available" - fi - else - log "WARN: HDMI-1 is not connected; skipping display mode force" - fi + # Shared owner for startup and late HDMI insertion; never restart the client. + /usr/bin/python3 /usr/local/lib/itscreen/itscreen-display.py --once || \ + log "WARN: initial display check deferred to hotplug handler" } ensure_openbox() { @@ -1351,6 +1336,8 @@ post_install_self_test() { if [[ ! -f "$ITS_UNIT_FILE" ]]; then die "Service file missing: ${ITS_UNIT_FILE}" fi + [[ -r /usr/local/lib/itscreen/itscreen-display.py ]] || die "HDMI hotplug helper missing" + systemctl is-enabled --quiet itscreen-display-hotplug.service || die "HDMI hotplug handler is not enabled" for missing_path in \ "$ITS_WRAPPER" \ @@ -1412,6 +1399,9 @@ post_install_self_test() { if [[ "$service_active" == "yes" ]]; then log "Self-test: ${ITS_SERVICE} is active within grace window" + if ! systemctl is-active --quiet itscreen-display-hotplug.service; then + die "HDMI hotplug handler is not active" + fi else warn "Self-test: ${ITS_SERVICE} is not active after 30s; HDMI/headless startup may still be in progress" status_output="$(systemctl status "$ITS_SERVICE" --no-pager -l 2>&1 || true)" @@ -1502,6 +1492,7 @@ main() { install_wrapper install_audio_route_state install_pulseaudio_assets + bash "$SCRIPT_DIR/install_display_hotplug.sh" install_x11_session_scripts install_recovery_assets install_systemd_unit diff --git a/stage_itscreen/test_display_hotplug.py b/stage_itscreen/test_display_hotplug.py new file mode 100644 index 0000000..0be7613 --- /dev/null +++ b/stage_itscreen/test_display_hotplug.py @@ -0,0 +1,102 @@ +import importlib.util +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location('display', Path(__file__).parent / 'display/itscreen-display.py') +display = importlib.util.module_from_spec(spec) +spec.loader.exec_module(display) + +DISCONNECTED = 'HDMI-1 disconnected primary (normal)\n' +IDLE = 'HDMI-1 connected primary (normal)\n 1920x1080 60.00+ 50.00\n' +ACTIVE = 'HDMI-1 connected primary 1920x1080+0+0 (normal)\n 1920x1080 60.00*+\n' + + +class DisplayTest(unittest.TestCase): + def fake_run(self, query=IDLE, appliance=True, desktop=False, fail=False): + def call(*args): + if args[0] == 'systemctl': + rc = (not appliance) if args[-1] == 'itscreen-x11.service' else (not desktop) + return subprocess.CompletedProcess(args, int(rc), '', '') + if args == ('xrandr', '--query'): + return subprocess.CompletedProcess(args, 0, query, '') + return subprocess.CompletedProcess(args, int(fail), '', '') + return call + + def test_headless_is_normal_and_does_not_change_mode(self): + with patch.object(display, 'run', side_effect=self.fake_run(DISCONNECTED)) as run: + self.assertEqual(display.reconcile({}, 100), 'disconnected') + self.assertEqual(run.call_count, 3) + + def test_cold_boot_late_connection_activates_output(self): + fake = self.fake_run() + queries = iter([IDLE, ACTIVE]) + with patch.object(display, 'run', side_effect=lambda *a: subprocess.CompletedProcess(a, 0, next(queries), '') if a == ('xrandr', '--query') else fake(*a)) as run: + state = {} + self.assertEqual(display.reconcile(state, 100), 'active') + run.assert_any_call('xrandr', '--output', 'HDMI-1', '--mode', '1920x1080', '--rate', '60') + self.assertNotIn('retry_after', state) # quick reconnect is not throttled + + def test_preserves_active_custom_resolution(self): + with patch.object(display, 'run', side_effect=self.fake_run(ACTIVE.replace('1920x1080', '1280x720'))) as run: + self.assertEqual(display.reconcile({}, 100), 'active') + self.assertEqual(run.call_count, 3) + + def test_failed_activation_is_throttled(self): + with patch.object(display, 'run', side_effect=self.fake_run(fail=True)) as run: + state = {} + self.assertEqual(display.reconcile(state, 100), 'failed') + self.assertEqual(display.reconcile(state, 101), 'cooldown') + self.assertEqual(display.reconcile(state, 129), 'cooldown') + self.assertEqual(display.reconcile(state, 130), 'failed') + self.assertEqual(sum(c.args[:2] == ('xrandr', '--output') for c in run.call_args_list), 2) + + def test_preferred_mode_fallback_for_other_monitor(self): + with patch.object(display, 'run', side_effect=self.fake_run(IDLE.replace('1920x1080', '1280x720'))) as run: + display.reconcile({}, 100) + run.assert_any_call('xrandr', '--output', 'HDMI-1', '--auto') + + def test_no_service_restart_or_desktop_interference(self): + for appliance, desktop in [(False, False), (True, True)]: + with patch.object(display, 'run', side_effect=self.fake_run(appliance=appliance, desktop=desktop)) as run: + self.assertIn(display.reconcile({}, 100), ('waiting', 'desktop')) + self.assertTrue(all(c.args[:3] == ('systemctl', 'is-active', '--quiet') for c in run.call_args_list)) + + def test_ignores_non_kernel_and_unrelated_events(self): + event = b'change@/devices/card0\0SUBSYSTEM=drm\0HOTPLUG=1\0ACTION=change\0' + self.assertTrue(display.is_hotplug(event, (0, 1))) + self.assertFalse(display.is_hotplug(event, (1234, 1))) + self.assertFalse(display.is_hotplug(event.replace(b'drm', b'usb'), (0, 1))) + self.assertFalse(display.is_hotplug(event.replace(b'HOTPLUG=1', b'OTHER=1'), (0, 1))) + + def test_timeout_keeps_failure_cooldown_across_invocations(self): + with tempfile.TemporaryDirectory() as directory, patch.object(display, 'RUNTIME', Path(directory)): + def timeout(state, now): + state['retry_after'] = now + 30 + raise subprocess.TimeoutExpired('xrandr', 8) + with patch.object(display, 'reconcile', side_effect=timeout): + self.assertEqual(display.apply_once(), 'waiting') + self.assertIn('retry_after', (Path(directory) / 'state.json').read_text()) + + def test_listener_blocks_without_polling_and_readiness_retries_are_bounded(self): + for status, expected in [('active', 1), ('disconnected', 1), ('failed', 1), ('waiting', 4)]: + clock = [100.0] + waits = [] + def wait(readers, writers, errors, timeout): + waits.append(timeout) + if timeout is None: + raise StopIteration('idle, blocked on kernel events') + self.assertLess(len(waits), 6) + clock[0] += timeout + return [], [], [] + with patch.object(display.socket, 'socket'), patch.object(display.time, 'monotonic', side_effect=lambda: clock[0]), patch.object(display.select, 'select', side_effect=wait), patch.object(display, 'apply_once', return_value=status) as apply: + with self.assertRaises(StopIteration): + display.watch() + self.assertEqual(apply.call_count, expected) + self.assertIsNone(waits[-1]) + + +if __name__ == '__main__': + unittest.main() diff --git a/stage_itscreen/version.json b/stage_itscreen/version.json index 1587a66..ca84e70 100644 --- a/stage_itscreen/version.json +++ b/stage_itscreen/version.json @@ -1,3 +1,3 @@ { - "version": "1.0.0" + "version": "1.0.1" }