qvm_create.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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.list_vmclass()
  85. print('\n'.join(vm_classes))
  86. return 0
  87. pools = {}
  88. pool = None
  89. if hasattr(args, 'pool') and args.pool:
  90. for pool_vol in args.pool:
  91. try:
  92. volume_name, pool_name = pool_vol.split('=')
  93. pools[volume_name] = pool_name
  94. except ValueError:
  95. parser.error(
  96. 'Pool argument must be of form: -P volume_name=pool_name')
  97. if args.one_pool:
  98. pool = args.one_pool
  99. if args.disp:
  100. args.properties.setdefault('label', 'red')
  101. args.cls = 'DispVM'
  102. if args.standalone:
  103. args.cls = 'StandaloneVM'
  104. if 'label' not in args.properties:
  105. parser.error('--label option is mandatory')
  106. if 'name' not in args.properties:
  107. parser.error('VMNAME is mandatory')
  108. root_source_path = args.root_copy_from or args.root_move_from
  109. if root_source_path and not os.path.exists(root_source_path):
  110. parser.error(
  111. 'File pointed by --root-copy-from/--root-move-from does not exist')
  112. # those are known of non-persistent root, do not list those with known
  113. # persistent root, as an extension may add new classes
  114. if root_source_path and args.cls in ('AppVM', 'DispVM'):
  115. parser.error('--root-copy-from/--root-move-from used but this qube '
  116. 'does not have own \'root\' volume (uses template\'s one)')
  117. try:
  118. args.app.get_label(args.properties['label'])
  119. except KeyError:
  120. parser.error('no such label: {!r}; available: {}'.format(
  121. args.properties['label'],
  122. ', '.join(args.app.labels)))
  123. try:
  124. args.app.get_vm_class(args.cls)
  125. except KeyError:
  126. parser.error('no such domain class: {!r}'.format(args.cls))
  127. try:
  128. if args.cls == 'StandaloneVM' and 'template' in args.properties:
  129. # "template-based" StandaloneVM is special, as it's a clone of
  130. # the template
  131. vm = args.app.clone_vm(args.properties.pop('template'),
  132. args.properties.pop('name'),
  133. new_cls=args.cls,
  134. pool=pool,
  135. pools=pools,
  136. ignore_volumes=('private',))
  137. else:
  138. vm = args.app.add_new_vm(args.cls,
  139. name=args.properties.pop('name'),
  140. label=args.properties.pop('label'),
  141. template=args.properties.pop('template', None),
  142. pool=pool,
  143. pools=pools)
  144. except qubesadmin.exc.QubesException as e:
  145. args.app.log.error('Error creating VM: {!s}'.format(e))
  146. return 1
  147. retcode = 0
  148. for prop, value in args.properties.items():
  149. try:
  150. setattr(vm, prop, value)
  151. except qubesadmin.exc.QubesException as e:
  152. args.app.log.error(
  153. 'Error setting property {} (but VM created): {!s}'.
  154. format(prop, e))
  155. retcode = 2
  156. if root_source_path:
  157. try:
  158. root_size = os.path.getsize(root_source_path)
  159. if root_size > vm.volumes['root'].size:
  160. vm.volumes['root'].resize(root_size)
  161. with open(root_source_path, 'rb') as root_file:
  162. vm.volumes['root'].import_data(root_file)
  163. if args.root_move_from:
  164. os.unlink(root_source_path)
  165. except qubesadmin.exc.QubesException as e:
  166. args.app.log.error(
  167. 'Error importing root volume (but VM created): {}'.
  168. format(e))
  169. retcode = 3
  170. return retcode
  171. if __name__ == '__main__':
  172. sys.exit(main())