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 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 init_volume(self, vm, volume_config):
  50. volume_config['dir_path'] = self.dir_path
  51. if os.path.join(self.dir_path, self._vid_prefix(vm)) == vm.dir_path:
  52. volume_config['backward_comp'] = True
  53. if 'vid' not in volume_config:
  54. volume_config['vid'] = os.path.join(
  55. self._vid_prefix(vm), volume_config['name'])
  56. try:
  57. if volume_config['reset_on_start']:
  58. volume_config['revisions_to_keep'] = 0
  59. except KeyError:
  60. pass
  61. finally:
  62. if 'revisions_to_keep' not in volume_config:
  63. volume_config['revisions_to_keep'] = self.revisions_to_keep
  64. volume_config['pool'] = self
  65. volume = FileVolume(**volume_config)
  66. self._volumes += [volume]
  67. return volume
  68. def remove(self, volume):
  69. if not volume.internal:
  70. return # do not remove random attached file volumes
  71. elif volume._is_snapshot:
  72. return # no need to remove, because it's just a snapshot
  73. else:
  74. _remove_if_exists(volume.path)
  75. if volume._is_origin:
  76. _remove_if_exists(volume.path_cow)
  77. def rename(self, volume, old_name, new_name):
  78. assert issubclass(volume.__class__, FileVolume)
  79. subdir, _, volume_path = volume.vid.split('/', 2)
  80. if volume._is_origin:
  81. # TODO: Renaming the old revisions
  82. new_path = os.path.join(self.dir_path, subdir, new_name)
  83. if not os.path.exists(new_path):
  84. os.mkdir(new_path, 0o755)
  85. new_volume_path = os.path.join(new_path, self.name + '.img')
  86. if not volume.backward_comp:
  87. os.rename(volume.path, new_volume_path)
  88. new_volume_path_cow = os.path.join(new_path, self.name + '-cow.img')
  89. if os.path.exists(new_volume_path_cow) and not volume.backward_comp:
  90. os.rename(volume.path_cow, new_volume_path_cow)
  91. volume.vid = os.path.join(subdir, new_name, volume_path)
  92. return volume
  93. def destroy(self):
  94. pass
  95. def setup(self):
  96. create_dir_if_not_exists(self.dir_path)
  97. appvms_path = os.path.join(self.dir_path, 'appvms')
  98. create_dir_if_not_exists(appvms_path)
  99. vm_templates_path = os.path.join(self.dir_path, 'vm-templates')
  100. create_dir_if_not_exists(vm_templates_path)
  101. @staticmethod
  102. def _vid_prefix(vm):
  103. ''' Helper to create a prefix for the vid for volume
  104. ''' # FIX Remove this if we drop the file backend
  105. import qubes.vm.templatevm # pylint: disable=redefined-outer-name
  106. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  107. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  108. subdir = 'vm-templates'
  109. else:
  110. subdir = 'appvms'
  111. return os.path.join(subdir, vm.name)
  112. def target_dir(self, vm):
  113. """ Returns the path to vmdir depending on the type of the VM.
  114. The default QubesOS file storage saves the vm images in three
  115. different directories depending on the ``QubesVM`` type:
  116. * ``appvms`` for ``QubesAppVm`` or ``QubesHvm``
  117. * ``vm-templates`` for ``QubesTemplateVm`` or ``QubesTemplateHvm``
  118. Args:
  119. vm: a QubesVM
  120. pool_dir: the root directory of the pool
  121. Returns:
  122. string (str) absolute path to the directory where the vm files
  123. are stored
  124. """
  125. return os.path.join(self.dir_path, self._vid_prefix(vm))
  126. @property
  127. def volumes(self):
  128. return self._volumes
  129. class FileVolume(qubes.storage.Volume):
  130. ''' Parent class for the xen volumes implementation which expects a
  131. `target_dir` param on initialization. '''
  132. def __init__(self, dir_path, backward_comp=False, **kwargs):
  133. self.dir_path = dir_path
  134. self.backward_comp = backward_comp
  135. assert self.dir_path, "dir_path not specified"
  136. super(FileVolume, self).__init__(**kwargs)
  137. if self.snap_on_start and self.source is None:
  138. msg = "snap_on_start specified on {!r} but no volume source set"
  139. msg = msg.format(self.name)
  140. raise qubes.storage.StoragePoolException(msg)
  141. elif not self.snap_on_start and self.source is not None:
  142. msg = "source specified on {!r} but no snap_on_start set"
  143. msg = msg.format(self.name)
  144. raise qubes.storage.StoragePoolException(msg)
  145. if self._is_snapshot:
  146. img_name = self.source.vid + '-cow.img'
  147. self.path_source_cow = os.path.join(self.dir_path, img_name)
  148. elif self._is_volume or self._is_volatile:
  149. pass
  150. elif self._is_origin:
  151. pass
  152. else:
  153. assert False, 'This should not happen'
  154. def create(self):
  155. assert isinstance(self.size, int) and self.size > 0, \
  156. 'Volatile volume size must be > 0'
  157. if self._is_origin:
  158. create_sparse_file(self.path, self.size)
  159. create_sparse_file(self.path_cow, self.size)
  160. elif not self._is_snapshot:
  161. if self.source is not None:
  162. source_path = os.path.join(self.dir_path,
  163. self.source.vid + '.img')
  164. copy_file(source_path, self.path)
  165. elif self._is_volatile:
  166. pass
  167. else:
  168. create_sparse_file(self.path, self.size)
  169. def is_dirty(self):
  170. return False # TODO: How to implement this?
  171. def resize(self, size):
  172. ''' Expands volume, throws
  173. :py:class:`qubst.storage.qubes.storage.StoragePoolException` if
  174. given size is less than current_size
  175. ''' # pylint: disable=no-self-use
  176. if not self.rw:
  177. msg = 'Can not resize reađonly volume {!s}'.format(self)
  178. raise qubes.storage.StoragePoolException(msg)
  179. if size <= self.size:
  180. raise qubes.storage.StoragePoolException(
  181. 'For your own safety, shrinking of %s is'
  182. ' disabled. If you really know what you'
  183. ' are doing, use `truncate` on %s manually.' %
  184. (self.name, self.vid))
  185. with open(self.path, 'a+b') as fd:
  186. fd.truncate(size)
  187. p = subprocess.Popen(['sudo', 'losetup', '--associated', self.path],
  188. stdout=subprocess.PIPE)
  189. result = p.communicate()
  190. m = re.match(r'^(/dev/loop\d+):\s', result[0].decode())
  191. if m is not None:
  192. loop_dev = m.group(1)
  193. # resize loop device
  194. subprocess.check_call(['sudo', 'losetup', '--set-capacity',
  195. loop_dev])
  196. self.size = size
  197. def commit(self):
  198. msg = 'Tried to commit a non commitable volume {!r}'.format(self)
  199. assert (self._is_origin or self._is_volume) and self.rw, msg
  200. if self._is_volume:
  201. return self
  202. if os.path.exists(self.path_cow):
  203. old_path = self.path_cow + '.old'
  204. os.rename(self.path_cow, old_path)
  205. old_umask = os.umask(0o002)
  206. with open(self.path_cow, 'w') as f_cow:
  207. f_cow.truncate(self.size)
  208. os.umask(old_umask)
  209. return self
  210. def export(self):
  211. return self.path
  212. def import_volume(self, src_volume):
  213. msg = "Can not import snapshot volume {!s} in to pool {!s} "
  214. msg = msg.format(src_volume, self)
  215. assert not src_volume.snap_on_start, msg
  216. if self.save_on_stop:
  217. copy_file(src_volume.export(), self.path)
  218. return self
  219. def import_data(self):
  220. return self.path
  221. def reset(self):
  222. ''' Remove and recreate a volatile volume '''
  223. assert self._is_volatile, "Not a volatile volume"
  224. assert isinstance(self.size, int) and self.size > 0, \
  225. 'Volatile volume size must be > 0'
  226. _remove_if_exists(self.path)
  227. with open(self.path, "w") as f_volatile:
  228. f_volatile.truncate(self.size)
  229. return self
  230. def revert(self, revision=None):
  231. if revision is not None:
  232. try:
  233. return self.revisions[revision]
  234. except KeyError:
  235. msg = "Volume {!r} does not have revision {!s}"
  236. msg = msg.format(self, revision)
  237. raise qubes.storage.StoragePoolException(msg)
  238. else:
  239. try:
  240. old_path = self.revisions.values().pop()
  241. os.rename(old_path, self.path_cow)
  242. except IndexError:
  243. msg = "Volume {!r} does not have old revisions".format(self)
  244. raise qubes.storage.StoragePoolException(msg)
  245. def start(self):
  246. if self._is_volatile:
  247. self.reset()
  248. else:
  249. _check_path(self.path)
  250. if self.snap_on_start:
  251. if not self.save_on_stop:
  252. # make sure previous snapshot is removed - even if VM
  253. # shutdown routing wasn't called (power interrupt or so)
  254. _remove_if_exists(self.path_cow)
  255. try:
  256. _check_path(self.path_cow)
  257. except qubes.storage.StoragePoolException:
  258. create_sparse_file(self.path_cow, self.size)
  259. _check_path(self.path_cow)
  260. if hasattr(self, 'path_source_cow'):
  261. try:
  262. _check_path(self.path_source_cow)
  263. except qubes.storage.StoragePoolException:
  264. create_sparse_file(self.path_source_cow, self.size)
  265. _check_path(self.path_source_cow)
  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._is_snapshot:
  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. def verify(self):
  285. ''' Verifies the volume. '''
  286. if not os.path.exists(self.path) and not self._is_volatile:
  287. msg = 'Missing image file: {!s}.'.format(self.path)
  288. raise qubes.storage.StoragePoolException(msg)
  289. return True
  290. @property
  291. def script(self):
  292. if self._is_volume or self._is_volatile:
  293. return None
  294. elif self._is_origin:
  295. return 'block-origin'
  296. elif self._is_origin_snapshot or self._is_snapshot:
  297. return 'block-snapshot'
  298. def block_device(self):
  299. ''' Return :py:class:`qubes.storage.BlockDevice` for serialization in
  300. the libvirt XML template as <disk>.
  301. '''
  302. path = self.path
  303. if self._is_snapshot:
  304. path += ":" + self.path_source_cow
  305. if self._is_origin or self._is_snapshot:
  306. path += ":" + self.path_cow
  307. return qubes.storage.BlockDevice(path, self.name, self.script, self.rw,
  308. self.domain, self.devtype)
  309. @property
  310. def revisions(self):
  311. if not hasattr(self, 'path_cow'):
  312. return {}
  313. old_revision = self.path_cow + '.old' # pylint: disable=no-member
  314. if not os.path.exists(old_revision):
  315. return {}
  316. seconds = os.path.getctime(old_revision)
  317. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  318. return {iso_date: old_revision}
  319. @property
  320. def usage(self):
  321. ''' Returns the actualy used space '''
  322. return get_disk_usage(self.vid)
  323. @property
  324. def _is_volatile(self):
  325. ''' Internal helper. Useful for differentiating volume handling '''
  326. return not self.snap_on_start and not self.save_on_stop
  327. @property
  328. def _is_origin(self):
  329. ''' Internal helper. Useful for differentiating volume handling '''
  330. # pylint: disable=line-too-long
  331. return self.save_on_stop and self.revisions_to_keep > 0 # NOQA
  332. @property
  333. def _is_snapshot(self):
  334. ''' Internal helper. Useful for differentiating volume handling '''
  335. return self.snap_on_start and not self.save_on_stop
  336. @property
  337. def _is_origin_snapshot(self):
  338. ''' Internal helper. Useful for differentiating volume handling '''
  339. return self.snap_on_start and self.save_on_stop
  340. @property
  341. def _is_volume(self):
  342. ''' Internal helper. Usefull for differentiating volume handling '''
  343. # pylint: disable=line-too-long
  344. return not self.snap_on_start and self.save_on_stop and self.revisions_to_keep == 0 # NOQA
  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 estiate 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=auto',
  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)