reflink.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. timestamp = qubes.storage.isodate(int(ctime))
  158. _copy_file(self._path_clean,
  159. self._path_revision(self._next_revision_number, timestamp))
  160. def _prune_revisions(self, keep=None):
  161. if keep is None:
  162. keep = self.revisions_to_keep
  163. # pylint: disable=invalid-unary-operand-type
  164. for number, timestamp in list(self.revisions.items())[:-keep or None]:
  165. _remove_file(self._path_revision(number, timestamp))
  166. def revert(self, revision=None):
  167. if revision is None:
  168. number, timestamp = list(self.revisions.items())[-1]
  169. else:
  170. number, timestamp = revision, None
  171. path_revision = self._path_revision(number, timestamp)
  172. self._add_revision()
  173. _rename_file(path_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, number, timestamp=None):
  226. if timestamp is None:
  227. timestamp = self.revisions[number]
  228. return self._path_clean + '.' + number + '@' + timestamp + 'Z'
  229. @property
  230. def _path_clean(self):
  231. return os.path.join(self.pool.dir_path, self.vid + '.img')
  232. @property
  233. def _path_dirty(self):
  234. return os.path.join(self.pool.dir_path, self.vid + '-dirty.img')
  235. @property
  236. def path(self):
  237. return self._path_dirty
  238. @property
  239. def _next_revision_number(self):
  240. numbers = self.revisions.keys()
  241. if numbers:
  242. return str(int(list(numbers)[-1]) + 1)
  243. return '1'
  244. @property
  245. def revisions(self):
  246. prefix = self._path_clean + '.'
  247. paths = glob.glob(glob.escape(prefix) + '*@*Z')
  248. items = sorted((path[len(prefix):-1].split('@') for path in paths),
  249. key=lambda item: int(item[0]))
  250. return collections.OrderedDict(items)
  251. @property
  252. def usage(self):
  253. ''' Return volume disk usage from the VM's perspective. It is
  254. usually much lower from the host's perspective due to CoW.
  255. '''
  256. with suppress(FileNotFoundError):
  257. return _get_file_disk_usage(self._path_dirty)
  258. with suppress(FileNotFoundError):
  259. return _get_file_disk_usage(self._path_clean)
  260. return 0
  261. @contextmanager
  262. def _replace_file(dst):
  263. ''' Yield a tempfile whose name starts with dst, creating the last
  264. directory component if necessary. If the block does not raise
  265. an exception, flush+fsync the tempfile and rename it to dst.
  266. '''
  267. tmp_dir, prefix = os.path.split(dst + '~')
  268. _make_dir(tmp_dir)
  269. tmp = tempfile.NamedTemporaryFile(dir=tmp_dir, prefix=prefix, delete=False)
  270. try:
  271. yield tmp
  272. tmp.flush()
  273. os.fsync(tmp.fileno())
  274. tmp.close()
  275. _rename_file(tmp.name, dst)
  276. except:
  277. tmp.close()
  278. _remove_file(tmp.name)
  279. raise
  280. def _get_file_disk_usage(path):
  281. ''' Return real disk usage (not logical file size) of a file. '''
  282. return os.stat(path).st_blocks * BLKSIZE
  283. def _fsync_dir(path):
  284. dir_fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
  285. try:
  286. os.fsync(dir_fd)
  287. finally:
  288. os.close(dir_fd)
  289. def _make_dir(path):
  290. ''' mkdir path, ignoring FileExistsError; return whether we
  291. created it.
  292. '''
  293. with suppress(FileExistsError):
  294. os.mkdir(path)
  295. _fsync_dir(os.path.dirname(path))
  296. LOGGER.info('Created directory: %s', path)
  297. return True
  298. return False
  299. def _remove_file(path):
  300. with suppress(FileNotFoundError):
  301. os.remove(path)
  302. _fsync_dir(os.path.dirname(path))
  303. LOGGER.info('Removed file: %s', path)
  304. def _remove_empty_dir(path):
  305. try:
  306. os.rmdir(path)
  307. _fsync_dir(os.path.dirname(path))
  308. LOGGER.info('Removed empty directory: %s', path)
  309. except OSError as ex:
  310. if ex.errno not in (errno.ENOENT, errno.ENOTEMPTY):
  311. raise
  312. def _rename_file(src, dst):
  313. os.rename(src, dst)
  314. dst_dir = os.path.dirname(dst)
  315. src_dir = os.path.dirname(src)
  316. _fsync_dir(dst_dir)
  317. if src_dir != dst_dir:
  318. _fsync_dir(src_dir)
  319. LOGGER.info('Renamed file: %s -> %s', src, dst)
  320. def _resize_file(path, size):
  321. ''' Resize an existing file. '''
  322. with open(path, 'rb+') as file:
  323. file.truncate(size)
  324. os.fsync(file.fileno())
  325. def _create_sparse_file(path, size):
  326. ''' Create an empty sparse file. '''
  327. with _replace_file(path) as tmp:
  328. tmp.truncate(size)
  329. LOGGER.info('Created sparse file: %s', tmp.name)
  330. def _copy_file(src, dst):
  331. ''' Copy src to dst as a reflink if possible, sparse if not. '''
  332. if not os.path.exists(src):
  333. raise FileNotFoundError(src)
  334. with _replace_file(dst) as tmp:
  335. LOGGER.info('Copying file: %s -> %s', src, tmp.name)
  336. _cmd('cp', '--sparse=always', '--reflink=auto', src, tmp.name)
  337. def _cmd(*args):
  338. ''' Run command until finished; return stdout (as bytes) if it
  339. exited 0. Otherwise, raise a detailed StoragePoolException.
  340. '''
  341. try:
  342. return subprocess.run(args, check=True,
  343. stdout=subprocess.PIPE,
  344. stderr=subprocess.PIPE).stdout
  345. except subprocess.CalledProcessError as ex:
  346. msg = '{!s} err={!r} out={!r}'.format(ex, ex.stderr, ex.stdout)
  347. raise qubes.storage.StoragePoolException(msg) from ex
  348. def is_reflink_supported(dst_dir, src_dir=None):
  349. ''' Return whether destination directory supports reflink copies
  350. from source directory. (A temporary file is created in each
  351. directory, using O_TMPFILE if possible.)
  352. '''
  353. if src_dir is None:
  354. src_dir = dst_dir
  355. dst = tempfile.TemporaryFile(dir=dst_dir)
  356. src = tempfile.TemporaryFile(dir=src_dir)
  357. src.write(b'foo') # don't let any filesystem get clever with empty files
  358. try:
  359. fcntl.ioctl(dst.fileno(), FICLONE, src.fileno())
  360. return True
  361. except OSError:
  362. return False