lvm.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. #
  20. ''' Driver for storing vm images in a LVM thin pool '''
  21. import logging
  22. import os
  23. import subprocess
  24. import qubes
  25. import qubes.storage
  26. import qubes.utils
  27. def check_lvm_version():
  28. #Check if lvm is very very old, like in Travis-CI
  29. try:
  30. lvm_help = subprocess.check_output(['lvm', 'lvcreate', '--help'],
  31. stderr=subprocess.DEVNULL).decode()
  32. return '--setactivationskip' not in lvm_help
  33. except (subprocess.CalledProcessError, FileNotFoundError):
  34. pass
  35. lvm_is_very_old = check_lvm_version()
  36. class ThinPool(qubes.storage.Pool):
  37. ''' LVM Thin based pool implementation
  38. ''' # pylint: disable=protected-access
  39. size_cache = None
  40. driver = 'lvm_thin'
  41. def __init__(self, volume_group, thin_pool, revisions_to_keep=1, **kwargs):
  42. super(ThinPool, self).__init__(revisions_to_keep=revisions_to_keep,
  43. **kwargs)
  44. self.volume_group = volume_group
  45. self.thin_pool = thin_pool
  46. self._pool_id = "{!s}/{!s}".format(volume_group, thin_pool)
  47. self.log = logging.getLogger('qube.storage.lvm.%s' % self._pool_id)
  48. @property
  49. def config(self):
  50. return {
  51. 'name': self.name,
  52. 'volume_group': self.volume_group,
  53. 'thin_pool': self.thin_pool,
  54. 'driver': ThinPool.driver
  55. }
  56. def destroy(self):
  57. pass # TODO Should we remove an existing pool?
  58. def init_volume(self, vm, volume_config):
  59. ''' Initialize a :py:class:`qubes.storage.Volume` from `volume_config`.
  60. '''
  61. if 'vid' not in volume_config.keys():
  62. if vm and hasattr(vm, 'name'):
  63. vm_name = vm.name
  64. else:
  65. # for the future if we have volumes not belonging to a vm
  66. vm_name = qubes.utils.random_string()
  67. assert self.name
  68. volume_config['vid'] = "{!s}/vm-{!s}-{!s}".format(
  69. self.volume_group, vm_name, volume_config['name'])
  70. volume_config['volume_group'] = self.volume_group
  71. volume_config['pool'] = self
  72. return ThinVolume(**volume_config)
  73. def setup(self):
  74. pass # TODO Should we create a non existing pool?
  75. def list_volumes(self):
  76. ''' Return a list of volumes managed by this pool '''
  77. volumes = []
  78. for vid, vol_info in size_cache.items():
  79. if not vid.startswith(self.volume_group + '/'):
  80. continue
  81. if vol_info['pool_lv'] != self.thin_pool:
  82. continue
  83. if vid.endswith('-snap'):
  84. # implementation detail volume
  85. continue
  86. config = {
  87. 'pool': self,
  88. 'vid': vid,
  89. 'name': vid,
  90. 'volume_group': self.volume_group,
  91. 'rw': vol_info['attr'][1] == 'w',
  92. }
  93. volumes += [ThinVolume(**config)]
  94. return volumes
  95. def init_cache(log=logging.getLogger('qube.storage.lvm')):
  96. cmd = ['lvs', '--noheadings', '-o',
  97. 'vg_name,pool_lv,name,lv_size,data_percent,lv_attr',
  98. '--units', 'b', '--separator', ',']
  99. if os.getuid() != 0:
  100. cmd.insert(0, 'sudo')
  101. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  102. close_fds=True)
  103. out, err = p.communicate()
  104. return_code = p.returncode
  105. if return_code == 0 and err:
  106. log.warning(err)
  107. elif return_code != 0:
  108. raise qubes.storage.StoragePoolException(err)
  109. result = {}
  110. for line in out.splitlines():
  111. line = line.decode().strip()
  112. pool_name, pool_lv, name, size, usage_percent, attr = line.split(',', 5)
  113. if '' in [pool_name, pool_lv, name, size, usage_percent]:
  114. continue
  115. name = pool_name + "/" + name
  116. size = int(size[:-1])
  117. usage = int(size / 100 * float(usage_percent))
  118. result[name] = {'size': size, 'usage': usage, 'pool_lv': pool_lv,
  119. 'attr': attr}
  120. return result
  121. size_cache = init_cache()
  122. class ThinVolume(qubes.storage.Volume):
  123. ''' Default LVM thin volume implementation
  124. ''' # pylint: disable=too-few-public-methods
  125. def __init__(self, volume_group, size=0, **kwargs):
  126. self.volume_group = volume_group
  127. super(ThinVolume, self).__init__(size=size, **kwargs)
  128. self.log = logging.getLogger('qube.storage.lvm.%s' % str(self.pool))
  129. if self.snap_on_start and self.source is None:
  130. msg = "snap_on_start specified on {!r} but no volume source set"
  131. msg = msg.format(self.name)
  132. raise qubes.storage.StoragePoolException(msg)
  133. elif not self.snap_on_start and self.source is not None:
  134. msg = "source specified on {!r} but no snap_on_start set"
  135. msg = msg.format(self.name)
  136. raise qubes.storage.StoragePoolException(msg)
  137. if self.snap_on_start:
  138. self._vid_snap = self.vid + '-snap'
  139. self._size = size
  140. @property
  141. def path(self):
  142. return '/dev/' + self.vid
  143. @property
  144. def revisions(self):
  145. path = self.path + '-back'
  146. if os.path.exists(path):
  147. seconds = os.path.getctime(path)
  148. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  149. return {iso_date: path}
  150. return {}
  151. @property
  152. def _is_origin(self):
  153. return not self.snap_on_start and self.save_on_stop
  154. @property
  155. def _is_origin_snapshot(self):
  156. return self.snap_on_start and self.save_on_stop
  157. @property
  158. def _is_snapshot(self):
  159. return self.snap_on_start and not self.save_on_stop
  160. @property
  161. def _is_volatile(self):
  162. return not self.snap_on_start and not self.save_on_stop
  163. @property
  164. def size(self):
  165. try:
  166. return qubes.storage.lvm.size_cache[self.vid]['size']
  167. except KeyError:
  168. return self._size
  169. @size.setter
  170. def size(self, _):
  171. raise qubes.storage.StoragePoolException(
  172. "You shouldn't use lvm size setter")
  173. def _reset(self):
  174. ''' Resets a volatile volume '''
  175. assert self._is_volatile, \
  176. 'Expected a volatile volume, but got {!r}'.format(self)
  177. self.log.debug('Resetting volatile ' + self.vid)
  178. try:
  179. cmd = ['remove', self.vid]
  180. qubes_lvm(cmd, self.log)
  181. except qubes.storage.StoragePoolException:
  182. pass
  183. # pylint: disable=protected-access
  184. cmd = ['create', self.pool._pool_id, self.vid.split('/')[1],
  185. str(self.size)]
  186. qubes_lvm(cmd, self.log)
  187. def _commit(self):
  188. msg = "Trying to commit {!s}, but it has save_on_stop == False"
  189. msg = msg.format(self)
  190. assert self.save_on_stop, msg
  191. msg = "Trying to commit {!s}, but it has rw == False"
  192. msg = msg.format(self)
  193. assert self.rw, msg
  194. assert hasattr(self, '_vid_snap')
  195. try:
  196. cmd = ['remove', self.vid + "-back"]
  197. qubes_lvm(cmd, self.log)
  198. except qubes.storage.StoragePoolException:
  199. pass
  200. cmd = ['clone', self.vid, self.vid + "-back"]
  201. qubes_lvm(cmd, self.log)
  202. cmd = ['remove', self.vid]
  203. qubes_lvm(cmd, self.log)
  204. cmd = ['clone', self._vid_snap, self.vid]
  205. qubes_lvm(cmd, self.log)
  206. def create(self):
  207. assert self.vid
  208. assert self.size
  209. if self.save_on_stop:
  210. if self.source:
  211. cmd = ['clone', str(self.source), self.vid]
  212. else:
  213. cmd = [
  214. 'create',
  215. self.pool._pool_id, # pylint: disable=protected-access
  216. self.vid.split('/', 1)[1],
  217. str(self.size)
  218. ]
  219. qubes_lvm(cmd, self.log)
  220. reset_cache()
  221. return self
  222. def remove(self):
  223. assert self.vid
  224. if self.is_dirty():
  225. cmd = ['remove', self._vid_snap]
  226. qubes_lvm(cmd, self.log)
  227. if not os.path.exists(self.path):
  228. return
  229. cmd = ['remove', self.vid]
  230. qubes_lvm(cmd, self.log)
  231. reset_cache()
  232. def export(self):
  233. ''' Returns an object that can be `open()`. '''
  234. devpath = '/dev/' + self.vid
  235. return devpath
  236. def import_volume(self, src_volume):
  237. if not src_volume.save_on_stop:
  238. return self
  239. # HACK: neat trick to speed up testing if you have same physical thin
  240. # pool assigned to two qubes-pools i.e: qubes_dom0 and test-lvm
  241. # pylint: disable=line-too-long
  242. if isinstance(src_volume.pool, ThinPool) and \
  243. src_volume.pool.thin_pool == self.pool.thin_pool: # NOQA
  244. cmd = ['remove', self.vid]
  245. qubes_lvm(cmd, self.log)
  246. cmd = ['clone', str(src_volume), str(self)]
  247. qubes_lvm(cmd, self.log)
  248. else:
  249. src_path = src_volume.export()
  250. cmd = ['sudo', 'dd', 'if=' + src_path, 'of=/dev/' + self.vid,
  251. 'conv=sparse']
  252. subprocess.check_call(cmd)
  253. reset_cache()
  254. return self
  255. def import_data(self):
  256. ''' Returns an object that can be `open()`. '''
  257. devpath = '/dev/' + self.vid
  258. return devpath
  259. def is_dirty(self):
  260. if self.save_on_stop:
  261. return os.path.exists(self.path + '-snap')
  262. return False
  263. def revert(self, revision=None):
  264. old_path = self.path + '-back'
  265. if not os.path.exists(old_path):
  266. msg = "Volume {!s} has no {!s}".format(self, old_path)
  267. raise qubes.storage.StoragePoolException(msg)
  268. cmd = ['remove', self.vid]
  269. qubes_lvm(cmd, self.log)
  270. cmd = ['clone', self.vid + '-back', self.vid]
  271. qubes_lvm(cmd, self.log)
  272. reset_cache()
  273. return self
  274. def resize(self, size):
  275. ''' Expands volume, throws
  276. :py:class:`qubst.storage.qubes.storage.StoragePoolException` if
  277. given size is less than current_size
  278. '''
  279. if not self.rw:
  280. msg = 'Can not resize reađonly volume {!s}'.format(self)
  281. raise qubes.storage.StoragePoolException(msg)
  282. if size <= self.size:
  283. raise qubes.storage.StoragePoolException(
  284. 'For your own safety, shrinking of %s is'
  285. ' disabled. If you really know what you'
  286. ' are doing, use `lvresize` on %s manually.' %
  287. (self.name, self.vid))
  288. cmd = ['extend', self.vid, str(size)]
  289. qubes_lvm(cmd, self.log)
  290. reset_cache()
  291. def _snapshot(self):
  292. try:
  293. cmd = ['remove', self._vid_snap]
  294. qubes_lvm(cmd, self.log)
  295. except: # pylint: disable=bare-except
  296. pass
  297. if self.source is None:
  298. cmd = ['clone', self.vid, self._vid_snap]
  299. else:
  300. cmd = ['clone', str(self.source), self._vid_snap]
  301. qubes_lvm(cmd, self.log)
  302. def start(self):
  303. if self.snap_on_start:
  304. if not self.save_on_stop or not self.is_dirty():
  305. self._snapshot()
  306. elif not self.save_on_stop:
  307. self._reset()
  308. reset_cache()
  309. return self
  310. def stop(self):
  311. if self.save_on_stop and self.snap_on_start:
  312. self._commit()
  313. if self.snap_on_start:
  314. cmd = ['remove', self._vid_snap]
  315. qubes_lvm(cmd, self.log)
  316. elif not self.save_on_stop:
  317. cmd = ['remove', self.vid]
  318. qubes_lvm(cmd, self.log)
  319. reset_cache()
  320. return self
  321. def verify(self):
  322. ''' Verifies the volume. '''
  323. try:
  324. vol_info = size_cache[self.vid]
  325. return vol_info['attr'][4] == 'a'
  326. except KeyError:
  327. return False
  328. def block_device(self):
  329. ''' Return :py:class:`qubes.storage.BlockDevice` for serialization in
  330. the libvirt XML template as <disk>.
  331. '''
  332. if self.snap_on_start:
  333. return qubes.storage.BlockDevice(
  334. '/dev/' + self._vid_snap, self.name, self.script,
  335. self.rw, self.domain, self.devtype)
  336. return super(ThinVolume, self).block_device()
  337. @property
  338. def usage(self): # lvm thin usage always returns at least the same usage as
  339. # the parent
  340. try:
  341. return qubes.storage.lvm.size_cache[self.vid]['usage']
  342. except KeyError:
  343. return 0
  344. def pool_exists(pool_id):
  345. ''' Return true if pool exists '''
  346. try:
  347. vol_info = size_cache[pool_id]
  348. return vol_info['attr'][0] == 't'
  349. except KeyError:
  350. return False
  351. def qubes_lvm(cmd, log=logging.getLogger('qubes.storage.lvm')):
  352. ''' Call :program:`lvm` to execute an LVM operation '''
  353. action = cmd[0]
  354. if action == 'remove':
  355. lvm_cmd = ['lvremove', '-f', cmd[1]]
  356. elif action == 'clone':
  357. lvm_cmd = ['lvcreate', '-kn', '-ay', '-s', cmd[1], '-n', cmd[2]]
  358. elif action == 'create':
  359. lvm_cmd = ['lvcreate', '-T', cmd[1], '-kn', '-ay', '-n', cmd[2], '-V',
  360. str(cmd[3]) + 'B']
  361. elif action == 'extend':
  362. size = int(cmd[2]) / (1000 * 1000)
  363. lvm_cmd = ["lvextend", "-L%s" % size, cmd[1]]
  364. else:
  365. raise NotImplementedError('unsupported action: ' + action)
  366. if lvm_is_very_old:
  367. # old lvm in trusty image used there does not support -k option
  368. lvm_cmd = [x for x in lvm_cmd if x != '-kn']
  369. if os.getuid() != 0:
  370. cmd = ['sudo', 'lvm'] + lvm_cmd
  371. else:
  372. cmd = ['lvm'] + lvm_cmd
  373. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  374. close_fds=True)
  375. out, err = p.communicate()
  376. return_code = p.returncode
  377. if out:
  378. log.debug(out)
  379. if return_code == 0 and err:
  380. log.warning(err)
  381. elif return_code != 0:
  382. assert err, "Command exited unsuccessful, but printed nothing to stderr"
  383. raise qubes.storage.StoragePoolException(err)
  384. return True
  385. def reset_cache():
  386. qubes.storage.lvm.size_cache = init_cache()