events.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. #!/usr/bin/python2 -O
  2. '''Qubes events.
  3. Events are fired when something happens, like VM start or stop, property change
  4. etc.
  5. '''
  6. import collections
  7. def handler(*events):
  8. '''Event handler decorator factory.
  9. To hook an event, decorate a method in your plugin class with this
  10. decorator.
  11. It probably makes no sense to specify more than one handler for specific
  12. event in one class, because handlers are not run concurrently and there is
  13. no guarantee of the order of execution.
  14. .. note::
  15. For hooking events from extensions, see :py:func:`qubes.ext.handler`.
  16. :param str event: event type
  17. '''
  18. def decorator(f):
  19. f.ha_events = events
  20. return f
  21. return decorator
  22. def ishandler(o):
  23. '''Test if a method is hooked to an event.
  24. :param object o: suspected hook
  25. :return: :py:obj:`True` when function is a hook, :py:obj:`False` otherwise
  26. :rtype: bool
  27. '''
  28. return callable(o) \
  29. and hasattr(o, 'ha_events')
  30. class EmitterMeta(type):
  31. '''Metaclass for :py:class:`Emitter`'''
  32. def __init__(cls, name, bases, dict_):
  33. super(type, cls).__init__(name, bases, dict_)
  34. cls.__handlers__ = collections.defaultdict(set)
  35. try:
  36. propnames = set(prop.__name__ for prop in cls.get_props_list())
  37. except AttributeError:
  38. propnames = set()
  39. for attr in dict_:
  40. if attr in propnames:
  41. # we have to be careful, not to getattr() on properties which
  42. # may be unset
  43. continue
  44. attr = dict_[attr]
  45. if not ishandler(attr):
  46. continue
  47. for event in attr.ha_events:
  48. cls.add_handler(event, attr)
  49. class Emitter(object):
  50. '''Subject that can emit events
  51. '''
  52. __metaclass__ = EmitterMeta
  53. def __init__(self, *args, **kwargs):
  54. super(Emitter, self).__init__(*args, **kwargs)
  55. self.events_enabled = True
  56. @classmethod
  57. def add_handler(cls, event, handler):
  58. '''Add event handler to subject's class
  59. :param str event: event identificator
  60. :param collections.Callable handler: handler callable
  61. '''
  62. cls.__handlers__[event].add(handler)
  63. def _fire_event_in_order(self, order, event, *args, **kwargs):
  64. '''Fire event for classes in given order.
  65. Do not use this method. Use :py:meth:`fire_event` or
  66. :py:meth:`fire_event_pre`.
  67. '''
  68. if not self.events_enabled:
  69. return
  70. for cls in order:
  71. if not hasattr(cls, '__handlers__'):
  72. continue
  73. for handler in sorted(cls.__handlers__[event],
  74. key=(lambda handler: hasattr(handler, 'ha_bound')), reverse=True):
  75. handler(self, event, *args, **kwargs)
  76. def fire_event(self, event, *args, **kwargs):
  77. '''Call all handlers for an event.
  78. Handlers are called for class and all parent classess, in **reversed**
  79. method resolution order. For each class first are called bound handlers
  80. (specified in class definition), then handlers from extensions. Aside
  81. from above, remaining order is undefined.
  82. .. seealso::
  83. :py:meth:`fire_event_pre`
  84. :param str event: event identificator
  85. All *args* and *kwargs* are passed verbatim. They are different for
  86. different events.
  87. '''
  88. self._fire_event_in_order(reversed(self.__class__.__mro__), event, *args, **kwargs)
  89. def fire_event_pre(self, event, *args, **kwargs):
  90. '''Call all handlers for an event.
  91. Handlers are called for class and all parent classess, in **true**
  92. method resolution order. This is intended for ``-pre-`` events, where
  93. order of invocation should be reversed.
  94. .. seealso::
  95. :py:meth:`fire_event`
  96. :param str event: event identificator
  97. All *args* and *kwargs* are passed verbatim. They are different for
  98. different events.
  99. '''
  100. self._fire_event_in_order(self.__class__.__mro__, event, *args, **kwargs)