qvm_start.py 6.1 KB

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