Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get worker id from Gunicorn worker itself

I run multiple gunicorn workers with workers=4 setting. So as I understand I have 5 different processes: one gunicorn master process and 4 other worker processes. Can I get information about which worker is serving request at the moment? So can I get any worker id from inside worker itself like for each request send back a response with content: this request was served by worker:worker_id?

like image 560
Most Wanted Avatar asked Jan 06 '16 09:01

Most Wanted


People also ask

How do I access gunicorn logs?

This log file is located at /var/log/cloudify/rest/gunicorn-access.

Are gunicorn workers threads or processes?

Gunicorn is based on the pre-fork worker model. This means that there is a central master process that manages a set of worker processes. The master never knows anything about individual clients. All requests and responses are handled completely by worker processes.

How do I check my gunicorn process?

To see the processes is ps ax|grep gunicorn and to stop gunicorn_django is pkill gunicorn .

Does gunicorn workers share memory?

There is no shared memory between the workers. The suggested number of workers is (2*CPU)+1 . For a dual-core (2 CPU) machine, 5 is the suggested workers value. Gunicorn with default worker class (sync).


2 Answers

Within a worker code just use

import os
print(os.getpid())

Process id is a good enough identifier for such a case. Another option which is overkill obviously is to create a worker-id-file for each worker at this point https://docs.gunicorn.org/en/stable/settings.html?highlight=hooks#post-worker-init and read from it when needed. Do not forget to remove this file on exit https://docs.gunicorn.org/en/stable/settings.html?highlight=hooks#worker-exit

like image 88
Most Wanted Avatar answered Oct 06 '22 00:10

Most Wanted


For debugging purpose, you may use post_request hook to log the worker pid

def post_response(worker, req, environ, resp):
    worker.log.debug("%s", worker.pid)
like image 22
chuan Avatar answered Oct 05 '22 23:10

chuan