__init__.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2013-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. from __future__ import absolute_import
  26. import importlib
  27. import os
  28. import os.path
  29. import re
  30. import shutil
  31. import subprocess
  32. import sys
  33. import qubes
  34. import qubes.utils
  35. class VMStorage(object):
  36. '''Class for handling VM virtual disks.
  37. This is base class for all other implementations, mostly with Xen on Linux
  38. in mind.
  39. ''' # pylint: disable=abstract-class-little-used
  40. def __init__(self, vm, private_img_size=None, root_img_size=None,
  41. modules_img=None, modules_img_rw=False):
  42. #: Domain for which we manage storage
  43. self.vm = vm
  44. #: Size of the private image
  45. self.private_img_size = private_img_size \
  46. if private_img_size is not None \
  47. else qubes.config.defaults['private_img_size']
  48. #: Size of the root image
  49. self.root_img_size = root_img_size \
  50. if root_img_size is not None \
  51. else qubes.config.defaults['root_img_size']
  52. # For now compute this path still in QubesVm
  53. self.modules_img = modules_img
  54. self.modules_img_rw = modules_img_rw
  55. #: Additional drive (currently used only by HVM)
  56. self.drive = None
  57. @property
  58. def private_img(self):
  59. '''Path to the private image'''
  60. return self.abspath(qubes.config.vm_files['private_img'])
  61. @property
  62. def root_img(self):
  63. '''Path to the root image'''
  64. return self.vm.template.root_img if hasattr(self.vm, 'template') \
  65. else self.abspath(qubes.config.vm_files['root_img'])
  66. @property
  67. def volatile_img(self):
  68. '''Path to the volatile image'''
  69. return self.abspath(qubes.config.vm_files['volatile_img'])
  70. def abspath(self, path, rel=None):
  71. '''Make absolute path.
  72. If given path is relative, it is interpreted as relative to
  73. :py:attr:`self.vm.dir_path` or given *rel*.
  74. '''
  75. return path if os.path.isabs(path) \
  76. else os.path.join(rel or self.vm.dir_path, path)
  77. def get_config_params(self):
  78. raise NotImplementedError()
  79. @staticmethod
  80. def _copy_file(source, destination):
  81. '''Effective file copy, preserving sparse files etc.
  82. '''
  83. # TODO: Windows support
  84. # We prefer to use Linux's cp, because it nicely handles sparse files
  85. try:
  86. subprocess.check_call(['cp', source, destination])
  87. except subprocess.CalledProcessError:
  88. raise IOError('Error while copying {!r} to {!r}'.format(
  89. source, destination))
  90. def get_disk_utilization(self):
  91. return qubes.utils.get_disk_usage(self.vmdir)
  92. def get_disk_utilization_private_img(self):
  93. # pylint: disable=invalid-name
  94. return qubes.utils.get_disk_usage(self.private_img)
  95. def get_private_img_sz(self):
  96. if not os.path.exists(self.private_img):
  97. return 0
  98. return os.path.getsize(self.private_img)
  99. def resize_private_img(self, size):
  100. raise NotImplementedError()
  101. def create_on_disk_private_img(self, source_template=None):
  102. raise NotImplementedError()
  103. def create_on_disk_root_img(self, source_template=None):
  104. raise NotImplementedError()
  105. def create_on_disk(self, source_template=None):
  106. if source_template is None:
  107. source_template = self.vm.template
  108. old_umask = os.umask(002)
  109. self.vm.log.info('Creating directory: {0}'.format(self.vm.dir_path))
  110. os.mkdir(self.vmdir)
  111. self.create_on_disk_private_img(source_template)
  112. self.create_on_disk_root_img(source_template)
  113. self.reset_volatile_storage(source_template)
  114. os.umask(old_umask)
  115. def clone_disk_files(self, src_vm):
  116. self.vm.log.info('Creating directory: {0}'.format(self.vm.dir_path))
  117. os.mkdir(self.vm.dir_path)
  118. if hasattr(src_vm, 'private_img'):
  119. self.vm.log.info('Copying the private image: {} -> {}'.format(
  120. src_vm.private_img, self.vm.private_img))
  121. self._copy_file(src_vm.private_img, self.vm.private_img)
  122. if src_vm.updateable and hasattr(src_vm, 'root_img'):
  123. self.vm.log.info('Copying the root image: {} -> {}'.format(
  124. src_vm.root_img, self.root_img))
  125. self._copy_file(src_vm.root_img, self.root_img)
  126. # TODO: modules?
  127. # XXX which modules? -woju
  128. @staticmethod
  129. def rename(newpath, oldpath):
  130. '''Move storage directory, most likely during domain's rename.
  131. .. note::
  132. The arguments are in different order than in :program:`cp` utility.
  133. .. versionchange:: 3.0
  134. This is now dummy method that just passes everything to
  135. :py:func:`os.rename`.
  136. :param str newpath: New path
  137. :param str oldpath: Old path
  138. '''
  139. os.rename(oldpath, newpath)
  140. def verify_files(self):
  141. if not os.path.exists(self.vm.dir_path):
  142. raise qubes.QubesException(
  143. 'VM directory does not exist: {}'.format(self.vmdir))
  144. if hasattr(self.vm, 'root_img') and not os.path.exists(self.root_img):
  145. raise qubes.QubesException(
  146. 'VM root image file does not exist: {}'.format(self.root_img))
  147. if hasattr(self.vm, 'private_img') \
  148. and not os.path.exists(self.private_img):
  149. raise qubes.QubesException(
  150. 'VM private image file does not exist: {}'.format(
  151. self.private_img))
  152. if self.modules_img is not None \
  153. and not os.path.exists(self.modules_img):
  154. raise qubes.QubesException(
  155. 'VM kernel modules image does not exists: {}'.format(
  156. self.modules_img))
  157. def remove_from_disk(self):
  158. shutil.rmtree(self.vm.dir_path)
  159. def reset_volatile_storage(self, source_template=None):
  160. if source_template is None:
  161. source_template = self.vm.template
  162. # Re-create only for template based VMs
  163. if source_template is not None and self.volatile_img:
  164. if os.path.exists(self.volatile_img):
  165. os.remove(self.volatile_img)
  166. # For StandaloneVM create it only if not already exists
  167. # (eg after backup-restore)
  168. if hasattr(self.vm, 'volatile_img') \
  169. and not os.path.exists(self.vm.volatile_img):
  170. self.vm.log.info(
  171. 'Creating volatile image: {0}'.format(self.volatile_img))
  172. subprocess.check_call(
  173. [qubes.config.system_path["prepare_volatile_img_cmd"],
  174. self.volatile_img,
  175. str(self.root_img_size / 1024 / 1024)])
  176. def prepare_for_vm_startup(self):
  177. self.reset_volatile_storage()
  178. if hasattr(self.vm, 'private_img') \
  179. and not os.path.exists(self.private_img):
  180. self.vm.log.info('Creating empty VM private image file: {0}'.format(
  181. self.private_img))
  182. self.storage.create_on_disk_private_img()
  183. def get_storage(vm):
  184. '''Factory yielding storage class instances for domains.
  185. :raises ImportError: when storage class specified in config cannot be found
  186. :raises KeyError: when storage class specified in config cannot be found
  187. '''
  188. pkg, cls = qubes.config.defaults['storage_class'].strip().rsplit('.', 1)
  189. # this may raise ImportError or KeyError, that's okay
  190. return importlib.import_module(pkg).__dict__[cls](vm)