base.py 41 KB

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