datastructures.py 18 KB

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