01QubesDisposableVm.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. qmemman_present = False
  33. try:
  34. from qubes.qmemman_client import QMemmanClient
  35. qmemman_present = True
  36. except ImportError:
  37. pass
  38. class QubesDisposableVm(QubesVm):
  39. """
  40. A class that represents an DisposableVM. A child of QubesVm.
  41. """
  42. # In which order load this VM type from qubes.xml
  43. load_order = 120
  44. def get_attrs_config(self):
  45. attrs_config = super(QubesDisposableVm, self).get_attrs_config()
  46. attrs_config['name']['eval'] = '"disp%d" % self._qid if value is None else value'
  47. # New attributes
  48. attrs_config['dispid'] = { 'func': lambda x: self._qid if x is None else int(x),
  49. 'save': lambda: str(self.dispid) }
  50. attrs_config['include_in_backups']['func'] = lambda x: False
  51. attrs_config['disp_savefile'] = {
  52. 'default': '/var/run/qubes/current-savefile',
  53. 'save': lambda: str(self.disp_savefile) }
  54. return attrs_config
  55. def __init__(self, **kwargs):
  56. disp_template = None
  57. if 'disp_template' in kwargs.keys():
  58. disp_template = kwargs['disp_template']
  59. kwargs['template'] = disp_template.template
  60. kwargs['dir_path'] = disp_template.dir_path
  61. super(QubesDisposableVm, self).__init__(**kwargs)
  62. assert self.template is not None, "Missing template for DisposableVM!"
  63. if disp_template:
  64. self.clone_attrs(disp_template)
  65. # Use DispVM icon with the same color
  66. if self._label:
  67. self._label = QubesDispVmLabels[self._label.name]
  68. self.icon_path = self._label.icon_path
  69. @property
  70. def type(self):
  71. return "DisposableVM"
  72. def is_disposablevm(self):
  73. return True
  74. @property
  75. def ip(self):
  76. if self.netvm is not None:
  77. return self.netvm.get_ip_for_dispvm(self.dispid)
  78. else:
  79. return None
  80. def get_clone_attrs(self):
  81. attrs = super(QubesDisposableVm, self).get_clone_attrs()
  82. attrs.remove('_label')
  83. return attrs
  84. def do_not_use_get_xml_attrs(self):
  85. # Minimal set - do not inherit rest of attributes
  86. attrs = {}
  87. attrs["qid"] = str(self.qid)
  88. attrs["name"] = self.name
  89. attrs["dispid"] = str(self.dispid)
  90. attrs["template_qid"] = str(self.template.qid)
  91. attrs["label"] = self.label.name
  92. attrs["firewall_conf"] = self.relative_path(self.firewall_conf)
  93. attrs["netvm_qid"] = str(self.netvm.qid) if self.netvm is not None else "none"
  94. return attrs
  95. def verify_files(self):
  96. return True
  97. def get_config_params(self):
  98. attrs = super(QubesDisposableVm, self).get_config_params()
  99. attrs['privatedev'] = ''
  100. return attrs
  101. def create_qubesdb_entries(self):
  102. super(QubesDisposableVm, self).create_qubesdb_entries()
  103. self.qdb.write('/qubes-restore-complete', '1')
  104. def start(self, verbose = False, **kwargs):
  105. self.log.debug('start()')
  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_qubesdb_entries()
  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)