文件
fnos-apfs/application/service.py
T

59 行
1.9 KiB
Python

"""fnOS lifecycle controller. Stops only the two service processes, not copy jobs."""
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parent
VAR = Path(os.environ['TRIM_PKGVAR'])
STATE = VAR / 'services.json'
def alive(pid, script):
try:
return str(ROOT / script).encode() in (Path('/proc') / str(pid) / 'cmdline').read_bytes()
except OSError:
return False
def main():
action = sys.argv[1]
VAR.mkdir(parents=True, exist_ok=True)
os.chown(VAR, 0, int(os.environ['TRIM_GID']))
VAR.chmod(0o750)
records = json.loads(STATE.read_text()) if STATE.exists() else {}
if action == 'status':
raise SystemExit(0 if all(alive(records.get(name, -1), name) for name in ('broker.py', 'front.py')) else 3)
if action == 'stop':
for script, pid in records.items():
if alive(pid, script):
os.kill(pid, signal.SIGTERM)
for _ in range(30):
if not any(alive(pid, script) for script, pid in records.items()):
break
time.sleep(.1)
STATE.unlink(missing_ok=True)
return
if action != 'start':
raise SystemExit(1)
for script in ('broker.py', 'front.py'):
if alive(records.get(script, -1), script):
continue
with (VAR / 'service.log').open('ab') as log:
process = subprocess.Popen(['/usr/bin/python3', str(ROOT / script)],
stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
records[script] = process.pid
STATE.write_text(json.dumps(records))
for _ in range(50):
if (ROOT / 'app.sock').exists() and (VAR / 'broker.sock').exists():
return
time.sleep(.1)
raise SystemExit('服务启动失败,请查看应用日志')
if __name__ == '__main__':
main()