lvm.py 16 KB

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