reflink.py 16 KB

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