qvm_shutdown.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # encoding=utf-8
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2010-2016 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2011-2016 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2016 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU Lesser General Public License as published by
  12. # the Free Software Foundation; either version 2.1 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU Lesser General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU Lesser General Public License along
  21. # with this program; if not, see <http://www.gnu.org/licenses/>.
  22. ''' Shutdown a qube '''
  23. from __future__ import print_function
  24. import sys
  25. import time
  26. import qubesadmin.tools
  27. import qubesadmin.exc
  28. parser = qubesadmin.tools.QubesArgumentParser(
  29. description=__doc__, vmname_nargs='+')
  30. parser.add_argument('--force',
  31. action='store_true', default=False,
  32. help='force operation, even if may damage other VMs (eg. shutdown of'
  33. ' network provider)')
  34. parser.add_argument('--wait',
  35. action='store_true', default=False,
  36. help='wait for the VMs to shut down')
  37. parser.add_argument('--timeout',
  38. action='store', type=float,
  39. default=60,
  40. help='timeout after which domains are killed when using --wait'
  41. ' (default: %d)')
  42. def main(args=None, app=None): # pylint: disable=missing-docstring
  43. args = parser.parse_args(args, app=app)
  44. for vm in args.domains:
  45. try:
  46. vm.shutdown(force=args.force)
  47. except qubesadmin.exc.QubesVMNotStartedError:
  48. pass
  49. if not args.wait:
  50. return
  51. timeout = args.timeout
  52. current_vms = list(sorted(args.domains))
  53. while timeout >= 0:
  54. current_vms = [vm for vm in current_vms
  55. if vm.get_power_state() != 'Halted']
  56. if not current_vms:
  57. return 0
  58. args.app.log.info('Waiting for shutdown ({}): {}'.format(
  59. timeout, ', '.join([str(vm) for vm in current_vms])))
  60. time.sleep(1)
  61. timeout -= 1
  62. args.app.log.info(
  63. 'Killing remaining qubes: {}'
  64. .format(', '.join([str(vm) for vm in current_vms])))
  65. for vm in current_vms:
  66. vm.kill()
  67. if __name__ == '__main__':
  68. sys.exit(main())