dispvm.py 7.9 KB

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