__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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:
  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(source_template)
  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, source_template=None):
  212. if source_template is None:
  213. source_template = self.vm.template
  214. # Re-create only for template based VMs
  215. if source_template is not None and self.volatile_img:
  216. if os.path.exists(self.volatile_img):
  217. os.remove(self.volatile_img)
  218. # For StandaloneVM create it only if not already exists
  219. # (eg after backup-restore)
  220. if hasattr(self, 'volatile_img') \
  221. and not os.path.exists(self.vm.volatile_img):
  222. self.vm.log.info(
  223. 'Creating volatile image: {0}'.format(self.volatile_img))
  224. subprocess.check_call(
  225. [qubes.config.system_path["prepare_volatile_img_cmd"],
  226. self.volatile_img,
  227. str(self.root_img_size / 1024 / 1024)])
  228. def prepare_for_vm_startup(self):
  229. self.reset_volatile_storage()
  230. if hasattr(self.vm, 'private_img') \
  231. and not os.path.exists(self.private_img):
  232. self.vm.log.info('Creating empty VM private image file: {0}'.format(
  233. self.private_img))
  234. self.create_on_disk_private_img()
  235. def get_disk_usage_one(st):
  236. '''Extract disk usage of one inode from its stat_result struct.
  237. If known, get real disk usage, as written to device by filesystem, not
  238. logical file size. Those values may be different for sparse files.
  239. :param os.stat_result st: stat result
  240. :returns: disk usage
  241. '''
  242. try:
  243. return st.st_blocks * BLKSIZE
  244. except AttributeError:
  245. return st.st_size
  246. def get_disk_usage(path):
  247. '''Get real disk usage of given path (file or directory).
  248. When *path* points to directory, then it is evaluated recursively.
  249. This function tries estiate real disk usage. See documentation of
  250. :py:func:`get_disk_usage_one`.
  251. :param str path: path to evaluate
  252. :returns: disk usage
  253. '''
  254. try:
  255. st = os.lstat(path)
  256. except OSError:
  257. return 0
  258. ret = get_disk_usage_one(st)
  259. # if path is not a directory, this is skipped
  260. for dirpath, dirnames, filenames in os.walk(path):
  261. for name in dirnames + filenames:
  262. ret += get_disk_usage_one(os.lstat(os.path.join(dirpath, name)))
  263. return ret
  264. def load(clsname):
  265. '''Given a dotted full module string representation of a class it loads it
  266. Args:
  267. string (str) i.e. 'qubes.storage.xen.QubesXenVmStorage'
  268. Returns:
  269. type
  270. See also:
  271. :func:`qubes.storage.dump`
  272. :raises ImportError: when storage class specified in config cannot be found
  273. :raises KeyError: when storage class specified in config cannot be found
  274. '''
  275. if not isinstance(clsname, basestring):
  276. return clsname
  277. pkg, cls = clsname.strip().rsplit('.', 1)
  278. # this may raise ImportError or KeyError, that's okay
  279. return importlib.import_module(pkg).__dict__[cls]
  280. def dump(o):
  281. """ Returns a string represention of the given object
  282. Args:
  283. o (object): anything that response to `__module__` and `__class__`
  284. Given the class :class:`qubes.storage.QubesVmStorage` it returns
  285. 'qubes.storage.QubesVmStorage' as string
  286. """
  287. return o.__module__ + '.' + o.__class__.__name__
  288. def get_pool(name, vm):
  289. """ Instantiates the storage for the specified vm """
  290. config = _get_storage_config_parser()
  291. klass = _get_pool_klass(name, config)
  292. keys = [k for k in config.options(name) if k != 'driver' and k != 'class']
  293. values = [config.get(name, o) for o in keys]
  294. config_kwargs = dict(zip(keys, values))
  295. if name == 'default':
  296. kwargs = qubes.config.defaults['pool_config'].copy()
  297. kwargs.update(keys)
  298. else:
  299. kwargs = config_kwargs
  300. return klass(vm, **kwargs)
  301. def pool_exists(name):
  302. """ Check if the specified pool exists """
  303. try:
  304. _get_pool_klass(name)
  305. return True
  306. except StoragePoolException:
  307. return False
  308. def add_pool(name, **kwargs):
  309. """ Add a storage pool to config."""
  310. config = _get_storage_config_parser()
  311. config.add_section(name)
  312. for key, value in kwargs.iteritems():
  313. config.set(name, key, value)
  314. _write_config(config)
  315. def remove_pool(name):
  316. """ Remove a storage pool from config file. """
  317. config = _get_storage_config_parser()
  318. config.remove_section(name)
  319. _write_config(config)
  320. def _write_config(config):
  321. with open(CONFIG_FILE, 'w') as configfile:
  322. config.write(configfile)
  323. def _get_storage_config_parser():
  324. """ Instantiates a `ConfigParaser` for specified storage config file.
  325. Returns:
  326. RawConfigParser
  327. """
  328. config = ConfigParser.RawConfigParser()
  329. config.read(CONFIG_FILE)
  330. return config
  331. def _get_pool_klass(name, config=None):
  332. """ Returns the storage klass for the specified pool.
  333. Args:
  334. name: The pool name.
  335. config: If ``config`` is not specified
  336. `_get_storage_config_parser()` is called.
  337. Returns:
  338. type: A class inheriting from `QubesVmStorage`
  339. """
  340. if config is None:
  341. config = _get_storage_config_parser()
  342. if not config.has_section(name):
  343. raise StoragePoolException('Uknown storage pool ' + name)
  344. if config.has_option(name, 'class'):
  345. klass = load(config.get(name, 'class'))
  346. elif config.has_option(name, 'driver'):
  347. pool_driver = config.get(name, 'driver')
  348. klass = qubes.config.defaults['pool_drivers'][pool_driver]
  349. else:
  350. raise StoragePoolException('Uknown storage pool driver ' + name)
  351. return klass
  352. class Pool(object):
  353. def __init__(self, vm, dir_path):
  354. assert vm is not None
  355. assert dir_path is not None
  356. self.vm = vm
  357. self.dir_path = dir_path
  358. self.create_dir_if_not_exists(self.dir_path)
  359. self.vmdir = self.vmdir_path(vm, self.dir_path)
  360. appvms_path = os.path.join(self.dir_path, 'appvms')
  361. self.create_dir_if_not_exists(appvms_path)
  362. servicevms_path = os.path.join(self.dir_path, 'servicevms')
  363. self.create_dir_if_not_exists(servicevms_path)
  364. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  365. self.create_dir_if_not_exists(vm_templates_path)
  366. # XXX there is also a class attribute on the domain classes which does
  367. # exactly that -- which one should prevail?
  368. def vmdir_path(self, vm, pool_dir):
  369. """ Returns the path to vmdir depending on the type of the VM.
  370. The default QubesOS file storage saves the vm images in three
  371. different directories depending on the ``QubesVM`` type:
  372. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  373. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  374. * ``servicevms`` for any subclass of ``QubesNetVm``
  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_appvm():
  383. subdir = 'appvms'
  384. elif vm.is_template():
  385. subdir = 'vm-templates'
  386. elif vm.is_netvm():
  387. subdir = 'servicevms'
  388. elif vm.is_disposablevm():
  389. subdir = 'appvms'
  390. return os.path.join(pool_dir, subdir, vm.template.name + '-dvm')
  391. else:
  392. raise qubes.exc.QubesException(
  393. 'unknown vm type: {!r}'.format(vm.type()))
  394. return os.path.join(pool_dir, subdir, vm.name)
  395. def create_dir_if_not_exists(self, path):
  396. """ Check if a directory exists in if not create it.
  397. This method does not create any parent directories.
  398. """
  399. if not os.path.exists(path):
  400. os.mkdir(path)