supervisor_util.py 16 KB

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