supervisor_util.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. __package__ = 'archivebox.queues'
  2. import sys
  3. import time
  4. import signal
  5. import psutil
  6. import shutil
  7. import subprocess
  8. from typing import Dict, cast, Iterator
  9. from pathlib import Path
  10. from functools import cache
  11. from rich import print
  12. from supervisor.xmlrpc import SupervisorTransport
  13. from xmlrpc.client import ServerProxy
  14. from archivebox.config import CONSTANTS
  15. from archivebox.config.paths import get_or_create_working_tmp_dir
  16. from archivebox.config.permissions import ARCHIVEBOX_USER
  17. from archivebox.misc.logging import STDERR
  18. from archivebox.logging_util import pretty_path
  19. LOG_FILE_NAME = "supervisord.log"
  20. CONFIG_FILE_NAME = "supervisord.conf"
  21. PID_FILE_NAME = "supervisord.pid"
  22. WORKERS_DIR_NAME = "workers"
  23. @cache
  24. def get_sock_file():
  25. """Get the path to the supervisord socket file, symlinking to a shorter path if needed due to unix path length limits"""
  26. TMP_DIR = get_or_create_working_tmp_dir(autofix=True, quiet=False)
  27. assert TMP_DIR, "Failed to find or create a writable TMP_DIR!"
  28. socket_file = TMP_DIR / "supervisord.sock"
  29. return socket_file
  30. def follow(file, sleep_sec=0.1) -> Iterator[str]:
  31. """ Yield each line from a file as they are written.
  32. `sleep_sec` is the time to sleep after empty reads. """
  33. line = ''
  34. while True:
  35. tmp = file.readline()
  36. if tmp is not None and tmp != "":
  37. line += tmp
  38. if line.endswith("\n"):
  39. yield line
  40. line = ''
  41. elif sleep_sec:
  42. time.sleep(sleep_sec)
  43. def create_supervisord_config():
  44. SOCK_FILE = get_sock_file()
  45. WORKERS_DIR = SOCK_FILE.parent / WORKERS_DIR_NAME
  46. CONFIG_FILE = SOCK_FILE.parent / CONFIG_FILE_NAME
  47. PID_FILE = SOCK_FILE.parent / PID_FILE_NAME
  48. LOG_FILE = CONSTANTS.LOGS_DIR / LOG_FILE_NAME
  49. config_content = f"""
  50. [supervisord]
  51. nodaemon = true
  52. environment = IS_SUPERVISORD_PARENT="true"
  53. pidfile = {PID_FILE}
  54. logfile = {LOG_FILE}
  55. childlogdir = {CONSTANTS.LOGS_DIR}
  56. directory = {CONSTANTS.DATA_DIR}
  57. strip_ansi = true
  58. nocleanup = true
  59. user = {ARCHIVEBOX_USER}
  60. [unix_http_server]
  61. file = {SOCK_FILE}
  62. chmod = 0700
  63. [supervisorctl]
  64. serverurl = unix://{SOCK_FILE}
  65. [rpcinterface:supervisor]
  66. supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
  67. [include]
  68. files = {WORKERS_DIR}/*.conf
  69. """
  70. CONFIG_FILE.write_text(config_content)
  71. Path.mkdir(WORKERS_DIR, exist_ok=True)
  72. (WORKERS_DIR / 'initial_startup.conf').write_text('') # hides error about "no files found to include" when supervisord starts
  73. def create_worker_config(daemon):
  74. SOCK_FILE = get_sock_file()
  75. WORKERS_DIR = SOCK_FILE.parent / WORKERS_DIR_NAME
  76. Path.mkdir(WORKERS_DIR, exist_ok=True)
  77. name = daemon['name']
  78. configfile = WORKERS_DIR / f"{name}.conf"
  79. config_content = f"[program:{name}]\n"
  80. for key, value in daemon.items():
  81. if key == 'name':
  82. continue
  83. config_content += f"{key}={value}\n"
  84. config_content += "\n"
  85. configfile.write_text(config_content)
  86. def get_existing_supervisord_process():
  87. SOCK_FILE = get_sock_file()
  88. try:
  89. transport = SupervisorTransport(None, None, f"unix://{SOCK_FILE}")
  90. server = ServerProxy("http://localhost", transport=transport)
  91. current_state = cast(Dict[str, int | str], server.supervisor.getState())
  92. if current_state["statename"] == "RUNNING":
  93. pid = server.supervisor.getPID()
  94. print(f"[🦸‍♂️] Supervisord connected (pid={pid}) via unix://{pretty_path(SOCK_FILE)}.")
  95. return server.supervisor
  96. except FileNotFoundError:
  97. return None
  98. except Exception as e:
  99. print(f"Error connecting to existing supervisord: {str(e)}")
  100. return None
  101. def stop_existing_supervisord_process():
  102. SOCK_FILE = get_sock_file()
  103. PID_FILE = SOCK_FILE.parent / PID_FILE_NAME
  104. try:
  105. try:
  106. pid = int(PID_FILE.read_text())
  107. except (FileNotFoundError, ValueError):
  108. return
  109. try:
  110. print(f"[🦸‍♂️] Stopping supervisord process (pid={pid})...")
  111. proc = psutil.Process(pid)
  112. proc.terminate()
  113. proc.wait()
  114. except (Exception, BrokenPipeError, IOError):
  115. pass
  116. finally:
  117. try:
  118. # clear PID file and socket file
  119. PID_FILE.unlink(missing_ok=True)
  120. get_sock_file().unlink(missing_ok=True)
  121. except Exception:
  122. pass
  123. def start_new_supervisord_process(daemonize=False):
  124. SOCK_FILE = get_sock_file()
  125. WORKERS_DIR = SOCK_FILE.parent / WORKERS_DIR_NAME
  126. LOG_FILE = CONSTANTS.LOGS_DIR / LOG_FILE_NAME
  127. CONFIG_FILE = SOCK_FILE.parent / CONFIG_FILE_NAME
  128. PID_FILE = SOCK_FILE.parent / PID_FILE_NAME
  129. print(f"[🦸‍♂️] Supervisord starting{' in background' if daemonize else ''}...")
  130. pretty_log_path = pretty_path(LOG_FILE)
  131. print(f" > Writing supervisord logs to: {pretty_log_path}")
  132. print(f" > Writing task worker logs to: {pretty_log_path.replace('supervisord.log', 'worker_*.log')}")
  133. print(f' > Using supervisord config file: {pretty_path(CONFIG_FILE)}')
  134. print(f" > Using supervisord UNIX socket: {pretty_path(SOCK_FILE)}")
  135. print()
  136. # clear out existing stale state files
  137. shutil.rmtree(WORKERS_DIR, ignore_errors=True)
  138. PID_FILE.unlink(missing_ok=True)
  139. get_sock_file().unlink(missing_ok=True)
  140. CONFIG_FILE.unlink(missing_ok=True)
  141. # create the supervisord config file
  142. create_supervisord_config()
  143. # Start supervisord
  144. # panel = Panel(f"Starting supervisord with config: {SUPERVISORD_CONFIG_FILE}")
  145. # with Live(panel, refresh_per_second=1) as live:
  146. subprocess.Popen(
  147. f"supervisord --configuration={CONFIG_FILE}",
  148. stdin=None,
  149. shell=True,
  150. start_new_session=daemonize,
  151. )
  152. def exit_signal_handler(signum, frame):
  153. if signum == 2:
  154. STDERR.print("\n[🛑] Got Ctrl+C. Terminating child processes...")
  155. elif signum != 13:
  156. STDERR.print(f"\n[🦸‍♂️] Supervisord got stop signal ({signal.strsignal(signum)}). Terminating child processes...")
  157. stop_existing_supervisord_process()
  158. raise SystemExit(0)
  159. # Monitor for termination signals and cleanup child processes
  160. if not daemonize:
  161. try:
  162. signal.signal(signal.SIGINT, exit_signal_handler)
  163. signal.signal(signal.SIGHUP, exit_signal_handler)
  164. signal.signal(signal.SIGPIPE, exit_signal_handler)
  165. signal.signal(signal.SIGTERM, exit_signal_handler)
  166. except Exception:
  167. # signal handlers only work in main thread
  168. pass
  169. # otherwise supervisord will containue in background even if parent proc is ends (aka daemon mode)
  170. time.sleep(2)
  171. return get_existing_supervisord_process()
  172. def get_or_create_supervisord_process(daemonize=False):
  173. SOCK_FILE = get_sock_file()
  174. WORKERS_DIR = SOCK_FILE.parent / WORKERS_DIR_NAME
  175. supervisor = get_existing_supervisord_process()
  176. if supervisor is None:
  177. stop_existing_supervisord_process()
  178. supervisor = start_new_supervisord_process(daemonize=daemonize)
  179. time.sleep(0.5)
  180. # wait up to 5s in case supervisord is slow to start
  181. if not supervisor:
  182. for _ in range(10):
  183. if supervisor is not None:
  184. print()
  185. break
  186. sys.stdout.write('.')
  187. sys.stdout.flush()
  188. time.sleep(0.5)
  189. supervisor = get_existing_supervisord_process()
  190. else:
  191. print()
  192. assert supervisor, "Failed to start supervisord or connect to it!"
  193. supervisor.getPID() # make sure it doesn't throw an exception
  194. (WORKERS_DIR / 'initial_startup.conf').unlink(missing_ok=True)
  195. return supervisor
  196. def start_worker(supervisor, daemon, lazy=False):
  197. assert supervisor.getPID()
  198. print(f"[🦸‍♂️] Supervisord starting new subprocess worker: {daemon['name']}...")
  199. create_worker_config(daemon)
  200. result = supervisor.reloadConfig()
  201. added, changed, removed = result[0]
  202. # print(f"Added: {added}, Changed: {changed}, Removed: {removed}")
  203. for removed in removed:
  204. supervisor.stopProcessGroup(removed)
  205. supervisor.removeProcessGroup(removed)
  206. for changed in changed:
  207. supervisor.stopProcessGroup(changed)
  208. supervisor.removeProcessGroup(changed)
  209. supervisor.addProcessGroup(changed)
  210. for added in added:
  211. supervisor.addProcessGroup(added)
  212. time.sleep(1)
  213. for _ in range(10):
  214. procs = supervisor.getAllProcessInfo()
  215. for proc in procs:
  216. if proc['name'] == daemon["name"]:
  217. # See process state diagram here: http://supervisord.org/subprocess.html
  218. if proc['statename'] == 'RUNNING':
  219. print(f" - Worker {daemon['name']}: already {proc['statename']} ({proc['description']})")
  220. return proc
  221. else:
  222. if not lazy:
  223. supervisor.startProcessGroup(daemon["name"], True)
  224. proc = supervisor.getProcessInfo(daemon["name"])
  225. print(f" - Worker {daemon['name']}: started {proc['statename']} ({proc['description']})")
  226. return proc
  227. # retry in a second in case it's slow to launch
  228. time.sleep(0.5)
  229. raise Exception(f"Failed to start worker {daemon['name']}! Only found: {procs}")
  230. def watch_worker(supervisor, daemon_name, interval=5):
  231. """loop continuously and monitor worker's health"""
  232. while True:
  233. proc = get_worker(supervisor, daemon_name)
  234. if not proc:
  235. raise Exception("Worker dissapeared while running! " + daemon_name)
  236. if proc['statename'] == 'STOPPED':
  237. return proc
  238. if proc['statename'] == 'RUNNING':
  239. time.sleep(1)
  240. continue
  241. if proc['statename'] in ('STARTING', 'BACKOFF', 'FATAL', 'EXITED', 'STOPPING'):
  242. print(f'[🦸‍♂️] WARNING: Worker {daemon_name} {proc["statename"]} {proc["description"]}')
  243. time.sleep(interval)
  244. continue
  245. def tail_worker_logs(log_path: str):
  246. get_or_create_supervisord_process(daemonize=False)
  247. from rich.live import Live
  248. from rich.table import Table
  249. table = Table()
  250. table.add_column("TS")
  251. table.add_column("URL")
  252. try:
  253. with Live(table, refresh_per_second=1) as live: # update 4 times a second to feel fluid
  254. with open(log_path, 'r') as f:
  255. for line in follow(f):
  256. if '://' in line:
  257. live.console.print(f"Working on: {line.strip()}")
  258. # table.add_row("123124234", line.strip())
  259. except (KeyboardInterrupt, BrokenPipeError, IOError):
  260. STDERR.print("\n[🛑] Got Ctrl+C, stopping gracefully...")
  261. except SystemExit:
  262. pass
  263. def get_worker(supervisor, daemon_name):
  264. try:
  265. return supervisor.getProcessInfo(daemon_name)
  266. except Exception:
  267. pass
  268. return None
  269. def stop_worker(supervisor, daemon_name):
  270. proc = get_worker(supervisor, daemon_name)
  271. for _ in range(10):
  272. if not proc:
  273. # worker does not exist (was never running or configured in the first place)
  274. return True
  275. # See process state diagram here: http://supervisord.org/subprocess.html
  276. if proc['statename'] == 'STOPPED':
  277. # worker was configured but has already stopped for some reason
  278. supervisor.removeProcessGroup(daemon_name)
  279. return True
  280. else:
  281. # worker was configured and is running, stop it now
  282. supervisor.stopProcessGroup(daemon_name)
  283. # wait 500ms and then re-check to make sure it's really stopped
  284. time.sleep(0.5)
  285. proc = get_worker(supervisor, daemon_name)
  286. raise Exception(f"Failed to stop worker {daemon_name}!")
  287. def start_server_workers(host='0.0.0.0', port='8000', daemonize=False):
  288. supervisor = get_or_create_supervisord_process(daemonize=daemonize)
  289. bg_workers = [
  290. {
  291. "name": "worker_scheduler",
  292. "command": "archivebox manage djangohuey --queue system_tasks -w 4 -k thread --disable-health-check --flush-locks",
  293. "autostart": "true",
  294. "autorestart": "true",
  295. "stdout_logfile": "logs/worker_scheduler.log",
  296. "redirect_stderr": "true",
  297. },
  298. {
  299. "name": "worker_system_tasks",
  300. "command": "archivebox manage djangohuey --queue system_tasks -w 4 -k thread --no-periodic --disable-health-check",
  301. "autostart": "true",
  302. "autorestart": "true",
  303. "stdout_logfile": "logs/worker_system_tasks.log",
  304. "redirect_stderr": "true",
  305. },
  306. ]
  307. fg_worker = {
  308. "name": "worker_daphne",
  309. "command": f"daphne --bind={host} --port={port} --application-close-timeout=600 archivebox.core.asgi:application",
  310. "autostart": "false",
  311. "autorestart": "true",
  312. "stdout_logfile": "logs/worker_daphne.log",
  313. "redirect_stderr": "true",
  314. }
  315. print()
  316. start_worker(supervisor, fg_worker)
  317. print()
  318. for worker in bg_workers:
  319. start_worker(supervisor, worker)
  320. print()
  321. if not daemonize:
  322. try:
  323. watch_worker(supervisor, "worker_daphne")
  324. except (KeyboardInterrupt, BrokenPipeError, IOError):
  325. STDERR.print("\n[🛑] Got Ctrl+C, stopping gracefully...")
  326. except SystemExit:
  327. pass
  328. except BaseException as e:
  329. STDERR.print(f"\n[🛑] Got {e.__class__.__name__} exception, stopping web server gracefully...")
  330. raise
  331. finally:
  332. stop_worker(supervisor, "worker_daphne")
  333. time.sleep(0.5)
  334. def start_cli_workers(watch=False):
  335. supervisor = get_or_create_supervisord_process(daemonize=False)
  336. fg_worker = {
  337. "name": "worker_system_tasks",
  338. "command": "archivebox manage djangohuey --queue system_tasks",
  339. "autostart": "true",
  340. "autorestart": "true",
  341. "stdout_logfile": "logs/worker_system_tasks.log",
  342. "redirect_stderr": "true",
  343. }
  344. start_worker(supervisor, fg_worker)
  345. if watch:
  346. try:
  347. watch_worker(supervisor, "worker_system_tasks")
  348. except (KeyboardInterrupt, BrokenPipeError, IOError):
  349. STDERR.print("\n[🛑] Got Ctrl+C, stopping gracefully...")
  350. except SystemExit:
  351. pass
  352. except BaseException as e:
  353. STDERR.print(f"\n[🛑] Got {e.__class__.__name__} exception, stopping web server gracefully...")
  354. raise
  355. finally:
  356. stop_worker(supervisor, "worker_system_tasks")
  357. stop_worker(supervisor, "worker_scheduler")
  358. time.sleep(0.5)
  359. return fg_worker
  360. # def main(daemons):
  361. # supervisor = get_or_create_supervisord_process(daemonize=False)
  362. # worker = start_worker(supervisor, daemons["webworker"])
  363. # pprint(worker)
  364. # print("All processes started in background.")
  365. # Optionally you can block the main thread until an exit signal is received:
  366. # try:
  367. # signal.pause()
  368. # except KeyboardInterrupt:
  369. # pass
  370. # finally:
  371. # stop_existing_supervisord_process()
  372. # if __name__ == "__main__":
  373. # DAEMONS = {
  374. # "webworker": {
  375. # "name": "webworker",
  376. # "command": "python3 -m http.server 9000",
  377. # "directory": str(cwd),
  378. # "autostart": "true",
  379. # "autorestart": "true",
  380. # "stdout_logfile": cwd / "webworker.log",
  381. # "stderr_logfile": cwd / "webworker_error.log",
  382. # },
  383. # }
  384. # main(DAEMONS, cwd)