Skip to content

Commit 97b477f

Browse files
committed
systemd: auto-shutdown old master post USR2 re-exec
1 parent 76f761f commit 97b477f

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

docs/source/signals.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,3 +117,9 @@ running::
117117
20859 benoitc 20 0 55748 11m 1500 S 0.0 0.1 0:00.02 gunicorn: worker [test:app]
118118
20860 benoitc 20 0 55748 11m 1500 S 0.0 0.1 0:00.02 gunicorn: worker [test:app]
119119
20861 benoitc 20 0 55748 11m 1500 S 0.0 0.1 0:00.01 gunicorn: worker [test:app]
120+
121+
If no pidfile is available (``kill -TERM $(cat /var/run/gunicorn.pid)``) then killing
122+
the *oldest* process (``pkill --oldest -TERM -f "gunicorn: master "``) should suffice.
123+
124+
When running via systemd socket activation, Gunicorn will *automatically* issue the graceful
125+
shutdown of the old master, as part of starting up the new one.

gunicorn/arbiter.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -173,9 +173,7 @@ def start(self):
173173

174174
self.cfg.when_ready(self)
175175

176-
# # call `pkill --oldest -TERM -f "gunicorn: master "` instead
177-
# if self.master_pid and self.systemd:
178-
# os.kill(self.master_pid, signal.SIGTERM)
176+
# systemd: not yet shutting down old master here (wait for workers)
179177

180178
def init_signals(self):
181179
"""\
@@ -343,6 +341,13 @@ def maybe_promote_master(self):
343341
# MAINPID does not change here, it was already set on fork
344342
systemd.sd_notify("READY=1\nMAINPID=%d\nSTATUS=Gunicorn arbiter promoted\n" % (os.getpid(), ), self.log)
345343

344+
elif self.systemd and len(self.WORKERS) >= 1:
345+
# still attached to old master, but we are ready to take over
346+
# this automates `kill -TERM $(cat /var/run/gunicorn.pid)`
347+
self.log.debug("systemd managed: shutting down old master %d after re-exec", self.master_pid)
348+
os.kill(self.master_pid, signal.SIGTERM)
349+
350+
346351
def wakeup(self):
347352
"""\
348353
Wake up the arbiter by writing to the PIPE
@@ -464,7 +469,7 @@ def reexec(self):
464469
self.log.debug("exe=%r argv=%r" % (self.START_CTX[0], self.START_CTX['args']))
465470
# let systemd know we will be in control after exec()
466471
systemd.sd_notify(
467-
"RELOADING=1\nMAINPID=%d\nSTATUS=Gunicorn arbiter re-exec in progress..\n" % (self.reexec_pid, ), self.log
472+
"RELOADING=1\nMAINPID=%d\nSTATUS=Gunicorn arbiter re-exec in progress..\n" % (os.getpid(), ), self.log
468473
)
469474
os.execve(self.START_CTX[0], self.START_CTX['args'], environ)
470475

0 commit comments

Comments
 (0)