hooks.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://aws.amazon.com/apache2.0/
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. import copy
  14. import logging
  15. from collections import defaultdict, deque, namedtuple
  16. from botocore.compat import accepts_kwargs, six
  17. from botocore.utils import EVENT_ALIASES
  18. logger = logging.getLogger(__name__)
  19. _NodeList = namedtuple('NodeList', ['first', 'middle', 'last'])
  20. _FIRST = 0
  21. _MIDDLE = 1
  22. _LAST = 2
  23. class NodeList(_NodeList):
  24. def __copy__(self):
  25. first_copy = copy.copy(self.first)
  26. middle_copy = copy.copy(self.middle)
  27. last_copy = copy.copy(self.last)
  28. copied = NodeList(first_copy, middle_copy, last_copy)
  29. return copied
  30. def first_non_none_response(responses, default=None):
  31. """Find first non None response in a list of tuples.
  32. This function can be used to find the first non None response from
  33. handlers connected to an event. This is useful if you are interested
  34. in the returned responses from event handlers. Example usage::
  35. print(first_non_none_response([(func1, None), (func2, 'foo'),
  36. (func3, 'bar')]))
  37. # This will print 'foo'
  38. :type responses: list of tuples
  39. :param responses: The responses from the ``EventHooks.emit`` method.
  40. This is a list of tuples, and each tuple is
  41. (handler, handler_response).
  42. :param default: If no non-None responses are found, then this default
  43. value will be returned.
  44. :return: The first non-None response in the list of tuples.
  45. """
  46. for response in responses:
  47. if response[1] is not None:
  48. return response[1]
  49. return default
  50. class BaseEventHooks(object):
  51. def emit(self, event_name, **kwargs):
  52. """Call all handlers subscribed to an event.
  53. :type event_name: str
  54. :param event_name: The name of the event to emit.
  55. :type **kwargs: dict
  56. :param **kwargs: Arbitrary kwargs to pass through to the
  57. subscribed handlers. The ``event_name`` will be injected
  58. into the kwargs so it's not necesary to add this to **kwargs.
  59. :rtype: list of tuples
  60. :return: A list of ``(handler_func, handler_func_return_value)``
  61. """
  62. return []
  63. def register(self, event_name, handler, unique_id=None,
  64. unique_id_uses_count=False):
  65. """Register an event handler for a given event.
  66. If a ``unique_id`` is given, the handler will not be registered
  67. if a handler with the ``unique_id`` has already been registered.
  68. Handlers are called in the order they have been registered.
  69. Note handlers can also be registered with ``register_first()``
  70. and ``register_last()``. All handlers registered with
  71. ``register_first()`` are called before handlers registered
  72. with ``register()`` which are called before handlers registered
  73. with ``register_last()``.
  74. """
  75. self._verify_and_register(event_name, handler, unique_id,
  76. register_method=self._register,
  77. unique_id_uses_count=unique_id_uses_count)
  78. def register_first(self, event_name, handler, unique_id=None,
  79. unique_id_uses_count=False):
  80. """Register an event handler to be called first for an event.
  81. All event handlers registered with ``register_first()`` will
  82. be called before handlers registered with ``register()`` and
  83. ``register_last()``.
  84. """
  85. self._verify_and_register(event_name, handler, unique_id,
  86. register_method=self._register_first,
  87. unique_id_uses_count=unique_id_uses_count)
  88. def register_last(self, event_name, handler, unique_id=None,
  89. unique_id_uses_count=False):
  90. """Register an event handler to be called last for an event.
  91. All event handlers registered with ``register_last()`` will be called
  92. after handlers registered with ``register_first()`` and ``register()``.
  93. """
  94. self._verify_and_register(event_name, handler, unique_id,
  95. register_method=self._register_last,
  96. unique_id_uses_count=unique_id_uses_count)
  97. def _verify_and_register(self, event_name, handler, unique_id,
  98. register_method, unique_id_uses_count):
  99. self._verify_is_callable(handler)
  100. self._verify_accept_kwargs(handler)
  101. register_method(event_name, handler, unique_id, unique_id_uses_count)
  102. def unregister(self, event_name, handler=None, unique_id=None,
  103. unique_id_uses_count=False):
  104. """Unregister an event handler for a given event.
  105. If no ``unique_id`` was given during registration, then the
  106. first instance of the event handler is removed (if the event
  107. handler has been registered multiple times).
  108. """
  109. pass
  110. def _verify_is_callable(self, func):
  111. if not six.callable(func):
  112. raise ValueError("Event handler %s must be callable." % func)
  113. def _verify_accept_kwargs(self, func):
  114. """Verifies a callable accepts kwargs
  115. :type func: callable
  116. :param func: A callable object.
  117. :returns: True, if ``func`` accepts kwargs, otherwise False.
  118. """
  119. try:
  120. if not accepts_kwargs(func):
  121. raise ValueError("Event handler %s must accept keyword "
  122. "arguments (**kwargs)" % func)
  123. except TypeError:
  124. return False
  125. class HierarchicalEmitter(BaseEventHooks):
  126. def __init__(self):
  127. # We keep a reference to the handlers for quick
  128. # read only access (we never modify self._handlers).
  129. # A cache of event name to handler list.
  130. self._lookup_cache = {}
  131. self._handlers = _PrefixTrie()
  132. # This is used to ensure that unique_id's are only
  133. # registered once.
  134. self._unique_id_handlers = {}
  135. def _emit(self, event_name, kwargs, stop_on_response=False):
  136. """
  137. Emit an event with optional keyword arguments.
  138. :type event_name: string
  139. :param event_name: Name of the event
  140. :type kwargs: dict
  141. :param kwargs: Arguments to be passed to the handler functions.
  142. :type stop_on_response: boolean
  143. :param stop_on_response: Whether to stop on the first non-None
  144. response. If False, then all handlers
  145. will be called. This is especially useful
  146. to handlers which mutate data and then
  147. want to stop propagation of the event.
  148. :rtype: list
  149. :return: List of (handler, response) tuples from all processed
  150. handlers.
  151. """
  152. responses = []
  153. # Invoke the event handlers from most specific
  154. # to least specific, each time stripping off a dot.
  155. handlers_to_call = self._lookup_cache.get(event_name)
  156. if handlers_to_call is None:
  157. handlers_to_call = self._handlers.prefix_search(event_name)
  158. self._lookup_cache[event_name] = handlers_to_call
  159. elif not handlers_to_call:
  160. # Short circuit and return an empty response is we have
  161. # no handlers to call. This is the common case where
  162. # for the majority of signals, nothing is listening.
  163. return []
  164. kwargs['event_name'] = event_name
  165. responses = []
  166. for handler in handlers_to_call:
  167. logger.debug('Event %s: calling handler %s', event_name, handler)
  168. response = handler(**kwargs)
  169. responses.append((handler, response))
  170. if stop_on_response and response is not None:
  171. return responses
  172. return responses
  173. def emit(self, event_name, **kwargs):
  174. """
  175. Emit an event by name with arguments passed as keyword args.
  176. >>> responses = emitter.emit(
  177. ... 'my-event.service.operation', arg1='one', arg2='two')
  178. :rtype: list
  179. :return: List of (handler, response) tuples from all processed
  180. handlers.
  181. """
  182. return self._emit(event_name, kwargs)
  183. def emit_until_response(self, event_name, **kwargs):
  184. """
  185. Emit an event by name with arguments passed as keyword args,
  186. until the first non-``None`` response is received. This
  187. method prevents subsequent handlers from being invoked.
  188. >>> handler, response = emitter.emit_until_response(
  189. 'my-event.service.operation', arg1='one', arg2='two')
  190. :rtype: tuple
  191. :return: The first (handler, response) tuple where the response
  192. is not ``None``, otherwise (``None``, ``None``).
  193. """
  194. responses = self._emit(event_name, kwargs, stop_on_response=True)
  195. if responses:
  196. return responses[-1]
  197. else:
  198. return (None, None)
  199. def _register(self, event_name, handler, unique_id=None,
  200. unique_id_uses_count=False):
  201. self._register_section(event_name, handler, unique_id,
  202. unique_id_uses_count, section=_MIDDLE)
  203. def _register_first(self, event_name, handler, unique_id=None,
  204. unique_id_uses_count=False):
  205. self._register_section(event_name, handler, unique_id,
  206. unique_id_uses_count, section=_FIRST)
  207. def _register_last(self, event_name, handler, unique_id,
  208. unique_id_uses_count=False):
  209. self._register_section(event_name, handler, unique_id,
  210. unique_id_uses_count, section=_LAST)
  211. def _register_section(self, event_name, handler, unique_id,
  212. unique_id_uses_count, section):
  213. if unique_id is not None:
  214. if unique_id in self._unique_id_handlers:
  215. # We've already registered a handler using this unique_id
  216. # so we don't need to register it again.
  217. count = self._unique_id_handlers[unique_id].get('count', None)
  218. if unique_id_uses_count:
  219. if not count:
  220. raise ValueError(
  221. "Initial registration of unique id %s was "
  222. "specified to use a counter. Subsequent register "
  223. "calls to unique id must specify use of a counter "
  224. "as well." % unique_id)
  225. else:
  226. self._unique_id_handlers[unique_id]['count'] += 1
  227. else:
  228. if count:
  229. raise ValueError(
  230. "Initial registration of unique id %s was "
  231. "specified to not use a counter. Subsequent "
  232. "register calls to unique id must specify not to "
  233. "use a counter as well." % unique_id)
  234. return
  235. else:
  236. # Note that the trie knows nothing about the unique
  237. # id. We track uniqueness in this class via the
  238. # _unique_id_handlers.
  239. self._handlers.append_item(event_name, handler,
  240. section=section)
  241. unique_id_handler_item = {'handler': handler}
  242. if unique_id_uses_count:
  243. unique_id_handler_item['count'] = 1
  244. self._unique_id_handlers[unique_id] = unique_id_handler_item
  245. else:
  246. self._handlers.append_item(event_name, handler, section=section)
  247. # Super simple caching strategy for now, if we change the registrations
  248. # clear the cache. This has the opportunity for smarter invalidations.
  249. self._lookup_cache = {}
  250. def unregister(self, event_name, handler=None, unique_id=None,
  251. unique_id_uses_count=False):
  252. if unique_id is not None:
  253. try:
  254. count = self._unique_id_handlers[unique_id].get('count', None)
  255. except KeyError:
  256. # There's no handler matching that unique_id so we have
  257. # nothing to unregister.
  258. return
  259. if unique_id_uses_count:
  260. if count is None:
  261. raise ValueError(
  262. "Initial registration of unique id %s was specified to "
  263. "use a counter. Subsequent unregister calls to unique "
  264. "id must specify use of a counter as well." % unique_id)
  265. elif count == 1:
  266. handler = self._unique_id_handlers.pop(unique_id)['handler']
  267. else:
  268. self._unique_id_handlers[unique_id]['count'] -= 1
  269. return
  270. else:
  271. if count:
  272. raise ValueError(
  273. "Initial registration of unique id %s was specified "
  274. "to not use a counter. Subsequent unregister calls "
  275. "to unique id must specify not to use a counter as "
  276. "well." % unique_id)
  277. handler = self._unique_id_handlers.pop(unique_id)['handler']
  278. try:
  279. self._handlers.remove_item(event_name, handler)
  280. self._lookup_cache = {}
  281. except ValueError:
  282. pass
  283. def __copy__(self):
  284. new_instance = self.__class__()
  285. new_state = self.__dict__.copy()
  286. new_state['_handlers'] = copy.copy(self._handlers)
  287. new_state['_unique_id_handlers'] = copy.copy(self._unique_id_handlers)
  288. new_instance.__dict__ = new_state
  289. return new_instance
  290. class EventAliaser(BaseEventHooks):
  291. def __init__(self, event_emitter, event_aliases=None):
  292. self._event_aliases = event_aliases
  293. if event_aliases is None:
  294. self._event_aliases = EVENT_ALIASES
  295. self._emitter = event_emitter
  296. def emit(self, event_name, **kwargs):
  297. aliased_event_name = self._alias_event_name(event_name)
  298. return self._emitter.emit(aliased_event_name, **kwargs)
  299. def emit_until_response(self, event_name, **kwargs):
  300. aliased_event_name = self._alias_event_name(event_name)
  301. return self._emitter.emit_until_response(aliased_event_name, **kwargs)
  302. def register(self, event_name, handler, unique_id=None,
  303. unique_id_uses_count=False):
  304. aliased_event_name = self._alias_event_name(event_name)
  305. return self._emitter.register(
  306. aliased_event_name, handler, unique_id, unique_id_uses_count
  307. )
  308. def register_first(self, event_name, handler, unique_id=None,
  309. unique_id_uses_count=False):
  310. aliased_event_name = self._alias_event_name(event_name)
  311. return self._emitter.register_first(
  312. aliased_event_name, handler, unique_id, unique_id_uses_count
  313. )
  314. def register_last(self, event_name, handler, unique_id=None,
  315. unique_id_uses_count=False):
  316. aliased_event_name = self._alias_event_name(event_name)
  317. return self._emitter.register_last(
  318. aliased_event_name, handler, unique_id, unique_id_uses_count
  319. )
  320. def unregister(self, event_name, handler=None, unique_id=None,
  321. unique_id_uses_count=False):
  322. aliased_event_name = self._alias_event_name(event_name)
  323. return self._emitter.unregister(
  324. aliased_event_name, handler, unique_id, unique_id_uses_count
  325. )
  326. def _alias_event_name(self, event_name):
  327. for old_part, new_part in self._event_aliases.items():
  328. # We can't simply do a string replace for everything, otherwise we
  329. # might end up translating substrings that we never intended to
  330. # translate. When there aren't any dots in the old event name
  331. # part, then we can quickly replace the item in the list if it's
  332. # there.
  333. event_parts = event_name.split('.')
  334. if '.' not in old_part:
  335. try:
  336. # Theoretically a given event name could have the same part
  337. # repeated, but in practice this doesn't happen
  338. event_parts[event_parts.index(old_part)] = new_part
  339. except ValueError:
  340. continue
  341. # If there's dots in the name, it gets more complicated. Now we
  342. # have to replace multiple sections of the original event.
  343. elif old_part in event_name:
  344. old_parts = old_part.split('.')
  345. self._replace_subsection(event_parts, old_parts, new_part)
  346. else:
  347. continue
  348. new_name = '.'.join(event_parts)
  349. logger.debug("Changing event name from %s to %s" % (
  350. event_name, new_name
  351. ))
  352. return new_name
  353. return event_name
  354. def _replace_subsection(self, sections, old_parts, new_part):
  355. for i in range(len(sections)):
  356. if sections[i] == old_parts[0] and \
  357. sections[i:i+len(old_parts)] == old_parts:
  358. sections[i:i+len(old_parts)] = [new_part]
  359. return
  360. def __copy__(self):
  361. return self.__class__(
  362. copy.copy(self._emitter),
  363. copy.copy(self._event_aliases)
  364. )
  365. class _PrefixTrie(object):
  366. """Specialized prefix trie that handles wildcards.
  367. The prefixes in this case are based on dot separated
  368. names so 'foo.bar.baz' is::
  369. foo -> bar -> baz
  370. Wildcard support just means that having a key such as 'foo.bar.*.baz' will
  371. be matched with a call to ``get_items(key='foo.bar.ANYTHING.baz')``.
  372. You can think of this prefix trie as the equivalent as defaultdict(list),
  373. except that it can do prefix searches:
  374. foo.bar.baz -> A
  375. foo.bar -> B
  376. foo -> C
  377. Calling ``get_items('foo.bar.baz')`` will return [A + B + C], from
  378. most specific to least specific.
  379. """
  380. def __init__(self):
  381. # Each dictionary can be though of as a node, where a node
  382. # has values associated with the node, and children is a link
  383. # to more nodes. So 'foo.bar' would have a 'foo' node with
  384. # a 'bar' node as a child of foo.
  385. # {'foo': {'children': {'bar': {...}}}}.
  386. self._root = {'chunk': None, 'children': {}, 'values': None}
  387. def append_item(self, key, value, section=_MIDDLE):
  388. """Add an item to a key.
  389. If a value is already associated with that key, the new
  390. value is appended to the list for the key.
  391. """
  392. key_parts = key.split('.')
  393. current = self._root
  394. for part in key_parts:
  395. if part not in current['children']:
  396. new_child = {'chunk': part, 'values': None, 'children': {}}
  397. current['children'][part] = new_child
  398. current = new_child
  399. else:
  400. current = current['children'][part]
  401. if current['values'] is None:
  402. current['values'] = NodeList([], [], [])
  403. current['values'][section].append(value)
  404. def prefix_search(self, key):
  405. """Collect all items that are prefixes of key.
  406. Prefix in this case are delineated by '.' characters so
  407. 'foo.bar.baz' is a 3 chunk sequence of 3 "prefixes" (
  408. "foo", "bar", and "baz").
  409. """
  410. collected = deque()
  411. key_parts = key.split('.')
  412. current = self._root
  413. self._get_items(current, key_parts, collected, 0)
  414. return collected
  415. def _get_items(self, starting_node, key_parts, collected, starting_index):
  416. stack = [(starting_node, starting_index)]
  417. key_parts_len = len(key_parts)
  418. # Traverse down the nodes, where at each level we add the
  419. # next part from key_parts as well as the wildcard element '*'.
  420. # This means for each node we see we potentially add two more
  421. # elements to our stack.
  422. while stack:
  423. current_node, index = stack.pop()
  424. if current_node['values']:
  425. # We're using extendleft because we want
  426. # the values associated with the node furthest
  427. # from the root to come before nodes closer
  428. # to the root. extendleft() also adds its items
  429. # in right-left order so .extendleft([1, 2, 3])
  430. # will result in final_list = [3, 2, 1], which is
  431. # why we reverse the lists.
  432. node_list = current_node['values']
  433. complete_order = (node_list.first + node_list.middle +
  434. node_list.last)
  435. collected.extendleft(reversed(complete_order))
  436. if not index == key_parts_len:
  437. children = current_node['children']
  438. directs = children.get(key_parts[index])
  439. wildcard = children.get('*')
  440. next_index = index + 1
  441. if wildcard is not None:
  442. stack.append((wildcard, next_index))
  443. if directs is not None:
  444. stack.append((directs, next_index))
  445. def remove_item(self, key, value):
  446. """Remove an item associated with a key.
  447. If the value is not associated with the key a ``ValueError``
  448. will be raised. If the key does not exist in the trie, a
  449. ``ValueError`` will be raised.
  450. """
  451. key_parts = key.split('.')
  452. current = self._root
  453. self._remove_item(current, key_parts, value, index=0)
  454. def _remove_item(self, current_node, key_parts, value, index):
  455. if current_node is None:
  456. return
  457. elif index < len(key_parts):
  458. next_node = current_node['children'].get(key_parts[index])
  459. if next_node is not None:
  460. self._remove_item(next_node, key_parts, value, index + 1)
  461. if index == len(key_parts) - 1:
  462. node_list = next_node['values']
  463. if value in node_list.first:
  464. node_list.first.remove(value)
  465. elif value in node_list.middle:
  466. node_list.middle.remove(value)
  467. elif value in node_list.last:
  468. node_list.last.remove(value)
  469. if not next_node['children'] and not next_node['values']:
  470. # Then this is a leaf node with no values so
  471. # we can just delete this link from the parent node.
  472. # This makes subsequent search faster in the case
  473. # where a key does not exist.
  474. del current_node['children'][key_parts[index]]
  475. else:
  476. raise ValueError(
  477. "key is not in trie: %s" % '.'.join(key_parts))
  478. def __copy__(self):
  479. # The fact that we're using a nested dict under the covers
  480. # is an implementation detail, and the user shouldn't have
  481. # to know that they'd normally need a deepcopy so we expose
  482. # __copy__ instead of __deepcopy__.
  483. new_copy = self.__class__()
  484. copied_attrs = self._recursive_copy(self.__dict__)
  485. new_copy.__dict__ = copied_attrs
  486. return new_copy
  487. def _recursive_copy(self, node):
  488. # We can't use copy.deepcopy because we actually only want to copy
  489. # the structure of the trie, not the handlers themselves.
  490. # Each node has a chunk, children, and values.
  491. copied_node = {}
  492. for key, value in node.items():
  493. if isinstance(value, NodeList):
  494. copied_node[key] = copy.copy(value)
  495. elif isinstance(value, dict):
  496. copied_node[key] = self._recursive_copy(value)
  497. else:
  498. copied_node[key] = value
  499. return copied_node