qvm_template_postprocess.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2016 Marek Marczykowski-Górecki
  5. # <marmarek@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU Lesser General Public License as published by
  9. # the Free Software Foundation; either version 2.1 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. ''' Tool for importing rpm-installed template'''
  21. import asyncio
  22. import glob
  23. import os
  24. import shutil
  25. import subprocess
  26. import sys
  27. import grp
  28. import qubesadmin
  29. import qubesadmin.exc
  30. import qubesadmin.tools
  31. try:
  32. # pylint: disable=wrong-import-position
  33. import qubesadmin.events.utils
  34. have_events = True
  35. except ImportError:
  36. have_events = False
  37. parser = qubesadmin.tools.QubesArgumentParser(
  38. description='Postprocess template package')
  39. parser.add_argument('--really', action='store_true', default=False,
  40. help='Really perform the action, YOU SHOULD REALLY KNOW WHAT YOU ARE DOING')
  41. parser.add_argument('--skip-start', action='store_true',
  42. help='Do not start the VM - do not retrieve menu entries etc.')
  43. parser.add_argument('--keep-source', action='store_true',
  44. help='Do not remove source data (*dir* directory) after import')
  45. parser.add_argument('--no-installed-by-rpm', action='store_true',
  46. help='Do not set installed_by_rpm')
  47. parser.add_argument('--allow-pv', action='store_true',
  48. help='Allow setting virt_mode to pv in configuration file.')
  49. parser.add_argument('--pool',
  50. help='Specify pool to store created VMs in.')
  51. parser.add_argument('action', choices=['post-install', 'pre-remove'],
  52. help='Action to perform')
  53. parser.add_argument('name', action='store',
  54. help='Template name')
  55. parser.add_argument('dir', action='store',
  56. help='Template directory')
  57. def get_root_img_size(source_dir):
  58. '''Extract size of root.img to be imported'''
  59. root_path = os.path.join(source_dir, 'root.img')
  60. # deal with both cases: split tar and non-split tar
  61. part_path = root_path + '.part.00'
  62. tar_path = root_path + '.tar'
  63. if os.path.exists(part_path) or os.path.exists(tar_path):
  64. # get just file root_size from the tar header
  65. path = part_path if os.path.exists(part_path) else tar_path
  66. p = subprocess.Popen(['tar', 'tvf', path],
  67. stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  68. (stdout, _) = p.communicate()
  69. # -rw-r--r-- 0/0 1073741824 1970-01-01 01:00 root.img
  70. root_size = int(stdout.split()[2])
  71. elif os.path.exists(root_path):
  72. root_size = os.path.getsize(root_path)
  73. else:
  74. raise qubesadmin.exc.QubesException('root.img not found')
  75. return root_size
  76. def import_root_img(vm, source_dir):
  77. '''Import root.img into VM object'''
  78. # Try not break existing data in the volume in case of import failure. If
  79. # volume needs to be extended, do it before import, if reduced - after.
  80. root_size = get_root_img_size(source_dir)
  81. if vm.volumes['root'].size < root_size:
  82. vm.volumes['root'].resize(root_size)
  83. root_path = os.path.join(source_dir, 'root.img')
  84. if os.path.exists(root_path + '.part.00'):
  85. input_files = glob.glob(root_path + '.part.*')
  86. cat = subprocess.Popen(['cat'] + sorted(input_files),
  87. stdout=subprocess.PIPE)
  88. tar = subprocess.Popen(['tar', 'xSOf', '-'],
  89. stdin=cat.stdout,
  90. stdout=subprocess.PIPE)
  91. cat.stdout.close()
  92. vm.volumes['root'].import_data(stream=tar.stdout)
  93. if tar.wait() != 0:
  94. raise qubesadmin.exc.QubesException('root.img extraction failed')
  95. if cat.wait() != 0:
  96. raise qubesadmin.exc.QubesException('root.img extraction failed')
  97. elif os.path.exists(root_path + '.tar'):
  98. tar = subprocess.Popen(['tar', 'xSOf', root_path + '.tar'],
  99. stdout=subprocess.PIPE)
  100. vm.volumes['root'].import_data(stream=tar.stdout)
  101. if tar.wait() != 0:
  102. raise qubesadmin.exc.QubesException('root.img extraction failed')
  103. elif os.path.exists(root_path):
  104. if vm.app.qubesd_connection_type == 'socket':
  105. # check if root.img was already overwritten, i.e. if the source
  106. # and destination paths are the same
  107. vid = vm.volumes['root'].vid
  108. pool = vm.app.pools[vm.volumes['root'].pool]
  109. if (pool.driver in ('file', 'file-reflink')
  110. and root_path == os.path.join(pool.config['dir_path'],
  111. vid + '.img')):
  112. vm.log.info('root.img already in place, do not re-import')
  113. return
  114. with open(root_path, 'rb') as root_file:
  115. vm.volumes['root'].import_data(stream=root_file)
  116. if vm.volumes['root'].size > root_size:
  117. try:
  118. vm.volumes['root'].resize(root_size)
  119. except qubesadmin.exc.QubesException as err:
  120. vm.log.warning(
  121. 'Failed to resize root volume of {} from {} to {} after '
  122. 'import: {}'.format(vm.name, vm.volumes['root'].size,
  123. root_size, str(err)))
  124. def reset_private_img(vm):
  125. '''Clear private volume'''
  126. vm.volumes['private'].clear_data()
  127. def import_appmenus(vm, source_dir):
  128. '''Import appmenus settings into VM object (later: GUI VM)'''
  129. if os.getuid() == 0:
  130. try:
  131. qubes_group = grp.getgrnam('qubes')
  132. user = qubes_group.gr_mem[0]
  133. cmd_prefix = ['runuser', '-u', user, '--', 'env', 'DISPLAY=:0']
  134. except KeyError as e:
  135. vm.log.warning('Default user not found, not importing appmenus: ' +
  136. str(e))
  137. return
  138. else:
  139. cmd_prefix = []
  140. # store the whitelists in VM features
  141. # separated by spaces should be ok as there should be no spaces in the file
  142. # name according to the FreeDesktop spec
  143. with open(os.path.join(source_dir, 'vm-whitelisted-appmenus.list'), 'r') \
  144. as fd:
  145. vm.features['default-menu-items'] = ' '.join([x.rstrip() for x in fd])
  146. with open(os.path.join(source_dir, 'whitelisted-appmenus.list'), 'r') \
  147. as fd:
  148. vm.features['menu-items'] = ' '.join([x.rstrip() for x in fd])
  149. with open(
  150. os.path.join(source_dir, 'netvm-whitelisted-appmenus.list'), 'r') \
  151. as fd:
  152. vm.features['netvm-menu-items'] = ' '.join([x.rstrip() for x in fd])
  153. # TODO: change this to qrexec calls to GUI VM, when GUI VM will be
  154. # implemented
  155. try:
  156. subprocess.check_call(cmd_prefix + ['qvm-appmenus',
  157. '--set-default-whitelist={}'.format(os.path.join(source_dir,
  158. 'vm-whitelisted-appmenus.list')), vm.name])
  159. subprocess.check_call(cmd_prefix + ['qvm-appmenus',
  160. '--set-whitelist={}'.format(os.path.join(source_dir,
  161. 'whitelisted-appmenus.list')), vm.name])
  162. except subprocess.CalledProcessError as e:
  163. vm.log.warning('Failed to set default application list: %s', e)
  164. def parse_template_config(path):
  165. '''Parse template.conf from template package. (KEY=VALUE format)'''
  166. with open(path, 'r') as fd:
  167. return dict(line.rstrip('\n').split('=', 1) for line in fd)
  168. @asyncio.coroutine
  169. def call_postinstall_service(vm):
  170. '''Call qubes.PostInstall service
  171. And adjust related settings (netvm, features).
  172. '''
  173. # just created, so no need to save previous value - we know what it was
  174. vm.netvm = None
  175. # temporarily enable qrexec feature - so vm.start() will wait for it;
  176. # if start fails, rollback it
  177. vm.features['qrexec'] = True
  178. try:
  179. vm.start()
  180. except qubesadmin.exc.QubesException:
  181. del vm.features['qrexec']
  182. else:
  183. try:
  184. vm.run_service_for_stdio('qubes.PostInstall')
  185. except subprocess.CalledProcessError:
  186. vm.log.error('qubes.PostInstall service failed')
  187. vm.shutdown()
  188. if have_events:
  189. try:
  190. # pylint: disable=no-member
  191. yield from asyncio.wait_for(
  192. qubesadmin.events.utils.wait_for_domain_shutdown([vm]),
  193. qubesadmin.config.defaults['shutdown_timeout'])
  194. except asyncio.TimeoutError:
  195. vm.kill()
  196. else:
  197. timeout = qubesadmin.config.defaults['shutdown_timeout']
  198. while timeout >= 0:
  199. if vm.is_halted():
  200. break
  201. yield from asyncio.sleep(1)
  202. timeout -= 1
  203. if not vm.is_halted():
  204. try:
  205. vm.kill()
  206. except qubesadmin.exc.QubesVMNotStartedError:
  207. pass
  208. finally:
  209. vm.netvm = qubesadmin.DEFAULT
  210. @asyncio.coroutine
  211. def post_install(args):
  212. '''Handle post-installation tasks'''
  213. app = args.app
  214. vm_created = False
  215. # reinstall and running in dom0, using the same directory as qubes core
  216. local_reinstall = False
  217. try:
  218. # reinstall
  219. vm = app.domains[args.name]
  220. if app.qubesd_connection_type == 'socket' and \
  221. args.dir == '/var/lib/qubes/vm-templates/' + args.name:
  222. # VM exists and use use the same directory as target vm - on
  223. # final cleanup remove only some files, not the whole directory
  224. local_reinstall = True
  225. except KeyError:
  226. if app.qubesd_connection_type == 'socket' and \
  227. args.dir == '/var/lib/qubes/vm-templates/' + args.name:
  228. # vm.create_on_disk() need to create the directory on its own,
  229. # move it away from its way
  230. tmp_sourcedir = os.path.join('/var/lib/qubes/vm-templates',
  231. 'tmp-' + args.name)
  232. shutil.move(args.dir, tmp_sourcedir)
  233. args.dir = tmp_sourcedir
  234. vm = app.add_new_vm('TemplateVM',
  235. name=args.name,
  236. label=qubesadmin.config.defaults['template_label'],
  237. pool=args.pool)
  238. vm_created = True
  239. vm.log.info('Importing data')
  240. try:
  241. import_root_img(vm, args.dir)
  242. except:
  243. # if data import fails, remove half-created VM
  244. if vm_created:
  245. del app.domains[vm.name]
  246. raise
  247. if not vm_created:
  248. vm.log.info('Clearing private volume')
  249. reset_private_img(vm)
  250. vm.installed_by_rpm = not args.no_installed_by_rpm
  251. import_appmenus(vm, args.dir)
  252. conf_path = os.path.join(args.dir, 'template.conf')
  253. if os.path.exists(conf_path):
  254. conf = parse_template_config(conf_path)
  255. # Import qvm-feature tags
  256. for key in (
  257. 'no-monitor-layout',
  258. 'pci-e820-host',
  259. 'linux-stubdom',
  260. 'gui',
  261. 'gui-emulated'
  262. 'qrexec'):
  263. if key in conf:
  264. if conf[key] == '1':
  265. vm.features[key] = conf[key]
  266. else:
  267. vm.log.warning(
  268. 'ignoring boolean config flags that are not \'1\'')
  269. for key in (
  270. 'net.fake-ip',
  271. 'net.fake-gateway',
  272. 'net.fake-netmask'):
  273. if key in conf:
  274. vm.features[key] = conf[key]
  275. if 'virt-mode' in conf:
  276. if conf['virt-mode'] == 'pv' and args.allow_pv:
  277. vm.virt_mode = 'pv'
  278. elif conf['virt-mode'] == 'pv':
  279. vm.log.warning(
  280. '--allow-pv not set, ignoring request to change virt-mode')
  281. elif conf['virt-mode'] in ('pvh', 'hvm'):
  282. vm.virt_mode = conf['virt-mode']
  283. if 'kernel' in conf:
  284. if conf['kernel'] == '':
  285. vm.kernel = ''
  286. else:
  287. vm.log.warning(
  288. 'Currently only supports setting kernel to (none)')
  289. if not args.skip_start:
  290. yield from call_postinstall_service(vm)
  291. if not args.keep_source:
  292. if local_reinstall:
  293. # remove only imported root img
  294. root_path = os.path.join(args.dir, 'root.img')
  295. for root_part in glob.glob(root_path + '.part.*'):
  296. os.unlink(root_part)
  297. else:
  298. shutil.rmtree(args.dir)
  299. # if running as root, tell underlying storage layer about just freed
  300. # data blocks
  301. if os.getuid() == 0:
  302. subprocess.call(['sync', '-f', os.path.dirname(args.dir)])
  303. subprocess.call(['fstrim', os.path.dirname(args.dir)])
  304. return 0
  305. def pre_remove(args):
  306. '''Handle pre-removal tasks'''
  307. app = args.app
  308. try:
  309. tpl = app.domains[args.name]
  310. except KeyError:
  311. parser.error('No Qube with this name exists')
  312. for appvm in tpl.appvms:
  313. parser.error('Qube {} uses this template'.format(appvm.name))
  314. tpl.installed_by_rpm = False
  315. del app.domains[args.name]
  316. return 0
  317. def is_chroot():
  318. '''Detect if running inside chroot'''
  319. try:
  320. stat_root = os.stat('/')
  321. stat_init_root = os.stat('/proc/1/root/.')
  322. return (
  323. stat_root.st_dev != stat_init_root.st_dev or
  324. stat_root.st_ino != stat_init_root.st_ino)
  325. except IOError:
  326. print('Stat failed, assuming not chroot', file=sys.stderr)
  327. return False
  328. def main(args=None, app=None):
  329. '''Main function of qvm-template-postprocess'''
  330. args = parser.parse_args(args, app=app)
  331. if is_chroot():
  332. print('Running in chroot, ignoring request. Import template with:',
  333. file=sys.stderr)
  334. print(' '.join(sys.argv), file=sys.stderr)
  335. return
  336. if not args.really:
  337. parser.error('Do not call this tool directly.')
  338. if args.action == 'post-install':
  339. loop = asyncio.get_event_loop()
  340. try:
  341. loop.run_until_complete(post_install(args))
  342. loop.stop()
  343. loop.run_forever()
  344. finally:
  345. loop.close()
  346. elif args.action == 'pre-remove':
  347. pre_remove(args)
  348. else:
  349. parser.error('Unknown action')
  350. return 0
  351. if __name__ == '__main__':
  352. sys.exit(main())