Login

Make runfcgi fail when database connection is open before fork

Author:
mpasternacki
Posted:
March 11, 2011
Language:
Python
Version:
Not specified
Tags:
fcgi prefork flup
Score:
0 (after 0 ratings)

FastCGI handler in prefork mode first imports every application, then forks. If any application during import opens connection to database, open connection is inherited by all of child processes; open db connection cannot be shared between processes, and if one process sends a request, another can receive a reply; also, if one process closes it, others have a desynchronized database handle.

See: http://stackoverflow.com/questions/1573579/psycopg2-disconnects-from-server http://stackoverflow.com/questions/393637/django-fastcgi-randomly-raising-operationalerror http://code.djangoproject.com/ticket/13215 http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48

If you put this snippet in your project-level init.py, then running manage.py runfcgi will fail loudly if the database connection is open in the parent process. This will happen only when you provide debug=true option to runfcgi to avoid monkey-patching code that runs in production mode.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# monkey-patch flup to fail loudly if database connection is open when
# preforked child starts - but ONLY when debug=true, so that we don't
# use monkey-patch on production.
import sys
if 'runfcgi' in sys.argv and 'debug=true' in sys.argv:
    from flup.server.preforkserver import PreforkServer
    def _spawnChild(self, sock):
        from django.db import connection
        if connection.connection is not None:
            raise Exception('''Django database connection is open. This MAY NOT happen.''')
        return self._spawnChild_orig(sock)
    PreforkServer._spawnChild_orig = PreforkServer._spawnChild
    PreforkServer._spawnChild = _spawnChild

More like this

  1. Effective content caching for mass-load site using redirect feature by nnseva 3 years, 9 months ago
  2. Fail Faster: unsafe_test Management Command by majgis 2 years, 8 months ago
  3. Binding signals to abstract models by andreterra 2 years, 11 months ago
  4. Run Django as a FastCGI authorizer by cme 6 years, 5 months ago
  5. Alternative to Class Based Views by sleepycal 2 years, 7 months ago

Comments

Please login first before commenting.