reflink.py 16 KB

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