base.py 15 KB

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