file.py 15 KB

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