llm-host/llmhost/service.py
neil e814a2359d install-newt: optional internet access via a Pangolin tunnel, with OIDC sign-in on the dashboard
A plain install is unchanged: LAN-only, dashboard behind the API key. `llmhost install-newt`
is the upgrade path. It installs a pinned, sha256-checked newt as a third user service and
switches the dashboard to an OIDC authorization-code + PKCE sign-in limited to allowed groups
or users. The API still takes the key. Secrets live in 0600 files, never in config.json, a
service file or argv. `llmhost remove-newt` undoes it; setup/update keep it; `logs --newt`
shows the tunnel (and `logs -f` now follows the service it was asked for).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 21:44:09 -08:00

226 lines
7.1 KiB
Python

"""Background services: systemd --user on Linux, launchd agents on macOS.
Two services: "model" (the inference server) and "web" (dashboard), plus "newt" (the
Pangolin tunnel) only after `llmhost install-newt`. Each runs `llmhost run-<name>`.
"""
import os
import re
import subprocess
import time
from pathlib import Path
from . import paths
NAMES = ("model", "web") # what setup installs
OPTIONAL = ("newt",) # installed by their own command
def _run(cmd, timeout=60):
try:
r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
return r.returncode, r.stdout.strip(), r.stderr.strip()
except (OSError, subprocess.TimeoutExpired) as e:
return 1, "", str(e)
# ---------------- systemd ----------------
def _unit(name):
return f"llm-host-{name}"
def _unit_path(name):
return paths.HOME / ".config/systemd/user" / f"{_unit(name)}.service"
def _systemd_install(name):
desc = {"model": "llm-host model server", "web": "llm-host dashboard",
"newt": "llm-host tunnel (newt)"}[name]
extra = "TimeoutStartSec=1800\nTimeoutStopSec=60\n" if name == "model" else ""
p = _unit_path(name)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(f"""[Unit]
Description={desc}
After=network-online.target
[Service]
ExecStart={paths.SHIM} run-{name}
Restart=on-failure
RestartSec=10
{extra}
[Install]
WantedBy=default.target
""")
# ---------------- launchd ----------------
def _label(name):
return f"dev.llm-host.{name}"
def _plist_path(name):
return paths.HOME / "Library/LaunchAgents" / f"{_label(name)}.plist"
def _domain():
return f"gui/{os.getuid()}"
def _launchd_install(name):
paths.LOG_DIR.mkdir(parents=True, exist_ok=True)
log = paths.LOG_DIR / f"{name}.log"
path_env = f"{paths.BIN_DIR}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
p = _plist_path(name)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>{_label(name)}</string>
<key>ProgramArguments</key>
<array><string>{paths.SHIM}</string><string>run-{name}</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
<key>ThrottleInterval</key><integer>10</integer>
<key>StandardOutPath</key><string>{log}</string>
<key>StandardErrorPath</key><string>{log}</string>
<key>EnvironmentVariables</key><dict><key>PATH</key><string>{path_env}</string></dict>
</dict>
</plist>
""")
def _launchd_loaded(name):
rc, out, _ = _run(["launchctl", "print", f"{_domain()}/{_label(name)}"])
return rc == 0, out
# ---------------- public API ----------------
def install(name):
if paths.IS_MAC:
_launchd_install(name)
else:
_systemd_install(name)
_run(["systemctl", "--user", "daemon-reload"])
_run(["systemctl", "--user", "enable", _unit(name)])
def installed(name):
return (_plist_path(name) if paths.IS_MAC else _unit_path(name)).exists()
def enable_linger():
"""Keep user services running without a login session (Linux). Often allowed without sudo."""
if paths.IS_MAC:
return True
user = os.environ.get("USER") or os.getlogin()
_run(["loginctl", "enable-linger", user])
rc, out, _ = _run(["loginctl", "show-user", user, "-p", "Linger"])
return out.strip() == "Linger=yes"
def start(name):
if paths.IS_MAC:
loaded, _ = _launchd_loaded(name)
if loaded:
return _run(["launchctl", "kickstart", f"{_domain()}/{_label(name)}"])[0] == 0
return _run(["launchctl", "bootstrap", _domain(), str(_plist_path(name))])[0] == 0
return _run(["systemctl", "--user", "start", _unit(name)], timeout=120)[0] == 0
def stop(name):
if paths.IS_MAC:
loaded, _ = _launchd_loaded(name)
return (not loaded) or _run(["launchctl", "bootout", f"{_domain()}/{_label(name)}"])[0] == 0
return _run(["systemctl", "--user", "stop", _unit(name)], timeout=120)[0] == 0
def restart(name):
if paths.IS_MAC:
loaded, _ = _launchd_loaded(name)
if loaded:
return _run(["launchctl", "kickstart", "-k", f"{_domain()}/{_label(name)}"])[0] == 0
return start(name)
return _run(["systemctl", "--user", "restart", _unit(name)], timeout=120)[0] == 0
def uninstall(name):
stop(name)
if paths.IS_MAC:
_plist_path(name).unlink(missing_ok=True)
else:
_run(["systemctl", "--user", "disable", _unit(name)])
_unit_path(name).unlink(missing_ok=True)
_run(["systemctl", "--user", "daemon-reload"])
def _etime_seconds(s):
# ps etime: [[dd-]hh:]mm:ss
days = 0
if "-" in s:
d, s = s.split("-", 1)
days = int(d)
parts = [int(x) for x in s.split(":")]
while len(parts) < 3:
parts.insert(0, 0)
h, m, sec = parts
return days * 86400 + h * 3600 + m * 60 + sec
def state(name):
"""Returns (state, uptime_seconds). state is one of active, activating, inactive, failed."""
if paths.IS_MAC:
loaded, out = _launchd_loaded(name)
if not loaded:
return "inactive", None
pid = re.search(r"\bpid = (\d+)", out)
if pid:
rc, et, _ = _run(["ps", "-o", "etime=", "-p", pid.group(1)])
return "active", (_etime_seconds(et.strip()) if rc == 0 and et.strip() else None)
last = re.search(r"last exit code = (\d+)", out)
return ("failed" if last and last.group(1) != "0" else "activating"), None
rc, out, _ = _run(["systemctl", "--user", "show", _unit(name), "-p", "ActiveState,ActiveEnterTimestampMonotonic"])
props = dict(l.split("=", 1) for l in out.splitlines() if "=" in l)
st = props.get("ActiveState", "inactive")
mono = int(props.get("ActiveEnterTimestampMonotonic", "0") or 0)
up = time.monotonic() - mono / 1e6 if st == "active" and mono else None
return st, up
def logs(name, n=200):
if paths.IS_MAC:
log = paths.LOG_DIR / f"{name}.log"
try:
with open(log, "rb") as f:
f.seek(0, 2)
size = f.tell()
f.seek(max(0, size - 256 * 1024))
lines = f.read().decode(errors="replace").splitlines()
return lines[-n:]
except OSError:
return []
rc, out, _ = _run(["journalctl", "--user", "-u", _unit(name), "-n", str(n), "--no-pager", "-o", "short-iso"])
return out.splitlines()
def log_command(name):
if paths.IS_MAC:
return ["tail", "-n", "100", "-F", str(paths.LOG_DIR / f"{name}.log")]
return ["journalctl", "--user", "-u", _unit(name), "-n", "100", "-f", "-o", "cat"]
def trim_log(name, max_bytes=50 * 2**20):
"""launchd never rotates; keep the log from growing forever."""
if not paths.IS_MAC:
return
log = paths.LOG_DIR / f"{name}.log"
try:
if log.stat().st_size > max_bytes:
with open(log, "rb") as f:
f.seek(-5 * 2**20, 2)
tail = f.read()
log.write_bytes(tail)
except OSError:
pass