I'm using CherryPy with gunicorn and I need to have my application instance run its init on the main thread pre-fork and run some other method post-fork (assume I have a good reason - as I do). I can install a post_fork hook, but I can't see how I reach my application instance to call the method.
import logging
bind = '0.0.0.0:80'
workers = 3
preload_app = True
logconfig = 'logging.conf'
def post_fork(server, worker):
logging.info('server:%s worker:%s', server, worker)
# How to I reach #2 in server.Server.start? <-------- #1
import logging
import cherrypy
class Server:
def __init__(self):
# I need to run pre-fork
logging.info('init')
def start(self):
# I need to be called post-fork <-------- #2
logging.info('start')
@cherrypy.expose
def test(self):
return "ok"
application = cherrypy.Application(Server(), config={"global": {"environment": "embedded"}}
$ gunicorn -c config.py server:application
2019-08-14 00:42:26,033:22541:MainThread:INFO: init
2019-08-14 00:42:26,033:22541:MainThread:INFO: Starting gunicorn 19.9.0
2019-08-14 00:42:26,033:22541:MainThread:INFO: Listening at: http://0.0.0.0:80 (22541)
2019-08-14 00:42:26,033:22541:MainThread:INFO: Using worker: sync
2019-08-14 00:42:26,038:22544:MainThread:INFO: Booting worker with pid: 22544
2019-08-14 00:42:26,040:22544:MainThread:INFO: server:<gunicorn.arbiter.Arbiter object at 0x108f8efd0> worker:<Worker 22544>
2019-08-14 00:42:26,131:22545:MainThread:INFO: Booting worker with pid: 22545
2019-08-14 00:42:26,133:22545:MainThread:INFO: server:<gunicorn.arbiter.Arbiter object at 0x108f8efd0> worker:<Worker 22545>
2019-08-14 00:42:26,156:22546:MainThread:INFO: Booting worker with pid: 22546
2019-08-14 00:42:26,157:22546:MainThread:INFO: server:<gunicorn.arbiter.Arbiter object at 0x108f8efd0> worker:<Worker 22546>
After a bit more playing, I've found the answer:
def post_fork(server, worker):
worker.app.callable.root.start()