benoitc / gunicorn

gunicorn 'Green Unicorn' is a WSGI HTTP Server for UNIX, fast clients and sleepy applications.
http://www.gunicorn.org
Other
9.66k stars 1.74k forks source link

Logging in signal handlers may be unsafe #3198

Open vanschelven opened 3 months ago

vanschelven commented 3 months ago

In the arbiter's signal-handling code, there are many uses of logging. E.g.

https://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L252

however, the docs say this:

If you are implementing asynchronous signal handlers using the signal module, you may not be able to use logging from within such handlers. This is because lock implementations in the threading module are not always re-entrant, and so cannot be invoked from such signal handlers.

https://docs.python.org/3/library/logging.html#thread-safety

elsewhere Gregory Smith says the following:

I'd still rank "doing IO" even in a python signal handler (which is effectively possible to be executed between any given bytecode and between some operations using the C API that check the internal signal context) as a bad idea.

What the consequences of the above remarks are... may depend on how many signals you send.

pajod commented 3 months ago

Related: https://github.com/benoitc/gunicorn/issues/2816

We do have suggested changes, notably https://github.com/benoitc/gunicorn/pull/3148 attempting to address this.

hendrikmuhs commented 2 weeks ago

I've run into various issues issues with signals/logging/uvicorn. This issue contains the root cause for the problems we saw.

A summary that explains/connects various reported issues and might help others running into this:

Mitigation

The issue can be mitigated by decoupling logging using QueueHandler and QueueListener, provided by a custom logconfig(_dict/_json)