file.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program 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
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. ''' This module contains pool implementations backed by file images'''
  24. from __future__ import absolute_import
  25. import os
  26. import os.path
  27. import re
  28. import subprocess
  29. import qubes.devices
  30. import qubes.storage
  31. BLKSIZE = 512
  32. class FilePool(qubes.storage.Pool):
  33. ''' File based 'original' disk implementation
  34. ''' # pylint: disable=protected-access
  35. driver = 'file'
  36. def __init__(self, revisions_to_keep=1, dir_path=None, **kwargs):
  37. super(FilePool, self).__init__(revisions_to_keep=revisions_to_keep,
  38. **kwargs)
  39. assert dir_path, "No pool dir_path specified"
  40. self.dir_path = os.path.normpath(dir_path)
  41. self._volumes = []
  42. @property
  43. def config(self):
  44. return {
  45. 'name': self.name,
  46. 'dir_path': self.dir_path,
  47. 'driver': FilePool.driver,
  48. 'revisions_to_keep': self.revisions_to_keep
  49. }
  50. def clone(self, source, target):
  51. new_dir = os.path.dirname(target.path)
  52. if target._is_origin or target._is_volume:
  53. if not os.path.exists:
  54. os.makedirs(new_dir)
  55. copy_file(source.path, target.path)
  56. return target
  57. def create(self, volume):
  58. assert isinstance(volume.size, int) and volume.size > 0, \
  59. 'Volatile volume size must be > 0'
  60. if volume._is_origin:
  61. create_sparse_file(volume.path, volume.size)
  62. create_sparse_file(volume.path_cow, volume.size)
  63. elif not volume._is_snapshot:
  64. if volume.source is not None:
  65. source_path = os.path.join(self.dir_path,
  66. volume.source + '.img')
  67. copy_file(source_path, volume.path)
  68. elif volume._is_volatile:
  69. pass
  70. else:
  71. create_sparse_file(volume.path, volume.size)
  72. def init_volume(self, vm, volume_config):
  73. volume_config['dir_path'] = self.dir_path
  74. if os.path.join(self.dir_path, self._vid_prefix(vm)) == vm.dir_path:
  75. volume_config['backward_comp'] = True
  76. if 'vid' not in volume_config:
  77. volume_config['vid'] = os.path.join(
  78. self._vid_prefix(vm), volume_config['name'])
  79. try:
  80. if volume_config['reset_on_start']:
  81. volume_config['revisions_to_keep'] = 0
  82. except KeyError:
  83. pass
  84. finally:
  85. if 'revisions_to_keep' not in volume_config:
  86. volume_config['revisions_to_keep'] = self.revisions_to_keep
  87. volume = FileVolume(**volume_config)
  88. self._volumes += [volume]
  89. return volume
  90. def is_dirty(self, volume):
  91. return False # TODO: How to implement this?
  92. def resize(self, volume, size):
  93. ''' Expands volume, throws
  94. :py:class:`qubst.storage.qubes.storage.StoragePoolException` if
  95. given size is less than current_size
  96. ''' # pylint: disable=no-self-use
  97. if not volume.rw:
  98. msg = 'Can not resize reađonly volume {!s}'.format(volume)
  99. raise qubes.storage.StoragePoolException(msg)
  100. if size <= volume.size:
  101. raise qubes.storage.StoragePoolException(
  102. 'For your own safety, shrinking of %s is'
  103. ' disabled. If you really know what you'
  104. ' are doing, use `truncate` on %s manually.' %
  105. (volume.name, volume.vid))
  106. with open(volume.path, 'a+b') as fd:
  107. fd.truncate(size)
  108. p = subprocess.Popen(['sudo', 'losetup', '--associated', volume.path],
  109. stdout=subprocess.PIPE)
  110. result = p.communicate()
  111. m = re.match(r'^(/dev/loop\d+):\s', result[0].decode())
  112. if m is not None:
  113. loop_dev = m.group(1)
  114. # resize loop device
  115. subprocess.check_call(['sudo', 'losetup', '--set-capacity',
  116. loop_dev])
  117. volume.size = size
  118. def remove(self, volume):
  119. if not volume.internal:
  120. return # do not remove random attached file volumes
  121. elif volume._is_snapshot:
  122. return # no need to remove, because it's just a snapshot
  123. else:
  124. _remove_if_exists(volume.path)
  125. if volume._is_origin:
  126. _remove_if_exists(volume.path_cow)
  127. def rename(self, volume, old_name, new_name):
  128. assert issubclass(volume.__class__, FileVolume)
  129. subdir, _, volume_path = volume.vid.split('/', 2)
  130. if volume._is_origin:
  131. # TODO: Renaming the old revisions
  132. new_path = os.path.join(self.dir_path, subdir, new_name)
  133. if not os.path.exists(new_path):
  134. os.mkdir(new_path, 0o755)
  135. new_volume_path = os.path.join(new_path, self.name + '.img')
  136. if not volume.backward_comp:
  137. os.rename(volume.path, new_volume_path)
  138. new_volume_path_cow = os.path.join(new_path, self.name + '-cow.img')
  139. if os.path.exists(new_volume_path_cow) and not volume.backward_comp:
  140. os.rename(volume.path_cow, new_volume_path_cow)
  141. volume.vid = os.path.join(subdir, new_name, volume_path)
  142. return volume
  143. def import_volume(self, dst_pool, dst_volume, src_pool, src_volume):
  144. msg = "Can not import snapshot volume {!s} in to pool {!s} "
  145. msg = msg.format(src_volume, self)
  146. assert not src_volume.snap_on_start, msg
  147. if dst_volume.save_on_stop:
  148. copy_file(src_pool.export(src_volume), dst_volume.path)
  149. return dst_volume
  150. def commit(self, volume):
  151. msg = 'Tried to commit a non commitable volume {!r}'.format(volume)
  152. assert (volume._is_origin or volume._is_volume) and volume.rw, msg
  153. if volume._is_volume:
  154. return volume
  155. if os.path.exists(volume.path_cow):
  156. old_path = volume.path_cow + '.old'
  157. os.rename(volume.path_cow, old_path)
  158. old_umask = os.umask(0o002)
  159. with open(volume.path_cow, 'w') as f_cow:
  160. f_cow.truncate(volume.size)
  161. os.umask(old_umask)
  162. return volume
  163. def destroy(self):
  164. pass
  165. def export(self, volume):
  166. return volume.path
  167. def reset(self, volume):
  168. ''' Remove and recreate a volatile volume '''
  169. assert volume._is_volatile, "Not a volatile volume"
  170. assert isinstance(volume.size, int) and volume.size > 0, \
  171. 'Volatile volume size must be > 0'
  172. _remove_if_exists(volume.path)
  173. with open(volume.path, "w") as f_volatile:
  174. f_volatile.truncate(volume.size)
  175. return volume
  176. def revert(self, volume, revision=None):
  177. if revision is not None:
  178. try:
  179. return volume.revisions[revision]
  180. except KeyError:
  181. msg = "Volume {!r} does not have revision {!s}"
  182. msg = msg.format(volume, revision)
  183. raise qubes.storage.StoragePoolException(msg)
  184. else:
  185. try:
  186. old_path = volume.revisions.values().pop()
  187. os.rename(old_path, volume.path_cow)
  188. except IndexError:
  189. msg = "Volume {!r} does not have old revisions".format(volume)
  190. raise qubes.storage.StoragePoolException(msg)
  191. def setup(self):
  192. create_dir_if_not_exists(self.dir_path)
  193. appvms_path = os.path.join(self.dir_path, 'appvms')
  194. create_dir_if_not_exists(appvms_path)
  195. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  196. create_dir_if_not_exists(vm_templates_path)
  197. def start(self, volume):
  198. if volume._is_snapshot or volume._is_origin:
  199. _check_path(volume.path)
  200. try:
  201. _check_path(volume.path_cow)
  202. except qubes.storage.StoragePoolException:
  203. create_sparse_file(volume.path_cow, volume.size)
  204. _check_path(volume.path_cow)
  205. elif volume._is_volatile:
  206. self.reset(volume)
  207. return volume
  208. def stop(self, volume):
  209. if volume.save_on_stop:
  210. self.commit(volume)
  211. elif volume._is_volatile:
  212. _remove_if_exists(volume.path)
  213. return volume
  214. @staticmethod
  215. def _vid_prefix(vm):
  216. ''' Helper to create a prefix for the vid for volume
  217. ''' # FIX Remove this if we drop the file backend
  218. import qubes.vm.templatevm # pylint: disable=redefined-outer-name
  219. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  220. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  221. subdir = 'vm-templates'
  222. else:
  223. subdir = 'appvms'
  224. return os.path.join(subdir, vm.name)
  225. def target_dir(self, vm):
  226. """ Returns the path to vmdir depending on the type of the VM.
  227. The default QubesOS file storage saves the vm images in three
  228. different directories depending on the ``QubesVM`` type:
  229. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  230. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  231. Args:
  232. vm: a QubesVM
  233. pool_dir: the root directory of the pool
  234. Returns:
  235. string (str) absolute path to the directory where the vm files
  236. are stored
  237. """
  238. return os.path.join(self.dir_path, self._vid_prefix(vm))
  239. def verify(self, volume):
  240. return volume.verify()
  241. @property
  242. def volumes(self):
  243. return self._volumes
  244. class FileVolume(qubes.storage.Volume):
  245. ''' Parent class for the xen volumes implementation which expects a
  246. `target_dir` param on initialization. '''
  247. def __init__(self, dir_path, backward_comp=False, **kwargs):
  248. self.dir_path = dir_path
  249. self.backward_comp = backward_comp
  250. assert self.dir_path, "dir_path not specified"
  251. super(FileVolume, self).__init__(**kwargs)
  252. if self.snap_on_start and self.source is None:
  253. msg = "snap_on_start specified on {!r} but no volume source set"
  254. msg = msg.format(self.name)
  255. raise qubes.storage.StoragePoolException(msg)
  256. elif not self.snap_on_start and self.source is not None:
  257. msg = "source specified on {!r} but no snap_on_start set"
  258. msg = msg.format(self.name)
  259. raise qubes.storage.StoragePoolException(msg)
  260. if self._is_snapshot:
  261. self.path = os.path.join(self.dir_path, self.source + '.img')
  262. img_name = self.source + '-cow.img'
  263. self.path_cow = os.path.join(self.dir_path, img_name)
  264. elif self._is_volume or self._is_volatile:
  265. self.path = os.path.join(self.dir_path, self.vid + '.img')
  266. elif self._is_origin:
  267. self.path = os.path.join(self.dir_path, self.vid + '.img')
  268. img_name = self.vid + '-cow.img'
  269. self.path_cow = os.path.join(self.dir_path, img_name)
  270. else:
  271. assert False, 'This should not happen'
  272. def verify(self):
  273. ''' Verifies the volume. '''
  274. if not os.path.exists(self.path) and not self._is_volatile:
  275. msg = 'Missing image file: {!s}.'.format(self.path)
  276. raise qubes.storage.StoragePoolException(msg)
  277. return True
  278. @property
  279. def script(self):
  280. if self._is_volume or self._is_volatile:
  281. return None
  282. elif self._is_origin:
  283. return 'block-origin'
  284. elif self._is_origin_snapshot or self._is_snapshot:
  285. return 'block-snapshot'
  286. def block_device(self):
  287. ''' Return :py:class:`qubes.devices.BlockDevice` for serialization in
  288. the libvirt XML template as <disk>.
  289. '''
  290. path = self.path
  291. if self._is_origin or self._is_snapshot:
  292. path += ":" + self.path_cow
  293. return qubes.devices.BlockDevice(path, self.name, self.script, self.rw,
  294. self.domain, self.devtype)
  295. @property
  296. def revisions(self):
  297. if not hasattr(self, 'path_cow'):
  298. return {}
  299. old_revision = self.path_cow + '.old' # pylint: disable=no-member
  300. if not os.path.exists(old_revision):
  301. return {}
  302. else:
  303. seconds = os.path.getctime(old_revision)
  304. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  305. return {iso_date: old_revision}
  306. @property
  307. def usage(self):
  308. ''' Returns the actualy used space '''
  309. return get_disk_usage(self.vid)
  310. @property
  311. def _is_volatile(self):
  312. ''' Internal helper. Useful for differentiating volume handling '''
  313. return not self.snap_on_start and not self.save_on_stop
  314. @property
  315. def _is_origin(self):
  316. ''' Internal helper. Useful for differentiating volume handling '''
  317. # pylint: disable=line-too-long
  318. return not self.snap_on_start and self.save_on_stop and self.revisions_to_keep > 0 # NOQA
  319. @property
  320. def _is_snapshot(self):
  321. ''' Internal helper. Useful for differentiating volume handling '''
  322. return self.snap_on_start and not self.save_on_stop
  323. @property
  324. def _is_origin_snapshot(self):
  325. ''' Internal helper. Useful for differentiating volume handling '''
  326. return self.snap_on_start and self.save_on_stop
  327. @property
  328. def _is_volume(self):
  329. ''' Internal helper. Usefull for differentiating volume handling '''
  330. # pylint: disable=line-too-long
  331. return not self.snap_on_start and self.save_on_stop and self.revisions_to_keep == 0 # NOQA
  332. def create_sparse_file(path, size):
  333. ''' Create an empty sparse file '''
  334. if os.path.exists(path):
  335. raise IOError("Volume %s already exists", path)
  336. parent_dir = os.path.dirname(path)
  337. if not os.path.exists(parent_dir):
  338. os.makedirs(parent_dir)
  339. with open(path, 'a+b') as fh:
  340. fh.truncate(size)
  341. def get_disk_usage_one(st):
  342. '''Extract disk usage of one inode from its stat_result struct.
  343. If known, get real disk usage, as written to device by filesystem, not
  344. logical file size. Those values may be different for sparse files.
  345. :param os.stat_result st: stat result
  346. :returns: disk usage
  347. '''
  348. try:
  349. return st.st_blocks * BLKSIZE
  350. except AttributeError:
  351. return st.st_size
  352. def get_disk_usage(path):
  353. '''Get real disk usage of given path (file or directory).
  354. When *path* points to directory, then it is evaluated recursively.
  355. This function tries estiate real disk usage. See documentation of
  356. :py:func:`get_disk_usage_one`.
  357. :param str path: path to evaluate
  358. :returns: disk usage
  359. '''
  360. try:
  361. st = os.lstat(path)
  362. except OSError:
  363. return 0
  364. ret = get_disk_usage_one(st)
  365. # if path is not a directory, this is skipped
  366. for dirpath, dirnames, filenames in os.walk(path):
  367. for name in dirnames + filenames:
  368. ret += get_disk_usage_one(os.lstat(os.path.join(dirpath, name)))
  369. return ret
  370. def create_dir_if_not_exists(path):
  371. """ Check if a directory exists in if not create it.
  372. This method does not create any parent directories.
  373. """
  374. if not os.path.exists(path):
  375. os.mkdir(path)
  376. def copy_file(source, destination):
  377. '''Effective file copy, preserving sparse files etc.'''
  378. # We prefer to use Linux's cp, because it nicely handles sparse files
  379. assert os.path.exists(source), \
  380. "Missing the source %s to copy from" % source
  381. assert not os.path.exists(destination), \
  382. "Destination %s already exists" % destination
  383. parent_dir = os.path.dirname(destination)
  384. if not os.path.exists(parent_dir):
  385. os.makedirs(parent_dir)
  386. try:
  387. cmd = ['cp', '--sparse=auto',
  388. '--reflink=auto', source, destination]
  389. subprocess.check_call(cmd)
  390. except subprocess.CalledProcessError:
  391. raise IOError('Error while copying {!r} to {!r}'.format(source,
  392. destination))
  393. def _remove_if_exists(path):
  394. ''' Removes a file if it exist, silently succeeds if file does not exist '''
  395. if os.path.exists(path):
  396. os.remove(path)
  397. def _check_path(path):
  398. ''' Raise an StoragePoolException if ``path`` does not exist'''
  399. if not os.path.exists(path):
  400. msg = 'Missing image file: %s' % path
  401. raise qubes.storage.StoragePoolException(msg)