qvm_create.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. # Copyright (C) 2017 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU Lesser General Public License as published by
  11. # the Free Software Foundation; either version 2.1 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. '''qvm-create tool'''
  24. # TODO list available classes
  25. # TODO list labels (maybe in qvm-prefs)
  26. # TODO features, devices, tags
  27. from __future__ import print_function
  28. import argparse
  29. import os
  30. import sys
  31. import qubesadmin
  32. import qubesadmin.tools
  33. parser = qubesadmin.tools.QubesArgumentParser()
  34. parser.add_argument('--class', '-C', dest='cls',
  35. default='AppVM',
  36. help='specify the class of the new domain (default: %(default)s)')
  37. parser.add_argument('--standalone',
  38. action="store_true",
  39. help=' shortcut for --class StandaloneVM')
  40. parser.add_argument('--disp',
  41. action="store_true",
  42. help='alias for --class DispVM --label red')
  43. parser.add_argument('--property', '--prop',
  44. action=qubesadmin.tools.PropertyAction,
  45. help='set domain\'s property, like "internal", "memory" or "vcpus"')
  46. parser.add_argument('--pool', '-p',
  47. action='append',
  48. metavar='VOLUME_NAME=POOL_NAME',
  49. help='specify the pool to use for a volume')
  50. parser.add_argument('-P',
  51. metavar='POOL_NAME',
  52. dest='one_pool',
  53. default='',
  54. help='change all volume pools to specified pool')
  55. parser.add_argument('--template', '-t',
  56. action=qubesadmin.tools.SinglePropertyAction,
  57. help='specify the TemplateVM to use')
  58. parser.add_argument('--label', '-l',
  59. action=qubesadmin.tools.SinglePropertyAction,
  60. help='specify the label to use for the new domain'
  61. ' (e.g. red, yellow, green, ...)')
  62. parser.add_argument('--help-classes',
  63. action='store_true',
  64. help='List available classes and exit')
  65. parser_root = parser.add_mutually_exclusive_group()
  66. parser_root.add_argument('--root-copy-from', '-r', metavar='FILENAME',
  67. help='use provided root.img instead of default/empty one'
  68. ' (file will be COPIED)')
  69. parser_root.add_argument('--root-move-from', '-R', metavar='FILENAME',
  70. help='use provided root.img instead of default/empty one'
  71. ' (file will be MOVED)')
  72. # silently ignored
  73. parser_root.add_argument('--no-root',
  74. action='store_true', default=False,
  75. help=argparse.SUPPRESS)
  76. parser.add_argument('name', metavar='VMNAME',
  77. action=qubesadmin.tools.SinglePropertyAction,
  78. nargs='?',
  79. help='name of the domain to create')
  80. def main(args=None, app=None):
  81. '''Main function of qvm-create tool'''
  82. args = parser.parse_args(args, app=app)
  83. if args.help_classes:
  84. vm_classes = args.app.qubesd_call('dom0', 'admin.vmclass.List').decode()
  85. vm_classes = vm_classes.splitlines()
  86. print('\n'.join(sorted(vm_classes)))
  87. return 0
  88. pools = {}
  89. pool = None
  90. if hasattr(args, 'pool') and args.pool:
  91. for pool_vol in args.pool:
  92. try:
  93. volume_name, pool_name = pool_vol.split('=')
  94. pools[volume_name] = pool_name
  95. except ValueError:
  96. parser.error(
  97. 'Pool argument must be of form: -P volume_name=pool_name')
  98. if args.one_pool:
  99. pool = args.one_pool
  100. if args.disp:
  101. args.properties.setdefault('label', 'red')
  102. args.cls = 'DispVM'
  103. if args.standalone:
  104. args.cls = 'StandaloneVM'
  105. if 'label' not in args.properties:
  106. parser.error('--label option is mandatory')
  107. if 'name' not in args.properties:
  108. parser.error('VMNAME is mandatory')
  109. root_source_path = args.root_copy_from or args.root_move_from
  110. if root_source_path and not os.path.exists(root_source_path):
  111. parser.error(
  112. 'File pointed by --root-copy-from/--root-move-from does not exist')
  113. # those are known of non-persistent root, do not list those with known
  114. # persistent root, as an extension may add new classes
  115. if root_source_path and args.cls in ('AppVM', 'DispVM'):
  116. parser.error('--root-copy-from/--root-move-from used but this qube '
  117. 'does not have own \'root\' volume (uses template\'s one)')
  118. try:
  119. args.app.get_label(args.properties['label'])
  120. except KeyError:
  121. parser.error('no such label: {!r}; available: {}'.format(
  122. args.properties['label'],
  123. ', '.join(args.app.labels)))
  124. try:
  125. args.app.get_vm_class(args.cls)
  126. except KeyError:
  127. parser.error('no such domain class: {!r}'.format(args.cls))
  128. try:
  129. if args.cls == 'StandaloneVM' and 'template' in args.properties:
  130. # "template-based" StandaloneVM is special, as it's a clone of
  131. # the template
  132. vm = args.app.clone_vm(args.properties.pop('template'),
  133. args.properties.pop('name'),
  134. new_cls=args.cls,
  135. pool=pool,
  136. pools=pools,
  137. ignore_volumes=('private',))
  138. else:
  139. vm = args.app.add_new_vm(args.cls,
  140. name=args.properties.pop('name'),
  141. label=args.properties.pop('label'),
  142. template=args.properties.pop('template', None),
  143. pool=pool,
  144. pools=pools)
  145. except qubesadmin.exc.QubesException as e:
  146. args.app.log.error('Error creating VM: {!s}'.format(e))
  147. return 1
  148. retcode = 0
  149. for prop, value in args.properties.items():
  150. try:
  151. setattr(vm, prop, value)
  152. except qubesadmin.exc.QubesException as e:
  153. args.app.log.error(
  154. 'Error setting property {} (but VM created): {!s}'.
  155. format(prop, e))
  156. retcode = 2
  157. if root_source_path:
  158. try:
  159. root_size = os.path.getsize(root_source_path)
  160. if root_size > vm.volumes['root'].size:
  161. vm.volumes['root'].resize(root_size)
  162. with open(root_source_path, 'rb') as root_file:
  163. vm.volumes['root'].import_data(root_file)
  164. if args.root_move_from:
  165. os.unlink(root_source_path)
  166. except qubesadmin.exc.QubesException as e:
  167. args.app.log.error(
  168. 'Error importing root volume (but VM created): {}'.
  169. format(e))
  170. retcode = 3
  171. return retcode
  172. if __name__ == '__main__':
  173. sys.exit(main())