file.py 17 KB

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