Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

arbiter.py 19KB

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