file.py 15 KB

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