file.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. def __init__(self, dir_path, **kwargs):
  147. self.dir_path = dir_path
  148. assert self.dir_path, "dir_path not specified"
  149. self._revisions_to_keep = 0
  150. super().__init__(**kwargs)
  151. if self.snap_on_start:
  152. img_name = self.source.vid + '-cow.img'
  153. self.path_source_cow = os.path.join(self.dir_path, img_name)
  154. @property
  155. def revisions_to_keep(self):
  156. return self._revisions_to_keep
  157. @revisions_to_keep.setter
  158. def revisions_to_keep(self, value):
  159. if int(value) > 1:
  160. raise NotImplementedError(
  161. 'FileVolume supports maximum 1 volume revision to keep')
  162. self._revisions_to_keep = int(value)
  163. def create(self):
  164. assert isinstance(self.size, int) and self.size > 0, \
  165. 'Volume size must be > 0'
  166. if not self.snap_on_start:
  167. create_sparse_file(self.path, self.size)
  168. def remove(self):
  169. if not self.snap_on_start:
  170. _remove_if_exists(self.path)
  171. if self.snap_on_start or self.save_on_stop:
  172. _remove_if_exists(self.path_cow)
  173. def is_dirty(self):
  174. if not self.save_on_stop:
  175. return False
  176. if os.path.exists(self.path_cow):
  177. stat = os.stat(self.path_cow)
  178. return stat.st_blocks > 0
  179. return False
  180. def resize(self, size):
  181. ''' Expands volume, throws
  182. :py:class:`qubst.storage.qubes.storage.StoragePoolException` if
  183. given size is less than current_size
  184. ''' # pylint: disable=no-self-use
  185. if not self.rw:
  186. msg = 'Can not resize reađonly volume {!s}'.format(self)
  187. raise qubes.storage.StoragePoolException(msg)
  188. if size < self.size:
  189. raise qubes.storage.StoragePoolException(
  190. 'For your own safety, shrinking of %s is'
  191. ' disabled. If you really know what you'
  192. ' are doing, use `truncate` on %s manually.' %
  193. (self.name, self.vid))
  194. with open(self.path, 'a+b') as fd:
  195. fd.truncate(size)
  196. p = subprocess.Popen(['losetup', '--associated', self.path],
  197. stdout=subprocess.PIPE)
  198. result = p.communicate()
  199. m = re.match(r'^(/dev/loop\d+):\s', result[0].decode())
  200. if m is not None:
  201. loop_dev = m.group(1)
  202. # resize loop device
  203. subprocess.check_call(['losetup', '--set-capacity',
  204. loop_dev])
  205. self._size = size
  206. def commit(self):
  207. msg = 'Tried to commit a non commitable volume {!r}'.format(self)
  208. assert self.save_on_stop and self.rw, msg
  209. if os.path.exists(self.path_cow):
  210. if self.revisions_to_keep:
  211. old_path = self.path_cow + '.old'
  212. os.rename(self.path_cow, old_path)
  213. else:
  214. os.unlink(self.path_cow)
  215. create_sparse_file(self.path_cow, self.size)
  216. return self
  217. def export(self):
  218. return snapshot(self.path, self.path_cow)
  219. @asyncio.coroutine
  220. def import_volume(self, src_volume):
  221. if src_volume.snap_on_start:
  222. raise qubes.storage.StoragePoolException(
  223. "Can not import snapshot volume {!s} in to pool {!s} ".format(
  224. src_volume, self))
  225. if self.save_on_stop:
  226. _remove_if_exists(self.path)
  227. path = yield from qubes.utils.coro_maybe(src_volume.export())
  228. try:
  229. copy_file(path, self.path)
  230. finally:
  231. yield from qubes.utils.coro_maybe(src_volume.export_end(path))
  232. return self
  233. def import_data(self, size):
  234. if not self.save_on_stop:
  235. raise qubes.storage.StoragePoolException(
  236. "Can not import into save_on_stop=False volume {!s}".format(
  237. self))
  238. create_sparse_file(self.path_import, size)
  239. return self.path_import
  240. def import_data_end(self, success):
  241. if success:
  242. os.rename(self.path_import, self.path)
  243. else:
  244. os.unlink(self.path_import)
  245. return self
  246. def reset(self):
  247. ''' Remove and recreate a volatile volume '''
  248. assert not self.snap_on_start and not self.save_on_stop, \
  249. "Not a volatile volume"
  250. assert isinstance(self.size, int) and self.size > 0, \
  251. 'Volatile volume size must be > 0'
  252. _remove_if_exists(self.path)
  253. create_sparse_file(self.path, self.size)
  254. return self
  255. def start(self):
  256. if not self.save_on_stop and not self.snap_on_start:
  257. self.reset()
  258. else:
  259. if not self.save_on_stop:
  260. # make sure previous snapshot is removed - even if VM
  261. # shutdown routine wasn't called (power interrupt or so)
  262. _remove_if_exists(self.path_cow)
  263. if not os.path.exists(self.path_cow):
  264. create_sparse_file(self.path_cow, self.size)
  265. if not self.snap_on_start:
  266. _check_path(self.path)
  267. if hasattr(self, 'path_source_cow'):
  268. if not os.path.exists(self.path_source_cow):
  269. create_sparse_file(self.path_source_cow, self.size)
  270. return self
  271. def stop(self):
  272. if self.save_on_stop:
  273. self.commit()
  274. elif self.snap_on_start:
  275. _remove_if_exists(self.path_cow)
  276. else:
  277. _remove_if_exists(self.path)
  278. return self
  279. @property
  280. def path(self):
  281. if self.snap_on_start:
  282. return os.path.join(self.dir_path, self.source.vid + '.img')
  283. return os.path.join(self.dir_path, self.vid + '.img')
  284. @property
  285. def path_cow(self):
  286. img_name = self.vid + '-cow.img'
  287. return os.path.join(self.dir_path, img_name)
  288. @property
  289. def path_import(self):
  290. img_name = self.vid + '-import.img'
  291. return os.path.join(self.dir_path, img_name)
  292. def verify(self):
  293. ''' Verifies the volume. '''
  294. if not os.path.exists(self.path) and \
  295. (self.snap_on_start or self.save_on_stop):
  296. msg = 'Missing image file: {!s}.'.format(self.path)
  297. raise qubes.storage.StoragePoolException(msg)
  298. return True
  299. @property
  300. def script(self):
  301. if not self.snap_on_start and not self.save_on_stop:
  302. return None
  303. if not self.snap_on_start and self.save_on_stop:
  304. return 'block-origin'
  305. if self.snap_on_start:
  306. return 'block-snapshot'
  307. return None
  308. def block_device(self):
  309. ''' Return :py:class:`qubes.storage.BlockDevice` for serialization in
  310. the libvirt XML template as <disk>.
  311. '''
  312. path = self.path
  313. if self.snap_on_start:
  314. path += ":" + self.path_source_cow
  315. if self.snap_on_start or self.save_on_stop:
  316. path += ":" + self.path_cow
  317. return qubes.storage.BlockDevice(path, self.name, self.script, self.rw,
  318. self.domain, self.devtype)
  319. @property
  320. def revisions(self):
  321. if not hasattr(self, 'path_cow'):
  322. return {}
  323. old_revision = self.path_cow + '.old' # pylint: disable=no-member
  324. if not os.path.exists(old_revision):
  325. return {}
  326. seconds = os.path.getctime(old_revision)
  327. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  328. return {'old': iso_date}
  329. @property
  330. def size(self):
  331. with suppress(FileNotFoundError):
  332. self._size = os.path.getsize(self.path)
  333. return self._size
  334. @size.setter
  335. def size(self, _):
  336. raise qubes.storage.StoragePoolException(
  337. "You shouldn't use volume size setter, use resize method instead")
  338. @property
  339. def usage(self):
  340. ''' Returns the actualy used space '''
  341. usage = 0
  342. if self.save_on_stop or self.snap_on_start:
  343. usage = get_disk_usage(self.path_cow)
  344. if self.save_on_stop or not self.snap_on_start:
  345. usage += get_disk_usage(self.path)
  346. return usage
  347. def create_sparse_file(path, size):
  348. ''' Create an empty sparse file '''
  349. if os.path.exists(path):
  350. raise IOError("Volume %s already exists" % path)
  351. parent_dir = os.path.dirname(path)
  352. if not os.path.exists(parent_dir):
  353. os.makedirs(parent_dir)
  354. with open(path, 'a+b') as fh:
  355. fh.truncate(size)
  356. def get_disk_usage_one(st):
  357. '''Extract disk usage of one inode from its stat_result struct.
  358. If known, get real disk usage, as written to device by filesystem, not
  359. logical file size. Those values may be different for sparse files.
  360. :param os.stat_result st: stat result
  361. :returns: disk usage
  362. '''
  363. try:
  364. return st.st_blocks * BLKSIZE
  365. except AttributeError:
  366. return st.st_size
  367. def get_disk_usage(path):
  368. '''Get real disk usage of given path (file or directory).
  369. When *path* points to directory, then it is evaluated recursively.
  370. This function tries estimate real disk usage. See documentation of
  371. :py:func:`get_disk_usage_one`.
  372. :param str path: path to evaluate
  373. :returns: disk usage
  374. '''
  375. try:
  376. st = os.lstat(path)
  377. except OSError:
  378. return 0
  379. ret = get_disk_usage_one(st)
  380. # if path is not a directory, this is skipped
  381. for dirpath, dirnames, filenames in os.walk(path):
  382. for name in dirnames + filenames:
  383. ret += get_disk_usage_one(os.lstat(os.path.join(dirpath, name)))
  384. return ret
  385. def create_dir_if_not_exists(path):
  386. """ Check if a directory exists in if not create it.
  387. This method does not create any parent directories.
  388. """
  389. if not os.path.exists(path):
  390. os.mkdir(path)
  391. def copy_file(source, destination):
  392. '''Effective file copy, preserving sparse files etc.'''
  393. # We prefer to use Linux's cp, because it nicely handles sparse files
  394. assert os.path.exists(source), \
  395. "Missing the source %s to copy from" % source
  396. assert not os.path.exists(destination), \
  397. "Destination %s already exists" % destination
  398. parent_dir = os.path.dirname(destination)
  399. if not os.path.exists(parent_dir):
  400. os.makedirs(parent_dir)
  401. try:
  402. cmd = ['cp', '--sparse=always',
  403. '--reflink=auto', source, destination]
  404. subprocess.check_call(cmd)
  405. except subprocess.CalledProcessError:
  406. raise IOError('Error while copying {!r} to {!r}'.format(source,
  407. destination))
  408. def _remove_if_exists(path):
  409. ''' Removes a file if it exist, silently succeeds if file does not exist '''
  410. if os.path.exists(path):
  411. os.remove(path)
  412. def _check_path(path):
  413. ''' Raise an StoragePoolException if ``path`` does not exist'''
  414. if not os.path.exists(path):
  415. msg = 'Missing image file: %s' % path
  416. raise qubes.storage.StoragePoolException(msg)