__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 ConfigParser
  27. import importlib
  28. import os
  29. import os.path
  30. import re
  31. import shutil
  32. import subprocess
  33. import sys
  34. import qubes
  35. import qubes.exc
  36. import qubes.utils
  37. BLKSIZE = 512
  38. CONFIG_FILE = '/etc/qubes/storage.conf'
  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 load(clsname):
  266. '''Given a dotted full module string representation of a class it loads it
  267. Args:
  268. string (str) i.e. 'qubes.storage.xen.QubesXenVmStorage'
  269. Returns:
  270. type
  271. See also:
  272. :func:`qubes.storage.dump`
  273. :raises ImportError: when storage class specified in config cannot be found
  274. :raises KeyError: when storage class specified in config cannot be found
  275. '''
  276. if not isinstance(clsname, basestring):
  277. return clsname
  278. pkg, cls = clsname.strip().rsplit('.', 1)
  279. # this may raise ImportError or KeyError, that's okay
  280. return importlib.import_module(pkg).__dict__[cls]
  281. def dump(o):
  282. """ Returns a string represention of the given object
  283. Args:
  284. o (object): anything that response to `__module__` and `__class__`
  285. Given the class :class:`qubes.storage.QubesVmStorage` it returns
  286. 'qubes.storage.QubesVmStorage' as string
  287. """
  288. return o.__module__ + '.' + o.__class__.__name__
  289. def get_pool(name, vm):
  290. """ Instantiates the storage for the specified vm """
  291. config = _get_storage_config_parser()
  292. klass = _get_pool_klass(name, config)
  293. keys = [k for k in config.options(name) if k != 'driver' and k != 'class']
  294. values = [config.get(name, o) for o in keys]
  295. config_kwargs = dict(zip(keys, values))
  296. if name == 'default':
  297. kwargs = qubes.config.defaults['pool_config'].copy()
  298. kwargs.update(keys)
  299. else:
  300. kwargs = config_kwargs
  301. return klass(vm, **kwargs)
  302. def pool_exists(name):
  303. """ Check if the specified pool exists """
  304. try:
  305. _get_pool_klass(name)
  306. return True
  307. except StoragePoolException:
  308. return False
  309. def add_pool(name, **kwargs):
  310. """ Add a storage pool to config."""
  311. config = _get_storage_config_parser()
  312. config.add_section(name)
  313. for key, value in kwargs.iteritems():
  314. config.set(name, key, value)
  315. _write_config(config)
  316. def remove_pool(name):
  317. """ Remove a storage pool from config file. """
  318. config = _get_storage_config_parser()
  319. config.remove_section(name)
  320. _write_config(config)
  321. def _write_config(config):
  322. with open(CONFIG_FILE, 'w') as configfile:
  323. config.write(configfile)
  324. def _get_storage_config_parser():
  325. """ Instantiates a `ConfigParaser` for specified storage config file.
  326. Returns:
  327. RawConfigParser
  328. """
  329. config = ConfigParser.RawConfigParser()
  330. config.read(CONFIG_FILE)
  331. return config
  332. def _get_pool_klass(name, config=None):
  333. """ Returns the storage klass for the specified pool.
  334. Args:
  335. name: The pool name.
  336. config: If ``config`` is not specified
  337. `_get_storage_config_parser()` is called.
  338. Returns:
  339. type: A class inheriting from `QubesVmStorage`
  340. """
  341. if config is None:
  342. config = _get_storage_config_parser()
  343. if not config.has_section(name):
  344. raise StoragePoolException('Uknown storage pool ' + name)
  345. if config.has_option(name, 'class'):
  346. klass = load(config.get(name, 'class'))
  347. elif config.has_option(name, 'driver'):
  348. pool_driver = config.get(name, 'driver')
  349. klass = load(qubes.config.defaults['pool_drivers'][pool_driver])
  350. else:
  351. raise StoragePoolException('Uknown storage pool driver ' + name)
  352. return klass
  353. class Pool(object):
  354. def __init__(self, vm, dir_path):
  355. assert vm is not None
  356. assert dir_path is not None
  357. self.vm = vm
  358. self.dir_path = dir_path
  359. self.create_dir_if_not_exists(self.dir_path)
  360. self.vmdir = self.vmdir_path(vm, self.dir_path)
  361. appvms_path = os.path.join(self.dir_path, 'appvms')
  362. self.create_dir_if_not_exists(appvms_path)
  363. servicevms_path = os.path.join(self.dir_path, 'servicevms')
  364. self.create_dir_if_not_exists(servicevms_path)
  365. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  366. self.create_dir_if_not_exists(vm_templates_path)
  367. # XXX there is also a class attribute on the domain classes which does
  368. # exactly that -- which one should prevail?
  369. def vmdir_path(self, vm, pool_dir):
  370. """ Returns the path to vmdir depending on the type of the VM.
  371. The default QubesOS file storage saves the vm images in three
  372. different directories depending on the ``QubesVM`` type:
  373. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  374. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  375. Args:
  376. vm: a QubesVM
  377. pool_dir: the root directory of the pool
  378. Returns:
  379. string (str) absolute path to the directory where the vm files
  380. are stored
  381. """
  382. if vm.is_template():
  383. subdir = 'vm-templates'
  384. elif vm.is_disposablevm():
  385. subdir = 'appvms'
  386. return os.path.join(pool_dir, subdir, vm.template.name + '-dvm')
  387. else:
  388. subdir = 'appvms'
  389. return os.path.join(pool_dir, subdir, vm.name)
  390. def create_dir_if_not_exists(self, path):
  391. """ Check if a directory exists in if not create it.
  392. This method does not create any parent directories.
  393. """
  394. if not os.path.exists(path):
  395. os.mkdir(path)