01QubesHVm.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #!/usr/bin/python2
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2013 Marek Marczykowski <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU General Public License
  11. # as published by the Free Software Foundation; either version 2
  12. # of the License, or (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 General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  22. #
  23. #
  24. import os
  25. import os.path
  26. import signal
  27. import subprocess
  28. import sys
  29. import shutil
  30. from xml.etree import ElementTree
  31. from qubes.qubes import (
  32. dry_run,
  33. defaults,
  34. register_qubes_vm_class,
  35. system_path,
  36. vmm,
  37. QubesException,
  38. QubesResizableVm,
  39. )
  40. system_path["config_template_hvm"] = '/usr/share/qubes/vm-template-hvm.xml'
  41. defaults["hvm_disk_size"] = 20*1024*1024*1024
  42. defaults["hvm_private_img_size"] = 2*1024*1024*1024
  43. defaults["hvm_memory"] = 512
  44. class QubesHVm(QubesResizableVm):
  45. """
  46. A class that represents an HVM. A child of QubesVm.
  47. """
  48. # FIXME: logically should inherit after QubesAppVm, but none of its methods
  49. # are useful for HVM
  50. def get_attrs_config(self):
  51. attrs = super(QubesHVm, self).get_attrs_config()
  52. attrs.pop('kernel')
  53. attrs.pop('kernels_dir')
  54. attrs.pop('kernelopts')
  55. attrs.pop('uses_default_kernel')
  56. attrs.pop('uses_default_kernelopts')
  57. attrs['dir_path']['func'] = lambda value: value if value is not None \
  58. else os.path.join(system_path["qubes_appvms_dir"], self.name)
  59. attrs['config_file_template']['func'] = \
  60. lambda x: system_path["config_template_hvm"]
  61. attrs['drive'] = { 'attr': '_drive',
  62. 'save': lambda: str(self.drive) }
  63. # Remove this two lines when HVM will get qmemman support
  64. attrs['maxmem'].pop('save')
  65. attrs['maxmem']['func'] = lambda x: self.memory
  66. attrs['timezone'] = { 'default': 'localtime',
  67. 'save': lambda: str(self.timezone) }
  68. attrs['qrexec_installed'] = { 'default': False,
  69. 'attr': '_qrexec_installed',
  70. 'save': lambda: str(self._qrexec_installed) }
  71. attrs['guiagent_installed'] = { 'default' : False,
  72. 'attr': '_guiagent_installed',
  73. 'save': lambda: str(self._guiagent_installed) }
  74. attrs['seamless_gui_mode'] = { 'default': False,
  75. 'attr': '_seamless_gui_mode',
  76. 'save': lambda: str(self._seamless_gui_mode) }
  77. attrs['services']['default'] = "{'meminfo-writer': False}"
  78. attrs['memory']['default'] = defaults["hvm_memory"]
  79. return attrs
  80. def __init__(self, **kwargs):
  81. super(QubesHVm, self).__init__(**kwargs)
  82. # Default for meminfo-writer have changed to (correct) False in the
  83. # same version as introduction of guiagent_installed, so for older VMs
  84. # with wrong setting, change is based on 'guiagent_installed' presence
  85. if "guiagent_installed" not in kwargs and \
  86. (not 'xml_element' in kwargs or kwargs['xml_element'].get('guiagent_installed') is None):
  87. self.services['meminfo-writer'] = False
  88. self.storage.rootcow_img = None
  89. @property
  90. def type(self):
  91. return "HVM"
  92. def is_appvm(self):
  93. return True
  94. @classmethod
  95. def is_template_compatible(cls, template):
  96. if template and (not template.is_template() or template.type != "TemplateHVM"):
  97. return False
  98. return True
  99. def get_clone_attrs(self):
  100. attrs = super(QubesHVm, self).get_clone_attrs()
  101. attrs.remove('kernel')
  102. attrs.remove('uses_default_kernel')
  103. attrs.remove('kernelopts')
  104. attrs.remove('uses_default_kernelopts')
  105. attrs += [ 'timezone' ]
  106. attrs += [ 'qrexec_installed' ]
  107. attrs += [ 'guiagent_installed' ]
  108. return attrs
  109. @property
  110. def qrexec_installed(self):
  111. return self._qrexec_installed or \
  112. bool(self.template and self.template.qrexec_installed)
  113. @qrexec_installed.setter
  114. def qrexec_installed(self, value):
  115. if self.template and self.template.qrexec_installed and not value:
  116. print >>sys.stderr, "WARNING: When qrexec_installed set in template, it will be propagated to the VM"
  117. self._qrexec_installed = value
  118. @property
  119. def guiagent_installed(self):
  120. return self._guiagent_installed or \
  121. bool(self.template and self.template.guiagent_installed)
  122. @guiagent_installed.setter
  123. def guiagent_installed(self, value):
  124. if self.template and self.template.guiagent_installed and not value:
  125. print >>sys.stderr, "WARNING: When guiagent_installed set in template, it will be propagated to the VM"
  126. self._guiagent_installed = value
  127. @property
  128. def seamless_gui_mode(self):
  129. if not self.guiagent_installed:
  130. return False
  131. return self._seamless_gui_mode
  132. @seamless_gui_mode.setter
  133. def seamless_gui_mode(self, value):
  134. if self._seamless_gui_mode == value:
  135. return
  136. if not self.guiagent_installed and value:
  137. raise ValueError("Seamless GUI mode requires GUI agent installed")
  138. self._seamless_gui_mode = value
  139. if self.is_running():
  140. self.send_gui_mode()
  141. @property
  142. def drive(self):
  143. return self._drive
  144. @drive.setter
  145. def drive(self, value):
  146. if value is None:
  147. self._drive = None
  148. return
  149. # strip type for a moment
  150. drv_type = "cdrom"
  151. if value.startswith("hd:") or value.startswith("cdrom:"):
  152. (drv_type, unused, value) = value.partition(":")
  153. drv_type = drv_type.lower()
  154. # sanity check
  155. if drv_type not in ['hd', 'cdrom']:
  156. raise QubesException("Unsupported drive type: %s" % type)
  157. if value.count(":") == 0:
  158. value = "dom0:" + value
  159. if value.count(":/") == 0:
  160. # FIXME: when Windows backend will be supported, improve this
  161. raise QubesException("Drive path must be absolute")
  162. self._drive = drv_type + ":" + value
  163. def create_on_disk(self, verbose, source_template = None):
  164. self.log.debug('create_on_disk(source_template={!r})'.format(
  165. source_template))
  166. if dry_run:
  167. return
  168. if source_template is None:
  169. source_template = self.template
  170. # create empty disk
  171. self.storage.private_img_size = defaults["hvm_private_img_size"]
  172. self.storage.root_img_size = defaults["hvm_disk_size"]
  173. self.storage.create_on_disk(verbose, source_template)
  174. if verbose:
  175. print >> sys.stderr, "--> Creating icon symlink: {0} -> {1}".format(self.icon_path, self.label.icon_path)
  176. try:
  177. if hasattr(os, "symlink"):
  178. os.symlink (self.label.icon_path, self.icon_path)
  179. else:
  180. shutil.copy(self.label.icon_path, self.icon_path)
  181. except Exception as e:
  182. print >> sys.stderr, "WARNING: Failed to set VM icon: %s" % str(e)
  183. # Make sure that we have UUID allocated
  184. self._update_libvirt_domain()
  185. # fire hooks
  186. for hook in self.hooks_create_on_disk:
  187. hook(self, verbose, source_template=source_template)
  188. def get_private_img_sz(self):
  189. if not os.path.exists(self.private_img):
  190. return 0
  191. return os.path.getsize(self.private_img)
  192. def resize_private_img(self, size):
  193. assert size >= self.get_private_img_sz(), "Cannot shrink private.img"
  194. if self.is_running():
  195. raise NotImplementedError("Online resize of HVM's private.img not implemented, shutdown the VM first")
  196. self.storage.resize_private_img(size)
  197. def get_config_params(self):
  198. params = super(QubesHVm, self).get_config_params()
  199. self.storage.drive = self.drive
  200. params.update(self.storage.get_config_params())
  201. params['volatiledev'] = ''
  202. if self.timezone.lower() == 'localtime':
  203. params['time_basis'] = 'localtime'
  204. params['timeoffset'] = '0'
  205. elif self.timezone.isdigit():
  206. params['time_basis'] = 'UTC'
  207. params['timeoffset'] = self.timezone
  208. else:
  209. print >>sys.stderr, "WARNING: invalid 'timezone' value: %s" % self.timezone
  210. params['time_basis'] = 'UTC'
  211. params['timeoffset'] = '0'
  212. return params
  213. def verify_files(self):
  214. if dry_run:
  215. return
  216. self.storage.verify_files()
  217. # fire hooks
  218. for hook in self.hooks_verify_files:
  219. hook(self)
  220. return True
  221. @property
  222. def vif(self):
  223. if self.xid < 0:
  224. return None
  225. if self.netvm is None:
  226. return None
  227. return "vif{0}.+".format(self.stubdom_xid)
  228. @property
  229. def mac(self):
  230. if self._mac is not None:
  231. return self._mac
  232. elif self.template is not None:
  233. return self.template.mac
  234. else:
  235. return "00:16:3E:5E:6C:{qid:02X}".format(qid=self.qid)
  236. @mac.setter
  237. def mac(self, value):
  238. self._mac = value
  239. def run(self, command, **kwargs):
  240. if self.qrexec_installed:
  241. if 'gui' in kwargs and kwargs['gui']==False:
  242. command = "nogui:" + command
  243. return super(QubesHVm, self).run(command, **kwargs)
  244. else:
  245. raise QubesException("Needs qrexec agent installed in VM to use this function. See also qvm-prefs.")
  246. @property
  247. def stubdom_xid(self):
  248. if self.xid < 0:
  249. return -1
  250. if vmm.xs is None:
  251. return -1
  252. stubdom_xid_str = vmm.xs.read('', '/local/domain/%d/image/device-model-domid' % self.xid)
  253. if stubdom_xid_str is not None:
  254. return int(stubdom_xid_str)
  255. else:
  256. return -1
  257. def start(self, *args, **kwargs):
  258. # make it available to storage.prepare_for_vm_startup, which is
  259. # called before actually building VM libvirt configuration
  260. self.storage.drive = self.drive
  261. if self.template and self.template.is_running():
  262. raise QubesException("Cannot start the HVM while its template is running")
  263. try:
  264. if 'mem_required' not in kwargs:
  265. # Reserve 44MB for stubdomain
  266. kwargs['mem_required'] = (self.memory + 44) * 1024 * 1024
  267. return super(QubesHVm, self).start(*args, **kwargs)
  268. except QubesException as e:
  269. capabilities = vmm.libvirt_conn.getCapabilities()
  270. tree = ElementTree.fromstring(capabilities)
  271. os_types = tree.findall('./guest/os_type')
  272. if 'hvm' not in map(lambda x: x.text, os_types):
  273. raise QubesException("Cannot start HVM without VT-x/AMD-v enabled")
  274. else:
  275. raise
  276. def start_stubdom_guid(self, verbose=True):
  277. guid_cmd = [system_path["qubes_guid_path"],
  278. "-d", str(self.stubdom_xid),
  279. "-t", str(self.xid),
  280. "-N", self.name,
  281. "-c", self.label.color,
  282. "-i", self.label.icon_path,
  283. "-l", str(self.label.index)]
  284. if self.debug:
  285. guid_cmd += ['-v', '-v']
  286. elif not verbose:
  287. guid_cmd += ['-q']
  288. retcode = subprocess.call (guid_cmd)
  289. if (retcode != 0) :
  290. raise QubesException("Cannot start qubes-guid!")
  291. def start_guid(self, verbose=True, notify_function=None,
  292. before_qrexec=False, **kwargs):
  293. if not before_qrexec:
  294. return
  295. if not self.guiagent_installed or self.debug:
  296. if verbose:
  297. print >> sys.stderr, "--> Starting Qubes GUId (full screen)..."
  298. self.start_stubdom_guid(verbose=verbose)
  299. kwargs['extra_guid_args'] = kwargs.get('extra_guid_args', []) + \
  300. ['-Q', '-n']
  301. stubdom_guid_pidfile = \
  302. '/var/run/qubes/guid-running.%d' % self.stubdom_xid
  303. if not self.debug and os.path.exists(stubdom_guid_pidfile):
  304. # Terminate stubdom guid once "real" gui agent connects
  305. stubdom_guid_pid = int(open(stubdom_guid_pidfile, 'r').read())
  306. kwargs['extra_guid_args'] += ['-K', str(stubdom_guid_pid)]
  307. super(QubesHVm, self).start_guid(verbose, notify_function, **kwargs)
  308. def start_qrexec_daemon(self, **kwargs):
  309. if not self.qrexec_installed:
  310. if kwargs.get('verbose', False):
  311. print >> sys.stderr, "--> Starting the qrexec daemon..."
  312. xid = self.get_xid()
  313. qrexec_env = os.environ.copy()
  314. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  315. retcode = subprocess.call ([system_path["qrexec_daemon_path"], str(xid), self.name, self.default_user], env=qrexec_env)
  316. if (retcode != 0) :
  317. self.force_shutdown(xid=xid)
  318. raise OSError ("ERROR: Cannot execute qrexec-daemon!")
  319. else:
  320. super(QubesHVm, self).start_qrexec_daemon(**kwargs)
  321. if self.guiagent_installed:
  322. if kwargs.get('verbose'):
  323. print >> sys.stderr, "--> Waiting for user '%s' login..." % self.default_user
  324. self.wait_for_session(notify_function=kwargs.get('notify_function', None))
  325. self.send_gui_mode()
  326. def send_gui_mode(self):
  327. if self.seamless_gui_mode:
  328. service_input = "SEAMLESS"
  329. else:
  330. service_input = "FULLSCREEN"
  331. self.run_service("qubes.SetGuiMode", input=service_input)
  332. def _cleanup_zombie_domains(self):
  333. super(QubesHVm, self)._cleanup_zombie_domains()
  334. if not self.is_running():
  335. xc_stubdom = self.get_xc_dominfo(name=self.name+'-dm')
  336. if xc_stubdom is not None:
  337. if xc_stubdom['paused'] == 1:
  338. subprocess.call(['xl', 'destroy', str(xc_stubdom['domid'])])
  339. if xc_stubdom['dying'] == 1:
  340. # GUID still running?
  341. guid_pidfile = \
  342. '/var/run/qubes/guid-running.%d' % xc_stubdom['domid']
  343. if os.path.exists(guid_pidfile):
  344. guid_pid = open(guid_pidfile).read().strip()
  345. os.kill(int(guid_pid), 15)
  346. def suspend(self):
  347. if dry_run:
  348. return
  349. if not self.is_running() and not self.is_paused():
  350. raise QubesException ("VM not running!")
  351. self.pause()
  352. def is_guid_running(self):
  353. # If user force the guiagent, is_guid_running will mimic a standard QubesVM
  354. if self.guiagent_installed:
  355. return super(QubesHVm, self).is_guid_running()
  356. else:
  357. xid = self.stubdom_xid
  358. if xid < 0:
  359. return False
  360. if not os.path.exists('/var/run/qubes/guid-running.%d' % xid):
  361. return False
  362. return True
  363. def is_fully_usable(self):
  364. # Running gui-daemon implies also VM running
  365. if not self.is_guid_running():
  366. return False
  367. if self.qrexec_installed and not self.is_qrexec_running():
  368. return False
  369. return True
  370. register_qubes_vm_class(QubesHVm)