Spaces:
Running
Running
| #!/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()) | |