service.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. r"""服务注册/卸载/起停/状态 (2026-09-17 用户令 1: 观澜安装为服务)。
  4. Windows : Windows 服务 (SCM)。本器用 `sc.exe` 注册, 服务体是 `scripts\win_service.py`
  5. (ctypes 直连 SCM, 不依赖 pywin32 —— 保持"单包离线零新依赖")。
  6. Linux : systemd 单元 `guanlan.service`, 服务体是 `scripts/service_main.py` (前台守护)。
  7. ## 为什么要有 --dry-run 与前置检查
  8. 注册服务需要**管理员/root**;没有权限时最该做的是"把将要做的事说清楚",而不是抛一句 Access is denied。
  9. 所以本器的每个动作都先过一遍前置检查(权限 / .venv / 版本记录 / 端口),
  10. `--dry-run` 逐条打印将要执行的命令与实际会写的文件内容(systemd 单元全文),一条都不落。
  11. ## 用法
  12. python scripts/service_ctl.py status # 装没装 / 在跑没在跑(不需要权限)
  13. python scripts/service_ctl.py install --dry-run # 只打印: 前置检查 + 将执行的命令 + 单元文件
  14. python scripts/service_ctl.py install # 真注册(Windows 需管理员, Linux 需 root)
  15. python scripts/service_ctl.py start|stop|restart|uninstall
  16. # 注: Windows 的 sc.exe **没有 restart 子命令** ⇒ 本器的 restart = 停 → 等状态真的变 STOPPED → 起
  17. # (判据必须认 STOP_PENDING: 只看"不是 RUNNING"会抢跑, 紧接着 start 吃 1056)
  18. python scripts/service_ctl.py install --user-login # Windows 备选: 不用管理员的"登录自启(Run 键)"
  19. 退出码: 0 成功 · 2 前置条件不满足(如缺 .venv) · 3 权限不足 · 4 平台不支持 · 5 服务操作失败
  20. """
  21. from __future__ import annotations
  22. try:
  23. from app_common.app_common_guanlan.api import install_root as _install_root
  24. except ImportError: # 极端兜底(包结构异常时按位置上跳)
  25. from pathlib import Path as _P
  26. def _install_root(_f): return _P(_f).resolve().parents[3]
  27. import argparse
  28. import os
  29. import pathlib
  30. import subprocess
  31. import sys
  32. import time
  33. ROOT = _install_root(__file__)
  34. sys.path.insert(0, str(ROOT))
  35. from src import paths as P # noqa: E402
  36. from src import version as V # noqa: E402
  37. PY = None
  38. UNIT_PATH = pathlib.Path('/etc/systemd/system') / f'{V.SERVICE_NAME}.service'
  39. WIN32 = os.name == 'nt'
  40. def py_exe() -> str:
  41. global PY
  42. if PY is None:
  43. cand = P.venv_python()
  44. PY = str(cand if cand else sys.executable)
  45. return PY
  46. # ── 前置条件 ─────────────────────────────────────────────────────────────────────────
  47. def is_admin() -> bool:
  48. if not WIN32:
  49. return os.geteuid() == 0
  50. try:
  51. import ctypes
  52. return bool(ctypes.windll.shell32.IsUserAnAdmin())
  53. except Exception:
  54. return False
  55. def preflight() -> list[str]:
  56. """→ 问题清单(空 = 可以做)。每条都写成"人能照着解决"的一句话。"""
  57. bad = []
  58. if not (ROOT / 'guanlan.py').is_file():
  59. bad.append(f'安装根不对:{ROOT} 下没有 guanlan.py')
  60. if not pathlib.Path(py_exe()).is_file():
  61. bad.append(f'没找到虚拟环境解释器 {py_exe()} —— 先跑 install.bat / sh install.sh')
  62. if WIN32 and not (ROOT / 'scripts' / 'win_service.py').is_file():
  63. bad.append('缺 scripts\\win_service.py(服务体)')
  64. if not WIN32 and not (ROOT / 'scripts' / 'service_main.py').is_file():
  65. bad.append('缺 scripts/service_main.py(服务体)')
  66. return bad
  67. def unit_text() -> str:
  68. """systemd 单元全文(--dry-run 会原样打印;install 时写进 UNIT_PATH)。
  69. ★ 路径统一用 POSIX 写法并用引号包住(安装目录可能带空格:`/opt/guanlan app`),
  70. 否则 systemd 会把 `ExecStart=/opt/gu anlan/.venv/bin/python` 拆成两个参数。
  71. """
  72. root = pathlib.Path(ROOT).as_posix()
  73. py = pathlib.Path(py_exe()).as_posix()
  74. return f'''[Unit]
  75. Description={V.SERVICE_DISPLAY}
  76. Documentation=file://{root}/docs/系统设计说明.md
  77. After=network-online.target
  78. Wants=network-online.target
  79. [Service]
  80. Type=simple
  81. WorkingDirectory="{root}"
  82. ExecStart="{py}" "{root}/scripts/service_main.py"
  83. ExecStop="{py}" "{root}/guanlan.py" stop
  84. Restart=always
  85. RestartSec=10
  86. TimeoutStopSec=120
  87. KillMode=mixed
  88. # 组件只绑 127.0.0.1;要对外**不要改组件绑定** —— 改 configs/serve.json 的 public_host
  89. # (用户令 2026-09-19「观澜改为监听所有 IP」): 只让门户网关绑所有网卡, 组件照旧只本机。
  90. # 页面无鉴权 ⇒ 对外必须在防火墙侧限来源, 或走 nginx 反代加认证。
  91. Environment=PYTHONUTF8=1
  92. Environment=PYTHONUNBUFFERED=1
  93. [Install]
  94. WantedBy=multi-user.target
  95. '''
  96. def win_commands(action: str) -> list[list[str]]:
  97. """Windows 侧要执行的 sc.exe 命令(--dry-run 原样打印,install/start/... 真跑)。"""
  98. binpath = f'"{py_exe()}" "{ROOT / "scripts" / "win_service.py"}"'
  99. n = V.SERVICE_NAME
  100. if action == 'install':
  101. return [
  102. ['sc.exe', 'create', n, 'binPath=', binpath, 'start=', 'auto', 'DisplayName=', V.SERVICE_DISPLAY],
  103. ['sc.exe', 'description', n, f'{V.NAME} v{V.VERSION} 本机离线版(观澜风电资产智能)'],
  104. # 服务崩溃/被结束时的恢复策略: 60 s 后重启, 连续失败继续重启, 一天后重置计数
  105. ['sc.exe', 'failure', n, 'reset=', '86400', 'actions=', 'restart/60000/restart/60000/restart/60000'],
  106. ['sc.exe', 'start', n],
  107. ]
  108. if action == 'uninstall':
  109. return [['sc.exe', 'stop', n], ['sc.exe', 'delete', n]]
  110. if action == 'restart':
  111. # sc.exe 没有 restart 子命令(这是 Windows 与 systemd 的差异,2017 年就有定论);
  112. # 这里给"停 → 起"两条,真跑时用 win_restart() 在中间等停稳。
  113. return [['sc.exe', 'stop', n], ['sc.exe', 'start', n]]
  114. return [['sc.exe', action, n]]
  115. def win_state() -> str:
  116. """抓 `sc.exe query` 里的状态字:RUNNING / STOPPED / STOP_PENDING / START_PENDING / …
  117. ★ 必须连 PENDING 态一起认(2026-09-28 实逮):只看"不是 RUNNING"会把 **STOP_PENDING** 当成已停,
  118. 于是紧接着 `sc.exe start` 吃 1056(服务的一个实例已在运行)—— 远端服务就是这么被停掉的。
  119. """
  120. r = subprocess.run(['sc.exe', 'query', V.SERVICE_NAME], capture_output=True, text=True, errors='replace')
  121. txt = ((r.stdout or '') + (r.stderr or '')).upper()
  122. # 顺序要紧: 先认 *_PENDING, 再认稳态
  123. for s in ('STOP_PENDING', 'START_PENDING', 'CONTINUE_PENDING', 'PAUSE_PENDING', 'RUNNING', 'STOPPED', 'PAUSED'):
  124. if s in txt:
  125. return s
  126. return ''
  127. def wait_state(target: str, timeout: float = 120.0) -> bool:
  128. """轮询 SCM 直到状态字**等于** target(`sc.exe stop/start` 都是异步的,只回 *_PENDING)。"""
  129. end = time.time() + timeout
  130. while time.time() < end:
  131. if win_state() == target:
  132. return True
  133. time.sleep(2)
  134. return False
  135. def win_restart(dry: bool) -> int:
  136. """Windows 的 restart = 停 → 等真停稳 → 起(2.11.5 起两条命令自己拼, 2.11.6 收紧等待判据)。"""
  137. n = V.SERVICE_NAME
  138. if dry:
  139. rc = run_cmds([['sc.exe', 'stop', n]], True)
  140. print(' (真跑时在此等 SCM 报 STOPPED, 最长 120 s)')
  141. return run_cmds([['sc.exe', 'start', n]], True) or rc
  142. run_cmds([['sc.exe', 'stop', n]], dry) # 1062(本来就没在跑)不算错, 后面按状态判
  143. if not wait_state('STOPPED'):
  144. print(f' [X] 等待服务停止超时(120 s): 当前状态 {win_state() or "未知"}; '
  145. f'先 `sc.exe query {n}` 看状态, 必要时 taskkill /f /im python.exe 兜底')
  146. return 5
  147. print(' 已停稳(STOPPED), 重新启动 …')
  148. # start 偶发 1056/1058(SCM 状态刚刚落地)⇒ 给三次机会, 每次间隔 5 s
  149. for i in range(1, 4):
  150. rc = run_cmds([['sc.exe', 'start', n]], dry)
  151. if rc == 0:
  152. return 0
  153. print(f' 第 {i} 次 start 失败(rc={rc}), 等 5 s 再试 …')
  154. time.sleep(5)
  155. return rc
  156. def linux_commands(action: str) -> list[list[str]]:
  157. n = V.SERVICE_NAME
  158. if action == 'install':
  159. return [['systemctl', 'daemon-reload'], ['systemctl', 'enable', '--now', n],
  160. ['systemctl', 'status', n, '--no-pager']]
  161. if action == 'uninstall':
  162. return [['systemctl', 'disable', '--now', n], ['rm', '-f', str(UNIT_PATH)], ['systemctl', 'daemon-reload']]
  163. return [['systemctl', action, n]]
  164. def run_cmds(cmds: list[list[str]], dry: bool) -> int:
  165. rc = 0
  166. for c in cmds:
  167. printable = ' '.join(f'"{x}"' if ' ' in x else x for x in c)
  168. print(f' $ {printable}')
  169. if dry:
  170. continue
  171. try:
  172. r = subprocess.run(c, capture_output=True, text=True, errors='replace')
  173. except FileNotFoundError:
  174. print(f' [X] 找不到命令 {c[0]}')
  175. rc = 5
  176. continue
  177. for ln in (r.stdout or '').strip().splitlines():
  178. print(' ' + ln)
  179. for ln in (r.stderr or '').strip().splitlines():
  180. print(' [stderr] ' + ln)
  181. rc = rc or (0 if r.returncode == 0 else 5)
  182. return rc
  183. # ── 状态(不需要权限) ───────────────────────────────────────────────────────────────
  184. def win_status() -> dict:
  185. r = subprocess.run(['sc.exe', 'query', V.SERVICE_NAME], capture_output=True, text=True, errors='replace')
  186. txt = (r.stdout or '') + (r.stderr or '')
  187. installed = r.returncode == 0
  188. running = installed and ('RUNNING' in txt.upper())
  189. return dict(platform='windows', installed=installed, running=running, detail=txt.strip().splitlines()[:6])
  190. def linux_status() -> dict:
  191. if not UNIT_PATH.is_file():
  192. return dict(platform='linux', installed=False, running=False, detail=[f'没有 {UNIT_PATH}'])
  193. r = subprocess.run(['systemctl', 'is-active', V.SERVICE_NAME], capture_output=True, text=True, errors='replace')
  194. return dict(platform='linux', installed=True, running=(r.stdout or '').strip() == 'active',
  195. detail=[f'{UNIT_PATH} 存在', f'is-active: {(r.stdout or "").strip() or (r.stderr or "").strip()[:60]}'])
  196. def user_login_entry(action: str, dry: bool) -> int:
  197. """Windows 备选(**不需要管理员**):把启动器写进当前用户的开机自启(HKCU\\...\\Run)。
  198. 真服务要管理员权限;很多现场账号没有。这条给一个"登录即起"的等价退路,
  199. 并在文档里写明它与真服务的区别(服务=开机即起、无需登录、可被 SCM 恢复;本项=用户登录后起)。
  200. """
  201. import winreg # noqa: PLC0415
  202. key_path = r'Software\Microsoft\Windows\CurrentVersion\Run'
  203. cmd = f'"{py_exe()}" "{ROOT / "scripts" / "guanlan_start_hidden.py"}"'
  204. if dry:
  205. print(f' $ reg add HKCU\\{key_path} /v {V.SERVICE_NAME} /d "{cmd}" /f (= {action})')
  206. return 0
  207. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE) as k:
  208. if action == 'install':
  209. winreg.SetValueEx(k, V.SERVICE_NAME, 0, winreg.REG_SZ, cmd)
  210. print(f' 已写入 HKCU\\{key_path}\\{V.SERVICE_NAME}')
  211. else:
  212. try:
  213. winreg.DeleteValue(k, V.SERVICE_NAME)
  214. print(' 已移除登录自启项')
  215. except FileNotFoundError:
  216. print(' (本来就没有这项)')
  217. return 0
  218. def main() -> int:
  219. ap = argparse.ArgumentParser()
  220. ap.add_argument('action', choices=('status', 'install', 'uninstall', 'start', 'stop', 'restart', 'selftest'))
  221. ap.add_argument('--dry-run', action='store_true', help='只打印要做的事与将执行的命令, 不落任何改动')
  222. ap.add_argument('--user-login', action='store_true',
  223. help='Windows 备选: 不注册服务, 改成"当前用户登录时自启"(不需要管理员)')
  224. a = ap.parse_args()
  225. print(f'== {V.NAME} v{V.VERSION} 服务化 · {a.action} ({"" if WIN32 else "linux/macos"}) ==')
  226. print(f' 安装根: {ROOT}')
  227. print(f' 解释器: {py_exe()}')
  228. print(f' 管理员/root: {is_admin()}')
  229. if a.action == 'selftest':
  230. import service_worker as SW
  231. return SW.selftest()
  232. st = win_status() if WIN32 else linux_status()
  233. print(f' 当前状态: 已注册={st["installed"]} 运行中={st["running"]}')
  234. for ln in st['detail']:
  235. print(f' {ln}')
  236. if a.action == 'status':
  237. return 0
  238. if a.action == 'install' and a.dry_run:
  239. bad = preflight()
  240. if bad:
  241. print(' 前置条件不满足:')
  242. for b in bad:
  243. print(f' - {b}')
  244. return 2
  245. print(' 前置检查: 通过')
  246. elif a.action == 'install':
  247. bad = preflight()
  248. if bad:
  249. print(' [X] 前置条件不满足:')
  250. for b in bad:
  251. print(f' - {b}')
  252. return 2
  253. if a.action in ('install', 'uninstall', 'start', 'stop', 'restart') and not is_admin() and not a.dry_run \
  254. and not (WIN32 and a.action == 'install' and a.user_login):
  255. print(' [X] 权限不足: 注册/卸载/起停服务需要管理员权限。')
  256. print(' ① 用管理员身份重开终端再执行本命令; 或')
  257. print(' ② 先看它会做什么: python scripts/service_ctl.py install --dry-run')
  258. if WIN32:
  259. print(' ③ 不想提权: python scripts/service_ctl.py install --user-login'
  260. '(当前用户登录时自启, 不是真服务)')
  261. return 3
  262. if WIN32 and a.action == 'install' and a.user_login:
  263. return user_login_entry('install', a.dry_run)
  264. if WIN32 and a.action == 'uninstall' and a.user_login:
  265. return user_login_entry('uninstall', a.dry_run)
  266. if not WIN32 and a.action == 'install':
  267. print(f' 将写入单元文件 {UNIT_PATH}:')
  268. print(' ' + '-' * 66)
  269. for ln in unit_text().rstrip().splitlines():
  270. print(' | ' + ln)
  271. print(' ' + '-' * 66)
  272. if a.dry_run:
  273. run_cmds(linux_commands(a.action), True)
  274. print(' (dry-run: 以上命令未执行)')
  275. return 0
  276. UNIT_PATH.parent.mkdir(parents=True, exist_ok=True)
  277. UNIT_PATH.write_text(unit_text(), encoding='utf-8')
  278. print(f' 已写 {UNIT_PATH}')
  279. if WIN32 and a.action == 'restart':
  280. rc = win_restart(a.dry_run)
  281. if a.dry_run:
  282. print(' (dry-run: 以上命令未执行;去掉 --dry-run 才真做)')
  283. return rc
  284. cmds = win_commands(a.action) if WIN32 else linux_commands(a.action)
  285. rc = run_cmds(cmds, a.dry_run)
  286. if a.dry_run:
  287. print(' (dry-run: 以上命令未执行;去掉 --dry-run 才真做)')
  288. # 装完写安装记录里的运行方式 (install-info.json 的 mode)
  289. if a.action == 'install' and not a.dry_run and rc == 0:
  290. mode = 'windows-service' if WIN32 else 'systemd'
  291. V.write_installed(ROOT, python=py_exe(), mode=mode)
  292. print(f' 已在 {V.info_path(ROOT)} 记录运行方式 = {mode}')
  293. return rc
  294. if __name__ == '__main__':
  295. sys.exit(main())