base.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.app.base
  4. ~~~~~~~~~~~~~~~
  5. Application Base Class.
  6. :copyright: (c) 2009 - 2012 by Ask Solem.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from __future__ import absolute_import
  10. from __future__ import with_statement
  11. import warnings
  12. from collections import deque
  13. from contextlib import contextmanager
  14. from copy import deepcopy
  15. from functools import wraps
  16. from billiard.util import register_after_fork
  17. from kombu.clocks import LamportClock
  18. from kombu.utils import cached_property
  19. from celery import platforms
  20. from celery.exceptions import AlwaysEagerIgnored
  21. from celery.loaders import get_loader_cls
  22. from celery.local import PromiseProxy, maybe_evaluate
  23. from celery.utils.functional import first
  24. from celery.utils.imports import instantiate, symbol_by_name
  25. from .annotations import prepare as prepare_annotations
  26. from .builtins import shared_task, load_shared_tasks
  27. from .defaults import DEFAULTS, find_deprecated_settings
  28. from .registry import TaskRegistry
  29. from .state import _tls, get_current_app
  30. from .utils import AppPickler, Settings, bugreport, _unpickle_app
  31. def _unpickle_appattr(reverse_name, args):
  32. """Given an attribute name and a list of args, gets
  33. the attribute from the current app and calls it."""
  34. return get_current_app()._rgetattr(reverse_name)(*args)
  35. class Celery(object):
  36. Pickler = AppPickler
  37. SYSTEM = platforms.SYSTEM
  38. IS_OSX, IS_WINDOWS = platforms.IS_OSX, platforms.IS_WINDOWS
  39. amqp_cls = "celery.app.amqp:AMQP"
  40. backend_cls = None
  41. events_cls = "celery.events:Events"
  42. loader_cls = "celery.loaders.app:AppLoader"
  43. log_cls = "celery.app.log:Logging"
  44. control_cls = "celery.app.control:Control"
  45. registry_cls = TaskRegistry
  46. _pool = None
  47. def __init__(self, main=None, loader=None, backend=None,
  48. amqp=None, events=None, log=None, control=None,
  49. set_as_current=True, accept_magic_kwargs=False,
  50. tasks=None, broker=None, **kwargs):
  51. self.clock = LamportClock()
  52. self.main = main
  53. self.amqp_cls = amqp or self.amqp_cls
  54. self.backend_cls = backend or self.backend_cls
  55. self.events_cls = events or self.events_cls
  56. self.loader_cls = loader or self.loader_cls
  57. self.log_cls = log or self.log_cls
  58. self.control_cls = control or self.control_cls
  59. self.set_as_current = set_as_current
  60. self.registry_cls = symbol_by_name(self.registry_cls)
  61. self.accept_magic_kwargs = accept_magic_kwargs
  62. self.finalized = False
  63. self._pending = deque()
  64. self._tasks = tasks
  65. if not isinstance(self._tasks, TaskRegistry):
  66. self._tasks = TaskRegistry(self._tasks or {})
  67. # these options are moved to the config to
  68. # simplify pickling of the app object.
  69. self._preconf = {}
  70. if broker:
  71. self._preconf["BROKER_URL"] = broker
  72. if self.set_as_current:
  73. self.set_current()
  74. self.on_init()
  75. def set_current(self):
  76. _tls.current_app = self
  77. def on_init(self):
  78. """Optional callback called at init."""
  79. pass
  80. def start(self, argv=None):
  81. return instantiate("celery.bin.celery:CeleryCommand", app=self) \
  82. .execute_from_commandline(argv)
  83. def worker_main(self, argv=None):
  84. return instantiate("celery.bin.celeryd:WorkerCommand", app=self) \
  85. .execute_from_commandline(argv)
  86. def task(self, *args, **opts):
  87. """Creates new task class from any callable."""
  88. def inner_create_task_cls(shared=True, **opts):
  89. def _create_task_cls(fun):
  90. if shared:
  91. cons = lambda app: app._task_from_fun(fun, **opts)
  92. cons.__name__ = fun.__name__
  93. shared_task(cons)
  94. if self.accept_magic_kwargs: # compat mode
  95. return self._task_from_fun(fun, **opts)
  96. # return a proxy object that is only evaluated when first used
  97. promise = PromiseProxy(self._task_from_fun, (fun, ), opts)
  98. self._pending.append(promise)
  99. return promise
  100. return _create_task_cls
  101. if len(args) == 1 and callable(args[0]):
  102. return inner_create_task_cls(**opts)(*args)
  103. return inner_create_task_cls(**opts)
  104. def _task_from_fun(self, fun, **options):
  105. base = options.pop("base", None) or self.Task
  106. T = type(fun.__name__, (base, ), dict({
  107. "app": self,
  108. "accept_magic_kwargs": False,
  109. "run": staticmethod(fun),
  110. "__doc__": fun.__doc__,
  111. "__module__": fun.__module__}, **options))()
  112. task = self._tasks[T.name] # return global instance.
  113. task.bind(self)
  114. return task
  115. def finalize(self):
  116. if not self.finalized:
  117. load_shared_tasks(self)
  118. pending = self._pending
  119. while pending:
  120. maybe_evaluate(pending.pop())
  121. self.finalized = True
  122. def config_from_object(self, obj, silent=False):
  123. del(self.conf)
  124. return self.loader.config_from_object(obj, silent=silent)
  125. def config_from_envvar(self, variable_name, silent=False):
  126. del(self.conf)
  127. return self.loader.config_from_envvar(variable_name, silent=silent)
  128. def config_from_cmdline(self, argv, namespace="celery"):
  129. self.conf.update(self.loader.cmdline_config_parser(argv, namespace))
  130. def send_task(self, name, args=None, kwargs=None, countdown=None,
  131. eta=None, task_id=None, publisher=None, connection=None,
  132. result_cls=None, expires=None, queues=None, **options):
  133. if self.conf.CELERY_ALWAYS_EAGER: # pragma: no cover
  134. warnings.warn(AlwaysEagerIgnored(
  135. "CELERY_ALWAYS_EAGER has no effect on send_task"))
  136. result_cls = result_cls or self.AsyncResult
  137. router = self.amqp.Router(queues)
  138. options.setdefault("compression",
  139. self.conf.CELERY_MESSAGE_COMPRESSION)
  140. options = router.route(options, name, args, kwargs)
  141. with self.default_producer(publisher) as producer:
  142. return result_cls(producer.delay_task(name, args, kwargs,
  143. task_id=task_id,
  144. countdown=countdown, eta=eta,
  145. expires=expires, **options))
  146. def broker_connection(self, hostname=None, userid=None,
  147. password=None, virtual_host=None, port=None, ssl=None,
  148. insist=None, connect_timeout=None, transport=None,
  149. transport_options=None, **kwargs):
  150. conf = self.conf
  151. return self.amqp.BrokerConnection(
  152. hostname or conf.BROKER_HOST,
  153. userid or conf.BROKER_USER,
  154. password or conf.BROKER_PASSWORD,
  155. virtual_host or conf.BROKER_VHOST,
  156. port or conf.BROKER_PORT,
  157. transport=transport or conf.BROKER_TRANSPORT,
  158. insist=self.either("BROKER_INSIST", insist),
  159. ssl=self.either("BROKER_USE_SSL", ssl),
  160. connect_timeout=self.either(
  161. "BROKER_CONNECTION_TIMEOUT", connect_timeout),
  162. transport_options=dict(conf.BROKER_TRANSPORT_OPTIONS,
  163. **transport_options or {}))
  164. @contextmanager
  165. def default_connection(self, connection=None, *args, **kwargs):
  166. if connection:
  167. yield connection
  168. else:
  169. with self.pool.acquire(block=True) as connection:
  170. yield connection
  171. @contextmanager
  172. def default_producer(self, producer=None):
  173. if producer:
  174. yield producer
  175. else:
  176. with self.amqp.publisher_pool.acquire(block=True) as producer:
  177. yield producer
  178. def with_default_connection(self, fun):
  179. """With any function accepting a `connection`
  180. keyword argument, establishes a default connection if one is
  181. not already passed to it.
  182. Any automatically established connection will be closed after
  183. the function returns.
  184. **Deprecated**
  185. Use ``with app.default_connection(connection)`` instead.
  186. """
  187. @wraps(fun)
  188. def _inner(*args, **kwargs):
  189. connection = kwargs.pop("connection", None)
  190. with self.default_connection(connection) as c:
  191. return fun(*args, **dict(kwargs, connection=c))
  192. return _inner
  193. def prepare_config(self, c):
  194. """Prepare configuration before it is merged with the defaults."""
  195. return find_deprecated_settings(c)
  196. def now(self):
  197. return self.loader.now(utc=self.conf.CELERY_ENABLE_UTC)
  198. def mail_admins(self, subject, body, fail_silently=False):
  199. if self.conf.ADMINS:
  200. to = [admin_email for _, admin_email in self.conf.ADMINS]
  201. return self.loader.mail_admins(subject, body, fail_silently, to=to,
  202. sender=self.conf.SERVER_EMAIL,
  203. host=self.conf.EMAIL_HOST,
  204. port=self.conf.EMAIL_PORT,
  205. user=self.conf.EMAIL_HOST_USER,
  206. password=self.conf.EMAIL_HOST_PASSWORD,
  207. timeout=self.conf.EMAIL_TIMEOUT,
  208. use_ssl=self.conf.EMAIL_USE_SSL,
  209. use_tls=self.conf.EMAIL_USE_TLS)
  210. def select_queues(self, queues=None):
  211. return self.amqp.queues.select_subset(queues)
  212. def either(self, default_key, *values):
  213. """Fallback to the value of a configuration key if none of the
  214. `*values` are true."""
  215. return first(None, values) or self.conf.get(default_key)
  216. def bugreport(self):
  217. return bugreport(self)
  218. def _get_backend(self):
  219. from celery.backends import get_backend_by_url
  220. backend, url = get_backend_by_url(
  221. self.backend_cls or self.conf.CELERY_RESULT_BACKEND,
  222. self.loader)
  223. return backend(app=self, url=url)
  224. def _get_config(self):
  225. s = Settings({}, [self.prepare_config(self.loader.conf),
  226. deepcopy(DEFAULTS)])
  227. if self._preconf:
  228. for key, value in self._preconf.iteritems():
  229. setattr(s, key, value)
  230. return s
  231. def _after_fork(self, obj_):
  232. if self._pool:
  233. self._pool.force_close_all()
  234. self._pool = None
  235. def create_task_cls(self):
  236. """Creates a base task class using default configuration
  237. taken from this app."""
  238. return self.subclass_with_self("celery.app.task:BaseTask", name="Task",
  239. attribute="_app", abstract=True)
  240. def subclass_with_self(self, Class, name=None, attribute="app",
  241. reverse=None, **kw):
  242. """Subclass an app-compatible class by setting its app attribute
  243. to be this app instance.
  244. App-compatible means that the class has a class attribute that
  245. provides the default app it should use, e.g.
  246. ``class Foo: app = None``.
  247. :param Class: The app-compatible class to subclass.
  248. :keyword name: Custom name for the target class.
  249. :keyword attribute: Name of the attribute holding the app,
  250. default is "app".
  251. """
  252. Class = symbol_by_name(Class)
  253. reverse = reverse if reverse else Class.__name__
  254. def __reduce__(self):
  255. return _unpickle_appattr, (reverse, self.__reduce_args__())
  256. attrs = dict({attribute: self}, __module__=Class.__module__,
  257. __doc__=Class.__doc__, __reduce__=__reduce__, **kw)
  258. return type(name or Class.__name__, (Class, ), attrs)
  259. def _rgetattr(self, path):
  260. return reduce(getattr, [self] + path.split('.'))
  261. def __repr__(self):
  262. return "<%s %s:0x%x>" % (self.__class__.__name__,
  263. self.main or "__main__", id(self), )
  264. def __reduce__(self):
  265. # Reduce only pickles the configuration changes,
  266. # so the default configuration doesn't have to be passed
  267. # between processes.
  268. return (_unpickle_app, (self.__class__, self.Pickler)
  269. + self.__reduce_args__())
  270. def __reduce_args__(self):
  271. return (self.main, self.conf.changes, self.loader_cls,
  272. self.backend_cls, self.amqp_cls, self.events_cls,
  273. self.log_cls, self.control_cls, self.accept_magic_kwargs)
  274. @cached_property
  275. def Worker(self):
  276. """Create new :class:`~celery.apps.worker.Worker` instance."""
  277. return self.subclass_with_self("celery.apps.worker:Worker")
  278. @cached_property
  279. def WorkController(self, **kwargs):
  280. return self.subclass_with_self("celery.worker:WorkController")
  281. @cached_property
  282. def Beat(self, **kwargs):
  283. """Create new :class:`~celery.apps.beat.Beat` instance."""
  284. return self.subclass_with_self("celery.apps.beat:Beat")
  285. @cached_property
  286. def TaskSet(self):
  287. return self.subclass_with_self("celery.task.sets:TaskSet")
  288. @cached_property
  289. def Task(self):
  290. """Default Task base class for this application."""
  291. return self.create_task_cls()
  292. @cached_property
  293. def annotations(self):
  294. return prepare_annotations(self.conf.CELERY_ANNOTATIONS)
  295. @cached_property
  296. def AsyncResult(self):
  297. return self.subclass_with_self("celery.result:AsyncResult")
  298. @cached_property
  299. def TaskSetResult(self):
  300. return self.subclass_with_self("celery.result:TaskSetResult")
  301. @property
  302. def pool(self):
  303. if self._pool is None:
  304. register_after_fork(self, self._after_fork)
  305. self._pool = self.broker_connection().Pool(
  306. limit=self.conf.BROKER_POOL_LIMIT)
  307. return self._pool
  308. @cached_property
  309. def amqp(self):
  310. """Sending/receiving messages. See :class:`~celery.app.amqp.AMQP`."""
  311. return instantiate(self.amqp_cls, app=self)
  312. @cached_property
  313. def backend(self):
  314. """Storing/retrieving task state. See
  315. :class:`~celery.backend.base.BaseBackend`."""
  316. return self._get_backend()
  317. @cached_property
  318. def conf(self):
  319. """Current configuration (dict and attribute access)."""
  320. return self._get_config()
  321. @cached_property
  322. def control(self):
  323. """Controlling worker nodes. See
  324. :class:`~celery.app.control.Control`."""
  325. return instantiate(self.control_cls, app=self)
  326. @cached_property
  327. def events(self):
  328. """Sending/receiving events. See :class:`~celery.events.Events`. """
  329. return instantiate(self.events_cls, app=self)
  330. @cached_property
  331. def loader(self):
  332. """Current loader."""
  333. return get_loader_cls(self.loader_cls)(app=self)
  334. @cached_property
  335. def log(self):
  336. """Logging utilities. See :class:`~celery.app.log.Logging`."""
  337. return instantiate(self.log_cls, app=self)
  338. @cached_property
  339. def tasks(self):
  340. """Registry of available tasks.
  341. Accessing this attribute will also finalize the app.
  342. """
  343. self.finalize()
  344. return self._tasks
  345. App = Celery # compat