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