datastructures.py 18 KB

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