datastructures.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.datastructures
  4. ~~~~~~~~~~~~~~~~~~~~~
  5. Custom types and data structures.
  6. """
  7. from __future__ import absolute_import, print_function, unicode_literals
  8. import sys
  9. import time
  10. from collections import defaultdict, Mapping, MutableMapping, MutableSet
  11. from heapq import heapify, heappush, heappop
  12. from functools import partial
  13. from itertools import chain
  14. from billiard.einfo import ExceptionInfo # noqa
  15. from kombu.utils.encoding import safe_str
  16. from kombu.utils.limits import TokenBucket # noqa
  17. from celery.five import items
  18. from celery.utils.functional import LRUCache, first, uniq # noqa
  19. try:
  20. from django.utils.functional import LazyObject
  21. except ImportError:
  22. class LazyObject(object): # noqa
  23. pass
  24. DOT_HEAD = """
  25. {IN}{type} {id} {{
  26. {INp}graph [{attrs}]
  27. """
  28. DOT_ATTR = '{name}={value}'
  29. DOT_NODE = '{INp}"{0}" [{attrs}]'
  30. DOT_EDGE = '{INp}"{0}" {dir} "{1}" [{attrs}]'
  31. DOT_ATTRSEP = ', '
  32. DOT_DIRS = {'graph': '--', 'digraph': '->'}
  33. DOT_TAIL = '{IN}}}'
  34. __all__ = ['GraphFormatter', 'CycleError', 'DependencyGraph',
  35. 'AttributeDictMixin', 'AttributeDict', 'DictAttribute',
  36. 'ConfigurationView', 'LimitedSet']
  37. def force_mapping(m):
  38. if isinstance(m, LazyObject):
  39. m = m._wrapped
  40. return DictAttribute(m) if not isinstance(m, Mapping) else m
  41. class GraphFormatter(object):
  42. _attr = DOT_ATTR.strip()
  43. _node = DOT_NODE.strip()
  44. _edge = DOT_EDGE.strip()
  45. _head = DOT_HEAD.strip()
  46. _tail = DOT_TAIL.strip()
  47. _attrsep = DOT_ATTRSEP
  48. _dirs = dict(DOT_DIRS)
  49. scheme = {
  50. 'shape': 'box',
  51. 'arrowhead': 'vee',
  52. 'style': 'filled',
  53. 'fontname': 'HelveticaNeue',
  54. }
  55. edge_scheme = {
  56. 'color': 'darkseagreen4',
  57. 'arrowcolor': 'black',
  58. 'arrowsize': 0.7,
  59. }
  60. node_scheme = {'fillcolor': 'palegreen3', 'color': 'palegreen4'}
  61. term_scheme = {'fillcolor': 'palegreen1', 'color': 'palegreen2'}
  62. graph_scheme = {'bgcolor': 'mintcream'}
  63. def __init__(self, root=None, type=None, id=None,
  64. indent=0, inw=' ' * 4, **scheme):
  65. self.id = id or 'dependencies'
  66. self.root = root
  67. self.type = type or 'digraph'
  68. self.direction = self._dirs[self.type]
  69. self.IN = inw * (indent or 0)
  70. self.INp = self.IN + inw
  71. self.scheme = dict(self.scheme, **scheme)
  72. self.graph_scheme = dict(self.graph_scheme, root=self.label(self.root))
  73. def attr(self, name, value):
  74. value = '"{0}"'.format(value)
  75. return self.FMT(self._attr, name=name, value=value)
  76. def attrs(self, d, scheme=None):
  77. d = dict(self.scheme, **dict(scheme, **d or {}) if scheme else d)
  78. return self._attrsep.join(
  79. safe_str(self.attr(k, v)) for k, v in items(d)
  80. )
  81. def head(self, **attrs):
  82. return self.FMT(
  83. self._head, id=self.id, type=self.type,
  84. attrs=self.attrs(attrs, self.graph_scheme),
  85. )
  86. def tail(self):
  87. return self.FMT(self._tail)
  88. def label(self, obj):
  89. return obj
  90. def node(self, obj, **attrs):
  91. return self.draw_node(obj, self.node_scheme, attrs)
  92. def terminal_node(self, obj, **attrs):
  93. return self.draw_node(obj, self.term_scheme, attrs)
  94. def edge(self, a, b, **attrs):
  95. return self.draw_edge(a, b, **attrs)
  96. def _enc(self, s):
  97. return s.encode('utf-8', 'ignore')
  98. def FMT(self, fmt, *args, **kwargs):
  99. return self._enc(fmt.format(
  100. *args, **dict(kwargs, IN=self.IN, INp=self.INp)
  101. ))
  102. def draw_edge(self, a, b, scheme=None, attrs=None):
  103. return self.FMT(
  104. self._edge, self.label(a), self.label(b),
  105. dir=self.direction, attrs=self.attrs(attrs, self.edge_scheme),
  106. )
  107. def draw_node(self, obj, scheme=None, attrs=None):
  108. return self.FMT(
  109. self._node, self.label(obj), attrs=self.attrs(attrs, scheme),
  110. )
  111. class CycleError(Exception):
  112. """A cycle was detected in an acyclic graph."""
  113. class DependencyGraph(object):
  114. """A directed acyclic graph of objects and their dependencies.
  115. Supports a robust topological sort
  116. to detect the order in which they must be handled.
  117. Takes an optional iterator of ``(obj, dependencies)``
  118. tuples to build the graph from.
  119. .. warning::
  120. Does not support cycle detection.
  121. """
  122. def __init__(self, it=None, formatter=None):
  123. self.formatter = formatter or GraphFormatter()
  124. self.adjacent = {}
  125. if it is not None:
  126. self.update(it)
  127. def add_arc(self, obj):
  128. """Add an object to the graph."""
  129. self.adjacent.setdefault(obj, [])
  130. def add_edge(self, A, B):
  131. """Add an edge from object ``A`` to object ``B``
  132. (``A`` depends on ``B``)."""
  133. self[A].append(B)
  134. def connect(self, graph):
  135. """Add nodes from another graph."""
  136. self.adjacent.update(graph.adjacent)
  137. def topsort(self):
  138. """Sort the graph topologically.
  139. :returns: a list of objects in the order
  140. in which they must be handled.
  141. """
  142. graph = DependencyGraph()
  143. components = self._tarjan72()
  144. NC = dict((node, component)
  145. for component in components
  146. for node in component)
  147. for component in components:
  148. graph.add_arc(component)
  149. for node in self:
  150. node_c = NC[node]
  151. for successor in self[node]:
  152. successor_c = NC[successor]
  153. if node_c != successor_c:
  154. graph.add_edge(node_c, successor_c)
  155. return [t[0] for t in graph._khan62()]
  156. def valency_of(self, obj):
  157. """Return the valency (degree) of a vertex in the graph."""
  158. try:
  159. l = [len(self[obj])]
  160. except KeyError:
  161. return 0
  162. for node in self[obj]:
  163. l.append(self.valency_of(node))
  164. return sum(l)
  165. def update(self, it):
  166. """Update the graph with data from a list
  167. of ``(obj, dependencies)`` tuples."""
  168. tups = list(it)
  169. for obj, _ in tups:
  170. self.add_arc(obj)
  171. for obj, deps in tups:
  172. for dep in deps:
  173. self.add_edge(obj, dep)
  174. def edges(self):
  175. """Return generator that yields for all edges in the graph."""
  176. return (obj for obj, adj in items(self) if adj)
  177. def _khan62(self):
  178. """Khans simple topological sort algorithm from '62
  179. See http://en.wikipedia.org/wiki/Topological_sorting
  180. """
  181. count = defaultdict(lambda: 0)
  182. result = []
  183. for node in self:
  184. for successor in self[node]:
  185. count[successor] += 1
  186. ready = [node for node in self if not count[node]]
  187. while ready:
  188. node = ready.pop()
  189. result.append(node)
  190. for successor in self[node]:
  191. count[successor] -= 1
  192. if count[successor] == 0:
  193. ready.append(successor)
  194. result.reverse()
  195. return result
  196. def _tarjan72(self):
  197. """Tarjan's algorithm to find strongly connected components.
  198. See http://bit.ly/vIMv3h.
  199. """
  200. result, stack, low = [], [], {}
  201. def visit(node):
  202. if node in low:
  203. return
  204. num = len(low)
  205. low[node] = num
  206. stack_pos = len(stack)
  207. stack.append(node)
  208. for successor in self[node]:
  209. visit(successor)
  210. low[node] = min(low[node], low[successor])
  211. if num == low[node]:
  212. component = tuple(stack[stack_pos:])
  213. stack[stack_pos:] = []
  214. result.append(component)
  215. for item in component:
  216. low[item] = len(self)
  217. for node in self:
  218. visit(node)
  219. return result
  220. def to_dot(self, fh, formatter=None):
  221. """Convert the graph to DOT format.
  222. :param fh: A file, or a file-like object to write the graph to.
  223. """
  224. seen = set()
  225. draw = formatter or self.formatter
  226. P = partial(print, file=fh)
  227. def if_not_seen(fun, obj):
  228. if draw.label(obj) not in seen:
  229. P(fun(obj))
  230. seen.add(draw.label(obj))
  231. P(draw.head())
  232. for obj, adjacent in items(self):
  233. if not adjacent:
  234. if_not_seen(draw.terminal_node, obj)
  235. for req in adjacent:
  236. if_not_seen(draw.node, obj)
  237. P(draw.edge(obj, req))
  238. P(draw.tail())
  239. def format(self, obj):
  240. return self.formatter(obj) if self.formatter else obj
  241. def __iter__(self):
  242. return iter(self.adjacent)
  243. def __getitem__(self, node):
  244. return self.adjacent[node]
  245. def __len__(self):
  246. return len(self.adjacent)
  247. def __contains__(self, obj):
  248. return obj in self.adjacent
  249. def _iterate_items(self):
  250. return items(self.adjacent)
  251. items = iteritems = _iterate_items
  252. def __repr__(self):
  253. return '\n'.join(self.repr_node(N) for N in self)
  254. def repr_node(self, obj, level=1, fmt='{0}({1})'):
  255. output = [fmt.format(obj, self.valency_of(obj))]
  256. if obj in self:
  257. for other in self[obj]:
  258. d = fmt.format(other, self.valency_of(other))
  259. output.append(' ' * level + d)
  260. output.extend(self.repr_node(other, level + 1).split('\n')[1:])
  261. return '\n'.join(output)
  262. class AttributeDictMixin(object):
  263. """Augment classes with a Mapping interface by adding attribute access.
  264. I.e. `d.key -> d[key]`.
  265. """
  266. def __getattr__(self, k):
  267. """`d.key -> d[key]`"""
  268. try:
  269. return self[k]
  270. except KeyError:
  271. raise AttributeError(
  272. '{0!r} object has no attribute {1!r}'.format(
  273. type(self).__name__, k))
  274. def __setattr__(self, key, value):
  275. """`d[key] = value -> d.key = value`"""
  276. self[key] = value
  277. class AttributeDict(dict, AttributeDictMixin):
  278. """Dict subclass with attribute access."""
  279. pass
  280. class DictAttribute(object):
  281. """Dict interface to attributes.
  282. `obj[k] -> obj.k`
  283. `obj[k] = val -> obj.k = val`
  284. """
  285. obj = None
  286. def __init__(self, obj):
  287. object.__setattr__(self, 'obj', obj)
  288. def __getattr__(self, key):
  289. return getattr(self.obj, key)
  290. def __setattr__(self, key, value):
  291. return setattr(self.obj, key, value)
  292. def get(self, key, default=None):
  293. try:
  294. return self[key]
  295. except KeyError:
  296. return default
  297. def setdefault(self, key, default):
  298. try:
  299. return self[key]
  300. except KeyError:
  301. self[key] = default
  302. return default
  303. def __getitem__(self, key):
  304. try:
  305. return getattr(self.obj, key)
  306. except AttributeError:
  307. raise KeyError(key)
  308. def __setitem__(self, key, value):
  309. setattr(self.obj, key, value)
  310. def __contains__(self, key):
  311. return hasattr(self.obj, key)
  312. def _iterate_keys(self):
  313. return iter(dir(self.obj))
  314. iterkeys = _iterate_keys
  315. def __iter__(self):
  316. return self._iterate_keys()
  317. def _iterate_items(self):
  318. for key in self._iterate_keys():
  319. yield key, getattr(self.obj, key)
  320. iteritems = _iterate_items
  321. def _iterate_values(self):
  322. for key in self._iterate_keys():
  323. yield getattr(self.obj, key)
  324. itervalues = _iterate_values
  325. if sys.version_info[0] == 3: # pragma: no cover
  326. items = _iterate_items
  327. keys = _iterate_keys
  328. values = _iterate_values
  329. else:
  330. def keys(self):
  331. return list(self)
  332. def items(self):
  333. return list(self._iterate_items())
  334. def values(self):
  335. return list(self._iterate_values())
  336. MutableMapping.register(DictAttribute)
  337. class ConfigurationView(AttributeDictMixin):
  338. """A view over an applications configuration dicts.
  339. Custom (but older) version of :class:`collections.ChainMap`.
  340. If the key does not exist in ``changes``, the ``defaults`` dicts
  341. are consulted.
  342. :param changes: Dict containing changes to the configuration.
  343. :param defaults: List of dicts containing the default configuration.
  344. """
  345. changes = None
  346. defaults = None
  347. _order = None
  348. def __init__(self, changes, defaults):
  349. self.__dict__.update(changes=changes, defaults=defaults,
  350. _order=[changes] + defaults)
  351. def add_defaults(self, d):
  352. d = force_mapping(d)
  353. self.defaults.insert(0, d)
  354. self._order.insert(1, d)
  355. def __getitem__(self, key):
  356. for d in self._order:
  357. try:
  358. return d[key]
  359. except KeyError:
  360. pass
  361. raise KeyError(key)
  362. def __setitem__(self, key, value):
  363. self.changes[key] = value
  364. def first(self, *keys):
  365. return first(None, (self.get(key) for key in keys))
  366. def get(self, key, default=None):
  367. try:
  368. return self[key]
  369. except KeyError:
  370. return default
  371. def clear(self):
  372. """Remove all changes, but keep defaults."""
  373. self.changes.clear()
  374. def setdefault(self, key, default):
  375. try:
  376. return self[key]
  377. except KeyError:
  378. self[key] = default
  379. return default
  380. def update(self, *args, **kwargs):
  381. return self.changes.update(*args, **kwargs)
  382. def __contains__(self, key):
  383. return any(key in m for m in self._order)
  384. def __bool__(self):
  385. return any(self._order)
  386. __nonzero__ = __bool__ # Py2
  387. def __repr__(self):
  388. return repr(dict(items(self)))
  389. def __iter__(self):
  390. return self._iterate_keys()
  391. def __len__(self):
  392. # The logic for iterating keys includes uniq(),
  393. # so to be safe we count by explicitly iterating
  394. return len(set().union(*self._order))
  395. def _iter(self, op):
  396. # defaults must be first in the stream, so values in
  397. # changes takes precedence.
  398. return chain(*[op(d) for d in reversed(self._order)])
  399. def _iterate_keys(self):
  400. return uniq(self._iter(lambda d: d))
  401. iterkeys = _iterate_keys
  402. def _iterate_items(self):
  403. return ((key, self[key]) for key in self)
  404. iteritems = _iterate_items
  405. def _iterate_values(self):
  406. return (self[key] for key in self)
  407. itervalues = _iterate_values
  408. if sys.version_info[0] == 3: # pragma: no cover
  409. keys = _iterate_keys
  410. items = _iterate_items
  411. values = _iterate_values
  412. else: # noqa
  413. def keys(self):
  414. return list(self._iterate_keys())
  415. def items(self):
  416. return list(self._iterate_items())
  417. def values(self):
  418. return list(self._iterate_values())
  419. MutableMapping.register(ConfigurationView)
  420. class LimitedSet(object):
  421. """Kind-of Set with limitations.
  422. Good for when you need to test for membership (`a in set`),
  423. but the list might become to big.
  424. :keyword maxlen: Maximum number of members before we start
  425. evicting expired members.
  426. :keyword expires: Time in seconds, before a membership expires.
  427. """
  428. def __init__(self, maxlen=None, expires=None, data=None, heap=None):
  429. self.maxlen = maxlen
  430. self.expires = expires
  431. self._data = {} if data is None else data
  432. self._heap = [] if heap is None else heap
  433. # make shortcuts
  434. self.__len__ = self._heap.__len__
  435. self.__iter__ = self._heap.__iter__
  436. self.__contains__ = self._data.__contains__
  437. def add(self, value, now=time.time):
  438. """Add a new member."""
  439. # offset is there to modify the length of the list,
  440. # this way we can expire an item before inserting the value,
  441. # and it will end up in correct order.
  442. self.purge(1, offset=1)
  443. inserted = now()
  444. self._data[value] = inserted
  445. heappush(self._heap, (inserted, value))
  446. def clear(self):
  447. """Remove all members"""
  448. self._data.clear()
  449. self._heap[:] = []
  450. def discard(self, value):
  451. """Remove membership by finding value."""
  452. try:
  453. itime = self._data[value]
  454. except KeyError:
  455. return
  456. try:
  457. self._heap.remove((value, itime))
  458. except ValueError:
  459. pass
  460. self._data.pop(value, None)
  461. pop_value = discard # XXX compat
  462. def purge(self, limit=None, offset=0, now=time.time):
  463. """Purge expired items."""
  464. H, maxlen = self._heap, self.maxlen
  465. if not maxlen:
  466. return
  467. # If the data/heap gets corrupted and limit is None
  468. # this will go into an infinite loop, so limit must
  469. # have a value to guard the loop.
  470. limit = len(self) + offset if limit is None else limit
  471. i = 0
  472. while len(self) + offset > maxlen:
  473. if i >= limit:
  474. break
  475. try:
  476. item = heappop(H)
  477. except IndexError:
  478. break
  479. if self.expires:
  480. if now() < item[0] + self.expires:
  481. heappush(H, item)
  482. break
  483. try:
  484. self._data.pop(item[1])
  485. except KeyError: # out of sync with heap
  486. pass
  487. i += 1
  488. def update(self, other, heappush=heappush):
  489. if isinstance(other, LimitedSet):
  490. self._data.update(other._data)
  491. self._heap.extend(other._heap)
  492. heapify(self._heap)
  493. else:
  494. for obj in other:
  495. self.add(obj)
  496. def as_dict(self):
  497. return self._data
  498. def __eq__(self, other):
  499. return self._heap == other._heap
  500. def __ne__(self, other):
  501. return not self.__eq__(other)
  502. def __repr__(self):
  503. return 'LimitedSet({0})'.format(len(self))
  504. def __iter__(self):
  505. return (item[1] for item in self._heap)
  506. def __len__(self):
  507. return len(self._heap)
  508. def __contains__(self, key):
  509. return key in self._data
  510. def __reduce__(self):
  511. return self.__class__, (
  512. self.maxlen, self.expires, self._data, self._heap,
  513. )
  514. MutableSet.register(LimitedSet)