File size: 2,124 Bytes
e317359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
"""Start/stop only this checkout's daemon; retain the lock inode across restarts."""

from __future__ import annotations
import os
from pathlib import Path
import signal
import subprocess
import sys
import time

ROOT = Path(__file__).resolve().parents[1]
PID_FILE = ROOT / ".daemon.pid"


def owned_process(pid: int, root: Path = ROOT) -> bool:
    result = subprocess.run(
        ["ps", "-p", str(pid), "-o", "command="], capture_output=True, text=True
    )
    return str(root / "scripts/run_online_daemon.py") in result.stdout


def main() -> int:
    action = sys.argv[1]
    pid = int(PID_FILE.read_text().strip()) if PID_FILE.exists() else None
    if action == "stop":
        if pid and owned_process(pid):
            os.kill(pid, signal.SIGTERM)
            for _ in range(30):
                if not owned_process(pid):
                    break
                time.sleep(1)
            else:
                raise SystemExit(
                    "Daemon has not stopped; inspect its log before restarting."
                )
            print(f"Stopped this checkout daemon ({pid}).")
        else:
            print("No running daemon owned by this checkout.")
        PID_FILE.unlink(missing_ok=True)
        return 0
    if pid and owned_process(pid):
        print(f"Already running ({pid}).")
        return 0
    (ROOT / "logs").mkdir(exist_ok=True)
    with (ROOT / "logs/online_daemon.log").open("a") as log:
        process = subprocess.Popen(
            [sys.executable, str(ROOT / "scripts/run_online_daemon.py"), *sys.argv[2:]],
            cwd=ROOT,
            stdin=subprocess.DEVNULL,
            stdout=log,
            stderr=log,
            start_new_session=True,
        )
    PID_FILE.write_text(f"{process.pid}\n")
    time.sleep(2)
    if process.poll() is not None:
        PID_FILE.unlink(missing_ok=True)
        print("Daemon exited; inspect logs/online_daemon.log.", file=sys.stderr)
        return 1
    print(f"Started ({process.pid}); logs/online_daemon.log; stop with ./stop.sh")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())