qubes-events.rst 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. :py:mod:`qubes.events` -- Qubes events
  2. ======================================
  3. Some objects in qubes (most notably domains) emit events. You may hook them and
  4. execute your code when particular event is fired. Events in qubes are added
  5. class-wide -- it is not possible to add event handler to one instance only, you
  6. have to add handler for whole class.
  7. Firing events
  8. -------------
  9. Events are fired by calling :py:meth:`qubes.events.Emitter.fire_event`. The
  10. first argument is event name (a string). You can fire any event you wish, the
  11. names are not checked in any way, however each class' documentation tells what
  12. standard events will be fired on it. When firing an event, caller may specify
  13. some optional keyword arguments. Those are dependent on the particular event in
  14. question -- they are passed as-is to handlers.
  15. Event handlers are fired in reverse method resolution order, that is, first for
  16. parent class and then for it's child. For each class, first are called handlers
  17. defined in it's source, then handlers from extensions and last the callers added
  18. manually.
  19. The :py:meth:`qubes.events.Emitter.fire_event` method have keyword argument
  20. `pre_event`, which fires events in reverse order. It is suitable for events
  21. fired before some action is performed. You may at your own responsibility raise
  22. exceptions from such events to try to prevent such action.
  23. Events handlers may yield values. Those values are aggregated and returned
  24. to the caller as a list of those values. See below for details.
  25. Handling events
  26. ---------------
  27. There are several ways to handle events. In all cases you supply a callable
  28. (most likely function or method) that will be called when someone fires the
  29. event. The first argument passed to the callable will be the object instance on
  30. which the event was fired and the second one is the event name. The rest are
  31. passed from :py:meth:`qubes.events.Emitter.fire_event` as described previously.
  32. One callable can handle more than one event.
  33. The easiest way to hook an event is to use
  34. :py:func:`qubes.events.handler` decorator.
  35. .. code-block:: python
  36. import qubes.events
  37. class MyClass(qubes.events.Emitter):
  38. @qubes.events.handler('event1', 'event2')
  39. def event_handler(self, event):
  40. if event == 'event1':
  41. print('Got event 1')
  42. elif event == 'event2':
  43. print('Got event 2')
  44. o = MyClass()
  45. o.fire_event('event1')
  46. Note that your handler will be called for all instances of this class.
  47. .. TODO: extensions
  48. .. TODO: add/remove_handler
  49. Handling events with variable signature
  50. ---------------------------------------
  51. Some events are specified with variable signature (i.e. they may have different
  52. number of arguments on each call to handlers). You can write handlers just like
  53. every other python function with variable signature.
  54. .. code-block:: python
  55. import qubes
  56. def on_property_change(subject, event, name, newvalue, oldvalue=None):
  57. if oldvalue is None:
  58. print('Property {} initialised to {!r}'.format(name, newvalue))
  59. else:
  60. print('Property {} changed {!r} -> {!r}'.format(name, oldvalue, newvalue))
  61. app = qubes.Qubes()
  62. app.add_handler('property-set:default_netvm')
  63. If you expect :py:obj:`None` to be a reasonable value of the property, you have
  64. a problem. One way to solve it is to invent your very own, magic
  65. :py:class:`object` instance.
  66. .. code-block:: python
  67. import qubes
  68. MAGIC_NO_VALUE = object()
  69. def on_property_change(subject, event, name, newvalue, oldvalue=MAGIC_NO_VALUE):
  70. if oldvalue is MAGIC_NO_VALUE:
  71. print('Property {} initialised to {!r}'.format(name, newvalue))
  72. else:
  73. print('Property {} changed {!r} -> {!r}'.format(name, oldvalue, newvalue))
  74. app = qubes.Qubes()
  75. app.add_handler('property-set:default_netvm')
  76. There is no possible way of collision other than intentionally passing this very
  77. object (not even passing similar featureless ``object()``), because ``is``
  78. python syntax checks object's :py:meth:`id`\ entity, which will be different for
  79. each :py:class:`object` instance.
  80. Returning values from events
  81. ----------------------------
  82. Some events may be called to collect values from the handlers. For example the
  83. event ``is-fully-usable`` allows plugins to report a domain as not fully usable.
  84. Such handlers, instead of returning :py:obj:`None` (which is the default when
  85. the function does not include ``return`` statement), should return an iterable
  86. or itself be a generator. Those values are aggregated from all handlers and
  87. returned to the caller as list. The order of this list is undefined.
  88. .. code-block:: python
  89. import qubes.events
  90. class MyClass(qubes.events.Emitter):
  91. @qubes.events.handler('event1')
  92. def event1_handler1(self, event):
  93. # do not return anything, equivalent to "return" and "return None"
  94. pass
  95. @qubes.events.handler('event1')
  96. def event1_handler2(self, event):
  97. yield 'aqq'
  98. yield 'zxc'
  99. @qubes.events.handler('event1')
  100. def event1_handler3(self, event):
  101. return ('123', '456')
  102. o = MyClass()
  103. # returns ['aqq', 'zxc', '123', '456'], possibly not in order
  104. effect = o.fire_event('event1')
  105. Asynchronous event handling
  106. ---------------------------
  107. Event handlers can be defined as coroutine. This way they can execute long
  108. running actions without blocking the whole qubesd process. To define
  109. asynchronous event handler, annotate a coroutine (a function defined with
  110. `async def`, or decorated with :py:func:`asyncio.coroutine`) with
  111. :py:func:`qubes.events.handler` decorator. By definition, order of
  112. such handlers is undefined.
  113. Asynchronous events can be fired using
  114. :py:meth:`qubes.events.Emitter.fire_event_async` method. It will handle both
  115. synchronous and asynchronous handlers. It's an error to register asynchronous
  116. handler (a coroutine) for synchronous event (the one fired with
  117. :py:meth:`qubes.events.Emitter.fire_event`) - it will result in
  118. :py:exc:`RuntimeError` exception.
  119. .. code-block:: python
  120. import asyncio
  121. import qubes.events
  122. class MyClass(qubes.events.Emitter):
  123. @qubes.events.handler('event1', 'event2')
  124. @asyncio.coroutine
  125. def event_handler(self, event):
  126. if event == 'event1':
  127. print('Got event 1, starting long running action')
  128. yield from asyncio.sleep(10)
  129. print('Done')
  130. o = MyClass()
  131. loop = asyncio.get_event_loop()
  132. loop.run_until_complete(o.fire_event_async('event1'))
  133. Asynchronous event handlers can also return value - but only a collection, not
  134. yield individual values (because of python limitation):
  135. .. code-block:: python
  136. import asyncio
  137. import qubes.events
  138. class MyClass(qubes.events.Emitter):
  139. @qubes.events.handler('event1')
  140. @asyncio.coroutine
  141. def event_handler(self, event):
  142. print('Got event, starting long running action')
  143. yield from asyncio.sleep(10)
  144. return ('result1', 'result2')
  145. @qubes.events.handler('event1')
  146. @asyncio.coroutine
  147. def another_handler(self, event):
  148. print('Got event, starting long running action')
  149. yield from asyncio.sleep(10)
  150. return ('result3', 'result4')
  151. @qubes.events.handler('event1')
  152. def synchronous_handler(self, event):
  153. yield 'sync result'
  154. o = MyClass()
  155. loop = asyncio.get_event_loop()
  156. # returns ['sync result', 'result1', 'result2', 'result3', 'result4'],
  157. # possibly not in order
  158. effects = loop.run_until_complete(o.fire_event_async('event1'))
  159. Module contents
  160. ---------------
  161. .. automodule:: qubes.events
  162. :members:
  163. :show-inheritance:
  164. .. vim: ts=3 sw=3 et