utils.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.app.utils
  4. ~~~~~~~~~~~~~~~~
  5. App utilities: Compat settings, bugreport tool, pickling apps.
  6. """
  7. from __future__ import absolute_import
  8. import os
  9. import platform as _platform
  10. import re
  11. from collections import Mapping
  12. from types import ModuleType
  13. from celery.datastructures import ConfigurationView
  14. from celery.five import items, string_t, values
  15. from celery.platforms import pyimplementation
  16. from celery.utils.text import pretty
  17. from celery.utils.imports import import_from_cwd, symbol_by_name, qualname
  18. from .defaults import find
  19. __all__ = ['Settings', 'appstr', 'bugreport',
  20. 'filter_hidden_settings', 'find_app']
  21. #: Format used to generate bugreport information.
  22. BUGREPORT_INFO = """
  23. software -> celery:{celery_v} kombu:{kombu_v} py:{py_v}
  24. billiard:{billiard_v} {driver_v}
  25. platform -> system:{system} arch:{arch} imp:{py_i}
  26. loader -> {loader}
  27. settings -> transport:{transport} results:{results}
  28. {human_settings}
  29. """
  30. HIDDEN_SETTINGS = re.compile(
  31. 'API|TOKEN|KEY|SECRET|PASS|PROFANITIES_LIST|SIGNATURE|DATABASE',
  32. re.IGNORECASE,
  33. )
  34. def appstr(app):
  35. """String used in __repr__ etc, to id app instances."""
  36. return '{0}:0x{1:x}'.format(app.main or '__main__', id(app))
  37. class Settings(ConfigurationView):
  38. """Celery settings object."""
  39. @property
  40. def CELERY_RESULT_BACKEND(self):
  41. return self.first('CELERY_RESULT_BACKEND', 'CELERY_BACKEND')
  42. @property
  43. def BROKER_TRANSPORT(self):
  44. return self.first('BROKER_TRANSPORT',
  45. 'BROKER_BACKEND', 'CARROT_BACKEND')
  46. @property
  47. def BROKER_BACKEND(self):
  48. """Deprecated compat alias to :attr:`BROKER_TRANSPORT`."""
  49. return self.BROKER_TRANSPORT
  50. @property
  51. def BROKER_URL(self):
  52. return (os.environ.get('CELERY_BROKER_URL') or
  53. self.first('BROKER_URL', 'BROKER_HOST'))
  54. @property
  55. def CELERY_TIMEZONE(self):
  56. # this way we also support django's time zone.
  57. return self.first('CELERY_TIMEZONE', 'TIME_ZONE')
  58. def without_defaults(self):
  59. """Return the current configuration, but without defaults."""
  60. # the last stash is the default settings, so just skip that
  61. return Settings({}, self._order[:-1])
  62. def value_set_for(self, key):
  63. return key in self.without_defaults()
  64. def find_option(self, name, namespace='celery'):
  65. """Search for option by name.
  66. Will return ``(namespace, key, type)`` tuple, e.g.::
  67. >>> from proj.celery import app
  68. >>> app.conf.find_option('disable_rate_limits')
  69. ('CELERY', 'DISABLE_RATE_LIMITS',
  70. <Option: type->bool default->False>))
  71. :param name: Name of option, cannot be partial.
  72. :keyword namespace: Preferred namespace (``CELERY`` by default).
  73. """
  74. return find(name, namespace)
  75. def find_value_for_key(self, name, namespace='celery'):
  76. """Shortcut to ``get_by_parts(*find_option(name)[:-1])``"""
  77. return self.get_by_parts(*self.find_option(name, namespace)[:-1])
  78. def get_by_parts(self, *parts):
  79. """Return the current value for setting specified as a path.
  80. Example::
  81. >>> from proj.celery import app
  82. >>> app.conf.get_by_parts('CELERY', 'DISABLE_RATE_LIMITS')
  83. False
  84. """
  85. return self['_'.join(part for part in parts if part)]
  86. def table(self, with_defaults=False, censored=True):
  87. filt = filter_hidden_settings if censored else lambda v: v
  88. return filt(dict(
  89. (k, v) for k, v in items(
  90. self if with_defaults else self.without_defaults())
  91. if k.isupper() and not k.startswith('_')
  92. ))
  93. def humanize(self, with_defaults=False, censored=True):
  94. """Return a human readable string showing changes to the
  95. configuration."""
  96. return '\n'.join(
  97. '{0}: {1}'.format(key, pretty(value, width=50))
  98. for key, value in items(self.table(with_defaults, censored)))
  99. class AppPickler(object):
  100. """Old application pickler/unpickler (< 3.1)."""
  101. def __call__(self, cls, *args):
  102. kwargs = self.build_kwargs(*args)
  103. app = self.construct(cls, **kwargs)
  104. self.prepare(app, **kwargs)
  105. return app
  106. def prepare(self, app, **kwargs):
  107. app.conf.update(kwargs['changes'])
  108. def build_kwargs(self, *args):
  109. return self.build_standard_kwargs(*args)
  110. def build_standard_kwargs(self, main, changes, loader, backend, amqp,
  111. events, log, control, accept_magic_kwargs,
  112. config_source=None):
  113. return dict(main=main, loader=loader, backend=backend, amqp=amqp,
  114. changes=changes, events=events, log=log, control=control,
  115. set_as_current=False,
  116. accept_magic_kwargs=accept_magic_kwargs,
  117. config_source=config_source)
  118. def construct(self, cls, **kwargs):
  119. return cls(**kwargs)
  120. def _unpickle_app(cls, pickler, *args):
  121. """Rebuild app for versions 2.5+"""
  122. return pickler()(cls, *args)
  123. def _unpickle_app_v2(cls, kwargs):
  124. """Rebuild app for versions 3.1+"""
  125. kwargs['set_as_current'] = False
  126. return cls(**kwargs)
  127. def filter_hidden_settings(conf):
  128. def maybe_censor(key, value, mask='*' * 8):
  129. if isinstance(value, Mapping):
  130. return filter_hidden_settings(value)
  131. if isinstance(value, string_t) and HIDDEN_SETTINGS.search(key):
  132. return mask
  133. if isinstance(key, string_t) and 'BROKER_URL' in key.upper():
  134. from kombu import Connection
  135. return Connection(value).as_uri(mask=mask)
  136. return value
  137. return dict((k, maybe_censor(k, v)) for k, v in items(conf))
  138. def bugreport(app):
  139. """Return a string containing information useful in bug reports."""
  140. import billiard
  141. import celery
  142. import kombu
  143. try:
  144. conn = app.connection()
  145. driver_v = '{0}:{1}'.format(conn.transport.driver_name,
  146. conn.transport.driver_version())
  147. transport = conn.transport_cls
  148. except Exception:
  149. transport = driver_v = ''
  150. return BUGREPORT_INFO.format(
  151. system=_platform.system(),
  152. arch=', '.join(x for x in _platform.architecture() if x),
  153. py_i=pyimplementation(),
  154. celery_v=celery.VERSION_BANNER,
  155. kombu_v=kombu.__version__,
  156. billiard_v=billiard.__version__,
  157. py_v=_platform.python_version(),
  158. driver_v=driver_v,
  159. transport=transport,
  160. results=app.conf.CELERY_RESULT_BACKEND or 'disabled',
  161. human_settings=app.conf.humanize(),
  162. loader=qualname(app.loader.__class__),
  163. )
  164. def find_app(app, symbol_by_name=symbol_by_name, imp=import_from_cwd):
  165. from .base import Celery
  166. try:
  167. sym = symbol_by_name(app, imp=imp)
  168. except AttributeError:
  169. # last part was not an attribute, but a module
  170. sym = imp(app)
  171. if isinstance(sym, ModuleType) and ':' not in app:
  172. try:
  173. found = sym.app
  174. if isinstance(found, ModuleType):
  175. raise AttributeError()
  176. except AttributeError:
  177. try:
  178. found = sym.celery
  179. if isinstance(found, ModuleType):
  180. raise AttributeError()
  181. except AttributeError:
  182. if getattr(sym, '__path__', None):
  183. try:
  184. return find_app(
  185. '{0}.celery'.format(app),
  186. symbol_by_name=symbol_by_name, imp=imp,
  187. )
  188. except ImportError:
  189. pass
  190. for suspect in values(vars(sym)):
  191. if isinstance(suspect, Celery):
  192. return suspect
  193. raise
  194. else:
  195. return found
  196. else:
  197. return found
  198. return sym