01QubesDisposableVm.py 7.0 KB

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