django.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. from __future__ import absolute_import
  2. import os
  3. import sys
  4. import warnings
  5. from kombu.utils import symbol_by_name
  6. from datetime import datetime
  7. from importlib import import_module
  8. from celery import signals
  9. from celery.exceptions import FixupWarning
  10. ERR_NOT_INSTALLED = """\
  11. Environment variable DJANGO_SETTINGS_MODULE is defined
  12. but Django is not installed. Will not apply Django fixups!
  13. """
  14. def _maybe_close_fd(fh):
  15. try:
  16. os.close(fh.fileno())
  17. except (AttributeError, OSError, TypeError):
  18. # TypeError added for celery#962
  19. pass
  20. def fixup(app, env='DJANGO_SETTINGS_MODULE'):
  21. SETTINGS_MODULE = os.environ.get(env)
  22. if SETTINGS_MODULE:
  23. try:
  24. import django # noqa
  25. except ImportError:
  26. warnings.warn(FixupWarning(ERR_NOT_INSTALLED))
  27. else:
  28. return DjangoFixup(app).install()
  29. class DjangoFixup(object):
  30. _db_recycles = 0
  31. def __init__(self, app):
  32. self.app = app
  33. self.db_reuse_max = self.app.conf.get('CELERY_DB_REUSE_MAX', None)
  34. self._db = import_module('django.db')
  35. self._cache = import_module('django.core.cache')
  36. self._settings = symbol_by_name('django.conf:settings')
  37. self._mail_admins = symbol_by_name('django.core.mail:mail_admins')
  38. # Current time and date
  39. try:
  40. self._now = symbol_by_name('django.utils.timezone:now')
  41. except ImportError: # pre django-1.4
  42. self._now = datetime.now # noqa
  43. # Database-related exceptions.
  44. DatabaseError = symbol_by_name('django.db:DatabaseError')
  45. try:
  46. import MySQLdb as mysql
  47. _my_database_errors = (mysql.DatabaseError,
  48. mysql.InterfaceError,
  49. mysql.OperationalError)
  50. except ImportError:
  51. _my_database_errors = () # noqa
  52. try:
  53. import psycopg2 as pg
  54. _pg_database_errors = (pg.DatabaseError,
  55. pg.InterfaceError,
  56. pg.OperationalError)
  57. except ImportError:
  58. _pg_database_errors = () # noqa
  59. try:
  60. import sqlite3
  61. _lite_database_errors = (sqlite3.DatabaseError,
  62. sqlite3.InterfaceError,
  63. sqlite3.OperationalError)
  64. except ImportError:
  65. _lite_database_errors = () # noqa
  66. try:
  67. import cx_Oracle as oracle
  68. _oracle_database_errors = (oracle.DatabaseError,
  69. oracle.InterfaceError,
  70. oracle.OperationalError)
  71. except ImportError:
  72. _oracle_database_errors = () # noqa
  73. try:
  74. self._close_old_connections = symbol_by_name(
  75. 'django.db:close_old_connections',
  76. )
  77. except ImportError:
  78. self._close_old_connections = None
  79. self.database_errors = (
  80. (DatabaseError, ) +
  81. _my_database_errors +
  82. _pg_database_errors +
  83. _lite_database_errors +
  84. _oracle_database_errors
  85. )
  86. def install(self):
  87. # Need to add project directory to path
  88. sys.path.append(os.getcwd())
  89. signals.beat_embedded_init.connect(self.close_database)
  90. signals.worker_ready.connect(self.on_worker_ready)
  91. signals.task_prerun.connect(self.on_task_prerun)
  92. signals.task_postrun.connect(self.on_task_postrun)
  93. signals.worker_init.connect(self.on_worker_init)
  94. signals.worker_process_init.connect(self.on_worker_process_init)
  95. self.app.loader.now = self.now
  96. self.app.loader.mail_admins = self.mail_admins
  97. return self
  98. def now(self, utc=False):
  99. return datetime.utcnow() if utc else self._now()
  100. def mail_admins(self, subject, body, fail_silently=False, **kwargs):
  101. return self._mail_admins(subject, body, fail_silently=fail_silently)
  102. def on_worker_init(self, **kwargs):
  103. """Called when the worker starts.
  104. Automatically discovers any ``tasks.py`` files in the applications
  105. listed in ``INSTALLED_APPS``.
  106. """
  107. self.close_database()
  108. self.close_cache()
  109. def on_worker_process_init(self, **kwargs):
  110. # the parent process may have established these,
  111. # so need to close them.
  112. # calling db.close() on some DB connections will cause
  113. # the inherited DB conn to also get broken in the parent
  114. # process so we need to remove it without triggering any
  115. # network IO that close() might cause.
  116. try:
  117. for c in self._db.connections.all():
  118. if c and c.connection:
  119. _maybe_close_fd(c.connection)
  120. except AttributeError:
  121. if self._db.connection and self._db.connection.connection:
  122. _maybe_close_fd(self._db.connection.connection)
  123. # use the _ version to avoid DB_REUSE preventing the conn.close() call
  124. self._close_database()
  125. self.close_cache()
  126. def on_task_prerun(self, sender, **kwargs):
  127. """Called before every task."""
  128. if not getattr(sender.request, 'is_eager', False):
  129. self.close_database()
  130. def on_task_postrun(self, **kwargs):
  131. """Does everything necessary for Django to work in a long-living,
  132. multiprocessing environment.
  133. """
  134. # See http://groups.google.com/group/django-users/
  135. # browse_thread/thread/78200863d0c07c6d/
  136. self.close_database()
  137. self.close_cache()
  138. def close_database(self, **kwargs):
  139. if self._close_old_connections:
  140. return self._close_old_connections() # Django 1.6
  141. if not self.db_reuse_max:
  142. return self._close_database()
  143. if self._db_recycles >= self.db_reuse_max * 2:
  144. self._db_recycles = 0
  145. self._close_database()
  146. self._db_recycles += 1
  147. def _close_database(self):
  148. try:
  149. funs = [conn.close for conn in self._db.connections]
  150. except AttributeError:
  151. funs = [self._db.close_connection] # pre multidb
  152. for close in funs:
  153. try:
  154. close()
  155. except self.database_errors as exc:
  156. str_exc = str(exc)
  157. if 'closed' not in str_exc and 'not connected' not in str_exc:
  158. raise
  159. def close_cache(self):
  160. try:
  161. self._cache.cache.close()
  162. except (TypeError, AttributeError):
  163. pass
  164. def on_worker_ready(self, **kwargs):
  165. if self._settings.DEBUG:
  166. warnings.warn('Using settings.DEBUG leads to a memory leak, never '
  167. 'use this setting in production environments!')