__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. CONFIG_FILE = '/etc/qubes/storage.conf'
  38. class Storage(object):
  39. '''Class for handling VM virtual disks.
  40. This is base class for all other implementations, mostly with Xen on Linux
  41. in mind.
  42. ''' # pylint: disable=abstract-class-little-used
  43. root_img = None
  44. private_img = None
  45. volatile_img = None
  46. def __init__(self, vm, private_img_size=None, root_img_size=None):
  47. #: Domain for which we manage storage
  48. self.vm = vm
  49. #: Size of the private image
  50. self.private_img_size = private_img_size \
  51. if private_img_size is not None \
  52. else qubes.config.defaults['private_img_size']
  53. #: Size of the root image
  54. self.root_img_size = root_img_size \
  55. if root_img_size is not None \
  56. else qubes.config.defaults['root_img_size']
  57. #: Additional drive (currently used only by HVM)
  58. self.drive = None
  59. def get_config_params(self):
  60. args = {}
  61. args['rootdev'] = self.root_dev_config()
  62. args['privatedev'] = self.private_dev_config()
  63. args['volatiledev'] = self.volatile_dev_config()
  64. args['otherdevs'] = self.other_dev_config()
  65. args['kerneldir'] = self.kernels_dir
  66. return args
  67. def root_dev_config(self):
  68. raise NotImplementedError()
  69. def private_dev_config(self):
  70. raise NotImplementedError()
  71. def volatile_dev_config(self):
  72. raise NotImplementedError()
  73. def other_dev_config(self)
  74. if self.modules_img is not None:
  75. return self.format_disk_dev(self.modules_img, None,
  76. self.modules_dev, rw=self.modules_img_rw)
  77. elif self.drive is not None:
  78. (drive_type, drive_domain, drive_path) = self.drive.split(":")
  79. if drive_type == 'hd':
  80. drive_type = 'disk'
  81. rw = (drive_type == 'disk')
  82. if drive_domain.lower() == "dom0":
  83. drive_domain = None
  84. return self.format_disk_dev(drive_path,
  85. None,
  86. self.modules_dev,
  87. rw=rw,
  88. type=drive_type,
  89. domain=drive_domain)
  90. else:
  91. return ''
  92. def format_disk_dev(self, path, script, vdev, rw=True, type='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. def get_config_params(self):
  129. raise NotImplementedError()
  130. @staticmethod
  131. def _copy_file(source, destination):
  132. '''Effective file copy, preserving sparse files etc.
  133. '''
  134. # TODO: Windows support
  135. # We prefer to use Linux's cp, because it nicely handles sparse files
  136. try:
  137. subprocess.check_call(['cp', '--reflink=auto', source, destination])
  138. except subprocess.CalledProcessError:
  139. raise IOError('Error while copying {!r} to {!r}'.format(
  140. source, destination))
  141. def get_disk_utilization(self):
  142. return get_disk_usage(self.vm.dir_path)
  143. def get_disk_utilization_private_img(self):
  144. # pylint: disable=invalid-name
  145. return get_disk_usage(self.private_img)
  146. def get_private_img_sz(self):
  147. if not os.path.exists(self.private_img):
  148. return 0
  149. return os.path.getsize(self.private_img)
  150. def resize_private_img(self, size):
  151. raise NotImplementedError()
  152. def create_on_disk_private_img(self, source_template=None):
  153. raise NotImplementedError()
  154. def create_on_disk_root_img(self, source_template=None):
  155. raise NotImplementedError()
  156. def create_on_disk(self, source_template=None):
  157. if source_template is None:
  158. source_template = self.vm.template
  159. old_umask = os.umask(002)
  160. self.vm.log.info('Creating directory: {0}'.format(self.vm.dir_path))
  161. os.mkdir(self.vm.dir_path)
  162. self.create_on_disk_private_img(source_template)
  163. self.create_on_disk_root_img(source_template)
  164. self.reset_volatile_storage(source_template)
  165. os.umask(old_umask)
  166. def clone_disk_files(self, src_vm):
  167. self.vm.log.info('Creating directory: {0}'.format(self.vm.dir_path))
  168. os.mkdir(self.vm.dir_path)
  169. if hasattr(src_vm, 'private_img'):
  170. self.vm.log.info('Copying the private image: {} -> {}'.format(
  171. src_vm.private_img, self.vm.private_img))
  172. self._copy_file(src_vm.private_img, self.vm.private_img)
  173. if src_vm.updateable and hasattr(src_vm, 'root_img'):
  174. self.vm.log.info('Copying the root image: {} -> {}'.format(
  175. src_vm.root_img, self.root_img))
  176. self._copy_file(src_vm.root_img, self.root_img)
  177. # TODO: modules?
  178. # XXX which modules? -woju
  179. @staticmethod
  180. def rename(newpath, oldpath):
  181. '''Move storage directory, most likely during domain's rename.
  182. .. note::
  183. The arguments are in different order than in :program:`cp` utility.
  184. .. versionchange:: 4.0
  185. This is now dummy method that just passes everything to
  186. :py:func:`os.rename`.
  187. :param str newpath: New path
  188. :param str oldpath: Old path
  189. '''
  190. os.rename(oldpath, newpath)
  191. def verify_files(self):
  192. if not os.path.exists(self.vm.dir_path):
  193. raise qubes.exc.QubesVMError(self.vm,
  194. 'VM directory does not exist: {}'.format(self.vm.dir_path))
  195. if hasattr(self.vm, 'root_img') and not os.path.exists(self.root_img):
  196. raise qubes.exc.QubesVMError(self.vm,
  197. 'VM root image file does not exist: {}'.format(self.root_img))
  198. if hasattr(self.vm, 'private_img') \
  199. and not os.path.exists(self.private_img):
  200. raise qubes.exc.QubesVMError(self.vm,
  201. 'VM private image file does not exist: {}'.format(
  202. self.private_img))
  203. if self.modules_img is not None \
  204. and not os.path.exists(self.modules_img):
  205. raise qubes.exc.QubesVMError(self.vm,
  206. 'VM kernel modules image does not exists: {}'.format(
  207. self.modules_img))
  208. def remove_from_disk(self):
  209. shutil.rmtree(self.vm.dir_path)
  210. def reset_volatile_storage(self, source_template=None):
  211. if source_template is None:
  212. source_template = self.vm.template
  213. # Re-create only for template based VMs
  214. if source_template is not None and self.volatile_img:
  215. if os.path.exists(self.volatile_img):
  216. os.remove(self.volatile_img)
  217. # For StandaloneVM create it only if not already exists
  218. # (eg after backup-restore)
  219. if hasattr(self, 'volatile_img') \
  220. and not os.path.exists(self.vm.volatile_img):
  221. self.vm.log.info(
  222. 'Creating volatile image: {0}'.format(self.volatile_img))
  223. subprocess.check_call(
  224. [qubes.config.system_path["prepare_volatile_img_cmd"],
  225. self.volatile_img,
  226. str(self.root_img_size / 1024 / 1024)])
  227. def prepare_for_vm_startup(self):
  228. self.reset_volatile_storage()
  229. if hasattr(self.vm, 'private_img') \
  230. and not os.path.exists(self.private_img):
  231. self.vm.log.info('Creating empty VM private image file: {0}'.format(
  232. self.private_img))
  233. self.create_on_disk_private_img()
  234. def get_disk_usage_one(st):
  235. '''Extract disk usage of one inode from its stat_result struct.
  236. If known, get real disk usage, as written to device by filesystem, not
  237. logical file size. Those values may be different for sparse files.
  238. :param os.stat_result st: stat result
  239. :returns: disk usage
  240. '''
  241. try:
  242. return st.st_blocks * BLKSIZE
  243. except AttributeError:
  244. return st.st_size
  245. def get_disk_usage(path):
  246. '''Get real disk usage of given path (file or directory).
  247. When *path* points to directory, then it is evaluated recursively.
  248. This function tries estiate real disk usage. See documentation of
  249. :py:func:`get_disk_usage_one`.
  250. :param str path: path to evaluate
  251. :returns: disk usage
  252. '''
  253. try:
  254. st = os.lstat(path)
  255. except OSError:
  256. return 0
  257. ret = get_disk_usage_one(st)
  258. # if path is not a directory, this is skipped
  259. for dirpath, dirnames, filenames in os.walk(path):
  260. for name in dirnames + filenames:
  261. ret += get_disk_usage_one(os.lstat(os.path.join(dirpath, name)))
  262. return ret
  263. #def get_storage(vm):
  264. # '''Factory yielding storage class instances for domains.
  265. #
  266. # :raises ImportError: when storage class specified in config cannot be found
  267. # :raises KeyError: when storage class specified in config cannot be found
  268. # '''
  269. # pkg, cls = qubes.config.defaults['storage_class'].strip().rsplit('.', 1)
  270. #
  271. # # this may raise ImportError or KeyError, that's okay
  272. # return importlib.import_module(pkg).__dict__[cls](vm)
  273. def dump(o):
  274. """ Returns a string represention of the given object
  275. Args:
  276. o (object): anything that response to `__module__` and `__class__`
  277. Given the class :class:`qubes.storage.QubesVmStorage` it returns
  278. 'qubes.storage.QubesVmStorage' as string
  279. """
  280. return o.__module__ + '.' + o.__class__.__name__
  281. def load(string):
  282. """ Given a dotted full module string representation of a class it loads it
  283. Args:
  284. string (str) i.e. 'qubes.storage.xen.QubesXenVmStorage'
  285. Returns:
  286. type
  287. See also:
  288. :func:`qubes.storage.dump`
  289. """
  290. if not type(string) is str:
  291. # This is a hack which allows giving a real class to a vm instead of a
  292. # string as string_class parameter.
  293. return string
  294. components = string.split(".")
  295. module_path = ".".join(components[:-1])
  296. klass = components[-1:][0]
  297. module = __import__(module_path, fromlist=[klass])
  298. return getattr(module, klass)
  299. def get_pool(name, vm):
  300. """ Instantiates the storage for the specified vm """
  301. config = _get_storage_config_parser()
  302. klass = _get_pool_klass(name, config)
  303. keys = [k for k in config.options(name) if k != 'driver' and k != 'class']
  304. values = [config.get(name, o) for o in keys]
  305. config_kwargs = dict(zip(keys, values))
  306. if name == 'default':
  307. kwargs = defaults['pool_config'].copy()
  308. kwargs.update(keys)
  309. else:
  310. kwargs = config_kwargs
  311. return klass(vm, **kwargs)
  312. def pool_exists(name):
  313. """ Check if the specified pool exists """
  314. try:
  315. _get_pool_klass(name)
  316. return True
  317. except StoragePoolException:
  318. return False
  319. def add_pool(name, **kwargs):
  320. """ Add a storage pool to config."""
  321. config = _get_storage_config_parser()
  322. config.add_section(name)
  323. for key, value in kwargs.iteritems():
  324. config.set(name, key, value)
  325. _write_config(config)
  326. def remove_pool(name):
  327. """ Remove a storage pool from config file. """
  328. config = _get_storage_config_parser()
  329. config.remove_section(name)
  330. _write_config(config)
  331. def _write_config(config):
  332. with open(CONFIG_FILE, 'w') as configfile:
  333. config.write(configfile)
  334. def _get_storage_config_parser():
  335. """ Instantiates a `ConfigParaser` for specified storage config file.
  336. Returns:
  337. RawConfigParser
  338. """
  339. config = ConfigParser.RawConfigParser()
  340. config.read(CONFIG_FILE)
  341. return config
  342. def _get_pool_klass(name, config=None):
  343. """ Returns the storage klass for the specified pool.
  344. Args:
  345. name: The pool name.
  346. config: If ``config`` is not specified
  347. `_get_storage_config_parser()` is called.
  348. Returns:
  349. type: A class inheriting from `QubesVmStorage`
  350. """
  351. if config is None:
  352. config = _get_storage_config_parser()
  353. if not config.has_section(name):
  354. raise StoragePoolException('Uknown storage pool ' + name)
  355. if config.has_option(name, 'class'):
  356. klass = load(config.get(name, 'class'))
  357. elif config.has_option(name, 'driver'):
  358. pool_driver = config.get(name, 'driver')
  359. klass = defaults['pool_drivers'][pool_driver]
  360. else:
  361. raise StoragePoolException('Uknown storage pool driver ' + name)
  362. return klass
  363. class StoragePoolException(QubesException):
  364. pass
  365. class Pool(object):
  366. def __init__(self, vm, dir_path):
  367. assert vm is not None
  368. assert dir_path is not None
  369. self.vm = vm
  370. self.dir_path = dir_path
  371. self.create_dir_if_not_exists(self.dir_path)
  372. self.vmdir = self.vmdir_path(vm, self.dir_path)
  373. appvms_path = os.path.join(self.dir_path, 'appvms')
  374. self.create_dir_if_not_exists(appvms_path)
  375. servicevms_path = os.path.join(self.dir_path, 'servicevms')
  376. self.create_dir_if_not_exists(servicevms_path)
  377. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  378. self.create_dir_if_not_exists(vm_templates_path)
  379. def vmdir_path(self, vm, pool_dir):
  380. """ Returns the path to vmdir depending on the type of the VM.
  381. The default QubesOS file storage saves the vm images in three
  382. different directories depending on the ``QubesVM`` type:
  383. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  384. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  385. * ``servicevms`` for any subclass of ``QubesNetVm``
  386. Args:
  387. vm: a QubesVM
  388. pool_dir: the root directory of the pool
  389. Returns:
  390. string (str) absolute path to the directory where the vm files
  391. are stored
  392. """
  393. if vm.is_appvm():
  394. subdir = 'appvms'
  395. elif vm.is_template():
  396. subdir = 'vm-templates'
  397. elif vm.is_netvm():
  398. subdir = 'servicevms'
  399. elif vm.is_disposablevm():
  400. subdir = 'appvms'
  401. return os.path.join(pool_dir, subdir, vm.template.name + '-dvm')
  402. else:
  403. raise QubesException(vm.type() + ' unknown vm type')
  404. return os.path.join(pool_dir, subdir, vm.name)
  405. def create_dir_if_not_exists(self, path):
  406. """ Check if a directory exists in if not create it.
  407. This method does not create any parent directories.
  408. """
  409. if not os.path.exists(path):
  410. os.mkdir(path)