file.py 18 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 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 reset(self, volume):
  167. ''' Remove and recreate a volatile volume '''
  168. assert volume._is_volatile, "Not a volatile volume"
  169. assert isinstance(volume.size, int) and volume.size > 0, \
  170. 'Volatile volume size must be > 0'
  171. _remove_if_exists(volume.path)
  172. with open(volume.path, "w") as f_volatile:
  173. f_volatile.truncate(volume.size)
  174. return volume
  175. def revert(self, volume, revision=None):
  176. if revision is not None:
  177. try:
  178. return volume.revisions[revision]
  179. except KeyError:
  180. msg = "Volume {!r} does not have revision {!s}"
  181. msg = msg.format(volume, revision)
  182. raise qubes.storage.StoragePoolException(msg)
  183. else:
  184. try:
  185. old_path = volume.revisions.values().pop()
  186. os.rename(old_path, volume.path_cow)
  187. except IndexError:
  188. msg = "Volume {!r} does not have old revisions".format(volume)
  189. raise qubes.storage.StoragePoolException(msg)
  190. def setup(self):
  191. create_dir_if_not_exists(self.dir_path)
  192. appvms_path = os.path.join(self.dir_path, 'appvms')
  193. create_dir_if_not_exists(appvms_path)
  194. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  195. create_dir_if_not_exists(vm_templates_path)
  196. def start(self, volume):
  197. if volume._is_volatile:
  198. self.reset(volume)
  199. else:
  200. _check_path(volume.path)
  201. if volume.snap_on_start:
  202. if not volume.save_on_stop:
  203. # make sure previous snapshot is removed - even if VM
  204. # shutdown routing wasn't called (power interrupt or so)
  205. _remove_if_exists(volume.path_cow)
  206. try:
  207. _check_path(volume.path_cow)
  208. except qubes.storage.StoragePoolException:
  209. create_sparse_file(volume.path_cow, volume.size)
  210. _check_path(volume.path_cow)
  211. if hasattr(volume, 'path_source_cow'):
  212. try:
  213. _check_path(volume.path_source_cow)
  214. except qubes.storage.StoragePoolException:
  215. create_sparse_file(volume.path_source_cow, volume.size)
  216. _check_path(volume.path_source_cow)
  217. return volume
  218. def stop(self, volume):
  219. if volume.save_on_stop:
  220. self.commit(volume)
  221. elif volume.snap_on_start:
  222. _remove_if_exists(volume.path_cow)
  223. else:
  224. _remove_if_exists(volume.path)
  225. return volume
  226. @staticmethod
  227. def _vid_prefix(vm):
  228. ''' Helper to create a prefix for the vid for volume
  229. ''' # FIX Remove this if we drop the file backend
  230. import qubes.vm.templatevm # pylint: disable=redefined-outer-name
  231. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  232. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  233. subdir = 'vm-templates'
  234. else:
  235. subdir = 'appvms'
  236. return os.path.join(subdir, vm.name)
  237. def target_dir(self, vm):
  238. """ Returns the path to vmdir depending on the type of the VM.
  239. The default QubesOS file storage saves the vm images in three
  240. different directories depending on the ``QubesVM`` type:
  241. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  242. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  243. Args:
  244. vm: a QubesVM
  245. pool_dir: the root directory of the pool
  246. Returns:
  247. string (str) absolute path to the directory where the vm files
  248. are stored
  249. """
  250. return os.path.join(self.dir_path, self._vid_prefix(vm))
  251. def verify(self, volume):
  252. return volume.verify()
  253. @property
  254. def volumes(self):
  255. return self._volumes
  256. class FileVolume(qubes.storage.Volume):
  257. ''' Parent class for the xen volumes implementation which expects a
  258. `target_dir` param on initialization. '''
  259. def __init__(self, dir_path, backward_comp=False, **kwargs):
  260. self.dir_path = dir_path
  261. self.backward_comp = backward_comp
  262. assert self.dir_path, "dir_path not specified"
  263. super(FileVolume, self).__init__(**kwargs)
  264. if self.snap_on_start and self.source is None:
  265. msg = "snap_on_start specified on {!r} but no volume source set"
  266. msg = msg.format(self.name)
  267. raise qubes.storage.StoragePoolException(msg)
  268. elif not self.snap_on_start and self.source is not None:
  269. msg = "source specified on {!r} but no snap_on_start set"
  270. msg = msg.format(self.name)
  271. raise qubes.storage.StoragePoolException(msg)
  272. if self._is_snapshot:
  273. self.path = os.path.join(self.dir_path, self.source + '.img')
  274. img_name = self.source + '-cow.img'
  275. self.path_source_cow = os.path.join(self.dir_path, img_name)
  276. img_name = self.vid + '-cow.img'
  277. self.path_cow = os.path.join(self.dir_path, img_name)
  278. elif self._is_volume or self._is_volatile:
  279. self.path = os.path.join(self.dir_path, self.vid + '.img')
  280. elif self._is_origin:
  281. self.path = os.path.join(self.dir_path, self.vid + '.img')
  282. img_name = self.vid + '-cow.img'
  283. self.path_cow = os.path.join(self.dir_path, img_name)
  284. else:
  285. assert False, 'This should not happen'
  286. def verify(self):
  287. ''' Verifies the volume. '''
  288. if not os.path.exists(self.path) and not self._is_volatile:
  289. msg = 'Missing image file: {!s}.'.format(self.path)
  290. raise qubes.storage.StoragePoolException(msg)
  291. return True
  292. @property
  293. def script(self):
  294. if self._is_volume or self._is_volatile:
  295. return None
  296. elif self._is_origin:
  297. return 'block-origin'
  298. elif self._is_origin_snapshot or self._is_snapshot:
  299. return 'block-snapshot'
  300. def block_device(self):
  301. ''' Return :py:class:`qubes.storage.BlockDevice` for serialization in
  302. the libvirt XML template as <disk>.
  303. '''
  304. path = self.path
  305. if self._is_snapshot:
  306. path += ":" + self.path_source_cow
  307. if self._is_origin or self._is_snapshot:
  308. path += ":" + self.path_cow
  309. return qubes.storage.BlockDevice(path, self.name, self.script, self.rw,
  310. self.domain, self.devtype)
  311. @property
  312. def revisions(self):
  313. if not hasattr(self, 'path_cow'):
  314. return {}
  315. old_revision = self.path_cow + '.old' # pylint: disable=no-member
  316. if not os.path.exists(old_revision):
  317. return {}
  318. seconds = os.path.getctime(old_revision)
  319. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  320. return {iso_date: old_revision}
  321. @property
  322. def usage(self):
  323. ''' Returns the actualy used space '''
  324. return get_disk_usage(self.vid)
  325. @property
  326. def _is_volatile(self):
  327. ''' Internal helper. Useful for differentiating volume handling '''
  328. return not self.snap_on_start and not self.save_on_stop
  329. @property
  330. def _is_origin(self):
  331. ''' Internal helper. Useful for differentiating volume handling '''
  332. # pylint: disable=line-too-long
  333. return self.save_on_stop and self.revisions_to_keep > 0 # NOQA
  334. @property
  335. def _is_snapshot(self):
  336. ''' Internal helper. Useful for differentiating volume handling '''
  337. return self.snap_on_start and not self.save_on_stop
  338. @property
  339. def _is_origin_snapshot(self):
  340. ''' Internal helper. Useful for differentiating volume handling '''
  341. return self.snap_on_start and self.save_on_stop
  342. @property
  343. def _is_volume(self):
  344. ''' Internal helper. Usefull for differentiating volume handling '''
  345. # pylint: disable=line-too-long
  346. return not self.snap_on_start and self.save_on_stop and self.revisions_to_keep == 0 # NOQA
  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 estiate 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=auto',
  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)