events.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. import qubes.vm
  8. #: collection of system-wide hooks
  9. system_hooks = collections.defaultdict(list)
  10. def hook(event, vm=None, system=False):
  11. '''Decorator factory.
  12. To hook an event, decorate a method in your plugin class with this
  13. decorator.
  14. :param str event: event type
  15. :param type vm: VM to hook (leave as None to hook all VMs)
  16. :param bool system: when :py:obj:`True`, hook is system-wide (not attached to any VM)
  17. '''
  18. def decorator(f):
  19. f.ho_event = event
  20. if system:
  21. f.ho_vm = None
  22. elif vm is None:
  23. f.ho_vm = qubes.vm.BaseVM
  24. else:
  25. f.ho_vm = vm
  26. return f
  27. return decorator
  28. def ishook(o):
  29. '''Test if a method is hooked to an event.
  30. :param object o: suspected hook
  31. :return: :py:obj:`True` when function is a hook, :py:obj:`False` otherwise
  32. :rtype: bool
  33. '''
  34. return callable(o) \
  35. and hasattr(o, 'ho_event') \
  36. and hasattr(o, 'ho_vm')
  37. def add_system_hook(event, f):
  38. '''Add system-wide hook.
  39. :param callable f: function to call
  40. '''
  41. global_hooks[event].append(f)
  42. def fire_system_hooks(event, *args, **kwargs):
  43. '''Fire system-wide hooks.
  44. :param str event: event type
  45. *args* and *kwargs* are passed to all hooks.
  46. '''
  47. for hook in system_hooks[event]:
  48. hook(self, *args, **kwargs)