dispvm.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2014-2016 Wojtek Porczyk <woju@invisiblethingslab.com>
  5. # Copyright (C) 2016 Marek Marczykowski <marmarek@invisiblethingslab.com>)
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  19. #
  20. ''' A disposable vm implementation '''
  21. import asyncio
  22. import qubes.vm.qubesvm
  23. import qubes.vm.appvm
  24. import qubes.config
  25. class DispVM(qubes.vm.qubesvm.QubesVM):
  26. '''Disposable VM'''
  27. template = qubes.VMProperty('template',
  28. load_stage=4,
  29. vmclass=qubes.vm.appvm.AppVM,
  30. doc='AppVM, on which this DispVM is based.')
  31. dispid = qubes.property('dispid', type=int, write_once=True,
  32. clone=False,
  33. doc='''Internal, persistent identifier of particular DispVM.''')
  34. auto_cleanup = qubes.property('auto_cleanup', type=bool, default=False,
  35. doc='automatically remove this VM upon shutdown')
  36. def __init__(self, app, xml, *args, **kwargs):
  37. self.volume_config = {
  38. 'root': {
  39. 'name': 'root',
  40. 'snap_on_start': True,
  41. 'save_on_stop': False,
  42. 'rw': False,
  43. 'source': None,
  44. },
  45. 'private': {
  46. 'name': 'private',
  47. 'snap_on_start': True,
  48. 'save_on_stop': False,
  49. 'rw': True,
  50. 'source': None,
  51. },
  52. 'volatile': {
  53. 'name': 'volatile',
  54. 'snap_on_start': False,
  55. 'save_on_stop': False,
  56. 'rw': True,
  57. 'size': qubes.config.defaults['root_img_size'] +
  58. qubes.config.defaults['private_img_size'],
  59. },
  60. 'kernel': {
  61. 'name': 'kernel',
  62. 'snap_on_start': False,
  63. 'save_on_stop': False,
  64. 'rw': False,
  65. }
  66. }
  67. template = kwargs.get('template', None)
  68. if xml is None:
  69. assert template is not None
  70. if not template.template_for_dispvms:
  71. raise qubes.exc.QubesValueError(
  72. 'template for DispVM ({}) needs to have '
  73. 'template_for_dispvms=True'.format(template.name))
  74. if 'dispid' not in kwargs:
  75. kwargs['dispid'] = app.domains.get_new_unused_dispid()
  76. if 'name' not in kwargs:
  77. kwargs['name'] = 'disp' + str(kwargs['dispid'])
  78. if template is not None:
  79. # template is only passed if the AppVM is created, in other cases we
  80. # don't need to patch the volume_config because the config is
  81. # coming from XML, already as we need it
  82. for name, config in template.volume_config.items():
  83. # in case the template vm has more volumes add them to own
  84. # config
  85. if name not in self.volume_config:
  86. self.volume_config[name] = config.copy()
  87. if 'vid' in self.volume_config[name]:
  88. del self.volume_config[name]['vid']
  89. super(DispVM, self).__init__(app, xml, *args, **kwargs)
  90. if xml is None:
  91. # by default inherit properties from the DispVM template
  92. proplist = [prop.__name__ for prop in template.property_list()
  93. if prop.clone and prop.__name__ not in ['template']]
  94. self_props = [prop.__name__ for prop in self.property_list()]
  95. self.clone_properties(template, set(proplist).intersection(
  96. self_props))
  97. self.firewall.clone(template.firewall)
  98. self.features.update(template.features)
  99. self.tags.update(template.tags)
  100. @qubes.events.handler('domain-load')
  101. def on_domain_loaded(self, event):
  102. ''' When domain is loaded assert that this vm has a template.
  103. ''' # pylint: disable=unused-argument
  104. assert self.template
  105. @qubes.events.handler('property-pre-set:template',
  106. 'property-pre-del:template')
  107. def on_property_pre_set_template(self, event, name, newvalue=None,
  108. oldvalue=None):
  109. ''' Disposable VM cannot have template changed '''
  110. # pylint: disable=unused-argument
  111. raise qubes.exc.QubesValueError(self,
  112. 'Cannot change template of Disposable VM')
  113. @qubes.events.handler('domain-shutdown')
  114. @asyncio.coroutine
  115. def on_domain_shutdown(self, _event, **_kwargs):
  116. yield from self._auto_cleanup()
  117. @asyncio.coroutine
  118. def _auto_cleanup(self):
  119. '''Do auto cleanup if enabled'''
  120. if self.auto_cleanup and self in self.app.domains:
  121. yield from self.remove_from_disk()
  122. del self.app.domains[self]
  123. self.app.save()
  124. @classmethod
  125. @asyncio.coroutine
  126. def from_appvm(cls, appvm, **kwargs):
  127. '''Create a new instance from given AppVM
  128. :param qubes.vm.appvm.AppVM appvm: template from which the VM should \
  129. be created
  130. :returns: new disposable vm
  131. *kwargs* are passed to the newly created VM
  132. >>> import qubes.vm.dispvm.DispVM
  133. >>> dispvm = qubes.vm.dispvm.DispVM.from_appvm(appvm).start()
  134. >>> dispvm.run_service('qubes.VMShell', input='firefox')
  135. >>> dispvm.cleanup()
  136. This method modifies :file:`qubes.xml` file.
  137. The qube returned is not started.
  138. '''
  139. if not appvm.template_for_dispvms:
  140. raise qubes.exc.QubesException(
  141. 'Refusing to create DispVM out of this AppVM, because '
  142. 'template_for_dispvms=False')
  143. app = appvm.app
  144. dispvm = app.add_new_vm(
  145. cls,
  146. template=appvm,
  147. auto_cleanup=True,
  148. **kwargs)
  149. yield from dispvm.create_on_disk()
  150. app.save()
  151. return dispvm
  152. @asyncio.coroutine
  153. def cleanup(self):
  154. '''Clean up after the DispVM
  155. This stops the disposable qube and removes it from the store.
  156. This method modifies :file:`qubes.xml` file.
  157. '''
  158. try:
  159. # pylint: disable=not-an-iterable
  160. yield from self.kill()
  161. except qubes.exc.QubesVMNotStartedError:
  162. pass
  163. # if auto_cleanup is set, this will be done automatically
  164. if not self.auto_cleanup:
  165. yield from self.remove_from_disk()
  166. del self.app.domains[self]
  167. self.app.save()
  168. @asyncio.coroutine
  169. def start(self, **kwargs):
  170. # pylint: disable=arguments-differ
  171. try:
  172. # sanity check, if template_for_dispvm got changed in the meantime
  173. if not self.template.template_for_dispvms:
  174. raise qubes.exc.QubesException(
  175. 'template for DispVM ({}) needs to have '
  176. 'template_for_dispvms=True'.format(self.template.name))
  177. yield from super(DispVM, self).start(**kwargs)
  178. except:
  179. # Cleanup also on failed startup
  180. yield from self._auto_cleanup()
  181. raise