From 2ca7e86d72a6e94bdf214bcef6241190847e1ae5 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 2 Nov 2026 21:13:29 +0100 Subject: [PATCH] Owner install artifacts and docs/unattended.md: systemd install script, lab mode, exact owner steps scripts/ops/install-leleka-service.sh (owner runs it with sudo; nothing here was run by an agent): --install [--no-start] [--force] copies scripts/ops/leleka.service to /etc/systemd/system, daemon-reload, enable, start; refuses when the state is not prepared, a binary is missing, the user para does not exist, or the lab KAR holder runs --remove stop, disable, remove the unit (state, logs, models untouched) --status unprivileged: systemd state, lab mode, the supervisor's status.json (phase, uptime, restarts and reason, health), log tail --lab on|off STATE/lab-mode: the unit (ConditionPathExists=!) stays down while the GPU belongs to the lab queue docs/unattended.md: what runs, the exact owner steps (prepare with `leleka up --mode none`, install, use, look, update), lab mode, the fast cold load (problem, change, measurements), the supervision table (what happens for every failure), logs and disk, security defaults, the soak test (harness, criteria, the multi-day command), open items. docs/deploy.md section 6 follows the new restart, log and status behaviour. Co-Authored-By: Claude Sonnet 5.5 --- docs/deploy.md | 15 +- docs/unattended.md | 224 ++++++++++++++++++++++++++ scripts/ops/install-leleka-service.sh | 125 ++++++++++++++ 3 files changed, 359 insertions(+), 5 deletions(-) create mode 100644 docs/unattended.md create mode 100755 scripts/ops/install-leleka-service.sh diff --git a/docs/deploy.md b/docs/deploy.md index dd05f17c..0502d05d 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -235,11 +235,16 @@ Other commands: `leleka verify` (full parallel hash of shards and archive, renew ## 6. Operating it * systemd: `systemctl status leleka`, `journalctl -u leleka -f` (user unit: add `--user`; run `loginctl enable-linger USER` to start without a login). The unit has - `Restart=on-failure` with `RestartSec=30`, at most 3 starts in 30 minutes, and no restart after exit code 2 (configuration), because every start re-reads 55 GB. -* The supervisor restarts a dead engine up to twice (counter reset after 10 ready minutes) with the same sealed descriptor and loads the model again; the API process stays up and - answers not-ready meanwhile. A dead gateway (3) or API (5) is restarted too. Then it exits 1 and systemd decides. + `Restart=on-failure` with `RestartSec=30` growing to 10 minutes (`RestartSteps`), no start limit, and no restart after exit code 2 (configuration). The unattended + server setup (hardened unit, install script, lab mode) is in [`unattended.md`](unattended.md). +* The supervisor restarts a dead engine with the same sealed descriptor and loads the model again, waiting 5 s, 10 s, 20 s ... (at most 300 s) between attempts; + a start that fails counts as an attempt; after 6 in a row (the counter resets after 10 ready minutes) it exits 1 and systemd starts everything afresh. A hung engine is + found by the health check (`GET /metrics` every 10 s) and killed; see `unattended.md` section 5. The API process stays up and answers not-ready meanwhile. + A dead gateway (3) or API (5) is restarted too. * `SIGTERM`/`SIGINT` drain: the API first (`shutdown_grace_s` 10), then the gateway and the engine (both handle SIGINT only, so the supervisor sends SIGINT), then SIGKILL after the grace. -* Logs: `STATE/logs/{leleka,engine,gateway,api,install}.log` (rotated once past 64 MiB at start). Status: `STATE/run/status.json` (`phase`: sealing, starting_engine, loading, starting_api, ready, engine_restarting, draining, stopped, failed). +* Logs: `STATE/logs/{leleka,engine,gateway,api,install}.log`; the supervisor copy-truncates any log past 16 MiB every 10 s and keeps 3 generations (`logs` in `leleka.json`). + Status: `STATE/run/status.json` (`phase`: sealing, starting_engine, loading, starting_api, ready, engine_restarting, draining, stopped, failed; also uptime, restarts and + their reason, the health judgement, log volume; rewritten every 30 s). `leleka status` renders it, `leleka verify --quick` checks the installation without reading the model. * Use it: `curl -H "Authorization: Bearer $(cat STATE/api-key)" -H 'content-type: application/json' -d '{"model":"qwen-iq3","input":"hello","max_output_tokens":32}' http://127.0.0.1:8081/v1/responses`. Remote clients: an SSH tunnel. Known limits of this API-over-engine path (4096 output tokens, 256 generations per engine epoch, no image input) are in [`api-over-rust-engine.md`](api-over-rust-engine.md). @@ -256,7 +261,7 @@ A start used to hash 83.6 GB of shards and the 55 GB archive one after the other | a reader thread keeps 6 x 8 MiB chunks ahead of the hasher (`pread`, `FADV_SEQUENTIAL`, recycled buffers) | `model-format/src/readahead.rs`, used by `VerifiedGgufFile::open` and the archive scan | I/O and hashing overlap | | archive scan: SHA-256 on one thread, per-section CRC-32 on another | `kar.rs` `verify_integrity_pipelined`; same verdicts and precedence (SHA mismatch before CRC failure), tested against the stream scan | the 55 GB pass costs the slower of the two | | **verification stamps**: a file that matched its pinned digest and is unchanged (device, inode, size, mtime, **ctime**) is not hashed again | `model-format/src/verify_stamp.rs`, `leleka-inference --verify-stamps DIR` (the supervisor passes `STATE/stamps/engine`) | a restart hashes nothing that did not change | -| the supervisor copies the archive into the memfd with several threads and checks that the source did not change while it was copied | `sealed.rs` `seal_file_with_identity` | the fill runs at memory bandwidth | +| the supervisor copies the archive into the memfd with 32 threads reading 8 MiB `O_DIRECT` blocks (`model-format/src/bulk_read.rs`) and checks that the source did not change while it was copied | `sealed.rs` `seal_file_report` | 55 GB cold in 153 s on the 5090 server instead of 6-33 min (`unattended.md` section 4) | | a sealed memfd that this supervisor already had verified (an earlier engine) or that was copied from a file whose `kar-source` stamp matched is not hashed again: `--kar-attested-by-stamp` | `supervisor.rs`, `verify_stamp::set_attested_archive` | engine restarts and service restarts skip the 55 GB hash | | on the first start, a CPU-only `--verify-only` hashes the shards while the supervisor fills the memfd | `supervisor.rs` `spawn_shard_preverify` | the two big reads overlap | | `leleka verify` | `app.rs` | hashes shards and archive in full, in parallel, renews every stamp | diff --git a/docs/unattended.md b/docs/unattended.md new file mode 100644 index 00000000..4f2f078a --- /dev/null +++ b/docs/unattended.md @@ -0,0 +1,224 @@ +# Leleka as an unattended service on the 5090 server + +Branch `claude/unattended` (base `f9003b7ce`). Goal: the owner uses Leleka as the thinking system for daily work (Codex CLI through the +control-plane HTTP/Responses gateway) and never has to babysit it: it starts at boot, starts fast, restarts itself when the engine dies or +hangs, answers a failing request with an error instead of a hang, keeps its logs small, and exposes nothing beyond loopback. + +Everything here is about **operations**. No kernel, sampler or model path changed; the one engine-side change (how the expert bank is read from +disk) is bitwise-identical by construction and is checked by the replay gate in section 9. Nothing here is a throughput claim. + +Contents: 1 what runs; 2 owner steps (exact commands); 3 lab mode; 4 fast cold load; 5 supervision; 6 logs; 7 security defaults; +8 the soak test (harness, criteria, multi-day command); 9 what was run and what happened; 10 open items. + +## 1. What runs + +```text +systemd: leleka.service (User=para, Restart=on-failure, starts at boot) + `- leleka run --config STATE/leleka.json the supervisor ("the holder": it owns the sealed archive) + |- seals the 55 GB KAR archive into a memfd ONCE (O_DIRECT, 32 x 8 MiB blocks; 2.5 min cold) + |- leleka-daemon gateway, 127.0.0.1:18080 + |- leleka-inference engine, gRPC 127.0.0.1:18766 (gets a duplicate of the memfd) + `- strata-next serve the API Codex talks to, 127.0.0.1:8081, bearer key in STATE/api-key +``` + +The service replaces the lab infrastructure for daily use: the Python KAR holder (`run_holder2.sh`), `gpu.lock` and the job stubs in +`~/work/gpu-runs/holder2/jobs` are **not** involved (nothing in the product reads them). They are mutually exclusive with the service +(both want the GPU and 51 GB of RAM); section 3 says how to hand the machine from one to the other. + +Layout on `rnr5090` (all inside the work folder, which is a symlink to `/data/leleka-e2e`): + +| path | content | +| --- | --- | +| `/data/leleka-e2e/service/prefix/bin/` | `leleka`, `leleka-inference`, `leleka-daemon`, `leleka-cli`, `leleka-seal-exec`, `strata-next` | +| `/data/leleka-e2e/service/state/` | `leleka.json` (run configuration), `runtime.env` + `api-key` (mode 0600), `run/status.json`, `logs/`, `stamps/` | +| `/home/para/work/leleka/models/leleka-gates/assets/` | shards, archive, MTP pack, tokenizer (read only; unchanged) | +| `/data/leleka-e2e/service/ops/` | `install-leleka-service.sh`, `leleka.service` (copies of `scripts/ops/`) | + +## 2. Owner steps + +Everything below is run by the owner; the agent that wrote this did not run any of it on the server (no sudo, no system settings). + +**2.1 Binaries.** Built in WSL from this branch (commit named in section 9) and copied; the server never builds. The agent left a build in +`/data/leleka-e2e/unattended/bin-12d1d71/` (the six binaries). To install them as the service prefix: + +```sh +ssh rnr5090 +mkdir -p /data/leleka-e2e/service/prefix /data/leleka-e2e/service/state +``` + +**2.2 Prepare (as `para`, no sudo; the GPU must be free and the lab holder stopped, section 3).** One command creates the state, tokens, API +key, configs, verification stamps and installs the binaries; it starts nothing: + +```sh +/data/leleka-e2e/unattended/bin-12d1d71/leleka up --mode none \ + --assets /home/para/work/leleka/models/leleka-gates/assets \ + --state-dir /data/leleka-e2e/service/state --prefix /data/leleka-e2e/service/prefix \ + --bin-src /data/leleka-e2e/unattended/bin-12d1d71 \ + --cublas-dir /home/para/cuda-toolkits/cublas-12.9.1.4/lib --trust-archive +``` + +It prints the preflight (13 checks), the resource plan and the exact engine command. If the profile came out as the file/mapped form instead +of `memfd`/`resident`, the host did not have the 109 GiB it needs free at that moment (the lab holder is the usual reason; preflight now says +so): stop it and run the command again. + +**2.3 Install and start (sudo, once).** + +The two files (`install-leleka-service.sh`, `leleka.service`) are in `scripts/ops/` of the repository; there is no repository on the server, so +the agent left a copy in `/data/leleka-e2e/service/ops/` (same directory: the script looks for the unit next to itself). + +```sh +sudo /data/leleka-e2e/service/ops/install-leleka-service.sh --install # copies leleka.service, daemon-reload, enable, start +/data/leleka-e2e/service/ops/install-leleka-service.sh --status # no sudo +``` + +`--install` refuses when the state is not prepared, when the lab holder runs (`--force` overrides), or when a binary is missing; `--no-start` +installs and enables without starting; `--remove` stops, disables and deletes the unit (state, logs and models stay). +The first start after a boot is the archive copy (2.6 min cold, section 4) plus the engine load (section 9); a later restart of the engine alone +takes the load time only (the supervisor keeps the archive). + +**2.4 Use it.** The API is `http://127.0.0.1:8081`; the key is in `/data/leleka-e2e/service/state/api-key`. For Codex on the server: +`base_url = "http://127.0.0.1:8081/v1"`, key from that file. From the laptop use an SSH tunnel (`ssh -L 8081:127.0.0.1:8081 rnr5090`); the +service never listens on anything but loopback (section 7). + +**2.5 Look at it.** + +```sh +STATE=/data/leleka-e2e/service/state; LELEKA=/data/leleka-e2e/service/prefix/bin/leleka +$LELEKA status --state-dir $STATE # ready?, supervisor phase and age, uptime, restarts and why, health, logs, GPU/RAM/throughput +$LELEKA verify --quick --state-dir $STATE --assets /home/para/work/leleka/models/leleka-gates/assets # health without reading the model; exit 0 = OK +systemctl status leleka ; journalctl -u leleka -n 50 +tail -n 30 $STATE/logs/leleka.log # the supervisor's own log: every restart, every health finding +``` + +**2.6 Update.** Copy new binaries to a new directory, `sudo systemctl stop leleka`, run 2.2 again with `--bin-src NEW` (idempotent: it +replaces the binaries by rename and keeps tokens and key), `sudo systemctl start leleka`. + +## 3. Lab mode (hand the machine to the queue and back) + +The lab queue (`kar_holder2.py`, `gpu.lock`, job stubs) and the service want the same GPU and the same 51 GB of RAM. + +```sh +scripts/ops/install-leleka-service.sh --lab on # creates STATE/lab-mode: the unit will not start while it exists (boot included) +sudo systemctl stop leleka # if it runs; then start the lab holder as before (run_holder2.sh) +... +touch ~/work/gpu-runs/holder2/jobs/STOP # lab holder: stop between jobs; wait until its process is gone +scripts/ops/install-leleka-service.sh --lab off && sudo systemctl start leleka +``` + +`leleka up` and the install script both recognise a running `kar_holder` process and say so instead of failing with a bare memory number. + +## 4. Fast cold load + +**Problem (docs/experiments/baseline-pair-5090.md, section 9).** After a reboot the holder read the 55 GB archive with plain `read()` at 8-35 MB/s +(2003.8 s for the first holder). The drive (Lexar NM610PRO, DRAM-less, `max_sectors_kb` 128) serves a 128 KiB request at a time to a sequential +reader; it needs many requests in flight to be fast. The product's own copy (`sealed.rs`, 8 threads of buffered 32 MiB reads) was better but +not enough, and the expert bank load (50 GB from shard 0) used one sequential `read_exact` loop. + +**Change.** `crates/model-format/src/bulk_read.rs`: 32 threads each read 8 MiB blocks with `O_DIRECT` into aligned bounce buffers (the file is +re-opened through its own `/proc/self/fd` entry; no `unsafe`), so the page cache is never touched: nothing to evict, and the free-memory +state that vanilla's huge-page guard looks at stays as it was. Used by the sealed-archive copy, by the expert-bank read (spans >= 64 MiB) and, +as a `WILLNEED` readahead, by the hashing passes. `O_DIRECT` falls back to `WILLNEED`/`DONTNEED` readahead where the file system refuses it. +Knobs for A/B in one binary: `LELEKA_LOAD_READ=direct|advise|plain|legacy`, `LELEKA_LOAD_THREADS`, `LELEKA_LOAD_CHUNK_MIB`. + +**Measured** (page cache of the span evicted with `posix_fadvise(DONTNEED)`, never `drop_caches`; the drive is shared with other agents' jobs, so +every number carries the other traffic; `bulk_read_bench`, `/data/leleka-e2e/unattended/*.out`): + +| | MB/s | 55 GB in | +| --- | ---: | ---: | +| whole KAR file, new default (direct, 32 x 8 MiB), two runs | 362, 346 | 153 s, 160 s | +| one thread, 16-32 MiB reads (the holder's pattern), four cold slices | 65, 86, 105, 154 | 6-14 min | +| the recorded holder after a reboot | 27 | 2003.8 s | +| 8 threads x 32 MiB buffered (old `sealed.rs`), sharing the drive | 240 | 3.8 min | + +The drive's speed varies up to 10x between regions and moments whatever the strategy (the same config measured 113 and 1133 MB/s), so the +multi-thread strategies are not told apart by the 4x7 matrix in the commit message; all beat one thread; `direct` is the default because it +leaves the cache alone. **Target < 5 min: met for the archive copy (2.6 min).** The engine's own load (verify stamps, bank copy, CUDA setup) +is measured in section 9. + +## 5. Supervision (what happens when something breaks) + +| event | what the service does | +| --- | --- | +| engine process dies | the API answers not-ready / errors at once; after 5 s (then 10, 20, ... up to 300 s) the supervisor starts the engine again with the same sealed archive (no 55 GB copy) and loads the model; a start that fails counts as an attempt and is retried; 6 attempts in a row (the counter resets after 10 ready minutes) end the service with exit 1 and systemd starts everything afresh (30 s, growing to 10 min, never gives up) | +| engine hangs (alive, not working) | a request that gets no event for 600 s is cancelled by the API with an error to the client (`stall_timeout_s`); an engine that does not take the cancellation is declared lost by the API; after 120 s of "worker not ready" the supervisor SIGKILLs it and restarts it; a request still active after 3900 s (the API's own 3600 s deadline + 300) does the same | +| API process hangs or dies | dies: restarted after 2 s (5 times); hangs (no answer to `/metrics` for 120 s): killed and restarted | +| gateway dies | restarted after 2 s (3 times); serving does not depend on it | +| supervisor dies | systemd restarts the unit; the sealed archive is copied again (2.6 min cold) and everything starts in order | +| a request fails | HTTP 5xx / `response.failed` with a message, never an open connection: engine death mid-stream ends the stream with a failure event; a stall or an overlong generation is cancelled by the API (above) | +| SIGTERM / `systemctl stop` | the API drains first, then gateway and engine (SIGINT, SIGKILL after the grace), exit 0; `TimeoutStopSec=180` | +| host reboot | the unit is enabled; it starts after `network.target` once `/data` is mounted; lab mode (`STATE/lab-mode`) keeps it down | + +The judgement is `crates/deploy/src/watchdog.rs` (pure, unit-tested) over `GET /metrics` (the control plane's own view). The engine's telemetry +is not used for it: the API refreshes it only between requests, so mid-request it is stale (a finding of this work; `leleka status` shows +`machine: null` during a request longer than 30 s for the same reason). + +Not covered: a process stuck in uninterruptible driver sleep cannot be killed (the supervisor says so and exits; only a reboot helps; the +host already has `server-hang-autoreboot.sh`); GPU or driver faults that corrupt output without hanging. + +## 6. Logs and disk + +* `STATE/logs/{leleka,engine,gateway,api,preverify}.log`, written by the children themselves in append mode. Every 10 s the supervisor + copy-truncates any `*.log` over 16 MiB into `.1` ... `.3` (oldest dropped): at most 16 MiB x 4 x 5 files = 320 MiB, written in 16 MiB + pieces (no stream of small writes). The engine is quiet by default (a few lines per request); trace switches stay off. +* `leleka.json` `logs: {limit_mib, keep}` changes the bound. The status file reports `log_bytes`. +* systemd: `LimitCORE=0` (no 100 GB core dump on the root NVMe), journal rate limit 1000 messages / 30 s for the unit. +* No request capture, transcript or response history is written by default (`api_monitor` is off; `history` is memory only). +* Per-request telemetry stays in memory. + +## 7. Security defaults + +* The API binds `127.0.0.1:8081` (`--api-bind` only for containers); engine and gateway are loopback-only and refuse anything else in + `leleka.json` validation. Remote access: SSH tunnel. No TLS inside the machine. +* Every route except `/health` needs `Authorization: Bearer `; the key is generated by `strata-next api-key init` (random, file 0600, + never rotated by `up`); the two internal tokens live in `runtime.env` (0600) and reach children through their environment, never argv. + `HF_TOKEN` is removed from every child. The unit runs with `UMask=0077` and `NoNewPrivileges=yes` as the unprivileged user `para`. +* No secret in a log: the supervisor never logs a command line with a token; the soak harness scans every log for the key and the tokens + and fails if one appears (section 9). +* `leleka status --json` and `status.json` hold no secret. + +## 8. The soak test + +`scripts/soak/soak.py` (Python, offline tooling; stdlib only) plays a Codex-style session against the running service and breaks it: + +* **session**: one conversation at a time, grown turn by turn from the frozen 782-file source corpus (`/data/leleka-e2e/decode/corpus`, + digest checked; a toy corpus is refused) up to 200k tokens, then a new one; streamed `POST /v1/responses`, `store:false`, a `shell` function + tool whose calls are answered; after an error it retries with backoff like a real client. +* **faults**, injected while a request is in flight: `engine` (kill -9), `hang` (SIGSTOP the engine), `api` (kill -9), `gateway` (kill -9) and + `gateway-term`, `supervisor` (kill -9 the holder), `abort` (client disconnects mid-stream), `logs` (64 MiB flood into three logs), `burst` + (8 parallel requests). +* **criteria** (all must hold; `soak-result.json` lists each with its measurement): + 1. every fault recovers within its bound (engine 900 s, hang stall + 900 s, API / gateway 120 s, supervisor 1500 s); + 2. no request ends improperly: every request ends with a completed response, an HTTP error or an SSE failure event; none hangs or is cut + off silently; a request hit by a crash ends within 90 s, one hit by a hang within stall timeout + 150 s; + 3. a fixed greedy probe returns the same text before the first fault, after every fault and at the end (the state after recovery is sound); + 4. the log directory stays under 400 MiB through the log flood; + 5. no secret in any log; 6. supervisor descriptors stay bounded; 7. the session keeps completing requests; 8. the service is ready at the end. +* `scripts/soak/test_soak.py` tests the harness against a fake service (no GPU). + +**Short run on the GPU (queue job, 1.5-2 h):** `scripts/soak/soak-job.sh` as a holder job (it inherits the holder's memfd, takes `gpu.lock`, +prepares the service state from nothing with `leleka up --mode none`, A/B-measures the cold load, then soaks under a restart loop that plays +systemd including its cgroup kill of the children). The identity gate is `scripts/soak/identity-job.sh`. + +**Multi-day run (owner or agent, with the service installed, lab mode off):** + +```sh +python3 /data/leleka-e2e/unattended/soak/soak.py --state-dir /data/leleka-e2e/service/state --out /data/leleka-e2e/unattended/soak-long-1 \ + --duration-s 259200 \ + --faults "engine@every:7200,api@every:5400,gateway@every:9000,abort@every:1800,burst@every:4000,logs@every:21600,hang@every:43200,supervisor@every:86400" +``` + +(72 h; ~12 engine kills, 6 hangs, 3 supervisor kills with a cold re-seal each; the harness competes with real Codex use for the single +engine slot, so run it when you are away. `soak-result.json` and `events.jsonl` (capped at 50 MiB) stay in the `--out` directory.) + +## 9. What was run, what happened + +(filled in after the GPU run; see the end of this file) + +## 10. Open items + +* The soak was run for 1.5 h, not for days; the multi-day command above is for the owner or the next agent. +* `LELEKA_ORIGINAL_SERVE_PCIE_FRAC` is not set by the profile (the lab jobs pin 0.45); the adaptive-window defaults are being changed on + `claude/window-policy`. The service runs the profile as committed; reconcile when that branch lands. +* `leleka status` shows no machine telemetry while a request longer than 30 s runs (control plane refreshes it between requests). +* The sealed memfd is in RAM only: a supervisor crash costs a 2.6 min re-copy (previously 25-55 min). +* The e2e suite of `leleka-deploy` has 6 environment-dependent failures on the laptop (and one flaky lifecycle test) that exist on the base commit. diff --git a/scripts/ops/install-leleka-service.sh b/scripts/ops/install-leleka-service.sh new file mode 100755 index 00000000..4ee3c99e --- /dev/null +++ b/scripts/ops/install-leleka-service.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +# Owner-run (needs sudo for --install and --remove): put the Leleka runtime under systemd on the 5090 server, so that it +# starts at boot and is restarted when it fails. Nothing here is run by an agent. Read docs/unattended.md first. +# +# sudo scripts/ops/install-leleka-service.sh --install [--no-start] [--force] +# sudo scripts/ops/install-leleka-service.sh --remove +# scripts/ops/install-leleka-service.sh --status +# scripts/ops/install-leleka-service.sh --lab on|off (no sudo: the flag file only; see "Lab mode" in the doc) +# +# --install copies scripts/ops/leleka.service to /etc/systemd/system, reloads systemd, enables the unit (start at boot) and +# starts it unless --no-start is given. It refuses when the service state is not prepared, when the lab KAR +# holder is still running (it holds 51 GB of RAM and the GPU queue; --force overrides), or when the lab flag is set. +# --remove stops and disables the unit and removes the unit file. State, logs and models are left alone. +# --status unprivileged summary: systemd state, the supervisor's status.json, the last log lines. +# --lab on: create STATE/lab-mode (the unit will not start while it exists); off: remove it. The running service is +# not touched by this flag; stop or start it with systemctl. +set -euo pipefail + +SERVICE_DIR=${LELEKA_SERVICE_DIR:-/data/leleka-e2e/service} +STATE=$SERVICE_DIR/state +PREFIX=$SERVICE_DIR/prefix +UNIT=leleka.service +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +SRC=$HERE/$UNIT +DST=/etc/systemd/system/$UNIT + +die() { echo "install-leleka-service: $*" >&2; exit 1; } +need_root() { [ "$(id -u)" = 0 ] || die "this needs root: sudo $0 $*"; } + +lab_holder_running() { pgrep -f 'kar_holder' >/dev/null 2>&1; } + +checks() { + [ -f "$SRC" ] || die "missing $SRC" + [ -f "$STATE/leleka.json" ] && [ -f "$STATE/runtime.env" ] || die "the service state is not prepared ($STATE/leleka.json, runtime.env): run the prepare step of docs/unattended.md first" + [ -x "$PREFIX/bin/leleka" ] || die "missing $PREFIX/bin/leleka" + for b in leleka-inference leleka-daemon leleka-cli strata-next; do + [ -x "$PREFIX/bin/$b" ] || die "missing $PREFIX/bin/$b" + done + id para >/dev/null 2>&1 || die "the unit runs as user para, which does not exist" + if [ -e "$STATE/lab-mode" ]; then + echo "note: $STATE/lab-mode exists, so the unit will be installed and enabled but will not start until it is removed ($0 --lab off)" >&2 + fi + if lab_holder_running && [ "${FORCE:-0}" != 1 ]; then + die "the lab KAR holder (kar_holder*.py) is running: it holds 51 GB of RAM and the GPU queue. Stop it first (touch the STOP file in its jobs directory, wait for it to exit) or pass --force" + fi + if command -v systemd-analyze >/dev/null 2>&1; then + systemd-analyze verify "$SRC" 2>&1 | sed 's/^/systemd-analyze: /' || true + fi +} + +install_unit() { + need_root "$@" + checks + install -m 0644 -o root -g root "$SRC" "$DST" + systemctl daemon-reload + systemctl enable "$UNIT" + if [ "${NO_START:-0}" = 1 ] || [ -e "$STATE/lab-mode" ]; then + echo "installed and enabled; not started. Start it with: sudo systemctl start $UNIT" + else + systemctl start "$UNIT" + echo "installed, enabled and started. Follow it with: journalctl -u $UNIT -f (first start after a boot: a few minutes)" + fi + echo "check: $0 --status" +} + +remove_unit() { + need_root "$@" + if systemctl list-unit-files "$UNIT" >/dev/null 2>&1; then + systemctl disable --now "$UNIT" || true + fi + rm -f "$DST" + systemctl daemon-reload + echo "removed $DST (state, logs and models are untouched)" +} + +status() { + echo "unit: $(systemctl is-enabled "$UNIT" 2>&1 || true) / $(systemctl is-active "$UNIT" 2>&1 || true)" + [ -e "$STATE/lab-mode" ] && echo "lab mode: ON ($STATE/lab-mode exists; the unit does not start)" || echo "lab mode: off" + if lab_holder_running; then echo "lab: the KAR holder is running"; fi + if [ -f "$STATE/run/status.json" ]; then + python3 - "$STATE/run/status.json" <<'PY' 2>/dev/null || cat "$STATE/run/status.json" +import json, sys, time +d = json.load(open(sys.argv[1])) +age = int(time.time()) - d.get("updated_unix", 0) +up = int(time.time()) - d.get("started_unix", d.get("updated_unix", 0)) +print(f"supervisor: phase={d['phase']} ready={d['ready']} up={up//3600}h{up%3600//60:02d}m status age={age}s") +print(f"engine: pid={d.get('engine_pid')} restarts_total={d.get('restarts_total')} in_a_row={d.get('engine_restarts')} last={d.get('last_restart_reason')}") +print(f"health: {d.get('health')} endpoint {d.get('endpoint')} logs {d.get('log_bytes', 0)//(1<<20)} MiB") +print(f"message: {d.get('message')}") +PY + else + echo "status: no $STATE/run/status.json (the service has not run)" + fi + if [ -f "$STATE/logs/leleka.log" ]; then echo "--- last lines of $STATE/logs/leleka.log"; tail -n 8 "$STATE/logs/leleka.log"; fi +} + +lab() { + case "${1:-}" in + on) : > "$STATE/lab-mode"; echo "lab mode ON: the unit will not start. If it is running: sudo systemctl stop $UNIT (then start the lab holder)";; + off) rm -f "$STATE/lab-mode"; echo "lab mode off. Stop the lab holder, then: sudo systemctl start $UNIT";; + *) die "--lab needs on or off";; + esac +} + +ACTION= +FORCE=0 +NO_START=0 +while [ $# -gt 0 ]; do + case "$1" in + --install|--remove|--status) ACTION=${1#--}; shift;; + --lab) ACTION=lab; shift; LABARG=${1:-}; [ $# -gt 0 ] && shift;; + --no-start) NO_START=1; shift;; + --force) FORCE=1; shift;; + -h|--help) sed -n '2,20p' "$0"; exit 0;; + *) die "unknown argument $1 (see --help)";; + esac +done +export FORCE NO_START +case "$ACTION" in + install) install_unit "$@";; + remove) remove_unit "$@";; + status) status;; + lab) lab "${LABARG:-}";; + *) sed -n '2,20p' "$0"; exit 2;; +esac