base.py 41 KB

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