@simplexai/localmodels-linux-x64 0.1.0-dev.36 → 0.1.0-dev.38
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/bootstrap.identity +1 -1
- package/bootstrap.sha256 +132 -110
- package/kit.py +1 -0
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +9 -3
- package/modules/localmodels/bifrost_checks.py +9 -6
- package/modules/localmodels/bifrost_config.py +203 -0
- package/modules/localmodels/bifrost_datasheet.py +12 -2
- package/modules/localmodels/budget.py +13 -2
- package/modules/localmodels/catalog.json +137 -2
- package/modules/localmodels/catalog.py +70 -321
- package/modules/localmodels/catalog_add.py +2 -8
- package/modules/localmodels/catalog_recipes.py +352 -0
- package/modules/localmodels/cli_parser.py +4 -1
- package/modules/localmodels/console.py +5 -4
- package/modules/localmodels/contracts.py +13 -3
- package/modules/localmodels/debug_cli.py +158 -0
- package/modules/localmodels/debug_mode.py +727 -0
- package/modules/localmodels/debug_stub_server.py +192 -0
- package/modules/localmodels/decode_calibration.json +1 -1
- package/modules/localmodels/decode_calibration.py +34 -17
- package/modules/localmodels/gateway.py +21 -155
- package/modules/localmodels/gateway_accept.py +201 -0
- package/modules/localmodels/gateway_bifrost.py +30 -193
- package/modules/localmodels/gateway_cli.py +15 -6
- package/modules/localmodels/gateway_foundations.py +2 -4
- package/modules/localmodels/gateway_probe.py +0 -1
- package/modules/localmodels/gateway_server.py +2 -3
- package/modules/localmodels/gpu_specs.py +12 -0
- package/modules/localmodels/guard.py +2 -7
- package/modules/localmodels/harness.py +16 -129
- package/modules/localmodels/harness_cleanup.py +135 -0
- package/modules/localmodels/harness_gateway.py +16 -14
- package/modules/localmodels/harness_probe.py +12 -4
- package/modules/localmodels/hosts.py +25 -2
- package/modules/localmodels/http_local.py +59 -0
- package/modules/localmodels/install.py +23 -8
- package/modules/localmodels/library_gateway.py +20 -9
- package/modules/localmodels/library_jobs.py +125 -28
- package/modules/localmodels/library_model.py +10 -0
- package/modules/localmodels/library_pricing.py +29 -22
- package/modules/localmodels/library_serve.py +17 -1
- package/modules/localmodels/library_state.py +15 -2
- package/modules/localmodels/library_status.py +30 -0
- package/modules/localmodels/llm_rank.py +185 -39
- package/modules/localmodels/probe.py +108 -174
- package/modules/localmodels/process_identity.py +120 -154
- package/modules/localmodels/process_windows.py +86 -0
- package/modules/localmodels/recommend.py +6 -3
- package/modules/localmodels/recommend_cli.py +14 -6
- package/modules/localmodels/remote_ops.py +65 -0
- package/modules/localmodels/remote_ops_service.py +14 -2
- package/modules/localmodels/runtime_args.py +10 -3
- package/modules/localmodels/runtime_auth.py +5 -9
- package/modules/localmodels/runtime_cli.py +128 -129
- package/modules/localmodels/runtime_discovery.py +84 -0
- package/modules/localmodels/runtime_install.py +101 -0
- package/modules/localmodels/runtime_releases.py +302 -0
- package/modules/localmodels/search_server.py +5 -1
- package/modules/localmodels/service_stop.py +8 -108
- package/modules/localmodels/service_upgrade.py +394 -63
- package/modules/localmodels/services_cli.py +24 -14
- package/modules/localmodels/setup_inspection.py +97 -9
- package/modules/localmodels/setup_text.py +7 -0
- package/modules/localmodels/sizecalc.py +0 -1
- package/modules/localmodels/stack.py +45 -235
- package/modules/localmodels/stack_arena.py +732 -0
- package/modules/localmodels/stack_args.py +21 -12
- package/modules/localmodels/stack_auto.py +384 -3
- package/modules/localmodels/stack_aux_gpu.py +4 -3
- package/modules/localmodels/stack_capacity.py +138 -0
- package/modules/localmodels/stack_cleanup.py +9 -4
- package/modules/localmodels/stack_cli.py +288 -0
- package/modules/localmodels/stack_compose.py +63 -30
- package/modules/localmodels/stack_console.py +9 -6
- package/modules/localmodels/stack_hardware.py +95 -265
- package/modules/localmodels/stack_hardware_text.py +263 -0
- package/modules/localmodels/stack_journal.py +3 -9
- package/modules/localmodels/stack_ledger.py +48 -18
- package/modules/localmodels/stack_lifecycle.py +33 -312
- package/modules/localmodels/stack_llm_ram.py +16 -6
- package/modules/localmodels/stack_mcp.py +729 -0
- package/modules/localmodels/stack_memory.py +0 -2
- package/modules/localmodels/stack_picks.py +62 -15
- package/modules/localmodels/stack_plan.py +19 -1
- package/modules/localmodels/stack_preflight.py +11 -19
- package/modules/localmodels/stack_progress.py +9 -1
- package/modules/localmodels/stack_remove.py +373 -0
- package/modules/localmodels/stack_route.py +101 -17
- package/modules/localmodels/stack_run.py +29 -0
- package/modules/localmodels/stack_suite.py +21 -10
- package/modules/localmodels/stack_summary.py +14 -0
- package/modules/localmodels/stack_try.py +238 -24
- package/modules/localmodels/stack_try_client.py +53 -15
- package/modules/localmodels/stack_try_docs.py +2 -2
- package/modules/localmodels/stack_view.py +24 -171
- package/modules/localmodels/stack_view_access.py +114 -1
- package/modules/localmodels/stack_view_agent.py +3 -13
- package/modules/localmodels/stack_view_hub.py +9 -10
- package/modules/localmodels/stack_view_llm.py +1 -1
- package/modules/localmodels/stack_view_sandbox.py +2 -2
- package/modules/localmodels/stack_view_schema.py +183 -0
- package/modules/localmodels/stack_view_serve.py +7 -1
- package/modules/localmodels/stack_view_service.py +1 -2
- package/modules/localmodels/stack_view_text.py +13 -9
- package/modules/localmodels/stack_warm.py +48 -4
- package/modules/localmodels/stack_warm_store.py +517 -0
- package/modules/localmodels/tools.json +32 -18
- package/modules/localmodels/transport.py +38 -13
- package/modules/localmodels/tui.py +28 -4
- package/modules/localmodels/tui_dialogs.py +136 -0
- package/modules/localmodels/tui_modals.py +279 -0
- package/modules/localmodels/tui_screen.py +113 -154
- package/modules/localmodels/tui_views.py +134 -203
- package/modules/localmodels/web/index.html +510 -101
- package/modules/localmodels/web/sizecalc/app.js +363 -10
- package/modules/localmodels/web/sizecalc/page.html +27 -3
- package/modules/localmodels/web/view/fleet.html +11 -2
- package/modules/localmodels/web/view/fleet.js +191 -17
- package/modules/localmodels/web/view/i18n.js +3 -2
- package/modules/localmodels/web/view/index.html +1 -1
- package/modules/localmodels/web/view/nav.js +22 -3
- package/modules/localmodels/web/view/view.css +63 -18
- package/modules/localmodels/web/view/view.js +169 -32
- package/modules/localmodels/windows_job.py +69 -0
- package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/RECORD +128 -106
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
- /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -1,58 +1,412 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""End the controller running under a root, on Linux, macOS and Windows.
|
|
2
|
+
|
|
3
|
+
A controller from 0.1.0.dev34 or later exits when asked over its loopback API with the key under
|
|
4
|
+
the root, which works the same on every platform, so it is always asked first. An older one is
|
|
5
|
+
stopped only after the platform proves which process holds the root's ``worker.lock`` and runs
|
|
6
|
+
the exact worker command as this user: ``/proc`` locks and a pidfd on Linux; ``ps``, ``lsof`` and
|
|
7
|
+
the start time on macOS; the command line and creation time on Windows. Nothing it cannot prove is
|
|
8
|
+
signalled. Failures raise ``ControllerError`` whose ``code`` names what failed.
|
|
9
|
+
"""
|
|
2
10
|
|
|
3
11
|
from __future__ import annotations
|
|
4
12
|
|
|
13
|
+
import contextlib
|
|
14
|
+
import errno
|
|
15
|
+
import json
|
|
5
16
|
import os
|
|
6
17
|
import signal
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
7
20
|
import time
|
|
21
|
+
import urllib.error
|
|
22
|
+
import urllib.request
|
|
23
|
+
from collections.abc import Callable
|
|
8
24
|
from pathlib import Path
|
|
9
25
|
|
|
10
|
-
from localmodels import runtime_io, service_autostart
|
|
26
|
+
from localmodels import process_identity, process_windows, runtime_io, service_autostart
|
|
11
27
|
|
|
28
|
+
GRACE = 15.0 # an install in progress finishes its current step before the worker exits
|
|
29
|
+
KILL_AFTER = 10.0 # after SIGTERM, before SIGKILL
|
|
30
|
+
KILLED_GRACE = 5.0 # after SIGKILL, before giving up
|
|
12
31
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
32
|
+
UNVERIFIED = "controller_unverified" # a lock holder that cannot be proven to be the controller
|
|
33
|
+
CHANGED = "controller_changed" # the proven process was replaced while it was being stopped
|
|
34
|
+
DID_NOT_STOP = "controller_did_not_stop" # it outlived the request, SIGTERM and SIGKILL
|
|
35
|
+
|
|
36
|
+
Identity = tuple[int, str] # PID and the start time the platform reports for it
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ControllerError(ValueError):
|
|
40
|
+
"""A refusal to replace or stop the controller; ``code`` names what failed."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, code: str, message: str) -> None:
|
|
43
|
+
super().__init__(f"{code}: {message}")
|
|
44
|
+
self.code = code
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _unverified(root: Path, why: str) -> ControllerError:
|
|
48
|
+
return ControllerError(
|
|
49
|
+
UNVERIFIED,
|
|
50
|
+
f"cannot verify that the process holding {root / 'worker.lock'} is this root's model "
|
|
51
|
+
f"controller ({why}); it did not exit when asked over the control API, so nothing was "
|
|
52
|
+
"stopped",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# ── platform-neutral: the lock and the control API ──
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def idle(root: Path) -> bool:
|
|
60
|
+
"""True when nothing holds the root's worker lock (taken and released at once)."""
|
|
61
|
+
try:
|
|
62
|
+
with runtime_io.private_lock(root / "worker.lock", blocking=False):
|
|
63
|
+
return True
|
|
64
|
+
except OSError as error:
|
|
65
|
+
# flock answers EAGAIN (BlockingIOError); msvcrt.locking EACCES or EDEADLOCK.
|
|
66
|
+
if error.errno in (errno.EAGAIN, errno.EACCES, errno.EDEADLK):
|
|
67
|
+
return False
|
|
68
|
+
raise
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def wait_idle(root: Path, seconds: float) -> bool:
|
|
72
|
+
deadline = time.monotonic() + seconds
|
|
73
|
+
while not idle(root):
|
|
74
|
+
if time.monotonic() >= deadline:
|
|
75
|
+
return False
|
|
76
|
+
time.sleep(0.1)
|
|
77
|
+
return True
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def request_stop(root: Path) -> bool:
|
|
81
|
+
"""Ask the controller to exit; False when it does not answer or predates the request."""
|
|
82
|
+
try:
|
|
83
|
+
runtime_io.private_permissions(root / "control.json")
|
|
84
|
+
port = json.loads((root / "control.json").read_text())["port"]
|
|
85
|
+
if type(port) is not int or not 1 <= port <= 65535:
|
|
86
|
+
return False
|
|
87
|
+
runtime_io.private_permissions(root / "control.key")
|
|
88
|
+
key = json.loads((root / "control.key").read_text())
|
|
89
|
+
request = urllib.request.Request(
|
|
90
|
+
f"http://127.0.0.1:{port}/v1/controller/stop",
|
|
91
|
+
data=b"{}",
|
|
92
|
+
headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
|
|
93
|
+
method="POST",
|
|
94
|
+
)
|
|
95
|
+
with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(
|
|
96
|
+
request, timeout=2
|
|
97
|
+
) as response:
|
|
98
|
+
return bool(response.status == 202)
|
|
99
|
+
except (OSError, ValueError, KeyError, TypeError, urllib.error.URLError):
|
|
100
|
+
return False
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ── Linux: /proc locks and a pidfd ──
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _dev_ino_matches(field: str, target_dev_ino: tuple[int, int, int]) -> bool:
|
|
107
|
+
parts = field.split(":")
|
|
108
|
+
if len(parts) != 3:
|
|
109
|
+
return False
|
|
110
|
+
try:
|
|
111
|
+
return (int(parts[0], 16), int(parts[1], 16), int(parts[2])) == target_dev_ino
|
|
112
|
+
except ValueError:
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _matches_worker(directory: Path, expected: list[bytes]) -> bool:
|
|
117
|
+
if directory.is_symlink() or directory.stat().st_uid != os.getuid():
|
|
118
|
+
return False
|
|
119
|
+
cmdline = directory / "cmdline"
|
|
120
|
+
if cmdline.is_symlink():
|
|
121
|
+
return False
|
|
122
|
+
command = cmdline.read_bytes().rstrip(b"\0").split(b"\0")
|
|
123
|
+
return command[1:] == expected
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _fdinfo_has_write_flock(text: str, target_dev_ino: tuple[int, int, int]) -> bool:
|
|
127
|
+
for line in text.splitlines():
|
|
128
|
+
if not line.startswith("lock:"):
|
|
19
129
|
continue
|
|
20
|
-
|
|
21
|
-
if (
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
130
|
+
fields = line.split()
|
|
131
|
+
if (
|
|
132
|
+
len(fields) < 7
|
|
133
|
+
or fields[0] != "lock:"
|
|
134
|
+
or fields[2:5] != ["FLOCK", "ADVISORY", "WRITE"]
|
|
135
|
+
or not fields[5].isdigit()
|
|
136
|
+
or not _dev_ino_matches(fields[6], target_dev_ino)
|
|
25
137
|
):
|
|
26
138
|
continue
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
139
|
+
return True
|
|
140
|
+
return False
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _holds_worker_lock(directory: Path, target_dev_ino: tuple[int, int, int]) -> bool:
|
|
144
|
+
fd_dir, fdinfo_dir = directory / "fd", directory / "fdinfo"
|
|
145
|
+
if fd_dir.is_symlink() or fdinfo_dir.is_symlink():
|
|
146
|
+
return False
|
|
147
|
+
for fd_entry in fd_dir.iterdir():
|
|
148
|
+
if not fd_entry.name.isdigit():
|
|
149
|
+
continue
|
|
150
|
+
with contextlib.suppress(OSError):
|
|
151
|
+
fd_stat = fd_entry.stat()
|
|
152
|
+
if (
|
|
153
|
+
os.major(fd_stat.st_dev),
|
|
154
|
+
os.minor(fd_stat.st_dev),
|
|
155
|
+
fd_stat.st_ino,
|
|
156
|
+
) != target_dev_ino:
|
|
157
|
+
continue
|
|
158
|
+
fdinfo = fdinfo_dir / fd_entry.name
|
|
159
|
+
if not fdinfo.is_symlink() and _fdinfo_has_write_flock(
|
|
160
|
+
fdinfo.read_text(), target_dev_ino
|
|
161
|
+
):
|
|
162
|
+
return True
|
|
163
|
+
return False
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _controller_pid_from_locks(
|
|
167
|
+
target_dev_ino: tuple[int, int, int], expected: list[bytes], proc: Path
|
|
168
|
+
) -> int | None:
|
|
169
|
+
locks = proc / "locks"
|
|
170
|
+
if locks.is_symlink():
|
|
171
|
+
return None
|
|
172
|
+
with contextlib.suppress(OSError):
|
|
173
|
+
for line in locks.read_text().splitlines():
|
|
174
|
+
fields = line.split()
|
|
175
|
+
if len(fields) < 6 or fields[1:4] != ["FLOCK", "ADVISORY", "WRITE"]:
|
|
176
|
+
continue
|
|
177
|
+
if not fields[4].isdigit() or not _dev_ino_matches(fields[5], target_dev_ino):
|
|
178
|
+
continue
|
|
179
|
+
pid = int(fields[4])
|
|
180
|
+
with contextlib.suppress(OSError):
|
|
181
|
+
if _matches_worker(proc / str(pid), expected):
|
|
182
|
+
return pid
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _controller_pid_from_fdinfo(
|
|
187
|
+
target_dev_ino: tuple[int, int, int], expected: list[bytes], proc: Path
|
|
188
|
+
) -> int | None:
|
|
189
|
+
if proc.is_symlink():
|
|
190
|
+
return None
|
|
191
|
+
with contextlib.suppress(OSError):
|
|
192
|
+
for directory in proc.iterdir():
|
|
193
|
+
if not directory.name.isdigit():
|
|
194
|
+
continue
|
|
195
|
+
with contextlib.suppress(OSError):
|
|
196
|
+
if _matches_worker(directory, expected) and _holds_worker_lock(
|
|
197
|
+
directory, target_dev_ino
|
|
198
|
+
):
|
|
199
|
+
return int(directory.name)
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def controller_pid(root: Path, proc: Path = Path("/proc")) -> int:
|
|
204
|
+
"""Linux: the current user's exact worker holding this root's advisory lock."""
|
|
205
|
+
lock = root / "worker.lock"
|
|
206
|
+
if root.is_symlink() or lock.is_symlink():
|
|
207
|
+
raise _unverified(root, "its lock file is a symbolic link")
|
|
208
|
+
info = lock.stat()
|
|
209
|
+
target_dev_ino = (os.major(info.st_dev), os.minor(info.st_dev), info.st_ino)
|
|
210
|
+
expected = [value.encode() for value in service_autostart.worker_command(root)[1:]]
|
|
211
|
+
pid = _controller_pid_from_locks(target_dev_ino, expected, proc)
|
|
212
|
+
if pid is None:
|
|
213
|
+
pid = _controller_pid_from_fdinfo(target_dev_ino, expected, proc)
|
|
214
|
+
if pid is None:
|
|
215
|
+
raise _unverified(root, "no process of this user with the worker command holds the lock")
|
|
216
|
+
return pid
|
|
34
217
|
|
|
35
218
|
|
|
36
|
-
def
|
|
37
|
-
pid = controller_pid(root)
|
|
219
|
+
def linux_identity(root: Path, proc: Path = Path("/proc")) -> Identity:
|
|
220
|
+
pid = controller_pid(root, proc)
|
|
221
|
+
stat_path = proc / str(pid) / "stat"
|
|
222
|
+
if stat_path.is_symlink():
|
|
223
|
+
raise _unverified(root, "its process status is a symbolic link")
|
|
38
224
|
# starttime is field 22; comm may itself contain spaces or parentheses.
|
|
39
|
-
|
|
40
|
-
|
|
225
|
+
parts = stat_path.read_text().rsplit(")", 1)
|
|
226
|
+
fields = parts[1].split() if len(parts) == 2 else []
|
|
227
|
+
if len(fields) < 20:
|
|
228
|
+
raise _unverified(root, "its start time cannot be read")
|
|
229
|
+
return pid, fields[19]
|
|
41
230
|
|
|
42
231
|
|
|
43
|
-
def
|
|
232
|
+
def _linux_signal(root: Path, identity: Identity, force: bool) -> None:
|
|
44
233
|
# pidfd binds the signal to this process even if the numeric PID is later reused.
|
|
45
|
-
|
|
46
|
-
raise ValueError("Cannot safely upgrade a running controller on this platform")
|
|
47
|
-
descriptor = os.pidfd_open(identity[0])
|
|
234
|
+
descriptor = os.pidfd_open(identity[0]) # type: ignore[attr-defined,unused-ignore]
|
|
48
235
|
try:
|
|
49
236
|
if controller_identity(root) != identity:
|
|
50
|
-
raise
|
|
51
|
-
signal.
|
|
237
|
+
raise ControllerError(CHANGED, "the model controller changed while it was stopped")
|
|
238
|
+
signum = signal.SIGKILL if force else signal.SIGTERM # type: ignore[attr-defined,unused-ignore]
|
|
239
|
+
signal.pidfd_send_signal(descriptor, signum) # type: ignore[attr-defined,unused-ignore]
|
|
52
240
|
finally:
|
|
53
241
|
os.close(descriptor)
|
|
54
242
|
|
|
55
243
|
|
|
244
|
+
# ── macOS: ps, lsof and the start time ──
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _run(argv: list[str]) -> str | None:
|
|
248
|
+
"""A read-only system tool's stdout in the C locale; None when it cannot answer."""
|
|
249
|
+
try:
|
|
250
|
+
done = subprocess.run(
|
|
251
|
+
argv,
|
|
252
|
+
capture_output=True,
|
|
253
|
+
text=True,
|
|
254
|
+
timeout=10,
|
|
255
|
+
check=False,
|
|
256
|
+
env={**os.environ, "LC_ALL": "C"},
|
|
257
|
+
)
|
|
258
|
+
except (OSError, subprocess.SubprocessError):
|
|
259
|
+
return None
|
|
260
|
+
return done.stdout if done.returncode in (0, 1) else None # 1: nothing matched
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _darwin_identity(root: Path) -> Identity:
|
|
264
|
+
"""The one process of this user that runs the exact worker command for ``root`` and has its
|
|
265
|
+
lock file open, while the lock is held: ``ps`` joins argv with spaces, so the command is
|
|
266
|
+
compared as text after the interpreter, and ``lsof`` names who has the lock file open."""
|
|
267
|
+
lock = root / "worker.lock"
|
|
268
|
+
if root.is_symlink() or lock.is_symlink():
|
|
269
|
+
raise _unverified(root, "its lock file is a symbolic link")
|
|
270
|
+
listing = _run(["/bin/ps", "-A", "-ww", "-o", "pid=,uid=,args="])
|
|
271
|
+
openers = _run(["/usr/sbin/lsof", "-w", "-n", "-Fp", "--", str(lock)])
|
|
272
|
+
if listing is None or openers is None:
|
|
273
|
+
raise _unverified(root, "ps or lsof did not answer")
|
|
274
|
+
tail = " " + " ".join(service_autostart.worker_command(root)[1:])
|
|
275
|
+
holding = {int(line[1:]) for line in openers.splitlines() if line[1:].isdecimal()}
|
|
276
|
+
candidates = []
|
|
277
|
+
for row in listing.splitlines():
|
|
278
|
+
fields = row.split(None, 2)
|
|
279
|
+
if (
|
|
280
|
+
len(fields) == 3
|
|
281
|
+
and fields[0].isdecimal()
|
|
282
|
+
and fields[1] == str(os.getuid())
|
|
283
|
+
and fields[2].endswith(tail)
|
|
284
|
+
and int(fields[0]) in holding
|
|
285
|
+
):
|
|
286
|
+
candidates.append(int(fields[0]))
|
|
287
|
+
if len(candidates) != 1:
|
|
288
|
+
raise _unverified(
|
|
289
|
+
root, f"{len(candidates)} processes of this user run the worker with the lock open"
|
|
290
|
+
)
|
|
291
|
+
found = process_identity.inspect(candidates[0])
|
|
292
|
+
if found is None or found["uid"] != os.getuid():
|
|
293
|
+
raise _unverified(root, "the worker process ended or changed owner")
|
|
294
|
+
return candidates[0], found["started"]
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _darwin_signal(root: Path, identity: Identity, force: bool) -> None:
|
|
298
|
+
# No pidfd on macOS: re-prove the PID's command, lock and start time just before signalling.
|
|
299
|
+
if controller_identity(root) != identity:
|
|
300
|
+
raise ControllerError(CHANGED, "the model controller changed while it was stopped")
|
|
301
|
+
os.kill(identity[0], signal.SIGKILL if force else signal.SIGTERM) # type: ignore[attr-defined,unused-ignore]
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
# ── Windows: the command line and creation time ──
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _windows_identity(root: Path) -> Identity:
|
|
308
|
+
"""The one process of this user whose command line ends with the exact worker arguments
|
|
309
|
+
(as ``subprocess`` quoted them when it started the worker)."""
|
|
310
|
+
tail = " " + subprocess.list2cmdline(service_autostart.worker_command(root)[1:])
|
|
311
|
+
candidates = []
|
|
312
|
+
try:
|
|
313
|
+
for pid in process_windows.own_pids():
|
|
314
|
+
line = process_windows.command_line(pid)
|
|
315
|
+
if line is not None and line.endswith(tail):
|
|
316
|
+
candidates.append(pid)
|
|
317
|
+
found = process_identity.inspect(candidates[0]) if len(candidates) == 1 else None
|
|
318
|
+
except OSError as error:
|
|
319
|
+
raise _unverified(root, f"the process list cannot be read: {error}") from None
|
|
320
|
+
if len(candidates) != 1:
|
|
321
|
+
raise _unverified(root, f"{len(candidates)} processes of this user run the worker")
|
|
322
|
+
if found is None or found["uid"] != process_identity.current_uid():
|
|
323
|
+
raise _unverified(root, "the worker process ended or changed owner")
|
|
324
|
+
return candidates[0], found["started"]
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _windows_signal(root: Path, identity: Identity, force: bool) -> None:
|
|
328
|
+
# Windows has no SIGTERM for another process: end exactly this one, never its tree (the
|
|
329
|
+
# model services it started keep running). The handle pins the creation time checked.
|
|
330
|
+
if controller_identity(root) != identity:
|
|
331
|
+
raise ControllerError(CHANGED, "the model controller changed while it was stopped")
|
|
332
|
+
if not process_windows.terminate(identity[0], identity[1]):
|
|
333
|
+
raise ControllerError(CHANGED, "the model controller changed while it was stopped")
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
# ── dispatch ──
|
|
337
|
+
|
|
338
|
+
_IDENTITY: dict[str, Callable[[Path], Identity]] = {
|
|
339
|
+
"linux": linux_identity,
|
|
340
|
+
"darwin": _darwin_identity,
|
|
341
|
+
"win32": _windows_identity,
|
|
342
|
+
}
|
|
343
|
+
_SIGNAL: dict[str, Callable[[Path, Identity, bool], None]] = {
|
|
344
|
+
"linux": _linux_signal,
|
|
345
|
+
"darwin": _darwin_signal,
|
|
346
|
+
"win32": _windows_signal,
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def platform() -> str:
|
|
351
|
+
"""``sys.platform``, read at each call; tests replace this instead of the interpreter's."""
|
|
352
|
+
return sys.platform
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def controller_identity(root: Path) -> Identity:
|
|
356
|
+
"""The proven controller process holding ``root``'s lock: (PID, start time)."""
|
|
357
|
+
prove = _IDENTITY.get(platform())
|
|
358
|
+
if prove is None:
|
|
359
|
+
raise _unverified(root, f"no process proof on {platform()}")
|
|
360
|
+
return prove(root)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def signal_controller(root: Path, identity: Identity, force: bool) -> None:
|
|
364
|
+
"""SIGTERM (``force``: SIGKILL; on Windows always an exact termination) the proven PID."""
|
|
365
|
+
_SIGNAL[platform()](root, identity, force)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _signal_until_idle(root: Path) -> None:
|
|
369
|
+
"""SIGTERM (the worker's clean shutdown), SIGKILL after KILL_AFTER, each re-proven."""
|
|
370
|
+
deadline = time.monotonic() + KILL_AFTER
|
|
371
|
+
sent: Identity | None = None
|
|
372
|
+
killed = False
|
|
373
|
+
while not idle(root):
|
|
374
|
+
try:
|
|
375
|
+
identity = controller_identity(root)
|
|
376
|
+
if sent is None:
|
|
377
|
+
signal_controller(root, identity, False)
|
|
378
|
+
sent = identity
|
|
379
|
+
elif identity != sent:
|
|
380
|
+
raise ControllerError(CHANGED, "the model controller changed while it was stopped")
|
|
381
|
+
elif time.monotonic() >= deadline:
|
|
382
|
+
if killed:
|
|
383
|
+
raise ControllerError(
|
|
384
|
+
DID_NOT_STOP, "the model controller is still running after SIGKILL"
|
|
385
|
+
)
|
|
386
|
+
signal_controller(root, identity, True)
|
|
387
|
+
killed = True
|
|
388
|
+
deadline = time.monotonic() + KILLED_GRACE
|
|
389
|
+
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
|
390
|
+
# The owner may exit between the lock attempt and its proof; a free lock settles it.
|
|
391
|
+
if idle(root):
|
|
392
|
+
return
|
|
393
|
+
if isinstance(error, ControllerError):
|
|
394
|
+
raise
|
|
395
|
+
raise _unverified(root, str(error) or type(error).__name__) from None
|
|
396
|
+
time.sleep(0.05)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def end_controller(root: Path) -> str | None:
|
|
400
|
+
"""Make the root's worker lock free: None when nothing held it, ``request`` when the
|
|
401
|
+
controller exited when asked, ``signal`` when a proven older one had to be signalled."""
|
|
402
|
+
if idle(root):
|
|
403
|
+
return None
|
|
404
|
+
if request_stop(root) and wait_idle(root, GRACE):
|
|
405
|
+
return "request"
|
|
406
|
+
_signal_until_idle(root)
|
|
407
|
+
return "signal"
|
|
408
|
+
|
|
409
|
+
|
|
56
410
|
def _discard_jobs(root: Path) -> None:
|
|
57
411
|
path = root / "jobs.json"
|
|
58
412
|
if path.exists() or path.is_symlink():
|
|
@@ -62,36 +416,13 @@ def _discard_jobs(root: Path) -> None:
|
|
|
62
416
|
|
|
63
417
|
def retire_implicit_jobs(root: Path) -> None:
|
|
64
418
|
"""Stop only the proven old controller, then discard its obsolete scheduling state."""
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
identity = controller_identity(root)
|
|
76
|
-
if signalled is None:
|
|
77
|
-
signal_controller(root, identity, signal.SIGTERM)
|
|
78
|
-
signalled = identity
|
|
79
|
-
elif identity != signalled:
|
|
80
|
-
raise ValueError("Model controller changed during upgrade") from None
|
|
81
|
-
elif time.monotonic() >= deadline:
|
|
82
|
-
# Revalidate lock ownership and command above before targeting this PID.
|
|
83
|
-
if killed:
|
|
84
|
-
raise ValueError("Model controller did not stop during upgrade") from None
|
|
85
|
-
signal_controller(root, identity, signal.SIGKILL)
|
|
86
|
-
killed = True
|
|
87
|
-
deadline = time.monotonic() + 2
|
|
88
|
-
except (OSError, ValueError) as error:
|
|
89
|
-
# The old owner may exit between the failed lock attempt and validation.
|
|
90
|
-
# A free exclusive lock is the only proof that retirement can proceed.
|
|
91
|
-
try:
|
|
92
|
-
with runtime_io.private_lock(root / "worker.lock", blocking=False):
|
|
93
|
-
_discard_jobs(root)
|
|
94
|
-
return
|
|
95
|
-
except BlockingIOError:
|
|
96
|
-
raise error from None
|
|
97
|
-
time.sleep(0.05)
|
|
419
|
+
end_controller(root)
|
|
420
|
+
try:
|
|
421
|
+
with runtime_io.private_lock(root / "worker.lock", blocking=False):
|
|
422
|
+
_discard_jobs(root)
|
|
423
|
+
except OSError as error:
|
|
424
|
+
if error.errno in (errno.EAGAIN, errno.EACCES, errno.EDEADLK):
|
|
425
|
+
raise ControllerError(
|
|
426
|
+
CHANGED, "another model controller took the lock during the upgrade"
|
|
427
|
+
) from None
|
|
428
|
+
raise
|
|
@@ -195,7 +195,8 @@ ENSURE_CALLS = (
|
|
|
195
195
|
"Each call sets the whole selection: no --component deselects every service and no\n"
|
|
196
196
|
"--share-gpu withdraws consent. Deselecting stops no process and deletes no weights;\n"
|
|
197
197
|
"a service that is still installing cannot be deselected. After a package upgrade,\n"
|
|
198
|
-
"ensure replaces the old controller process it owns
|
|
198
|
+
"ensure replaces the old controller process it owns (asked over its API, or signalled\n"
|
|
199
|
+
"after proof, as `stop` does); model services keep running."
|
|
199
200
|
)
|
|
200
201
|
RUN = (
|
|
201
202
|
"Run the controller in the foreground until SIGTERM or SIGINT: it serves the loopback "
|
|
@@ -229,10 +230,12 @@ STOP = (
|
|
|
229
230
|
"Stop the controller under --root and remove its autostart, for an uninstall or before "
|
|
230
231
|
"installing another version: on Linux the user unit simplex-model-services-<hash> is "
|
|
231
232
|
"stopped, disabled and its file deleted; a running controller is asked to exit over its "
|
|
232
|
-
"loopback API.
|
|
233
|
-
"command prove it belongs to this root
|
|
234
|
-
"
|
|
235
|
-
"
|
|
233
|
+
"loopback API. A controller from before 0.1.0.dev34, which has no such request, is "
|
|
234
|
+
"signalled only after its lock and exact command prove it belongs to this root: /proc and "
|
|
235
|
+
"a pidfd on Linux, ps, lsof and its start time on macOS, its command line and creation time "
|
|
236
|
+
"on Windows (SIGTERM, then SIGKILL after 10 seconds; Windows ends that one process). A lock "
|
|
237
|
+
"holder that cannot be proven is left running and reported with code "
|
|
238
|
+
"controller_unverified. Idempotent: no controller config "
|
|
236
239
|
"under --root, or no controller running, is a success. Model services it started, "
|
|
237
240
|
"control.json, the key, jobs and model files stay; the next `ensure` registers and starts "
|
|
238
241
|
"it again.\n\nPrints localmodels.service-controller-stop/v1: root, stopped (a controller "
|
|
@@ -304,7 +307,10 @@ def _ensure_options(command: argparse.ArgumentParser) -> None:
|
|
|
304
307
|
"exit status",
|
|
305
308
|
"0 binding printed\n"
|
|
306
309
|
"1 refused, message on stderr: --root belongs to another --base-dir, a repeated\n"
|
|
307
|
-
" --component, a deselected service still installing, or unsafe state files
|
|
310
|
+
" --component, a deselected service still installing, or unsafe state files;\n"
|
|
311
|
+
" or the controller of an earlier version could not be replaced, printed as\n"
|
|
312
|
+
" {ok: false, code, error} with code controller_unverified, controller_changed\n"
|
|
313
|
+
" or controller_did_not_stop\n"
|
|
308
314
|
"2 bad arguments, such as a relative path",
|
|
309
315
|
),
|
|
310
316
|
],
|
|
@@ -445,14 +451,18 @@ def cli(args: argparse.Namespace) -> int:
|
|
|
445
451
|
|
|
446
452
|
value = stop(args.root)
|
|
447
453
|
elif args.services_command == "ensure":
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
454
|
+
try:
|
|
455
|
+
value = ensure(
|
|
456
|
+
args.root,
|
|
457
|
+
args.base_dir,
|
|
458
|
+
args.main_plan,
|
|
459
|
+
residency=args.residency,
|
|
460
|
+
components=args.component,
|
|
461
|
+
share_gpu=args.share_gpu,
|
|
462
|
+
)
|
|
463
|
+
except service_upgrade.ControllerError as error:
|
|
464
|
+
# Replacing the running controller failed: say which step, not a binding problem.
|
|
465
|
+
value = {"ok": False, "code": error.code, "error": str(error)}
|
|
456
466
|
else:
|
|
457
467
|
config = read_configuration(args.root)
|
|
458
468
|
key = json.loads((args.root / "control.key").read_text())
|