__init__.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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.exc
  35. import qubes.utils
  36. BLKSIZE = 512
  37. class VMStorage(object):
  38. '''Class for handling VM virtual disks.
  39. This is base class for all other implementations, mostly with Xen on Linux
  40. in mind.
  41. ''' # pylint: disable=abstract-class-little-used
  42. def __init__(self, vm, private_img_size=None, root_img_size=None):
  43. #: Domain for which we manage storage
  44. self.vm = vm
  45. #: Size of the private image
  46. self.private_img_size = private_img_size \
  47. if private_img_size is not None \
  48. else qubes.config.defaults['private_img_size']
  49. #: Size of the root image
  50. self.root_img_size = root_img_size \
  51. if root_img_size is not None \
  52. else qubes.config.defaults['root_img_size']
  53. #: Additional drive (currently used only by HVM)
  54. self.drive = None
  55. @property
  56. def private_img(self):
  57. '''Path to the private image'''
  58. return self.abspath(qubes.config.vm_files['private_img'])
  59. @property
  60. def root_img(self):
  61. '''Path to the root image'''
  62. return self.vm.template.root_img if hasattr(self.vm, 'template') \
  63. else self.abspath(qubes.config.vm_files['root_img'])
  64. @property
  65. def volatile_img(self):
  66. '''Path to the volatile image'''
  67. return self.abspath(qubes.config.vm_files['volatile_img'])
  68. @property
  69. def kernels_dir(self):
  70. '''Directory where kernel resides.
  71. If :py:attr:`self.vm.kernel` is :py:obj:`None`, the this points inside
  72. :py:attr:`self.vm.dir_path`
  73. '''
  74. return os.path.join(qubes.config.system_path['qubes_base_dir'],
  75. qubes.config.system_path['qubes_kernels_base_dir'], self.vm.kernel)\
  76. if self.vm.kernel is not None \
  77. else os.path.join(self.vm.dir_path,
  78. qubes.config.vm_files['kernels_subdir'])
  79. @property
  80. def modules_img(self):
  81. '''Path to image with modules.
  82. Depending on domain, this may be global or inside domain's dir.
  83. '''
  84. return os.path.join(self.kernels_dir, 'modules.img')
  85. @property
  86. def modules_img_rw(self):
  87. ''':py:obj:`True` if module image should be mounted RW, :py:obj:`False`
  88. otherwise.'''
  89. return self.vm.kernel is None
  90. def abspath(self, path, rel=None):
  91. '''Make absolute path.
  92. If given path is relative, it is interpreted as relative to
  93. :py:attr:`self.vm.dir_path` or given *rel*.
  94. '''
  95. return path if os.path.isabs(path) \
  96. else os.path.join(rel or self.vm.dir_path, path)
  97. def get_config_params(self):
  98. raise NotImplementedError()
  99. @staticmethod
  100. def _copy_file(source, destination):
  101. '''Effective file copy, preserving sparse files etc.
  102. '''
  103. # TODO: Windows support
  104. # We prefer to use Linux's cp, because it nicely handles sparse files
  105. try:
  106. subprocess.check_call(['cp', source, destination])
  107. except subprocess.CalledProcessError:
  108. raise IOError('Error while copying {!r} to {!r}'.format(
  109. source, destination))
  110. def get_disk_utilization(self):
  111. return get_disk_usage(self.vm.dir_path)
  112. def get_disk_utilization_private_img(self):
  113. # pylint: disable=invalid-name
  114. return get_disk_usage(self.private_img)
  115. def get_private_img_sz(self):
  116. if not os.path.exists(self.private_img):
  117. return 0
  118. return os.path.getsize(self.private_img)
  119. def resize_private_img(self, size):
  120. raise NotImplementedError()
  121. def create_on_disk_private_img(self, source_template=None):
  122. raise NotImplementedError()
  123. def create_on_disk_root_img(self, source_template=None):
  124. raise NotImplementedError()
  125. def create_on_disk(self, source_template=None):
  126. if source_template is None:
  127. source_template = self.vm.template
  128. old_umask = os.umask(002)
  129. self.vm.log.info('Creating directory: {0}'.format(self.vm.dir_path))
  130. os.mkdir(self.vm.dir_path)
  131. self.create_on_disk_private_img(source_template)
  132. self.create_on_disk_root_img(source_template)
  133. self.reset_volatile_storage(source_template)
  134. os.umask(old_umask)
  135. def clone_disk_files(self, src_vm):
  136. self.vm.log.info('Creating directory: {0}'.format(self.vm.dir_path))
  137. os.mkdir(self.vm.dir_path)
  138. if hasattr(src_vm, 'private_img'):
  139. self.vm.log.info('Copying the private image: {} -> {}'.format(
  140. src_vm.private_img, self.vm.private_img))
  141. self._copy_file(src_vm.private_img, self.vm.private_img)
  142. if src_vm.updateable and hasattr(src_vm, 'root_img'):
  143. self.vm.log.info('Copying the root image: {} -> {}'.format(
  144. src_vm.root_img, self.root_img))
  145. self._copy_file(src_vm.root_img, self.root_img)
  146. # TODO: modules?
  147. # XXX which modules? -woju
  148. @staticmethod
  149. def rename(newpath, oldpath):
  150. '''Move storage directory, most likely during domain's rename.
  151. .. note::
  152. The arguments are in different order than in :program:`cp` utility.
  153. .. versionchange:: 3.0
  154. This is now dummy method that just passes everything to
  155. :py:func:`os.rename`.
  156. :param str newpath: New path
  157. :param str oldpath: Old path
  158. '''
  159. os.rename(oldpath, newpath)
  160. def verify_files(self):
  161. if not os.path.exists(self.vm.dir_path):
  162. raise qubes.exc.QubesVMError(self.vm,
  163. 'VM directory does not exist: {}'.format(self.vm.dir_path))
  164. if hasattr(self.vm, 'root_img') and not os.path.exists(self.root_img):
  165. raise qubes.exc.QubesVMError(self.vm,
  166. 'VM root image file does not exist: {}'.format(self.root_img))
  167. if hasattr(self.vm, 'private_img') \
  168. and not os.path.exists(self.private_img):
  169. raise qubes.exc.QubesVMError(self.vm,
  170. 'VM private image file does not exist: {}'.format(
  171. self.private_img))
  172. if self.modules_img is not None \
  173. and not os.path.exists(self.modules_img):
  174. raise qubes.exc.QubesVMError(self.vm,
  175. 'VM kernel modules image does not exists: {}'.format(
  176. self.modules_img))
  177. def remove_from_disk(self):
  178. shutil.rmtree(self.vm.dir_path)
  179. def reset_volatile_storage(self, source_template=None):
  180. if source_template is None:
  181. source_template = self.vm.template
  182. # Re-create only for template based VMs
  183. if source_template is not None and self.volatile_img:
  184. if os.path.exists(self.volatile_img):
  185. os.remove(self.volatile_img)
  186. # For StandaloneVM create it only if not already exists
  187. # (eg after backup-restore)
  188. if hasattr(self.vm, 'volatile_img') \
  189. and not os.path.exists(self.vm.volatile_img):
  190. self.vm.log.info(
  191. 'Creating volatile image: {0}'.format(self.volatile_img))
  192. subprocess.check_call(
  193. [qubes.config.system_path["prepare_volatile_img_cmd"],
  194. self.volatile_img,
  195. str(self.root_img_size / 1024 / 1024)])
  196. def prepare_for_vm_startup(self):
  197. self.reset_volatile_storage()
  198. if hasattr(self.vm, 'private_img') \
  199. and not os.path.exists(self.private_img):
  200. self.vm.log.info('Creating empty VM private image file: {0}'.format(
  201. self.private_img))
  202. self.create_on_disk_private_img()
  203. def get_disk_usage_one(st):
  204. '''Extract disk usage of one inode from its stat_result struct.
  205. If known, get real disk usage, as written to device by filesystem, not
  206. logical file size. Those values may be different for sparse files.
  207. :param os.stat_result st: stat result
  208. :returns: disk usage
  209. '''
  210. try:
  211. return st.st_blocks * BLKSIZE
  212. except AttributeError:
  213. return st.st_size
  214. def get_disk_usage(path):
  215. '''Get real disk usage of given path (file or directory).
  216. When *path* points to directory, then it is evaluated recursively.
  217. This function tries estiate real disk usage. See documentation of
  218. :py:func:`get_disk_usage_one`.
  219. :param str path: path to evaluate
  220. :returns: disk usage
  221. '''
  222. try:
  223. st = os.lstat(path)
  224. except OSError:
  225. return 0
  226. ret = get_disk_usage_one(st)
  227. # if path is not a directory, this is skipped
  228. for dirpath, dirnames, filenames in os.walk(path):
  229. for name in dirnames + filenames:
  230. ret += get_disk_usage_one(os.lstat(os.path.join(dirpath, name)))
  231. return ret
  232. def get_storage(vm):
  233. '''Factory yielding storage class instances for domains.
  234. :raises ImportError: when storage class specified in config cannot be found
  235. :raises KeyError: when storage class specified in config cannot be found
  236. '''
  237. pkg, cls = qubes.config.defaults['storage_class'].strip().rsplit('.', 1)
  238. # this may raise ImportError or KeyError, that's okay
  239. return importlib.import_module(pkg).__dict__[cls](vm)