qvm_start.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. '''qvm-start - start a domain'''
  21. import argparse
  22. import sys
  23. import subprocess
  24. import time
  25. import qubesadmin.devices
  26. import qubesadmin.exc
  27. import qubesadmin.tools
  28. class DriveAction(argparse.Action):
  29. '''Action for argument parser that stores drive image path.'''
  30. # pylint: disable=redefined-builtin,too-few-public-methods
  31. def __init__(self,
  32. option_strings,
  33. dest='drive',
  34. prefix='cdrom:',
  35. metavar='IMAGE',
  36. required=False,
  37. help='Attach drive'):
  38. super(DriveAction, self).__init__(option_strings, dest,
  39. metavar=metavar, help=help)
  40. self.prefix = prefix
  41. def __call__(self, parser, namespace, values, option_string=None):
  42. # pylint: disable=redefined-outer-name
  43. setattr(namespace, self.dest, self.prefix + values)
  44. parser = qubesadmin.tools.QubesArgumentParser(
  45. description='start a domain', vmname_nargs='+')
  46. parser.add_argument('--skip-if-running',
  47. action='store_true', default=False,
  48. help='Do not fail if the qube is already runnning')
  49. parser_drive = parser.add_mutually_exclusive_group()
  50. parser_drive.add_argument('--drive', metavar='DRIVE',
  51. help='temporarily attach specified drive as CD/DVD or hard disk (can be'
  52. ' specified with prefix "hd:" or "cdrom:", default is cdrom)')
  53. parser_drive.add_argument('--hddisk',
  54. action=DriveAction, dest='drive', prefix='hd:',
  55. help='temporarily attach specified drive as hard disk')
  56. parser_drive.add_argument('--cdrom', metavar='IMAGE',
  57. action=DriveAction, dest='drive', prefix='cdrom:',
  58. help='temporarily attach specified drive as CD/DVD')
  59. parser_drive.add_argument('--install-windows-tools',
  60. action='store_const', dest='drive', default=False,
  61. const='cdrom:dom0:/usr/lib/qubes/qubes-windows-tools.iso',
  62. help='temporarily attach Windows tools CDROM to the domain')
  63. def get_drive_assignment(app, drive_str):
  64. ''' Prepare :py:class:`qubesadmin.devices.DeviceAssignment` object for a
  65. given drive.
  66. If running in dom0, it will also take care about creating appropriate
  67. loop device (if necessary). Otherwise, only existing block devices are
  68. supported.
  69. :param app: Qubes() instance
  70. :param drive_str: drive argument
  71. :return: DeviceAssignment matching *drive_str*
  72. '''
  73. devtype = 'cdrom'
  74. if drive_str.startswith('cdrom:'):
  75. devtype = 'cdrom'
  76. drive_str = drive_str[len('cdrom:'):]
  77. elif drive_str.startswith('hd:'):
  78. devtype = 'disk'
  79. drive_str = drive_str[len('hd:'):]
  80. backend_domain_name, ident = drive_str.split(':', 1)
  81. try:
  82. backend_domain = app.domains[backend_domain_name]
  83. except KeyError:
  84. raise qubesadmin.exc.QubesVMNotFoundError(
  85. 'No such VM: %s', backend_domain_name)
  86. if ident.startswith('/'):
  87. # it is a path - if we're running in dom0, try to call losetup to
  88. # export the device, otherwise reject
  89. if app.qubesd_connection_type == 'qrexec':
  90. raise qubesadmin.exc.QubesException(
  91. 'Existing block device identifier needed when running from '
  92. 'outside of dom0 (see qvm-block)')
  93. try:
  94. if backend_domain.klass == 'AdminVM':
  95. loop_name = subprocess.check_output(
  96. ['sudo', 'losetup', '-f', '--show', ident])
  97. else:
  98. loop_name, _ = backend_domain.run(
  99. 'losetup -f --show ' + ident, user='root')
  100. except subprocess.CalledProcessError:
  101. raise qubesadmin.exc.QubesException(
  102. 'Failed to setup loop device for %s', ident)
  103. loop_name = loop_name.strip()
  104. assert loop_name.startswith(b'/dev/loop')
  105. ident = loop_name.decode().split('/')[2]
  106. # wait for device to appear
  107. # FIXME: convert this to waiting for event
  108. timeout = 10
  109. while isinstance(backend_domain.devices['block'][ident],
  110. qubesadmin.devices.UnknownDevice):
  111. if timeout == 0:
  112. raise qubesadmin.exc.QubesException(
  113. 'Timeout waiting for {}:{} device to appear'.format(
  114. backend_domain.name, ident))
  115. timeout -= 1
  116. time.sleep(1)
  117. options = {
  118. 'devtype': devtype,
  119. 'read-only': devtype == 'cdrom'
  120. }
  121. assignment = qubesadmin.devices.DeviceAssignment(
  122. backend_domain,
  123. ident,
  124. options=options,
  125. persistent=True)
  126. return assignment
  127. def main(args=None, app=None):
  128. '''Main routine of :program:`qvm-start`.
  129. :param list args: Optional arguments to override those delivered from \
  130. command line.
  131. '''
  132. args = parser.parse_args(args, app=app)
  133. exit_code = 0
  134. for domain in args.domains:
  135. if domain.is_running():
  136. if args.skip_if_running:
  137. continue
  138. exit_code = 1
  139. parser.print_error(
  140. 'domain {} is already running'.format(domain.name))
  141. return exit_code
  142. drive_assignment = None
  143. try:
  144. if args.drive:
  145. drive_assignment = get_drive_assignment(args.app, args.drive)
  146. try:
  147. domain.devices['block'].attach(drive_assignment)
  148. except:
  149. drive_assignment = None
  150. raise
  151. domain.start()
  152. if drive_assignment:
  153. # don't reconnect this device after VM reboot
  154. domain.devices['block'].update_persistent(
  155. drive_assignment.device, False)
  156. except (IOError, OSError, qubesadmin.exc.QubesException) as e:
  157. if drive_assignment:
  158. try:
  159. domain.devices['block'].detach(drive_assignment)
  160. except qubesadmin.exc.QubesException:
  161. pass
  162. exit_code = 1
  163. parser.print_error(str(e))
  164. return exit_code
  165. if __name__ == '__main__':
  166. sys.exit(main())