01QubesHVm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. #!/usr/bin/python2
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2013 Marek Marczykowski <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. #
  23. import os
  24. import os.path
  25. import subprocess
  26. import sys
  27. import re
  28. from qubes.qubes import QubesVm,register_qubes_vm_class,xs,xc,dry_run
  29. from qubes.qubes import QubesException
  30. from qubes.qubes import system_path,defaults
  31. system_path["config_template_hvm"] = '/usr/share/qubes/vm-template-hvm.conf'
  32. defaults["hvm_disk_size"] = 20*1024*1024*1024
  33. defaults["hvm_private_img_size"] = 2*1024*1024*1024
  34. defaults["hvm_memory"] = 512
  35. class QubesHVm(QubesVm):
  36. """
  37. A class that represents an HVM. A child of QubesVm.
  38. """
  39. # FIXME: logically should inherit after QubesAppVm, but none of its methods
  40. # are useful for HVM
  41. def get_attrs_config(self):
  42. attrs = super(QubesHVm, self).get_attrs_config()
  43. attrs.pop('kernel')
  44. attrs.pop('kernels_dir')
  45. attrs.pop('kernelopts')
  46. attrs.pop('uses_default_kernel')
  47. attrs.pop('uses_default_kernelopts')
  48. attrs['dir_path']['eval'] = 'value if value is not None else os.path.join(system_path["qubes_appvms_dir"], self.name)'
  49. attrs['volatile_img']['eval'] = 'None'
  50. attrs['config_file_template']['eval'] = 'system_path["config_template_hvm"]'
  51. attrs['drive'] = { 'save': 'str(self.drive)' }
  52. attrs['maxmem'].pop('save')
  53. attrs['timezone'] = { 'default': 'localtime', 'save': 'str(self.timezone)' }
  54. attrs['qrexec_installed'] = { 'default': False, 'save': 'str(self.qrexec_installed)' }
  55. attrs['guiagent_installed'] = { 'default' : False, 'save': 'str(self.guiagent_installed)' }
  56. attrs['_start_guid_first']['eval'] = 'True'
  57. attrs['services']['default'] = "{'meminfo-writer': False}"
  58. # only standalone HVM supported for now
  59. attrs['template']['eval'] = 'None'
  60. attrs['memory']['default'] = defaults["hvm_memory"]
  61. return attrs
  62. def __init__(self, **kwargs):
  63. super(QubesHVm, self).__init__(**kwargs)
  64. # Default for meminfo-writer have changed to (correct) False in the
  65. # same version as introduction of guiagent_installed, so for older VMs
  66. # with wrong setting, change is based on 'guiagent_installed' presence
  67. if "guiagent_installed" not in kwargs and \
  68. (not 'xml_element' in kwargs or kwargs['xml_element'].get('guiagent_installed') is None):
  69. self.services['meminfo-writer'] = False
  70. # HVM normally doesn't support dynamic memory management
  71. if not ('meminfo-writer' in self.services and self.services['meminfo-writer']):
  72. self.maxmem = self.memory
  73. # Disable qemu GUID if the user installed qubes gui agent
  74. if self.guiagent_installed:
  75. self._start_guid_first = False
  76. @property
  77. def type(self):
  78. return "HVM"
  79. def is_appvm(self):
  80. return True
  81. def get_clone_attrs(self):
  82. attrs = super(QubesHVm, self).get_clone_attrs()
  83. attrs.remove('kernel')
  84. attrs.remove('uses_default_kernel')
  85. attrs.remove('kernelopts')
  86. attrs.remove('uses_default_kernelopts')
  87. attrs += [ 'timezone' ]
  88. attrs += [ 'qrexec_installed' ]
  89. attrs += [ 'guiagent_installed' ]
  90. return attrs
  91. def create_on_disk(self, verbose, source_template = None):
  92. if dry_run:
  93. return
  94. if verbose:
  95. print >> sys.stderr, "--> Creating directory: {0}".format(self.dir_path)
  96. os.mkdir (self.dir_path)
  97. if verbose:
  98. print >> sys.stderr, "--> Creating icon symlink: {0} -> {1}".format(self.icon_path, self.label.icon_path)
  99. os.symlink (self.label.icon_path, self.icon_path)
  100. self.create_config_file()
  101. # create empty disk
  102. f_root = open(self.root_img, "w")
  103. f_root.truncate(defaults["hvm_disk_size"])
  104. f_root.close()
  105. # create empty private.img
  106. f_private = open(self.private_img, "w")
  107. f_private.truncate(defaults["hvm_private_img_size"])
  108. f_root.close()
  109. # fire hooks
  110. for hook in self.hooks_create_on_disk:
  111. hook(self, verbose, source_template=source_template)
  112. def get_disk_utilization_private_img(self):
  113. return 0
  114. def get_private_img_sz(self):
  115. return 0
  116. def resize_private_img(self, size):
  117. raise NotImplementedError("HVM has no private.img")
  118. def get_config_params(self, source_template=None):
  119. params = super(QubesHVm, self).get_config_params(source_template=source_template)
  120. params['volatiledev'] = ''
  121. if self.drive:
  122. type_mode = ":cdrom,r"
  123. drive_path = self.drive
  124. # leave empty to use standard syntax in case of dom0
  125. backend_domain = ""
  126. if drive_path.startswith("hd:"):
  127. type_mode = ",w"
  128. drive_path = drive_path[3:]
  129. elif drive_path.startswith("cdrom:"):
  130. type_mode = ":cdrom,r"
  131. drive_path = drive_path[6:]
  132. backend_split = re.match(r"^([a-zA-Z0-9-]*):(.*)", drive_path)
  133. if backend_split:
  134. backend_domain = "," + backend_split.group(1)
  135. drive_path = backend_split.group(2)
  136. # FIXME: os.stat will work only when backend in dom0...
  137. stat_res = None
  138. if backend_domain == "":
  139. stat_res = os.stat(drive_path)
  140. if stat_res and stat.S_ISBLK(stat_res.st_mode):
  141. params['otherdevs'] = "'phy:%s,xvdc%s%s'," % (drive_path, type_mode, backend_domain)
  142. else:
  143. params['otherdevs'] = "'script:file:%s,xvdc%s%s'," % (drive_path, type_mode, backend_domain)
  144. else:
  145. params['otherdevs'] = ''
  146. # Disable currently unused private.img - to be enabled when TemplateHVm done
  147. params['privatedev'] = ''
  148. if self.timezone.lower() == 'localtime':
  149. params['localtime'] = '1'
  150. params['timeoffset'] = '0'
  151. elif self.timezone.isdigit():
  152. params['localtime'] = '0'
  153. params['timeoffset'] = self.timezone
  154. else:
  155. print >>sys.stderr, "WARNING: invalid 'timezone' value: %s" % self.timezone
  156. params['localtime'] = '0'
  157. params['timeoffset'] = '0'
  158. return params
  159. def verify_files(self):
  160. if dry_run:
  161. return
  162. if not os.path.exists (self.dir_path):
  163. raise QubesException (
  164. "VM directory doesn't exist: {0}".\
  165. format(self.dir_path))
  166. if self.is_updateable() and not os.path.exists (self.root_img):
  167. raise QubesException (
  168. "VM root image file doesn't exist: {0}".\
  169. format(self.root_img))
  170. if not os.path.exists (self.private_img):
  171. print >>sys.stderr, "WARNING: Creating empty VM private image file: {0}".\
  172. format(self.private_img)
  173. f_private = open(self.private_img, "w")
  174. f_private.truncate(defaults["hvm_private_img_size"])
  175. f_private.close()
  176. # fire hooks
  177. for hook in self.hooks_verify_files:
  178. hook(self)
  179. return True
  180. def reset_volatile_storage(self, **kwargs):
  181. pass
  182. @property
  183. def vif(self):
  184. if self.xid < 0:
  185. return None
  186. if self.netvm is None:
  187. return None
  188. return "vif{0}.+".format(self.stubdom_xid)
  189. def run(self, command, **kwargs):
  190. if self.qrexec_installed:
  191. if 'gui' in kwargs and kwargs['gui']==False:
  192. command = "nogui:" + command
  193. return super(QubesHVm, self).run(command, **kwargs)
  194. else:
  195. raise QubesException("Needs qrexec agent installed in VM to use this function. See also qvm-prefs.")
  196. @property
  197. def stubdom_xid(self):
  198. if self.xid < 0:
  199. return -1
  200. stubdom_xid_str = xs.read('', '/local/domain/%d/image/device-model-domid' % self.xid)
  201. if stubdom_xid_str is not None:
  202. return int(stubdom_xid_str)
  203. else:
  204. return -1
  205. def start_guid(self, verbose = True, notify_function = None):
  206. # If user force the guiagent, start_guid will mimic a standard QubesVM
  207. if self.guiagent_installed:
  208. super(QubesHVm, self).start_guid(verbose, notify_function)
  209. else:
  210. if verbose:
  211. print >> sys.stderr, "--> Starting Qubes GUId..."
  212. retcode = subprocess.call ([system_path["qubes_guid_path"], "-d", str(self.stubdom_xid), "-c", self.label.color, "-i", self.label.icon_path, "-l", str(self.label.index)])
  213. if (retcode != 0) :
  214. raise QubesException("Cannot start qubes-guid!")
  215. def start_qrexec_daemon(self, **kwargs):
  216. if not self.qrexec_installed:
  217. if kwargs.get('verbose', False):
  218. print >> sys.stderr, "--> Starting the qrexec daemon..."
  219. xid = self.get_xid()
  220. qrexec_env = os.environ
  221. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  222. retcode = subprocess.call ([system_path["qrexec_daemon_path"], str(xid), self.name, self.default_user], env=qrexec_env)
  223. if (retcode != 0) :
  224. self.force_shutdown(xid=xid)
  225. raise OSError ("ERROR: Cannot execute qrexec-daemon!")
  226. else:
  227. super(QubesHVm, self).start_qrexec_daemon(**kwargs)
  228. if self._start_guid_first:
  229. if kwargs.get('verbose'):
  230. print >> sys.stderr, "--> Waiting for user '%s' login..." % self.default_user
  231. self.wait_for_session(notify_function=kwargs.get('notify_function', None))
  232. def create_xenstore_entries(self, xid = None):
  233. if dry_run:
  234. return
  235. super(QubesHVm, self).create_xenstore_entries(xid)
  236. if xid is None:
  237. xid = self.xid
  238. domain_path = xs.get_domain_path(xid)
  239. # Prepare xenstore directory for tools advertise
  240. xs.write('',
  241. "{0}/qubes-tools".format(domain_path),
  242. '')
  243. # Allow VM writes there
  244. xs.set_permissions('', '{0}/qubes-tools'.format(domain_path),
  245. [{ 'dom': xid }])
  246. def suspend(self):
  247. if dry_run:
  248. return
  249. if not self.is_running() and not self.is_paused():
  250. raise QubesException ("VM not running!")
  251. self.pause()
  252. def pause(self):
  253. if dry_run:
  254. return
  255. xc.domain_pause(self.stubdom_xid)
  256. super(QubesHVm, self).pause()
  257. def unpause(self):
  258. if dry_run:
  259. return
  260. xc.domain_unpause(self.stubdom_xid)
  261. super(QubesHVm, self).unpause()
  262. def is_guid_running(self):
  263. # If user force the guiagent, is_guid_running will mimic a standard QubesVM
  264. if self.guiagent_installed:
  265. return super(QubesHVm, self).is_guid_running()
  266. else:
  267. xid = self.stubdom_xid
  268. if xid < 0:
  269. return False
  270. if not os.path.exists('/var/run/qubes/guid-running.%d' % xid):
  271. return False
  272. return True
  273. register_qubes_vm_class(QubesHVm)