file.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. ''' This module contains pool implementations backed by file images'''
  24. from __future__ import absolute_import
  25. import os
  26. import os.path
  27. import re
  28. import subprocess
  29. import qubes.storage
  30. BLKSIZE = 512
  31. class FilePool(qubes.storage.Pool):
  32. ''' File based 'original' disk implementation
  33. Volumes are stored in sparse files. Additionally device-mapper is used for
  34. applying copy-on-write layer.
  35. Quick reference on device-mapper layers:
  36. snap_on_start save_on_stop layout
  37. yes yes not supported
  38. no yes snapshot-origin(volume.img, volume-cow.img)
  39. yes no snapshot(
  40. snapshot(source.img, source-cow.img),
  41. volume-cow.img)
  42. no no volume.img directly
  43. ''' # pylint: disable=protected-access
  44. driver = 'file'
  45. def __init__(self, revisions_to_keep=1, dir_path=None, **kwargs):
  46. super(FilePool, self).__init__(revisions_to_keep=revisions_to_keep,
  47. **kwargs)
  48. assert dir_path, "No pool dir_path specified"
  49. self.dir_path = os.path.normpath(dir_path)
  50. self._volumes = []
  51. @property
  52. def config(self):
  53. return {
  54. 'name': self.name,
  55. 'dir_path': self.dir_path,
  56. 'driver': FilePool.driver,
  57. 'revisions_to_keep': self.revisions_to_keep
  58. }
  59. def init_volume(self, vm, volume_config):
  60. if volume_config.get('snap_on_start', False) and \
  61. volume_config.get('save_on_stop', False):
  62. raise NotImplementedError(
  63. 'snap_on_start + save_on_stop not supported by file driver')
  64. volume_config['dir_path'] = self.dir_path
  65. if 'vid' not in volume_config:
  66. volume_config['vid'] = os.path.join(
  67. self._vid_prefix(vm), volume_config['name'])
  68. try:
  69. if not volume_config.get('save_on_stop', False):
  70. volume_config['revisions_to_keep'] = 0
  71. except KeyError:
  72. pass
  73. finally:
  74. if 'revisions_to_keep' not in volume_config:
  75. volume_config['revisions_to_keep'] = self.revisions_to_keep
  76. if int(volume_config['revisions_to_keep']) > 1:
  77. raise NotImplementedError(
  78. 'FilePool supports maximum 1 volume revision to keep')
  79. volume_config['pool'] = self
  80. volume = FileVolume(**volume_config)
  81. self._volumes += [volume]
  82. return volume
  83. def destroy(self):
  84. pass
  85. def setup(self):
  86. create_dir_if_not_exists(self.dir_path)
  87. appvms_path = os.path.join(self.dir_path, 'appvms')
  88. create_dir_if_not_exists(appvms_path)
  89. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  90. create_dir_if_not_exists(vm_templates_path)
  91. @staticmethod
  92. def _vid_prefix(vm):
  93. ''' Helper to create a prefix for the vid for volume
  94. ''' # FIX Remove this if we drop the file backend
  95. import qubes.vm.templatevm # pylint: disable=redefined-outer-name
  96. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  97. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  98. subdir = 'vm-templates'
  99. else:
  100. subdir = 'appvms'
  101. return os.path.join(subdir, vm.name)
  102. def target_dir(self, vm):
  103. """ Returns the path to vmdir depending on the type of the VM.
  104. The default QubesOS file storage saves the vm images in three
  105. different directories depending on the ``QubesVM`` type:
  106. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  107. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  108. Args:
  109. vm: a QubesVM
  110. pool_dir: the root directory of the pool
  111. Returns:
  112. string (str) absolute path to the directory where the vm files
  113. are stored
  114. """
  115. return os.path.join(self.dir_path, self._vid_prefix(vm))
  116. def list_volumes(self):
  117. return self._volumes
  118. class FileVolume(qubes.storage.Volume):
  119. ''' Parent class for the xen volumes implementation which expects a
  120. `target_dir` param on initialization. '''
  121. def __init__(self, dir_path, **kwargs):
  122. self.dir_path = dir_path
  123. assert self.dir_path, "dir_path not specified"
  124. super(FileVolume, self).__init__(**kwargs)
  125. if self.snap_on_start:
  126. img_name = self.source.vid + '-cow.img'
  127. self.path_source_cow = os.path.join(self.dir_path, img_name)
  128. def create(self):
  129. assert isinstance(self.size, int) and self.size > 0, \
  130. 'Volume size must be > 0'
  131. if not self.snap_on_start:
  132. create_sparse_file(self.path, self.size)
  133. def remove(self):
  134. if not self.snap_on_start:
  135. _remove_if_exists(self.path)
  136. if self.snap_on_start or self.save_on_stop:
  137. _remove_if_exists(self.path_cow)
  138. def is_dirty(self):
  139. if not self.save_on_stop:
  140. return False
  141. if os.path.exists(self.path_cow):
  142. stat = os.stat(self.path_cow)
  143. return stat.st_blocks > 0
  144. return False
  145. def resize(self, size):
  146. ''' Expands volume, throws
  147. :py:class:`qubst.storage.qubes.storage.StoragePoolException` if
  148. given size is less than current_size
  149. ''' # pylint: disable=no-self-use
  150. if not self.rw:
  151. msg = 'Can not resize reađonly volume {!s}'.format(self)
  152. raise qubes.storage.StoragePoolException(msg)
  153. if size < self.size:
  154. raise qubes.storage.StoragePoolException(
  155. 'For your own safety, shrinking of %s is'
  156. ' disabled. If you really know what you'
  157. ' are doing, use `truncate` on %s manually.' %
  158. (self.name, self.vid))
  159. with open(self.path, 'a+b') as fd:
  160. fd.truncate(size)
  161. p = subprocess.Popen(['losetup', '--associated', self.path],
  162. stdout=subprocess.PIPE)
  163. result = p.communicate()
  164. m = re.match(r'^(/dev/loop\d+):\s', result[0].decode())
  165. if m is not None:
  166. loop_dev = m.group(1)
  167. # resize loop device
  168. subprocess.check_call(['losetup', '--set-capacity',
  169. loop_dev])
  170. self.size = size
  171. def commit(self):
  172. msg = 'Tried to commit a non commitable volume {!r}'.format(self)
  173. assert self.save_on_stop and self.rw, msg
  174. if os.path.exists(self.path_cow):
  175. if self.revisions_to_keep:
  176. old_path = self.path_cow + '.old'
  177. os.rename(self.path_cow, old_path)
  178. else:
  179. os.unlink(self.path_cow)
  180. create_sparse_file(self.path_cow, self.size)
  181. return self
  182. def export(self):
  183. # FIXME: this should rather return snapshot(self.path, self.path_cow)
  184. # if domain is running
  185. return self.path
  186. def import_volume(self, src_volume):
  187. msg = "Can not import snapshot volume {!s} in to pool {!s} "
  188. msg = msg.format(src_volume, self)
  189. assert not src_volume.snap_on_start, msg
  190. if self.save_on_stop:
  191. _remove_if_exists(self.path)
  192. copy_file(src_volume.export(), self.path)
  193. return self
  194. def import_data(self):
  195. return self.path
  196. def reset(self):
  197. ''' Remove and recreate a volatile volume '''
  198. assert not self.snap_on_start and not self.save_on_stop, \
  199. "Not a volatile volume"
  200. assert isinstance(self.size, int) and self.size > 0, \
  201. 'Volatile volume size must be > 0'
  202. _remove_if_exists(self.path)
  203. create_sparse_file(self.path, self.size)
  204. return self
  205. def start(self):
  206. if not self.save_on_stop and not self.snap_on_start:
  207. self.reset()
  208. else:
  209. if not self.save_on_stop:
  210. # make sure previous snapshot is removed - even if VM
  211. # shutdown routine wasn't called (power interrupt or so)
  212. _remove_if_exists(self.path_cow)
  213. if not os.path.exists(self.path_cow):
  214. create_sparse_file(self.path_cow, self.size)
  215. if not self.snap_on_start:
  216. _check_path(self.path)
  217. if hasattr(self, 'path_source_cow'):
  218. if not os.path.exists(self.path_source_cow):
  219. create_sparse_file(self.path_source_cow, self.size)
  220. return self
  221. def stop(self):
  222. if self.save_on_stop:
  223. self.commit()
  224. elif self.snap_on_start:
  225. _remove_if_exists(self.path_cow)
  226. else:
  227. _remove_if_exists(self.path)
  228. return self
  229. @property
  230. def path(self):
  231. if self.snap_on_start:
  232. return os.path.join(self.dir_path, self.source.vid + '.img')
  233. return os.path.join(self.dir_path, self.vid + '.img')
  234. @property
  235. def path_cow(self):
  236. img_name = self.vid + '-cow.img'
  237. return os.path.join(self.dir_path, img_name)
  238. def verify(self):
  239. ''' Verifies the volume. '''
  240. if not os.path.exists(self.path) and \
  241. (self.snap_on_start or self.save_on_stop):
  242. msg = 'Missing image file: {!s}.'.format(self.path)
  243. raise qubes.storage.StoragePoolException(msg)
  244. return True
  245. @property
  246. def script(self):
  247. if not self.snap_on_start and not self.save_on_stop:
  248. return None
  249. elif not self.snap_on_start and self.save_on_stop:
  250. return 'block-origin'
  251. elif self.snap_on_start:
  252. return 'block-snapshot'
  253. def block_device(self):
  254. ''' Return :py:class:`qubes.storage.BlockDevice` for serialization in
  255. the libvirt XML template as <disk>.
  256. '''
  257. path = self.path
  258. if self.snap_on_start:
  259. path += ":" + self.path_source_cow
  260. if self.snap_on_start or self.save_on_stop:
  261. path += ":" + self.path_cow
  262. return qubes.storage.BlockDevice(path, self.name, self.script, self.rw,
  263. self.domain, self.devtype)
  264. @property
  265. def revisions(self):
  266. if not hasattr(self, 'path_cow'):
  267. return {}
  268. old_revision = self.path_cow + '.old' # pylint: disable=no-member
  269. if not os.path.exists(old_revision):
  270. return {}
  271. seconds = os.path.getctime(old_revision)
  272. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  273. return {'old': iso_date}
  274. @property
  275. def usage(self):
  276. ''' Returns the actualy used space '''
  277. usage = 0
  278. if self.save_on_stop or self.snap_on_start:
  279. usage = get_disk_usage(self.path_cow)
  280. if self.save_on_stop or not self.snap_on_start:
  281. usage += get_disk_usage(self.path)
  282. return usage
  283. def create_sparse_file(path, size):
  284. ''' Create an empty sparse file '''
  285. if os.path.exists(path):
  286. raise IOError("Volume %s already exists", path)
  287. parent_dir = os.path.dirname(path)
  288. if not os.path.exists(parent_dir):
  289. os.makedirs(parent_dir)
  290. with open(path, 'a+b') as fh:
  291. fh.truncate(size)
  292. def get_disk_usage_one(st):
  293. '''Extract disk usage of one inode from its stat_result struct.
  294. If known, get real disk usage, as written to device by filesystem, not
  295. logical file size. Those values may be different for sparse files.
  296. :param os.stat_result st: stat result
  297. :returns: disk usage
  298. '''
  299. try:
  300. return st.st_blocks * BLKSIZE
  301. except AttributeError:
  302. return st.st_size
  303. def get_disk_usage(path):
  304. '''Get real disk usage of given path (file or directory).
  305. When *path* points to directory, then it is evaluated recursively.
  306. This function tries estimate real disk usage. See documentation of
  307. :py:func:`get_disk_usage_one`.
  308. :param str path: path to evaluate
  309. :returns: disk usage
  310. '''
  311. try:
  312. st = os.lstat(path)
  313. except OSError:
  314. return 0
  315. ret = get_disk_usage_one(st)
  316. # if path is not a directory, this is skipped
  317. for dirpath, dirnames, filenames in os.walk(path):
  318. for name in dirnames + filenames:
  319. ret += get_disk_usage_one(os.lstat(os.path.join(dirpath, name)))
  320. return ret
  321. def create_dir_if_not_exists(path):
  322. """ Check if a directory exists in if not create it.
  323. This method does not create any parent directories.
  324. """
  325. if not os.path.exists(path):
  326. os.mkdir(path)
  327. def copy_file(source, destination):
  328. '''Effective file copy, preserving sparse files etc.'''
  329. # We prefer to use Linux's cp, because it nicely handles sparse files
  330. assert os.path.exists(source), \
  331. "Missing the source %s to copy from" % source
  332. assert not os.path.exists(destination), \
  333. "Destination %s already exists" % destination
  334. parent_dir = os.path.dirname(destination)
  335. if not os.path.exists(parent_dir):
  336. os.makedirs(parent_dir)
  337. try:
  338. cmd = ['cp', '--sparse=auto',
  339. '--reflink=auto', source, destination]
  340. subprocess.check_call(cmd)
  341. except subprocess.CalledProcessError:
  342. raise IOError('Error while copying {!r} to {!r}'.format(source,
  343. destination))
  344. def _remove_if_exists(path):
  345. ''' Removes a file if it exist, silently succeeds if file does not exist '''
  346. if os.path.exists(path):
  347. os.remove(path)
  348. def _check_path(path):
  349. ''' Raise an StoragePoolException if ``path`` does not exist'''
  350. if not os.path.exists(path):
  351. msg = 'Missing image file: %s' % path
  352. raise qubes.storage.StoragePoolException(msg)