__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. #!/usr/bin/python2
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2013 Marek Marczykowski <marmarek@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU General Public License
  9. # as published by the Free Software Foundation; either version 2
  10. # of the License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
  20. # USA.
  21. #
  22. from __future__ import absolute_import
  23. import ConfigParser
  24. import os
  25. import os.path
  26. import shutil
  27. import subprocess
  28. import sys
  29. import qubes.qubesutils
  30. from qubes.qubes import QubesException, defaults, system_path
  31. CONFIG_FILE = '/etc/qubes/storage.conf'
  32. class QubesVmStorage(object):
  33. """
  34. Class for handling VM virtual disks. This is base class for all other
  35. implementations, mostly with Xen on Linux in mind.
  36. """
  37. def __init__(self, vm,
  38. private_img_size = None,
  39. root_img_size = None,
  40. modules_img = None,
  41. modules_img_rw = False):
  42. self.vm = vm
  43. self.vmdir = vm.dir_path
  44. if private_img_size:
  45. self.private_img_size = private_img_size
  46. else:
  47. self.private_img_size = defaults['private_img_size']
  48. if root_img_size:
  49. self.root_img_size = root_img_size
  50. else:
  51. self.root_img_size = defaults['root_img_size']
  52. self.root_dev = "xvda"
  53. self.private_dev = "xvdb"
  54. self.volatile_dev = "xvdc"
  55. self.modules_dev = "xvdd"
  56. # For now compute this path still in QubesVm
  57. self.modules_img = modules_img
  58. self.modules_img_rw = modules_img_rw
  59. # Additional drive (currently used only by HVM)
  60. self.drive = None
  61. def format_disk_dev(self, path, script, vdev, rw=True, type="disk",
  62. domain=None):
  63. if path is None:
  64. return ''
  65. template = " <disk type='block' device='{type}'>\n" \
  66. " <driver name='phy'/>\n" \
  67. " <source dev='{path}'/>\n" \
  68. " <target dev='{vdev}' bus='xen'/>\n" \
  69. "{params}" \
  70. " </disk>\n"
  71. params = ""
  72. if not rw:
  73. params += " <readonly/>\n"
  74. if domain:
  75. params += " <backenddomain name='%s'/>\n" % domain
  76. if script:
  77. params += " <script path='%s'/>\n" % script
  78. return template.format(path=path, vdev=vdev, type=type, params=params)
  79. def get_config_params(self):
  80. raise NotImplementedError
  81. def _copy_file(self, source, destination):
  82. """
  83. Effective file copy, preserving sparse files etc.
  84. """
  85. # TODO: Windows support
  86. # We prefer to use Linux's cp, because it nicely handles sparse files
  87. retcode = subprocess.call (["cp", "--reflink=auto", source, destination])
  88. if retcode != 0:
  89. raise IOError ("Error while copying {0} to {1}".\
  90. format(source, destination))
  91. def get_disk_utilization(self):
  92. return qubes.qubesutils.get_disk_usage(self.vmdir)
  93. def get_disk_utilization_private_img(self):
  94. return qubes.qubesutils.get_disk_usage(self.private_img)
  95. def get_private_img_sz(self):
  96. if not os.path.exists(self.private_img):
  97. return 0
  98. return os.path.getsize(self.private_img)
  99. def resize_private_img(self, size):
  100. raise NotImplementedError
  101. def create_on_disk_private_img(self, verbose, source_template = None):
  102. raise NotImplementedError
  103. def create_on_disk_root_img(self, verbose, source_template = None):
  104. raise NotImplementedError
  105. def create_on_disk(self, verbose, source_template = None):
  106. if source_template is None:
  107. source_template = self.vm.template
  108. old_umask = os.umask(002)
  109. if verbose:
  110. print >> sys.stderr, "--> Creating directory: {0}".format(self.vmdir)
  111. os.mkdir (self.vmdir)
  112. self.create_on_disk_private_img(verbose, source_template)
  113. self.create_on_disk_root_img(verbose, source_template)
  114. self.reset_volatile_storage(verbose, source_template)
  115. os.umask(old_umask)
  116. def clone_disk_files(self, src_vm, verbose):
  117. if verbose:
  118. print >> sys.stderr, "--> Creating directory: {0}".format(self.vmdir)
  119. os.mkdir (self.vmdir)
  120. if src_vm.private_img is not None and self.private_img is not None:
  121. if verbose:
  122. print >> sys.stderr, "--> Copying the private image:\n{0} ==>\n{1}".\
  123. format(src_vm.private_img, self.private_img)
  124. self._copy_file(src_vm.private_img, self.private_img)
  125. if src_vm.updateable and src_vm.root_img is not None and self.root_img is not None:
  126. if verbose:
  127. print >> sys.stderr, "--> Copying the root image:\n{0} ==>\n{1}".\
  128. format(src_vm.root_img, self.root_img)
  129. self._copy_file(src_vm.root_img, self.root_img)
  130. # TODO: modules?
  131. def rename(self, old_name, new_name):
  132. old_vmdir = self.vmdir
  133. new_vmdir = os.path.join(os.path.dirname(self.vmdir), new_name)
  134. os.rename(self.vmdir, new_vmdir)
  135. self.vmdir = new_vmdir
  136. if self.private_img:
  137. self.private_img = self.private_img.replace(old_vmdir, new_vmdir)
  138. if self.root_img:
  139. self.root_img = self.root_img.replace(old_vmdir, new_vmdir)
  140. if self.volatile_img:
  141. self.volatile_img = self.volatile_img.replace(old_vmdir, new_vmdir)
  142. def verify_files(self):
  143. if not os.path.exists (self.vmdir):
  144. raise QubesException (
  145. "VM directory doesn't exist: {0}".\
  146. format(self.vmdir))
  147. if self.root_img and not os.path.exists (self.root_img):
  148. raise QubesException (
  149. "VM root image file doesn't exist: {0}".\
  150. format(self.root_img))
  151. if self.private_img and not os.path.exists (self.private_img):
  152. raise QubesException (
  153. "VM private image file doesn't exist: {0}".\
  154. format(self.private_img))
  155. if self.modules_img is not None:
  156. if not os.path.exists(self.modules_img):
  157. raise QubesException (
  158. "VM kernel modules image does not exists: {0}".\
  159. format(self.modules_img))
  160. def remove_from_disk(self):
  161. shutil.rmtree (self.vmdir)
  162. def reset_volatile_storage(self, verbose = False, source_template = None):
  163. if source_template is None:
  164. source_template = self.vm.template
  165. # Re-create only for template based VMs
  166. if source_template is not None and self.volatile_img:
  167. if os.path.exists(self.volatile_img):
  168. os.remove(self.volatile_img)
  169. # For StandaloneVM create it only if not already exists (eg after backup-restore)
  170. if self.volatile_img and not os.path.exists(self.volatile_img):
  171. if verbose:
  172. print >> sys.stderr, "--> Creating volatile image: {0}...".\
  173. format(self.volatile_img)
  174. subprocess.check_call([system_path["prepare_volatile_img_cmd"],
  175. self.volatile_img, str(self.root_img_size / 1024 / 1024)])
  176. def prepare_for_vm_startup(self, verbose):
  177. self.reset_volatile_storage(verbose=verbose)
  178. if self.private_img and not os.path.exists (self.private_img):
  179. print >>sys.stderr, "WARNING: Creating empty VM private image file: {0}".\
  180. format(self.private_img)
  181. self.create_on_disk_private_img(verbose=False)
  182. def dump(o):
  183. """ Returns a string represention of the given object
  184. Args:
  185. o (object): anything that response to `__module__` and `__class__`
  186. Given the class :class:`qubes.storage.QubesVmStorage` it returns
  187. 'qubes.storage.QubesVmStorage' as string
  188. """
  189. return o.__module__ + '.' + o.__class__.__name__
  190. def load(string):
  191. """ Given a dotted full module string representation of a class it loads it
  192. Args:
  193. string (str) i.e. 'qubes.storage.xen.QubesXenVmStorage'
  194. Returns:
  195. type
  196. See also:
  197. :func:`qubes.storage.dump`
  198. """
  199. if not type(string) is str:
  200. # This is a hack which allows giving a real class to a vm instead of a
  201. # string as string_class parameter.
  202. return string
  203. components = string.split(".")
  204. module_path = ".".join(components[:-1])
  205. klass = components[-1:][0]
  206. module = __import__(module_path, fromlist=[klass])
  207. return getattr(module, klass)
  208. def get_pool(name, vm):
  209. """ Instantiates the storage for the specified vm """
  210. config = _get_storage_config_parser()
  211. klass = _get_pool_klass(name, config)
  212. keys = [k for k in config.options(name) if k != 'driver' and k != 'class']
  213. values = [config.get(name, o) for o in keys]
  214. config_kwargs = dict(zip(keys, values))
  215. if name == 'default':
  216. kwargs = defaults['pool_config'].copy()
  217. kwargs.update(keys)
  218. else:
  219. kwargs = config_kwargs
  220. return klass(vm, **kwargs)
  221. def pool_exists(name):
  222. """ Check if the specified pool exists """
  223. try:
  224. _get_pool_klass(name)
  225. return True
  226. except StoragePoolException:
  227. return False
  228. def add_pool(name, **kwargs):
  229. """ Add a storage pool to config."""
  230. config = _get_storage_config_parser()
  231. config.add_section(name)
  232. for key, value in kwargs.iteritems():
  233. config.set(name, key, value)
  234. _write_config(config)
  235. def remove_pool(name):
  236. """ Remove a storage pool from config file. """
  237. config = _get_storage_config_parser()
  238. config.remove_section(name)
  239. _write_config(config)
  240. def _write_config(config):
  241. with open(CONFIG_FILE, 'w') as configfile:
  242. config.write(configfile)
  243. def _get_storage_config_parser():
  244. """ Instantiates a `ConfigParaser` for specified storage config file.
  245. Returns:
  246. RawConfigParser
  247. """
  248. config = ConfigParser.RawConfigParser()
  249. config.read(CONFIG_FILE)
  250. return config
  251. def _get_pool_klass(name, config=None):
  252. """ Returns the storage klass for the specified pool.
  253. Args:
  254. name: The pool name.
  255. config: If ``config`` is not specified
  256. `_get_storage_config_parser()` is called.
  257. Returns:
  258. type: A class inheriting from `QubesVmStorage`
  259. """
  260. if config is None:
  261. config = _get_storage_config_parser()
  262. if not config.has_section(name):
  263. raise StoragePoolException('Uknown storage pool ' + name)
  264. if config.has_option(name, 'class'):
  265. klass = load(config.get(name, 'class'))
  266. elif config.has_option(name, 'driver'):
  267. pool_driver = config.get(name, 'driver')
  268. klass = defaults['pool_drivers'][pool_driver]
  269. else:
  270. raise StoragePoolException('Uknown storage pool driver ' + name)
  271. return klass
  272. class StoragePoolException(QubesException):
  273. pass
  274. class Pool(object):
  275. def __init__(self, vm, dir_path):
  276. assert vm is not None
  277. assert dir_path is not None
  278. self.vm = vm
  279. self.dir_path = dir_path
  280. self.create_dir_if_not_exists(self.dir_path)
  281. self.vmdir = self.vmdir_path(vm, self.dir_path)
  282. appvms_path = os.path.join(self.dir_path, 'appvms')
  283. self.create_dir_if_not_exists(appvms_path)
  284. servicevms_path = os.path.join(self.dir_path, 'servicevms')
  285. self.create_dir_if_not_exists(servicevms_path)
  286. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  287. self.create_dir_if_not_exists(vm_templates_path)
  288. def vmdir_path(self, vm, pool_dir):
  289. """ Returns the path to vmdir depending on the type of the VM.
  290. The default QubesOS file storage saves the vm images in three
  291. different directories depending on the ``QubesVM`` type:
  292. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  293. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  294. * ``servicevms`` for any subclass of ``QubesNetVm``
  295. Args:
  296. vm: a QubesVM
  297. pool_dir: the root directory of the pool
  298. Returns:
  299. string (str) absolute path to the directory where the vm files
  300. are stored
  301. """
  302. if vm.is_appvm():
  303. subdir = 'appvms'
  304. elif vm.is_template():
  305. subdir = 'vm-templates'
  306. elif vm.is_netvm():
  307. subdir = 'servicevms'
  308. elif vm.is_disposablevm():
  309. subdir = 'appvms'
  310. return os.path.join(pool_dir, subdir, vm.template.name + '-dvm')
  311. else:
  312. raise QubesException(vm.type() + ' unknown vm type')
  313. return os.path.join(pool_dir, subdir, vm.name)
  314. def create_dir_if_not_exists(self, path):
  315. """ Check if a directory exists in if not create it.
  316. This method does not create any parent directories.
  317. """
  318. if not os.path.exists(path):
  319. os.mkdir(path)