utils.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. ''' Utilities for common events-based actions '''
  21. import asyncio
  22. import functools
  23. import qubesadmin.events
  24. import qubesadmin.exc
  25. class Interrupt(Exception):
  26. '''Interrupt events processing'''
  27. def interrupt_on_vm_shutdown(vm, subject, event):
  28. '''Interrupt events processing when given VM was shutdown'''
  29. # pylint: disable=unused-argument
  30. if event == 'connection-established':
  31. if vm.is_halted():
  32. raise Interrupt
  33. elif event == 'domain-shutdown' and vm == subject:
  34. raise Interrupt
  35. def wait_for_domain_shutdown(vm, timeout):
  36. ''' Helper function to wait for domain shutdown.
  37. This function wait for domain shutdown, but do not initiate the shutdown
  38. itself.
  39. Note: you need to close event loop after calling this function.
  40. :param vm: QubesVM object to wait for shutdown on
  41. :param timeout: Timeout in seconds, use 0 for no timeout
  42. '''
  43. events = qubesadmin.events.EventsDispatcher(vm.app)
  44. loop = asyncio.get_event_loop()
  45. events.add_handler('domain-shutdown',
  46. functools.partial(interrupt_on_vm_shutdown, vm))
  47. events.add_handler('connection-established',
  48. functools.partial(interrupt_on_vm_shutdown, vm))
  49. events_task = asyncio.ensure_future(events.listen_for_events(),
  50. loop=loop)
  51. if timeout:
  52. # pylint: disable=no-member
  53. loop.call_later(timeout, events_task.cancel)
  54. try:
  55. loop.run_until_complete(events_task)
  56. except asyncio.CancelledError:
  57. raise qubesadmin.exc.QubesVMShutdownTimeout(
  58. 'VM %s shutdown timeout expired', vm.name)
  59. except Interrupt:
  60. pass