reflink.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. class ReflinkVolume(qubes.storage.Volume):
  95. def create(self):
  96. if self.save_on_stop and not self.snap_on_start:
  97. _create_sparse_file(self._path_clean, self.size)
  98. return self
  99. def verify(self):
  100. if self.snap_on_start:
  101. img = self.source._path_clean # pylint: disable=protected-access
  102. elif self.save_on_stop:
  103. img = self._path_clean
  104. else:
  105. img = None
  106. if img is None or os.path.exists(img):
  107. return True
  108. raise qubes.storage.StoragePoolException(
  109. 'Missing image file {!r} for volume {!s}'.format(img, self.vid))
  110. def remove(self):
  111. ''' Drop volume object from pool; remove volume images from
  112. oldest to newest; remove empty VM directory.
  113. '''
  114. self.pool._volumes.pop(self, None) # pylint: disable=protected-access
  115. self._prune_revisions(keep=0)
  116. _remove_file(self._path_clean)
  117. _remove_file(self._path_dirty)
  118. _remove_empty_dir(os.path.dirname(self._path_dirty))
  119. return self
  120. def is_outdated(self):
  121. if self.snap_on_start:
  122. with suppress(FileNotFoundError):
  123. # pylint: disable=protected-access
  124. return (os.path.getmtime(self.source._path_clean) >
  125. os.path.getmtime(self._path_clean))
  126. return False
  127. def is_dirty(self):
  128. return self.save_on_stop and os.path.exists(self._path_dirty)
  129. def start(self):
  130. if self.is_dirty(): # implies self.save_on_stop
  131. return self
  132. if self.snap_on_start:
  133. # pylint: disable=protected-access
  134. _copy_file(self.source._path_clean, self._path_clean)
  135. if self.snap_on_start or self.save_on_stop:
  136. _copy_file(self._path_clean, self._path_dirty)
  137. else:
  138. _create_sparse_file(self._path_dirty, self.size)
  139. return self
  140. def stop(self):
  141. if self.save_on_stop:
  142. self._commit()
  143. else:
  144. _remove_file(self._path_dirty)
  145. _remove_file(self._path_clean)
  146. return self
  147. def _commit(self):
  148. self._add_revision()
  149. self._prune_revisions()
  150. _rename_file(self._path_dirty, self._path_clean)
  151. def _add_revision(self):
  152. if self.revisions_to_keep == 0:
  153. return
  154. if _get_file_disk_usage(self._path_clean) == 0:
  155. return
  156. ctime = os.path.getctime(self._path_clean)
  157. revision = qubes.storage.isodate(int(ctime)) + 'Z'
  158. _copy_file(self._path_clean, self._path_revision(revision))
  159. def _prune_revisions(self, keep=None):
  160. if keep is None:
  161. keep = self.revisions_to_keep
  162. # pylint: disable=invalid-unary-operand-type
  163. for revision in list(self.revisions.keys())[:(-keep) or None]:
  164. _remove_file(self._path_revision(revision))
  165. def revert(self, revision=None):
  166. if revision is None:
  167. revision = list(self.revisions.keys())[-1]
  168. elif not os.path.exists(self._path_revision(revision)):
  169. raise qubes.storage.StoragePoolException(
  170. 'Missing revision {!r} for volume {!s}'.format(
  171. revision, self.vid))
  172. self._add_revision()
  173. _rename_file(self._path_revision(revision), self._path_clean)
  174. return self
  175. def resize(self, size):
  176. ''' Expand a read-write volume image; notify any corresponding
  177. loop devices of the size change.
  178. '''
  179. if not self.rw:
  180. raise qubes.storage.StoragePoolException(
  181. 'Cannot resize: {!s} is read-only'.format(self.vid))
  182. if size < self.size:
  183. raise qubes.storage.StoragePoolException(
  184. 'For your own safety, shrinking of {!s} is disabled'
  185. ' ({:d} < {:d}). If you really know what you are doing,'
  186. ' use "truncate" manually.'.format(self.vid, size, self.size))
  187. try: # assume volume is not (cleanly) stopped ...
  188. _resize_file(self._path_dirty, size)
  189. except FileNotFoundError: # ... but it actually is.
  190. _resize_file(self._path_clean, size)
  191. self.size = size
  192. # resize any corresponding loop devices
  193. out = _cmd('losetup', '--associated', self._path_dirty)
  194. for match in re.finditer(br'^(/dev/loop[0-9]+): ', out, re.MULTILINE):
  195. loop_dev = match.group(1).decode('ascii')
  196. _cmd('losetup', '--set-capacity', loop_dev)
  197. return self
  198. def _require_save_on_stop(self, method_name):
  199. if not self.save_on_stop:
  200. raise NotImplementedError(
  201. 'Cannot {!s}: {!s} is not save_on_stop'.format(
  202. method_name, self.vid))
  203. def export(self):
  204. self._require_save_on_stop('export')
  205. return self._path_clean
  206. def import_data(self):
  207. self._require_save_on_stop('import_data')
  208. _create_sparse_file(self._path_dirty, self.size)
  209. return self._path_dirty
  210. def import_data_end(self, success):
  211. if success:
  212. self._commit()
  213. else:
  214. _remove_file(self._path_dirty)
  215. return self
  216. def import_volume(self, src_volume):
  217. self._require_save_on_stop('import_volume')
  218. try:
  219. _copy_file(src_volume.export(), self._path_dirty)
  220. except:
  221. self.import_data_end(False)
  222. raise
  223. self.import_data_end(True)
  224. return self
  225. def _path_revision(self, revision):
  226. return self._path_clean + '@' + revision
  227. @property
  228. def _path_clean(self):
  229. return os.path.join(self.pool.dir_path, self.vid + '.img')
  230. @property
  231. def _path_dirty(self):
  232. return os.path.join(self.pool.dir_path, self.vid + '-dirty.img')
  233. @property
  234. def path(self):
  235. return self._path_dirty
  236. @property
  237. def revisions(self):
  238. revision_to_timestamp = collections.OrderedDict()
  239. prefix = self._path_revision('')
  240. for filename in sorted(glob.glob(glob.escape(prefix) + '*Z')):
  241. revision = filename[len(prefix):]
  242. timestamp = revision[:-1]
  243. revision_to_timestamp[revision] = timestamp
  244. return revision_to_timestamp
  245. @property
  246. def usage(self):
  247. ''' Return volume disk usage from the VM's perspective. It is
  248. usually much lower from the host's perspective due to CoW.
  249. '''
  250. with suppress(FileNotFoundError):
  251. return _get_file_disk_usage(self._path_dirty)
  252. with suppress(FileNotFoundError):
  253. return _get_file_disk_usage(self._path_clean)
  254. return 0
  255. @contextmanager
  256. def _replace_file(dst):
  257. ''' Yield a tempfile whose name starts with dst, creating the last
  258. directory component if necessary. If the block does not raise
  259. an exception, flush+fsync the tempfile and rename it to dst.
  260. '''
  261. tmp_dir, prefix = os.path.split(dst + '~')
  262. _make_dir(tmp_dir)
  263. tmp = tempfile.NamedTemporaryFile(dir=tmp_dir, prefix=prefix, delete=False)
  264. try:
  265. yield tmp
  266. tmp.flush()
  267. os.fsync(tmp.fileno())
  268. tmp.close()
  269. _rename_file(tmp.name, dst)
  270. except:
  271. tmp.close()
  272. _remove_file(tmp.name)
  273. raise
  274. def _get_file_disk_usage(path):
  275. ''' Return real disk usage (not logical file size) of a file. '''
  276. return os.stat(path).st_blocks * BLKSIZE
  277. def _fsync_dir(path):
  278. dir_fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
  279. try:
  280. os.fsync(dir_fd)
  281. finally:
  282. os.close(dir_fd)
  283. def _make_dir(path):
  284. ''' mkdir path, ignoring FileExistsError; return whether we
  285. created it.
  286. '''
  287. with suppress(FileExistsError):
  288. os.mkdir(path)
  289. _fsync_dir(os.path.dirname(path))
  290. LOGGER.info('Created directory: %s', path)
  291. return True
  292. return False
  293. def _remove_file(path):
  294. with suppress(FileNotFoundError):
  295. os.remove(path)
  296. _fsync_dir(os.path.dirname(path))
  297. LOGGER.info('Removed file: %s', path)
  298. def _remove_empty_dir(path):
  299. try:
  300. os.rmdir(path)
  301. _fsync_dir(os.path.dirname(path))
  302. LOGGER.info('Removed empty directory: %s', path)
  303. except OSError as ex:
  304. if ex.errno not in (errno.ENOENT, errno.ENOTEMPTY):
  305. raise
  306. def _rename_file(src, dst):
  307. os.rename(src, dst)
  308. dst_dir = os.path.dirname(dst)
  309. src_dir = os.path.dirname(src)
  310. _fsync_dir(dst_dir)
  311. if src_dir != dst_dir:
  312. _fsync_dir(src_dir)
  313. LOGGER.info('Renamed file: %s -> %s', src, dst)
  314. def _resize_file(path, size):
  315. ''' Resize an existing file. '''
  316. with open(path, 'rb+') as file:
  317. file.truncate(size)
  318. os.fsync(file.fileno())
  319. def _create_sparse_file(path, size):
  320. ''' Create an empty sparse file. '''
  321. with _replace_file(path) as tmp:
  322. tmp.truncate(size)
  323. LOGGER.info('Created sparse file: %s', tmp.name)
  324. def _copy_file(src, dst):
  325. ''' Copy src to dst as a reflink if possible, sparse if not. '''
  326. if not os.path.exists(src):
  327. raise FileNotFoundError(src)
  328. with _replace_file(dst) as tmp:
  329. LOGGER.info('Copying file: %s -> %s', src, tmp.name)
  330. _cmd('cp', '--sparse=always', '--reflink=auto', src, tmp.name)
  331. def _cmd(*args):
  332. ''' Run command until finished; return stdout (as bytes) if it
  333. exited 0. Otherwise, raise a detailed StoragePoolException.
  334. '''
  335. try:
  336. return subprocess.run(args, check=True,
  337. stdout=subprocess.PIPE,
  338. stderr=subprocess.PIPE).stdout
  339. except subprocess.CalledProcessError as ex:
  340. msg = '{!s} err={!r} out={!r}'.format(ex, ex.stderr, ex.stdout)
  341. raise qubes.storage.StoragePoolException(msg) from ex
  342. def is_reflink_supported(dst_dir, src_dir=None):
  343. ''' Return whether destination directory supports reflink copies
  344. from source directory. (A temporary file is created in each
  345. directory, using O_TMPFILE if possible.)
  346. '''
  347. if src_dir is None:
  348. src_dir = dst_dir
  349. dst = tempfile.TemporaryFile(dir=dst_dir)
  350. src = tempfile.TemporaryFile(dir=src_dir)
  351. src.write(b'foo') # don't let any filesystem get clever with empty files
  352. try:
  353. fcntl.ioctl(dst.fileno(), FICLONE, src.fileno())
  354. return True
  355. except OSError:
  356. return False