base.py 16 KB

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