service_ctl.py 12 KB

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