file.py 18 KB

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