01QubesDisposableVm.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. from qubes.qubes import QubesDispVmLabels
  30. from qubes.qubes import dry_run,vmm
  31. qmemman_present = False
  32. try:
  33. from qubes.qmemman_client import QMemmanClient
  34. qmemman_present = True
  35. except ImportError:
  36. pass
  37. class QubesDisposableVm(QubesVm):
  38. """
  39. A class that represents an DisposableVM. A child of QubesVm.
  40. """
  41. # In which order load this VM type from qubes.xml
  42. load_order = 120
  43. def get_attrs_config(self):
  44. attrs_config = super(QubesDisposableVm, self).get_attrs_config()
  45. attrs_config['name']['eval'] = '"disp%d" % self._qid if value is None else value'
  46. attrs_config.pop('kernel')
  47. attrs_config.pop('kernels_dir')
  48. attrs_config.pop('kernelopts')
  49. attrs_config.pop('uses_default_kernel')
  50. attrs_config.pop('uses_default_kernelopts')
  51. # New attributes
  52. attrs_config['dispid'] = { 'func': lambda x: self._qid if x is None else int(x),
  53. 'save': lambda: str(self.dispid) }
  54. attrs_config['include_in_backups']['func'] = lambda x: False
  55. attrs_config['disp_savefile'] = {
  56. 'default': '/var/run/qubes/current-savefile',
  57. 'save': lambda: str(self.disp_savefile) }
  58. return attrs_config
  59. def __init__(self, **kwargs):
  60. disp_template = None
  61. if 'disp_template' in kwargs.keys():
  62. disp_template = kwargs['disp_template']
  63. kwargs['template'] = disp_template.template
  64. kwargs['dir_path'] = disp_template.dir_path
  65. super(QubesDisposableVm, self).__init__(**kwargs)
  66. assert self.template is not None, "Missing template for DisposableVM!"
  67. if disp_template:
  68. self.clone_attrs(disp_template)
  69. # Use DispVM icon with the same color
  70. if self._label:
  71. self._label = QubesDispVmLabels[self._label.name]
  72. self.icon_path = self._label.icon_path
  73. @property
  74. def type(self):
  75. return "DisposableVM"
  76. def is_disposablevm(self):
  77. return True
  78. @property
  79. def ip(self):
  80. if self.netvm is not None:
  81. return self.netvm.get_ip_for_dispvm(self.dispid)
  82. else:
  83. return None
  84. def get_clone_attrs(self):
  85. attrs = super(QubesDisposableVm, self).get_clone_attrs()
  86. attrs.remove('_label')
  87. return attrs
  88. def do_not_use_get_xml_attrs(self):
  89. # Minimal set - do not inherit rest of attributes
  90. attrs = {}
  91. attrs["qid"] = str(self.qid)
  92. attrs["name"] = self.name
  93. attrs["dispid"] = str(self.dispid)
  94. attrs["template_qid"] = str(self.template.qid)
  95. attrs["label"] = self.label.name
  96. attrs["firewall_conf"] = self.relative_path(self.firewall_conf)
  97. attrs["netvm_qid"] = str(self.netvm.qid) if self.netvm is not None else "none"
  98. return attrs
  99. def verify_files(self):
  100. return True
  101. def get_config_params(self):
  102. attrs = super(QubesDisposableVm, self).get_config_params()
  103. attrs['privatedev'] = ''
  104. return attrs
  105. def start(self, verbose = False, **kwargs):
  106. if dry_run:
  107. return
  108. # Intentionally not used is_running(): eliminate also "Paused", "Crashed", "Halting"
  109. if self.get_power_state() != "Halted":
  110. raise QubesException ("VM is already running!")
  111. # skip netvm state checking - calling VM have the same netvm, so it
  112. # must be already running
  113. if verbose:
  114. print >> sys.stderr, "--> Loading the VM (type = {0})...".format(self.type)
  115. print >>sys.stderr, "time=%s, creating config file" % (str(time.time()))
  116. # refresh config file
  117. domain_config = self.create_config_file()
  118. if qmemman_present:
  119. mem_required = int(self.memory) * 1024 * 1024
  120. print >>sys.stderr, "time=%s, getting %d memory" % (str(time.time()), mem_required)
  121. qmemman_client = QMemmanClient()
  122. try:
  123. got_memory = qmemman_client.request_memory(mem_required)
  124. except IOError as e:
  125. raise IOError("ERROR: Failed to connect to qmemman: %s" % str(e))
  126. if not got_memory:
  127. qmemman_client.close()
  128. raise MemoryError ("ERROR: insufficient memory to start VM '%s'" % self.name)
  129. # dispvm cannot have PCI devices
  130. assert (len(self.pcidevs) == 0), "DispVM cannot have PCI devices"
  131. print >>sys.stderr, "time=%s, calling restore" % (str(time.time()))
  132. vmm.libvirt_conn.restoreFlags(self.disp_savefile,
  133. domain_config, libvirt.VIR_DOMAIN_SAVE_PAUSED)
  134. print >>sys.stderr, "time=%s, done" % (str(time.time()))
  135. self._libvirt_domain = None
  136. if verbose:
  137. print >> sys.stderr, "--> Starting Qubes DB..."
  138. self.start_qubesdb()
  139. self.services['qubes-dvm'] = True
  140. if verbose:
  141. print >> sys.stderr, "--> Setting Qubes DB info for the VM..."
  142. self.create_xenstore_entries(self.xid)
  143. print >>sys.stderr, "time=%s, done qubesdb" % (str(time.time()))
  144. # fire hooks
  145. for hook in self.hooks_start:
  146. hook(self, verbose = verbose, **kwargs)
  147. if verbose:
  148. print >> sys.stderr, "--> Starting the VM..."
  149. self.libvirt_domain.resume()
  150. print >>sys.stderr, "time=%s, resumed" % (str(time.time()))
  151. # close() is not really needed, because the descriptor is close-on-exec
  152. # anyway, the reason to postpone close() is that possibly xl is not done
  153. # constructing the domain after its main process exits
  154. # so we close() when we know the domain is up
  155. # the successful unpause is some indicator of it
  156. if qmemman_present:
  157. qmemman_client.close()
  158. if self._start_guid_first and kwargs.get('start_guid', True) and os.path.exists('/var/run/shm.id'):
  159. self.start_guid(verbose=verbose,
  160. notify_function=kwargs.get('notify_function', None))
  161. self.start_qrexec_daemon(verbose=verbose,
  162. notify_function=kwargs.get('notify_function', None))
  163. print >>sys.stderr, "time=%s, qrexec done" % (str(time.time()))
  164. if not self._start_guid_first and kwargs.get('start_guid', True) and os.path.exists('/var/run/shm.id'):
  165. self.start_guid(verbose=verbose,
  166. notify_function=kwargs.get('notify_function', None))
  167. print >>sys.stderr, "time=%s, guid done" % (str(time.time()))
  168. return self.xid
  169. # register classes
  170. register_qubes_vm_class(QubesDisposableVm)