__init__.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # -*- coding: utf-8 -*-
  2. """Distributed Task Queue."""
  3. # :copyright: (c) 2015-2016 Ask Solem. All rights reserved.
  4. # :copyright: (c) 2012-2014 GoPivotal, Inc., All rights reserved.
  5. # :copyright: (c) 2009 - 2012 Ask Solem and individual contributors,
  6. # All rights reserved.
  7. # :license: BSD (3 Clause), see LICENSE for more details.
  8. from __future__ import absolute_import, print_function, unicode_literals
  9. import os
  10. import re
  11. import sys
  12. from collections import namedtuple
  13. SERIES = 'latentcall'
  14. __version__ = '4.1.0'
  15. __author__ = 'Ask Solem'
  16. __contact__ = 'ask@celeryproject.org'
  17. __homepage__ = 'http://celeryproject.org'
  18. __docformat__ = 'restructuredtext'
  19. __keywords__ = 'task job queue distributed messaging actor'
  20. # -eof meta-
  21. __all__ = (
  22. 'Celery', 'bugreport', 'shared_task', 'task',
  23. 'current_app', 'current_task', 'maybe_signature',
  24. 'chain', 'chord', 'chunks', 'group', 'signature',
  25. 'xmap', 'xstarmap', 'uuid',
  26. )
  27. VERSION_BANNER = '{0} ({1})'.format(__version__, SERIES)
  28. version_info_t = namedtuple('version_info_t', (
  29. 'major', 'minor', 'micro', 'releaselevel', 'serial',
  30. ))
  31. # bumpversion can only search for {current_version}
  32. # so we have to parse the version here.
  33. _temp = re.match(
  34. r'(\d+)\.(\d+).(\d+)(.+)?', __version__).groups()
  35. VERSION = version_info = version_info_t(
  36. int(_temp[0]), int(_temp[1]), int(_temp[2]), _temp[3] or '', '')
  37. del _temp
  38. del re
  39. if os.environ.get('C_IMPDEBUG'): # pragma: no cover
  40. from .five import builtins
  41. def debug_import(name, locals=None, globals=None,
  42. fromlist=None, level=-1, real_import=builtins.__import__):
  43. glob = globals or getattr(sys, 'emarfteg_'[::-1])(1).f_globals
  44. importer_name = glob and glob.get('__name__') or 'unknown'
  45. print('-- {0} imports {1}'.format(importer_name, name))
  46. return real_import(name, locals, globals, fromlist, level)
  47. builtins.__import__ = debug_import
  48. # This is never executed, but tricks static analyzers (PyDev, PyCharm,
  49. # pylint, etc.) into knowing the types of these symbols, and what
  50. # they contain.
  51. STATICA_HACK = True
  52. globals()['kcah_acitats'[::-1].upper()] = False
  53. if STATICA_HACK: # pragma: no cover
  54. from celery.app import shared_task # noqa
  55. from celery.app.base import Celery # noqa
  56. from celery.app.utils import bugreport # noqa
  57. from celery.app.task import Task # noqa
  58. from celery._state import current_app, current_task # noqa
  59. from celery.canvas import ( # noqa
  60. chain, chord, chunks, group,
  61. signature, maybe_signature, xmap, xstarmap, subtask,
  62. )
  63. from celery.utils import uuid # noqa
  64. # Eventlet/gevent patching must happen before importing
  65. # anything else, so these tools must be at top-level.
  66. def _find_option_with_arg(argv, short_opts=None, long_opts=None):
  67. """Search argv for options specifying short and longopt alternatives.
  68. Returns:
  69. str: value for option found
  70. Raises:
  71. KeyError: if option not found.
  72. """
  73. for i, arg in enumerate(argv):
  74. if arg.startswith('-'):
  75. if long_opts and arg.startswith('--'):
  76. name, sep, val = arg.partition('=')
  77. if name in long_opts:
  78. return val if sep else argv[i + 1]
  79. if short_opts and arg in short_opts:
  80. return argv[i + 1]
  81. raise KeyError('|'.join(short_opts or [] + long_opts or []))
  82. def _patch_eventlet():
  83. import eventlet
  84. import eventlet.debug
  85. eventlet.monkey_patch()
  86. blockdetect = float(os.environ.get('EVENTLET_NOBLOCK', 0))
  87. if blockdetect:
  88. eventlet.debug.hub_blocking_detection(blockdetect, blockdetect)
  89. def _patch_gevent():
  90. import gevent
  91. from gevent import monkey, signal as gevent_signal
  92. monkey.patch_all()
  93. if gevent.version_info[0] == 0: # pragma: no cover
  94. # Signals aren't working in gevent versions <1.0,
  95. # and aren't monkey patched by patch_all()
  96. _signal = __import__('signal')
  97. _signal.signal = gevent_signal
  98. def maybe_patch_concurrency(argv=sys.argv,
  99. short_opts=['-P'], long_opts=['--pool'],
  100. patches={'eventlet': _patch_eventlet,
  101. 'gevent': _patch_gevent}):
  102. """Apply eventlet/gevent monkeypatches.
  103. With short and long opt alternatives that specify the command line
  104. option to set the pool, this makes sure that anything that needs
  105. to be patched is completed as early as possible.
  106. (e.g., eventlet/gevent monkey patches).
  107. """
  108. try:
  109. pool = _find_option_with_arg(argv, short_opts, long_opts)
  110. except KeyError:
  111. pass
  112. else:
  113. try:
  114. patcher = patches[pool]
  115. except KeyError:
  116. pass
  117. else:
  118. patcher()
  119. # set up eventlet/gevent environments ASAP
  120. from celery import concurrency
  121. concurrency.get_implementation(pool)
  122. # Lazy loading
  123. from . import local # noqa
  124. # this just creates a new module, that imports stuff on first attribute
  125. # access. This makes the library faster to use.
  126. old_module, new_module = local.recreate_module( # pragma: no cover
  127. __name__,
  128. by_module={
  129. 'celery.app': ['Celery', 'bugreport', 'shared_task'],
  130. 'celery.app.task': ['Task'],
  131. 'celery._state': ['current_app', 'current_task'],
  132. 'celery.canvas': [
  133. 'Signature', 'chain', 'chord', 'chunks', 'group',
  134. 'signature', 'maybe_signature', 'subtask',
  135. 'xmap', 'xstarmap',
  136. ],
  137. 'celery.utils': ['uuid'],
  138. },
  139. direct={'task': 'celery.task'},
  140. __package__='celery', __file__=__file__,
  141. __path__=__path__, __doc__=__doc__, __version__=__version__,
  142. __author__=__author__, __contact__=__contact__,
  143. __homepage__=__homepage__, __docformat__=__docformat__, local=local,
  144. VERSION=VERSION, SERIES=SERIES, VERSION_BANNER=VERSION_BANNER,
  145. version_info_t=version_info_t,
  146. version_info=version_info,
  147. maybe_patch_concurrency=maybe_patch_concurrency,
  148. _find_option_with_arg=_find_option_with_arg,
  149. absolute_import=absolute_import,
  150. unicode_literals=unicode_literals,
  151. print_function=print_function,
  152. )