01QubesDisposableVm.py 8.4 KB

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