reflink.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2018 Rusty Bird <rustybird@net-c.com>
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  18. #
  19. ''' Driver for handling VM images as files, without any device-mapper
  20. involvement. A reflink-capable filesystem is strongly recommended,
  21. but not required.
  22. '''
  23. import collections
  24. import errno
  25. import fcntl
  26. import glob
  27. import logging
  28. import os
  29. import re
  30. import subprocess
  31. import tempfile
  32. from contextlib import contextmanager, suppress
  33. import qubes.storage
  34. BLKSIZE = 512
  35. FICLONE = 1074041865 # see ioctl_ficlone manpage
  36. LOGGER = logging.getLogger('qubes.storage.reflink')
  37. class ReflinkPool(qubes.storage.Pool):
  38. driver = 'file-reflink'
  39. _known_dir_path_prefixes = ['appvms', 'vm-templates']
  40. def __init__(self, dir_path, setup_check='yes', revisions_to_keep=1,
  41. **kwargs):
  42. super().__init__(revisions_to_keep=revisions_to_keep, **kwargs)
  43. self._volumes = {}
  44. self.dir_path = os.path.abspath(dir_path)
  45. self.setup_check = qubes.property.bool(None, None, setup_check)
  46. def setup(self):
  47. created = _make_dir(self.dir_path)
  48. if self.setup_check and not is_reflink_supported(self.dir_path):
  49. if created:
  50. _remove_empty_dir(self.dir_path)
  51. raise qubes.storage.StoragePoolException(
  52. 'The filesystem for {!r} does not support reflinks. If you'
  53. ' can live with VM startup delays and wasted disk space, pass'
  54. ' the "setup_check=no" option.'.format(self.dir_path))
  55. for dir_path_prefix in self._known_dir_path_prefixes:
  56. _make_dir(os.path.join(self.dir_path, dir_path_prefix))
  57. return self
  58. def init_volume(self, vm, volume_config):
  59. # Fail closed on any strange VM dir_path_prefix, just in case
  60. # /etc/udev/rules/00-qubes-ignore-devices.rules needs updating
  61. assert vm.dir_path_prefix in self._known_dir_path_prefixes, \
  62. 'Unknown dir_path_prefix {!r}'.format(vm.dir_path_prefix)
  63. volume_config['pool'] = self
  64. if 'revisions_to_keep' not in volume_config:
  65. volume_config['revisions_to_keep'] = self.revisions_to_keep
  66. if 'vid' not in volume_config:
  67. volume_config['vid'] = os.path.join(vm.dir_path_prefix, vm.name,
  68. volume_config['name'])
  69. volume = ReflinkVolume(**volume_config)
  70. self._volumes[volume_config['vid']] = volume
  71. return volume
  72. def list_volumes(self):
  73. return list(self._volumes.values())
  74. def get_volume(self, vid):
  75. return self._volumes[vid]
  76. def destroy(self):
  77. pass
  78. @property
  79. def config(self):
  80. return {
  81. 'name': self.name,
  82. 'dir_path': self.dir_path,
  83. 'driver': ReflinkPool.driver,
  84. 'revisions_to_keep': self.revisions_to_keep
  85. }
  86. @property
  87. def size(self):
  88. statvfs = os.statvfs(self.dir_path)
  89. return statvfs.f_frsize * statvfs.f_blocks
  90. @property
  91. def usage(self):
  92. statvfs = os.statvfs(self.dir_path)
  93. return statvfs.f_frsize * (statvfs.f_blocks - statvfs.f_bfree)
  94. def included_in(self, app):
  95. ''' Check if there is pool containing this one - either as a
  96. filesystem or its LVM volume'''
  97. return qubes.storage.search_pool_containing_dir(
  98. [pool for pool in app.pools.values() if pool is not self],
  99. self.dir_path)
  100. class ReflinkVolume(qubes.storage.Volume):
  101. def create(self):
  102. if self.save_on_stop and not self.snap_on_start:
  103. _create_sparse_file(self._path_clean, self.size)
  104. return self
  105. def verify(self):
  106. if self.snap_on_start:
  107. # pylint: disable=protected-access
  108. img = self.source._path_clean
  109. elif self.save_on_stop:
  110. img = self._path_clean
  111. else:
  112. img = None
  113. if img is None or os.path.exists(img):
  114. return True
  115. raise qubes.storage.StoragePoolException(
  116. 'Missing image file {!r} for volume {!s}'.format(img, self.vid))
  117. def remove(self):
  118. ''' Drop volume object from pool; remove volume images from
  119. oldest to newest; remove empty VM directory.
  120. '''
  121. with suppress(KeyError):
  122. # pylint: disable=protected-access
  123. del self.pool._volumes[self]
  124. self._prune_revisions(keep=0)
  125. _remove_file(self._path_clean)
  126. _remove_file(self._path_dirty)
  127. try:
  128. _remove_empty_dir(os.path.dirname(self._path_dirty))
  129. except OSError as ex:
  130. if ex.errno is not errno.ENOTEMPTY:
  131. raise
  132. return self
  133. def is_outdated(self):
  134. if self.snap_on_start:
  135. with suppress(FileNotFoundError):
  136. # pylint: disable=protected-access
  137. return (os.path.getmtime(self.source._path_clean) >
  138. os.path.getmtime(self._path_clean))
  139. return False
  140. def is_dirty(self):
  141. return self.save_on_stop and os.path.exists(self._path_dirty)
  142. def start(self):
  143. if self.snap_on_start:
  144. # pylint: disable=protected-access
  145. _copy_file(self.source._path_clean, self._path_clean)
  146. if self.is_dirty(): # implies self.save_on_stop
  147. return self
  148. if self.save_on_stop or self.snap_on_start:
  149. _copy_file(self._path_clean, self._path_dirty)
  150. else:
  151. _create_sparse_file(self._path_dirty, self.size)
  152. return self
  153. def stop(self):
  154. if self.save_on_stop:
  155. self._commit()
  156. else:
  157. _remove_file(self._path_dirty)
  158. if self.snap_on_start:
  159. _remove_file(self._path_clean)
  160. return self
  161. def _commit(self):
  162. self._add_revision()
  163. self._prune_revisions()
  164. _rename_file(self._path_dirty, self._path_clean)
  165. def _add_revision(self):
  166. if self.revisions_to_keep == 0:
  167. return
  168. if _get_file_disk_usage(self._path_clean) == 0:
  169. return
  170. ctime = os.path.getctime(self._path_clean)
  171. revision = qubes.storage.isodate(int(ctime)) + 'Z'
  172. _copy_file(self._path_clean, self._path_revision(revision))
  173. def _prune_revisions(self, keep=None):
  174. if keep is None:
  175. keep = self.revisions_to_keep
  176. # pylint: disable=invalid-unary-operand-type
  177. for revision in list(self.revisions.keys())[:(-keep) or None]:
  178. _remove_file(self._path_revision(revision))
  179. def revert(self, revision=None):
  180. if revision is None:
  181. revision = list(self.revisions.keys())[-1]
  182. elif not os.path.exists(self._path_revision(revision)):
  183. raise qubes.storage.StoragePoolException(
  184. 'Missing revision {!r} for volume {!s}'.format(
  185. revision, self.vid))
  186. self._add_revision()
  187. _rename_file(self._path_revision(revision), self._path_clean)
  188. return self
  189. def resize(self, size):
  190. ''' Expand a read-write volume image; notify any corresponding
  191. loop devices of the size change.
  192. '''
  193. if not self.rw:
  194. raise qubes.storage.StoragePoolException(
  195. 'Cannot resize: {!s} is read-only'.format(self.vid))
  196. if size < self.size:
  197. raise qubes.storage.StoragePoolException(
  198. 'For your own safety, shrinking of {!s} is disabled.'
  199. ' If you really know what you are doing,'
  200. ' use "truncate" manually.'.format(self.vid))
  201. try: # assume volume is not (cleanly) stopped ...
  202. _resize_file(self._path_dirty, size)
  203. except FileNotFoundError: # ... but it actually is.
  204. _resize_file(self._path_clean, size)
  205. self.size = size
  206. # resize any corresponding loop devices
  207. out = _cmd('losetup', '--associated', self._path_dirty)
  208. for match in re.finditer(br'^(/dev/loop[0-9]+): ', out, re.MULTILINE):
  209. loop_dev = match.group(1).decode('ascii')
  210. _cmd('losetup', '--set-capacity', loop_dev)
  211. return self
  212. def _require_save_on_stop(self, method_name):
  213. if not self.save_on_stop:
  214. raise NotImplementedError(
  215. 'Cannot {!s}: {!s} is not save_on_stop'.format(
  216. method_name, self.vid))
  217. def export(self):
  218. self._require_save_on_stop('export')
  219. return self._path_clean
  220. def import_data(self):
  221. self._require_save_on_stop('import_data')
  222. _create_sparse_file(self._path_dirty, self.size)
  223. return self._path_dirty
  224. def import_data_end(self, success):
  225. if success:
  226. self._commit()
  227. else:
  228. _remove_file(self._path_dirty)
  229. return self
  230. def import_volume(self, src_volume):
  231. self._require_save_on_stop('import_volume')
  232. try:
  233. _copy_file(src_volume.export(), self._path_dirty)
  234. except:
  235. self.import_data_end(False)
  236. raise
  237. self.import_data_end(True)
  238. return self
  239. def _path_revision(self, revision):
  240. return self._path_clean + '@' + revision
  241. @property
  242. def _path_clean(self):
  243. return os.path.join(self.pool.dir_path, self.vid + '.img')
  244. @property
  245. def _path_dirty(self):
  246. return os.path.join(self.pool.dir_path, self.vid + '-dirty.img')
  247. @property
  248. def path(self):
  249. return self._path_dirty
  250. @property
  251. def revisions(self):
  252. revision_to_timestamp = collections.OrderedDict()
  253. prefix = self._path_revision('')
  254. for filename in sorted(glob.glob(glob.escape(prefix) + '*Z')):
  255. revision = filename[len(prefix):]
  256. timestamp = revision[:-1]
  257. revision_to_timestamp[revision] = timestamp
  258. return revision_to_timestamp
  259. @property
  260. def usage(self):
  261. ''' Return volume disk usage from the VM's perspective. It is
  262. usually much lower from the host's perspective due to CoW.
  263. '''
  264. with suppress(FileNotFoundError):
  265. return _get_file_disk_usage(self._path_dirty)
  266. with suppress(FileNotFoundError):
  267. return _get_file_disk_usage(self._path_clean)
  268. return 0
  269. @contextmanager
  270. def _replace_file(dst):
  271. ''' Yield a tempfile whose name starts with dst, creating the last
  272. directory component if necessary. If the block does not raise
  273. an exception, flush+fsync the tempfile and rename it to dst.
  274. '''
  275. tmp_dir, prefix = os.path.split(dst + '~')
  276. _make_dir(tmp_dir)
  277. tmp = tempfile.NamedTemporaryFile(dir=tmp_dir, prefix=prefix, delete=False)
  278. try:
  279. yield tmp
  280. tmp.flush()
  281. os.fsync(tmp.fileno())
  282. tmp.close()
  283. _rename_file(tmp.name, dst)
  284. except:
  285. tmp.close()
  286. _remove_file(tmp.name)
  287. raise
  288. def _get_file_disk_usage(path):
  289. ''' Return real disk usage (not logical file size) of a file. '''
  290. return os.stat(path).st_blocks * BLKSIZE
  291. def _fsync_dir(path):
  292. dir_fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
  293. try:
  294. os.fsync(dir_fd)
  295. finally:
  296. os.close(dir_fd)
  297. def _make_dir(path):
  298. ''' mkdir path, ignoring FileExistsError; return whether we
  299. created it.
  300. '''
  301. with suppress(FileExistsError):
  302. os.mkdir(path)
  303. _fsync_dir(os.path.dirname(path))
  304. LOGGER.info('Created directory: %s', path)
  305. return True
  306. return False
  307. def _remove_file(path):
  308. with suppress(FileNotFoundError):
  309. os.remove(path)
  310. _fsync_dir(os.path.dirname(path))
  311. LOGGER.info('Removed file: %s', path)
  312. def _remove_empty_dir(path):
  313. with suppress(FileNotFoundError):
  314. os.rmdir(path)
  315. _fsync_dir(os.path.dirname(path))
  316. LOGGER.info('Removed empty directory: %s', path)
  317. def _rename_file(src, dst):
  318. os.rename(src, dst)
  319. dst_dir = os.path.dirname(dst)
  320. src_dir = os.path.dirname(src)
  321. _fsync_dir(dst_dir)
  322. if src_dir != dst_dir:
  323. _fsync_dir(src_dir)
  324. LOGGER.info('Renamed file: %s -> %s', src, dst)
  325. def _resize_file(path, size):
  326. ''' Resize an existing file. '''
  327. with open(path, 'rb+') as file:
  328. file.truncate(size)
  329. def _create_sparse_file(path, size):
  330. ''' Create an empty sparse file. '''
  331. with _replace_file(path) as tmp:
  332. tmp.truncate(size)
  333. LOGGER.info('Created sparse file: %s', tmp.name)
  334. def _copy_file(src, dst):
  335. ''' Copy src to dst as a reflink if possible, sparse if not. '''
  336. if not os.path.exists(src):
  337. raise FileNotFoundError(src)
  338. with _replace_file(dst) as tmp:
  339. LOGGER.info('Copying file: %s -> %s', src, tmp.name)
  340. _cmd('cp', '--sparse=always', '--reflink=auto', src, tmp.name)
  341. def _cmd(*args):
  342. ''' Run command until finished; return stdout (as bytes) if it
  343. exited 0. Otherwise, raise a detailed StoragePoolException.
  344. '''
  345. try:
  346. return subprocess.run(args, check=True,
  347. stdout=subprocess.PIPE,
  348. stderr=subprocess.PIPE).stdout
  349. except subprocess.CalledProcessError as ex:
  350. msg = '{!s} err={!r} out={!r}'.format(ex, ex.stderr, ex.stdout)
  351. raise qubes.storage.StoragePoolException(msg) from ex
  352. def is_reflink_supported(dst_dir, src_dir=None):
  353. ''' Return whether destination directory supports reflink copies
  354. from source directory. (A temporary file is created in each
  355. directory, using O_TMPFILE if possible.)
  356. '''
  357. if src_dir is None:
  358. src_dir = dst_dir
  359. dst = tempfile.TemporaryFile(dir=dst_dir)
  360. src = tempfile.TemporaryFile(dir=src_dir)
  361. src.write(b'foo') # don't let any filesystem get clever with empty files
  362. try:
  363. fcntl.ioctl(dst.fileno(), FICLONE, src.fileno())
  364. return True
  365. except OSError:
  366. return False