@vibelord/lanes 1.7.3 → 1.7.5
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.
- package/README.md +9 -0
- package/package.json +1 -1
- package/payload/lanes/VERSION +1 -1
- package/payload/lanes/bin/lanes +128 -24
- package/payload/lanes/bin/lanes-site-serve +15 -0
- package/payload/lanes/bin-rs/BINARIES.json +5 -0
- package/payload/lanes/container/lane-mcp +108 -5
- package/payload/lanes/container/lane_core.py +116 -0
- package/payload/lanes/container/throttle-pulse +159 -14
- package/payload/lanes/docs/ARCHITECTURE.md +132 -13
- package/payload/lanes/docs/DESIGN.md +10 -8
- package/payload/lanes/docs/INSTALL.md +1 -1
- package/payload/lanes/docs/RUNBOOK.md +436 -8
- package/payload/lanes/docs/USERGUIDE.md +82 -9
- package/payload/lanes/install/host-install.sh +35 -4
- package/payload/lanes/libexec/adopt.py +364 -0
- package/payload/lanes/libexec/attach.py +35 -5
- package/payload/lanes/libexec/cutover.py +656 -0
- package/payload/lanes/libexec/docsd.py +12 -8
- package/payload/lanes/libexec/doctor_lanes2.py +284 -0
- package/payload/lanes/libexec/economy_poll.py +87 -2
- package/payload/lanes/libexec/gc_unregistered.py +407 -0
- package/payload/lanes/libexec/lanes_lib.py +474 -2
- package/payload/lanes/libexec/native.sh +38 -0
- package/payload/lanes/libexec/native_bin.py +670 -0
- package/payload/lanes/libexec/session_actions.py +85 -7
- package/payload/lanes/libexec/shadow.py +1311 -0
- package/payload/lanes/libexec/sidebar.py +252 -30
- package/payload/lanes/libexec/sidebar_status.py +373 -25
- package/payload/lanes/libexec/statusd.py +67 -3
- package/payload/lanes/libexec/tokens.py +99 -131
- package/payload/lanes/libexec/tokens.sh +1 -1
- package/payload/lanes/libexec/update.py +78 -8
- package/payload/lanes/libexec/users.py +282 -0
- package/payload/lanes/site/README.md +9 -0
- package/payload/lanes/site/conformance.py +280 -0
- package/payload/lanes/site/protocol.py +368 -0
- package/payload/lanes/site/server.py +314 -0
- package/payload/lanes/systemd/lanes-gc.service +1 -1
- package/payload/lanes/systemd/lanes-gc.timer +14 -3
- package/payload/lanes/tokens/README.md +156 -0
- package/payload/lanes/tokens/generate.py +930 -0
- package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
- package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
- package/payload/lanes/tokens/tokens.v1.json +763 -0
- package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
- package/payload/lanes/web/Caddyfile +11 -0
- package/payload/lanes/web/README.md +253 -4
- package/payload/lanes/web/directory.css +95 -0
- package/payload/lanes/web/directory.js +951 -0
- package/payload/lanes/web/generated/README.md +107 -0
- package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
- package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
- package/payload/lanes/web/inbox.js +1140 -0
- package/payload/lanes/web/mobile.js +35 -45
- package/payload/lanes/web/tokens.css +137 -0
- package/payload/manifest.json +7 -4
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""`lanes gc --unregistered [--write] [--board B]`: end the unregistered tmux sessions in which nothing runs.
|
|
3
|
+
Python 3 stdlib.
|
|
4
|
+
|
|
5
|
+
Ending a lane stays a person's call (lanes/docs/ARCHITECTURE.md "What stays with a person"). This sweep is the
|
|
6
|
+
operator's standing instruction for one site ("unless they are running live"), and it is opt-in: site.conf
|
|
7
|
+
`LANES_GC_UNREGISTERED=1` (default off) makes the daily `lanes gc` (lanes-gc.timer, at midnight) run it in write mode
|
|
8
|
+
after its other tasks; `LANES_GC_IDLE_S` (seconds, default 21600 = 6 h, at least 3600) is how long a session's last
|
|
9
|
+
output must lie back. A raw site.conf line naming a LANES_GC_ key that lanes_lib.SITE_LINE refuses (a trailing comment,
|
|
10
|
+
quotes, a space) refuses the sweep — nothing is ended, `lanes doctor` names the line — rather than being read as unset.
|
|
11
|
+
It reads only status.json's `unregistered` rows (statusd's tmux sessions no registry declares — unregistered, including
|
|
12
|
+
a lane a person unregistered while it ran), so a registered lane is never one.
|
|
13
|
+
|
|
14
|
+
The rule (decided in the review of PR #750): a session is ended only on POSITIVE evidence that nothing runs in it —
|
|
15
|
+
1. its agent's status is `shell` (the harness ended into its shell), or it has no agent and its pane's command is a
|
|
16
|
+
bare shell (agent_state.SHELL_COMMANDS, normalised as agent_state does), or its pane is dead; and
|
|
17
|
+
2. just before the close, a live probe of every pane of the session (every window: `list-panes -s`, through
|
|
18
|
+
L.tmux_probe, the typed route close_session asks) shows each pane dead, or a bare shell with no process under it
|
|
19
|
+
(agent_state.child_liveness over the container's /proc: a harness started as `bash -c '<harness> …'` leaves the
|
|
20
|
+
shell as tmux's foreground command, so the command alone is no evidence).
|
|
21
|
+
Every other agent — errored, done, needs_input, needs_approval, working, idle, or a status this sweep does not know —
|
|
22
|
+
keeps the session: every harness prompt survives, as Lanes' own "Needs you" and "Done stays until you open the lane".
|
|
23
|
+
|
|
24
|
+
Each session gets one line, `<verdict>: <reason> — <id> (<container> <socket>/<session>)`. A session is kept when ANY
|
|
25
|
+
of these holds, checked in this order (the first one found is the reason):
|
|
26
|
+
|
|
27
|
+
keep: not closable (…) no closable tmux row (a retired legacy shell, a row marked unclosable)
|
|
28
|
+
keep: behind guest:<alias> (…) its container is reached through a guest: the guest's own Lanes sweeps it
|
|
29
|
+
keep: not typed here (…) no local write route: reached only through a tmux_probe hook, or not at all
|
|
30
|
+
keep: unobserved (…) status.json older than STATUS_FRESH_S, no row, a `stale` row, state
|
|
31
|
+
`unknown`, a row without its client counts or (no agent) its pane command:
|
|
32
|
+
no evidence is never "idle"
|
|
33
|
+
keep: attached a terminal is attached to it (or to a session viewing it)
|
|
34
|
+
keep: viewers N N sessions view it (a Studio browser's grouped `view-…` session)
|
|
35
|
+
keep: agent <status> an agent whose status is not `shell`: errored, done, needs_input,
|
|
36
|
+
needs_approval, working, idle, … (a harness prompt is live)
|
|
37
|
+
keep: runs <command> no agent, and the pane's command is no bare shell (vim, python3, ssh, tail)
|
|
38
|
+
keep: active <age> ago state `active`, or output newer than LANES_GC_IDLE_S
|
|
39
|
+
keep: state <state> any state but `quiet` or `dead`
|
|
40
|
+
keep: no output time the row carries no `activity` (the newest window_activity): fail closed
|
|
41
|
+
keep: runs <command> the pane probe: another pane runs it (a Claude in window 1 behind a bash)
|
|
42
|
+
keep: runs a process under <shell> the pane probe: a live bare-shell pane has a child process
|
|
43
|
+
keep: panes not checked (…) the pane probe did not answer, listed no pane or a line it cannot read, or a
|
|
44
|
+
pane's children could not be read
|
|
45
|
+
reap: idle <age>, <what>, no client everything else (<what>: `agent shell`, `pane dead` or `no agent`)
|
|
46
|
+
|
|
47
|
+
Without --write nothing is ended; the dry run still probes each `reap` candidate's panes (read-only), so it says what a
|
|
48
|
+
write would do. With --write each candidate is read again from a fresh status.json, judged again, its panes probed,
|
|
49
|
+
and ended through session_actions.close_idle_session. Under the registry lock it rechecks cached eligibility and
|
|
50
|
+
every pane's process evidence. The final tmux predicate requires the exact identity, no client or session group,
|
|
51
|
+
and positive, old activity on every window. GC never kills a viewer to make the session eligible. Its line becomes `ended: …` (the
|
|
52
|
+
journal line: under the timer stdout is `journalctl --user -u lanes-gc.service`) or `not ended: <why> — …`; a write
|
|
53
|
+
records the run in $LANES_STATE/gc-unregistered.json (DM-LANES-GC-UNREGISTERED: `by` is `timer` when systemd started
|
|
54
|
+
the process — it sets INVOCATION_ID for every unit it runs — else `hand`), which `lanes doctor` reads. Exit 0 whatever
|
|
55
|
+
was found.
|
|
56
|
+
"""
|
|
57
|
+
import json
|
|
58
|
+
import math
|
|
59
|
+
import os
|
|
60
|
+
import time
|
|
61
|
+
from pathlib import Path
|
|
62
|
+
|
|
63
|
+
import agent_state as AS
|
|
64
|
+
import lanes_lib as L
|
|
65
|
+
|
|
66
|
+
SWITCH = 'LANES_GC_UNREGISTERED' # site.conf: 1 = the daily `lanes gc` runs the sweep with --write; else off
|
|
67
|
+
IDLE_KEY = 'LANES_GC_IDLE_S' # site.conf: seconds since the last output before a session may be ended
|
|
68
|
+
KEY_PREFIX = 'LANES_GC_' # a raw site.conf line naming such a key that SITE_LINE refuses refuses the sweep
|
|
69
|
+
IDLE_DEFAULT = 21600 # 6 h
|
|
70
|
+
IDLE_MIN = 3600 # a smaller value is refused: the sweep then ends nothing
|
|
71
|
+
STATUS_FRESH_S = 30 # status.json older than this (statusd rewrites it every 15 s): nothing is observed
|
|
72
|
+
STATE_FILE = 'gc-unregistered.json' # under $LANES_STATE: the last write run
|
|
73
|
+
REAPABLE_AGENT = ('shell',) # agent_state.STATUSES: the one word that says the harness ended into its shell
|
|
74
|
+
REAPABLE_STATE = ('quiet', 'dead') # statusd's `state` words a session may be ended in (never `active`)
|
|
75
|
+
# The pane probe: every pane of the session (`-s`: all its windows), its foreground command, whether it is dead and its
|
|
76
|
+
# root pid (the container's pid: its children are read in the container's /proc).
|
|
77
|
+
PANES_FORMAT = '#{pane_current_command}\t#{pane_dead}\t#{pane_pid}'
|
|
78
|
+
PROBE_TIMEOUT = 5 # seconds, as close_session's own tmux questions
|
|
79
|
+
SHOWN_MAX = 160 # characters of a refused site.conf line a message repeats
|
|
80
|
+
USAGE = 'usage: lanes gc [--unregistered [--write] [--board B]]'
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def is_count(value):
|
|
84
|
+
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def ago(seconds):
|
|
88
|
+
"""A coarse age: `45s`, `12m`, `7h`, `3d` (days from two on)."""
|
|
89
|
+
seconds = max(0, int(seconds))
|
|
90
|
+
if seconds >= 2 * 86400:
|
|
91
|
+
return f'{seconds // 86400}d'
|
|
92
|
+
if seconds >= 3600:
|
|
93
|
+
return f'{seconds // 3600}h'
|
|
94
|
+
if seconds >= 60:
|
|
95
|
+
return f'{seconds // 60}m'
|
|
96
|
+
return f'{seconds}s'
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def span(seconds):
|
|
100
|
+
"""An exact setting: `6h`, `1h30m`, `90s`."""
|
|
101
|
+
hours, rest = divmod(int(seconds), 3600)
|
|
102
|
+
minutes, secs = divmod(rest, 60)
|
|
103
|
+
if secs:
|
|
104
|
+
return f'{int(seconds)}s'
|
|
105
|
+
return (f'{hours}h' if hours else '') + (f'{minutes}m' if minutes else '') or '0s'
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def switch_text(settings):
|
|
109
|
+
"""`on (LANES_GC_UNREGISTERED=1)`, `off (LANES_GC_UNREGISTERED unset)` or `off (LANES_GC_UNREGISTERED=<value>)`."""
|
|
110
|
+
value = settings.get(SWITCH)
|
|
111
|
+
if value == '1':
|
|
112
|
+
return f'on ({SWITCH}=1)'
|
|
113
|
+
return f'off ({SWITCH} unset)' if value is None else f'off ({SWITCH}={value})'
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def printable(text):
|
|
117
|
+
return ''.join(char if char.isprintable() else '?' for char in str(text))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def read_site(home=None):
|
|
121
|
+
"""(settings, refused): site.conf's LANES_* facts read as lanes_lib.site_conf reads them (SITE_LINE; the last line
|
|
122
|
+
naming a key wins), and the raw lines that name a LANES_GC_ key outside a comment (before any `#`) but SITE_LINE
|
|
123
|
+
refuses — a trailing comment, quotes, a trailing space, a leading blank, an `export`. Such a line is REFUSED, never
|
|
124
|
+
read as unset (that would leave the switch silently off, or the floor silently IDLE_DEFAULT): the sweep ends nothing
|
|
125
|
+
and `lanes doctor` names it, as bin/lanes fleet_dashboard_url judges its own key's raw lines. A comment line (`#`
|
|
126
|
+
first) names nothing, and neither does another key's line whose comment mentions one. ({}, []) without a readable
|
|
127
|
+
file."""
|
|
128
|
+
try:
|
|
129
|
+
text = ((Path(home) if home is not None else Path.home()) / L.SITE_CONF).read_text()
|
|
130
|
+
except (OSError, UnicodeDecodeError, KeyError, RuntimeError):
|
|
131
|
+
return {}, []
|
|
132
|
+
lines = text.splitlines()
|
|
133
|
+
settings = dict(match.groups() for match in map(L.SITE_LINE.match, lines) if match)
|
|
134
|
+
refused = [line for line in lines if KEY_PREFIX in line.split('#', 1)[0] and not L.SITE_LINE.match(line)]
|
|
135
|
+
return settings, refused
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def refusal(refused):
|
|
139
|
+
"""The words for read_site's refused lines: the first one, quoted, and how many more."""
|
|
140
|
+
first = printable(refused[0])
|
|
141
|
+
first = first if len(first) <= SHOWN_MAX else first[:SHOWN_MAX - 1] + '…'
|
|
142
|
+
more = f' (and {len(refused) - 1} more)' if len(refused) > 1 else ''
|
|
143
|
+
return (f'site.conf line `{first}`{more} is refused: a LANES_GC_ line is KEY=VALUE alone '
|
|
144
|
+
'(no comment, quote or space after the value)')
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def invoker(environ=None):
|
|
148
|
+
"""The run record's `by`: `timer` when systemd started this process (it sets INVOCATION_ID for every unit it runs —
|
|
149
|
+
lanes-gc.service, under lanes-gc.timer), else `hand`."""
|
|
150
|
+
return 'timer' if (os.environ if environ is None else environ).get('INVOCATION_ID') else 'hand'
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def idle_floor(settings, refused=()):
|
|
154
|
+
"""(seconds, None) from site.conf's LANES_GC_IDLE_S (default IDLE_DEFAULT), or (None, why): a LANES_GC_ line
|
|
155
|
+
SITE_LINE refused (`refused`, read_site's), or a value that is not a whole number of seconds of at least IDLE_MIN."""
|
|
156
|
+
if refused:
|
|
157
|
+
return None, refusal(refused)
|
|
158
|
+
value = settings.get(IDLE_KEY)
|
|
159
|
+
if value is None:
|
|
160
|
+
return IDLE_DEFAULT, None
|
|
161
|
+
if not value.isdigit() or int(value) < IDLE_MIN:
|
|
162
|
+
return None, f'{IDLE_KEY}={value} is not a whole number of seconds ≥ {IDLE_MIN}'
|
|
163
|
+
return int(value), None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def who(entry):
|
|
167
|
+
binding = entry.get('tmux') if isinstance(entry.get('tmux'), dict) else {}
|
|
168
|
+
return printable(f"{entry.get('id')} ({entry.get('container')} {binding.get('socket')}/{binding.get('session')})")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def bare_shell(command):
|
|
172
|
+
"""Whether a pane's foreground command is a bare shell, by agent_state's own test (`_shell_foreground`: a login
|
|
173
|
+
shell's `-bash` and a path normalised, SHELL_COMMANDS); anything else, an empty or absent command included, is not."""
|
|
174
|
+
return isinstance(command, str) and AS._shell_foreground({'pane_current_command': command})
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def verdict(entry, row, info, now, floor, status_age):
|
|
178
|
+
"""('keep' | 'reap', reason) for one `unregistered` entry: `row` its status.json `lanes` row (None: none), `info`
|
|
179
|
+
its container's containers.json record, `status_age` the seconds since statusd wrote status.json. See the module
|
|
180
|
+
docstring for the order; anything this function cannot read is a keep."""
|
|
181
|
+
if entry.get('holder') != 'tmux' or entry.get('legacy') or not entry.get('closable'):
|
|
182
|
+
return 'keep', 'not closable (no tmux session the sidebar could close)'
|
|
183
|
+
binding = entry.get('tmux') if isinstance(entry.get('tmux'), dict) else {}
|
|
184
|
+
route, why = L.write_route(entry.get('container'), info, binding.get('socket'))
|
|
185
|
+
if route is None:
|
|
186
|
+
return 'keep', f'not typed here ({why})'
|
|
187
|
+
if route.startswith(L.GUEST_PREFIX):
|
|
188
|
+
return 'keep', f'behind {route} (its guest sweeps)'
|
|
189
|
+
if route != L.TRANSPORT_LOCAL:
|
|
190
|
+
return 'keep', f'not typed here ({route}: no local write route; its own host sweeps)'
|
|
191
|
+
if not math.isfinite(status_age) or status_age < 0:
|
|
192
|
+
return 'keep', 'unobserved (invalid status timestamp)'
|
|
193
|
+
if status_age > STATUS_FRESH_S:
|
|
194
|
+
return 'keep', f'unobserved (status.json {ago(status_age)} old: is lanes-statusd running?)'
|
|
195
|
+
if not isinstance(row, dict):
|
|
196
|
+
return 'keep', 'unobserved (no status row)'
|
|
197
|
+
if row.get('stale'):
|
|
198
|
+
return 'keep', 'unobserved (stale: its tmux server did not answer)'
|
|
199
|
+
if row.get('state') in (None, 'unknown'):
|
|
200
|
+
return 'keep', 'unobserved (unknown)'
|
|
201
|
+
clients, viewers = row.get('attached'), row.get('viewers', 0)
|
|
202
|
+
if not is_count(clients) or not is_count(viewers):
|
|
203
|
+
return 'keep', 'unobserved (no client count)'
|
|
204
|
+
if row['attached'] > 0:
|
|
205
|
+
return 'keep', 'attached'
|
|
206
|
+
if viewers > 0:
|
|
207
|
+
return 'keep', f'viewers {viewers}'
|
|
208
|
+
agent, state = row.get('agent'), row.get('state')
|
|
209
|
+
status = agent.get('status') if isinstance(agent, dict) else None
|
|
210
|
+
if agent is not None and status not in REAPABLE_AGENT:
|
|
211
|
+
return 'keep', f'agent {printable(status) if isinstance(status, str) else "?"}'
|
|
212
|
+
command = row.get('command')
|
|
213
|
+
if agent is None and state != 'dead':
|
|
214
|
+
if not isinstance(command, str) or not command:
|
|
215
|
+
return 'keep', 'unobserved (no pane command)'
|
|
216
|
+
if not bare_shell(command):
|
|
217
|
+
return 'keep', f'runs {printable(command)}'
|
|
218
|
+
activity = row.get('activity')
|
|
219
|
+
known = (isinstance(activity, (int, float)) and not isinstance(activity, bool)
|
|
220
|
+
and math.isfinite(activity) and activity > 0)
|
|
221
|
+
if row.get('state') == 'active':
|
|
222
|
+
return 'keep', f'active {ago(now - activity)} ago' if known else 'active now'
|
|
223
|
+
if state not in REAPABLE_STATE:
|
|
224
|
+
return 'keep', f'state {printable(state)}'
|
|
225
|
+
if not known:
|
|
226
|
+
return 'keep', 'no output time'
|
|
227
|
+
idle = now - activity
|
|
228
|
+
if idle < floor:
|
|
229
|
+
return 'keep', f'active {ago(idle)} ago'
|
|
230
|
+
what = f'agent {status}' if agent is not None else ('pane dead' if state == 'dead' else 'no agent')
|
|
231
|
+
return 'reap', f'idle {ago(idle)}, {what}, no client'
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def nothing_runs(entry, info):
|
|
235
|
+
"""The second half of the rule, asked live -> (True, None) when every pane of `entry`'s session (`list-panes -s`:
|
|
236
|
+
every window) is dead, or a bare shell (bare_shell) with no process under it (agent_state.child_liveness over the
|
|
237
|
+
container's /proc, read from this host: False); else (False, why) — `runs <command>`, `runs a process under
|
|
238
|
+
<shell>`, or `panes not checked (…)` for a probe that did not answer `ok`, listed no pane or a line it cannot read,
|
|
239
|
+
or a child read that failed. One read-only tmux question through L.tmux_probe (the typed route close_session asks),
|
|
240
|
+
the session named `=<name>:` as there (exact; a trailing `;` cannot end the tmux command). `info` is the container's
|
|
241
|
+
containers.json record."""
|
|
242
|
+
binding = entry.get('tmux') if isinstance(entry.get('tmux'), dict) else {}
|
|
243
|
+
outcome, listing = L.tmux_probe(info, binding.get('socket'),
|
|
244
|
+
['list-panes', '-s', '-t', '=' + str(binding.get('session')) + ':',
|
|
245
|
+
'-F', PANES_FORMAT], PROBE_TIMEOUT)
|
|
246
|
+
if outcome != 'ok':
|
|
247
|
+
return False, f'panes not checked ({printable(outcome)})'
|
|
248
|
+
panes = [line.split('\t') for line in (listing or '').splitlines() if line]
|
|
249
|
+
if not panes:
|
|
250
|
+
return False, 'panes not checked (none listed)'
|
|
251
|
+
shells = {}
|
|
252
|
+
for fields in panes:
|
|
253
|
+
if len(fields) != 3 or fields[1] not in ('0', '1'):
|
|
254
|
+
return False, 'panes not checked (a line it cannot read)'
|
|
255
|
+
command, dead, pid = fields
|
|
256
|
+
if dead == '1':
|
|
257
|
+
continue
|
|
258
|
+
if not bare_shell(command):
|
|
259
|
+
return False, f'runs {printable(command) or "?"}'
|
|
260
|
+
if not pid.isdigit() or int(pid) <= 0:
|
|
261
|
+
return False, 'panes not checked (no pane pid)'
|
|
262
|
+
shells[int(pid)] = command
|
|
263
|
+
if shells:
|
|
264
|
+
live = AS.child_liveness(Path(L.proc_root()) / str(info.get('pid')) / 'root' / 'proc', sorted(shells))
|
|
265
|
+
for pid, command in sorted(shells.items()):
|
|
266
|
+
if live.get(pid) is None:
|
|
267
|
+
return False, f'panes not checked (what runs under pane pid {pid} could not be read)'
|
|
268
|
+
if live[pid]:
|
|
269
|
+
return False, f'runs a process under {printable(command)}'
|
|
270
|
+
return True, None
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def listed(status, board=None):
|
|
274
|
+
"""[(board, entry)] of status.json's `unregistered` rows, each session once (a session no board could claim is
|
|
275
|
+
listed under every owner of its socket, with one id), in board order; only `board`'s when given. The board is the
|
|
276
|
+
one close_session is asked under: the entry's own `workspace` when that board lists it, else the first that does."""
|
|
277
|
+
owners, order = {}, []
|
|
278
|
+
groups = status.get('unregistered') if isinstance(status.get('unregistered'), dict) else {}
|
|
279
|
+
for name in sorted(groups):
|
|
280
|
+
if board is not None and name != board:
|
|
281
|
+
continue
|
|
282
|
+
for entry in groups[name] or ():
|
|
283
|
+
if isinstance(entry, dict) and isinstance(entry.get('id'), str) and entry['id']:
|
|
284
|
+
if entry['id'] not in owners:
|
|
285
|
+
owners[entry['id']] = []
|
|
286
|
+
order.append(entry)
|
|
287
|
+
owners[entry['id']].append(name)
|
|
288
|
+
return [(entry['workspace'] if entry.get('workspace') in owners[entry['id']] else owners[entry['id']][0], entry)
|
|
289
|
+
for entry in order]
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def judge(status, entry, containers, floor, now):
|
|
293
|
+
"""verdict() for `entry` as `status` (a whole status.json) shows it."""
|
|
294
|
+
rows = status.get('lanes') if isinstance(status.get('lanes'), dict) else {}
|
|
295
|
+
updated = status.get('updated_at')
|
|
296
|
+
age = now - updated if isinstance(updated, (int, float)) and not isinstance(updated, bool) else float('inf')
|
|
297
|
+
return verdict(entry, rows.get(entry['id']), containers.get(entry.get('container')) or {}, now, floor, age)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def read_status():
|
|
301
|
+
status = L.read_json(L.STATE / 'status.json')
|
|
302
|
+
return status if isinstance(status, dict) else {}
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def sweep(write, board=None, by=None, out=print):
|
|
306
|
+
"""One pass: a line per session, then the summary; without `write` each `reap` candidate's panes are probed
|
|
307
|
+
(nothing_runs) so the line says what a write would do; with `write`, each candidate is ended (end) and the run
|
|
308
|
+
recorded, `by` (default invoker()). -> 0. Raises LanesError for a refused setting or an unknown board."""
|
|
309
|
+
settings, refused = read_site()
|
|
310
|
+
floor, problem = idle_floor(settings, refused)
|
|
311
|
+
if problem:
|
|
312
|
+
raise L.LanesError(f'gc unregistered: {problem}; nothing was ended')
|
|
313
|
+
status = read_status()
|
|
314
|
+
if board is not None:
|
|
315
|
+
registry = L.read_json(L.STATE / 'registry.json') or {}
|
|
316
|
+
known = {w.get('id') for w in registry.get('workspaces') or () if isinstance(w, dict)}
|
|
317
|
+
if board not in known | set(status.get('unregistered') or {}):
|
|
318
|
+
raise L.LanesError(f'Unknown workspace: {board}')
|
|
319
|
+
containers = L.read_json(L.STATE / 'containers.json') or {}
|
|
320
|
+
out(f'gc unregistered: {switch_text(settings)}, idle ≥ {span(floor)}'
|
|
321
|
+
+ ('' if write else ' — dry run: --write ends each reap'))
|
|
322
|
+
counts = {'ended': 0, 'not ended': 0, 'reap': 0, 'keep': 0}
|
|
323
|
+
for name, entry in listed(status, board):
|
|
324
|
+
said, reason = judge(status, entry, containers, floor, time.time())
|
|
325
|
+
if said == 'reap' and write:
|
|
326
|
+
said, reason = end(name, entry, containers, floor)
|
|
327
|
+
elif said == 'reap':
|
|
328
|
+
quiet, why = nothing_runs(entry, containers.get(entry.get('container')) or {})
|
|
329
|
+
if not quiet:
|
|
330
|
+
said, reason = 'keep', why
|
|
331
|
+
counts[said] += 1
|
|
332
|
+
out(f'{said}: {reason} — {who(entry)}')
|
|
333
|
+
if write:
|
|
334
|
+
record = {'v': 1, 'at': int(time.time()), 'by': invoker() if by is None else by, 'idle_s': floor,
|
|
335
|
+
'ended': counts['ended'],
|
|
336
|
+
'not_ended': counts['not ended'], 'kept': counts['keep']}
|
|
337
|
+
L.atomic_write(L.STATE / STATE_FILE, json.dumps(record) + '\n')
|
|
338
|
+
out(f"gc unregistered: ended {counts['ended']}, not ended {counts['not ended']}, kept {counts['keep']}")
|
|
339
|
+
else:
|
|
340
|
+
out(f"gc unregistered: {counts['reap']} to end, {counts['keep']} kept — "
|
|
341
|
+
'lanes gc --unregistered --write ends them')
|
|
342
|
+
return 0
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def end(board, entry, containers, floor):
|
|
346
|
+
"""End one session judged `reap`: read status.json again and judge its row again (a person may have attached since
|
|
347
|
+
the listing), probe every pane (nothing_runs), then the guarded session_actions.close_idle_session
|
|
348
|
+
(cached policy and pane evidence under lock; live identity/client/group/activity condition) -> (verdict, reason)."""
|
|
349
|
+
import session_actions
|
|
350
|
+
status = read_status()
|
|
351
|
+
fresh = next((e for b, e in listed(status, board) if e['id'] == entry['id']), None)
|
|
352
|
+
if (fresh is None or session_actions.session_key(fresh) != session_actions.session_key(entry)
|
|
353
|
+
or fresh.get('identity') != entry.get('identity')):
|
|
354
|
+
return 'keep', 'gone or changed since the listing'
|
|
355
|
+
said, reason = judge(status, fresh, containers, floor, time.time())
|
|
356
|
+
if said != 'reap':
|
|
357
|
+
return 'keep', f'{reason} (since the listing)'
|
|
358
|
+
quiet, why = nothing_runs(fresh, containers.get(fresh.get('container')) or {})
|
|
359
|
+
if not quiet:
|
|
360
|
+
return 'keep', why
|
|
361
|
+
try:
|
|
362
|
+
session_actions.close_idle_session(board, fresh, idle_s=floor)
|
|
363
|
+
except (L.LanesError, OSError, ValueError) as error:
|
|
364
|
+
return 'not ended', str(error) or type(error).__name__
|
|
365
|
+
return 'ended', reason
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def daily(out=print):
|
|
369
|
+
"""What the plain `lanes gc` (lanes-gc.timer) runs after its other tasks: nothing, silently, unless site.conf has
|
|
370
|
+
LANES_GC_UNREGISTERED=1; then the sweep with --write. A LANES_GC_ line SITE_LINE refuses (whatever the switch says)
|
|
371
|
+
or a refused LANES_GC_IDLE_S is one line, nothing ended."""
|
|
372
|
+
settings, refused = read_site()
|
|
373
|
+
if refused:
|
|
374
|
+
out(f'gc unregistered: {refusal(refused)}; nothing was ended')
|
|
375
|
+
return 0
|
|
376
|
+
if settings.get(SWITCH) != '1':
|
|
377
|
+
return 0
|
|
378
|
+
try:
|
|
379
|
+
return sweep(True, out=out)
|
|
380
|
+
except L.LanesError as error:
|
|
381
|
+
out(str(error))
|
|
382
|
+
return 0
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def doctor_line(state=None, settings=None, refused=None):
|
|
386
|
+
"""`lanes doctor`'s one line -> (mark, text): an information line ('') with the switch, the idle floor and the last
|
|
387
|
+
write run (gc-unregistered.json; `(by hand)` unless the timer ran it); ⚠ naming a LANES_GC_ line SITE_LINE refuses
|
|
388
|
+
(whatever the switch says), or when the sweep is on but LANES_GC_IDLE_S is refused. `settings`/`refused` default to
|
|
389
|
+
read_site()'s."""
|
|
390
|
+
if settings is None:
|
|
391
|
+
settings, read = read_site()
|
|
392
|
+
refused = read if refused is None else refused
|
|
393
|
+
refused = refused or []
|
|
394
|
+
record = L.read_json((L.STATE if state is None else state) / STATE_FILE)
|
|
395
|
+
last = ''
|
|
396
|
+
if isinstance(record, dict) and is_count(record.get('at')):
|
|
397
|
+
when = time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(record['at']))
|
|
398
|
+
ended = record['ended'] if is_count(record.get('ended')) else '?'
|
|
399
|
+
last = f", last sweep {when}{' (by hand)' if record.get('by') == 'hand' else ''}: ended {ended}"
|
|
400
|
+
if refused:
|
|
401
|
+
return '⚠', f'gc unregistered: {refusal(refused)}: the sweep ends nothing'
|
|
402
|
+
if settings.get(SWITCH) != '1':
|
|
403
|
+
return '', f'gc unregistered: {switch_text(settings)}{last}'
|
|
404
|
+
floor, problem = idle_floor(settings)
|
|
405
|
+
if problem:
|
|
406
|
+
return '⚠', f'gc unregistered: on, but {problem}: the daily sweep ends nothing'
|
|
407
|
+
return '', f"gc unregistered: on, idle ≥ {span(floor)}{last or ', no sweep yet (lanes-gc.timer, at midnight)'}"
|