diff --git a/docs/ops-laptop.md b/docs/ops-laptop.md new file mode 100644 index 0000000..710696d --- /dev/null +++ b/docs/ops-laptop.md @@ -0,0 +1,52 @@ +# 운영 노트북 영구 설정 (#103) + +행사 운영 노트북(Agent 실행 PC)의 화면·전원 설정을 재부팅 뒤에도 유지되게 하는 기준과 점검·복구 절차다. +설정 변경(아래 `sudo` 명령)은 운영자가 직접 한다. 점검 스크립트는 읽기 전용이다. + +## 점검 + +```bash +python3 scripts/ops_laptop_check.py # 그래픽 세션의 터미널에서 실행 +``` + +항목별 `[PASS|FAIL|UNKNOWN]` 과 마지막 한 줄(`OK`/`FAIL`/`CHECK`)을 출력한다. `UNKNOWN` 은 SSH 처럼 +그래픽 세션이 아니라 `gsettings`·`xrandr` 를 읽지 못한 경우다. + +| 항목 | 기준(영구 설정) | +|---|---| +| Xorg 기본 세션 | `/etc/gdm3/custom.conf` `[daemon]` 에 `WaylandEnable=false` | +| 덮개 닫힘 무시 | `/etc/systemd/logind.conf.d/50-poppy-lid.conf` 에 `HandleLidSwitch=ignore`, `HandleLidSwitchExternalPower=ignore`, `HandleLidSwitchDocked=ignore` | +| 절전 target mask | `sleep.target`, `suspend.target`, `hibernate.target`, `hybrid-sleep.target` 가 `/dev/null` 로 mask | +| GNOME 자동 절전·화면 끄기 | `sleep-inactive-ac-type`·`sleep-inactive-battery-type` = `'nothing'`, `idle-delay` = `uint32 0` | +| 외부 모니터 1080p60 | 외부 출력(eDP 제외)의 현재 모드 1920x1080, 60 Hz | + +## 설정 (운영자, 1회) + +```bash +sudo sed -i 's/^#\?WaylandEnable=.*/WaylandEnable=false/' /etc/gdm3/custom.conf +sudo mkdir -p /etc/systemd/logind.conf.d +printf '[Login]\nHandleLidSwitch=ignore\nHandleLidSwitchExternalPower=ignore\nHandleLidSwitchDocked=ignore\n' \ + | sudo tee /etc/systemd/logind.conf.d/50-poppy-lid.conf +sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target +gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-ac-type 'nothing' +gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-battery-type 'nothing' +gsettings set org.gnome.desktop.session idle-delay 0 +``` + +GDM·logind 설정은 재부팅 후 적용된다(행사 중 `systemctl restart systemd-logind`/`gdm3` 는 세션을 끊으므로 하지 않는다). +1080p60 은 GNOME 디스플레이 설정에서 외부 모니터를 1920×1080, 60 Hz 로 고르고 "변경 사항 유지"를 누르면 +`~/.config/monitors.xml` 에 저장되어 같은 모니터를 다시 연결하면 복원된다. + +## 현장 체크리스트 + +- [ ] 재부팅 → 자동 로그인 후 `ops_laptop_check.py` 가 `OK` +- [ ] 덮개 닫고 1분 → Agent `status.json` `observedAt` 이 계속 갱신(절전 안 함) +- [ ] 외부 모니터 분리 → 재연결: 1080p60 복원, 점검 `OK` +- [ ] 외부 모니터 연결 상태로 재부팅: 1080p60 유지 +- [ ] 결과(날짜, 모니터 모델, 항목별 결과)를 `docs/trial-records/` 에 기록 + +## 복구 + +- 1080p60 이 아니면 디스플레이 설정에서 다시 고른다. 안 되면 `~/.config/monitors.xml` 을 백업 후 지우고 재로그인해 다시 고른다. +- Wayland 로 로그인됐으면(`echo $XDG_SESSION_TYPE` 이 `wayland`) `custom.conf` 를 확인하고 재부팅한다. +- 덮개를 닫았는데 절전되면 `50-poppy-lid.conf` 와 mask 를 확인하고 재부팅한다. diff --git a/scripts/ops_laptop_check.py b/scripts/ops_laptop_check.py new file mode 100644 index 0000000..7a76a7f --- /dev/null +++ b/scripts/ops_laptop_check.py @@ -0,0 +1,188 @@ +"""Read-only check of the operator laptop's persistent display and power settings (#103). + +Checks: Xorg default session (GDM ``WaylandEnable=false``), logind lid switch +``ignore``, sleep targets masked, GNOME automatic suspend/idle off, and an +external 1920x1080 at 60 Hz mode. Nothing is changed; each failed item prints +the persistent fix from docs/ops-laptop.md. The last line is a one-line summary. +""" + +from __future__ import annotations + +import argparse +import os +import re +import subprocess +import sys +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from pathlib import Path + +PASS, FAIL, UNKNOWN = "PASS", "FAIL", "UNKNOWN" +LID_KEYS = ("HandleLidSwitch", "HandleLidSwitchExternalPower", "HandleLidSwitchDocked") +SLEEP_TARGETS = ("sleep.target", "suspend.target", "hibernate.target", "hybrid-sleep.target") +GSETTINGS = ( + ("org.gnome.settings-daemon.plugins.power", "sleep-inactive-ac-type", "'nothing'"), + ("org.gnome.settings-daemon.plugins.power", "sleep-inactive-battery-type", "'nothing'"), + ("org.gnome.desktop.session", "idle-delay", "uint32 0"), +) + +Runner = Callable[[Sequence[str]], str | None] + + +@dataclass(frozen=True, slots=True) +class Check: + name: str + result: str + detail: str + + +def run_readonly(command: Sequence[str]) -> str | None: + """Run a read-only query; ``None`` when it is unavailable or fails.""" + try: + completed = subprocess.run( # noqa: S603 - fixed read-only queries + list(command), capture_output=True, text=True, check=False, timeout=10 + ) + except (OSError, subprocess.TimeoutExpired): + return None + return completed.stdout if completed.returncode == 0 else None + + +def _ini_value(paths: Sequence[Path], key: str) -> str | None: + """Last uncommented ``key=value`` across files in order (later files win).""" + value: str | None = None + for path in paths: + try: + text = path.read_text(encoding="utf-8") + except OSError: + continue + for line in text.splitlines(): + stripped = line.strip() + if stripped.startswith(("#", ";")): + continue + name, sep, raw = stripped.partition("=") + if sep and name.strip() == key: + value = raw.strip() + return value + + +def check_xorg(root: Path) -> Check: + value = _ini_value([root / "etc/gdm3/custom.conf"], "WaylandEnable") + if value is None: + return Check("Xorg 기본 세션", FAIL, "/etc/gdm3/custom.conf 에 WaylandEnable=false 없음") + if value.lower() == "false": + return Check("Xorg 기본 세션", PASS, "WaylandEnable=false") + return Check("Xorg 기본 세션", FAIL, f"WaylandEnable={value}") + + +def check_lid(root: Path) -> Check: + drop_ins = sorted((root / "etc/systemd/logind.conf.d").glob("*.conf")) + paths = [root / "etc/systemd/logind.conf", *drop_ins] + wrong = [ + f"{key}={_ini_value(paths, key)}" for key in LID_KEYS if _ini_value(paths, key) != "ignore" + ] + if wrong: + return Check("덮개 닫힘 무시", FAIL, ", ".join(wrong)) + return Check("덮개 닫힘 무시", PASS, "HandleLidSwitch*=ignore") + + +def check_sleep_masked(root: Path) -> Check: + unmasked = [] + for target in SLEEP_TARGETS: + path = root / "etc/systemd/system" / target + try: + masked = path.is_symlink() and os.readlink(path) == "/dev/null" + except OSError: + masked = False + if not masked: + unmasked.append(target) + if unmasked: + return Check("절전 target mask", FAIL, "mask 안 됨: " + ", ".join(unmasked)) + return Check("절전 target mask", PASS, "sleep/suspend/hibernate/hybrid-sleep masked") + + +def check_gnome(runner: Runner) -> Check: + wrong = [] + for schema, key, expected in GSETTINGS: + value = runner(["gsettings", "get", schema, key]) + if value is None: + return Check( + "GNOME 자동 절전·화면 끄기", UNKNOWN, "gsettings 조회 불가(그래픽 세션 밖)" + ) + if value.strip() != expected: + wrong.append(f"{key}={value.strip()}") + if wrong: + return Check("GNOME 자동 절전·화면 끄기", FAIL, ", ".join(wrong)) + return Check("GNOME 자동 절전·화면 끄기", PASS, "자동 절전 nothing, idle-delay 0") + + +_OUTPUT = re.compile(r"^(\S+) connected") +_MODE = re.compile(r"^\s+(\d+x\d+)\s+(.*)$") + + +def check_display(runner: Runner) -> Check: + text = runner(["xrandr", "--current"]) + if text is None: + return Check("외부 모니터 1080p60", UNKNOWN, "xrandr 조회 불가(DISPLAY 없음)") + output: str | None = None + current: dict[str, str] = {} + for line in text.splitlines(): + connected = _OUTPUT.match(line) + if connected: + output = connected.group(1) + continue + if line and not line[0].isspace(): + output = None + continue + mode = _MODE.match(line) + if output and mode: + active = [rate for rate in mode.group(2).split() if "*" in rate] + if active: + current[output] = f"{mode.group(1)}@{active[0].strip('*+')}" + external = {name: mode for name, mode in current.items() if not name.startswith("eDP")} + for name, active_mode in external.items(): + resolution, rate = active_mode.split("@") + if resolution == "1920x1080" and abs(float(rate) - 60.0) < 0.5: + return Check("외부 모니터 1080p60", PASS, f"{name} {active_mode}") + if not external: + return Check("외부 모니터 1080p60", FAIL, "외부 모니터 없음") + return Check( + "외부 모니터 1080p60", + FAIL, + ", ".join(f"{name} {mode}" for name, mode in external.items()), + ) + + +def run_checks(root: Path, runner: Runner) -> list[Check]: + return [ + check_xorg(root), + check_lid(root), + check_sleep_masked(root), + check_gnome(runner), + check_display(runner), + ] + + +def summary(checks: Sequence[Check]) -> str: + failed = [c.name for c in checks if c.result == FAIL] + unknown = [c.name for c in checks if c.result == UNKNOWN] + if failed: + return "FAIL: " + ", ".join(failed) + " (docs/ops-laptop.md 참고)" + if unknown: + return "CHECK: 그래픽 세션에서 다시 확인 — " + ", ".join(unknown) + return "OK: 화면·전원 설정 유지됨" + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", type=Path, default=Path("/"), help="filesystem root (tests)") + args = parser.parse_args(argv) + checks = run_checks(args.root, run_readonly) + for check in checks: + print(f"[{check.result}] {check.name}: {check.detail}") + line = summary(checks) + print(line) + return 1 if line.startswith("FAIL") else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_ops_laptop_check.py b/tests/test_ops_laptop_check.py new file mode 100644 index 0000000..e933527 --- /dev/null +++ b/tests/test_ops_laptop_check.py @@ -0,0 +1,117 @@ +"""scripts/ops_laptop_check.py against a fixture filesystem and fake queries (#103).""" + +from __future__ import annotations + +import importlib.util +import os +import sys +from collections.abc import Sequence +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location( + "ops_laptop_check", ROOT / "scripts" / "ops_laptop_check.py" +) +assert SPEC is not None and SPEC.loader is not None +check = importlib.util.module_from_spec(SPEC) +sys.modules["ops_laptop_check"] = check +SPEC.loader.exec_module(check) + +XRANDR_OK = """Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 16384 x 16384 +eDP-1 connected primary 1920x1080+0+0 (normal) 344mm x 194mm + 1920x1080 60.02*+ 48.00 +HDMI-1 connected 1920x1080+0+0 (normal) 531mm x 299mm + 1920x1080 60.00*+ 50.00 59.94 + 1280x720 60.00 +DP-1 disconnected (normal left inverted right x axis y axis) +""" +GOOD_GSETTINGS = { + "sleep-inactive-ac-type": "'nothing'\n", + "sleep-inactive-battery-type": "'nothing'\n", + "idle-delay": "uint32 0\n", +} + + +def fake(xrandr: str | None = XRANDR_OK, gsettings: dict[str, str] | None = None): + values = GOOD_GSETTINGS if gsettings is None else gsettings + + def runner(command: Sequence[str]) -> str | None: + if command[0] == "xrandr": + return xrandr + if command[0] == "gsettings": + return values.get(command[3]) + raise AssertionError(f"unexpected command {command}") + + return runner + + +def good_root(tmp_path: Path) -> Path: + (tmp_path / "etc/gdm3").mkdir(parents=True) + (tmp_path / "etc/gdm3/custom.conf").write_text( + "[daemon]\n#WaylandEnable=true\nWaylandEnable=false\n", encoding="utf-8" + ) + (tmp_path / "etc/systemd/logind.conf.d").mkdir(parents=True) + (tmp_path / "etc/systemd/logind.conf").write_text( + "[Login]\n#HandleLidSwitch=suspend\n", encoding="utf-8" + ) + (tmp_path / "etc/systemd/logind.conf.d/50-poppy-lid.conf").write_text( + "[Login]\nHandleLidSwitch=ignore\nHandleLidSwitchExternalPower=ignore\n" + "HandleLidSwitchDocked=ignore\n", + encoding="utf-8", + ) + system = tmp_path / "etc/systemd/system" + system.mkdir(parents=True) + for target in check.SLEEP_TARGETS: + os.symlink("/dev/null", system / target) + return tmp_path + + +def test_all_persistent_settings_pass(tmp_path: Path) -> None: + checks = check.run_checks(good_root(tmp_path), fake()) + assert [c.result for c in checks] == ["PASS"] * 5 + assert check.summary(checks) == "OK: 화면·전원 설정 유지됨" + assert "HDMI-1 1920x1080@60.00" in checks[-1].detail + + +def test_wayland_lid_and_sleep_failures(tmp_path: Path) -> None: + root = good_root(tmp_path) + (root / "etc/gdm3/custom.conf").write_text("[daemon]\nWaylandEnable=true\n", encoding="utf-8") + (root / "etc/systemd/logind.conf.d/90-later.conf").write_text( + "[Login]\nHandleLidSwitch=suspend\n", encoding="utf-8" + ) + (root / "etc/systemd/system/suspend.target").unlink() + checks = {c.name: c for c in check.run_checks(root, fake())} + + assert checks["Xorg 기본 세션"].result == "FAIL" + assert "HandleLidSwitch=suspend" in checks["덮개 닫힘 무시"].detail + assert "suspend.target" in checks["절전 target mask"].detail + assert check.summary(list(checks.values())).startswith("FAIL: ") + + +def test_missing_files_fail_instead_of_passing(tmp_path: Path) -> None: + checks = check.run_checks(tmp_path, fake()) + assert [c.result for c in checks[:3]] == ["FAIL", "FAIL", "FAIL"] + + +def test_gnome_values_and_unavailable_session(tmp_path: Path) -> None: + root = good_root(tmp_path) + wrong = {**GOOD_GSETTINGS, "idle-delay": "uint32 300\n"} + assert check.check_gnome(fake(gsettings=wrong)).detail == "idle-delay=uint32 300" + assert check.check_gnome(fake(gsettings={})).result == "UNKNOWN" + checks = check.run_checks(root, fake(xrandr=None, gsettings={})) + assert check.summary(checks).startswith("CHECK: ") + + +def test_display_requires_external_1080p60() -> None: + laptop_only = XRANDR_OK.split("HDMI-1")[0] + assert check.check_display(fake(xrandr=laptop_only)).detail == "외부 모니터 없음" + at_50 = XRANDR_OK.replace("60.00*+ 50.00", "60.00 + 50.00*") + result = check.check_display(fake(xrandr=at_50)) + assert result.result == "FAIL" and "HDMI-1 1920x1080@50.00" in result.detail + assert check.check_display(fake(xrandr=None)).result == "UNKNOWN" + + +def test_script_has_no_mutating_commands() -> None: + source = (ROOT / "scripts/ops_laptop_check.py").read_text(encoding="utf-8") + for forbidden in ("sudo", "systemctl", "gsettings set", "--output", "write_text"): + assert forbidden not in source