reflink.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 asyncio
  24. import collections
  25. import errno
  26. import fcntl
  27. import functools
  28. import glob
  29. import logging
  30. import os
  31. import subprocess
  32. import tempfile
  33. from contextlib import contextmanager, suppress
  34. import qubes.storage
  35. FICLONE = 1074041865 # defined in <linux/fs.h>, assuming sizeof(int)==4
  36. LOOP_SET_CAPACITY = 0x4C07 # defined in <linux/loop.h>
  37. LOGGER = logging.getLogger('qubes.storage.reflink')
  38. def _coroutinized(function):
  39. ''' Decorator transforming a synchronous function into a coroutine
  40. that runs the function in the event loop's thread-based
  41. default executor.
  42. '''
  43. @asyncio.coroutine
  44. @functools.wraps(function)
  45. def wrapper(*args, **kwargs):
  46. return (yield from asyncio.get_event_loop().run_in_executor(
  47. None, functools.partial(function, *args, **kwargs)))
  48. return wrapper
  49. class ReflinkPool(qubes.storage.Pool):
  50. driver = 'file-reflink'
  51. _known_dir_path_prefixes = ['appvms', 'vm-templates']
  52. def __init__(self, *, name, revisions_to_keep=1,
  53. dir_path, setup_check=True):
  54. super().__init__(name=name, revisions_to_keep=revisions_to_keep)
  55. self._setup_check = qubes.property.bool(None, None, setup_check)
  56. self._volumes = {}
  57. self.dir_path = os.path.abspath(dir_path)
  58. @_coroutinized
  59. def setup(self):
  60. created = _make_dir(self.dir_path)
  61. if self._setup_check and not is_supported(self.dir_path):
  62. if created:
  63. _remove_empty_dir(self.dir_path)
  64. raise qubes.storage.StoragePoolException(
  65. 'The filesystem for {!r} does not support reflinks. If you'
  66. ' can live with VM startup delays and wasted disk space, pass'
  67. ' the "setup_check=False" option.'.format(self.dir_path))
  68. for dir_path_prefix in self._known_dir_path_prefixes:
  69. _make_dir(os.path.join(self.dir_path, dir_path_prefix))
  70. return self
  71. def init_volume(self, vm, volume_config):
  72. # Fail closed on any strange VM dir_path_prefix, just in case
  73. # /etc/udev/rules.d/00-qubes-ignore-devices.rules needs update
  74. assert vm.dir_path_prefix in self._known_dir_path_prefixes, \
  75. 'Unknown dir_path_prefix {!r}'.format(vm.dir_path_prefix)
  76. volume_config['pool'] = self
  77. if 'revisions_to_keep' not in volume_config:
  78. volume_config['revisions_to_keep'] = self.revisions_to_keep
  79. if 'vid' not in volume_config:
  80. volume_config['vid'] = os.path.join(vm.dir_path_prefix, vm.name,
  81. volume_config['name'])
  82. volume = ReflinkVolume(**volume_config)
  83. self._volumes[volume_config['vid']] = volume
  84. return volume
  85. def list_volumes(self):
  86. return list(self._volumes.values())
  87. def get_volume(self, vid):
  88. return self._volumes[vid]
  89. def destroy(self):
  90. pass
  91. @property
  92. def config(self):
  93. return {
  94. 'name': self.name,
  95. 'dir_path': self.dir_path,
  96. 'driver': ReflinkPool.driver,
  97. 'revisions_to_keep': self.revisions_to_keep
  98. }
  99. @property
  100. def size(self):
  101. statvfs = os.statvfs(self.dir_path)
  102. return statvfs.f_frsize * statvfs.f_blocks
  103. @property
  104. def usage(self):
  105. statvfs = os.statvfs(self.dir_path)
  106. return statvfs.f_frsize * (statvfs.f_blocks - statvfs.f_bfree)
  107. def included_in(self, app):
  108. ''' Check if there is pool containing this one - either as a
  109. filesystem or its LVM volume'''
  110. return qubes.storage.search_pool_containing_dir(
  111. [pool for pool in app.pools.values() if pool is not self],
  112. self.dir_path)
  113. class ReflinkVolume(qubes.storage.Volume):
  114. def __init__(self, *args, **kwargs):
  115. super().__init__(*args, **kwargs)
  116. self._path_vid = os.path.join(self.pool.dir_path, self.vid)
  117. self._path_clean = self._path_vid + '.img'
  118. self._path_dirty = self._path_vid + '-dirty.img'
  119. self._path_import = self._path_vid + '-import.img'
  120. self.path = self._path_dirty
  121. @qubes.storage.Volume.locked
  122. @_coroutinized
  123. def create(self):
  124. self._remove_all_images()
  125. if self.save_on_stop and not self.snap_on_start:
  126. _create_sparse_file(self._path_clean, self._size)
  127. return self
  128. @_coroutinized
  129. def verify(self):
  130. if self.snap_on_start:
  131. img = self.source._path_clean # pylint: disable=protected-access
  132. elif self.save_on_stop:
  133. img = self._path_clean
  134. else:
  135. img = None
  136. if img is None or os.path.exists(img):
  137. return True
  138. raise qubes.storage.StoragePoolException(
  139. 'Missing image file {!r} for volume {}'.format(img, self.vid))
  140. @qubes.storage.Volume.locked
  141. @_coroutinized
  142. def remove(self):
  143. self.pool._volumes.pop(self, None) # pylint: disable=protected-access
  144. self._remove_all_images()
  145. _remove_empty_dir(os.path.dirname(self._path_vid))
  146. return self
  147. def _remove_all_images(self):
  148. self._remove_incomplete_images()
  149. self._prune_revisions(keep=0)
  150. _remove_file(self._path_clean)
  151. _remove_file(self._path_dirty)
  152. def _remove_incomplete_images(self):
  153. for tmp in glob.iglob(glob.escape(self._path_vid) + '*.img*~*'):
  154. _remove_file(tmp)
  155. _remove_file(self._path_import)
  156. def is_outdated(self):
  157. if self.snap_on_start:
  158. with suppress(FileNotFoundError):
  159. # pylint: disable=protected-access
  160. return (os.path.getmtime(self.source._path_clean) >
  161. os.path.getmtime(self._path_clean))
  162. return False
  163. def is_dirty(self):
  164. return self.save_on_stop and os.path.exists(self._path_dirty)
  165. @qubes.storage.Volume.locked
  166. @_coroutinized
  167. def start(self):
  168. self._remove_incomplete_images()
  169. if not self.is_dirty():
  170. if self.snap_on_start:
  171. # pylint: disable=protected-access
  172. _copy_file(self.source._path_clean, self._path_clean)
  173. if self.snap_on_start or self.save_on_stop:
  174. _copy_file(self._path_clean, self._path_dirty)
  175. else:
  176. # Preferably use the size of a leftover image, in case
  177. # the volume was previously resized - but then a crash
  178. # prevented qubes.xml serialization of the new size.
  179. _create_sparse_file(self._path_dirty, self.size)
  180. return self
  181. @qubes.storage.Volume.locked
  182. @_coroutinized
  183. def stop(self):
  184. if self.save_on_stop:
  185. self._commit(self._path_dirty)
  186. else:
  187. if not self.snap_on_start:
  188. self._size = self.size # preserve manual resize of image
  189. _remove_file(self._path_dirty)
  190. _remove_file(self._path_clean)
  191. return self
  192. def _commit(self, path_from):
  193. self._add_revision()
  194. self._prune_revisions()
  195. _fsync_path(path_from)
  196. _rename_file(path_from, self._path_clean)
  197. def _add_revision(self):
  198. if self.revisions_to_keep == 0:
  199. return
  200. ctime = os.path.getctime(self._path_clean)
  201. timestamp = qubes.storage.isodate(int(ctime))
  202. _copy_file(self._path_clean,
  203. self._path_revision(self._next_revision_number, timestamp))
  204. def _prune_revisions(self, keep=None):
  205. if keep is None:
  206. keep = self.revisions_to_keep
  207. # pylint: disable=invalid-unary-operand-type
  208. for number, timestamp in list(self.revisions.items())[:-keep or None]:
  209. _remove_file(self._path_revision(number, timestamp))
  210. @qubes.storage.Volume.locked
  211. @_coroutinized
  212. def revert(self, revision=None):
  213. if self.is_dirty():
  214. raise qubes.storage.StoragePoolException(
  215. 'Cannot revert: {} is not cleanly stopped'.format(self.vid))
  216. if revision is None:
  217. number, timestamp = list(self.revisions.items())[-1]
  218. else:
  219. number, timestamp = revision, None
  220. path_revision = self._path_revision(number, timestamp)
  221. self._add_revision()
  222. _rename_file(path_revision, self._path_clean)
  223. return self
  224. @qubes.storage.Volume.locked
  225. @_coroutinized
  226. def resize(self, size):
  227. ''' Resize a read-write volume; notify any corresponding loop
  228. devices of the size change.
  229. '''
  230. if not self.rw:
  231. raise qubes.storage.StoragePoolException(
  232. 'Cannot resize: {} is read-only'.format(self.vid))
  233. for path in (self._path_dirty, self._path_clean):
  234. with suppress(FileNotFoundError):
  235. _resize_file(path, size)
  236. break
  237. self._size = size
  238. if path == self._path_dirty:
  239. _update_loopdev_sizes(self._path_dirty)
  240. return self
  241. def export(self):
  242. if not self.save_on_stop:
  243. raise NotImplementedError(
  244. 'Cannot export: {} is not save_on_stop'.format(self.vid))
  245. return self._path_clean
  246. @qubes.storage.Volume.locked
  247. @_coroutinized
  248. def import_data(self, size):
  249. if not self.save_on_stop:
  250. raise NotImplementedError(
  251. 'Cannot import_data: {} is not save_on_stop'.format(self.vid))
  252. _create_sparse_file(self._path_import, size)
  253. return self._path_import
  254. def _import_data_end(self, success):
  255. (self._commit if success else _remove_file)(self._path_import)
  256. return self
  257. import_data_end = qubes.storage.Volume.locked(_coroutinized(
  258. _import_data_end))
  259. @qubes.storage.Volume.locked
  260. @_coroutinized
  261. def import_volume(self, src_volume):
  262. if self.save_on_stop:
  263. try:
  264. success = False
  265. _copy_file(src_volume.export(), self._path_import)
  266. success = True
  267. finally:
  268. self._import_data_end(success)
  269. return self
  270. def _path_revision(self, number, timestamp=None):
  271. if timestamp is None:
  272. timestamp = self.revisions[number]
  273. return self._path_clean + '.' + number + '@' + timestamp + 'Z'
  274. @property
  275. def _next_revision_number(self):
  276. numbers = self.revisions.keys()
  277. if numbers:
  278. return str(int(list(numbers)[-1]) + 1)
  279. return '1'
  280. @property
  281. def revisions(self):
  282. prefix = self._path_clean + '.'
  283. paths = glob.iglob(glob.escape(prefix) + '*@*Z')
  284. items = (path[len(prefix):-1].split('@') for path in paths)
  285. return collections.OrderedDict(sorted(items,
  286. key=lambda item: int(item[0])))
  287. @property
  288. def size(self):
  289. for path in (self._path_dirty, self._path_clean):
  290. with suppress(FileNotFoundError):
  291. return os.path.getsize(path)
  292. return self._size
  293. @property
  294. def usage(self):
  295. ''' Return volume disk usage from the VM's perspective. It is
  296. usually much lower from the host's perspective due to CoW.
  297. '''
  298. for path in (self._path_dirty, self._path_clean):
  299. with suppress(FileNotFoundError):
  300. return os.stat(path).st_blocks * 512
  301. return 0
  302. @contextmanager
  303. def _replace_file(dst):
  304. ''' Yield a tempfile whose name starts with dst, creating the last
  305. directory component if necessary. If the block does not raise
  306. an exception, safely rename the tempfile to dst.
  307. '''
  308. tmp_dir, prefix = os.path.split(dst + '~')
  309. _make_dir(tmp_dir)
  310. tmp = tempfile.NamedTemporaryFile(dir=tmp_dir, prefix=prefix, delete=False)
  311. try:
  312. yield tmp
  313. tmp.flush()
  314. os.fsync(tmp.fileno())
  315. tmp.close()
  316. _rename_file(tmp.name, dst)
  317. except:
  318. tmp.close()
  319. _remove_file(tmp.name)
  320. raise
  321. def _fsync_path(path):
  322. fd = os.open(path, os.O_RDONLY) # works for a file or a directory
  323. try:
  324. os.fsync(fd)
  325. finally:
  326. os.close(fd)
  327. def _make_dir(path):
  328. ''' mkdir path, ignoring FileExistsError; return whether we
  329. created it.
  330. '''
  331. with suppress(FileExistsError):
  332. os.mkdir(path)
  333. _fsync_path(os.path.dirname(path))
  334. LOGGER.info('Created directory: %s', path)
  335. return True
  336. return False
  337. def _remove_file(path):
  338. with suppress(FileNotFoundError):
  339. os.remove(path)
  340. _fsync_path(os.path.dirname(path))
  341. LOGGER.info('Removed file: %s', path)
  342. def _remove_empty_dir(path):
  343. try:
  344. os.rmdir(path)
  345. _fsync_path(os.path.dirname(path))
  346. LOGGER.info('Removed empty directory: %s', path)
  347. except OSError as ex:
  348. if ex.errno not in (errno.ENOENT, errno.ENOTEMPTY):
  349. raise
  350. def _rename_file(src, dst):
  351. os.rename(src, dst)
  352. dst_dir = os.path.dirname(dst)
  353. src_dir = os.path.dirname(src)
  354. _fsync_path(dst_dir)
  355. if src_dir != dst_dir:
  356. _fsync_path(src_dir)
  357. LOGGER.info('Renamed file: %s -> %s', src, dst)
  358. def _resize_file(path, size):
  359. ''' Resize an existing file. '''
  360. with open(path, 'rb+') as file:
  361. file.truncate(size)
  362. os.fsync(file.fileno())
  363. def _create_sparse_file(path, size):
  364. ''' Create an empty sparse file. '''
  365. with _replace_file(path) as tmp:
  366. tmp.truncate(size)
  367. LOGGER.info('Created sparse file: %s', tmp.name)
  368. def _update_loopdev_sizes(img):
  369. ''' Resolve img; update the size of loop devices backed by it. '''
  370. needle = os.fsencode(os.path.realpath(img)) + b'\n'
  371. for sys_path in glob.iglob('/sys/block/loop[0-9]*/loop/backing_file'):
  372. try:
  373. with open(sys_path, 'rb') as sys_io:
  374. if sys_io.read() != needle:
  375. continue
  376. except FileNotFoundError:
  377. continue
  378. with open('/dev/' + sys_path.split('/')[3], 'rb') as dev_io:
  379. fcntl.ioctl(dev_io.fileno(), LOOP_SET_CAPACITY)
  380. def _attempt_ficlone(src, dst):
  381. try:
  382. fcntl.ioctl(dst.fileno(), FICLONE, src.fileno())
  383. return True
  384. except OSError as ex:
  385. if ex.errno not in (errno.EBADF, errno.EINVAL,
  386. errno.EOPNOTSUPP, errno.EXDEV):
  387. raise
  388. return False
  389. def _copy_file(src, dst):
  390. ''' Copy src to dst as a reflink if possible, sparse if not. '''
  391. with _replace_file(dst) as tmp_io:
  392. with open(src, 'rb') as src_io:
  393. if _attempt_ficlone(src_io, tmp_io):
  394. LOGGER.info('Reflinked file: %s -> %s', src, tmp_io.name)
  395. return True
  396. LOGGER.info('Copying file: %s -> %s', src, tmp_io.name)
  397. cmd = 'cp', '--sparse=always', src, tmp_io.name
  398. p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  399. check=False)
  400. if p.returncode != 0:
  401. raise qubes.storage.StoragePoolException(str(p))
  402. return False
  403. def is_supported(dst_dir, src_dir=None):
  404. ''' Return whether destination directory supports reflink copies
  405. from source directory. (A temporary file is created in each
  406. directory, using O_TMPFILE if possible.)
  407. '''
  408. if src_dir is None:
  409. src_dir = dst_dir
  410. with tempfile.TemporaryFile(dir=src_dir) as src, \
  411. tempfile.TemporaryFile(dir=dst_dir) as dst:
  412. src.write(b'foo') # don't let any fs get clever with empty files
  413. return _attempt_ficlone(src, dst)