01QubesDisposableVm.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 sys
  26. import libvirt
  27. import time
  28. from qubes.qubes import QubesVm,QubesVmLabel,register_qubes_vm_class, \
  29. QubesException
  30. from qubes.qubes import QubesDispVmLabels
  31. from qubes.qubes import dry_run,vmm
  32. import grp
  33. qmemman_present = False
  34. try:
  35. from qubes.qmemman_client import QMemmanClient
  36. qmemman_present = True
  37. except ImportError:
  38. pass
  39. DISPID_STATE_FILE = '/var/run/qubes/dispid'
  40. GUID_SHMID_FILE = ['/var/run/qubes/shm.id', '/var/run/shm.id']
  41. class QubesDisposableVm(QubesVm):
  42. """
  43. A class that represents an DisposableVM. A child of QubesVm.
  44. """
  45. # In which order load this VM type from qubes.xml
  46. load_order = 120
  47. def _assign_new_dispid(self):
  48. # This method in called while lock on qubes.xml is held, so no need for
  49. # additional lock
  50. if os.path.exists(DISPID_STATE_FILE):
  51. f = open(DISPID_STATE_FILE, 'r+')
  52. dispid = int(f.read())
  53. f.seek(0)
  54. f.truncate(0)
  55. f.write(str(dispid+1))
  56. f.close()
  57. else:
  58. dispid = 1
  59. f = open(DISPID_STATE_FILE, 'w')
  60. f.write(str(dispid+1))
  61. f.close()
  62. os.chown(DISPID_STATE_FILE, -1, grp.getgrnam('qubes').gr_gid)
  63. os.chmod(DISPID_STATE_FILE, 0664)
  64. return dispid
  65. def get_attrs_config(self):
  66. attrs_config = super(QubesDisposableVm, self).get_attrs_config()
  67. attrs_config['name']['func'] = \
  68. lambda x: "disp%d" % self.dispid if x is None else x
  69. # New attributes
  70. attrs_config['dispid'] = {
  71. 'func': lambda x: (self._assign_new_dispid() if x is None
  72. else int(x)),
  73. 'save': lambda: str(self.dispid),
  74. # needs to be set before name
  75. 'order': 0
  76. }
  77. attrs_config['include_in_backups']['func'] = lambda x: False
  78. attrs_config['disp_savefile'] = {
  79. 'default': '/var/run/qubes/current-savefile',
  80. 'save': lambda: str(self.disp_savefile) }
  81. return attrs_config
  82. def __init__(self, **kwargs):
  83. disp_template = None
  84. if 'disp_template' in kwargs.keys():
  85. disp_template = kwargs['disp_template']
  86. kwargs['template'] = disp_template.template
  87. kwargs['dir_path'] = disp_template.dir_path
  88. kwargs['kernel'] = disp_template.kernel
  89. kwargs['uses_default_kernel'] = disp_template.uses_default_kernel
  90. kwargs['kernelopts'] = disp_template.kernelopts
  91. kwargs['uses_default_kernelopts'] = \
  92. disp_template.uses_default_kernelopts
  93. super(QubesDisposableVm, self).__init__(**kwargs)
  94. assert self.template is not None, "Missing template for DisposableVM!"
  95. if disp_template:
  96. self.clone_attrs(disp_template)
  97. # Use DispVM icon with the same color
  98. if self._label:
  99. self._label = QubesDispVmLabels[self._label.name]
  100. self.icon_path = self._label.icon_path
  101. @property
  102. def type(self):
  103. return "DisposableVM"
  104. def is_disposablevm(self):
  105. return True
  106. @property
  107. def ip(self):
  108. if self.netvm is not None:
  109. return self.netvm.get_ip_for_dispvm(self.dispid)
  110. else:
  111. return None
  112. def get_clone_attrs(self):
  113. attrs = super(QubesDisposableVm, self).get_clone_attrs()
  114. attrs.remove('_label')
  115. return attrs
  116. def do_not_use_get_xml_attrs(self):
  117. # Minimal set - do not inherit rest of attributes
  118. attrs = {}
  119. attrs["qid"] = str(self.qid)
  120. attrs["name"] = self.name
  121. attrs["dispid"] = str(self.dispid)
  122. attrs["template_qid"] = str(self.template.qid)
  123. attrs["label"] = self.label.name
  124. attrs["firewall_conf"] = self.relative_path(self.firewall_conf)
  125. attrs["netvm_qid"] = str(self.netvm.qid) if self.netvm is not None else "none"
  126. return attrs
  127. def verify_files(self):
  128. return True
  129. def get_config_params(self):
  130. attrs = super(QubesDisposableVm, self).get_config_params()
  131. attrs['privatedev'] = ''
  132. return attrs
  133. def create_qubesdb_entries(self):
  134. super(QubesDisposableVm, self).create_qubesdb_entries()
  135. self.qdb.write("/qubes-vm-persistence", "none")
  136. self.qdb.write('/qubes-restore-complete', '1')
  137. def start(self, verbose = False, **kwargs):
  138. self.log.debug('start()')
  139. if dry_run:
  140. return
  141. # Intentionally not used is_running(): eliminate also "Paused", "Crashed", "Halting"
  142. if self.get_power_state() != "Halted":
  143. raise QubesException ("VM is already running!")
  144. if self.netvm is not None:
  145. if self.netvm.qid != 0:
  146. if not self.netvm.is_running():
  147. if verbose:
  148. print >> sys.stderr, "--> Starting NetVM {0}...".\
  149. format(self.netvm.name)
  150. self.netvm.start(verbose=verbose, **kwargs)
  151. if verbose:
  152. print >> sys.stderr, "--> Loading the VM (type = {0})...".format(self.type)
  153. print >>sys.stderr, "time=%s, creating config file" % (str(time.time()))
  154. # refresh config file
  155. domain_config = self.create_config_file()
  156. qmemman_client = self.request_memory()
  157. # dispvm cannot have PCI devices
  158. assert (len(self.pcidevs) == 0), "DispVM cannot have PCI devices"
  159. print >>sys.stderr, "time=%s, calling restore" % (str(time.time()))
  160. vmm.libvirt_conn.restoreFlags(self.disp_savefile,
  161. domain_config, libvirt.VIR_DOMAIN_SAVE_PAUSED)
  162. print >>sys.stderr, "time=%s, done" % (str(time.time()))
  163. self._libvirt_domain = None
  164. if verbose:
  165. print >> sys.stderr, "--> Starting Qubes DB..."
  166. self.start_qubesdb()
  167. self.services['qubes-dvm'] = True
  168. if verbose:
  169. print >> sys.stderr, "--> Setting Qubes DB info for the VM..."
  170. self.create_qubesdb_entries()
  171. print >>sys.stderr, "time=%s, done qubesdb" % (str(time.time()))
  172. # fire hooks
  173. for hook in self.hooks_start:
  174. hook(self, verbose = verbose, **kwargs)
  175. if verbose:
  176. print >> sys.stderr, "--> Starting the VM..."
  177. self.libvirt_domain.resume()
  178. print >>sys.stderr, "time=%s, resumed" % (str(time.time()))
  179. # close() is not really needed, because the descriptor is close-on-exec
  180. # anyway, the reason to postpone close() is that possibly xl is not done
  181. # constructing the domain after its main process exits
  182. # so we close() when we know the domain is up
  183. # the successful unpause is some indicator of it
  184. if qmemman_present:
  185. qmemman_client.close()
  186. if kwargs.get('start_guid', True) and \
  187. any(os.path.exists(x) for x in GUID_SHMID_FILE):
  188. self.start_guid(verbose=verbose, before_qrexec=True,
  189. notify_function=kwargs.get('notify_function', None))
  190. self.start_qrexec_daemon(verbose=verbose,
  191. notify_function=kwargs.get('notify_function', None))
  192. print >>sys.stderr, "time=%s, qrexec done" % (str(time.time()))
  193. if kwargs.get('start_guid', True) and \
  194. any(os.path.exists(x) for x in GUID_SHMID_FILE):
  195. self.start_guid(verbose=verbose,
  196. notify_function=kwargs.get('notify_function', None))
  197. print >>sys.stderr, "time=%s, guid done" % (str(time.time()))
  198. return self.xid
  199. def remove_from_disk(self):
  200. # nothing to remove
  201. pass
  202. # register classes
  203. register_qubes_vm_class(QubesDisposableVm)