base.py 16 KB

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