base.py 43 KB

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