@simplexai/localmodels-linux-x64 0.1.0-dev.45 → 0.1.0-dev.47
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 +38 -36
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/catalog.json +150 -0
- package/modules/localmodels/catalog.py +20 -5
- package/modules/localmodels/catalog_recipes.py +8 -0
- package/modules/localmodels/context_policy.py +32 -9
- package/modules/localmodels/deploy.py +20 -14
- package/modules/localmodels/engines-b12588-mix-c0c3de8.json +98 -0
- package/modules/localmodels/engines.py +28 -2
- package/modules/localmodels/estimator.py +12 -3
- package/modules/localmodels/gateway_bifrost.py +95 -22
- package/modules/localmodels/gguf.py +6 -2
- package/modules/localmodels/harness_probe.py +60 -13
- package/modules/localmodels/library_pricing.py +6 -4
- package/modules/localmodels/library_state.py +6 -4
- package/modules/localmodels/probe.py +38 -11
- package/modules/localmodels/process_identity.py +47 -33
- package/modules/localmodels/process_identity_linux.py +135 -0
- package/modules/localmodels/process_windows.py +150 -1
- package/modules/localmodels/runtime_windows_acl.py +100 -0
- package/modules/localmodels/service_probe.py +26 -20
- package/modules/localmodels/setup_inspection.py +132 -36
- package/modules/localmodels/setup_text.py +14 -0
- package/modules/localmodels/stack_binding.py +58 -0
- package/modules/localmodels/stack_lifecycle.py +7 -4
- package/modules/localmodels/stack_view_llm.py +1 -1
- package/modules/localmodels/stack_view_sandbox.py +3 -1
- package/modules/localmodels/stack_warm.py +18 -7
- package/modules/localmodels/strata_poly_server.py +4 -2
- package/modules/localmodels/transport.py +7 -1
- package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/RECORD +35 -33
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -11,6 +11,7 @@ import ctypes
|
|
|
11
11
|
import datetime as dt
|
|
12
12
|
import glob
|
|
13
13
|
import json
|
|
14
|
+
import ntpath
|
|
14
15
|
import os
|
|
15
16
|
import platform
|
|
16
17
|
import re
|
|
@@ -202,7 +203,8 @@ _VERSION_RE = re.compile(r"version:\s*(\d+)\s*\(([0-9a-f]+)\)")
|
|
|
202
203
|
_SEMVER_RE = re.compile(r"version:\s*([\w.\-]+)\s*\(build\s*(\d+),\s*commit\s*([0-9a-f]+)\)")
|
|
203
204
|
SERVICE_PORTS = (8080, 9931, 18100, 18321, 18331, 18351, 18352, 18370)
|
|
204
205
|
_CONTAINER_CGROUP_RE = re.compile(r"docker|kubepods|containerd|libpod|lxc|crio")
|
|
205
|
-
|
|
206
|
+
_CUDA_RE = re.compile(r"\bCUDA(?:\s+(?:UMD|Driver|API))?\s+Version\s*:\s*(\d+(?:\.\d+)*)", re.I)
|
|
207
|
+
_DRIVER_RE = re.compile(r"\b(?:Driver|KMD)\s+Version\s*:\s*(\d+(?:\.\d+)*)", re.I)
|
|
206
208
|
HOST_LIBRARIES = ("libgomp.so.1",)
|
|
207
209
|
DETAIL_FIELDS = ("compute_cap", "memory.reserved", "display_active") # nvidia-smi names
|
|
208
210
|
_UNLIMITED = 1 << 60 # cgroup v1 reports "no limit" as a page-aligned LONG_MAX
|
|
@@ -300,10 +302,19 @@ def ram() -> tuple[int, int]:
|
|
|
300
302
|
return 0, 0
|
|
301
303
|
|
|
302
304
|
|
|
305
|
+
def _win_system32(name: str) -> str:
|
|
306
|
+
return ntpath.join(os.environ.get("SystemRoot") or r"C:\Windows", "System32", name)
|
|
307
|
+
|
|
308
|
+
|
|
303
309
|
def _nvidia_smi() -> str | None:
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
310
|
+
if found := shutil.which("nvidia-smi"):
|
|
311
|
+
return found
|
|
312
|
+
if sys.platform != "win32":
|
|
313
|
+
wsl = "/usr/lib/wsl/lib/nvidia-smi"
|
|
314
|
+
return wsl if os.path.exists(wsl) else None
|
|
315
|
+
pf = os.environ.get("ProgramFiles") or r"C:\Program Files"
|
|
316
|
+
nvsmi = ntpath.join(pf, "NVIDIA Corporation", "NVSMI", "nvidia-smi.exe")
|
|
317
|
+
return next((p for p in (_win_system32("nvidia-smi.exe"), nvsmi) if os.path.exists(p)), None)
|
|
307
318
|
|
|
308
319
|
|
|
309
320
|
def parse_gpu_csv(text: str) -> list[GPU]:
|
|
@@ -341,13 +352,17 @@ def parse_gpu_csv(text: str) -> list[GPU]:
|
|
|
341
352
|
|
|
342
353
|
def parse_cuda_version(text: str) -> str:
|
|
343
354
|
"""Driver-supported CUDA version from ``nvidia-smi`` banner or ``-q`` text, or empty."""
|
|
344
|
-
|
|
345
|
-
|
|
355
|
+
return m.group(1) if (m := _CUDA_RE.search(text)) else ""
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def parse_driver_version(text: str) -> str:
|
|
359
|
+
"""NVIDIA driver/KMD version from ``nvidia-smi`` banner or ``-q`` text, or empty."""
|
|
360
|
+
return m.group(1) if (m := _DRIVER_RE.search(text)) else ""
|
|
346
361
|
|
|
347
362
|
|
|
348
363
|
def _load_cuda_driver() -> ctypes.CDLL | None:
|
|
349
364
|
names: tuple[str, ...] = (
|
|
350
|
-
("nvcuda.dll",)
|
|
365
|
+
("nvcuda.dll", _win_system32("nvcuda.dll"))
|
|
351
366
|
if sys.platform == "win32"
|
|
352
367
|
else ("libcuda.so.1", "libcuda.so", "/usr/lib/wsl/lib/libcuda.so.1")
|
|
353
368
|
if sys.platform.startswith("linux")
|
|
@@ -389,8 +404,15 @@ def _nvidia(errors: list[dict[str, str]]) -> tuple[dict[str, str] | None, list[G
|
|
|
389
404
|
errors.append({"source": "nvidia-smi", "error": (err or out).strip()[:300]})
|
|
390
405
|
return None, []
|
|
391
406
|
gpus = parse_gpu_csv(out)
|
|
392
|
-
|
|
393
|
-
|
|
407
|
+
drv = "" if not gpus or gpus[0]["driver_version"].startswith("[") else gpus[0]["driver_version"]
|
|
408
|
+
cuda_version = _cuda_driver_version()
|
|
409
|
+
if not cuda_version or not drv:
|
|
410
|
+
banner = _run([exe])[1]
|
|
411
|
+
cuda_version = cuda_version or parse_cuda_version(banner)
|
|
412
|
+
drv = drv or parse_driver_version(banner)
|
|
413
|
+
for gpu in gpus:
|
|
414
|
+
if not gpu["driver_version"] or gpu["driver_version"].startswith("["):
|
|
415
|
+
gpu["driver_version"] = drv
|
|
394
416
|
return {"driver_version": drv, "cuda_version": cuda_version}, gpus
|
|
395
417
|
|
|
396
418
|
|
|
@@ -428,10 +450,15 @@ def shared_libraries(names: Sequence[str] = HOST_LIBRARIES) -> dict[str, bool]:
|
|
|
428
450
|
|
|
429
451
|
|
|
430
452
|
def _gpu_vendor_class() -> str:
|
|
453
|
+
exists = os.path.exists
|
|
431
454
|
if sys.platform == "darwin":
|
|
432
455
|
return "apple_silicon" if _arch() == "arm64" else "unknown"
|
|
433
|
-
if
|
|
434
|
-
return "nvidia"
|
|
456
|
+
if sys.platform == "win32":
|
|
457
|
+
return "nvidia" if _nvidia_smi() or exists(_win_system32("nvcuda.dll")) else "unknown"
|
|
458
|
+
if exists("/proc/driver/nvidia/version") or exists("/usr/lib/wsl/lib/nvidia-smi"):
|
|
459
|
+
return "nvidia"
|
|
460
|
+
if exists("/usr/lib/wsl/lib/libcuda.so.1"):
|
|
461
|
+
return "nvidia"
|
|
435
462
|
root = "/sys/class/drm"
|
|
436
463
|
try:
|
|
437
464
|
cards = [e for e in sorted(os.listdir(root)) if e.startswith("card") and "-" not in e][:16]
|
|
@@ -10,8 +10,6 @@ from __future__ import annotations
|
|
|
10
10
|
import ctypes
|
|
11
11
|
import json
|
|
12
12
|
import os
|
|
13
|
-
import shlex
|
|
14
|
-
import shutil
|
|
15
13
|
import stat
|
|
16
14
|
import subprocess
|
|
17
15
|
import sys
|
|
@@ -19,6 +17,11 @@ import tempfile
|
|
|
19
17
|
from pathlib import Path
|
|
20
18
|
from typing import Any, TypedDict
|
|
21
19
|
|
|
20
|
+
try:
|
|
21
|
+
from localmodels import process_identity_linux
|
|
22
|
+
except ImportError: # run as a bare file from this directory
|
|
23
|
+
import process_identity_linux # type: ignore[import-not-found,no-redef]
|
|
24
|
+
|
|
22
25
|
|
|
23
26
|
class Identity(TypedDict):
|
|
24
27
|
pid: int
|
|
@@ -483,12 +486,43 @@ def kill_started(pid: int) -> None:
|
|
|
483
486
|
|
|
484
487
|
# ── POSIX and shared ──
|
|
485
488
|
|
|
489
|
+
_IDENTITY_FIELDS = {"pid": int, "uid": int, "pgid": int, "started": str}
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _same_start(current: str, saved: str) -> bool:
|
|
493
|
+
return current == saved or (
|
|
494
|
+
sys.platform.startswith("linux") and process_identity_linux.same_start(current, saved)
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _valid_identity(saved: dict[str, Any]) -> bool:
|
|
499
|
+
return set(saved) == set(_IDENTITY_FIELDS) and all(
|
|
500
|
+
type(saved[k]) is t for k, t in _IDENTITY_FIELDS.items()
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def matches(current: Identity | None, saved: object) -> bool:
|
|
505
|
+
"""Whether ``current`` proves the same process instance recorded in ``saved``."""
|
|
506
|
+
if current is None or not isinstance(saved, dict) or not _valid_identity(saved):
|
|
507
|
+
return False
|
|
508
|
+
return (
|
|
509
|
+
current["pid"] == saved["pid"]
|
|
510
|
+
and current["uid"] == saved["uid"]
|
|
511
|
+
and current["pgid"] == saved["pgid"]
|
|
512
|
+
and _same_start(current["started"], saved["started"])
|
|
513
|
+
)
|
|
514
|
+
|
|
486
515
|
|
|
487
516
|
def inspect(pid: int) -> Identity | None:
|
|
488
517
|
if pid <= 1:
|
|
489
518
|
return None
|
|
490
519
|
if _windows():
|
|
491
520
|
return _windows_inspect(pid)
|
|
521
|
+
if sys.platform.startswith("linux"):
|
|
522
|
+
found = process_identity_linux.inspect(pid)
|
|
523
|
+
if found is None:
|
|
524
|
+
return None
|
|
525
|
+
return {"pid": pid, "uid": found[0], "pgid": found[1], "started": found[2]}
|
|
492
526
|
# LC_ALL=C keeps lstart in 5 English tokens (zh_CN outputs 4).
|
|
493
527
|
result = subprocess.run(
|
|
494
528
|
["/bin/ps", "-p", str(pid), "-o", "uid=,pgid=,lstart=,stat="],
|
|
@@ -536,7 +570,7 @@ def status(pid_file: str | Path) -> tuple[str, int | None]:
|
|
|
536
570
|
if current is None:
|
|
537
571
|
return "inactive", None
|
|
538
572
|
saved = json.loads(_private(Path(str(path) + ".identity.json")))
|
|
539
|
-
if current
|
|
573
|
+
if matches(current, saved) and current["uid"] == current_uid() and current["pgid"] == pid:
|
|
540
574
|
return "active", pid
|
|
541
575
|
except (OSError, ValueError, subprocess.TimeoutExpired):
|
|
542
576
|
pass
|
|
@@ -581,11 +615,9 @@ def _recorded(pid_file: Path) -> Identity | None:
|
|
|
581
615
|
"a legacy PID file has no identity receipt; cannot prove ownership"
|
|
582
616
|
) from None
|
|
583
617
|
return None
|
|
584
|
-
fields = {"pid": int, "uid": int, "pgid": int, "started": str}
|
|
585
618
|
if (
|
|
586
619
|
not isinstance(saved, dict)
|
|
587
|
-
or
|
|
588
|
-
or not all(type(saved[k]) is t for k, t in fields.items())
|
|
620
|
+
or not _valid_identity(saved)
|
|
589
621
|
or int(_private(pid_file).strip()) != saved["pid"]
|
|
590
622
|
):
|
|
591
623
|
raise ValueError("malformed identity receipt")
|
|
@@ -606,13 +638,17 @@ def stop(pid_file: str | Path, grace: float = 15.0) -> str:
|
|
|
606
638
|
try:
|
|
607
639
|
saved = _recorded(path)
|
|
608
640
|
current = None if saved is None else inspect(saved["pid"])
|
|
609
|
-
if
|
|
641
|
+
if (
|
|
642
|
+
saved is None
|
|
643
|
+
or current is None
|
|
644
|
+
or not _same_start(current["started"], saved["started"])
|
|
645
|
+
):
|
|
610
646
|
_forget(path)
|
|
611
647
|
return "gone"
|
|
612
|
-
if current
|
|
648
|
+
if not matches(current, saved):
|
|
613
649
|
raise ValueError("the process identity does not match the receipt")
|
|
614
650
|
if _windows():
|
|
615
|
-
if windows_stop_tree(saved["pid"],
|
|
651
|
+
if windows_stop_tree(saved["pid"], current, grace):
|
|
616
652
|
_forget(path)
|
|
617
653
|
return "stopped"
|
|
618
654
|
raise RuntimeError(
|
|
@@ -622,7 +658,7 @@ def stop(pid_file: str | Path, grace: float = 15.0) -> str:
|
|
|
622
658
|
os.killpg(saved["pid"], sig)
|
|
623
659
|
deadline = time.monotonic() + grace
|
|
624
660
|
while time.monotonic() < deadline:
|
|
625
|
-
if inspect(saved["pid"]) !=
|
|
661
|
+
if inspect(saved["pid"]) != current:
|
|
626
662
|
_forget(path)
|
|
627
663
|
return "stopped"
|
|
628
664
|
time.sleep(0.1)
|
|
@@ -673,29 +709,7 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
|
|
|
673
709
|
"""Read-only Linux argv proof (plus shebang); on Windows checks owned executable image path."""
|
|
674
710
|
if _windows():
|
|
675
711
|
return _windows_command_matches(pid, expected)
|
|
676
|
-
|
|
677
|
-
process = Path(root) / "proc" / str(pid)
|
|
678
|
-
if process.stat().st_uid != os.getuid():
|
|
679
|
-
return False
|
|
680
|
-
actual = process.joinpath("cmdline").read_bytes().decode().rstrip("\0").split("\0")
|
|
681
|
-
if actual == expected:
|
|
682
|
-
return True
|
|
683
|
-
target = expected[0] if root == "/" else Path(root) / expected[0].lstrip("/")
|
|
684
|
-
with open(target, "rb") as executable:
|
|
685
|
-
header = executable.readline(512).decode()
|
|
686
|
-
if not header.startswith("#!"):
|
|
687
|
-
return False
|
|
688
|
-
interp = shlex.split(header[2:].strip())
|
|
689
|
-
if interp[:1] == ["/usr/bin/env"]:
|
|
690
|
-
interp = interp[1:]
|
|
691
|
-
if len(interp) != 1 or actual[1:] != expected:
|
|
692
|
-
return False
|
|
693
|
-
resolved = shutil.which(interp[0])
|
|
694
|
-
return (
|
|
695
|
-
resolved is not None and process.joinpath("exe").resolve() == Path(resolved).resolve()
|
|
696
|
-
)
|
|
697
|
-
except (OSError, ValueError, UnicodeError, IndexError):
|
|
698
|
-
return False
|
|
712
|
+
return process_identity_linux.command_matches(pid, expected, root)
|
|
699
713
|
|
|
700
714
|
|
|
701
715
|
def venv_base(python: str) -> str | None:
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Linux /proc process identity, legacy lstart compatibility, and argv proof; stdlib-only, Python 3.8+."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shlex
|
|
7
|
+
import shutil
|
|
8
|
+
import time
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
# Receipts written before Linux switched from ``ps -o lstart=`` to /proc/<pid>/stat boot ticks
|
|
12
|
+
# hold wall-clock seconds derived from /proc/stat btime, which can drift by ~1-2 s under NTP.
|
|
13
|
+
_LEGACY_LSTART_TOLERANCE_S = 5.0
|
|
14
|
+
_ENGLISH_DAYS = frozenset(("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))
|
|
15
|
+
_ENGLISH_MONTHS = {
|
|
16
|
+
"Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6,
|
|
17
|
+
"Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10, "Nov": 11, "Dec": 12,
|
|
18
|
+
} # fmt: skip
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _status_euid(status_text: str) -> int | None:
|
|
22
|
+
for line in status_text.splitlines():
|
|
23
|
+
if line.startswith("Uid:"):
|
|
24
|
+
parts = line.split()
|
|
25
|
+
if len(parts) == 5 and all(part.isdigit() for part in parts[1:]):
|
|
26
|
+
return int(parts[2])
|
|
27
|
+
return None
|
|
28
|
+
return None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def inspect(pid: int, root: str = "/") -> tuple[int, int, str] | None:
|
|
32
|
+
"""Return ``(euid, pgid, starttime_ticks)`` from ``/proc/<pid>``, or None if gone/zombie."""
|
|
33
|
+
proc = Path(root) / "proc" / str(pid)
|
|
34
|
+
try:
|
|
35
|
+
stat_text = (proc / "stat").read_text(encoding="utf-8")
|
|
36
|
+
status_text = (proc / "status").read_text(encoding="utf-8")
|
|
37
|
+
except (FileNotFoundError, ProcessLookupError):
|
|
38
|
+
return None
|
|
39
|
+
except OSError:
|
|
40
|
+
raise OSError("process identity unavailable") from None
|
|
41
|
+
_, sep, after = stat_text.rpartition(")")
|
|
42
|
+
if not sep:
|
|
43
|
+
raise OSError("process identity unavailable")
|
|
44
|
+
fields = after.split()
|
|
45
|
+
if len(fields) <= 19 or not fields[19].isdigit():
|
|
46
|
+
raise OSError("process identity unavailable")
|
|
47
|
+
if fields[0] == "Z":
|
|
48
|
+
return None
|
|
49
|
+
uid = _status_euid(status_text)
|
|
50
|
+
if uid is None:
|
|
51
|
+
raise OSError("process identity unavailable")
|
|
52
|
+
try:
|
|
53
|
+
pgid = int(fields[2])
|
|
54
|
+
except ValueError:
|
|
55
|
+
raise OSError("process identity unavailable") from None
|
|
56
|
+
return uid, pgid, fields[19]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _boot_time(root: str = "/") -> int | None:
|
|
60
|
+
try:
|
|
61
|
+
for line in (Path(root) / "proc" / "stat").read_text(encoding="ascii").splitlines():
|
|
62
|
+
if line.startswith("btime "):
|
|
63
|
+
parts = line.split()
|
|
64
|
+
if len(parts) == 2 and parts[1].isdigit():
|
|
65
|
+
return int(parts[1])
|
|
66
|
+
except OSError:
|
|
67
|
+
return None
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _parse_legacy_lstart(value: str) -> float | None:
|
|
72
|
+
"""Parse C-locale ``ps -o lstart=`` (``Wed Nov 18 06:16:50 2026``) without relying on LC_TIME."""
|
|
73
|
+
parts = value.split()
|
|
74
|
+
if len(parts) != 5 or parts[0] not in _ENGLISH_DAYS or parts[1] not in _ENGLISH_MONTHS:
|
|
75
|
+
return None
|
|
76
|
+
hms = parts[3].split(":")
|
|
77
|
+
if len(hms) != 3 or not (
|
|
78
|
+
parts[2].isdigit() and parts[4].isdigit() and all(p.isdigit() for p in hms)
|
|
79
|
+
):
|
|
80
|
+
return None
|
|
81
|
+
try:
|
|
82
|
+
year, month, day = int(parts[4]), _ENGLISH_MONTHS[parts[1]], int(parts[2])
|
|
83
|
+
hour, minute, second = int(hms[0]), int(hms[1]), int(hms[2])
|
|
84
|
+
if not (1 <= day <= 31 and 0 <= hour <= 23 and 0 <= minute <= 59 and 0 <= second <= 60):
|
|
85
|
+
return None
|
|
86
|
+
return time.mktime((year, month, day, hour, minute, second, 0, 0, -1))
|
|
87
|
+
except (OverflowError, ValueError):
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def same_start(current_started: str, saved_started: str, root: str = "/") -> bool:
|
|
92
|
+
"""Match exact boot ticks, or a pre-upgrade ``ps -o lstart=`` receipt within NTP btime jitter."""
|
|
93
|
+
if current_started == saved_started:
|
|
94
|
+
return True
|
|
95
|
+
if not current_started.isdigit():
|
|
96
|
+
return False
|
|
97
|
+
saved_epoch = _parse_legacy_lstart(saved_started)
|
|
98
|
+
if saved_epoch is None:
|
|
99
|
+
return False
|
|
100
|
+
try:
|
|
101
|
+
hz = os.sysconf("SC_CLK_TCK")
|
|
102
|
+
except (OSError, ValueError):
|
|
103
|
+
return False
|
|
104
|
+
btime = _boot_time(root)
|
|
105
|
+
if btime is None or hz <= 0:
|
|
106
|
+
return False
|
|
107
|
+
actual_epoch = btime + int(current_started) / hz
|
|
108
|
+
return abs(actual_epoch - saved_epoch) <= _LEGACY_LSTART_TOLERANCE_S
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
|
|
112
|
+
"""Read-only Linux ``/proc/<pid>/cmdline`` argv proof (including ``#!`` scripts)."""
|
|
113
|
+
try:
|
|
114
|
+
process = Path(root) / "proc" / str(pid)
|
|
115
|
+
if process.stat().st_uid != os.getuid():
|
|
116
|
+
return False
|
|
117
|
+
actual = process.joinpath("cmdline").read_bytes().decode().rstrip("\0").split("\0")
|
|
118
|
+
if actual == expected:
|
|
119
|
+
return True
|
|
120
|
+
target = expected[0] if root == "/" else Path(root) / expected[0].lstrip("/")
|
|
121
|
+
with open(target, "rb") as executable:
|
|
122
|
+
header = executable.readline(512).decode()
|
|
123
|
+
if not header.startswith("#!"):
|
|
124
|
+
return False
|
|
125
|
+
interp = shlex.split(header[2:].strip())
|
|
126
|
+
if interp[:1] == ["/usr/bin/env"]:
|
|
127
|
+
interp = interp[1:]
|
|
128
|
+
if len(interp) != 1 or actual[1:] != expected:
|
|
129
|
+
return False
|
|
130
|
+
resolved = shutil.which(interp[0])
|
|
131
|
+
return (
|
|
132
|
+
resolved is not None and process.joinpath("exe").resolve() == Path(resolved).resolve()
|
|
133
|
+
)
|
|
134
|
+
except (OSError, ValueError, UnicodeError, IndexError):
|
|
135
|
+
return False
|
|
@@ -6,8 +6,16 @@ proved its creation time. stdlib only (ctypes); every function needs Windows.
|
|
|
6
6
|
from __future__ import annotations
|
|
7
7
|
|
|
8
8
|
import ctypes
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
9
12
|
|
|
10
|
-
|
|
13
|
+
try:
|
|
14
|
+
from localmodels import process_identity
|
|
15
|
+
except ImportError: # run as a bare file beside service_probe
|
|
16
|
+
import process_identity # type: ignore[import-not-found,no-redef]
|
|
17
|
+
|
|
18
|
+
WINDOWS_DEPLOYMENTS = "~/.local/share/localmodels/deployments" # deploy.DEFAULT_BASE_DIR's
|
|
11
19
|
|
|
12
20
|
|
|
13
21
|
def own_pids() -> list[int]:
|
|
@@ -84,3 +92,144 @@ def terminate(pid: int, started: str) -> bool:
|
|
|
84
92
|
return True
|
|
85
93
|
finally:
|
|
86
94
|
kernel.CloseHandle(handle)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def windows_tree_pids(root_pid: int) -> list[int]:
|
|
98
|
+
"""Windows: ``root_pid`` followed by its verified same-user descendant PIDs (BFS).
|
|
99
|
+
A launcher such as ``strata_poly_server.py`` is the recorded PID while its child
|
|
100
|
+
``strata-poly.exe`` holds the GPU and memory. Creation timestamps reject recycled PIDs;
|
|
101
|
+
falls back to ``[root_pid]`` off Windows or when the snapshot is unavailable."""
|
|
102
|
+
if not process_identity._windows() or root_pid <= 0:
|
|
103
|
+
return [root_pid]
|
|
104
|
+
try:
|
|
105
|
+
root = process_identity.inspect(root_pid)
|
|
106
|
+
if root is None or root["uid"] != 0:
|
|
107
|
+
return [root_pid]
|
|
108
|
+
parents = process_identity._parent_pids()
|
|
109
|
+
except (OSError, AttributeError):
|
|
110
|
+
return [root_pid]
|
|
111
|
+
children_of: dict[int, list[int]] = {}
|
|
112
|
+
for child, parent in parents.items():
|
|
113
|
+
if child > 4 and parent > 0:
|
|
114
|
+
children_of.setdefault(parent, []).append(child)
|
|
115
|
+
tree: list[int] = [root_pid]
|
|
116
|
+
seen: set[int] = {root_pid}
|
|
117
|
+
queue: list[tuple[int, int]] = [(root_pid, int(root["started"]))]
|
|
118
|
+
while queue:
|
|
119
|
+
cur, cur_started = queue.pop(0)
|
|
120
|
+
for child in sorted(children_of.get(cur, ())):
|
|
121
|
+
if child in seen:
|
|
122
|
+
continue
|
|
123
|
+
seen.add(child)
|
|
124
|
+
try:
|
|
125
|
+
found = process_identity.inspect(child)
|
|
126
|
+
except (OSError, AttributeError):
|
|
127
|
+
continue
|
|
128
|
+
if found is None or found["uid"] != 0 or int(found["started"]) < cur_started:
|
|
129
|
+
continue
|
|
130
|
+
tree.append(child)
|
|
131
|
+
queue.append((child, int(found["started"])))
|
|
132
|
+
return tree
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _state_receipts() -> list[Path]:
|
|
136
|
+
"""``server.pid`` paths named by local deployment records under ``LOCALMODELS_STATE``."""
|
|
137
|
+
state = os.path.expanduser(os.environ.get("LOCALMODELS_STATE", "~/.local/state/localmodels"))
|
|
138
|
+
records = Path(state) / "deployments" / "local"
|
|
139
|
+
found: list[Path] = []
|
|
140
|
+
try:
|
|
141
|
+
entries = list(records.glob("*.json"))[:256]
|
|
142
|
+
except OSError:
|
|
143
|
+
return found
|
|
144
|
+
for path in entries:
|
|
145
|
+
try:
|
|
146
|
+
if not path.is_file() or path.is_symlink():
|
|
147
|
+
continue
|
|
148
|
+
directory = json.loads(path.read_text(encoding="utf-8"))["plan"]["service"][
|
|
149
|
+
"deploy_dir"
|
|
150
|
+
]
|
|
151
|
+
if isinstance(directory, str) and directory:
|
|
152
|
+
found.append(Path(os.path.expanduser(directory), "server.pid"))
|
|
153
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
154
|
+
continue
|
|
155
|
+
return found
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _receipt_roots(deployments: str) -> dict[int, str]:
|
|
159
|
+
"""{PID: creation timestamp} of active, same-user Windows nohup deployment receipts."""
|
|
160
|
+
candidates: list[Path] = []
|
|
161
|
+
try:
|
|
162
|
+
candidates.extend(Path(os.path.expanduser(deployments)).glob("*/server.pid"))
|
|
163
|
+
except OSError:
|
|
164
|
+
pass
|
|
165
|
+
if deployments == WINDOWS_DEPLOYMENTS:
|
|
166
|
+
candidates.extend(_state_receipts())
|
|
167
|
+
active: dict[int, str] = {}
|
|
168
|
+
for receipt in dict.fromkeys(candidates):
|
|
169
|
+
state, active_pid = process_identity.status(receipt)
|
|
170
|
+
if state != "active" or active_pid is None:
|
|
171
|
+
continue
|
|
172
|
+
try:
|
|
173
|
+
info = process_identity.inspect(active_pid)
|
|
174
|
+
except OSError:
|
|
175
|
+
continue
|
|
176
|
+
if info is not None and info["uid"] == 0:
|
|
177
|
+
active[active_pid] = info["started"]
|
|
178
|
+
return active
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _ancestor_owned(
|
|
182
|
+
pid: int, original: process_identity.Identity, roots: dict[int, str]
|
|
183
|
+
) -> bool | None:
|
|
184
|
+
"""Walk Windows parent PIDs up to an active receipt, rejecting recycled PIDs and drift."""
|
|
185
|
+
try:
|
|
186
|
+
parents = process_identity._parent_pids()
|
|
187
|
+
except OSError:
|
|
188
|
+
return None
|
|
189
|
+
chain: list[tuple[int, process_identity.Identity]] = [(pid, original)]
|
|
190
|
+
cur, cur_id = pid, original
|
|
191
|
+
seen = {pid}
|
|
192
|
+
for _ in range(16):
|
|
193
|
+
parent = parents.get(cur)
|
|
194
|
+
if not parent or parent <= 4 or parent in seen:
|
|
195
|
+
return False
|
|
196
|
+
seen.add(parent)
|
|
197
|
+
try:
|
|
198
|
+
parent_id = process_identity.inspect(parent)
|
|
199
|
+
except PermissionError:
|
|
200
|
+
return False
|
|
201
|
+
except OSError:
|
|
202
|
+
return None
|
|
203
|
+
if parent_id is None or parent_id["uid"] != 0:
|
|
204
|
+
return False
|
|
205
|
+
if int(parent_id["started"]) > int(cur_id["started"]):
|
|
206
|
+
return False # parent PID was reused after cur started
|
|
207
|
+
chain.append((parent, parent_id))
|
|
208
|
+
if roots.get(parent) == parent_id["started"]:
|
|
209
|
+
try:
|
|
210
|
+
return all(process_identity.inspect(p) == saved for p, saved in chain)
|
|
211
|
+
except OSError:
|
|
212
|
+
return False
|
|
213
|
+
cur, cur_id = parent, parent_id
|
|
214
|
+
return False
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def windows_owned(pid: int, deployments: str = WINDOWS_DEPLOYMENTS) -> bool | None:
|
|
218
|
+
"""Windows: a live receipt of one of this user's nohup deployments names the process or
|
|
219
|
+
a verified same-user ancestor (e.g. ``strata_poly_server.py`` -> ``strata-poly.exe``)."""
|
|
220
|
+
try:
|
|
221
|
+
original = process_identity.inspect(pid)
|
|
222
|
+
except PermissionError:
|
|
223
|
+
return False # protected or elevated process of another token: never this user's
|
|
224
|
+
except OSError:
|
|
225
|
+
return None
|
|
226
|
+
if original is None:
|
|
227
|
+
return None
|
|
228
|
+
if original["uid"] != 0:
|
|
229
|
+
return False
|
|
230
|
+
roots = _receipt_roots(deployments)
|
|
231
|
+
if not roots:
|
|
232
|
+
return False
|
|
233
|
+
if roots.get(pid) == original["started"]:
|
|
234
|
+
return True
|
|
235
|
+
return _ancestor_owned(pid, original, roots)
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import functools
|
|
6
|
+
import os
|
|
6
7
|
from pathlib import Path
|
|
7
8
|
from typing import Any
|
|
8
9
|
|
|
@@ -28,6 +29,9 @@ def api() -> tuple[Any, Any]:
|
|
|
28
29
|
"GetSecurityDescriptorDacl": [pointer, int_ptr, out, int_ptr],
|
|
29
30
|
"GetSecurityDescriptorControl": [pointer, ushort_ptr, uint_ptr],
|
|
30
31
|
"GetAce": [pointer, integer, out],
|
|
32
|
+
"GetSecurityInfo": [pointer, integer, integer, out, out, out, out, out],
|
|
33
|
+
"CreateWellKnownSid": [integer, pointer, pointer, uint_ptr],
|
|
34
|
+
"CheckTokenMembership": [pointer, pointer, int_ptr],
|
|
31
35
|
}
|
|
32
36
|
for name, arguments in signatures.items():
|
|
33
37
|
function = getattr(advapi, name)
|
|
@@ -70,6 +74,102 @@ def identity() -> tuple[Any, Any, Any, Any, str]:
|
|
|
70
74
|
kernel.CloseHandle(token)
|
|
71
75
|
|
|
72
76
|
|
|
77
|
+
@functools.lru_cache(maxsize=1)
|
|
78
|
+
def is_administrator() -> bool:
|
|
79
|
+
"""Whether this process's user is in BUILTIN\\Administrators, enabled in its token or in the
|
|
80
|
+
UAC-linked elevated token: the same administrator who installed elevated, now resuming from a
|
|
81
|
+
normal (filtered) desktop session."""
|
|
82
|
+
import ctypes
|
|
83
|
+
|
|
84
|
+
advapi, kernel = api()
|
|
85
|
+
administrators = ctypes.create_string_buffer(68) # SECURITY_MAX_SID_SIZE
|
|
86
|
+
size = ctypes.c_uint(ctypes.sizeof(administrators))
|
|
87
|
+
# WinBuiltinAdministratorsSid (26)
|
|
88
|
+
if not advapi.CreateWellKnownSid(26, None, administrators, ctypes.byref(size)):
|
|
89
|
+
raise ValueError("Cannot construct the Administrators SID")
|
|
90
|
+
|
|
91
|
+
def member(token: Any) -> bool:
|
|
92
|
+
found = ctypes.c_int()
|
|
93
|
+
if not advapi.CheckTokenMembership(token, administrators, ctypes.byref(found)):
|
|
94
|
+
raise ValueError("Cannot check Administrators membership")
|
|
95
|
+
return bool(found.value)
|
|
96
|
+
|
|
97
|
+
if member(None):
|
|
98
|
+
return True
|
|
99
|
+
token = ctypes.c_void_p()
|
|
100
|
+
if not advapi.OpenProcessToken(kernel.GetCurrentProcess(), 0x8, ctypes.byref(token)):
|
|
101
|
+
raise ValueError("Cannot query the process token")
|
|
102
|
+
try:
|
|
103
|
+
elevation, returned = ctypes.c_uint(), ctypes.c_uint()
|
|
104
|
+
# TokenElevationType (18): TokenElevationTypeLimited (3) is the filtered half of a UAC pair.
|
|
105
|
+
if not advapi.GetTokenInformation(
|
|
106
|
+
token, 18, ctypes.byref(elevation), ctypes.sizeof(elevation), ctypes.byref(returned)
|
|
107
|
+
):
|
|
108
|
+
raise ValueError("Cannot query the token elevation type")
|
|
109
|
+
if elevation.value != 3:
|
|
110
|
+
return False
|
|
111
|
+
linked = ctypes.c_void_p()
|
|
112
|
+
# TokenLinkedToken (19)
|
|
113
|
+
if not advapi.GetTokenInformation(
|
|
114
|
+
token, 19, ctypes.byref(linked), ctypes.sizeof(linked), ctypes.byref(returned)
|
|
115
|
+
):
|
|
116
|
+
raise ValueError("Cannot query the linked elevated token")
|
|
117
|
+
try:
|
|
118
|
+
return member(linked)
|
|
119
|
+
finally:
|
|
120
|
+
kernel.CloseHandle(linked)
|
|
121
|
+
finally:
|
|
122
|
+
kernel.CloseHandle(token)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def open_unfollowed(path: Path) -> int:
|
|
126
|
+
"""A read-only descriptor for ``path`` itself, never a link or junction's target, so its
|
|
127
|
+
attributes, owner and bytes all come from one object. Others may still replace or delete the
|
|
128
|
+
path meanwhile. FileNotFoundError when it is missing."""
|
|
129
|
+
import importlib
|
|
130
|
+
|
|
131
|
+
winapi: Any = importlib.import_module("_winapi")
|
|
132
|
+
msvcrt: Any = importlib.import_module("msvcrt")
|
|
133
|
+
# FILE_SHARE_READ | FILE_SHARE_DELETE; FILE_FLAG_OPEN_REPARSE_POINT. The handle is not
|
|
134
|
+
# inheritable (no security attributes).
|
|
135
|
+
handle = winapi.CreateFile(
|
|
136
|
+
str(path), winapi.GENERIC_READ, 0x1 | 0x4, winapi.NULL, winapi.OPEN_EXISTING, 0x00200000, 0
|
|
137
|
+
)
|
|
138
|
+
try:
|
|
139
|
+
return int(msvcrt.open_osfhandle(handle, os.O_RDONLY))
|
|
140
|
+
except OSError:
|
|
141
|
+
winapi.CloseHandle(handle)
|
|
142
|
+
raise
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def descriptor_owner_sid(fd: int) -> str:
|
|
146
|
+
"""The owner of the file open on ``fd``, as a string SID."""
|
|
147
|
+
import ctypes
|
|
148
|
+
import importlib
|
|
149
|
+
|
|
150
|
+
msvcrt: Any = importlib.import_module("msvcrt")
|
|
151
|
+
advapi, kernel = api()
|
|
152
|
+
owner, descriptor = ctypes.c_void_p(), ctypes.c_void_p()
|
|
153
|
+
try:
|
|
154
|
+
# SE_FILE_OBJECT (1), OWNER_SECURITY_INFORMATION (1)
|
|
155
|
+
error = advapi.GetSecurityInfo(
|
|
156
|
+
msvcrt.get_osfhandle(fd),
|
|
157
|
+
1,
|
|
158
|
+
0x1,
|
|
159
|
+
ctypes.byref(owner),
|
|
160
|
+
None,
|
|
161
|
+
None,
|
|
162
|
+
None,
|
|
163
|
+
ctypes.byref(descriptor),
|
|
164
|
+
)
|
|
165
|
+
if error:
|
|
166
|
+
raise OSError(error, "cannot read the file's owner")
|
|
167
|
+
return sid_text(advapi, kernel, owner)
|
|
168
|
+
finally:
|
|
169
|
+
if descriptor.value:
|
|
170
|
+
kernel.LocalFree(descriptor)
|
|
171
|
+
|
|
172
|
+
|
|
73
173
|
def private_permissions(path: Path, created: bool) -> None:
|
|
74
174
|
"""Query owner/DACL only; protect a newly created DACL without changing owner/group/SACL."""
|
|
75
175
|
import ctypes
|