reflink.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. @_unblock
  123. def create(self):
  124. if self.save_on_stop and not self.snap_on_start:
  125. _create_sparse_file(self._path_clean, self.size)
  126. return self
  127. @_unblock
  128. def verify(self):
  129. if self.snap_on_start:
  130. img = self.source._path_clean # pylint: disable=protected-access
  131. elif self.save_on_stop:
  132. img = self._path_clean
  133. else:
  134. img = None
  135. if img is None or os.path.exists(img):
  136. return True
  137. raise qubes.storage.StoragePoolException(
  138. 'Missing image file {!r} for volume {}'.format(img, self.vid))
  139. @_unblock
  140. def remove(self):
  141. ''' Drop volume object from pool; remove volume images from
  142. oldest to newest; remove empty VM directory.
  143. '''
  144. self.pool._volumes.pop(self, None) # pylint: disable=protected-access
  145. self._cleanup()
  146. self._prune_revisions(keep=0)
  147. _remove_file(self._path_clean)
  148. _remove_file(self._path_dirty)
  149. _remove_empty_dir(os.path.dirname(self._path_dirty))
  150. return self
  151. def _cleanup(self):
  152. for tmp in glob.iglob(glob.escape(self._path_vid) + '*.img*~*'):
  153. _remove_file(tmp)
  154. _remove_file(self._path_import)
  155. def is_outdated(self):
  156. if self.snap_on_start:
  157. with suppress(FileNotFoundError):
  158. # pylint: disable=protected-access
  159. return (os.path.getmtime(self.source._path_clean) >
  160. os.path.getmtime(self._path_clean))
  161. return False
  162. def is_dirty(self):
  163. return self.save_on_stop and os.path.exists(self._path_dirty)
  164. @_unblock
  165. def start(self):
  166. self._cleanup()
  167. if self.is_dirty(): # implies self.save_on_stop
  168. return self
  169. if self.snap_on_start:
  170. # pylint: disable=protected-access
  171. _copy_file(self.source._path_clean, self._path_clean)
  172. if self.snap_on_start or self.save_on_stop:
  173. _copy_file(self._path_clean, self._path_dirty)
  174. else:
  175. _create_sparse_file(self._path_dirty, self.size)
  176. return self
  177. @_unblock
  178. def stop(self):
  179. if self.save_on_stop:
  180. self._commit(self._path_dirty)
  181. else:
  182. _remove_file(self._path_dirty)
  183. _remove_file(self._path_clean)
  184. return self
  185. def _commit(self, path_from):
  186. self._add_revision()
  187. self._prune_revisions()
  188. _rename_file(path_from, self._path_clean)
  189. def _add_revision(self):
  190. if self.revisions_to_keep == 0:
  191. return
  192. ctime = os.path.getctime(self._path_clean)
  193. timestamp = qubes.storage.isodate(int(ctime))
  194. _copy_file(self._path_clean,
  195. self._path_revision(self._next_revision_number, timestamp))
  196. def _prune_revisions(self, keep=None):
  197. if keep is None:
  198. keep = self.revisions_to_keep
  199. # pylint: disable=invalid-unary-operand-type
  200. for number, timestamp in list(self.revisions.items())[:-keep or None]:
  201. _remove_file(self._path_revision(number, timestamp))
  202. @_unblock
  203. def revert(self, revision=None):
  204. if self.is_dirty():
  205. raise qubes.storage.StoragePoolException(
  206. 'Cannot revert: {} is not cleanly stopped'.format(self.vid))
  207. if revision is None:
  208. number, timestamp = list(self.revisions.items())[-1]
  209. else:
  210. number, timestamp = revision, None
  211. path_revision = self._path_revision(number, timestamp)
  212. self._add_revision()
  213. _rename_file(path_revision, self._path_clean)
  214. return self
  215. @_unblock
  216. def resize(self, size):
  217. ''' Resize a read-write volume image; notify any corresponding
  218. loop devices of the size change.
  219. '''
  220. if not self.rw:
  221. raise qubes.storage.StoragePoolException(
  222. 'Cannot resize: {} is read-only'.format(self.vid))
  223. for path in (self._path_dirty, self._path_clean):
  224. with suppress(FileNotFoundError):
  225. _resize_file(path, size)
  226. break
  227. self.size = size
  228. if path == self._path_dirty:
  229. _update_loopdev_sizes(self._path_dirty)
  230. return self
  231. def export(self):
  232. if not self.save_on_stop:
  233. raise NotImplementedError(
  234. 'Cannot export: {} is not save_on_stop'.format(self.vid))
  235. return self._path_clean
  236. @_unblock
  237. def import_data(self):
  238. if not self.save_on_stop:
  239. raise NotImplementedError(
  240. 'Cannot import_data: {} is not save_on_stop'.format(self.vid))
  241. _create_sparse_file(self._path_import, self.size)
  242. return self._path_import
  243. def _import_data_end(self, success):
  244. if success:
  245. self._commit(self._path_import)
  246. else:
  247. _remove_file(self._path_import)
  248. return self
  249. import_data_end = _unblock(_import_data_end)
  250. @_unblock
  251. def import_volume(self, src_volume):
  252. if not self.save_on_stop:
  253. return self
  254. try:
  255. success = False
  256. _copy_file(src_volume.export(), self._path_import)
  257. success = True
  258. finally:
  259. self._import_data_end(success)
  260. return self
  261. def _path_revision(self, number, timestamp=None):
  262. if timestamp is None:
  263. timestamp = self.revisions[number]
  264. return self._path_clean + '.' + number + '@' + timestamp + 'Z'
  265. @property
  266. def _next_revision_number(self):
  267. numbers = self.revisions.keys()
  268. if numbers:
  269. return str(int(list(numbers)[-1]) + 1)
  270. return '1'
  271. @property
  272. def revisions(self):
  273. prefix = self._path_clean + '.'
  274. paths = glob.iglob(glob.escape(prefix) + '*@*Z')
  275. items = (path[len(prefix):-1].split('@') for path in paths)
  276. return collections.OrderedDict(sorted(items,
  277. key=lambda item: int(item[0])))
  278. @property
  279. def usage(self):
  280. ''' Return volume disk usage from the VM's perspective. It is
  281. usually much lower from the host's perspective due to CoW.
  282. '''
  283. for path in (self._path_dirty, self._path_clean):
  284. with suppress(FileNotFoundError):
  285. return os.stat(path).st_blocks * 512
  286. return 0
  287. @contextmanager
  288. def _replace_file(dst):
  289. ''' Yield a tempfile whose name starts with dst, creating the last
  290. directory component if necessary. If the block does not raise
  291. an exception, flush+fsync the tempfile and rename it to dst.
  292. '''
  293. tmp_dir, prefix = os.path.split(dst + '~')
  294. _make_dir(tmp_dir)
  295. tmp = tempfile.NamedTemporaryFile(dir=tmp_dir, prefix=prefix, delete=False)
  296. try:
  297. yield tmp
  298. tmp.flush()
  299. os.fsync(tmp.fileno())
  300. tmp.close()
  301. _rename_file(tmp.name, dst)
  302. except:
  303. tmp.close()
  304. _remove_file(tmp.name)
  305. raise
  306. def _fsync_dir(path):
  307. dir_fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
  308. try:
  309. os.fsync(dir_fd)
  310. finally:
  311. os.close(dir_fd)
  312. def _make_dir(path):
  313. ''' mkdir path, ignoring FileExistsError; return whether we
  314. created it.
  315. '''
  316. with suppress(FileExistsError):
  317. os.mkdir(path)
  318. _fsync_dir(os.path.dirname(path))
  319. LOGGER.info('Created directory: %s', path)
  320. return True
  321. return False
  322. def _remove_file(path):
  323. with suppress(FileNotFoundError):
  324. os.remove(path)
  325. _fsync_dir(os.path.dirname(path))
  326. LOGGER.info('Removed file: %s', path)
  327. def _remove_empty_dir(path):
  328. try:
  329. os.rmdir(path)
  330. _fsync_dir(os.path.dirname(path))
  331. LOGGER.info('Removed empty directory: %s', path)
  332. except OSError as ex:
  333. if ex.errno not in (errno.ENOENT, errno.ENOTEMPTY):
  334. raise
  335. def _rename_file(src, dst):
  336. os.rename(src, dst)
  337. dst_dir = os.path.dirname(dst)
  338. src_dir = os.path.dirname(src)
  339. _fsync_dir(dst_dir)
  340. if src_dir != dst_dir:
  341. _fsync_dir(src_dir)
  342. LOGGER.info('Renamed file: %s -> %s', src, dst)
  343. def _resize_file(path, size):
  344. ''' Resize an existing file. '''
  345. with open(path, 'rb+') as file:
  346. file.truncate(size)
  347. os.fsync(file.fileno())
  348. def _create_sparse_file(path, size):
  349. ''' Create an empty sparse file. '''
  350. with _replace_file(path) as tmp:
  351. tmp.truncate(size)
  352. LOGGER.info('Created sparse file: %s', tmp.name)
  353. def _update_loopdev_sizes(img):
  354. ''' Resolve img; update the size of loop devices backed by it. '''
  355. needle = os.fsencode(os.path.realpath(img)) + b'\n'
  356. for sys_path in glob.iglob('/sys/block/loop[0-9]*/loop/backing_file'):
  357. try:
  358. with open(sys_path, 'rb') as sys_io:
  359. if sys_io.read() != needle:
  360. continue
  361. except FileNotFoundError:
  362. continue
  363. with open('/dev/' + sys_path.split('/')[3]) as dev_io:
  364. fcntl.ioctl(dev_io.fileno(), LOOP_SET_CAPACITY)
  365. def _attempt_ficlone(src, dst):
  366. try:
  367. fcntl.ioctl(dst.fileno(), FICLONE, src.fileno())
  368. return True
  369. except OSError:
  370. return False
  371. def _copy_file(src, dst):
  372. ''' Copy src to dst as a reflink if possible, sparse if not. '''
  373. with _replace_file(dst) as tmp_io:
  374. with open(src, 'rb') as src_io:
  375. if _attempt_ficlone(src_io, tmp_io):
  376. LOGGER.info('Reflinked file: %s -> %s', src, tmp_io.name)
  377. return True
  378. LOGGER.info('Copying file: %s -> %s', src, tmp_io.name)
  379. cmd = 'cp', '--sparse=always', src, tmp_io.name
  380. p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  381. if p.returncode != 0:
  382. raise qubes.storage.StoragePoolException(str(p))
  383. return False
  384. def is_supported(dst_dir, src_dir=None):
  385. ''' Return whether destination directory supports reflink copies
  386. from source directory. (A temporary file is created in each
  387. directory, using O_TMPFILE if possible.)
  388. '''
  389. if src_dir is None:
  390. src_dir = dst_dir
  391. with tempfile.TemporaryFile(dir=src_dir) as src, \
  392. tempfile.TemporaryFile(dir=dst_dir) as dst:
  393. src.write(b'foo') # don't let any fs get clever with empty files
  394. return _attempt_ficlone(src, dst)