__init__.py 15 KB

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