arbiter.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. # -*- coding: utf-8 -
  2. #
  3. # This file is part of gunicorn released under the MIT license.
  4. # See the NOTICE for more information.
  5. import errno
  6. import os
  7. import random
  8. import select
  9. import signal
  10. import sys
  11. import time
  12. import traceback
  13. from gunicorn.errors import HaltServer, AppImportError
  14. from gunicorn.pidfile import Pidfile
  15. from gunicorn import sock, systemd, util
  16. from gunicorn import __version__, SERVER_SOFTWARE
  17. class Arbiter(object):
  18. """
  19. Arbiter maintain the workers processes alive. It launches or
  20. kills them if needed. It also manages application reloading
  21. via SIGHUP/USR2.
  22. """
  23. # A flag indicating if a worker failed to
  24. # to boot. If a worker process exist with
  25. # this error code, the arbiter will terminate.
  26. WORKER_BOOT_ERROR = 3
  27. # A flag indicating if an application failed to be loaded
  28. APP_LOAD_ERROR = 4
  29. START_CTX = {}
  30. LISTENERS = []
  31. WORKERS = {}
  32. PIPE = []
  33. # I love dynamic languages
  34. SIG_QUEUE = []
  35. SIGNALS = [getattr(signal, "SIG%s" % x)
  36. for x in "HUP QUIT INT TERM TTIN TTOU USR1 USR2 WINCH".split()]
  37. SIG_NAMES = dict(
  38. (getattr(signal, name), name[3:].lower()) for name in dir(signal)
  39. if name[:3] == "SIG" and name[3] != "_"
  40. )
  41. def __init__(self, app):
  42. os.environ["SERVER_SOFTWARE"] = SERVER_SOFTWARE
  43. self._num_workers = None
  44. self._last_logged_active_worker_count = None
  45. self.log = None
  46. self.setup(app)
  47. self.pidfile = None
  48. self.systemd = False
  49. self.worker_age = 0
  50. self.reexec_pid = 0
  51. self.master_pid = 0
  52. self.master_name = "Master"
  53. cwd = util.getcwd()
  54. args = sys.argv[:]
  55. args.insert(0, sys.executable)
  56. # init start context
  57. self.START_CTX = {
  58. "args": args,
  59. "cwd": cwd,
  60. 0: sys.executable
  61. }
  62. def _get_num_workers(self):
  63. return self._num_workers
  64. def _set_num_workers(self, value):
  65. old_value = self._num_workers
  66. self._num_workers = value
  67. self.cfg.nworkers_changed(self, value, old_value)
  68. num_workers = property(_get_num_workers, _set_num_workers)
  69. def setup(self, app):
  70. self.app = app
  71. self.cfg = app.cfg
  72. if self.log is None:
  73. self.log = self.cfg.logger_class(app.cfg)
  74. # reopen files
  75. if 'GUNICORN_FD' in os.environ:
  76. self.log.reopen_files()
  77. self.worker_class = self.cfg.worker_class
  78. self.address = self.cfg.address
  79. self.num_workers = self.cfg.workers
  80. self.timeout = self.cfg.timeout
  81. self.proc_name = self.cfg.proc_name
  82. self.log.debug('Current configuration:\n{0}'.format(
  83. '\n'.join(
  84. ' {0}: {1}'.format(config, value.value)
  85. for config, value
  86. in sorted(self.cfg.settings.items(),
  87. key=lambda setting: setting[1]))))
  88. # set enviroment' variables
  89. if self.cfg.env:
  90. for k, v in self.cfg.env.items():
  91. os.environ[k] = v
  92. if self.cfg.preload_app:
  93. self.app.wsgi()
  94. def start(self):
  95. """\
  96. Initialize the arbiter. Start listening and set pidfile if needed.
  97. """
  98. self.log.info("Starting gunicorn %s", __version__)
  99. if 'GUNICORN_PID' in os.environ:
  100. self.master_pid = int(os.environ.get('GUNICORN_PID'))
  101. self.proc_name = self.proc_name + ".2"
  102. self.master_name = "Master.2"
  103. self.pid = os.getpid()
  104. if self.cfg.pidfile is not None:
  105. pidname = self.cfg.pidfile
  106. if self.master_pid != 0:
  107. pidname += ".2"
  108. self.pidfile = Pidfile(pidname)
  109. self.pidfile.create(self.pid)
  110. self.cfg.on_starting(self)
  111. self.init_signals()
  112. if not self.LISTENERS:
  113. fds = None
  114. listen_fds = systemd.listen_fds()
  115. if listen_fds:
  116. self.systemd = True
  117. fds = range(systemd.SD_LISTEN_FDS_START,
  118. systemd.SD_LISTEN_FDS_START + listen_fds)
  119. elif self.master_pid:
  120. fds = []
  121. for fd in os.environ.pop('GUNICORN_FD').split(','):
  122. fds.append(int(fd))
  123. self.LISTENERS = sock.create_sockets(self.cfg, self.log, fds)
  124. listeners_str = ",".join([str(l) for l in self.LISTENERS])
  125. self.log.debug("Arbiter booted")
  126. self.log.info("Listening at: %s (%s)", listeners_str, self.pid)
  127. self.log.info("Using worker: %s", self.cfg.worker_class_str)
  128. systemd.sd_notify("READY=1\nSTATUS=Gunicorn arbiter booted", self.log)
  129. # check worker class requirements
  130. if hasattr(self.worker_class, "check_config"):
  131. self.worker_class.check_config(self.cfg, self.log)
  132. self.cfg.when_ready(self)
  133. def init_signals(self):
  134. """\
  135. Initialize master signal handling. Most of the signals
  136. are queued. Child signals only wake up the master.
  137. """
  138. # close old PIPE
  139. for p in self.PIPE:
  140. os.close(p)
  141. # initialize the pipe
  142. self.PIPE = pair = os.pipe()
  143. for p in pair:
  144. util.set_non_blocking(p)
  145. util.close_on_exec(p)
  146. self.log.close_on_exec()
  147. # initialize all signals
  148. for s in self.SIGNALS:
  149. signal.signal(s, self.signal)
  150. signal.signal(signal.SIGCHLD, self.handle_chld)
  151. def signal(self, sig, frame):
  152. if len(self.SIG_QUEUE) < 5:
  153. self.SIG_QUEUE.append(sig)
  154. self.wakeup()
  155. def run(self):
  156. "Main master loop."
  157. self.start()
  158. util._setproctitle("master [%s]" % self.proc_name)
  159. try:
  160. self.manage_workers()
  161. while True:
  162. self.maybe_promote_master()
  163. sig = self.SIG_QUEUE.pop(0) if self.SIG_QUEUE else None
  164. if sig is None:
  165. self.sleep()
  166. self.murder_workers()
  167. self.manage_workers()
  168. continue
  169. if sig not in self.SIG_NAMES:
  170. self.log.info("Ignoring unknown signal: %s", sig)
  171. continue
  172. signame = self.SIG_NAMES.get(sig)
  173. handler = getattr(self, "handle_%s" % signame, None)
  174. if not handler:
  175. self.log.error("Unhandled signal: %s", signame)
  176. continue
  177. self.log.info("Handling signal: %s", signame)
  178. handler()
  179. self.wakeup()
  180. except (StopIteration, KeyboardInterrupt):
  181. self.halt()
  182. except HaltServer as inst:
  183. self.halt(reason=inst.reason, exit_status=inst.exit_status)
  184. except SystemExit:
  185. raise
  186. except Exception:
  187. self.log.info("Unhandled exception in main loop",
  188. exc_info=True)
  189. self.stop(False)
  190. if self.pidfile is not None:
  191. self.pidfile.unlink()
  192. sys.exit(-1)
  193. def handle_chld(self, sig, frame):
  194. "SIGCHLD handling"
  195. self.reap_workers()
  196. self.wakeup()
  197. def handle_hup(self):
  198. """\
  199. HUP handling.
  200. - Reload configuration
  201. - Start the new worker processes with a new configuration
  202. - Gracefully shutdown the old worker processes
  203. """
  204. self.log.info("Hang up: %s", self.master_name)
  205. self.reload()
  206. def handle_term(self):
  207. "SIGTERM handling"
  208. raise StopIteration
  209. def handle_int(self):
  210. "SIGINT handling"
  211. self.stop(False)
  212. raise StopIteration
  213. def handle_quit(self):
  214. "SIGQUIT handling"
  215. self.stop(False)
  216. raise StopIteration
  217. def handle_ttin(self):
  218. """\
  219. SIGTTIN handling.
  220. Increases the number of workers by one.
  221. """
  222. self.num_workers += 1
  223. self.manage_workers()
  224. def handle_ttou(self):
  225. """\
  226. SIGTTOU handling.
  227. Decreases the number of workers by one.
  228. """
  229. if self.num_workers <= 1:
  230. return
  231. self.num_workers -= 1
  232. self.manage_workers()
  233. def handle_usr1(self):
  234. """\
  235. SIGUSR1 handling.
  236. Kill all workers by sending them a SIGUSR1
  237. """
  238. self.log.reopen_files()
  239. self.kill_workers(signal.SIGUSR1)
  240. def handle_usr2(self):
  241. """\
  242. SIGUSR2 handling.
  243. Creates a new arbiter/worker set as a fork of the current
  244. arbiter without affecting old workers. Use this to do live
  245. deployment with the ability to backout a change.
  246. """
  247. self.reexec()
  248. def handle_winch(self):
  249. """SIGWINCH handling"""
  250. if self.cfg.daemon:
  251. self.log.info("graceful stop of workers")
  252. self.num_workers = 0
  253. self.kill_workers(signal.SIGTERM)
  254. else:
  255. self.log.debug("SIGWINCH ignored. Not daemonized")
  256. def maybe_promote_master(self):
  257. if self.master_pid == 0:
  258. return
  259. if self.master_pid != os.getppid():
  260. self.log.info("Master has been promoted.")
  261. # reset master infos
  262. self.master_name = "Master"
  263. self.master_pid = 0
  264. self.proc_name = self.cfg.proc_name
  265. del os.environ['GUNICORN_PID']
  266. # rename the pidfile
  267. if self.pidfile is not None:
  268. self.pidfile.rename(self.cfg.pidfile)
  269. # reset proctitle
  270. util._setproctitle("master [%s]" % self.proc_name)
  271. def wakeup(self):
  272. """\
  273. Wake up the arbiter by writing to the PIPE
  274. """
  275. try:
  276. os.write(self.PIPE[1], b'.')
  277. except IOError as e:
  278. if e.errno not in [errno.EAGAIN, errno.EINTR]:
  279. raise
  280. def halt(self, reason=None, exit_status=0):
  281. """ halt arbiter """
  282. self.stop()
  283. self.log.info("Shutting down: %s", self.master_name)
  284. if reason is not None:
  285. self.log.info("Reason: %s", reason)
  286. if self.pidfile is not None:
  287. self.pidfile.unlink()
  288. self.cfg.on_exit(self)
  289. sys.exit(exit_status)
  290. def sleep(self):
  291. """\
  292. Sleep until PIPE is readable or we timeout.
  293. A readable PIPE means a signal occurred.
  294. """
  295. try:
  296. ready = select.select([self.PIPE[0]], [], [], 1.0)
  297. if not ready[0]:
  298. return
  299. while os.read(self.PIPE[0], 1):
  300. pass
  301. except (select.error, OSError) as e:
  302. # TODO: select.error is a subclass of OSError since Python 3.3.
  303. error_number = getattr(e, 'errno', e.args[0])
  304. if error_number not in [errno.EAGAIN, errno.EINTR]:
  305. raise
  306. except KeyboardInterrupt:
  307. sys.exit()
  308. def stop(self, graceful=True):
  309. """\
  310. Stop workers
  311. :attr graceful: boolean, If True (the default) workers will be
  312. killed gracefully (ie. trying to wait for the current connection)
  313. """
  314. unlink = (
  315. self.reexec_pid == self.master_pid == 0
  316. and not self.systemd
  317. and not self.cfg.reuse_port
  318. )
  319. sock.close_sockets(self.LISTENERS, unlink)
  320. self.LISTENERS = []
  321. sig = signal.SIGTERM
  322. if not graceful:
  323. sig = signal.SIGQUIT
  324. limit = time.time() + self.cfg.graceful_timeout
  325. # instruct the workers to exit
  326. self.kill_workers(sig)
  327. # wait until the graceful timeout
  328. while self.WORKERS and time.time() < limit:
  329. time.sleep(0.1)
  330. self.kill_workers(signal.SIGKILL)
  331. def reexec(self):
  332. """\
  333. Relaunch the master and workers.
  334. """
  335. if self.reexec_pid != 0:
  336. self.log.warning("USR2 signal ignored. Child exists.")
  337. return
  338. if self.master_pid != 0:
  339. self.log.warning("USR2 signal ignored. Parent exists.")
  340. return
  341. master_pid = os.getpid()
  342. self.reexec_pid = os.fork()
  343. if self.reexec_pid != 0:
  344. return
  345. self.cfg.pre_exec(self)
  346. environ = self.cfg.env_orig.copy()
  347. environ['GUNICORN_PID'] = str(master_pid)
  348. if self.systemd:
  349. environ['LISTEN_PID'] = str(os.getpid())
  350. environ['LISTEN_FDS'] = str(len(self.LISTENERS))
  351. else:
  352. environ['GUNICORN_FD'] = ','.join(
  353. str(l.fileno()) for l in self.LISTENERS)
  354. os.chdir(self.START_CTX['cwd'])
  355. # exec the process using the original environment
  356. os.execvpe(self.START_CTX[0], self.START_CTX['args'], environ)
  357. def reload(self):
  358. old_address = self.cfg.address
  359. # reset old environment
  360. for k in self.cfg.env:
  361. if k in self.cfg.env_orig:
  362. # reset the key to the value it had before
  363. # we launched gunicorn
  364. os.environ[k] = self.cfg.env_orig[k]
  365. else:
  366. # delete the value set by gunicorn
  367. try:
  368. del os.environ[k]
  369. except KeyError:
  370. pass
  371. # reload conf
  372. self.app.reload()
  373. self.setup(self.app)
  374. # reopen log files
  375. self.log.reopen_files()
  376. # do we need to change listener ?
  377. if old_address != self.cfg.address:
  378. # close all listeners
  379. for l in self.LISTENERS:
  380. l.close()
  381. # init new listeners
  382. self.LISTENERS = sock.create_sockets(self.cfg, self.log)
  383. listeners_str = ",".join([str(l) for l in self.LISTENERS])
  384. self.log.info("Listening at: %s", listeners_str)
  385. # do some actions on reload
  386. self.cfg.on_reload(self)
  387. # unlink pidfile
  388. if self.pidfile is not None:
  389. self.pidfile.unlink()
  390. # create new pidfile
  391. if self.cfg.pidfile is not None:
  392. self.pidfile = Pidfile(self.cfg.pidfile)
  393. self.pidfile.create(self.pid)
  394. # set new proc_name
  395. util._setproctitle("master [%s]" % self.proc_name)
  396. # spawn new workers
  397. for _ in range(self.cfg.workers):
  398. self.spawn_worker()
  399. # manage workers
  400. self.manage_workers()
  401. def murder_workers(self):
  402. """\
  403. Kill unused/idle workers
  404. """
  405. if not self.timeout:
  406. return
  407. workers = list(self.WORKERS.items())
  408. for (pid, worker) in workers:
  409. try:
  410. if time.time() - worker.tmp.last_update() <= self.timeout:
  411. continue
  412. except (OSError, ValueError):
  413. continue
  414. if not worker.aborted:
  415. self.log.critical("WORKER TIMEOUT (pid:%s)", pid)
  416. worker.aborted = True
  417. self.kill_worker(pid, signal.SIGABRT)
  418. else:
  419. self.kill_worker(pid, signal.SIGKILL)
  420. def reap_workers(self):
  421. """\
  422. Reap workers to avoid zombie processes
  423. """
  424. try:
  425. while True:
  426. wpid, status = os.waitpid(-1, os.WNOHANG)
  427. if not wpid:
  428. break
  429. if self.reexec_pid == wpid:
  430. self.reexec_pid = 0
  431. else:
  432. # A worker was terminated. If the termination reason was
  433. # that it could not boot, we'll shut it down to avoid
  434. # infinite start/stop cycles.
  435. exitcode = status >> 8
  436. if exitcode == self.WORKER_BOOT_ERROR:
  437. reason = "Worker failed to boot."
  438. raise HaltServer(reason, self.WORKER_BOOT_ERROR)
  439. if exitcode == self.APP_LOAD_ERROR:
  440. reason = "App failed to load."
  441. raise HaltServer(reason, self.APP_LOAD_ERROR)
  442. if os.WIFSIGNALED(status):
  443. self.log.warning(
  444. "Worker with pid %s was terminated due to signal %s",
  445. wpid,
  446. os.WTERMSIG(status)
  447. )
  448. worker = self.WORKERS.pop(wpid, None)
  449. if not worker:
  450. continue
  451. worker.tmp.close()
  452. self.cfg.child_exit(self, worker)
  453. except OSError as e:
  454. if e.errno != errno.ECHILD:
  455. raise
  456. def manage_workers(self):
  457. """\
  458. Maintain the number of workers by spawning or killing
  459. as required.
  460. """
  461. if len(self.WORKERS) < self.num_workers:
  462. self.spawn_workers()
  463. workers = self.WORKERS.items()
  464. workers = sorted(workers, key=lambda w: w[1].age)
  465. while len(workers) > self.num_workers:
  466. (pid, _) = workers.pop(0)
  467. self.kill_worker(pid, signal.SIGTERM)
  468. active_worker_count = len(workers)
  469. if self._last_logged_active_worker_count != active_worker_count:
  470. self._last_logged_active_worker_count = active_worker_count
  471. self.log.debug("{0} workers".format(active_worker_count),
  472. extra={"metric": "gunicorn.workers",
  473. "value": active_worker_count,
  474. "mtype": "gauge"})
  475. def spawn_worker(self):
  476. self.worker_age += 1
  477. worker = self.worker_class(self.worker_age, self.pid, self.LISTENERS,
  478. self.app, self.timeout / 2.0,
  479. self.cfg, self.log)
  480. self.cfg.pre_fork(self, worker)
  481. pid = os.fork()
  482. if pid != 0:
  483. worker.pid = pid
  484. self.WORKERS[pid] = worker
  485. return pid
  486. # Do not inherit the temporary files of other workers
  487. for sibling in self.WORKERS.values():
  488. sibling.tmp.close()
  489. # Process Child
  490. worker.pid = os.getpid()
  491. try:
  492. util._setproctitle("worker [%s]" % self.proc_name)
  493. self.log.info("Booting worker with pid: %s", worker.pid)
  494. self.cfg.post_fork(self, worker)
  495. worker.init_process()
  496. sys.exit(0)
  497. except SystemExit:
  498. raise
  499. except AppImportError as e:
  500. self.log.debug("Exception while loading the application",
  501. exc_info=True)
  502. print("%s" % e, file=sys.stderr)
  503. sys.stderr.flush()
  504. sys.exit(self.APP_LOAD_ERROR)
  505. except Exception:
  506. self.log.exception("Exception in worker process")
  507. if not worker.booted:
  508. sys.exit(self.WORKER_BOOT_ERROR)
  509. sys.exit(-1)
  510. finally:
  511. self.log.info("Worker exiting (pid: %s)", worker.pid)
  512. try:
  513. worker.tmp.close()
  514. self.cfg.worker_exit(self, worker)
  515. except Exception:
  516. self.log.warning("Exception during worker exit:\n%s",
  517. traceback.format_exc())
  518. def spawn_workers(self):
  519. """\
  520. Spawn new workers as needed.
  521. This is where a worker process leaves the main loop
  522. of the master process.
  523. """
  524. for _ in range(self.num_workers - len(self.WORKERS)):
  525. self.spawn_worker()
  526. time.sleep(0.1 * random.random())
  527. def kill_workers(self, sig):
  528. """\
  529. Kill all workers with the signal `sig`
  530. :attr sig: `signal.SIG*` value
  531. """
  532. worker_pids = list(self.WORKERS.keys())
  533. for pid in worker_pids:
  534. self.kill_worker(pid, sig)
  535. def kill_worker(self, pid, sig):
  536. """\
  537. Kill a worker
  538. :attr pid: int, worker pid
  539. :attr sig: `signal.SIG*` value
  540. """
  541. try:
  542. os.kill(pid, sig)
  543. except OSError as e:
  544. if e.errno == errno.ESRCH:
  545. try:
  546. worker = self.WORKERS.pop(pid)
  547. worker.tmp.close()
  548. self.cfg.worker_exit(self, worker)
  549. return
  550. except (KeyError, OSError):
  551. return
  552. raise