file.py 17 KB

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