hugpy-queue 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hugpy_queue/rows.py ADDED
@@ -0,0 +1,205 @@
1
+ """A call's own row as the run keeps it, and the rows of its stages: brought here from the wrapper (2026-12-03).
2
+
3
+ The operator, 2026-12-03: the queue "is the actual component that is responsible for the calls". Until this move the
4
+ text of these tables and every statement that writes a call's row lived in hugpy-resources (`sql/statements.py`,
5
+ `sql/wrapper.py`, `queue/rows.py`, `queue/run.py`, `queue/telemetry.py`). They are here now, unchanged in what they
6
+ do, and the wrapper calls them.
7
+
8
+ Every function takes the connection it is to write on. Today that is the wrapper's database (wrapper.sqlite3), where
9
+ the tables `queue` and `call_stages` still are: the wrapper's process makes the launch and writes the call's row as it
10
+ goes. These are NOT the door's tables of queue.sqlite3 (`calls`, and a `call_stages` keyed by call_id: store.py),
11
+ and `QUEUE_TABLE` / `CALL_STAGES_TABLE` must not be run on that file while the two shapes are apart.
12
+
13
+ What stays with whoever calls: trying a write again while the database is locked, and waking its own run loop after
14
+ a write. Both belong to the process that holds the connection, so they are handed in (`retry`, `changed`) or done
15
+ around the call; nothing here waits on anything.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from .imports import json, sqlite3, sys, time
20
+
21
+ TERMINAL = ("done", "failed", "cancelled")
22
+
23
+ # The call's row. (hugpy-resources sql/statements.py, in WRAPPER_SCHEMA.)
24
+ QUEUE_TABLE = """
25
+ CREATE TABLE IF NOT EXISTS queue (
26
+ id INTEGER PRIMARY KEY, arrived_at REAL, model TEXT, key TEXT, variation TEXT, engine TEXT,
27
+ body TEXT, tokens_in INTEGER, tokens_out_hi INTEGER, endpoint TEXT,
28
+ state TEXT, -- waiting | turn | done | failed
29
+ -- the predictions, saved once at dispatch to compare with what happened
30
+ p_gpu_bytes INTEGER, p_ram_bytes INTEGER, p_swap_bytes INTEGER, p_disk_bytes INTEGER,
31
+ p_engine_lo_s REAL, p_engine_hi_s REAL, p_reap_s REAL, p_evict_s REAL, p_load_s REAL, p_eta_s REAL,
32
+ p_ready_s REAL, p_base_ms REAL, p_reads_gpu_bytes INTEGER, p_kappa REAL,
33
+ -- what happened
34
+ turn_at REAL, accommodated_at REAL, loaded_at REAL, done_at REAL, load_run INTEGER,
35
+ tokens_out INTEGER, prompt_ms REAL, decode_ms REAL, response TEXT, error TEXT,
36
+ -- the nested co-load group a waiting call joined on arrival (queue/groups: assigned by a co-load query
37
+ -- against the groups' lower bounds), so group priority is a column the admission read orders by, not Python state
38
+ group_id INTEGER, cpu_preempted_at REAL
39
+ );
40
+ """
41
+
42
+ QUEUE_INDEXES = """
43
+ CREATE INDEX IF NOT EXISTS queue_state ON queue(state);
44
+ CREATE INDEX IF NOT EXISTS queue_unit ON queue(key, variation, state);
45
+ """
46
+
47
+ # one row per finished stage of a call, in the order they finished (STAGE_ORDER names; DISCOVERIES 12): the sort's
48
+ # predictions as the row arrives, then each step of the run with when it started and ended. Written once, never
49
+ # changed, so core follows it by row id (the wrapper's queue/telemetry.py).
50
+ CALL_STAGES_TABLE = """
51
+ CREATE TABLE IF NOT EXISTS call_stages (
52
+ id INTEGER PRIMARY KEY, queue_id INTEGER NOT NULL, stage TEXT NOT NULL, started_at REAL, finished_at REAL,
53
+ predicted_s REAL, note TEXT
54
+ );
55
+ CREATE INDEX IF NOT EXISTS call_stages_queue ON call_stages(queue_id);
56
+ """
57
+
58
+ # Columns the call's row gained after its table was first made: added to a database that lacks them.
59
+ # (hugpy-resources sql/wrapper.py, the "queue" entry of its column loop.)
60
+ QUEUE_COLUMNS = (
61
+ ("p_ready_s", "REAL"), ("p_base_ms", "REAL"), ("p_reads_gpu_bytes", "INTEGER"),
62
+ ("p_kappa", "REAL"), ("endpoint", "TEXT"), ("p_reload_s", "REAL"), ("cancel_requested_at", "REAL"),
63
+ ("cpu_preempted_at", "REAL"),
64
+ # a failed row: the step it failed at, who failed (client | wrapper | wrapper-internal | discovery | engine),
65
+ # and the engine's own HTTP status
66
+ ("error_stage", "TEXT"), ("error_source", "TEXT"), ("error_status", "INTEGER"),
67
+ ("resolved", "TEXT"),
68
+ # the output-length range the prediction used, and how the call ended
69
+ ("p_tokens_out_lo", "INTEGER"), ("p_tokens_out_hi", "INTEGER"),
70
+ ("p_tokens_out", "INTEGER"), ("finish_reason", "TEXT"),
71
+ # its place in the queue's plan at dispatch, and the capacity rows ahead of it
72
+ ("p_position", "INTEGER"), ("p_capacity", "TEXT"),
73
+ # the id a caller sent with the call (core's request id): cancel and retry by it
74
+ ("parent_request_id", "TEXT"),
75
+ ("env", "TEXT"), # JSON: the env the unit was judged against, its status
76
+ # the input's bound on the fit (the wrapper's resources/fit.bounds_of): {start, only}, no names
77
+ ("tier_bounds", "TEXT"),
78
+ # what the row is doing now, said plainly (shown while it is at its turn)
79
+ ("doing", "TEXT"),
80
+ # the nested co-load group the waiting call joined on arrival: group priority is a column the admission read
81
+ # orders by, not Python state
82
+ ("group_id", "INTEGER"),
83
+ # its plan as admission made it, before its load starts: the context and KV the fit chose and where the KV goes,
84
+ # and everything it will take: on the card (its weights there, its KV when there, its engine's own room) and in
85
+ # host memory. p_gpu_bytes .. p_disk_bytes are the weights alone, per tier.
86
+ ("p_ctx", "INTEGER"), ("p_kv_bytes", "INTEGER"), ("p_kv_tier", "TEXT"),
87
+ ("p_engine_bytes", "INTEGER"), ("p_card_bytes", "INTEGER"), ("p_host_bytes", "INTEGER"),
88
+ # the KV is a range until the call is offered its turn: the least and the most its column keeps on that
89
+ # resource. p_ctx / p_kv_bytes are set only then, sized into the room the offer leaves it, up to the most.
90
+ ("p_ctx_min", "INTEGER"), ("p_kv_min_bytes", "INTEGER"),
91
+ ("p_ctx_max", "INTEGER"), ("p_kv_max_bytes", "INTEGER"),
92
+ )
93
+
94
+
95
+ def tokens_in_estimate(body: dict) -> int:
96
+ """Tokens in before any engine holds a tokenizer: characters / 4 (the actual count is recorded after)."""
97
+ chars = 0
98
+ for m in body.get("messages") or []:
99
+ c = m.get("content")
100
+ if isinstance(c, list):
101
+ c = " ".join(p.get("text", "") for p in c if isinstance(p, dict))
102
+ chars += len(c or "")
103
+ return max(1, chars // 4)
104
+
105
+
106
+ def stage(conn: sqlite3.Connection, queue_id: int, name: str, started: float, finished: float,
107
+ predicted: float = None, note: str = None) -> None:
108
+ """One finished stage of a call (call_stages). Recording a stage must never fail the call: a database error
109
+ here is reported on stderr and the run carries on."""
110
+ try:
111
+ with conn:
112
+ conn.execute("INSERT INTO call_stages (queue_id, stage, started_at, finished_at, predicted_s, note) "
113
+ "VALUES (?,?,?,?,?,?)", (queue_id, name, started, finished, predicted, (note or None) and str(note)[:1000]))
114
+ except sqlite3.Error as exc:
115
+ # `module` names the process that writes these rows today, as its journal has always had it
116
+ print(json.dumps(dict(ts=time.time(), module="test-wrapper", level="warning", event="call_stage.failed",
117
+ ids=dict(queue_id=queue_id, stage=name), error=f"{type(exc).__name__}: {exc}")),
118
+ file=sys.stderr, flush=True)
119
+
120
+
121
+ def arrived(conn: sqlite3.Connection, body: dict, endpoint: str, unit: dict, env, bounds, tokens_in: int,
122
+ tokens_out_hi: int, parent_request_id: str = None, retry=None, changed=None) -> int:
123
+ """A call arrives (stage 10): its row is written, waiting, and its `received` stage. Returns the row's id.
124
+
125
+ `unit` is the unit the call was resolved to (key, variation, engine, and `resolved` when a name matched several);
126
+ `env` and `bounds` are kept as JSON when there are any. The row is inserted cheaply: no fit, no plan. Its
127
+ predictions are left unset and derived later from the database, so many calls arriving at once each cost one
128
+ indexed insert. `retry(fn)` is the caller's way of trying a write again on a lock that passes, so a queued call is
129
+ never lost to it; `changed()` is called once the row is committed (the caller's run loop plans it)."""
130
+ def _insert():
131
+ with conn:
132
+ return conn.execute(
133
+ "INSERT INTO queue (arrived_at, model, key, variation, engine, body, tokens_in, tokens_out_hi, "
134
+ "state, endpoint, resolved, env, tier_bounds) VALUES (?,?,?,?,?,?,?,?,'waiting',?,?,?,?)",
135
+ (time.time(), body.get("model"), unit["key"], unit["variation"], unit["engine"], json.dumps(body),
136
+ tokens_in, tokens_out_hi, endpoint, json.dumps(unit["resolved"]) if unit.get("resolved") else None,
137
+ json.dumps(env) if env else None, json.dumps(bounds) if bounds else None)).lastrowid
138
+ rid = retry(_insert) if retry else _insert()
139
+ if changed:
140
+ changed()
141
+ now = time.time()
142
+ if parent_request_id:
143
+ with conn:
144
+ conn.execute("UPDATE queue SET parent_request_id = ? WHERE id = ?", (str(parent_request_id)[:200], rid))
145
+ stage(conn, rid, "received", now, now)
146
+ return rid
147
+
148
+
149
+ def mark(conn: sqlite3.Connection, row_id: int, **cols) -> None:
150
+ """Write columns of a call's row, in one transaction. (The wrapper's run._mark tries it again on a lock and wakes
151
+ its run loop after: both stay with it.)"""
152
+ sets = ", ".join(f"{k} = ?" for k in cols)
153
+ with conn:
154
+ conn.execute(f"UPDATE queue SET {sets} WHERE id = ?", (*cols.values(), row_id))
155
+
156
+
157
+ class Cancelled(Exception):
158
+ """A client cancelled the row (DELETE /v1/queue/{id}); the run stops at the next step boundary."""
159
+
160
+
161
+ def cancel_requested(conn: sqlite3.Connection, row_id: int) -> bool:
162
+ at = conn.execute("SELECT cancel_requested_at FROM queue WHERE id = ?", (row_id,)).fetchone()
163
+ return bool(at and at[0])
164
+
165
+
166
+ def check_cancel(conn: sqlite3.Connection, row_id: int) -> None:
167
+ if cancel_requested(conn, row_id):
168
+ raise Cancelled("cancelled by client (at a step boundary; what was done stays done)")
169
+
170
+
171
+ def cancel_row(conn: sqlite3.Connection, row_id: int, now: float) -> tuple:
172
+ """The row's part of a cancel, to be run inside the caller's transaction (and under its claim lock): a waiting
173
+ row is cancelled at once; one at its turn is marked as asked to stop. Returns (state, loaded_at, at_once):
174
+ the row's state after this, when it was loaded if it was, and whether it was cancelled here before its turn.
175
+ What is then done to an engine that is loading or answering for it is not the row's and stays with the caller."""
176
+ row = conn.execute("SELECT state, loaded_at FROM queue WHERE id = ?", (row_id,)).fetchone()
177
+ if not row:
178
+ raise LookupError(f"no queue row {row_id}")
179
+ state, loaded = row
180
+ if state == "waiting":
181
+ n = conn.execute("UPDATE queue SET state = 'cancelled', done_at = ?, cancel_requested_at = ?, "
182
+ "error = 'cancelled by client before its turn' WHERE id = ? AND state = 'waiting'",
183
+ (now, now, row_id)).rowcount
184
+ if n:
185
+ return "cancelled", loaded, True
186
+ state = conn.execute("SELECT state FROM queue WHERE id = ?", (row_id,)).fetchone()[0]
187
+ if state == "turn":
188
+ conn.execute("UPDATE queue SET cancel_requested_at = ? WHERE id = ? AND state = 'turn'", (now, row_id))
189
+ return state, loaded, False
190
+
191
+
192
+ def request_id(sid: str, queue_id: int) -> str:
193
+ """A call's stable id on the store `sid`: core keys call_log by it."""
194
+ return f"hw-{sid[:12]}-{queue_id}"
195
+
196
+
197
+ def queue_id_of(conn: sqlite3.Connection, rid: str, sid: str):
198
+ """The queue row a request id names: the store's own id for it (`sid` is that store's identity), or the id a
199
+ caller sent with the call (Idempotency-Key / X-Hugpy-Parent-Request-Id). None when it names none."""
200
+ prefix = f"hw-{sid[:12]}-"
201
+ if rid.startswith(prefix) and rid[len(prefix):].isdigit():
202
+ r = conn.execute("SELECT id FROM queue WHERE id = ?", (int(rid[len(prefix):]),)).fetchone()
203
+ return r[0] if r else None
204
+ r = conn.execute("SELECT id FROM queue WHERE parent_request_id = ? ORDER BY id DESC LIMIT 1", (rid,)).fetchone()
205
+ return r[0] if r else None
hugpy_queue/store.py ADDED
@@ -0,0 +1,166 @@
1
+ """The queue's own database: queue.sqlite3, written by ONE thread of this process and by nothing else.
2
+
3
+ Every write goes through `write(fn)`: the function is run on the writer thread with the one writing connection, in a
4
+ transaction. A door thread that needs what was written (the id of a call's row) waits for it; a record nobody waits
5
+ on (a door row, a count) is handed over and left. Anything may read (`reader()`: a read-only connection).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from .imports import DEFAULTS, QUEUE_DB, STAGE_ORDER, connect_wal, os, queue, sqlite3, threading, time
10
+
11
+ SCHEMA = """
12
+ CREATE TABLE IF NOT EXISTS settings (name TEXT PRIMARY KEY, value TEXT NOT NULL, by TEXT, at REAL);
13
+ -- The operator's order as data: a stage's number, its name, the part that owns it, and whether it predicts or acts.
14
+ CREATE TABLE IF NOT EXISTS stage_order (
15
+ stage_no INTEGER PRIMARY KEY, stage TEXT NOT NULL UNIQUE, owner TEXT NOT NULL, phase TEXT NOT NULL, what TEXT
16
+ );
17
+ -- A call: what it is and has. One row for every POST at the door, written when it arrives. `body` is held only
18
+ -- while the call is in flight (it is what each owner is handed) and removed when the call ends.
19
+ CREATE TABLE IF NOT EXISTS calls (
20
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
21
+ arrived_at REAL NOT NULL,
22
+ endpoint TEXT NOT NULL,
23
+ model TEXT, -- as the caller named it
24
+ stream INTEGER,
25
+ max_tokens INTEGER,
26
+ caller TEXT,
27
+ bytes_in INTEGER,
28
+ body BLOB,
29
+ state TEXT NOT NULL DEFAULT 'received', -- received | handed | done | failed
30
+ kind TEXT, -- call: the part it was handed to took it into its queue; refused: it would
31
+ -- not (status 400 and over); command: answered without being queued
32
+ handed_to TEXT, -- the part holding it now, or last
33
+ handed_ref TEXT, -- the id that part knows it by
34
+ status INTEGER, -- the HTTP status it was answered with
35
+ bytes_out INTEGER,
36
+ done_at REAL,
37
+ responded_at REAL,
38
+ error TEXT,
39
+ bytes_back INTEGER, -- what came back from the part it was handed to
40
+ verified INTEGER -- 1: all that part said it would send came back and all of it reached the caller
41
+ );
42
+ CREATE INDEX IF NOT EXISTS calls_state ON calls(state);
43
+ -- A row for each stage a call passes: when it began and ended, and the part that did it. `stage_no` is its number
44
+ -- in stage_order; NULL for `handed`, the hand-off of several stages at once to a part that still does them itself.
45
+ CREATE TABLE IF NOT EXISTS call_stages (
46
+ id INTEGER PRIMARY KEY, call_id INTEGER NOT NULL, stage_no INTEGER, stage TEXT NOT NULL, owner TEXT NOT NULL,
47
+ started_at REAL NOT NULL, finished_at REAL, note TEXT
48
+ );
49
+ CREATE INDEX IF NOT EXISTS call_stages_call ON call_stages(call_id);
50
+ -- Every request that reaches the door, of any kind (operator 2026-12-03: "anything that hits the front door should
51
+ -- be on record"): when, how long until its reply was written, what was asked, the status, bytes each way, who.
52
+ CREATE TABLE IF NOT EXISTS front_door (
53
+ id INTEGER PRIMARY KEY, at REAL NOT NULL, ms REAL, method TEXT, path TEXT, status INTEGER, bytes_in INTEGER,
54
+ bytes_out INTEGER, caller TEXT, call_id INTEGER
55
+ );
56
+ CREATE INDEX IF NOT EXISTS front_door_at ON front_door(at);
57
+ -- What is kept of the routine reads once their own rows are removed: an hour, route, status and caller.
58
+ CREATE TABLE IF NOT EXISTS front_door_hours (
59
+ hour INTEGER NOT NULL, method TEXT NOT NULL, route TEXT NOT NULL, status INTEGER NOT NULL, caller TEXT NOT NULL,
60
+ requests INTEGER NOT NULL, ms REAL, max_ms REAL, bytes_out INTEGER, first_at REAL, last_at REAL,
61
+ PRIMARY KEY (hour, method, route, status, caller)
62
+ );
63
+ -- Derived, not stored.
64
+ DROP VIEW IF EXISTS front_door_routes;
65
+ CREATE VIEW front_door_routes AS
66
+ SELECT method, route, status, SUM(requests) AS requests, SUM(ms) / SUM(requests) AS avg_ms, MAX(max_ms) AS max_ms,
67
+ SUM(bytes_out) AS bytes_out, MIN(first_at) AS first_at, MAX(last_at) AS last_at
68
+ FROM (SELECT method, CASE WHEN instr(path, '?') THEN substr(path, 1, instr(path, '?') - 1) ELSE path END AS route,
69
+ status, 1 AS requests, ms, ms AS max_ms, bytes_out, at AS first_at, at AS last_at FROM front_door
70
+ UNION ALL
71
+ SELECT method, route, status, requests, ms, max_ms, bytes_out, first_at, last_at FROM front_door_hours)
72
+ GROUP BY method, route, status;
73
+ DROP VIEW IF EXISTS call_times;
74
+ CREATE VIEW call_times AS
75
+ SELECT c.id, c.kind, c.endpoint, c.model, c.state, c.status, c.verified, c.bytes_back, c.bytes_out,
76
+ c.handed_to, c.handed_ref, c.arrived_at,
77
+ h.started_at AS handed_at, c.done_at, c.responded_at,
78
+ h.started_at - c.arrived_at AS held_s, -- in the queue's own hands before the hand-off
79
+ h.finished_at - h.started_at AS handed_s, -- with the part it was handed to, until its answer began
80
+ c.responded_at - h.finished_at AS reply_s, -- the answer passed back to the caller
81
+ c.responded_at - c.arrived_at AS total_s
82
+ FROM calls c LEFT JOIN call_stages h ON h.call_id = c.id AND h.stage = 'handed';
83
+ """
84
+
85
+ _JOBS = queue.Queue()
86
+ _STARTED = []
87
+ _LOCK = threading.Lock()
88
+
89
+
90
+ def open_db(path: str = QUEUE_DB) -> sqlite3.Connection:
91
+ """The writing connection: the tables made, the operator's order written as this source has it."""
92
+ os.makedirs(os.path.dirname(path), exist_ok=True)
93
+ conn = connect_wal(path)
94
+ have = {row[1] for row in conn.execute("PRAGMA table_info(calls)")}
95
+ for column in ("bytes_back INTEGER", "verified INTEGER"): # a database made before these were kept
96
+ if have and column.split()[0] not in have:
97
+ conn.execute(f"ALTER TABLE calls ADD COLUMN {column}")
98
+ conn.executescript(SCHEMA)
99
+ with conn:
100
+ conn.execute("DELETE FROM stage_order")
101
+ conn.executemany("INSERT INTO stage_order VALUES (?,?,?,?,?)", STAGE_ORDER)
102
+ return conn
103
+
104
+
105
+ def reader(path: str = QUEUE_DB) -> sqlite3.Connection:
106
+ conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=5)
107
+ conn.row_factory = sqlite3.Row
108
+ return conn
109
+
110
+
111
+ def _write_loop(path: str) -> None:
112
+ conn = open_db(path)
113
+ while True:
114
+ fn, done = _JOBS.get()
115
+ try:
116
+ with conn:
117
+ value = fn(conn)
118
+ if done is not None:
119
+ done["value"] = value
120
+ except Exception as exc: # noqa: BLE001 — the one who asked is told; the writer goes on
121
+ if done is not None:
122
+ done["error"] = exc
123
+ else:
124
+ print(f"queue.write_failed {type(exc).__name__}: {exc}", flush=True)
125
+ finally:
126
+ if done is not None:
127
+ done["event"].set()
128
+
129
+
130
+ def write(fn, wait: bool = True, path: str = QUEUE_DB):
131
+ """Run fn(conn) on the writer thread, in a transaction. wait=True: its value is returned (its error raised)."""
132
+ with _LOCK:
133
+ if not _STARTED:
134
+ _STARTED.append(True)
135
+ threading.Thread(target=_write_loop, args=(path,), daemon=True, name="queue-writer").start()
136
+ done = {"event": threading.Event()} if wait else None
137
+ _JOBS.put((fn, done))
138
+ if not wait:
139
+ return None
140
+ done["event"].wait()
141
+ if "error" in done:
142
+ raise done["error"]
143
+ return done.get("value")
144
+
145
+
146
+ def settings(conn=None) -> dict:
147
+ """Every setting: what a person saved, else its default."""
148
+ own = conn is None
149
+ out = dict(DEFAULTS)
150
+ try:
151
+ conn = conn or reader()
152
+ out.update({row[0]: row[1] for row in conn.execute("SELECT name, value FROM settings") if row[0] in DEFAULTS})
153
+ except sqlite3.Error:
154
+ pass # no database yet: the defaults hold
155
+ finally:
156
+ if own and conn is not None:
157
+ conn.close()
158
+ return out
159
+
160
+
161
+ def save_setting(name: str, value: str, by: str) -> None:
162
+ if name not in DEFAULTS:
163
+ raise KeyError(f"{name}: not a setting ({', '.join(DEFAULTS)})")
164
+ write(lambda conn: conn.execute("INSERT INTO settings VALUES (?,?,?,?) ON CONFLICT(name) DO UPDATE SET "
165
+ "value = excluded.value, by = excluded.by, at = excluded.at",
166
+ (name, str(value), by, time.time())))
@@ -0,0 +1,19 @@
1
+ """The system layer: `hugpy-queue system install | status | uninstall` (system.py).
2
+
3
+ A system command speaks of the service, so it runs with the host's data directory (HUGPY_DATA_DIR=/var/lib/hugpy),
4
+ where the service's database is. A command started without it starts itself again with it (the constants read the
5
+ data directory once, when they are loaded)."""
6
+ from ..imports import HOST_DATA_DIR, os, sys
7
+
8
+
9
+ def main(argv=None, given=None) -> int:
10
+ """``given`` is HUGPY_DATA_DIR as this process was started with it."""
11
+ argv = sys.argv[1:] if argv is None else list(argv)
12
+ if given != HOST_DATA_DIR:
13
+ os.execve(sys.executable, [sys.executable, "-P", "-m", "hugpy_queue", "system", *argv],
14
+ dict(os.environ, HUGPY_DATA_DIR=HOST_DATA_DIR))
15
+ from .system import main as run
16
+ return run(argv)
17
+
18
+
19
+ __all__ = ["main"]
@@ -0,0 +1,170 @@
1
+ """`hugpy-queue system install | status | uninstall`: the queue as a service of the host.
2
+
3
+ install (as root) lays down, saying each step:
4
+ the group hugpy, and in it the person who ran the install
5
+ the account hugpy-queue (it runs the door), in the group hugpy
6
+ /var/lib/hugpy/queue queue.sqlite3 (the calls, their stages, the door's record, the settings): shared by
7
+ the group hugpy, so a person at a terminal reads the same record
8
+ hugpy-queue.service the front door
9
+
10
+ This installer acts only on its own unit and its own folder; it never touches another tool's units, and it does not
11
+ change where anything else sends its calls: the door listens on its own port until a person points callers at it.
12
+ """
13
+ from .. import store
14
+ from ..imports import (
15
+ DEFAULTS,
16
+ FOLDER,
17
+ HOST_DATA_DIR,
18
+ HOST_GROUP,
19
+ QUEUE_DB,
20
+ SERVICE_ACCOUNT,
21
+ SERVICE_BACKUPS,
22
+ SERVICE_UNIT,
23
+ SHARED_FOLDER_MODE,
24
+ TOOL,
25
+ argparse,
26
+ data_folder_refusal,
27
+ ensure_account,
28
+ ensure_folder,
29
+ ensure_group,
30
+ ensure_member,
31
+ os,
32
+ remove_unit,
33
+ service_interpreter,
34
+ share_folder,
35
+ share_new_files,
36
+ sqlite3,
37
+ start_unit,
38
+ system_say,
39
+ systemctl,
40
+ tool_version,
41
+ unit_state,
42
+ write_unit,
43
+ )
44
+
45
+ UNIT_TEXT = """[Unit]
46
+ Description=hugpy queue: the front door, every call and the stages it passes (hugpy-queue {version})
47
+ After=network.target local-fs.target
48
+
49
+ [Service]
50
+ Type=simple
51
+ User={account}
52
+ Group={group}
53
+ # what the service makes in its folder is the group's to read and write
54
+ UMask=0002
55
+ # every hugpy tool of this host keeps its folder here
56
+ Environment=HUGPY_DATA_DIR={data}
57
+ Environment=HOME={home}
58
+ Environment=PYTHONUNBUFFERED=1
59
+ UnsetEnvironment=PYTHONPATH
60
+ ExecStart={python} -P -m hugpy_queue serve
61
+ Restart=on-failure
62
+ RestartSec=5
63
+
64
+ [Install]
65
+ WantedBy=multi-user.target
66
+ """
67
+
68
+
69
+ def version() -> str:
70
+ return tool_version("hugpy_queue", __file__)
71
+
72
+
73
+ def unit_text(python: str) -> str:
74
+ return UNIT_TEXT.format(version=version(), account=SERVICE_ACCOUNT, group=HOST_GROUP, data=HOST_DATA_DIR,
75
+ home=FOLDER, python=python)
76
+
77
+
78
+ def install(args) -> int:
79
+ if os.geteuid() != 0:
80
+ raise SystemExit(f"{TOOL} system install changes /: run it as root (sudo {TOOL} system install)")
81
+ print(f"{TOOL} system install ({version()})", flush=True)
82
+ ensure_group(HOST_GROUP)
83
+ ensure_account(SERVICE_ACCOUNT, FOLDER, (HOST_GROUP,))
84
+ # before anything else is laid down: an install the account cannot run (a venv in a person's home) stops here
85
+ python = service_interpreter(SERVICE_ACCOUNT, "hugpy_queue")
86
+ ensure_folder(FOLDER, SHARED_FOLDER_MODE, SERVICE_ACCOUNT, HOST_GROUP)
87
+ share_folder(FOLDER, HOST_GROUP)
88
+ share_new_files(FOLDER)
89
+ person = args.operator or os.environ.get("SUDO_USER")
90
+ if person and person != "root":
91
+ ensure_member(person, HOST_GROUP)
92
+ store.open_db().close()
93
+ system_say("ok", QUEUE_DB, "the calls, their stages, the door's record and the settings")
94
+ share_folder(FOLDER, HOST_GROUP) # what this run made as root is the group's as well
95
+ write_unit(SERVICE_UNIT, unit_text(python))
96
+ if args.no_start:
97
+ system_say("skip", "start", "--no-start")
98
+ return 0
99
+ started = start_unit(SERVICE_UNIT)
100
+ found = store.settings()
101
+ print(f"\nThe queue's door is at http://{found['host']}:{found['port']} and hands its calls to the wrapper at "
102
+ f"{found['wrapper_url']}.\n {TOOL} calls the latest calls and their stages\n"
103
+ f" journalctl -u {SERVICE_UNIT} -f\n"
104
+ "Nothing else was changed: callers still go where they went until a person points them here.", flush=True)
105
+ return 0 if started in ("active", "activating") else 1
106
+
107
+
108
+ def status(_args) -> int:
109
+ print(f"{SERVICE_UNIT:<28} {unit_state(SERVICE_UNIT)}")
110
+ print(f"data {FOLDER} ({'present' if os.path.isdir(FOLDER) else f'not made yet: sudo {TOOL} system install'})")
111
+ refusal = data_folder_refusal(FOLDER)
112
+ if refusal:
113
+ print(f"access {refusal}")
114
+ return 1
115
+ if not os.path.isfile(QUEUE_DB):
116
+ return 1
117
+ found = store.settings()
118
+ print(f"door http://{found['host']}:{found['port']}")
119
+ print(f"wrapper {found['wrapper_url']}")
120
+ conn = store.reader()
121
+ try:
122
+ total, flying = conn.execute("SELECT COUNT(*), SUM(state IN ('received','handed')) FROM calls").fetchone()
123
+ print(f"calls {total} on record, {flying or 0} in flight")
124
+ except sqlite3.Error as exc:
125
+ print(f"calls {exc}")
126
+ finally:
127
+ conn.close()
128
+ return 0
129
+
130
+
131
+ def uninstall(_args) -> int:
132
+ if os.geteuid() != 0:
133
+ raise SystemExit("run as root")
134
+ if not remove_unit(SERVICE_UNIT, SERVICE_BACKUPS):
135
+ system_say("ok", SERVICE_UNIT, "not installed")
136
+ system_say("keep", FOLDER, "the record and the settings are never removed")
137
+ return 0
138
+
139
+
140
+ def set_one(args) -> int:
141
+ """`system set NAME VALUE`: save one setting; the service is restarted so that it takes hold at once."""
142
+ if os.geteuid() != 0:
143
+ raise SystemExit(f"{TOOL} system set restarts the service: run it as root (sudo {TOOL} system set NAME VALUE)")
144
+ if args.name not in DEFAULTS:
145
+ raise SystemExit(f"{args.name} is not one of: {', '.join(DEFAULTS)}")
146
+ if store.settings().get(args.name) == args.value:
147
+ system_say("keep", args.name, f"already {args.value}")
148
+ return 0
149
+ store.save_setting(args.name, args.value, by=f"{TOOL} system set")
150
+ share_folder(FOLDER, HOST_GROUP)
151
+ system_say("save", QUEUE_DB, f"{args.name} = {args.value}")
152
+ if systemctl("is-active", SERVICE_UNIT, check=False).stdout.strip() == "active":
153
+ systemctl("restart", SERVICE_UNIT)
154
+ system_say("restart", SERVICE_UNIT, "the setting takes hold now; calls in flight at the door ended with it")
155
+ return 0
156
+
157
+
158
+ def main(argv=None) -> int:
159
+ parser = argparse.ArgumentParser(prog=f"{TOOL} system")
160
+ sub = parser.add_subparsers(dest="command", required=True)
161
+ p = sub.add_parser("install", help="the account, the shared folder, the database and the door's unit; start")
162
+ p.add_argument("--operator", metavar="USER", help="a person to put in the group hugpy (default: whoever ran this with sudo)")
163
+ p.add_argument("--no-start", action="store_true")
164
+ sub.add_parser("status")
165
+ sub.add_parser("uninstall", help="stop and remove the unit (the record and the settings are kept)")
166
+ one = sub.add_parser("set", help="save one setting (host, port, wrapper_url); the service restarts so it takes hold")
167
+ one.add_argument("name")
168
+ one.add_argument("value")
169
+ args = parser.parse_args(argv)
170
+ return {"install": install, "status": status, "uninstall": uninstall, "set": set_one}[args.command](args)