qvm_shutdown.py 2.6 KB

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