01QubesDisposableVm.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. super(QubesDisposableVm, self).__init__(**kwargs)
  88. assert self.template is not None, "Missing template for DisposableVM!"
  89. if disp_template:
  90. self.clone_attrs(disp_template)
  91. # Use DispVM icon with the same color
  92. if self._label:
  93. self._label = QubesDispVmLabels[self._label.name]
  94. self.icon_path = self._label.icon_path
  95. @property
  96. def type(self):
  97. return "DisposableVM"
  98. def is_disposablevm(self):
  99. return True
  100. @property
  101. def ip(self):
  102. if self.netvm is not None:
  103. return self.netvm.get_ip_for_dispvm(self.dispid)
  104. else:
  105. return None
  106. def get_clone_attrs(self):
  107. attrs = super(QubesDisposableVm, self).get_clone_attrs()
  108. attrs.remove('_label')
  109. return attrs
  110. def do_not_use_get_xml_attrs(self):
  111. # Minimal set - do not inherit rest of attributes
  112. attrs = {}
  113. attrs["qid"] = str(self.qid)
  114. attrs["name"] = self.name
  115. attrs["dispid"] = str(self.dispid)
  116. attrs["template_qid"] = str(self.template.qid)
  117. attrs["label"] = self.label.name
  118. attrs["firewall_conf"] = self.relative_path(self.firewall_conf)
  119. attrs["netvm_qid"] = str(self.netvm.qid) if self.netvm is not None else "none"
  120. return attrs
  121. def verify_files(self):
  122. return True
  123. def get_config_params(self):
  124. attrs = super(QubesDisposableVm, self).get_config_params()
  125. attrs['privatedev'] = ''
  126. return attrs
  127. def create_qubesdb_entries(self):
  128. super(QubesDisposableVm, self).create_qubesdb_entries()
  129. self.qdb.write('/qubes-restore-complete', '1')
  130. def start(self, verbose = False, **kwargs):
  131. self.log.debug('start()')
  132. if dry_run:
  133. return
  134. # Intentionally not used is_running(): eliminate also "Paused", "Crashed", "Halting"
  135. if self.get_power_state() != "Halted":
  136. raise QubesException ("VM is already running!")
  137. # skip netvm state checking - calling VM have the same netvm, so it
  138. # must be already running
  139. if verbose:
  140. print >> sys.stderr, "--> Loading the VM (type = {0})...".format(self.type)
  141. print >>sys.stderr, "time=%s, creating config file" % (str(time.time()))
  142. # refresh config file
  143. domain_config = self.create_config_file()
  144. if qmemman_present:
  145. mem_required = int(self.memory) * 1024 * 1024
  146. print >>sys.stderr, "time=%s, getting %d memory" % (str(time.time()), mem_required)
  147. qmemman_client = QMemmanClient()
  148. try:
  149. got_memory = qmemman_client.request_memory(mem_required)
  150. except IOError as e:
  151. raise IOError("ERROR: Failed to connect to qmemman: %s" % str(e))
  152. if not got_memory:
  153. qmemman_client.close()
  154. raise MemoryError ("ERROR: insufficient memory to start VM '%s'" % self.name)
  155. # dispvm cannot have PCI devices
  156. assert (len(self.pcidevs) == 0), "DispVM cannot have PCI devices"
  157. print >>sys.stderr, "time=%s, calling restore" % (str(time.time()))
  158. vmm.libvirt_conn.restoreFlags(self.disp_savefile,
  159. domain_config, libvirt.VIR_DOMAIN_SAVE_PAUSED)
  160. print >>sys.stderr, "time=%s, done" % (str(time.time()))
  161. self._libvirt_domain = None
  162. if verbose:
  163. print >> sys.stderr, "--> Starting Qubes DB..."
  164. self.start_qubesdb()
  165. self.services['qubes-dvm'] = True
  166. if verbose:
  167. print >> sys.stderr, "--> Setting Qubes DB info for the VM..."
  168. self.create_qubesdb_entries()
  169. print >>sys.stderr, "time=%s, done qubesdb" % (str(time.time()))
  170. # fire hooks
  171. for hook in self.hooks_start:
  172. hook(self, verbose = verbose, **kwargs)
  173. if verbose:
  174. print >> sys.stderr, "--> Starting the VM..."
  175. self.libvirt_domain.resume()
  176. print >>sys.stderr, "time=%s, resumed" % (str(time.time()))
  177. # close() is not really needed, because the descriptor is close-on-exec
  178. # anyway, the reason to postpone close() is that possibly xl is not done
  179. # constructing the domain after its main process exits
  180. # so we close() when we know the domain is up
  181. # the successful unpause is some indicator of it
  182. if qmemman_present:
  183. qmemman_client.close()
  184. if self._start_guid_first and kwargs.get('start_guid', True) and os.path.exists('/var/run/shm.id'):
  185. self.start_guid(verbose=verbose,
  186. notify_function=kwargs.get('notify_function', None))
  187. self.start_qrexec_daemon(verbose=verbose,
  188. notify_function=kwargs.get('notify_function', None))
  189. print >>sys.stderr, "time=%s, qrexec done" % (str(time.time()))
  190. if not self._start_guid_first and kwargs.get('start_guid', True) and os.path.exists('/var/run/shm.id'):
  191. self.start_guid(verbose=verbose,
  192. notify_function=kwargs.get('notify_function', None))
  193. print >>sys.stderr, "time=%s, guid done" % (str(time.time()))
  194. return self.xid
  195. # register classes
  196. register_qubes_vm_class(QubesDisposableVm)