events.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  19. #
  20. '''Qubes events.
  21. Events are fired when something happens, like VM start or stop, property change
  22. etc.
  23. '''
  24. import asyncio
  25. import collections
  26. import fnmatch
  27. import itertools
  28. def handler(*events):
  29. '''Event handler decorator factory.
  30. To hook an event, decorate a method in your plugin class with this
  31. decorator.
  32. Some event handlers may be defined as coroutine. In such a case
  33. :py:func:`asyncio.coroutine` decorator should be used after this one,
  34. i.e. you should decorate a coroutine.
  35. See appropriate event documentation for details.
  36. .. note::
  37. For hooking events from extensions, see :py:func:`qubes.ext.handler`.
  38. :param str events: events names, can contain basic wildcards (`*`, `?`)
  39. '''
  40. def decorator(func):
  41. # pylint: disable=missing-docstring
  42. func.ha_events = events
  43. # mark class own handler (i.e. not from extension)
  44. func.ha_bound = True
  45. return func
  46. return decorator
  47. def ishandler(obj):
  48. '''Test if a method is hooked to an event.
  49. :param object o: suspected hook
  50. :return: :py:obj:`True` when function is a hook, :py:obj:`False` otherwise
  51. :rtype: bool
  52. '''
  53. return callable(obj) \
  54. and hasattr(obj, 'ha_events')
  55. class EmitterMeta(type):
  56. '''Metaclass for :py:class:`Emitter`'''
  57. def __init__(cls, name, bases, dict_):
  58. super(EmitterMeta, cls).__init__(name, bases, dict_)
  59. cls.__handlers__ = collections.defaultdict(set)
  60. try:
  61. propnames = set(prop.__name__ for prop in cls.property_list())
  62. except AttributeError:
  63. propnames = set()
  64. for attr in dict_:
  65. if attr in propnames:
  66. # we have to be careful, not to getattr() on properties which
  67. # may be unset
  68. continue
  69. attr = dict_[attr]
  70. if not ishandler(attr):
  71. continue
  72. for event in attr.ha_events:
  73. cls.__handlers__[event].add(attr)
  74. class Emitter(metaclass=EmitterMeta):
  75. '''Subject that can emit events.
  76. By default all events are disabled not to interfere with loading from XML.
  77. To enable event dispatch, set :py:attr:`events_enabled` to :py:obj:`True`.
  78. '''
  79. def __init__(self, *args, **kwargs):
  80. super().__init__(*args, **kwargs)
  81. if not hasattr(self, 'events_enabled'):
  82. self.events_enabled = False
  83. self.__handlers__ = collections.defaultdict(set)
  84. def close(self):
  85. self.events_enabled = False
  86. def add_handler(self, event, func):
  87. '''Add event handler to subject's class.
  88. This is class method, it is invalid to call it on object instance.
  89. :param str event: event identificator
  90. :param collections.abc.Callable handler: handler callable
  91. '''
  92. # pylint: disable=no-member
  93. self.__handlers__[event].add(func)
  94. def remove_handler(self, event, func):
  95. '''Remove event handler from subject's class.
  96. This is class method, it is invalid to call it on object instance.
  97. This method must be called on the same class as
  98. :py:meth:`add_handler` was called to register the handler.
  99. :param str event: event identificator
  100. :param collections.abc.Callable handler: handler callable
  101. '''
  102. # pylint: disable=no-member
  103. self.__handlers__[event].remove(func)
  104. def _fire_event(self, event, kwargs, pre_event=False):
  105. '''Fire event for classes in given order.
  106. Do not use this method. Use :py:meth:`fire_event`.
  107. '''
  108. if not self.events_enabled:
  109. return [], []
  110. order = itertools.chain((self,), self.__class__.__mro__)
  111. if not pre_event:
  112. order = reversed(list(order))
  113. effects = []
  114. async_effects = []
  115. for i in order:
  116. try:
  117. handlers_dict = i.__handlers__
  118. except AttributeError:
  119. continue
  120. handlers = [h_func for h_name, h_func_set in handlers_dict.items()
  121. for h_func in h_func_set
  122. if fnmatch.fnmatch(event, h_name)]
  123. for func in sorted(handlers,
  124. key=(lambda handler: hasattr(handler, 'ha_bound')),
  125. reverse=True):
  126. effect = func(self, event, **kwargs)
  127. if asyncio.iscoroutinefunction(func):
  128. async_effects.append(effect)
  129. elif effect is not None:
  130. effects.extend(effect)
  131. return effects, async_effects
  132. def fire_event(self, event, pre_event=False, **kwargs):
  133. '''Call all handlers for an event.
  134. Handlers are called for class and all parent classes, in **reversed**
  135. or **true** (depending on *pre_event* parameter)
  136. method resolution order. For each class first are called bound handlers
  137. (specified in class definition), then handlers from extensions. Aside
  138. from above, remaining order is undefined.
  139. This method call only synchronous handlers. If any asynchronous
  140. handler is registered for the event, :py:class:``RuntimeError`` is
  141. raised.
  142. .. seealso::
  143. :py:meth:`fire_event_async`
  144. :param str event: event identifier
  145. :param pre_event: is this -pre- event? reverse handlers calling order
  146. :returns: list of effects
  147. All *kwargs* are passed verbatim. They are different for different
  148. events.
  149. '''
  150. sync_effects, async_effects = self._fire_event(event, kwargs,
  151. pre_event=pre_event)
  152. if async_effects:
  153. raise RuntimeError(
  154. 'unexpected async-handler(s) {!r} for sync event {!s}'.format(
  155. async_effects, event))
  156. return sync_effects
  157. @asyncio.coroutine
  158. def fire_event_async(self, event, pre_event=False, **kwargs):
  159. '''Call all handlers for an event, allowing async calls.
  160. Handlers are called for class and all parent classes, in **reversed**
  161. or **true** (depending on *pre_event* parameter)
  162. method resolution order. For each class first are called bound handlers
  163. (specified in class definition), then handlers from extensions. Aside
  164. from above, remaining order is undefined.
  165. This method call both synchronous and asynchronous handlers. Order of
  166. asynchronous calls is, by definition, undefined.
  167. .. seealso::
  168. :py:meth:`fire_event`
  169. :param str event: event identifier
  170. :param pre_event: is this -pre- event? reverse handlers calling order
  171. :returns: list of effects
  172. All *kwargs* are passed verbatim. They are different for different
  173. events.
  174. '''
  175. sync_effects, async_effects = self._fire_event(event,
  176. kwargs, pre_event=pre_event)
  177. effects = sync_effects
  178. if async_effects:
  179. async_tasks, _ = yield from asyncio.wait(async_effects)
  180. for task in async_tasks:
  181. effect = task.result()
  182. if effect is not None:
  183. effects.extend(effect)
  184. return effects