file.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. ''' This module contains pool implementations backed by file images'''
  23. import asyncio
  24. import os
  25. import os.path
  26. import re
  27. import subprocess
  28. from contextlib import suppress
  29. import qubes.storage
  30. import qubes.utils
  31. BLKSIZE = 512
  32. # 256 KiB chunk, same as in block-snapshot script. Header created by
  33. # struct.pack('<4I', 0x70416e53, 1, 1, 256) mimicking write_header()
  34. # in linux/drivers/md/dm-snap-persistent.c
  35. EMPTY_SNAPSHOT = b'SnAp\x01\x00\x00\x00\x01\x00\x00\x00\x00\x01\x00\x00' \
  36. + bytes(262128)
  37. class FilePool(qubes.storage.Pool):
  38. ''' File based 'original' disk implementation
  39. Volumes are stored in sparse files. Additionally device-mapper is used for
  40. applying copy-on-write layer.
  41. Quick reference on device-mapper layers:
  42. snap_on_start save_on_stop layout
  43. yes yes not supported
  44. no yes snapshot-origin(volume.img, volume-cow.img)
  45. yes no snapshot(
  46. snapshot(source.img, source-cow.img),
  47. volume-cow.img)
  48. no no volume.img directly
  49. ''' # pylint: disable=protected-access
  50. driver = 'file'
  51. def __init__(self, *, name, revisions_to_keep=1, dir_path):
  52. super().__init__(name=name, revisions_to_keep=revisions_to_keep)
  53. self.dir_path = os.path.normpath(dir_path)
  54. self._volumes = []
  55. @property
  56. def config(self):
  57. return {
  58. 'name': self.name,
  59. 'dir_path': self.dir_path,
  60. 'driver': FilePool.driver,
  61. 'revisions_to_keep': self.revisions_to_keep
  62. }
  63. def init_volume(self, vm, volume_config):
  64. if volume_config.get('snap_on_start', False) and \
  65. volume_config.get('save_on_stop', False):
  66. raise NotImplementedError(
  67. 'snap_on_start + save_on_stop not supported by file driver')
  68. volume_config['dir_path'] = self.dir_path
  69. if 'vid' not in volume_config:
  70. volume_config['vid'] = os.path.join(
  71. self._vid_prefix(vm), volume_config['name'])
  72. try:
  73. if not volume_config.get('save_on_stop', False):
  74. volume_config['revisions_to_keep'] = 0
  75. except KeyError:
  76. pass
  77. if 'revisions_to_keep' not in volume_config:
  78. volume_config['revisions_to_keep'] = self.revisions_to_keep
  79. volume_config['pool'] = self
  80. volume = FileVolume(**volume_config)
  81. self._volumes += [volume]
  82. return volume
  83. @property
  84. def revisions_to_keep(self):
  85. return self._revisions_to_keep
  86. @revisions_to_keep.setter
  87. def revisions_to_keep(self, value):
  88. value = int(value)
  89. if value > 1:
  90. raise NotImplementedError(
  91. 'FilePool supports maximum 1 volume revision to keep')
  92. self._revisions_to_keep = value
  93. def destroy(self):
  94. pass
  95. def setup(self):
  96. create_dir_if_not_exists(self.dir_path)
  97. appvms_path = os.path.join(self.dir_path, 'appvms')
  98. create_dir_if_not_exists(appvms_path)
  99. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  100. create_dir_if_not_exists(vm_templates_path)
  101. @staticmethod
  102. def _vid_prefix(vm):
  103. ''' Helper to create a prefix for the vid for volume
  104. ''' # FIX Remove this if we drop the file backend
  105. import qubes.vm.templatevm # pylint: disable=redefined-outer-name
  106. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  107. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  108. subdir = 'vm-templates'
  109. else:
  110. subdir = 'appvms'
  111. return os.path.join(subdir, vm.name)
  112. def target_dir(self, vm):
  113. """ Returns the path to vmdir depending on the type of the VM.
  114. The default QubesOS file storage saves the vm images in three
  115. different directories depending on the ``QubesVM`` type:
  116. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  117. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  118. Args:
  119. vm: a QubesVM
  120. pool_dir: the root directory of the pool
  121. Returns:
  122. string (str) absolute path to the directory where the vm files
  123. are stored
  124. """
  125. return os.path.join(self.dir_path, self._vid_prefix(vm))
  126. def list_volumes(self):
  127. return self._volumes
  128. @property
  129. def size(self):
  130. try:
  131. statvfs = os.statvfs(self.dir_path)
  132. return statvfs.f_frsize * statvfs.f_blocks
  133. except FileNotFoundError:
  134. return 0
  135. @property
  136. def usage(self):
  137. try:
  138. statvfs = os.statvfs(self.dir_path)
  139. return statvfs.f_frsize * (statvfs.f_blocks - statvfs.f_bfree)
  140. except FileNotFoundError:
  141. return 0
  142. def included_in(self, app):
  143. ''' Check if there is pool containing this one - either as a
  144. filesystem or its LVM volume'''
  145. return qubes.storage.search_pool_containing_dir(
  146. [pool for pool in app.pools.values() if pool is not self],
  147. self.dir_path)
  148. class FileVolume(qubes.storage.Volume):
  149. ''' Parent class for the xen volumes implementation which expects a
  150. `target_dir` param on initialization. '''
  151. _marker_running = object()
  152. _marker_exported = object()
  153. def __init__(self, dir_path, **kwargs):
  154. self.dir_path = dir_path
  155. assert self.dir_path, "dir_path not specified"
  156. self._revisions_to_keep = 0
  157. self._export_lock = None
  158. super().__init__(**kwargs)
  159. if self.snap_on_start:
  160. img_name = self.source.vid + '-cow.img'
  161. self.path_source_cow = os.path.join(self.dir_path, img_name)
  162. @property
  163. def revisions_to_keep(self):
  164. return self._revisions_to_keep
  165. @revisions_to_keep.setter
  166. def revisions_to_keep(self, value):
  167. if int(value) > 1:
  168. raise NotImplementedError(
  169. 'FileVolume supports maximum 1 volume revision to keep')
  170. self._revisions_to_keep = int(value)
  171. def create(self):
  172. assert isinstance(self.size, int) and self.size > 0, \
  173. 'Volume size must be > 0'
  174. if not self.snap_on_start:
  175. create_sparse_file(self.path, self.size)
  176. def remove(self):
  177. if not self.snap_on_start:
  178. _remove_if_exists(self.path)
  179. if self.snap_on_start or self.save_on_stop:
  180. _remove_if_exists(self.path_cow)
  181. def is_outdated(self):
  182. return False # avoid spamming the log with NotImplementedError
  183. def is_dirty(self):
  184. if self.save_on_stop:
  185. with suppress(FileNotFoundError), open(self.path_cow, 'rb') as cow:
  186. cow_used = os.fstat(cow.fileno()).st_blocks * BLKSIZE
  187. return (cow_used > 0 and
  188. (cow_used > len(EMPTY_SNAPSHOT) or
  189. cow.read(len(EMPTY_SNAPSHOT)) != EMPTY_SNAPSHOT or
  190. cow_used > cow.seek(0, os.SEEK_HOLE)))
  191. return False
  192. def resize(self, size):
  193. ''' Expands volume, throws
  194. :py:class:`qubst.storage.qubes.storage.StoragePoolException` if
  195. given size is less than current_size
  196. ''' # pylint: disable=no-self-use
  197. if not self.rw:
  198. msg = 'Can not resize reađonly volume {!s}'.format(self)
  199. raise qubes.storage.StoragePoolException(msg)
  200. if size < self.size:
  201. raise qubes.storage.StoragePoolException(
  202. 'For your own safety, shrinking of %s is'
  203. ' disabled. If you really know what you'
  204. ' are doing, use `truncate` on %s manually.' %
  205. (self.name, self.vid))
  206. with open(self.path, 'a+b') as fd:
  207. fd.truncate(size)
  208. p = subprocess.Popen(['losetup', '--associated', self.path],
  209. stdout=subprocess.PIPE)
  210. result = p.communicate()
  211. m = re.match(r'^(/dev/loop\d+):\s', result[0].decode())
  212. if m is not None:
  213. loop_dev = m.group(1)
  214. # resize loop device
  215. subprocess.check_call(['losetup', '--set-capacity',
  216. loop_dev])
  217. self._size = size
  218. def commit(self):
  219. msg = 'Tried to commit a non commitable volume {!r}'.format(self)
  220. assert self.save_on_stop and self.rw, msg
  221. if os.path.exists(self.path_cow):
  222. if self.revisions_to_keep:
  223. old_path = self.path_cow + '.old'
  224. os.rename(self.path_cow, old_path)
  225. else:
  226. os.unlink(self.path_cow)
  227. create_sparse_file(self.path_cow, self.size)
  228. return self
  229. def export(self):
  230. if self._export_lock is not None:
  231. assert self._export_lock is FileVolume._marker_running, \
  232. 'nested calls to export()'
  233. raise qubes.storage.StoragePoolException(
  234. 'file pool cannot export running volumes')
  235. if self.is_dirty():
  236. raise qubes.storage.StoragePoolException(
  237. 'file pool cannot export dirty volumes')
  238. self._export_lock = FileVolume._marker_exported
  239. return self.path
  240. def export_end(self, path):
  241. assert self._export_lock is not FileVolume._marker_running, \
  242. 'ending an export on a running volume?'
  243. self._export_lock = None
  244. @asyncio.coroutine
  245. def import_volume(self, src_volume):
  246. if src_volume.snap_on_start:
  247. raise qubes.storage.StoragePoolException(
  248. "Can not import snapshot volume {!s} in to pool {!s} ".format(
  249. src_volume, self))
  250. if self.save_on_stop:
  251. _remove_if_exists(self.path)
  252. path = yield from qubes.utils.coro_maybe(src_volume.export())
  253. try:
  254. copy_file(path, self.path)
  255. finally:
  256. yield from qubes.utils.coro_maybe(src_volume.export_end(path))
  257. return self
  258. def import_data(self, size):
  259. if not self.save_on_stop:
  260. raise qubes.storage.StoragePoolException(
  261. "Can not import into save_on_stop=False volume {!s}".format(
  262. self))
  263. create_sparse_file(self.path_import, size)
  264. return self.path_import
  265. def import_data_end(self, success):
  266. if success:
  267. os.rename(self.path_import, self.path)
  268. else:
  269. os.unlink(self.path_import)
  270. return self
  271. def reset(self):
  272. ''' Remove and recreate a volatile volume '''
  273. assert not self.snap_on_start and not self.save_on_stop, \
  274. "Not a volatile volume"
  275. assert isinstance(self.size, int) and self.size > 0, \
  276. 'Volatile volume size must be > 0'
  277. _remove_if_exists(self.path)
  278. create_sparse_file(self.path, self.size)
  279. return self
  280. def start(self):
  281. if self._export_lock is not None:
  282. assert self._export_lock is FileVolume._marker_exported, \
  283. 'nested calls to start()'
  284. raise qubes.storage.StoragePoolException(
  285. 'file pool cannot start a VM with an exported volume')
  286. self._export_lock = FileVolume._marker_running
  287. if not self.save_on_stop and not self.snap_on_start:
  288. self.reset()
  289. else:
  290. if not self.save_on_stop:
  291. # make sure previous snapshot is removed - even if VM
  292. # shutdown routine wasn't called (power interrupt or so)
  293. _remove_if_exists(self.path_cow)
  294. if not os.path.exists(self.path_cow):
  295. create_sparse_file(self.path_cow, self.size)
  296. if not self.snap_on_start:
  297. _check_path(self.path)
  298. if hasattr(self, 'path_source_cow'):
  299. if not os.path.exists(self.path_source_cow):
  300. create_sparse_file(self.path_source_cow, self.size)
  301. return self
  302. def stop(self):
  303. assert self._export_lock is not FileVolume._marker_exported, \
  304. 'trying to stop exported file volume?'
  305. if self.save_on_stop:
  306. self.commit()
  307. elif self.snap_on_start:
  308. _remove_if_exists(self.path_cow)
  309. else:
  310. _remove_if_exists(self.path)
  311. self._export_lock = None
  312. return self
  313. @property
  314. def path(self):
  315. if self.snap_on_start:
  316. return os.path.join(self.dir_path, self.source.vid + '.img')
  317. return os.path.join(self.dir_path, self.vid + '.img')
  318. @property
  319. def path_cow(self):
  320. img_name = self.vid + '-cow.img'
  321. return os.path.join(self.dir_path, img_name)
  322. @property
  323. def path_import(self):
  324. img_name = self.vid + '-import.img'
  325. return os.path.join(self.dir_path, img_name)
  326. def verify(self):
  327. ''' Verifies the volume. '''
  328. if not os.path.exists(self.path) and \
  329. (self.snap_on_start or self.save_on_stop):
  330. msg = 'Missing image file: {!s}.'.format(self.path)
  331. raise qubes.storage.StoragePoolException(msg)
  332. return True
  333. @property
  334. def script(self):
  335. if not self.snap_on_start and not self.save_on_stop:
  336. return None
  337. if not self.snap_on_start and self.save_on_stop:
  338. return 'block-origin'
  339. if self.snap_on_start:
  340. return 'block-snapshot'
  341. return None
  342. def block_device(self):
  343. ''' Return :py:class:`qubes.storage.BlockDevice` for serialization in
  344. the libvirt XML template as <disk>.
  345. '''
  346. path = self.path
  347. if self.snap_on_start:
  348. path += ":" + self.path_source_cow
  349. if self.snap_on_start or self.save_on_stop:
  350. path += ":" + self.path_cow
  351. return qubes.storage.BlockDevice(path, self.name, self.script, self.rw,
  352. self.domain, self.devtype)
  353. @property
  354. def revisions(self):
  355. if not hasattr(self, 'path_cow'):
  356. return {}
  357. old_revision = self.path_cow + '.old' # pylint: disable=no-member
  358. if not os.path.exists(old_revision):
  359. return {}
  360. seconds = os.path.getctime(old_revision)
  361. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  362. return {'old': iso_date}
  363. @property
  364. def size(self):
  365. with suppress(FileNotFoundError):
  366. self._size = os.path.getsize(self.path)
  367. return self._size
  368. @size.setter
  369. def size(self, _):
  370. raise qubes.storage.StoragePoolException(
  371. "You shouldn't use volume size setter, use resize method instead")
  372. @property
  373. def usage(self):
  374. ''' Returns the actualy used space '''
  375. usage = 0
  376. if self.save_on_stop or self.snap_on_start:
  377. usage = get_disk_usage(self.path_cow)
  378. if self.save_on_stop or not self.snap_on_start:
  379. usage += get_disk_usage(self.path)
  380. return usage
  381. def create_sparse_file(path, size):
  382. ''' Create an empty sparse file '''
  383. if os.path.exists(path):
  384. raise IOError("Volume %s already exists" % path)
  385. parent_dir = os.path.dirname(path)
  386. if not os.path.exists(parent_dir):
  387. os.makedirs(parent_dir)
  388. with open(path, 'a+b') as fh:
  389. fh.truncate(size)
  390. def get_disk_usage_one(st):
  391. '''Extract disk usage of one inode from its stat_result struct.
  392. If known, get real disk usage, as written to device by filesystem, not
  393. logical file size. Those values may be different for sparse files.
  394. :param os.stat_result st: stat result
  395. :returns: disk usage
  396. '''
  397. try:
  398. return st.st_blocks * BLKSIZE
  399. except AttributeError:
  400. return st.st_size
  401. def get_disk_usage(path):
  402. '''Get real disk usage of given path (file or directory).
  403. When *path* points to directory, then it is evaluated recursively.
  404. This function tries estimate real disk usage. See documentation of
  405. :py:func:`get_disk_usage_one`.
  406. :param str path: path to evaluate
  407. :returns: disk usage
  408. '''
  409. try:
  410. st = os.lstat(path)
  411. except OSError:
  412. return 0
  413. ret = get_disk_usage_one(st)
  414. # if path is not a directory, this is skipped
  415. for dirpath, dirnames, filenames in os.walk(path):
  416. for name in dirnames + filenames:
  417. ret += get_disk_usage_one(os.lstat(os.path.join(dirpath, name)))
  418. return ret
  419. def create_dir_if_not_exists(path):
  420. """ Check if a directory exists in if not create it.
  421. This method does not create any parent directories.
  422. """
  423. if not os.path.exists(path):
  424. os.mkdir(path)
  425. def copy_file(source, destination):
  426. '''Effective file copy, preserving sparse files etc.'''
  427. # We prefer to use Linux's cp, because it nicely handles sparse files
  428. assert os.path.exists(source), \
  429. "Missing the source %s to copy from" % source
  430. assert not os.path.exists(destination), \
  431. "Destination %s already exists" % destination
  432. parent_dir = os.path.dirname(destination)
  433. if not os.path.exists(parent_dir):
  434. os.makedirs(parent_dir)
  435. try:
  436. cmd = ['cp', '--sparse=always',
  437. '--reflink=auto', source, destination]
  438. subprocess.check_call(cmd)
  439. except subprocess.CalledProcessError:
  440. raise IOError('Error while copying {!r} to {!r}'.format(source,
  441. destination))
  442. def _remove_if_exists(path):
  443. ''' Removes a file if it exist, silently succeeds if file does not exist '''
  444. if os.path.exists(path):
  445. os.remove(path)
  446. def _check_path(path):
  447. ''' Raise an StoragePoolException if ``path`` does not exist'''
  448. if not os.path.exists(path):
  449. msg = 'Missing image file: %s' % path
  450. raise qubes.storage.StoragePoolException(msg)