__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. """ Qubes storage system"""
  26. from __future__ import absolute_import
  27. import os
  28. import os.path
  29. import shutil
  30. import subprocess
  31. import pkg_resources
  32. import qubes
  33. import qubes.exc
  34. import qubes.utils
  35. BLKSIZE = 512
  36. STORAGE_ENTRY_POINT = 'qubes.storage'
  37. class StoragePoolException(qubes.exc.QubesException):
  38. pass
  39. class Storage(object):
  40. '''Class for handling VM virtual disks.
  41. This is base class for all other implementations, mostly with Xen on Linux
  42. in mind.
  43. '''
  44. root_img = None
  45. private_img = None
  46. volatile_img = None
  47. modules_dev = None
  48. def __init__(self, vm, private_img_size=None, root_img_size=None):
  49. #: Domain for which we manage storage
  50. self.vm = vm
  51. #: Size of the private image
  52. self.private_img_size = private_img_size \
  53. if private_img_size is not None \
  54. else qubes.config.defaults['private_img_size']
  55. #: Size of the root image
  56. self.root_img_size = root_img_size \
  57. if root_img_size is not None \
  58. else qubes.config.defaults['root_img_size']
  59. #: Additional drive (currently used only by HVM)
  60. self.drive = None
  61. def get_config_params(self):
  62. args = {}
  63. args['rootdev'] = self.root_dev_config()
  64. args['privatedev'] = self.private_dev_config()
  65. args['volatiledev'] = self.volatile_dev_config()
  66. args['otherdevs'] = self.other_dev_config()
  67. args['kerneldir'] = self.kernels_dir
  68. return args
  69. def root_dev_config(self):
  70. raise NotImplementedError()
  71. def private_dev_config(self):
  72. raise NotImplementedError()
  73. def volatile_dev_config(self):
  74. raise NotImplementedError()
  75. def other_dev_config(self):
  76. if self.modules_img is not None:
  77. return BlockDevice(self.modules_img, 'kernel', rw=False)
  78. elif self.drive is not None:
  79. (drive_type, drive_domain, drive_path) = self.drive.split(":")
  80. if drive_type == 'hd':
  81. drive_type = 'disk'
  82. rw = (drive_type == 'disk')
  83. if drive_domain.lower() == "dom0":
  84. drive_domain = None
  85. return self.format_disk_dev(drive_path,
  86. 'other',
  87. rw=rw,
  88. devtype=drive_type,
  89. domain=drive_domain)
  90. else:
  91. return ''
  92. def format_disk_dev(self, path, name, script=None, rw=True, devtype='disk',
  93. domain=None):
  94. raise NotImplementedError()
  95. @property
  96. def kernels_dir(self):
  97. '''Directory where kernel resides.
  98. If :py:attr:`self.vm.kernel` is :py:obj:`None`, the this points inside
  99. :py:attr:`self.vm.dir_path`
  100. '''
  101. return os.path.join(qubes.config.system_path['qubes_base_dir'],
  102. qubes.config.system_path['qubes_kernels_base_dir'], self.vm.kernel)\
  103. if self.vm.kernel is not None \
  104. else os.path.join(self.vm.dir_path,
  105. qubes.config.vm_files['kernels_subdir'])
  106. @property
  107. def modules_img(self):
  108. '''Path to image with modules.
  109. Depending on domain, this may be global or inside domain's dir.
  110. '''
  111. modules_path = os.path.join(self.kernels_dir, 'modules.img')
  112. if os.path.exists(modules_path):
  113. return modules_path
  114. else:
  115. return None
  116. @property
  117. def modules_img_rw(self):
  118. ''':py:obj:`True` if module image should be mounted RW, :py:obj:`False`
  119. otherwise.'''
  120. return self.vm.kernel is None
  121. def abspath(self, path, rel=None):
  122. '''Make absolute path.
  123. If given path is relative, it is interpreted as relative to
  124. :py:attr:`self.vm.dir_path` or given *rel*.
  125. '''
  126. return path if os.path.isabs(path) \
  127. else os.path.join(rel or self.vm.dir_path, path)
  128. @staticmethod
  129. def _copy_file(source, destination):
  130. '''Effective file copy, preserving sparse files etc.
  131. '''
  132. # TODO: Windows support
  133. # We prefer to use Linux's cp, because it nicely handles sparse files
  134. try:
  135. subprocess.check_call(['cp', '--reflink=auto', source, destination])
  136. except subprocess.CalledProcessError:
  137. raise IOError('Error while copying {!r} to {!r}'.format(
  138. source, destination))
  139. def get_disk_utilization(self):
  140. return get_disk_usage(self.vm.dir_path)
  141. def get_disk_utilization_private_img(self):
  142. # pylint: disable=invalid-name
  143. return get_disk_usage(self.private_img)
  144. def get_private_img_sz(self):
  145. if not os.path.exists(self.private_img):
  146. return 0
  147. return os.path.getsize(self.private_img)
  148. def resize_private_img(self, size):
  149. raise NotImplementedError()
  150. def create_on_disk_private_img(self, source_template=None):
  151. raise NotImplementedError()
  152. def create_on_disk_root_img(self, source_template=None):
  153. raise NotImplementedError()
  154. def create_on_disk(self, source_template=None):
  155. if source_template is None and hasattr(self.vm, 'template'):
  156. source_template = self.vm.template
  157. old_umask = os.umask(002)
  158. self.vm.log.info('Creating directory: {0}'.format(self.vm.dir_path))
  159. os.mkdir(self.vm.dir_path)
  160. self.create_on_disk_private_img(source_template)
  161. self.create_on_disk_root_img(source_template)
  162. self.reset_volatile_storage()
  163. os.umask(old_umask)
  164. def clone_disk_files(self, src_vm):
  165. self.vm.log.info('Creating directory: {0}'.format(self.vm.dir_path))
  166. os.mkdir(self.vm.dir_path)
  167. if hasattr(src_vm, 'private_img'):
  168. self.vm.log.info('Copying the private image: {} -> {}'.format(
  169. src_vm.private_img, self.vm.private_img))
  170. self._copy_file(src_vm.private_img, self.vm.private_img)
  171. if src_vm.updateable and hasattr(src_vm, 'root_img'):
  172. self.vm.log.info('Copying the root image: {} -> {}'.format(
  173. src_vm.root_img, self.root_img))
  174. self._copy_file(src_vm.root_img, self.root_img)
  175. # TODO: modules?
  176. # XXX which modules? -woju
  177. @staticmethod
  178. def rename(newpath, oldpath):
  179. '''Move storage directory, most likely during domain's rename.
  180. .. note::
  181. The arguments are in different order than in :program:`cp` utility.
  182. .. versionchange:: 4.0
  183. This is now dummy method that just passes everything to
  184. :py:func:`os.rename`.
  185. :param str newpath: New path
  186. :param str oldpath: Old path
  187. '''
  188. os.rename(oldpath, newpath)
  189. def verify_files(self):
  190. if not os.path.exists(self.vm.dir_path):
  191. raise qubes.exc.QubesVMError(self.vm,
  192. 'VM directory does not exist: {}'.format(self.vm.dir_path))
  193. if hasattr(self.vm, 'root_img') and not os.path.exists(self.root_img):
  194. raise qubes.exc.QubesVMError(self.vm,
  195. 'VM root image file does not exist: {}'.format(self.root_img))
  196. if hasattr(self.vm, 'private_img') \
  197. and not os.path.exists(self.private_img):
  198. raise qubes.exc.QubesVMError(self.vm,
  199. 'VM private image file does not exist: {}'.format(
  200. self.private_img))
  201. if self.modules_img is not None \
  202. and not os.path.exists(self.modules_img):
  203. raise qubes.exc.QubesVMError(self.vm,
  204. 'VM kernel modules image does not exists: {}'.format(
  205. self.modules_img))
  206. def remove_from_disk(self):
  207. shutil.rmtree(self.vm.dir_path)
  208. def reset_volatile_storage(self):
  209. # Re-create only for template based VMs
  210. try:
  211. if self.vm.template is not None and self.volatile_img:
  212. if os.path.exists(self.volatile_img):
  213. os.remove(self.volatile_img)
  214. except AttributeError: # self.vm.template
  215. pass
  216. # For StandaloneVM create it only if not already exists
  217. # (eg after backup-restore)
  218. if hasattr(self, 'volatile_img') \
  219. and not os.path.exists(self.volatile_img):
  220. self.vm.log.info(
  221. 'Creating volatile image: {0}'.format(self.volatile_img))
  222. subprocess.check_call(
  223. [qubes.config.system_path["prepare_volatile_img_cmd"],
  224. self.volatile_img,
  225. str(self.root_img_size / 1024 / 1024)])
  226. def prepare_for_vm_startup(self):
  227. self.reset_volatile_storage()
  228. if hasattr(self.vm, 'private_img') \
  229. and not os.path.exists(self.private_img):
  230. self.vm.log.info('Creating empty VM private image file: {0}'.format(
  231. self.private_img))
  232. self.create_on_disk_private_img()
  233. def get_disk_usage_one(st):
  234. '''Extract disk usage of one inode from its stat_result struct.
  235. If known, get real disk usage, as written to device by filesystem, not
  236. logical file size. Those values may be different for sparse files.
  237. :param os.stat_result st: stat result
  238. :returns: disk usage
  239. '''
  240. try:
  241. return st.st_blocks * BLKSIZE
  242. except AttributeError:
  243. return st.st_size
  244. def get_disk_usage(path):
  245. '''Get real disk usage of given path (file or directory).
  246. When *path* points to directory, then it is evaluated recursively.
  247. This function tries estiate real disk usage. See documentation of
  248. :py:func:`get_disk_usage_one`.
  249. :param str path: path to evaluate
  250. :returns: disk usage
  251. '''
  252. try:
  253. st = os.lstat(path)
  254. except OSError:
  255. return 0
  256. ret = get_disk_usage_one(st)
  257. # if path is not a directory, this is skipped
  258. for dirpath, dirnames, filenames in os.walk(path):
  259. for name in dirnames + filenames:
  260. ret += get_disk_usage_one(os.lstat(os.path.join(dirpath, name)))
  261. return ret
  262. class Pool(object):
  263. def __init__(self, vm, dir_path):
  264. assert vm is not None
  265. assert dir_path is not None
  266. self.vm = vm
  267. self.dir_path = dir_path
  268. self.create_dir_if_not_exists(self.dir_path)
  269. self.vmdir = self.vmdir_path(vm, self.dir_path)
  270. appvms_path = os.path.join(self.dir_path, 'appvms')
  271. self.create_dir_if_not_exists(appvms_path)
  272. servicevms_path = os.path.join(self.dir_path, 'servicevms')
  273. self.create_dir_if_not_exists(servicevms_path)
  274. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  275. self.create_dir_if_not_exists(vm_templates_path)
  276. # XXX there is also a class attribute on the domain classes which does
  277. # exactly that -- which one should prevail?
  278. def vmdir_path(self, vm, pool_dir):
  279. """ Returns the path to vmdir depending on the type of the VM.
  280. The default QubesOS file storage saves the vm images in three
  281. different directories depending on the ``QubesVM`` type:
  282. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  283. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  284. Args:
  285. vm: a QubesVM
  286. pool_dir: the root directory of the pool
  287. Returns:
  288. string (str) absolute path to the directory where the vm files
  289. are stored
  290. """
  291. if vm.is_template():
  292. subdir = 'vm-templates'
  293. elif vm.is_disposablevm():
  294. subdir = 'appvms'
  295. return os.path.join(pool_dir, subdir, vm.template.name + '-dvm')
  296. else:
  297. subdir = 'appvms'
  298. return os.path.join(pool_dir, subdir, vm.name)
  299. def create_dir_if_not_exists(self, path):
  300. """ Check if a directory exists in if not create it.
  301. This method does not create any parent directories.
  302. """
  303. if not os.path.exists(path):
  304. os.mkdir(path)
  305. def pool_drivers():
  306. """ Return a list of EntryPoints names """
  307. return [ep.name
  308. for ep in pkg_resources.iter_entry_points(STORAGE_ENTRY_POINT)]