datastructures.py 18 KB

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