datastructures.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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 .five import items
  18. from .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. if sys.version_info[0] == 3: # pragma: no cover
  310. items = _iterate_items
  311. keys = _iterate_keys
  312. else:
  313. def keys(self):
  314. return list(self)
  315. def items(self):
  316. return list(self._iterate_items())
  317. MutableMapping.register(DictAttribute)
  318. class ConfigurationView(AttributeDictMixin):
  319. """A view over an applications configuration dicts.
  320. If the key does not exist in ``changes``, the ``defaults`` dicts
  321. are consulted.
  322. :param changes: Dict containing changes to the configuration.
  323. :param defaults: List of dicts containing the default configuration.
  324. """
  325. changes = None
  326. defaults = None
  327. _order = None
  328. def __init__(self, changes, defaults):
  329. self.__dict__.update(changes=changes, defaults=defaults,
  330. _order=[changes] + defaults)
  331. def add_defaults(self, d):
  332. if not isinstance(d, Mapping):
  333. d = DictAttribute(d)
  334. self.defaults.insert(0, d)
  335. self._order.insert(1, d)
  336. def __getitem__(self, key):
  337. for d in self._order:
  338. try:
  339. return d[key]
  340. except KeyError:
  341. pass
  342. raise KeyError(key)
  343. def __setitem__(self, key, value):
  344. self.changes[key] = value
  345. def first(self, *keys):
  346. return first(None, (self.get(key) for key in keys))
  347. def get(self, key, default=None):
  348. try:
  349. return self[key]
  350. except KeyError:
  351. return default
  352. def setdefault(self, key, default):
  353. try:
  354. return self[key]
  355. except KeyError:
  356. self[key] = default
  357. return default
  358. def update(self, *args, **kwargs):
  359. return self.changes.update(*args, **kwargs)
  360. def __contains__(self, key):
  361. for d in self._order:
  362. if key in d:
  363. return True
  364. return False
  365. def __repr__(self):
  366. return repr(dict(items(self)))
  367. def __iter__(self):
  368. return self._iterate_keys()
  369. def __len__(self):
  370. # The logic for iterating keys includes uniq(),
  371. # so to be safe we count by explicitly iterating
  372. return len(self.keys())
  373. def _iter(self, op):
  374. # defaults must be first in the stream, so values in
  375. # changes takes precedence.
  376. return chain(*[op(d) for d in reversed(self._order)])
  377. def _iterate_keys(self):
  378. return uniq(self._iter(lambda d: d))
  379. iterkeys = _iterate_keys
  380. def _iterate_items(self):
  381. return ((key, self[key]) for key in self)
  382. iteritems = _iterate_items
  383. def _iterate_values(self):
  384. return (self[key] for key in self)
  385. itervalues = _iterate_values
  386. def keys(self):
  387. return list(self._iterate_keys())
  388. def items(self):
  389. return list(self._iterate_items())
  390. def values(self):
  391. return list(self._iterate_values())
  392. MutableMapping.register(ConfigurationView)
  393. class LimitedSet(object):
  394. """Kind-of Set with limitations.
  395. Good for when you need to test for membership (`a in set`),
  396. but the list might become to big.
  397. :keyword maxlen: Maximum number of members before we start
  398. evicting expired members.
  399. :keyword expires: Time in seconds, before a membership expires.
  400. """
  401. def __init__(self, maxlen=None, expires=None, data=None, heap=None):
  402. self.maxlen = maxlen
  403. self.expires = expires
  404. self._data = {} if data is None else data
  405. self._heap = [] if heap is None else heap
  406. # make shortcuts
  407. self.__iter__ = self._data.__iter__
  408. self.__len__ = self._data.__len__
  409. self.__contains__ = self._data.__contains__
  410. def __iter__(self):
  411. return iter(self._data)
  412. def __len__(self):
  413. return len(self._data)
  414. def __contains__(self, key):
  415. return key in self._data
  416. def add(self, value):
  417. """Add a new member."""
  418. self.purge(1)
  419. now = time.time()
  420. self._data[value] = now
  421. heappush(self._heap, (now, value))
  422. def __reduce__(self):
  423. return self.__class__, (
  424. self.maxlen, self.expires, self._data, self._heap,
  425. )
  426. def clear(self):
  427. """Remove all members"""
  428. self._data.clear()
  429. self._heap[:] = []
  430. def pop_value(self, value):
  431. """Remove membership by finding value."""
  432. try:
  433. itime = self._data[value]
  434. except KeyError:
  435. return
  436. try:
  437. self._heap.remove((value, itime))
  438. except ValueError:
  439. pass
  440. self._data.pop(value, None)
  441. def _expire_item(self):
  442. """Hunt down and remove an expired item."""
  443. self.purge(1)
  444. def purge(self, limit=None):
  445. H, maxlen = self._heap, self.maxlen
  446. if not maxlen:
  447. return
  448. i = 0
  449. while len(self) >= maxlen:
  450. if limit and i > limit:
  451. break
  452. try:
  453. item = heappop(H)
  454. except IndexError:
  455. break
  456. if self.expires:
  457. if time.time() < item[0] + self.expires:
  458. heappush(H, item)
  459. break
  460. self._data.pop(item[1])
  461. i += 1
  462. def update(self, other, heappush=heappush):
  463. if isinstance(other, self.__class__):
  464. self._data.update(other._data)
  465. self._heap.extend(other._heap)
  466. heapify(self._heap)
  467. else:
  468. for obj in other:
  469. self.add(obj)
  470. def as_dict(self):
  471. return self._data
  472. def __repr__(self):
  473. return 'LimitedSet(%s)' % (repr(list(self._data))[:100], )
  474. @property
  475. def chronologically(self):
  476. return [value for _, value in self._heap]
  477. @property
  478. def first(self):
  479. """Get the oldest member."""
  480. return self._heap[0][1]
  481. MutableSet.register(LimitedSet)