qvm_template_postprocess.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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('action', choices=['post-install', 'pre-remove'],
  46. help='Action to perform')
  47. parser.add_argument('name', action='store',
  48. help='Template name')
  49. parser.add_argument('dir', action='store',
  50. help='Template directory')
  51. def move_if_exists(source, dest_dir):
  52. '''Move file/directory if exists'''
  53. if os.path.exists(source):
  54. shutil.move(source, os.path.join(dest_dir, os.path.basename(source)))
  55. def get_root_img_size(source_dir):
  56. '''Extract size of root.img to be imported'''
  57. root_path = os.path.join(source_dir, 'root.img')
  58. if os.path.exists(root_path + '.part.00'):
  59. # get just file root_size from the tar header
  60. p = subprocess.Popen(['tar', 'tvf', root_path + '.part.00'],
  61. stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  62. (stdout, _) = p.communicate()
  63. # -rw-r--r-- 0/0 1073741824 1970-01-01 01:00 root.img
  64. root_size = int(stdout.split()[2])
  65. elif os.path.exists(root_path):
  66. root_size = os.path.getsize(root_path)
  67. else:
  68. raise qubesadmin.exc.QubesException('root.img not found')
  69. return root_size
  70. def import_root_img(vm, source_dir):
  71. '''Import root.img into VM object'''
  72. root_size = get_root_img_size(source_dir)
  73. vm.volumes['root'].resize(root_size)
  74. root_path = os.path.join(source_dir, 'root.img')
  75. if os.path.exists(root_path + '.part.00'):
  76. input_files = glob.glob(root_path + '.part.*')
  77. cat = subprocess.Popen(['cat'] + sorted(input_files),
  78. stdout=subprocess.PIPE)
  79. tar = subprocess.Popen(['tar', 'xSOf', '-'],
  80. stdin=cat.stdout,
  81. stdout=subprocess.PIPE)
  82. cat.stdout.close()
  83. vm.volumes['root'].import_data(stream=tar.stdout)
  84. if tar.wait() != 0:
  85. raise qubesadmin.exc.QubesException('root.img extraction failed')
  86. if cat.wait() != 0:
  87. raise qubesadmin.exc.QubesException('root.img extraction failed')
  88. elif os.path.exists(root_path):
  89. if vm.app.qubesd_connection_type == 'socket':
  90. # check if root.img was already overwritten, i.e. if the source
  91. # and destination paths are the same
  92. vid = vm.volumes['root'].vid
  93. pool = vm.app.pools[vm.volumes['root'].pool]
  94. if pool.driver == 'file' and root_path == os.path.join(
  95. pool.config['dir_path'], vid + '.img'):
  96. vm.log.info('root.img already in place, do not re-import')
  97. return
  98. with open(root_path, 'rb') as root_file:
  99. vm.volumes['root'].import_data(stream=root_file)
  100. def import_appmenus(vm, source_dir):
  101. '''Import appmenus settings into VM object (later: GUI VM)'''
  102. if os.getuid() == 0:
  103. try:
  104. qubes_group = grp.getgrnam('qubes')
  105. user = qubes_group.gr_mem[0]
  106. cmd_prefix = ['runuser', '-u', user, '--', 'env', 'DISPLAY=:0']
  107. except KeyError as e:
  108. vm.log.warning('Default user not found, not importing appmenus: ' +
  109. str(e))
  110. return
  111. else:
  112. cmd_prefix = []
  113. # TODO: change this to qrexec calls to GUI VM, when GUI VM will be
  114. # implemented
  115. try:
  116. subprocess.check_call(cmd_prefix + ['qvm-appmenus',
  117. '--set-default-whitelist={}'.format(os.path.join(source_dir,
  118. 'vm-whitelisted-appmenus.list')), vm.name])
  119. subprocess.check_call(cmd_prefix + ['qvm-appmenus',
  120. '--set-whitelist={}'.format(os.path.join(source_dir,
  121. 'whitelisted-appmenus.list')), vm.name])
  122. except subprocess.CalledProcessError as e:
  123. vm.log.warning('Failed to set default application list: %s', e)
  124. @asyncio.coroutine
  125. def call_postinstall_service(vm):
  126. '''Call qubes.PostInstall service
  127. And adjust related settings (netvm, features).
  128. '''
  129. # just created, so no need to save previous value - we know what it was
  130. vm.netvm = None
  131. # temporarily enable qrexec feature - so vm.start() will wait for it;
  132. # if start fails, rollback it
  133. vm.features['qrexec'] = True
  134. try:
  135. vm.start()
  136. except qubesadmin.exc.QubesException:
  137. del vm.features['qrexec']
  138. else:
  139. try:
  140. vm.run_service_for_stdio('qubes.PostInstall')
  141. except subprocess.CalledProcessError:
  142. vm.log.error('qubes.PostInstall service failed')
  143. vm.shutdown()
  144. if have_events:
  145. try:
  146. # pylint: disable=no-member
  147. yield from asyncio.wait_for(
  148. qubesadmin.events.utils.wait_for_domain_shutdown([vm]),
  149. qubesadmin.config.defaults['shutdown_timeout'])
  150. except asyncio.TimeoutError:
  151. vm.kill()
  152. else:
  153. timeout = qubesadmin.config.defaults['shutdown_timeout']
  154. while timeout >= 0:
  155. if vm.is_halted():
  156. break
  157. yield from asyncio.sleep(1)
  158. timeout -= 1
  159. if not vm.is_halted():
  160. vm.kill()
  161. finally:
  162. vm.netvm = qubesadmin.DEFAULT
  163. @asyncio.coroutine
  164. def post_install(args):
  165. '''Handle post-installation tasks'''
  166. app = args.app
  167. try:
  168. # reinstall
  169. vm = app.domains[args.name]
  170. except KeyError:
  171. if app.qubesd_connection_type == 'socket' and \
  172. args.dir == '/var/lib/qubes/vm-templates/' + args.name:
  173. # vm.create_on_disk() need to create the directory on its own,
  174. # move it away for from its way
  175. tmp_sourcedir = os.path.join('/var/lib/qubes/vm-templates',
  176. 'tmp-' + args.name)
  177. shutil.move(args.dir, tmp_sourcedir)
  178. args.dir = tmp_sourcedir
  179. vm = app.add_new_vm('TemplateVM',
  180. name=args.name,
  181. label=qubesadmin.config.defaults['template_label'])
  182. vm.log.info('Importing data')
  183. try:
  184. import_root_img(vm, args.dir)
  185. except:
  186. # if data import fails, remove half-created VM
  187. del app.domains[vm.name]
  188. raise
  189. import_appmenus(vm, args.dir)
  190. if not args.skip_start:
  191. yield from call_postinstall_service(vm)
  192. if not args.keep_source:
  193. shutil.rmtree(args.dir)
  194. return 0
  195. def pre_remove(args):
  196. '''Handle pre-removal tasks'''
  197. app = args.app
  198. try:
  199. tpl = app.domains[args.name]
  200. except KeyError:
  201. parser.error('Qube with this name do not exist')
  202. for appvm in tpl.appvms:
  203. parser.error('Qube {} use this template'.format(appvm.name))
  204. del app.domains[args.name]
  205. return 0
  206. def is_chroot():
  207. '''Detect if running inside chroot'''
  208. try:
  209. stat_root = os.stat('/')
  210. stat_init_root = os.stat('/proc/1/root/.')
  211. return (
  212. stat_root.st_dev != stat_init_root.st_dev or
  213. stat_root.st_ino != stat_init_root.st_ino)
  214. except IOError:
  215. print('Stat failed, assuming not chroot', file=sys.stderr)
  216. return False
  217. def main(args=None, app=None):
  218. '''Main function of qvm-template-postprocess'''
  219. args = parser.parse_args(args, app=app)
  220. if is_chroot():
  221. print('Running in chroot, ignoring request. Import template with:',
  222. file=sys.stderr)
  223. print(' '.join(sys.argv), file=sys.stderr)
  224. return
  225. if not args.really:
  226. parser.error('Do not call this tool directly.')
  227. if args.action == 'post-install':
  228. loop = asyncio.get_event_loop()
  229. try:
  230. loop.run_until_complete(post_install(args))
  231. loop.stop()
  232. loop.run_forever()
  233. finally:
  234. loop.close()
  235. elif args.action == 'pre-remove':
  236. pre_remove(args)
  237. else:
  238. parser.error('Unknown action')
  239. return 0
  240. if __name__ == '__main__':
  241. sys.exit(main())