qvm_start.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 backend_domain.klass == '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. loop_name = loop_name.strip()
  103. assert loop_name.startswith(b'/dev/loop')
  104. ident = loop_name.decode().split('/')[2]
  105. # FIXME: synchronize with udev + exposing device in qubesdb
  106. options = {
  107. 'devtype': devtype,
  108. 'read-only': devtype == 'cdrom'
  109. }
  110. assignment = qubesadmin.devices.DeviceAssignment(
  111. backend_domain,
  112. ident,
  113. options=options,
  114. persistent=True)
  115. return assignment
  116. def main(args=None, app=None):
  117. '''Main routine of :program:`qvm-start`.
  118. :param list args: Optional arguments to override those delivered from \
  119. command line.
  120. '''
  121. args = parser.parse_args(args, app=app)
  122. exit_code = 0
  123. for domain in args.domains:
  124. if domain.is_running():
  125. if args.skip_if_running:
  126. continue
  127. exit_code = 1
  128. parser.print_error(
  129. 'domain {} is already running'.format(domain.name))
  130. return exit_code
  131. drive_assignment = None
  132. try:
  133. if args.drive:
  134. drive_assignment = get_drive_assignment(args.app, args.drive)
  135. try:
  136. domain.devices['block'].attach(drive_assignment)
  137. except:
  138. drive_assignment = None
  139. raise
  140. domain.start()
  141. if drive_assignment:
  142. # don't reconnect this device after VM reboot
  143. domain.devices['block'].update_persistent(
  144. drive_assignment.device, False)
  145. except (IOError, OSError, qubesadmin.exc.QubesException) as e:
  146. if drive_assignment:
  147. try:
  148. domain.devices['block'].detach(drive_assignment)
  149. except qubesadmin.exc.QubesException:
  150. pass
  151. exit_code = 1
  152. parser.print_error(str(e))
  153. return exit_code
  154. if __name__ == '__main__':
  155. sys.exit(main())