__init__.py 10 KB

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