events.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program 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
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. '''Qubes events.
  22. Events are fired when something happens, like VM start or stop, property change
  23. etc.
  24. '''
  25. import collections
  26. def handler(*events):
  27. '''Event handler decorator factory.
  28. To hook an event, decorate a method in your plugin class with this
  29. decorator.
  30. It probably makes no sense to specify more than one handler for specific
  31. event in one class, because handlers are not run concurrently and there is
  32. no guarantee of the order of execution.
  33. .. note::
  34. For hooking events from extensions, see :py:func:`qubes.ext.handler`.
  35. :param str event: event type
  36. '''
  37. def decorator(func):
  38. # pylint: disable=missing-docstring
  39. func.ha_events = events
  40. # mark class own handler (i.e. not from extension)
  41. func.ha_bound = True
  42. return func
  43. return decorator
  44. def ishandler(obj):
  45. '''Test if a method is hooked to an event.
  46. :param object o: suspected hook
  47. :return: :py:obj:`True` when function is a hook, :py:obj:`False` otherwise
  48. :rtype: bool
  49. '''
  50. return callable(obj) \
  51. and hasattr(obj, 'ha_events')
  52. class EmitterMeta(type):
  53. '''Metaclass for :py:class:`Emitter`'''
  54. def __init__(cls, name, bases, dict_):
  55. super(EmitterMeta, cls).__init__(name, bases, dict_)
  56. cls.__handlers__ = collections.defaultdict(set)
  57. try:
  58. propnames = set(prop.__name__ for prop in cls.property_list())
  59. except AttributeError:
  60. propnames = set()
  61. for attr in dict_:
  62. if attr in propnames:
  63. # we have to be careful, not to getattr() on properties which
  64. # may be unset
  65. continue
  66. attr = dict_[attr]
  67. if not ishandler(attr):
  68. continue
  69. for event in attr.ha_events:
  70. cls.add_handler(event, attr)
  71. class Emitter(object, metaclass=EmitterMeta):
  72. '''Subject that can emit events.
  73. By default all events are disabled not to interfere with loading from XML.
  74. To enable event dispatch, set :py:attr:`events_enabled` to :py:obj:`True`.
  75. '''
  76. def __init__(self, *args, **kwargs):
  77. super(Emitter, self).__init__(*args, **kwargs)
  78. if not hasattr(self, 'events_enabled'):
  79. self.events_enabled = False
  80. @classmethod
  81. def add_handler(cls, event, func):
  82. '''Add event handler to subject's class.
  83. :param str event: event identificator
  84. :param collections.Callable handler: handler callable
  85. '''
  86. # pylint: disable=no-member
  87. cls.__handlers__[event].add(func)
  88. def _fire_event_in_order(self, order, event, kwargs):
  89. '''Fire event for classes in given order.
  90. Do not use this method. Use :py:meth:`fire_event` or
  91. :py:meth:`fire_event_pre`.
  92. '''
  93. if not self.events_enabled:
  94. return []
  95. effects = []
  96. for cls in order:
  97. if not hasattr(cls, '__handlers__'):
  98. continue
  99. handlers = cls.__handlers__[event]
  100. if '*' in cls.__handlers__:
  101. handlers = cls.__handlers__['*'] | handlers
  102. for func in sorted(handlers,
  103. key=(lambda handler: hasattr(handler, 'ha_bound')),
  104. reverse=True):
  105. effect = func(self, event, **kwargs)
  106. if effect is not None:
  107. effects.extend(effect)
  108. return effects
  109. def fire_event(self, event, **kwargs):
  110. '''Call all handlers for an event.
  111. Handlers are called for class and all parent classess, in **reversed**
  112. method resolution order. For each class first are called bound handlers
  113. (specified in class definition), then handlers from extensions. Aside
  114. from above, remaining order is undefined.
  115. .. seealso::
  116. :py:meth:`fire_event_pre`
  117. :param str event: event identificator
  118. :returns: list of effects
  119. All *kwargs* are passed verbatim. They are different for different
  120. events.
  121. '''
  122. return self._fire_event_in_order(reversed(self.__class__.__mro__),
  123. event, kwargs)
  124. def fire_event_pre(self, event, **kwargs):
  125. '''Call all handlers for an event.
  126. Handlers are called for class and all parent classess, in **true**
  127. method resolution order. This is intended for ``-pre-`` events, where
  128. order of invocation should be reversed.
  129. .. seealso::
  130. :py:meth:`fire_event`
  131. :param str event: event identificator
  132. :returns: list of effects
  133. All *kwargs* are passed verbatim. They are different for different
  134. events.
  135. '''
  136. return self._fire_event_in_order(self.__class__.__mro__,
  137. event, kwargs)