01QubesDisposableVm.py 7.2 KB

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