base.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. # -*- coding: utf-8 -*-
  2. """Actual App instance implementation."""
  3. from __future__ import absolute_import, unicode_literals
  4. import os
  5. import threading
  6. import warnings
  7. from collections import defaultdict, deque
  8. from datetime import datetime
  9. from operator import attrgetter
  10. from kombu import pools
  11. from kombu.clocks import LamportClock
  12. from kombu.common import oid_from
  13. from kombu.utils.compat import register_after_fork
  14. from kombu.utils.objects import cached_property
  15. from kombu.utils.uuid import uuid
  16. from vine import starpromise
  17. from vine.utils import wraps
  18. from celery import platforms, signals
  19. from celery._state import (_announce_app_finalized, _deregister_app,
  20. _register_app, _set_current_app, _task_stack,
  21. connect_on_app_finalize, get_current_app,
  22. get_current_worker_task, set_default_app)
  23. from celery.exceptions import AlwaysEagerIgnored, ImproperlyConfigured
  24. from celery.five import (UserDict, bytes_if_py2, python_2_unicode_compatible,
  25. values)
  26. from celery.loaders import get_loader_cls
  27. from celery.local import PromiseProxy, maybe_evaluate
  28. from celery.utils import abstract
  29. from celery.utils.collections import AttributeDictMixin
  30. from celery.utils.dispatch import Signal
  31. from celery.utils.functional import first, head_from_fun, maybe_list
  32. from celery.utils.imports import gen_task_name, instantiate, symbol_by_name
  33. from celery.utils.log import get_logger
  34. from celery.utils.objects import FallbackContext, mro_lookup
  35. from celery.utils.time import (get_exponential_backoff_interval, timezone,
  36. to_utc)
  37. # Load all builtin tasks
  38. from . import builtins # noqa
  39. from . import backends
  40. from .annotations import prepare as prepare_annotations
  41. from .defaults import find_deprecated_settings
  42. from .registry import TaskRegistry
  43. from .utils import (AppPickler, Settings, _new_key_to_old, _old_key_to_new,
  44. _unpickle_app, _unpickle_app_v2, appstr, bugreport,
  45. detect_settings)
  46. __all__ = ('Celery',)
  47. logger = get_logger(__name__)
  48. BUILTIN_FIXUPS = {
  49. 'celery.fixups.django:fixup',
  50. }
  51. USING_EXECV = os.environ.get('FORKED_BY_MULTIPROCESSING')
  52. ERR_ENVVAR_NOT_SET = """
  53. The environment variable {0!r} is not set,
  54. and as such the configuration could not be loaded.
  55. Please set this variable and make sure it points to
  56. a valid configuration module.
  57. Example:
  58. {0}="proj.celeryconfig"
  59. """
  60. def app_has_custom(app, attr):
  61. """Return true if app has customized method `attr`.
  62. Note:
  63. This is used for optimizations in cases where we know
  64. how the default behavior works, but need to account
  65. for someone using inheritance to override a method/property.
  66. """
  67. return mro_lookup(app.__class__, attr, stop={Celery, object},
  68. monkey_patched=[__name__])
  69. def _unpickle_appattr(reverse_name, args):
  70. """Unpickle app."""
  71. # Given an attribute name and a list of args, gets
  72. # the attribute from the current app and calls it.
  73. return get_current_app()._rgetattr(reverse_name)(*args)
  74. def _after_fork_cleanup_app(app):
  75. # This is used with multiprocessing.register_after_fork,
  76. # so need to be at module level.
  77. try:
  78. app._after_fork()
  79. except Exception as exc: # pylint: disable=broad-except
  80. logger.info('after forker raised exception: %r', exc, exc_info=1)
  81. class PendingConfiguration(UserDict, AttributeDictMixin):
  82. # `app.conf` will be of this type before being explicitly configured,
  83. # meaning the app can keep any configuration set directly
  84. # on `app.conf` before the `app.config_from_object` call.
  85. #
  86. # accessing any key will finalize the configuration,
  87. # replacing `app.conf` with a concrete settings object.
  88. callback = None
  89. _data = None
  90. def __init__(self, conf, callback):
  91. object.__setattr__(self, '_data', conf)
  92. object.__setattr__(self, 'callback', callback)
  93. def __setitem__(self, key, value):
  94. self._data[key] = value
  95. def clear(self):
  96. self._data.clear()
  97. def update(self, *args, **kwargs):
  98. self._data.update(*args, **kwargs)
  99. def setdefault(self, *args, **kwargs):
  100. return self._data.setdefault(*args, **kwargs)
  101. def __contains__(self, key):
  102. # XXX will not show finalized configuration
  103. # setdefault will cause `key in d` to happen,
  104. # so for setdefault to be lazy, so does contains.
  105. return key in self._data
  106. def __len__(self):
  107. return len(self.data)
  108. def __repr__(self):
  109. return repr(self.data)
  110. @cached_property
  111. def data(self):
  112. return self.callback()
  113. @python_2_unicode_compatible
  114. class Celery(object):
  115. """Celery application.
  116. Arguments:
  117. main (str): Name of the main module if running as `__main__`.
  118. This is used as the prefix for auto-generated task names.
  119. Keyword Arguments:
  120. broker (str): URL of the default broker used.
  121. backend (Union[str, type]): The result store backend class,
  122. or the name of the backend class to use.
  123. Default is the value of the :setting:`result_backend` setting.
  124. autofinalize (bool): If set to False a :exc:`RuntimeError`
  125. will be raised if the task registry or tasks are used before
  126. the app is finalized.
  127. set_as_current (bool): Make this the global current app.
  128. include (List[str]): List of modules every worker should import.
  129. amqp (Union[str, type]): AMQP object or class name.
  130. events (Union[str, type]): Events object or class name.
  131. log (Union[str, type]): Log object or class name.
  132. control (Union[str, type]): Control object or class name.
  133. tasks (Union[str, type]): A task registry, or the name of
  134. a registry class.
  135. fixups (List[str]): List of fix-up plug-ins (e.g., see
  136. :mod:`celery.fixups.django`).
  137. config_source (Union[str, type]): Take configuration from a class,
  138. or object. Attributes may include any setings described in
  139. the documentation.
  140. """
  141. #: This is deprecated, use :meth:`reduce_keys` instead
  142. Pickler = AppPickler
  143. SYSTEM = platforms.SYSTEM
  144. IS_macOS, IS_WINDOWS = platforms.IS_macOS, platforms.IS_WINDOWS
  145. #: Name of the `__main__` module. Required for standalone scripts.
  146. #:
  147. #: If set this will be used instead of `__main__` when automatically
  148. #: generating task names.
  149. main = None
  150. #: Custom options for command-line programs.
  151. #: See :ref:`extending-commandoptions`
  152. user_options = None
  153. #: Custom bootsteps to extend and modify the worker.
  154. #: See :ref:`extending-bootsteps`.
  155. steps = None
  156. builtin_fixups = BUILTIN_FIXUPS
  157. amqp_cls = 'celery.app.amqp:AMQP'
  158. backend_cls = None
  159. events_cls = 'celery.app.events:Events'
  160. loader_cls = None
  161. log_cls = 'celery.app.log:Logging'
  162. control_cls = 'celery.app.control:Control'
  163. task_cls = 'celery.app.task:Task'
  164. registry_cls = 'celery.app.registry:TaskRegistry'
  165. _fixups = None
  166. _pool = None
  167. _conf = None
  168. _after_fork_registered = False
  169. #: Signal sent when app is loading configuration.
  170. on_configure = None
  171. #: Signal sent after app has prepared the configuration.
  172. on_after_configure = None
  173. #: Signal sent after app has been finalized.
  174. on_after_finalize = None
  175. #: Signal sent by every new process after fork.
  176. on_after_fork = None
  177. def __init__(self, main=None, loader=None, backend=None,
  178. amqp=None, events=None, log=None, control=None,
  179. set_as_current=True, tasks=None, broker=None, include=None,
  180. changes=None, config_source=None, fixups=None, task_cls=None,
  181. autofinalize=True, namespace=None, strict_typing=True,
  182. **kwargs):
  183. self.clock = LamportClock()
  184. self.main = main
  185. self.amqp_cls = amqp or self.amqp_cls
  186. self.events_cls = events or self.events_cls
  187. self.loader_cls = loader or self._get_default_loader()
  188. self.log_cls = log or self.log_cls
  189. self.control_cls = control or self.control_cls
  190. self.task_cls = task_cls or self.task_cls
  191. self.set_as_current = set_as_current
  192. self.registry_cls = symbol_by_name(self.registry_cls)
  193. self.user_options = defaultdict(set)
  194. self.steps = defaultdict(set)
  195. self.autofinalize = autofinalize
  196. self.namespace = namespace
  197. self.strict_typing = strict_typing
  198. self.configured = False
  199. self._config_source = config_source
  200. self._pending_defaults = deque()
  201. self._pending_periodic_tasks = deque()
  202. self.finalized = False
  203. self._finalize_mutex = threading.Lock()
  204. self._pending = deque()
  205. self._tasks = tasks
  206. if not isinstance(self._tasks, TaskRegistry):
  207. self._tasks = self.registry_cls(self._tasks or {})
  208. # If the class defines a custom __reduce_args__ we need to use
  209. # the old way of pickling apps: pickling a list of
  210. # args instead of the new way that pickles a dict of keywords.
  211. self._using_v1_reduce = app_has_custom(self, '__reduce_args__')
  212. # these options are moved to the config to
  213. # simplify pickling of the app object.
  214. self._preconf = changes or {}
  215. self._preconf_set_by_auto = set()
  216. self.__autoset('broker_url', broker)
  217. self.__autoset('result_backend', backend)
  218. self.__autoset('include', include)
  219. self._conf = Settings(
  220. PendingConfiguration(
  221. self._preconf, self._finalize_pending_conf),
  222. prefix=self.namespace,
  223. keys=(_old_key_to_new, _new_key_to_old),
  224. )
  225. # - Apply fix-ups.
  226. self.fixups = set(self.builtin_fixups) if fixups is None else fixups
  227. # ...store fixup instances in _fixups to keep weakrefs alive.
  228. self._fixups = [symbol_by_name(fixup)(self) for fixup in self.fixups]
  229. if self.set_as_current:
  230. self.set_current()
  231. # Signals
  232. if self.on_configure is None:
  233. # used to be a method pre 4.0
  234. self.on_configure = Signal(name='app.on_configure')
  235. self.on_after_configure = Signal(
  236. name='app.on_after_configure',
  237. providing_args={'source'},
  238. )
  239. self.on_after_finalize = Signal(name='app.on_after_finalize')
  240. self.on_after_fork = Signal(name='app.on_after_fork')
  241. self.on_init()
  242. _register_app(self)
  243. def _get_default_loader(self):
  244. # the --loader command-line argument sets the environment variable.
  245. return (
  246. os.environ.get('CELERY_LOADER') or
  247. self.loader_cls or
  248. 'celery.loaders.app:AppLoader'
  249. )
  250. def on_init(self):
  251. """Optional callback called at init."""
  252. def __autoset(self, key, value):
  253. if value:
  254. self._preconf[key] = value
  255. self._preconf_set_by_auto.add(key)
  256. def set_current(self):
  257. """Make this the current app for this thread."""
  258. _set_current_app(self)
  259. def set_default(self):
  260. """Make this the default app for all threads."""
  261. set_default_app(self)
  262. def _ensure_after_fork(self):
  263. if not self._after_fork_registered:
  264. self._after_fork_registered = True
  265. if register_after_fork is not None:
  266. register_after_fork(self, _after_fork_cleanup_app)
  267. def close(self):
  268. """Clean up after the application.
  269. Only necessary for dynamically created apps, and you should
  270. probably use the :keyword:`with` statement instead.
  271. Example:
  272. >>> with Celery(set_as_current=False) as app:
  273. ... with app.connection_for_write() as conn:
  274. ... pass
  275. """
  276. self._pool = None
  277. _deregister_app(self)
  278. def start(self, argv=None):
  279. """Run :program:`celery` using `argv`.
  280. Uses :data:`sys.argv` if `argv` is not specified.
  281. """
  282. return instantiate(
  283. 'celery.bin.celery:CeleryCommand', app=self
  284. ).execute_from_commandline(argv)
  285. def worker_main(self, argv=None):
  286. """Run :program:`celery worker` using `argv`.
  287. Uses :data:`sys.argv` if `argv` is not specified.
  288. """
  289. return instantiate(
  290. 'celery.bin.worker:worker', app=self
  291. ).execute_from_commandline(argv)
  292. def task(self, *args, **opts):
  293. """Decorator to create a task class out of any callable.
  294. Examples:
  295. .. code-block:: python
  296. @app.task
  297. def refresh_feed(url):
  298. store_feed(feedparser.parse(url))
  299. with setting extra options:
  300. .. code-block:: python
  301. @app.task(exchange='feeds')
  302. def refresh_feed(url):
  303. return store_feed(feedparser.parse(url))
  304. Note:
  305. App Binding: For custom apps the task decorator will return
  306. a proxy object, so that the act of creating the task is not
  307. performed until the task is used or the task registry is accessed.
  308. If you're depending on binding to be deferred, then you must
  309. not access any attributes on the returned object until the
  310. application is fully set up (finalized).
  311. """
  312. if USING_EXECV and opts.get('lazy', True):
  313. # When using execv the task in the original module will point to a
  314. # different app, so doing things like 'add.request' will point to
  315. # a different task instance. This makes sure it will always use
  316. # the task instance from the current app.
  317. # Really need a better solution for this :(
  318. from . import shared_task
  319. return shared_task(*args, lazy=False, **opts)
  320. def inner_create_task_cls(shared=True, filter=None, lazy=True, **opts):
  321. _filt = filter # stupid 2to3
  322. def _create_task_cls(fun):
  323. if shared:
  324. def cons(app):
  325. return app._task_from_fun(fun, **opts)
  326. cons.__name__ = fun.__name__
  327. connect_on_app_finalize(cons)
  328. if not lazy or self.finalized:
  329. ret = self._task_from_fun(fun, **opts)
  330. else:
  331. # return a proxy object that evaluates on first use
  332. ret = PromiseProxy(self._task_from_fun, (fun,), opts,
  333. __doc__=fun.__doc__)
  334. self._pending.append(ret)
  335. if _filt:
  336. return _filt(ret)
  337. return ret
  338. return _create_task_cls
  339. if len(args) == 1:
  340. if callable(args[0]):
  341. return inner_create_task_cls(**opts)(*args)
  342. raise TypeError('argument 1 to @task() must be a callable')
  343. if args:
  344. raise TypeError(
  345. '@task() takes exactly 1 argument ({0} given)'.format(
  346. sum([len(args), len(opts)])))
  347. return inner_create_task_cls(**opts)
  348. def _task_from_fun(self, fun, name=None, base=None, bind=False, **options):
  349. if not self.finalized and not self.autofinalize:
  350. raise RuntimeError('Contract breach: app not finalized')
  351. name = name or self.gen_task_name(fun.__name__, fun.__module__)
  352. base = base or self.Task
  353. if name not in self._tasks:
  354. run = fun if bind else staticmethod(fun)
  355. task = type(fun.__name__, (base,), dict({
  356. 'app': self,
  357. 'name': name,
  358. 'run': run,
  359. '_decorated': True,
  360. '__doc__': fun.__doc__,
  361. '__module__': fun.__module__,
  362. '__header__': staticmethod(head_from_fun(fun, bound=bind)),
  363. '__wrapped__': run}, **options))()
  364. # for some reason __qualname__ cannot be set in type()
  365. # so we have to set it here.
  366. try:
  367. task.__qualname__ = fun.__qualname__
  368. except AttributeError:
  369. pass
  370. self._tasks[task.name] = task
  371. task.bind(self) # connects task to this app
  372. autoretry_for = tuple(options.get('autoretry_for', ()))
  373. retry_kwargs = options.get('retry_kwargs', {})
  374. retry_backoff = int(options.get('retry_backoff', False))
  375. retry_backoff_max = int(options.get('retry_backoff_max', 600))
  376. retry_jitter = options.get('retry_jitter', True)
  377. if autoretry_for and not hasattr(task, '_orig_run'):
  378. @wraps(task.run)
  379. def run(*args, **kwargs):
  380. try:
  381. return task._orig_run(*args, **kwargs)
  382. except autoretry_for as exc:
  383. if retry_backoff:
  384. retry_kwargs['countdown'] = \
  385. get_exponential_backoff_interval(
  386. factor=retry_backoff,
  387. retries=task.request.retries,
  388. maximum=retry_backoff_max,
  389. full_jitter=retry_jitter)
  390. raise task.retry(exc=exc, **retry_kwargs)
  391. task._orig_run, task.run = task.run, run
  392. else:
  393. task = self._tasks[name]
  394. return task
  395. def register_task(self, task):
  396. """Utility for registering a task-based class.
  397. Note:
  398. This is here for compatibility with old Celery 1.0
  399. style task classes, you should not need to use this for
  400. new projects.
  401. """
  402. if not task.name:
  403. task_cls = type(task)
  404. task.name = self.gen_task_name(
  405. task_cls.__name__, task_cls.__module__)
  406. self.tasks[task.name] = task
  407. task._app = self
  408. task.bind(self)
  409. return task
  410. def gen_task_name(self, name, module):
  411. return gen_task_name(self, name, module)
  412. def finalize(self, auto=False):
  413. """Finalize the app.
  414. This loads built-in tasks, evaluates pending task decorators,
  415. reads configuration, etc.
  416. """
  417. with self._finalize_mutex:
  418. if not self.finalized:
  419. if auto and not self.autofinalize:
  420. raise RuntimeError('Contract breach: app not finalized')
  421. self.finalized = True
  422. _announce_app_finalized(self)
  423. pending = self._pending
  424. while pending:
  425. maybe_evaluate(pending.popleft())
  426. for task in values(self._tasks):
  427. task.bind(self)
  428. self.on_after_finalize.send(sender=self)
  429. def add_defaults(self, fun):
  430. """Add default configuration from dict ``d``.
  431. If the argument is a callable function then it will be regarded
  432. as a promise, and it won't be loaded until the configuration is
  433. actually needed.
  434. This method can be compared to:
  435. .. code-block:: pycon
  436. >>> celery.conf.update(d)
  437. with a difference that 1) no copy will be made and 2) the dict will
  438. not be transferred when the worker spawns child processes, so
  439. it's important that the same configuration happens at import time
  440. when pickle restores the object on the other side.
  441. """
  442. if not callable(fun):
  443. d, fun = fun, lambda: d
  444. if self.configured:
  445. return self._conf.add_defaults(fun())
  446. self._pending_defaults.append(fun)
  447. def config_from_object(self, obj,
  448. silent=False, force=False, namespace=None):
  449. """Read configuration from object.
  450. Object is either an actual object or the name of a module to import.
  451. Example:
  452. >>> celery.config_from_object('myapp.celeryconfig')
  453. >>> from myapp import celeryconfig
  454. >>> celery.config_from_object(celeryconfig)
  455. Arguments:
  456. silent (bool): If true then import errors will be ignored.
  457. force (bool): Force reading configuration immediately.
  458. By default the configuration will be read only when required.
  459. """
  460. self._config_source = obj
  461. self.namespace = namespace or self.namespace
  462. if force or self.configured:
  463. self._conf = None
  464. if self.loader.config_from_object(obj, silent=silent):
  465. return self.conf
  466. def config_from_envvar(self, variable_name, silent=False, force=False):
  467. """Read configuration from environment variable.
  468. The value of the environment variable must be the name
  469. of a module to import.
  470. Example:
  471. >>> os.environ['CELERY_CONFIG_MODULE'] = 'myapp.celeryconfig'
  472. >>> celery.config_from_envvar('CELERY_CONFIG_MODULE')
  473. """
  474. module_name = os.environ.get(variable_name)
  475. if not module_name:
  476. if silent:
  477. return False
  478. raise ImproperlyConfigured(
  479. ERR_ENVVAR_NOT_SET.strip().format(variable_name))
  480. return self.config_from_object(module_name, silent=silent, force=force)
  481. def config_from_cmdline(self, argv, namespace='celery'):
  482. self._conf.update(
  483. self.loader.cmdline_config_parser(argv, namespace)
  484. )
  485. def setup_security(self, allowed_serializers=None, key=None, cert=None,
  486. store=None, digest='sha1', serializer='json'):
  487. """Setup the message-signing serializer.
  488. This will affect all application instances (a global operation).
  489. Disables untrusted serializers and if configured to use the ``auth``
  490. serializer will register the ``auth`` serializer with the provided
  491. settings into the Kombu serializer registry.
  492. Arguments:
  493. allowed_serializers (Set[str]): List of serializer names, or
  494. content_types that should be exempt from being disabled.
  495. key (str): Name of private key file to use.
  496. Defaults to the :setting:`security_key` setting.
  497. cert (str): Name of certificate file to use.
  498. Defaults to the :setting:`security_certificate` setting.
  499. store (str): Directory containing certificates.
  500. Defaults to the :setting:`security_cert_store` setting.
  501. digest (str): Digest algorithm used when signing messages.
  502. Default is ``sha1``.
  503. serializer (str): Serializer used to encode messages after
  504. they've been signed. See :setting:`task_serializer` for
  505. the serializers supported. Default is ``json``.
  506. """
  507. from celery.security import setup_security
  508. return setup_security(allowed_serializers, key, cert,
  509. store, digest, serializer, app=self)
  510. def autodiscover_tasks(self, packages=None,
  511. related_name='tasks', force=False):
  512. """Auto-discover task modules.
  513. Searches a list of packages for a "tasks.py" module (or use
  514. related_name argument).
  515. If the name is empty, this will be delegated to fix-ups (e.g., Django).
  516. For example if you have a directory layout like this:
  517. .. code-block:: text
  518. foo/__init__.py
  519. tasks.py
  520. models.py
  521. bar/__init__.py
  522. tasks.py
  523. models.py
  524. baz/__init__.py
  525. models.py
  526. Then calling ``app.autodiscover_tasks(['foo', 'bar', 'baz'])`` will
  527. result in the modules ``foo.tasks`` and ``bar.tasks`` being imported.
  528. Arguments:
  529. packages (List[str]): List of packages to search.
  530. This argument may also be a callable, in which case the
  531. value returned is used (for lazy evaluation).
  532. related_name (str): The name of the module to find. Defaults
  533. to "tasks": meaning "look for 'module.tasks' for every
  534. module in ``packages``."
  535. force (bool): By default this call is lazy so that the actual
  536. auto-discovery won't happen until an application imports
  537. the default modules. Forcing will cause the auto-discovery
  538. to happen immediately.
  539. """
  540. if force:
  541. return self._autodiscover_tasks(packages, related_name)
  542. signals.import_modules.connect(starpromise(
  543. self._autodiscover_tasks, packages, related_name,
  544. ), weak=False, sender=self)
  545. def _autodiscover_tasks(self, packages, related_name, **kwargs):
  546. if packages:
  547. return self._autodiscover_tasks_from_names(packages, related_name)
  548. return self._autodiscover_tasks_from_fixups(related_name)
  549. def _autodiscover_tasks_from_names(self, packages, related_name):
  550. # packages argument can be lazy
  551. return self.loader.autodiscover_tasks(
  552. packages() if callable(packages) else packages, related_name,
  553. )
  554. def _autodiscover_tasks_from_fixups(self, related_name):
  555. return self._autodiscover_tasks_from_names([
  556. pkg for fixup in self._fixups
  557. for pkg in fixup.autodiscover_tasks()
  558. if hasattr(fixup, 'autodiscover_tasks')
  559. ], related_name=related_name)
  560. def send_task(self, name, args=None, kwargs=None, countdown=None,
  561. eta=None, task_id=None, producer=None, connection=None,
  562. router=None, result_cls=None, expires=None,
  563. publisher=None, link=None, link_error=None,
  564. add_to_parent=True, group_id=None, retries=0, chord=None,
  565. reply_to=None, time_limit=None, soft_time_limit=None,
  566. root_id=None, parent_id=None, route_name=None,
  567. shadow=None, chain=None, task_type=None, **options):
  568. """Send task by name.
  569. Supports the same arguments as :meth:`@-Task.apply_async`.
  570. Arguments:
  571. name (str): Name of task to call (e.g., `"tasks.add"`).
  572. result_cls (~@AsyncResult): Specify custom result class.
  573. """
  574. parent = have_parent = None
  575. amqp = self.amqp
  576. task_id = task_id or uuid()
  577. producer = producer or publisher # XXX compat
  578. router = router or amqp.router
  579. conf = self.conf
  580. if conf.task_always_eager: # pragma: no cover
  581. warnings.warn(AlwaysEagerIgnored(
  582. 'task_always_eager has no effect on send_task',
  583. ), stacklevel=2)
  584. options = router.route(
  585. options, route_name or name, args, kwargs, task_type)
  586. if not root_id or not parent_id:
  587. parent = self.current_worker_task
  588. if parent:
  589. if not root_id:
  590. root_id = parent.request.root_id or parent.request.id
  591. if not parent_id:
  592. parent_id = parent.request.id
  593. message = amqp.create_task_message(
  594. task_id, name, args, kwargs, countdown, eta, group_id,
  595. expires, retries, chord,
  596. maybe_list(link), maybe_list(link_error),
  597. reply_to or self.oid, time_limit, soft_time_limit,
  598. self.conf.task_send_sent_event,
  599. root_id, parent_id, shadow, chain,
  600. argsrepr=options.get('argsrepr'),
  601. kwargsrepr=options.get('kwargsrepr'),
  602. )
  603. if connection:
  604. producer = amqp.Producer(connection, auto_declare=False)
  605. with self.producer_or_acquire(producer) as P:
  606. with P.connection._reraise_as_library_errors():
  607. self.backend.on_task_call(P, task_id)
  608. amqp.send_task_message(P, name, message, **options)
  609. result = (result_cls or self.AsyncResult)(task_id)
  610. if add_to_parent:
  611. if not have_parent:
  612. parent, have_parent = self.current_worker_task, True
  613. if parent:
  614. parent.add_trail(result)
  615. return result
  616. def connection_for_read(self, url=None, **kwargs):
  617. """Establish connection used for consuming.
  618. See Also:
  619. :meth:`connection` for supported arguments.
  620. """
  621. return self._connection(url or self.conf.broker_read_url, **kwargs)
  622. def connection_for_write(self, url=None, **kwargs):
  623. """Establish connection used for producing.
  624. See Also:
  625. :meth:`connection` for supported arguments.
  626. """
  627. return self._connection(url or self.conf.broker_write_url, **kwargs)
  628. def connection(self, hostname=None, userid=None, password=None,
  629. virtual_host=None, port=None, ssl=None,
  630. connect_timeout=None, transport=None,
  631. transport_options=None, heartbeat=None,
  632. login_method=None, failover_strategy=None, **kwargs):
  633. """Establish a connection to the message broker.
  634. Please use :meth:`connection_for_read` and
  635. :meth:`connection_for_write` instead, to convey the intent
  636. of use for this connection.
  637. Arguments:
  638. url: Either the URL or the hostname of the broker to use.
  639. hostname (str): URL, Hostname/IP-address of the broker.
  640. If a URL is used, then the other argument below will
  641. be taken from the URL instead.
  642. userid (str): Username to authenticate as.
  643. password (str): Password to authenticate with
  644. virtual_host (str): Virtual host to use (domain).
  645. port (int): Port to connect to.
  646. ssl (bool, Dict): Defaults to the :setting:`broker_use_ssl`
  647. setting.
  648. transport (str): defaults to the :setting:`broker_transport`
  649. setting.
  650. transport_options (Dict): Dictionary of transport specific options.
  651. heartbeat (int): AMQP Heartbeat in seconds (``pyamqp`` only).
  652. login_method (str): Custom login method to use (AMQP only).
  653. failover_strategy (str, Callable): Custom failover strategy.
  654. **kwargs: Additional arguments to :class:`kombu.Connection`.
  655. Returns:
  656. kombu.Connection: the lazy connection instance.
  657. """
  658. return self.connection_for_write(
  659. hostname or self.conf.broker_write_url,
  660. userid=userid, password=password,
  661. virtual_host=virtual_host, port=port, ssl=ssl,
  662. connect_timeout=connect_timeout, transport=transport,
  663. transport_options=transport_options, heartbeat=heartbeat,
  664. login_method=login_method, failover_strategy=failover_strategy,
  665. **kwargs
  666. )
  667. def _connection(self, url, userid=None, password=None,
  668. virtual_host=None, port=None, ssl=None,
  669. connect_timeout=None, transport=None,
  670. transport_options=None, heartbeat=None,
  671. login_method=None, failover_strategy=None, **kwargs):
  672. conf = self.conf
  673. return self.amqp.Connection(
  674. url,
  675. userid or conf.broker_user,
  676. password or conf.broker_password,
  677. virtual_host or conf.broker_vhost,
  678. port or conf.broker_port,
  679. transport=transport or conf.broker_transport,
  680. ssl=self.either('broker_use_ssl', ssl),
  681. heartbeat=heartbeat or self.conf.broker_heartbeat,
  682. login_method=login_method or conf.broker_login_method,
  683. failover_strategy=(
  684. failover_strategy or conf.broker_failover_strategy
  685. ),
  686. transport_options=dict(
  687. conf.broker_transport_options, **transport_options or {}
  688. ),
  689. connect_timeout=self.either(
  690. 'broker_connection_timeout', connect_timeout
  691. ),
  692. )
  693. broker_connection = connection
  694. def _acquire_connection(self, pool=True):
  695. """Helper for :meth:`connection_or_acquire`."""
  696. if pool:
  697. return self.pool.acquire(block=True)
  698. return self.connection_for_write()
  699. def connection_or_acquire(self, connection=None, pool=True, *_, **__):
  700. """Context used to acquire a connection from the pool.
  701. For use within a :keyword:`with` statement to get a connection
  702. from the pool if one is not already provided.
  703. Arguments:
  704. connection (kombu.Connection): If not provided, a connection
  705. will be acquired from the connection pool.
  706. """
  707. return FallbackContext(connection, self._acquire_connection, pool=pool)
  708. default_connection = connection_or_acquire # XXX compat
  709. def producer_or_acquire(self, producer=None):
  710. """Context used to acquire a producer from the pool.
  711. For use within a :keyword:`with` statement to get a producer
  712. from the pool if one is not already provided
  713. Arguments:
  714. producer (kombu.Producer): If not provided, a producer
  715. will be acquired from the producer pool.
  716. """
  717. return FallbackContext(
  718. producer, self.producer_pool.acquire, block=True,
  719. )
  720. default_producer = producer_or_acquire # XXX compat
  721. def prepare_config(self, c):
  722. """Prepare configuration before it is merged with the defaults."""
  723. return find_deprecated_settings(c)
  724. def now(self):
  725. """Return the current time and date as a datetime."""
  726. now_in_utc = to_utc(datetime.utcnow())
  727. return now_in_utc.astimezone(self.timezone)
  728. def select_queues(self, queues=None):
  729. """Select subset of queues.
  730. Arguments:
  731. queues (Sequence[str]): a list of queue names to keep.
  732. """
  733. return self.amqp.queues.select(queues)
  734. def either(self, default_key, *defaults):
  735. """Get key from configuration or use default values.
  736. Fallback to the value of a configuration key if none of the
  737. `*values` are true.
  738. """
  739. return first(None, [
  740. first(None, defaults), starpromise(self.conf.get, default_key),
  741. ])
  742. def bugreport(self):
  743. """Return information useful in bug reports."""
  744. return bugreport(self)
  745. def _get_backend(self):
  746. backend, url = backends.by_url(
  747. self.backend_cls or self.conf.result_backend,
  748. self.loader)
  749. return backend(app=self, url=url)
  750. def _finalize_pending_conf(self):
  751. """Get config value by key and finalize loading the configuration.
  752. Note:
  753. This is used by PendingConfiguration:
  754. as soon as you access a key the configuration is read.
  755. """
  756. conf = self._conf = self._load_config()
  757. return conf
  758. def _load_config(self):
  759. if isinstance(self.on_configure, Signal):
  760. self.on_configure.send(sender=self)
  761. else:
  762. # used to be a method pre 4.0
  763. self.on_configure()
  764. if self._config_source:
  765. self.loader.config_from_object(self._config_source)
  766. self.configured = True
  767. settings = detect_settings(
  768. self.prepare_config(self.loader.conf), self._preconf,
  769. ignore_keys=self._preconf_set_by_auto, prefix=self.namespace,
  770. )
  771. if self._conf is not None:
  772. # replace in place, as someone may have referenced app.conf,
  773. # done some changes, accessed a key, and then try to make more
  774. # changes to the reference and not the finalized value.
  775. self._conf.swap_with(settings)
  776. else:
  777. self._conf = settings
  778. # load lazy config dict initializers.
  779. pending_def = self._pending_defaults
  780. while pending_def:
  781. self._conf.add_defaults(maybe_evaluate(pending_def.popleft()()))
  782. # load lazy periodic tasks
  783. pending_beat = self._pending_periodic_tasks
  784. while pending_beat:
  785. self._add_periodic_task(*pending_beat.popleft())
  786. self.on_after_configure.send(sender=self, source=self._conf)
  787. return self._conf
  788. def _after_fork(self):
  789. self._pool = None
  790. try:
  791. self.__dict__['amqp']._producer_pool = None
  792. except (AttributeError, KeyError):
  793. pass
  794. self.on_after_fork.send(sender=self)
  795. def signature(self, *args, **kwargs):
  796. """Return a new :class:`~celery.Signature` bound to this app."""
  797. kwargs['app'] = self
  798. return self._canvas.signature(*args, **kwargs)
  799. def add_periodic_task(self, schedule, sig,
  800. args=(), kwargs=(), name=None, **opts):
  801. key, entry = self._sig_to_periodic_task_entry(
  802. schedule, sig, args, kwargs, name, **opts)
  803. if self.configured:
  804. self._add_periodic_task(key, entry)
  805. else:
  806. self._pending_periodic_tasks.append((key, entry))
  807. return key
  808. def _sig_to_periodic_task_entry(self, schedule, sig,
  809. args=(), kwargs={}, name=None, **opts):
  810. sig = (sig.clone(args, kwargs)
  811. if isinstance(sig, abstract.CallableSignature)
  812. else self.signature(sig.name, args, kwargs))
  813. return name or repr(sig), {
  814. 'schedule': schedule,
  815. 'task': sig.name,
  816. 'args': sig.args,
  817. 'kwargs': sig.kwargs,
  818. 'options': dict(sig.options, **opts),
  819. }
  820. def _add_periodic_task(self, key, entry):
  821. self._conf.beat_schedule[key] = entry
  822. def create_task_cls(self):
  823. """Create a base task class bound to this app."""
  824. return self.subclass_with_self(
  825. self.task_cls, name='Task', attribute='_app',
  826. keep_reduce=True, abstract=True,
  827. )
  828. def subclass_with_self(self, Class, name=None, attribute='app',
  829. reverse=None, keep_reduce=False, **kw):
  830. """Subclass an app-compatible class.
  831. App-compatible means that the class has a class attribute that
  832. provides the default app it should use, for example:
  833. ``class Foo: app = None``.
  834. Arguments:
  835. Class (type): The app-compatible class to subclass.
  836. name (str): Custom name for the target class.
  837. attribute (str): Name of the attribute holding the app,
  838. Default is 'app'.
  839. reverse (str): Reverse path to this object used for pickling
  840. purposes. For example, to get ``app.AsyncResult``,
  841. use ``"AsyncResult"``.
  842. keep_reduce (bool): If enabled a custom ``__reduce__``
  843. implementation won't be provided.
  844. """
  845. Class = symbol_by_name(Class)
  846. reverse = reverse if reverse else Class.__name__
  847. def __reduce__(self):
  848. return _unpickle_appattr, (reverse, self.__reduce_args__())
  849. attrs = dict(
  850. {attribute: self},
  851. __module__=Class.__module__,
  852. __doc__=Class.__doc__,
  853. **kw)
  854. if not keep_reduce:
  855. attrs['__reduce__'] = __reduce__
  856. return type(bytes_if_py2(name or Class.__name__), (Class,), attrs)
  857. def _rgetattr(self, path):
  858. return attrgetter(path)(self)
  859. def __enter__(self):
  860. return self
  861. def __exit__(self, *exc_info):
  862. self.close()
  863. def __repr__(self):
  864. return '<{0} {1}>'.format(type(self).__name__, appstr(self))
  865. def __reduce__(self):
  866. if self._using_v1_reduce:
  867. return self.__reduce_v1__()
  868. return (_unpickle_app_v2, (self.__class__, self.__reduce_keys__()))
  869. def __reduce_v1__(self):
  870. # Reduce only pickles the configuration changes,
  871. # so the default configuration doesn't have to be passed
  872. # between processes.
  873. return (
  874. _unpickle_app,
  875. (self.__class__, self.Pickler) + self.__reduce_args__(),
  876. )
  877. def __reduce_keys__(self):
  878. """Keyword arguments used to reconstruct the object when unpickling."""
  879. return {
  880. 'main': self.main,
  881. 'changes':
  882. self._conf.changes if self.configured else self._preconf,
  883. 'loader': self.loader_cls,
  884. 'backend': self.backend_cls,
  885. 'amqp': self.amqp_cls,
  886. 'events': self.events_cls,
  887. 'log': self.log_cls,
  888. 'control': self.control_cls,
  889. 'fixups': self.fixups,
  890. 'config_source': self._config_source,
  891. 'task_cls': self.task_cls,
  892. 'namespace': self.namespace,
  893. }
  894. def __reduce_args__(self):
  895. """Deprecated method, please use :meth:`__reduce_keys__` instead."""
  896. return (self.main, self._conf.changes if self.configured else {},
  897. self.loader_cls, self.backend_cls, self.amqp_cls,
  898. self.events_cls, self.log_cls, self.control_cls,
  899. False, self._config_source)
  900. @cached_property
  901. def Worker(self):
  902. """Worker application.
  903. See Also:
  904. :class:`~@Worker`.
  905. """
  906. return self.subclass_with_self('celery.apps.worker:Worker')
  907. @cached_property
  908. def WorkController(self, **kwargs):
  909. """Embeddable worker.
  910. See Also:
  911. :class:`~@WorkController`.
  912. """
  913. return self.subclass_with_self('celery.worker:WorkController')
  914. @cached_property
  915. def Beat(self, **kwargs):
  916. """:program:`celery beat` scheduler application.
  917. See Also:
  918. :class:`~@Beat`.
  919. """
  920. return self.subclass_with_self('celery.apps.beat:Beat')
  921. @cached_property
  922. def Task(self):
  923. """Base task class for this app."""
  924. return self.create_task_cls()
  925. @cached_property
  926. def annotations(self):
  927. return prepare_annotations(self.conf.task_annotations)
  928. @cached_property
  929. def AsyncResult(self):
  930. """Create new result instance.
  931. See Also:
  932. :class:`celery.result.AsyncResult`.
  933. """
  934. return self.subclass_with_self('celery.result:AsyncResult')
  935. @cached_property
  936. def ResultSet(self):
  937. return self.subclass_with_self('celery.result:ResultSet')
  938. @cached_property
  939. def GroupResult(self):
  940. """Create new group result instance.
  941. See Also:
  942. :class:`celery.result.GroupResult`.
  943. """
  944. return self.subclass_with_self('celery.result:GroupResult')
  945. @property
  946. def pool(self):
  947. """Broker connection pool: :class:`~@pool`.
  948. Note:
  949. This attribute is not related to the workers concurrency pool.
  950. """
  951. if self._pool is None:
  952. self._ensure_after_fork()
  953. limit = self.conf.broker_pool_limit
  954. pools.set_limit(limit)
  955. self._pool = pools.connections[self.connection_for_write()]
  956. return self._pool
  957. @property
  958. def current_task(self):
  959. """Instance of task being executed, or :const:`None`."""
  960. return _task_stack.top
  961. @property
  962. def current_worker_task(self):
  963. """The task currently being executed by a worker or :const:`None`.
  964. Differs from :data:`current_task` in that it's not affected
  965. by tasks calling other tasks directly, or eagerly.
  966. """
  967. return get_current_worker_task()
  968. @cached_property
  969. def oid(self):
  970. """Universally unique identifier for this app."""
  971. # since 4.0: thread.get_ident() is not included when
  972. # generating the process id. This is due to how the RPC
  973. # backend now dedicates a single thread to receive results,
  974. # which would not work if each thread has a separate id.
  975. return oid_from(self, threads=False)
  976. @cached_property
  977. def amqp(self):
  978. """AMQP related functionality: :class:`~@amqp`."""
  979. return instantiate(self.amqp_cls, app=self)
  980. @cached_property
  981. def backend(self):
  982. """Current backend instance."""
  983. return self._get_backend()
  984. @property
  985. def conf(self):
  986. """Current configuration."""
  987. if self._conf is None:
  988. self._conf = self._load_config()
  989. return self._conf
  990. @conf.setter
  991. def conf(self, d): # noqa
  992. self._conf = d
  993. @cached_property
  994. def control(self):
  995. """Remote control: :class:`~@control`."""
  996. return instantiate(self.control_cls, app=self)
  997. @cached_property
  998. def events(self):
  999. """Consuming and sending events: :class:`~@events`."""
  1000. return instantiate(self.events_cls, app=self)
  1001. @cached_property
  1002. def loader(self):
  1003. """Current loader instance."""
  1004. return get_loader_cls(self.loader_cls)(app=self)
  1005. @cached_property
  1006. def log(self):
  1007. """Logging: :class:`~@log`."""
  1008. return instantiate(self.log_cls, app=self)
  1009. @cached_property
  1010. def _canvas(self):
  1011. from celery import canvas
  1012. return canvas
  1013. @cached_property
  1014. def tasks(self):
  1015. """Task registry.
  1016. Warning:
  1017. Accessing this attribute will also auto-finalize the app.
  1018. """
  1019. self.finalize(auto=True)
  1020. return self._tasks
  1021. @property
  1022. def producer_pool(self):
  1023. return self.amqp.producer_pool
  1024. def uses_utc_timezone(self):
  1025. """Check if the application uses the UTC timezone."""
  1026. return self.timezone == timezone.utc
  1027. @cached_property
  1028. def timezone(self):
  1029. """Current timezone for this app.
  1030. This is a cached property taking the time zone from the
  1031. :setting:`timezone` setting.
  1032. """
  1033. conf = self.conf
  1034. if not conf.timezone:
  1035. if conf.enable_utc:
  1036. return timezone.utc
  1037. else:
  1038. return timezone.local
  1039. return timezone.get_timezone(conf.timezone)
  1040. App = Celery # noqa: E305 XXX compat