base.py 45 KB

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