core-admin/qubes/events.py

72 lines
1.5 KiB
Python
Raw Normal View History

2014-11-13 14:38:41 +01:00
#!/usr/bin/python2 -O
2014-11-13 18:10:27 +01:00
'''Qubes events.
Events are fired when something happens, like VM start or stop, property change
etc.
'''
2014-11-13 14:38:41 +01:00
import collections
import qubes.vm
2014-11-13 18:10:27 +01:00
#: collection of system-wide hooks
2014-11-13 14:38:41 +01:00
system_hooks = collections.defaultdict(list)
def hook(event, vm=None, system=False):
2014-11-13 18:10:27 +01:00
'''Decorator factory.
To hook an event, decorate a method in your plugin class with this
decorator.
:param str event: event type
:param type vm: VM to hook (leave as None to hook all VMs)
:param bool system: when :py:obj:`True`, hook is system-wide (not attached to any VM)
'''
2014-11-13 14:38:41 +01:00
def decorator(f):
f.ho_event = event
if system:
f.ho_vm = None
elif vm is None:
f.ho_vm = qubes.vm.BaseVM
else:
f.ho_vm = vm
return f
return decorator
def ishook(o):
2014-11-13 18:10:27 +01:00
'''Test if a method is hooked to an event.
:param object o: suspected hook
:return: :py:obj:`True` when function is a hook, :py:obj:`False` otherwise
:rtype: bool
'''
2014-11-13 14:38:41 +01:00
return callable(o) \
and hasattr(o, 'ho_event') \
and hasattr(o, 'ho_vm')
def add_system_hook(event, f):
2014-11-13 18:10:27 +01:00
'''Add system-wide hook.
:param callable f: function to call
'''
2014-11-13 14:38:41 +01:00
global_hooks[event].append(f)
def fire_system_hooks(event, *args, **kwargs):
2014-11-13 18:10:27 +01:00
'''Fire system-wide hooks.
:param str event: event type
*args* and *kwargs* are passed to all hooks.
'''
2014-11-13 14:38:41 +01:00
for hook in system_hooks[event]:
hook(self, *args, **kwargs)