okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 7726f80cb (local, 11-10 14:08) into f-own-int714ff8242

main
19.7 KiB454 linesraw
1"""Which processes Strata started, and how to tell one of them from a stranger.
2
3Every engine, image encoder and server that Strata starts leaves a small private record: its PID, the time it
4started, its command line, and the same two things for the process that started it. When that parent is gone and
5the child is still running, the child is a leftover. A leftover is ended only when ALL of these still hold at the
6moment of the signal:
7
8* the process at that PID started at the recorded time (a later process that reused the number does not match);
9* its command line is the recorded one (PID reuse plus the same start time is not possible, but this is also what
10  makes an unrelated program impossible to hit by a corrupted record);
11* the recorded parent is not running as that same process.
12
13A PID that is only a number is never signalled. If the identity of a process cannot be read (no command line on
14this platform and no psutil), it is left alone and reported.
15
16Also here: the one-time check for engines left by earlier Strata versions, which wrote no record: an orphan of
17exactly the engine executable that is about to be started, running ``--serve`` with no live parent.
18"""
19
20from __future__ import annotations
21
22from strata_control.private_files import private_mkdir as _private_mkdir
23import json
24import os
25import signal
26import subprocess
27import sys
28import time
29from dataclasses import dataclass
30from pathlib import Path
31
32from strata_control import paths
33from strata_control import atomic as _atomic_mod
34
35WINDOWS = os.name == "nt"
36SCHEMA = 1
37INIT_NAMES = {"systemd", "init", "launchd", "upstart"}     # parents that adopt orphans
38
39try:  # psutil ships in every Strata runtime (requirements.txt, the Control lock files)
40    import psutil
41except ImportError:  # pragma: no cover - the Linux /proc fallback below still identifies processes
42    psutil = None
43
44
45# ---------------------------------------------------------------------------------------------- identity
46
47def start_token(pid: int) -> str | None:
48    """A string that is the same for the lifetime of one process and different for a later process with the same
49    PID. None when there is no such process or its start cannot be read."""
50    if type(pid) is not int or pid <= 0:
51        return None
52    if sys.platform.startswith("linux"):
53        try:
54            raw = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace")
55            fields = raw[raw.rindex(")") + 2:].split()
56            if fields[0] == "Z":                       # a zombie has exited; only its parent has not collected it
57                return None
58            return "l:" + fields[19]                   # starttime, clock ticks since boot (field 22)
59        except (OSError, ValueError, IndexError):
60            return None
61    if WINDOWS:
62        from strata_control import winproc
63        started = winproc.process_started(pid)
64        return None if started is None else f"w:{started}"
65    if psutil is not None:
66        try:
67            p = psutil.Process(pid)
68            if p.status() == psutil.STATUS_ZOMBIE:
69                return None
70            return f"p:{p.create_time():.3f}"
71        except (psutil.Error, OSError):
72            return None
73    try:
74        out = subprocess.run(["ps", "-o", "lstart=,stat=", "-p", str(pid)], capture_output=True, text=True,
75                             timeout=5).stdout.strip()
76    except (OSError, subprocess.SubprocessError):
77        return None
78    return None if not out or out.endswith("Z") else "s:" + out.rsplit(None, 1)[0]
79
80
81def started_epoch(pid: int) -> float | None:
82    """When the process at `pid` was created, in seconds since 1970, or None when there is no such process or the time cannot be read.
83    A number recorded in an old file can belong to a later process; a creation time after the file was written proves it does."""
84    if type(pid) is not int or pid <= 0:
85        return None
86    if psutil is not None:
87        try:
88            return float(psutil.Process(pid).create_time())
89        except (psutil.Error, OSError):
90            return None
91    if WINDOWS:
92        from strata_control import winproc
93        ticks = winproc.process_started(pid)
94        return None if ticks is None else (ticks - 116444736000000000) / 1e7     # 100 ns ticks since 1601
95    if sys.platform.startswith("linux"):
96        token = start_token(pid)
97        try:
98            boot = next(int(line.split()[1]) for line in Path("/proc/stat").read_text().splitlines() if line.startswith("btime "))
99            return boot + int(token[2:]) / os.sysconf("SC_CLK_TCK") if token else None
100        except (OSError, ValueError, StopIteration):
101            return None
102    return None
103
104
105def command_line(pid: int) -> list[str] | None:
106    """The process's argv, or None when it cannot be read (then it is never treated as a match)."""
107    if sys.platform.startswith("linux"):
108        try:
109            raw = Path(f"/proc/{pid}/cmdline").read_bytes()
110            return [part.decode("utf-8", "replace") for part in raw.split(b"\0") if part] or None
111        except OSError:
112            return None
113    if psutil is not None:
114        try:
115            return list(psutil.Process(pid).cmdline()) or None
116        except (psutil.Error, OSError):
117            return None
118    if not WINDOWS:
119        try:
120            out = subprocess.run(["ps", "-o", "command=", "-p", str(pid)], capture_output=True, text=True,
121                                 timeout=5).stdout.strip()
122        except (OSError, subprocess.SubprocessError):
123            return None
124        return out.split() or None
125    return None
126
127
128def parent_of(pid: int) -> int | None:
129    if sys.platform.startswith("linux"):
130        try:
131            raw = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace")
132            return int(raw[raw.rindex(")") + 2:].split()[1])
133        except (OSError, ValueError, IndexError):
134            return None
135    if psutil is not None:
136        try:
137            return psutil.Process(pid).ppid()
138        except (psutil.Error, OSError):
139            return None
140    return None
141
142
143def exe_path(pid: int) -> str | None:
144    if sys.platform.startswith("linux"):
145        try:
146            return os.readlink(f"/proc/{pid}/exe")
147        except OSError:
148            return None
149    if psutil is not None:
150        try:
151            return psutil.Process(pid).exe() or None
152        except (psutil.Error, OSError):
153            return None
154    return None
155
156
157def same_file(a: str | None, b: str | None) -> bool:
158    if not a or not b:
159        return False
160    try:
161        return os.path.samefile(a, b)
162    except OSError:
163        return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b))
164
165
166@dataclass(frozen=True)
167class Ident:
168    pid: int
169    token: str
170    cmd: tuple[str, ...]
171
172
173def identify(pid: int) -> Ident | None:
174    """The live process at `pid`, with the facts a record is later compared with."""
175    token = start_token(pid)
176    cmd = command_line(pid)
177    if token is None or not cmd:
178        return None
179    return Ident(pid, token, tuple(cmd))
180
181
182def is_same(pid: int, token: str, cmd: list[str] | tuple[str, ...] | None) -> bool:
183    """True only when the process now at `pid` started at `token` and runs exactly `cmd`."""
184    if start_token(pid) != token:
185        return False
186    now = command_line(pid)
187    return bool(now) and list(now) == list(cmd or [])
188
189
190# ---------------------------------------------------------------------------------------------- records
191
192def procs_dir(create: bool = True) -> Path:
193    """The owner-private folder of launch records (beside runtime/, under the per-user state)."""
194    base = paths.state_base() / "procs"
195    if create and not base.exists():
196        _private_mkdir(base, parents=True, exist_ok=True)
197        if WINDOWS:
198            from strata_control import private_files
199            private_files.restrict_to_current_user(base, directory=True)
200    return base
201
202
203def write_record(pid: int, role: str, *, profile: str | None = None, cmd: list[str] | None = None,
204                 parent_pid: int | None = None) -> str | None:
205    """Record that this process started `pid`; returns the process's start token (None: nothing was written).
206    Best effort: a record that cannot be written never stops a launch."""
207    try:
208        token = start_token(pid)
209        command = list(cmd) if cmd else command_line(pid)
210        parent_pid = os.getpid() if parent_pid is None else parent_pid
211        parent_token = start_token(parent_pid)
212        if token is None or not command or parent_token is None:
213            return None
214        record = {"schema": SCHEMA, "pid": pid, "token": token, "cmd": command, "role": role,
215                  "profile": profile, "parent": {"pid": parent_pid, "token": parent_token},
216                  "written_at": time.time()}
217        path = procs_dir() / f"{pid}.json"
218        tmp = path.with_suffix(f".{os.getpid()}.tmp")
219        tmp.write_text(json.dumps(record), encoding="utf-8")
220        _atomic_mod.replace(tmp, path)
221        return token
222    except (OSError, ValueError):
223        return None
224
225
226def drop_record(pid: int, token: str | None = None) -> None:
227    """Delete the record of `pid`; with `token`, only if it is the record of that process (not of a later one)."""
228    path = procs_dir(create=False) / f"{pid}.json"
229    try:
230        if token is not None:
231            record = _load(path)
232            if record is None or record["token"] != token:
233                return
234        path.unlink(missing_ok=True)
235    except OSError:
236        pass
237
238
239def _load(path: Path) -> dict | None:
240    try:
241        if path.stat().st_size > 16 * 1024:
242            return None
243        record = json.loads(path.read_text(encoding="utf-8"))
244    except (OSError, ValueError):
245        return None
246    ok = (isinstance(record, dict) and record.get("schema") == SCHEMA and type(record.get("pid")) is int and
247          isinstance(record.get("token"), str) and isinstance(record.get("cmd"), list) and
248          all(isinstance(part, str) for part in record["cmd"]) and isinstance(record.get("parent"), dict) and
249          type(record["parent"].get("pid")) is int and isinstance(record["parent"].get("token"), str))
250    return record if ok else None
251
252
253def records(profile: str | None = None) -> list[dict]:
254    base = procs_dir(create=False)
255    if not base.is_dir():
256        return []
257    found = []
258    for path in sorted(base.glob("*.json")):
259        record = _load(path)
260        if record is None:
261            continue
262        if profile is None or record.get("profile") == profile:
263            found.append(record)
264    return found
265
266
267# ---------------------------------------------------------------------------------------------- leftovers
268
269def leftovers(profile: str | None = None, *, forget_stale: bool = True) -> tuple[list[dict], list[dict]]:
270    """(to_end, unverifiable). `to_end`: recorded processes that still run as exactly what was recorded whose
271    parent is no longer that process. Records of processes that have gone, or whose PID now belongs to something
272    else, are deleted (when `forget_stale`); the stranger is not touched. `unverifiable`: still running but their
273    command line cannot be read here, so they are reported and left alone."""
274    to_end, unverifiable = [], []
275    for record in records(profile):
276        pid = record["pid"]
277        token = start_token(pid)
278        if token is None or token != record["token"]:
279            if forget_stale:
280                drop_record(pid)
281            continue
282        parent = record["parent"]
283        if start_token(parent["pid"]) == parent["token"]:
284            continue                                  # its starter is still there: not a leftover
285        if is_same(pid, record["token"], record["cmd"]):
286            to_end.append(record)
287        elif command_line(pid) is None:
288            unverifiable.append(record)
289        elif forget_stale:
290            drop_record(pid)                          # same start time, different command line: not ours
291    return to_end, unverifiable
292
293
294def _signal_verified(record: dict, sig: int) -> bool:
295    """Signal the recorded process, but only if it is still the recorded process at this instant."""
296    if not is_same(record["pid"], record["token"], record["cmd"]):
297        return False
298    try:
299        os.kill(record["pid"], sig)
300    except (ProcessLookupError, PermissionError):
301        return False
302    return True
303
304
305def end_one(record: dict, *, grace: float = 8.0, settle: float = 10.0, say=None) -> str:
306    """End one verified leftover: a polite signal where the OS has one, then a kill after `grace` seconds, then up to
307    `settle` seconds for it to be gone (#4051: an engine holding tens of GB of pinned memory can take longer than the
308    10 s that were enough for a small process; `say` is told every ~10 s while it is waited for).
309    Returns 'gone' (already not running), 'ended' or 'stuck'."""
310    pid = record["pid"]
311    if not is_same(pid, record["token"], record["cmd"]):
312        drop_record(pid)
313        return "gone"
314    # once signalled, the start token alone says it still runs: an exiting process has an empty command line on Linux
315    def running():
316        return start_token(pid) == record["token"]
317    if not WINDOWS:
318        _signal_verified(record, signal.SIGTERM)
319        deadline = time.monotonic() + grace
320        while time.monotonic() < deadline and running():
321            time.sleep(0.1)
322        if is_same(pid, record["token"], record["cmd"]):
323            _signal_verified(record, signal.SIGKILL)
324    else:
325        if is_same(pid, record["token"], record["cmd"]):
326            subprocess.run(["taskkill", "/F", "/PID", str(pid)], capture_output=True)      # one PID, verified just above
327    started = time.monotonic()
328    deadline = started + settle
329    told = 0
330    while time.monotonic() < deadline and running():
331        time.sleep(0.1)
332        waited = int((time.monotonic() - started) // 10)
333        if say is not None and waited > told:
334            told = waited
335            say(f"[strata] still waiting for process {pid} to give its memory back ({told * 10} s)")
336    if running():
337        return "stuck"
338    drop_record(pid)
339    return "ended"
340
341
342def end_leftovers(profile: str | None = None, *, grace: float = 8.0, settle: float = 10.0, say=None) -> dict:
343    """End every verified leftover (children first: a record whose parent is itself a leftover goes last)."""
344    to_end, unverifiable = leftovers(profile)
345    children_first = sorted(to_end, key=lambda r: r["written_at"], reverse=True)
346    result = {"ended": [], "gone": [], "stuck": [], "unverifiable": [
347        {"pid": r["pid"], "role": r.get("role")} for r in unverifiable]}
348    for record in children_first:
349        outcome = end_one(record, grace=grace, settle=settle, say=say)
350        result[outcome].append({"pid": record["pid"], "role": record.get("role"), "profile": record.get("profile")})
351        if say is not None and outcome != "gone":
352            say(f"[strata] leftover {record.get('role', 'process')} {record['pid']} {outcome}")
353    return result
354
355
356# ---------------------------------------------------------------------------- engines older versions left
357
358def _short_name(path: str) -> str | None:
359    """The 8.3 name Windows gives the file at `path` (None where there is none or it cannot be read)."""
360    try:
361        import ctypes
362        buf = ctypes.create_unicode_buffer(32768)
363        n = ctypes.windll.kernel32.GetShortPathNameW(str(path), buf, len(buf))
364        return os.path.basename(buf.value) if 0 < n < len(buf) else None
365    except (AttributeError, OSError, ValueError):
366        return None
367
368
369def _name_may_be(name: str, base: str, short: str | None) -> bool:
370    """Could a process whose image name is `name` be the engine file `base`?  Loose on purpose (same_file decides): the same name in
371    any case, the file's own 8.3 name, or any 8.3-looking name (STEM~N.EXT) whose stem starts the engine's name."""
372    n = name.lower()
373    if n == base or (short is not None and n == short):
374        return True
375    stem = n.split("~", 1)[0] if "~" in n else ""
376    return bool(stem) and base.replace(" ", "").startswith(stem)
377
378
379def _engine_candidates(engine_exe: str):
380    """psutil processes (with info pid, ppid, cmdline, create_time) that could be `engine_exe`.
381
382    Windows: reading a command line costs 30-150 ms for each protected process that refuses it (svchost, lsass ...): over 250 processes
383    that was 4-9 s at every server start. So the names come first (cheap) and only a process whose image name can be the engine's
384    file is read in full; a process whose name cannot be read is read in full as before. Elsewhere every process is read, as before
385    (a Linux name is the 15-character comm and can be a link's name)."""
386    full = ["pid", "ppid", "cmdline", "create_time"]
387    if not WINDOWS:
388        yield from psutil.process_iter(full)
389        return
390    import ntpath                                       # Windows path rules (os.path there; named so the tests can run elsewhere)
391    base = ntpath.basename(str(engine_exe)).lower()
392    short = (_short_name(engine_exe) or "").lower() or None
393    for p in psutil.process_iter(["pid", "name"]):
394        name = p.info.get("name")
395        if name and not _name_may_be(name, base, short):
396            continue
397        try:
398            p.info = p.as_dict(attrs=full)
399        except (psutil.Error, OSError):
400            continue
401        yield p
402
403
404def orphans_of(engine_exe: str) -> list[Ident]:
405    """Processes that are exactly this engine executable, running ``--serve``, whose parent no longer exists.
406
407    Earlier Strata versions wrote no record. Such an engine is not a service anybody started on purpose: the
408    server that owned it is gone, and it holds the GPU. Only the executable that is about to be started is
409    matched, never another installation's, and a process whose parent is alive is never an orphan."""
410    if psutil is None or not engine_exe:
411        return []
412    mine = {os.getpid()}
413    try:
414        # pid 1 and a subreaper such as `systemd --user` (an ancestor of every desktop terminal) adopt orphans: they are not starters
415        mine.update(q.pid for q in psutil.Process().parents() if q.pid != 1 and q.name().lower() not in INIT_NAMES)
416    except psutil.Error:
417        pass
418    found = []
419    for p in _engine_candidates(engine_exe):
420        try:
421            cmd = p.info.get("cmdline") or []
422            if "--serve" not in cmd or p.pid in mine:
423                continue
424            if not same_file(p.exe(), engine_exe):
425                continue
426            parent = p.info.get("ppid")
427            if parent in mine:
428                continue                              # started by this server (or by a process above it)
429            if parent and parent != 1:
430                try:
431                    q = psutil.Process(parent)
432                    adopted = q.name().lower() in INIT_NAMES      # an init that adopts orphans did not start it
433                    if not adopted and q.create_time() <= p.info["create_time"] + 1.0                             and q.status() != psutil.STATUS_ZOMBIE:
434                        continue                      # a live parent started it: not an orphan
435                except psutil.NoSuchProcess:
436                    pass
437            ident = identify(p.pid)
438            if ident is not None:
439                found.append(ident)
440        except (psutil.Error, OSError):
441            continue
442    return found
443
444
445def end_orphans(engine_exe: str, *, grace: float = 8.0, settle: float = 10.0, say=None) -> list[dict]:
446    """End the orphans of `engine_exe` (see `orphans_of`), re-verified one by one."""
447    ended = []
448    for ident in orphans_of(engine_exe):
449        record = {"pid": ident.pid, "token": ident.token, "cmd": list(ident.cmd), "role": "engine", "written_at": 0}
450        outcome = end_one(record, grace=grace, settle=settle, say=say)
451        ended.append({"pid": ident.pid, "outcome": outcome})
452        if say is not None and outcome != "gone":
453            say(f"[strata] an engine left behind by an earlier run (pid {ident.pid}) {outcome}")
454    return ended