dispvm.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. include_in_backups = qubes.property('include_in_backups', type=bool,
  37. default=(lambda self: not self.auto_cleanup),
  38. doc='If this domain is to be included in default backup.')
  39. def __init__(self, app, xml, *args, **kwargs):
  40. self.volume_config = {
  41. 'root': {
  42. 'name': 'root',
  43. 'snap_on_start': True,
  44. 'save_on_stop': False,
  45. 'rw': True,
  46. 'source': None,
  47. },
  48. 'private': {
  49. 'name': 'private',
  50. 'snap_on_start': True,
  51. 'save_on_stop': False,
  52. 'rw': True,
  53. 'source': None,
  54. },
  55. 'volatile': {
  56. 'name': 'volatile',
  57. 'snap_on_start': False,
  58. 'save_on_stop': False,
  59. 'rw': True,
  60. 'size': qubes.config.defaults['root_img_size'] +
  61. qubes.config.defaults['private_img_size'],
  62. },
  63. 'kernel': {
  64. 'name': 'kernel',
  65. 'snap_on_start': False,
  66. 'save_on_stop': False,
  67. 'rw': False,
  68. }
  69. }
  70. template = kwargs.get('template', None)
  71. if xml is None:
  72. assert template is not None
  73. if not getattr(template, 'template_for_dispvms', False):
  74. raise qubes.exc.QubesValueError(
  75. 'template for DispVM ({}) needs to be an AppVM with '
  76. 'template_for_dispvms=True'.format(template.name))
  77. if 'dispid' not in kwargs:
  78. kwargs['dispid'] = app.domains.get_new_unused_dispid()
  79. if 'name' not in kwargs:
  80. kwargs['name'] = 'disp' + str(kwargs['dispid'])
  81. if template is not None:
  82. # template is only passed if the AppVM is created, in other cases we
  83. # don't need to patch the volume_config because the config is
  84. # coming from XML, already as we need it
  85. for name, config in template.volume_config.items():
  86. # in case the template vm has more volumes add them to own
  87. # config
  88. if name not in self.volume_config:
  89. self.volume_config[name] = config.copy()
  90. if 'vid' in self.volume_config[name]:
  91. del self.volume_config[name]['vid']
  92. super(DispVM, self).__init__(app, xml, *args, **kwargs)
  93. if xml is None:
  94. # by default inherit properties from the DispVM template
  95. proplist = [prop.__name__ for prop in template.property_list()
  96. if prop.clone and prop.__name__ not in ['template']]
  97. self_props = [prop.__name__ for prop in self.property_list()]
  98. self.clone_properties(template, set(proplist).intersection(
  99. self_props))
  100. self.firewall.clone(template.firewall)
  101. self.features.update(template.features)
  102. self.tags.update(template.tags)
  103. @qubes.events.handler('domain-load')
  104. def on_domain_loaded(self, event):
  105. ''' When domain is loaded assert that this vm has a template.
  106. ''' # pylint: disable=unused-argument
  107. assert self.template
  108. @qubes.events.handler('property-pre-set:template',
  109. 'property-pre-del:template')
  110. def on_property_pre_set_template(self, event, name, newvalue=None,
  111. oldvalue=None):
  112. ''' Disposable VM cannot have template changed '''
  113. # pylint: disable=unused-argument
  114. raise qubes.exc.QubesValueError(self,
  115. 'Cannot change template of Disposable VM')
  116. @qubes.events.handler('domain-shutdown')
  117. @asyncio.coroutine
  118. def on_domain_shutdown(self, _event, **_kwargs):
  119. yield from self._auto_cleanup()
  120. @asyncio.coroutine
  121. def _auto_cleanup(self):
  122. '''Do auto cleanup if enabled'''
  123. if self.auto_cleanup and self in self.app.domains:
  124. yield from self.remove_from_disk()
  125. del self.app.domains[self]
  126. self.app.save()
  127. @classmethod
  128. @asyncio.coroutine
  129. def from_appvm(cls, appvm, **kwargs):
  130. '''Create a new instance from given AppVM
  131. :param qubes.vm.appvm.AppVM appvm: template from which the VM should \
  132. be created
  133. :returns: new disposable vm
  134. *kwargs* are passed to the newly created VM
  135. >>> import qubes.vm.dispvm.DispVM
  136. >>> dispvm = qubes.vm.dispvm.DispVM.from_appvm(appvm).start()
  137. >>> dispvm.run_service('qubes.VMShell', input='firefox')
  138. >>> dispvm.cleanup()
  139. This method modifies :file:`qubes.xml` file.
  140. The qube returned is not started.
  141. '''
  142. if not appvm.template_for_dispvms:
  143. raise qubes.exc.QubesException(
  144. 'Refusing to create DispVM out of this AppVM, because '
  145. 'template_for_dispvms=False')
  146. app = appvm.app
  147. dispvm = app.add_new_vm(
  148. cls,
  149. template=appvm,
  150. auto_cleanup=True,
  151. **kwargs)
  152. yield from dispvm.create_on_disk()
  153. app.save()
  154. return dispvm
  155. @asyncio.coroutine
  156. def cleanup(self):
  157. '''Clean up after the DispVM
  158. This stops the disposable qube and removes it from the store.
  159. This method modifies :file:`qubes.xml` file.
  160. '''
  161. try:
  162. # pylint: disable=not-an-iterable
  163. yield from self.kill()
  164. except qubes.exc.QubesVMNotStartedError:
  165. pass
  166. # if auto_cleanup is set, this will be done automatically
  167. if not self.auto_cleanup:
  168. yield from self.remove_from_disk()
  169. del self.app.domains[self]
  170. self.app.save()
  171. @asyncio.coroutine
  172. def start(self, **kwargs):
  173. # pylint: disable=arguments-differ
  174. try:
  175. # sanity check, if template_for_dispvm got changed in the meantime
  176. if not self.template.template_for_dispvms:
  177. raise qubes.exc.QubesException(
  178. 'template for DispVM ({}) needs to have '
  179. 'template_for_dispvms=True'.format(self.template.name))
  180. yield from super(DispVM, self).start(**kwargs)
  181. except:
  182. # Cleanup also on failed startup
  183. yield from self._auto_cleanup()
  184. raise