integrate the session broker: one CLI, a module unit, and a VM check
M0 of the sessions design, wired into the flake and gated by a real check. What is here now: - `src/hhstreamd/` — the broker: session registry, lifecycle verbs, process-group teardown, app allowlist, audit log, idle reaper on CLOCK_BOOTTIME. - `src/hhstream_session/` — the CLI handlers, registered into the one front door. - `src/hhstream/cli.py` — `hhstream status|shot|run|record|session …`, so the frame verbs and the session namespace are one binary. - `nix/module.nix` — `sessions.*` options and the `hhstream-sessions.service` unit: the operator's own account (never a service account, because launched applications should see that account's home), the compositor's group as a supplementary group (without it a launched GUI client cannot open the Wayland socket), the generated app allowlist, and `--compositor-runtime-dir` so applications are handed the compositor's session rather than the broker's. - `checks/vm-sessions.nix` — 18 subtests on a real compositor in a VM. Two bugs found by driving it, both fixed: - BUG-01: launched applications could not reach the compositor at all — the broker spawned them with its own inherited environment, which names the login session. `hhstreamd/compositor.py` discovers the socket and builds the child environment; a directory with no usable socket is a startup refusal, not a warning. - BUG-02: `kill` refused to signal a live application and said nothing was wrong. The identity gate hashed `/proc/<pid>/cmdline`, which every `execve` replaces — and on NixOS applications are reached through wrapper scripts that do exactly that. The gate now rests on `starttime` (+ boot id, + session id where it is immutable) and records command-line drift as evidence of nothing. KillMode=process is set on the unit on purpose: the default control-group kill would take the applications down with the broker, which would make adoption and a broker restart pointless.
This commit is contained in:
1 parent
9dc9e0da9a
commit
30f456c07e
37 files changed
+9118
-1
No files matched your search
@@ -0,0 +1,155 @@
|
||||
"""Rendering for the human views.
|
||||
|
||||
``--json`` output is the protocol's own objects, unmodified: a flag that
|
||||
reshapes the data would mean two contracts to keep in step. The tables below
|
||||
are for people.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from hhstreamd.clock import format_duration
|
||||
|
||||
DASH = "—"
|
||||
|
||||
|
||||
def dump_json(obj: Any, stream=None) -> None:
|
||||
print(json.dumps(obj, indent=2, sort_keys=True), file=stream or sys.stdout)
|
||||
|
||||
|
||||
def _cell(value: Any) -> str:
|
||||
return DASH if value is None else str(value)
|
||||
|
||||
|
||||
def render_table(rows: list[list[str]], headers: list[str]) -> str:
|
||||
widths = [len(h) for h in headers]
|
||||
for row in rows:
|
||||
for i, cell in enumerate(row):
|
||||
widths[i] = max(widths[i], len(cell))
|
||||
out = [" ".join(h.ljust(widths[i]) for i, h in enumerate(headers)).rstrip()]
|
||||
for row in rows:
|
||||
out.append(" ".join(cell.ljust(widths[i]) for i, cell in enumerate(row)).rstrip())
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def render_list(sessions: list[dict[str, Any]]) -> str:
|
||||
"""The default view.
|
||||
|
||||
``EXPIRES IN`` is on it rather than behind a flag because it is the number
|
||||
an agent actually needs.
|
||||
|
||||
There is **no ``FG`` column** (DESIGN.md §1.4, amended): foreground-ness
|
||||
needs compositor IPC, which this milestone does not have, so the column was
|
||||
``?`` on every row of every listing — a header and six columns of width
|
||||
paying for no information, and a reader who has to learn that ``?`` means
|
||||
*unknown* rather than *no*. ``foreground`` stays in the record and in
|
||||
``status``, where it is one line among many and can become real without
|
||||
changing the shape of this table.
|
||||
"""
|
||||
|
||||
if not sessions:
|
||||
return "no sessions"
|
||||
rows = []
|
||||
for s in sessions:
|
||||
live = s.get("live")
|
||||
if live:
|
||||
idle = format_duration(s.get("idle_s"))
|
||||
expires = format_duration(s.get("expires_in_s"))
|
||||
if s.get("expires_in_s") is None:
|
||||
expires = "never"
|
||||
else:
|
||||
idle = DASH
|
||||
left = s.get("tombstone_expires_in_s")
|
||||
expires = f"(tombstone, {format_duration(left)} left)" if left is not None else DASH
|
||||
rows.append(
|
||||
[
|
||||
_cell(s.get("id")),
|
||||
_cell(s.get("app")),
|
||||
_cell(s.get("state")),
|
||||
_cell(s.get("pid")) if live else DASH,
|
||||
idle,
|
||||
expires,
|
||||
]
|
||||
)
|
||||
return render_table(rows, ["ID", "APP", "STATE", "PID", "IDLE", "EXPIRES IN"])
|
||||
|
||||
|
||||
def render_status(session: dict[str, Any]) -> str:
|
||||
live = session.get("live")
|
||||
lines = [
|
||||
f"{session.get('id')} ({session.get('app')})",
|
||||
f" state {session.get('state')}"
|
||||
+ (f" [{session.get('last_error')}]" if session.get("last_error") else ""),
|
||||
f" pid {_cell(session.get('pid'))} pgid {_cell(session.get('pgid'))}"
|
||||
f" sid {_cell(session.get('sid'))}",
|
||||
f" argv {' '.join(session.get('argv') or []) or DASH}",
|
||||
f" home {_cell(session.get('home'))}",
|
||||
f" created {_cell(session.get('created_at'))}",
|
||||
f" last activity {_cell(session.get('last_activity_at'))}"
|
||||
f" ({session.get('command_count', 0)} command(s) counted)",
|
||||
f" idle {format_duration(session.get('idle_s'))}"
|
||||
f" of {format_duration(session.get('idle_timeout_s'))}",
|
||||
f" expires in {format_duration(session.get('expires_in_s'))}"
|
||||
if session.get("expires_in_s") is not None
|
||||
else " expires in never (idle timeout disabled)",
|
||||
f" ready signal {_cell(session.get('ready_signal'))}",
|
||||
f" adopted {session.get('adopted')}",
|
||||
]
|
||||
if not live:
|
||||
lines.append(
|
||||
f" exit code {_cell(session.get('exit_code'))}"
|
||||
f" detected by {_cell(session.get('exit_detected_by'))}"
|
||||
)
|
||||
if session.get("exit_detected_by") in ("pidfd", "proc_poll", "proc_check"):
|
||||
lines.append(" exit code unavailable (adopted process)")
|
||||
compositor = session.get("compositor") or {}
|
||||
lines.append(
|
||||
f" window {_cell(compositor.get('window'))}"
|
||||
f" workspace {_cell(compositor.get('workspace'))}"
|
||||
f" foreground {_cell(compositor.get('foreground'))}"
|
||||
)
|
||||
if compositor.get("note"):
|
||||
lines.append(f" {compositor['note']}")
|
||||
events = session.get("events") or []
|
||||
if events:
|
||||
lines.append(" recent events")
|
||||
for event in events[-20:]:
|
||||
lines.append(f" {event.get('ts')} {event.get('event')}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def render_gc(result: dict[str, Any]) -> str:
|
||||
lines = [
|
||||
f"pruned {result.get('pruned', 0)} tombstone(s), "
|
||||
f"reconciled {len(result.get('reconciled') or [])} session(s)",
|
||||
f"{result.get('live', 0)} live, {result.get('tombstones', 0)} tombstone(s) remain",
|
||||
]
|
||||
for item in result.get("reconciled") or []:
|
||||
lines.append(f" {item['id']}: {item['why']}")
|
||||
unresolved = result.get("unresolved") or []
|
||||
if unresolved:
|
||||
# Not a routine exit: the daemon could not establish whether these pids
|
||||
# are still their sessions', so it signalled nothing. Said loudly
|
||||
# because the application may well still be running (BUG-02 item 5).
|
||||
lines.append(
|
||||
"UNRESOLVED — identity could not be established, nothing was signalled:"
|
||||
)
|
||||
for item in unresolved:
|
||||
mismatched = ", ".join(item.get("mismatched") or []) or "no usable evidence"
|
||||
lines.append(f" {item['id']}: {item['why']} ({mismatched})")
|
||||
orphans = result.get("orphans") or []
|
||||
if orphans:
|
||||
lines.append("orphaned processes (escaped the process group AND the session id):")
|
||||
for item in orphans:
|
||||
lines.append(f" {item['id']} sid {item['sid']}: pids {item['pids']}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def render_error(reply: dict[str, Any]) -> str:
|
||||
parts = [f"error: {reply.get('reason') or reply.get('error')}"]
|
||||
if reply.get("hint"):
|
||||
parts.append(f"hint: {reply['hint']}")
|
||||
return "\n".join(parts)
|
||||
Reference in new issue
Block a user