utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # -*- coding: utf-8 -*-
  2. """App utilities: Compat settings, bug-report tool, pickling apps."""
  3. from __future__ import absolute_import, unicode_literals
  4. import os
  5. import platform as _platform
  6. import re
  7. from collections import Mapping, namedtuple
  8. from copy import deepcopy
  9. from types import ModuleType
  10. from kombu.utils.url import maybe_sanitize_url
  11. from celery.exceptions import ImproperlyConfigured
  12. from celery.five import items, keys, string_t, values
  13. from celery.platforms import pyimplementation
  14. from celery.utils.collections import ConfigurationView
  15. from celery.utils.text import pretty
  16. from celery.utils.imports import import_from_cwd, symbol_by_name, qualname
  17. from .defaults import (
  18. _TO_NEW_KEY, _TO_OLD_KEY, _OLD_DEFAULTS, _OLD_SETTING_KEYS,
  19. DEFAULTS, SETTING_KEYS, find,
  20. )
  21. __all__ = [
  22. 'Settings', 'appstr', 'bugreport',
  23. 'filter_hidden_settings', 'find_app',
  24. ]
  25. #: Format used to generate bug-report information.
  26. BUGREPORT_INFO = """
  27. software -> celery:{celery_v} kombu:{kombu_v} py:{py_v}
  28. billiard:{billiard_v} {driver_v}
  29. platform -> system:{system} arch:{arch} imp:{py_i}
  30. loader -> {loader}
  31. settings -> transport:{transport} results:{results}
  32. {human_settings}
  33. """
  34. HIDDEN_SETTINGS = re.compile(
  35. 'API|TOKEN|KEY|SECRET|PASS|PROFANITIES_LIST|SIGNATURE|DATABASE',
  36. re.IGNORECASE,
  37. )
  38. E_MIX_OLD_INTO_NEW = """
  39. Cannot mix new and old setting keys, please rename the
  40. following settings to the new format:
  41. {renames}
  42. """
  43. E_MIX_NEW_INTO_OLD = """
  44. Cannot mix new setting names with old setting names, please
  45. rename the following settings to use the old format:
  46. {renames}
  47. Or change all of the settings to use the new format :)
  48. """
  49. FMT_REPLACE_SETTING = '{replace:<36} -> {with_}'
  50. def appstr(app):
  51. """String used in __repr__ etc, to id app instances."""
  52. return '{0}:{1:#x}'.format(app.main or '__main__', id(app))
  53. class Settings(ConfigurationView):
  54. """Celery settings object.
  55. .. seealso:
  56. :ref:`configuration` for a full list of configuration keys.
  57. """
  58. @property
  59. def broker_read_url(self):
  60. return (
  61. os.environ.get('CELERY_BROKER_READ_URL') or
  62. self.get('broker_read_url') or
  63. self.broker_url
  64. )
  65. @property
  66. def broker_write_url(self):
  67. return (
  68. os.environ.get('CELERY_BROKER_WRITE_URL') or
  69. self.get('broker_write_url') or
  70. self.broker_url
  71. )
  72. @property
  73. def broker_url(self):
  74. return (
  75. os.environ.get('CELERY_BROKER_URL') or
  76. self.first('broker_url', 'broker_host')
  77. )
  78. @property
  79. def timezone(self):
  80. # this way we also support django's time zone.
  81. return self.first('timezone', 'time_zone')
  82. def without_defaults(self):
  83. """Return the current configuration, but without defaults."""
  84. # the last stash is the default settings, so just skip that
  85. return Settings({}, self.maps[:-1])
  86. def value_set_for(self, key):
  87. return key in self.without_defaults()
  88. def find_option(self, name, namespace=''):
  89. """Search for option by name.
  90. Example:
  91. >>> from proj.celery import app
  92. >>> app.conf.find_option('disable_rate_limits')
  93. ('worker', 'prefetch_multiplier',
  94. <Option: type->bool default->False>))
  95. Arguments:
  96. name (str): Name of option, cannot be partial.
  97. namespace (str): Preferred name-space (``None`` by default).
  98. Returns:
  99. Tuple: of ``(namespace, key, type)``.
  100. """
  101. return find(name, namespace)
  102. def find_value_for_key(self, name, namespace='celery'):
  103. """Shortcut to ``get_by_parts(*find_option(name)[:-1])``"""
  104. return self.get_by_parts(*self.find_option(name, namespace)[:-1])
  105. def get_by_parts(self, *parts):
  106. """Return the current value for setting specified as a path.
  107. Example:
  108. >>> from proj.celery import app
  109. >>> app.conf.get_by_parts('worker', 'disable_rate_limits')
  110. False
  111. """
  112. return self['_'.join(part for part in parts if part)]
  113. def table(self, with_defaults=False, censored=True):
  114. filt = filter_hidden_settings if censored else lambda v: v
  115. return filt({
  116. k: v for k, v in items(
  117. self if with_defaults else self.without_defaults())
  118. if not k.startswith('_')
  119. })
  120. def humanize(self, with_defaults=False, censored=True):
  121. """Return a human readable string showing changes to the
  122. configuration."""
  123. return '\n'.join(
  124. '{0}: {1}'.format(key, pretty(value, width=50))
  125. for key, value in items(self.table(with_defaults, censored)))
  126. def _new_key_to_old(key, convert=_TO_OLD_KEY.get):
  127. return convert(key, key)
  128. def _old_key_to_new(key, convert=_TO_NEW_KEY.get):
  129. return convert(key, key)
  130. _settings_info_t = namedtuple('settings_info_t', (
  131. 'defaults', 'convert', 'key_t', 'mix_error',
  132. ))
  133. _settings_info = _settings_info_t(
  134. DEFAULTS, _TO_NEW_KEY, _old_key_to_new, E_MIX_OLD_INTO_NEW,
  135. )
  136. _old_settings_info = _settings_info_t(
  137. _OLD_DEFAULTS, _TO_OLD_KEY, _new_key_to_old, E_MIX_NEW_INTO_OLD,
  138. )
  139. def detect_settings(conf, preconf={}, ignore_keys=set(), prefix=None,
  140. all_keys=SETTING_KEYS, old_keys=_OLD_SETTING_KEYS):
  141. source = conf
  142. if conf is None:
  143. source, conf = preconf, {}
  144. have = set(keys(source)) - ignore_keys
  145. is_in_new = have.intersection(all_keys)
  146. is_in_old = have.intersection(old_keys)
  147. info = None
  148. if is_in_new:
  149. # have new setting names
  150. info, left = _settings_info, is_in_old
  151. if is_in_old and len(is_in_old) > len(is_in_new):
  152. # Majority of the settings are old.
  153. info, left = _old_settings_info, is_in_new
  154. if is_in_old:
  155. # have old setting names, or a majority of the names are old.
  156. if not info:
  157. info, left = _old_settings_info, is_in_new
  158. if is_in_new and len(is_in_new) > len(is_in_old):
  159. # Majority of the settings are new
  160. info, left = _settings_info, is_in_old
  161. else:
  162. # no settings, just use new format.
  163. info, left = _settings_info, is_in_old
  164. if prefix:
  165. # always use new format if prefix is used.
  166. info, left = _settings_info, set()
  167. # only raise error for keys that the user didn't provide two keys
  168. # for (e.g. both ``result_expires`` and ``CELERY_TASK_RESULT_EXPIRES``).
  169. really_left = {key for key in left if info.convert[key] not in have}
  170. if really_left:
  171. # user is mixing old/new, or new/old settings, give renaming
  172. # suggestions.
  173. raise ImproperlyConfigured(info.mix_error.format(renames='\n'.join(
  174. FMT_REPLACE_SETTING.format(replace=key, with_=info.convert[key])
  175. for key in sorted(really_left)
  176. )))
  177. preconf = {info.convert.get(k, k): v for k, v in items(preconf)}
  178. defaults = dict(deepcopy(info.defaults), **preconf)
  179. return Settings(preconf, [conf, defaults], info.key_t, prefix=prefix)
  180. class AppPickler(object):
  181. """Old application pickler/unpickler (< 3.1)."""
  182. def __call__(self, cls, *args):
  183. kwargs = self.build_kwargs(*args)
  184. app = self.construct(cls, **kwargs)
  185. self.prepare(app, **kwargs)
  186. return app
  187. def prepare(self, app, **kwargs):
  188. app.conf.update(kwargs['changes'])
  189. def build_kwargs(self, *args):
  190. return self.build_standard_kwargs(*args)
  191. def build_standard_kwargs(self, main, changes, loader, backend, amqp,
  192. events, log, control, accept_magic_kwargs,
  193. config_source=None):
  194. return dict(main=main, loader=loader, backend=backend, amqp=amqp,
  195. changes=changes, events=events, log=log, control=control,
  196. set_as_current=False,
  197. config_source=config_source)
  198. def construct(self, cls, **kwargs):
  199. return cls(**kwargs)
  200. def _unpickle_app(cls, pickler, *args):
  201. """Rebuild app for versions 2.5+"""
  202. return pickler()(cls, *args)
  203. def _unpickle_app_v2(cls, kwargs):
  204. """Rebuild app for versions 3.1+"""
  205. kwargs['set_as_current'] = False
  206. return cls(**kwargs)
  207. def filter_hidden_settings(conf):
  208. def maybe_censor(key, value, mask='*' * 8):
  209. if isinstance(value, Mapping):
  210. return filter_hidden_settings(value)
  211. if isinstance(key, string_t):
  212. if HIDDEN_SETTINGS.search(key):
  213. return mask
  214. elif 'broker_url' in key.lower():
  215. from kombu import Connection
  216. return Connection(value).as_uri(mask=mask)
  217. elif 'backend' in key.lower():
  218. return maybe_sanitize_url(value, mask=mask)
  219. return value
  220. return {k: maybe_censor(k, v) for k, v in items(conf)}
  221. def bugreport(app):
  222. """Return a string containing information useful in bug-reports."""
  223. import billiard
  224. import celery
  225. import kombu
  226. try:
  227. conn = app.connection()
  228. driver_v = '{0}:{1}'.format(conn.transport.driver_name,
  229. conn.transport.driver_version())
  230. transport = conn.transport_cls
  231. except Exception:
  232. transport = driver_v = ''
  233. return BUGREPORT_INFO.format(
  234. system=_platform.system(),
  235. arch=', '.join(x for x in _platform.architecture() if x),
  236. py_i=pyimplementation(),
  237. celery_v=celery.VERSION_BANNER,
  238. kombu_v=kombu.__version__,
  239. billiard_v=billiard.__version__,
  240. py_v=_platform.python_version(),
  241. driver_v=driver_v,
  242. transport=transport,
  243. results=maybe_sanitize_url(app.conf.result_backend or 'disabled'),
  244. human_settings=app.conf.humanize(),
  245. loader=qualname(app.loader.__class__),
  246. )
  247. def find_app(app, symbol_by_name=symbol_by_name, imp=import_from_cwd):
  248. from .base import Celery
  249. try:
  250. sym = symbol_by_name(app, imp=imp)
  251. except AttributeError:
  252. # last part was not an attribute, but a module
  253. sym = imp(app)
  254. if isinstance(sym, ModuleType) and ':' not in app:
  255. try:
  256. found = sym.app
  257. if isinstance(found, ModuleType):
  258. raise AttributeError()
  259. except AttributeError:
  260. try:
  261. found = sym.celery
  262. if isinstance(found, ModuleType):
  263. raise AttributeError()
  264. except AttributeError:
  265. if getattr(sym, '__path__', None):
  266. try:
  267. return find_app(
  268. '{0}.celery'.format(app),
  269. symbol_by_name=symbol_by_name, imp=imp,
  270. )
  271. except ImportError:
  272. pass
  273. for suspect in values(vars(sym)):
  274. if isinstance(suspect, Celery):
  275. return suspect
  276. raise
  277. else:
  278. return found
  279. else:
  280. return found
  281. return sym