01QubesHVm.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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 stat
  29. import sys
  30. import re
  31. import stat
  32. from qubes.qubes import QubesVm,register_qubes_vm_class,vmm,dry_run
  33. from qubes.qubes import system_path,defaults
  34. from qubes.qubes import QubesException
  35. system_path["config_template_hvm"] = '/usr/share/qubes/vm-template-hvm.xml'
  36. defaults["hvm_disk_size"] = 20*1024*1024*1024
  37. defaults["hvm_private_img_size"] = 2*1024*1024*1024
  38. defaults["hvm_memory"] = 512
  39. class QubesHVm(QubesVm):
  40. """
  41. A class that represents an HVM. A child of QubesVm.
  42. """
  43. # FIXME: logically should inherit after QubesAppVm, but none of its methods
  44. # are useful for HVM
  45. def get_attrs_config(self):
  46. attrs = super(QubesHVm, self).get_attrs_config()
  47. attrs.pop('kernel')
  48. attrs.pop('kernels_dir')
  49. attrs.pop('kernelopts')
  50. attrs.pop('uses_default_kernel')
  51. attrs.pop('uses_default_kernelopts')
  52. attrs['dir_path']['func'] = lambda value: value if value is not None \
  53. else os.path.join(system_path["qubes_appvms_dir"], self.name)
  54. attrs['config_file_template']['func'] = \
  55. lambda x: system_path["config_template_hvm"]
  56. attrs['drive'] = { 'attr': '_drive',
  57. 'save': lambda: str(self.drive) }
  58. # Remove this two lines when HVM will get qmemman support
  59. attrs['maxmem'].pop('save')
  60. attrs['maxmem']['func'] = lambda x: self.memory
  61. attrs['timezone'] = { 'default': 'localtime',
  62. 'save': lambda: str(self.timezone) }
  63. attrs['qrexec_installed'] = { 'default': False,
  64. 'attr': '_qrexec_installed',
  65. 'save': lambda: str(self._qrexec_installed) }
  66. attrs['guiagent_installed'] = { 'default' : False,
  67. 'attr': '_guiagent_installed',
  68. 'save': lambda: str(self._guiagent_installed) }
  69. attrs['seamless_gui_mode'] = { 'default': False,
  70. 'attr': '_seamless_gui_mode',
  71. 'save': lambda: str(self._seamless_gui_mode) }
  72. attrs['_start_guid_first']['func'] = lambda x: True
  73. attrs['services']['default'] = "{'meminfo-writer': False}"
  74. attrs['memory']['default'] = defaults["hvm_memory"]
  75. return attrs
  76. def __init__(self, **kwargs):
  77. super(QubesHVm, self).__init__(**kwargs)
  78. # Default for meminfo-writer have changed to (correct) False in the
  79. # same version as introduction of guiagent_installed, so for older VMs
  80. # with wrong setting, change is based on 'guiagent_installed' presence
  81. if "guiagent_installed" not in kwargs and \
  82. (not 'xml_element' in kwargs or kwargs['xml_element'].get('guiagent_installed') is None):
  83. self.services['meminfo-writer'] = False
  84. # Disable qemu GUID if the user installed qubes gui agent
  85. if self.guiagent_installed:
  86. self._start_guid_first = False
  87. @property
  88. def type(self):
  89. return "HVM"
  90. def is_appvm(self):
  91. return True
  92. @classmethod
  93. def is_template_compatible(cls, template):
  94. if template and (not template.is_template() or template.type != "TemplateHVM"):
  95. return False
  96. return True
  97. def get_clone_attrs(self):
  98. attrs = super(QubesHVm, self).get_clone_attrs()
  99. attrs.remove('kernel')
  100. attrs.remove('uses_default_kernel')
  101. attrs.remove('kernelopts')
  102. attrs.remove('uses_default_kernelopts')
  103. attrs += [ 'timezone' ]
  104. attrs += [ 'qrexec_installed' ]
  105. attrs += [ 'guiagent_installed' ]
  106. return attrs
  107. @property
  108. def qrexec_installed(self):
  109. return self._qrexec_installed or \
  110. bool(self.template and self.template.qrexec_installed)
  111. @qrexec_installed.setter
  112. def qrexec_installed(self, value):
  113. if self.template and self.template.qrexec_installed and not value:
  114. print >>sys.stderr, "WARNING: When qrexec_installed set in template, it will be propagated to the VM"
  115. self._qrexec_installed = value
  116. @property
  117. def guiagent_installed(self):
  118. return self._guiagent_installed or \
  119. bool(self.template and self.template.guiagent_installed)
  120. @guiagent_installed.setter
  121. def guiagent_installed(self, value):
  122. if self.template and self.template.guiagent_installed and not value:
  123. print >>sys.stderr, "WARNING: When guiagent_installed set in template, it will be propagated to the VM"
  124. self._guiagent_installed = value
  125. @property
  126. def seamless_gui_mode(self):
  127. if not self.guiagent_installed:
  128. return False
  129. return self._seamless_gui_mode
  130. @seamless_gui_mode.setter
  131. def seamless_gui_mode(self, value):
  132. if self._seamless_gui_mode == value:
  133. return
  134. if not self.guiagent_installed and value:
  135. raise ValueError("Seamless GUI mode requires GUI agent installed")
  136. self._seamless_gui_mode = value
  137. if self.is_running():
  138. self.send_gui_mode()
  139. @property
  140. def drive(self):
  141. return self._drive
  142. @drive.setter
  143. def drive(self, value):
  144. if value is None:
  145. self._drive = None
  146. return
  147. # strip type for a moment
  148. drv_type = "cdrom"
  149. if value.startswith("hd:") or value.startswith("cdrom:"):
  150. (drv_type, unused, value) = value.partition(":")
  151. drv_type = drv_type.lower()
  152. # sanity check
  153. if drv_type not in ['hd', 'cdrom']:
  154. raise QubesException("Unsupported drive type: %s" % type)
  155. if value.count(":") == 0:
  156. value = "dom0:" + value
  157. if value.count(":/") == 0:
  158. # FIXME: when Windows backend will be supported, improve this
  159. raise QubesException("Drive path must be absolute")
  160. self._drive = drv_type + ":" + value
  161. def create_on_disk(self, verbose, source_template = None):
  162. if dry_run:
  163. return
  164. if verbose:
  165. print >> sys.stderr, "--> Creating directory: {0}".format(self.dir_path)
  166. os.mkdir (self.dir_path)
  167. if verbose:
  168. print >> sys.stderr, "--> Creating icon symlink: {0} -> {1}".format(self.icon_path, self.label.icon_path)
  169. os.symlink (self.label.icon_path, self.icon_path)
  170. self.create_config_file()
  171. # create empty disk
  172. if self.template is None:
  173. if verbose:
  174. print >> sys.stderr, "--> Creating root image: {0}".\
  175. format(self.root_img)
  176. f_root = open(self.root_img, "w")
  177. f_root.truncate(defaults["hvm_disk_size"])
  178. f_root.close()
  179. if self.template is None:
  180. # create empty private.img
  181. if verbose:
  182. print >> sys.stderr, "--> Creating private image: {0}".\
  183. format(self.private_img)
  184. f_private = open(self.private_img, "w")
  185. f_private.truncate(defaults["hvm_private_img_size"])
  186. f_private.close()
  187. else:
  188. # copy template private.img
  189. template_priv = self.template.private_img
  190. if verbose:
  191. print >> sys.stderr, "--> Copying the template's private image: {0}".\
  192. format(template_priv)
  193. # We prefer to use Linux's cp, because it nicely handles sparse files
  194. retcode = subprocess.call (["cp", template_priv, self.private_img])
  195. if retcode != 0:
  196. raise IOError ("Error while copying {0} to {1}".\
  197. format(template_priv, self.private_img))
  198. # fire hooks
  199. for hook in self.hooks_create_on_disk:
  200. hook(self, verbose, source_template=source_template)
  201. def get_private_img_sz(self):
  202. if not os.path.exists(self.private_img):
  203. return 0
  204. return os.path.getsize(self.private_img)
  205. def resize_private_img(self, size):
  206. assert size >= self.get_private_img_sz(), "Cannot shrink private.img"
  207. if self.is_running():
  208. raise NotImplementedError("Online resize of HVM's private.img not implemented, shutdown the VM first")
  209. f_private = open (self.private_img, "a+b")
  210. f_private.truncate (size)
  211. f_private.close ()
  212. def resize_root_img(self, size):
  213. if self.template:
  214. raise QubesException("Cannot resize root.img of template-based VM"
  215. ". Resize the root.img of the template "
  216. "instead.")
  217. if self.is_running():
  218. raise QubesException("Cannot resize root.img of running HVM")
  219. if size < self.get_root_img_sz():
  220. raise QubesException(
  221. "For your own safety shringing of root.img is disabled. If "
  222. "you really know what you are doing, use 'truncate' manually.")
  223. f_root = open (self.root_img, "a+b")
  224. f_root.truncate (size)
  225. f_root.close ()
  226. def get_rootdev(self, source_template=None):
  227. if self.template:
  228. return "'script:snapshot:{template_root}:{volatile},xvda,w',".format(
  229. template_root=self.template.root_img,
  230. volatile=self.volatile_img)
  231. else:
  232. return "'script:file:{root_img},xvda,w',".format(root_img=self.root_img)
  233. def get_config_params(self, source_template=None):
  234. params = super(QubesHVm, self).get_config_params(source_template=source_template)
  235. params['volatiledev'] = ''
  236. if self.drive:
  237. (drive_type, drive_domain, drive_path) = self.drive.split(":")
  238. if drive_domain.lower() == "dom0":
  239. drive_domain = None
  240. params['otherdevs'] = self._format_disk_dev(drive_path, None, "xvdc",
  241. rw=True if type == "disk" else False, type=type,
  242. domain=backend_domain)
  243. else:
  244. params['otherdevs'] = ''
  245. if self.timezone.lower() == 'localtime':
  246. params['time_basis'] = 'localtime'
  247. params['timeoffset'] = '0'
  248. elif self.timezone.isdigit():
  249. params['time_basis'] = 'UTC'
  250. params['timeoffset'] = self.timezone
  251. else:
  252. print >>sys.stderr, "WARNING: invalid 'timezone' value: %s" % self.timezone
  253. params['time_basis'] = 'UTC'
  254. params['timeoffset'] = '0'
  255. return params
  256. def verify_files(self):
  257. if dry_run:
  258. return
  259. if not os.path.exists (self.dir_path):
  260. raise QubesException (
  261. "VM directory doesn't exist: {0}".\
  262. format(self.dir_path))
  263. if self.is_updateable() and not os.path.exists (self.root_img):
  264. raise QubesException (
  265. "VM root image file doesn't exist: {0}".\
  266. format(self.root_img))
  267. if not os.path.exists (self.private_img):
  268. print >>sys.stderr, "WARNING: Creating empty VM private image file: {0}".\
  269. format(self.private_img)
  270. f_private = open(self.private_img, "w")
  271. f_private.truncate(defaults["hvm_private_img_size"])
  272. f_private.close()
  273. # fire hooks
  274. for hook in self.hooks_verify_files:
  275. hook(self)
  276. return True
  277. def reset_volatile_storage(self, **kwargs):
  278. assert not self.is_running(), "Attempt to clean volatile image of running VM!"
  279. source_template = kwargs.get("source_template", self.template)
  280. if source_template is None:
  281. # Nothing to do on non-template based VM
  282. return
  283. if os.path.exists (self.volatile_img):
  284. if self.debug:
  285. if os.path.getmtime(self.template.root_img) > os.path.getmtime(self.volatile_img):
  286. if kwargs.get("verbose", False):
  287. print >>sys.stderr, "--> WARNING: template have changed, resetting root.img"
  288. else:
  289. if kwargs.get("verbose", False):
  290. print >>sys.stderr, "--> Debug mode: not resetting root.img"
  291. print >>sys.stderr, "--> Debug mode: if you want to force root.img reset, either update template VM, or remove volatile.img file"
  292. return
  293. os.remove (self.volatile_img)
  294. f_volatile = open (self.volatile_img, "w")
  295. f_root = open (self.template.root_img, "r")
  296. f_root.seek(0, os.SEEK_END)
  297. f_volatile.truncate (f_root.tell()) # make empty sparse file of the same size as root.img
  298. f_volatile.close ()
  299. f_root.close()
  300. @property
  301. def vif(self):
  302. if self.xid < 0:
  303. return None
  304. if self.netvm is None:
  305. return None
  306. return "vif{0}.+".format(self.stubdom_xid)
  307. @property
  308. def mac(self):
  309. if self._mac is not None:
  310. return self._mac
  311. elif self.template is not None:
  312. return self.template.mac
  313. else:
  314. return "00:16:3E:5E:6C:{qid:02X}".format(qid=self.qid)
  315. @mac.setter
  316. def mac(self, value):
  317. self._mac = value
  318. def run(self, command, **kwargs):
  319. if self.qrexec_installed:
  320. if 'gui' in kwargs and kwargs['gui']==False:
  321. command = "nogui:" + command
  322. return super(QubesHVm, self).run(command, **kwargs)
  323. else:
  324. raise QubesException("Needs qrexec agent installed in VM to use this function. See also qvm-prefs.")
  325. @property
  326. def stubdom_xid(self):
  327. if self.xid < 0:
  328. return -1
  329. stubdom_xid_str = vmm.xs.read('', '/local/domain/%d/image/device-model-domid' % self.xid)
  330. if stubdom_xid_str is not None:
  331. return int(stubdom_xid_str)
  332. else:
  333. return -1
  334. def start(self, *args, **kwargs):
  335. if self.template and self.template.is_running():
  336. raise QubesException("Cannot start the HVM while its template is running")
  337. try:
  338. if 'mem_required' not in kwargs:
  339. # Reserve 32MB for stubdomain
  340. kwargs['mem_required'] = (self.memory + 32) * 1024 * 1024
  341. return super(QubesHVm, self).start(*args, **kwargs)
  342. except QubesException as e:
  343. if xc.physinfo()['virt_caps'].count('hvm') == 0:
  344. raise QubesException("Cannot start HVM without VT-x/AMD-v enabled")
  345. else:
  346. raise
  347. def start_stubdom_guid(self):
  348. cmdline = [system_path["qubes_guid_path"],
  349. "-d", str(self.stubdom_xid),
  350. "-t", str(self.xid),
  351. "-N", self.name,
  352. "-c", self.label.color,
  353. "-i", self.label.icon_path,
  354. "-l", str(self.label.index)]
  355. retcode = subprocess.call (cmdline)
  356. if (retcode != 0) :
  357. raise QubesException("Cannot start qubes-guid!")
  358. def start_guid(self, verbose = True, notify_function = None,
  359. before_qrexec=False, **kwargs):
  360. # If user force the guiagent, start_guid will mimic a standard QubesVM
  361. if not before_qrexec and self.guiagent_installed:
  362. super(QubesHVm, self).start_guid(verbose, notify_function, extra_guid_args=["-Q"], **kwargs)
  363. stubdom_guid_pidfile = '/var/run/qubes/guid-running.%d' % self.stubdom_xid
  364. if os.path.exists(stubdom_guid_pidfile) and not self.debug:
  365. try:
  366. stubdom_guid_pid = int(open(stubdom_guid_pidfile, 'r').read())
  367. os.kill(stubdom_guid_pid, signal.SIGTERM)
  368. except Exception as ex:
  369. print >> sys.stderr, "WARNING: Failed to kill stubdom gui daemon: %s" % str(ex)
  370. elif before_qrexec and (not self.guiagent_installed or self.debug):
  371. if verbose:
  372. print >> sys.stderr, "--> Starting Qubes GUId (full screen)..."
  373. self.start_stubdom_guid()
  374. def start_qrexec_daemon(self, **kwargs):
  375. if not self.qrexec_installed:
  376. if kwargs.get('verbose', False):
  377. print >> sys.stderr, "--> Starting the qrexec daemon..."
  378. xid = self.get_xid()
  379. qrexec_env = os.environ.copy()
  380. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  381. retcode = subprocess.call ([system_path["qrexec_daemon_path"], str(xid), self.name, self.default_user], env=qrexec_env)
  382. if (retcode != 0) :
  383. self.force_shutdown(xid=xid)
  384. raise OSError ("ERROR: Cannot execute qrexec-daemon!")
  385. else:
  386. super(QubesHVm, self).start_qrexec_daemon(**kwargs)
  387. if self._start_guid_first:
  388. if kwargs.get('verbose'):
  389. print >> sys.stderr, "--> Waiting for user '%s' login..." % self.default_user
  390. self.wait_for_session(notify_function=kwargs.get('notify_function', None))
  391. self.send_gui_mode()
  392. def send_gui_mode(self):
  393. if self.seamless_gui_mode:
  394. service_input = "SEAMLESS"
  395. else:
  396. service_input = "FULLSCREEN"
  397. self.run_service("qubes.SetGuiMode", input=service_input)
  398. def create_xenstore_entries(self, xid = None):
  399. if dry_run:
  400. return
  401. super(QubesHVm, self).create_xenstore_entries(xid)
  402. if xid is None:
  403. xid = self.xid
  404. domain_path = xs.get_domain_path(xid)
  405. # Prepare xenstore directory for tools advertise
  406. xs.write('',
  407. "{0}/qubes-tools".format(domain_path),
  408. '')
  409. # Allow VM writes there
  410. xs.set_permissions('', '{0}/qubes-tools'.format(domain_path),
  411. [{ 'dom': xid }])
  412. def _cleanup_zombie_domains(self):
  413. super(QubesHVm, self)._cleanup_zombie_domains()
  414. if not self.is_running():
  415. xc_stubdom = self.get_xc_dominfo(name=self.name+'-dm')
  416. if xc_stubdom is not None:
  417. if xc_stubdom['paused'] == 1:
  418. subprocess.call(['xl', 'destroy', str(xc_stubdom['domid'])])
  419. if xc_stubdom['dying'] == 1:
  420. # GUID still running?
  421. guid_pidfile = \
  422. '/var/run/qubes/guid-running.%d' % xc_stubdom['domid']
  423. if os.path.exists(guid_pidfile):
  424. guid_pid = open(guid_pidfile).read().strip()
  425. os.kill(int(guid_pid), 15)
  426. def suspend(self):
  427. if dry_run:
  428. return
  429. if not self.is_running() and not self.is_paused():
  430. raise QubesException ("VM not running!")
  431. self.pause()
  432. def is_guid_running(self):
  433. # If user force the guiagent, is_guid_running will mimic a standard QubesVM
  434. if self.guiagent_installed:
  435. return super(QubesHVm, self).is_guid_running()
  436. else:
  437. xid = self.stubdom_xid
  438. if xid < 0:
  439. return False
  440. if not os.path.exists('/var/run/qubes/guid-running.%d' % xid):
  441. return False
  442. return True
  443. def is_fully_usable(self):
  444. # Running gui-daemon implies also VM running
  445. if not self.is_guid_running():
  446. return False
  447. if self.qrexec_installed and not self.is_qrexec_running():
  448. return False
  449. return True
  450. register_qubes_vm_class(QubesHVm)