base.py 40 KB

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