lvm.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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 library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library 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 GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  18. #
  19. ''' Driver for storing vm images in a LVM thin pool '''
  20. import logging
  21. import operator
  22. import os
  23. import subprocess
  24. import time
  25. import asyncio
  26. import qubes
  27. import qubes.storage
  28. import qubes.utils
  29. def check_lvm_version():
  30. #Check if lvm is very very old, like in Travis-CI
  31. try:
  32. lvm_help = subprocess.check_output(['lvm', 'lvcreate', '--help'],
  33. stderr=subprocess.DEVNULL).decode()
  34. return '--setactivationskip' not in lvm_help
  35. except (subprocess.CalledProcessError, FileNotFoundError):
  36. pass
  37. lvm_is_very_old = check_lvm_version()
  38. class ThinPool(qubes.storage.Pool):
  39. ''' LVM Thin based pool implementation
  40. ''' # pylint: disable=protected-access
  41. size_cache = None
  42. driver = 'lvm_thin'
  43. def __init__(self, volume_group, thin_pool, revisions_to_keep=1, **kwargs):
  44. super(ThinPool, self).__init__(revisions_to_keep=revisions_to_keep,
  45. **kwargs)
  46. self.volume_group = volume_group
  47. self.thin_pool = thin_pool
  48. self._pool_id = "{!s}/{!s}".format(volume_group, thin_pool)
  49. self.log = logging.getLogger('qube.storage.lvm.%s' % self._pool_id)
  50. self._volume_objects_cache = {}
  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. volume = ThinVolume(**volume_config)
  76. self._volume_objects_cache[volume_config['vid']] = volume
  77. return volume
  78. def setup(self):
  79. reset_cache()
  80. cache_key = self.volume_group + '/' + self.thin_pool
  81. if cache_key not in size_cache:
  82. raise qubes.storage.StoragePoolException(
  83. 'Thin pool {} does not exist'.format(cache_key))
  84. if size_cache[cache_key]['attr'][0] != 't':
  85. raise qubes.storage.StoragePoolException(
  86. 'Volume {} is not a thin pool'.format(cache_key))
  87. # TODO Should we create a non existing pool?
  88. def get_volume(self, vid):
  89. ''' Return a volume with given vid'''
  90. if vid in self._volume_objects_cache:
  91. return self._volume_objects_cache[vid]
  92. config = {
  93. 'pool': self,
  94. 'vid': vid,
  95. 'name': vid,
  96. 'volume_group': self.volume_group,
  97. }
  98. # don't cache this object, as it doesn't carry full configuration
  99. return ThinVolume(**config)
  100. def list_volumes(self):
  101. ''' Return a list of volumes managed by this pool '''
  102. volumes = []
  103. for vid, vol_info in size_cache.items():
  104. if not vid.startswith(self.volume_group + '/'):
  105. continue
  106. if vol_info['pool_lv'] != self.thin_pool:
  107. continue
  108. if vid.endswith('-snap'):
  109. # implementation detail volume
  110. continue
  111. if vid.endswith('-back'):
  112. # old revisions
  113. continue
  114. config = {
  115. 'pool': self,
  116. 'vid': vid,
  117. 'name': vid,
  118. 'volume_group': self.volume_group,
  119. 'rw': vol_info['attr'][1] == 'w',
  120. }
  121. volumes += [ThinVolume(**config)]
  122. return volumes
  123. @property
  124. def size(self):
  125. try:
  126. return qubes.storage.lvm.size_cache[
  127. self.volume_group + '/' + self.thin_pool]['size']
  128. except KeyError:
  129. return 0
  130. @property
  131. def usage(self):
  132. try:
  133. return qubes.storage.lvm.size_cache[
  134. self.volume_group + '/' + self.thin_pool]['usage']
  135. except KeyError:
  136. return 0
  137. def init_cache(log=logging.getLogger('qubes.storage.lvm')):
  138. cmd = ['lvs', '--noheadings', '-o',
  139. 'vg_name,pool_lv,name,lv_size,data_percent,lv_attr,origin',
  140. '--units', 'b', '--separator', ';']
  141. if os.getuid() != 0:
  142. cmd.insert(0, 'sudo')
  143. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  144. close_fds=True)
  145. out, err = p.communicate()
  146. return_code = p.returncode
  147. if return_code == 0 and err:
  148. log.warning(err)
  149. elif return_code != 0:
  150. raise qubes.storage.StoragePoolException(err)
  151. result = {}
  152. for line in out.splitlines():
  153. line = line.decode().strip()
  154. pool_name, pool_lv, name, size, usage_percent, attr, \
  155. origin = line.split(';', 6)
  156. if '' in [pool_name, name, size, usage_percent]:
  157. continue
  158. name = pool_name + "/" + name
  159. size = int(size[:-1]) # Remove 'B' suffix
  160. usage = int(size / 100 * float(usage_percent))
  161. result[name] = {'size': size, 'usage': usage, 'pool_lv': pool_lv,
  162. 'attr': attr, 'origin': origin}
  163. return result
  164. size_cache = init_cache()
  165. class ThinVolume(qubes.storage.Volume):
  166. ''' Default LVM thin volume implementation
  167. ''' # pylint: disable=too-few-public-methods
  168. def __init__(self, volume_group, size=0, **kwargs):
  169. self.volume_group = volume_group
  170. super(ThinVolume, self).__init__(size=size, **kwargs)
  171. self.log = logging.getLogger('qube.storage.lvm.%s' % str(self.pool))
  172. if self.snap_on_start or self.save_on_stop:
  173. self._vid_snap = self.vid + '-snap'
  174. self._size = size
  175. @property
  176. def path(self):
  177. return '/dev/' + self.vid
  178. @property
  179. def revisions(self):
  180. name_prefix = self.vid + '-'
  181. revisions = {}
  182. for revision_vid in size_cache:
  183. if not revision_vid.startswith(name_prefix):
  184. continue
  185. if not revision_vid.endswith('-back'):
  186. continue
  187. revision_vid = revision_vid[len(name_prefix):]
  188. seconds = int(revision_vid[:-len('-back')])
  189. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  190. revisions[revision_vid] = iso_date
  191. return revisions
  192. @property
  193. def size(self):
  194. try:
  195. return qubes.storage.lvm.size_cache[self.vid]['size']
  196. except KeyError:
  197. return self._size
  198. @size.setter
  199. def size(self, _):
  200. raise qubes.storage.StoragePoolException(
  201. "You shouldn't use lvm size setter")
  202. def _reset(self):
  203. ''' Resets a volatile volume '''
  204. assert not self.snap_on_start and not self.save_on_stop, \
  205. "Not a volatile volume"
  206. self.log.debug('Resetting volatile %s', self.vid)
  207. try:
  208. cmd = ['remove', self.vid]
  209. qubes_lvm(cmd, self.log)
  210. except qubes.storage.StoragePoolException:
  211. pass
  212. # pylint: disable=protected-access
  213. cmd = ['create', self.pool._pool_id, self.vid.split('/')[1],
  214. str(self.size)]
  215. qubes_lvm(cmd, self.log)
  216. def _remove_revisions(self, revisions=None):
  217. '''Remove old volume revisions.
  218. If no revisions list is given, it removes old revisions according to
  219. :py:attr:`revisions_to_keep`
  220. :param revisions: list of revisions to remove
  221. '''
  222. if revisions is None:
  223. revisions = sorted(self.revisions.items(),
  224. key=operator.itemgetter(1))
  225. revisions = revisions[:-self.revisions_to_keep]
  226. revisions = [rev_id for rev_id, _ in revisions]
  227. for rev_id in revisions:
  228. try:
  229. cmd = ['remove', self.vid + rev_id]
  230. qubes_lvm(cmd, self.log)
  231. except qubes.storage.StoragePoolException:
  232. pass
  233. def _commit(self):
  234. msg = "Trying to commit {!s}, but it has save_on_stop == False"
  235. msg = msg.format(self)
  236. assert self.save_on_stop, msg
  237. msg = "Trying to commit {!s}, but it has rw == False"
  238. msg = msg.format(self)
  239. assert self.rw, msg
  240. assert hasattr(self, '_vid_snap')
  241. if self.revisions_to_keep > 0:
  242. cmd = ['clone', self.vid,
  243. '{}-{}-back'.format(self.vid, int(time.time()))]
  244. qubes_lvm(cmd, self.log)
  245. self._remove_revisions()
  246. # TODO: when converting this function to coroutine, this _must_ be
  247. # under a lock
  248. # remove old volume only after _successful_ clone of the new one
  249. cmd = ['rename', self.vid, self.vid + '-tmp']
  250. qubes_lvm(cmd, self.log)
  251. try:
  252. cmd = ['clone', self._vid_snap, self.vid]
  253. qubes_lvm(cmd, self.log)
  254. except:
  255. # restore original volume
  256. cmd = ['rename', self.vid + '-tmp', self.vid]
  257. qubes_lvm(cmd, self.log)
  258. raise
  259. else:
  260. cmd = ['remove', self.vid + '-tmp']
  261. qubes_lvm(cmd, self.log)
  262. def create(self):
  263. assert self.vid
  264. assert self.size
  265. if self.save_on_stop:
  266. if self.source:
  267. cmd = ['clone', str(self.source), self.vid]
  268. else:
  269. cmd = [
  270. 'create',
  271. self.pool._pool_id, # pylint: disable=protected-access
  272. self.vid.split('/', 1)[1],
  273. str(self.size)
  274. ]
  275. qubes_lvm(cmd, self.log)
  276. reset_cache()
  277. return self
  278. def remove(self):
  279. assert self.vid
  280. try:
  281. if os.path.exists('/dev/' + self._vid_snap):
  282. cmd = ['remove', self._vid_snap]
  283. qubes_lvm(cmd, self.log)
  284. except AttributeError:
  285. pass
  286. self._remove_revisions(self.revisions.keys())
  287. if not os.path.exists(self.path):
  288. return
  289. cmd = ['remove', self.vid]
  290. qubes_lvm(cmd, self.log)
  291. reset_cache()
  292. # pylint: disable=protected-access
  293. self.pool._volume_objects_cache.pop(self.vid, None)
  294. def export(self):
  295. ''' Returns an object that can be `open()`. '''
  296. # make sure the device node is available
  297. qubes_lvm(['activate', self.vid], self.log)
  298. devpath = '/dev/' + self.vid
  299. return devpath
  300. @asyncio.coroutine
  301. def import_volume(self, src_volume):
  302. if not src_volume.save_on_stop:
  303. return self
  304. # HACK: neat trick to speed up testing if you have same physical thin
  305. # pool assigned to two qubes-pools i.e: qubes_dom0 and test-lvm
  306. # pylint: disable=line-too-long
  307. if isinstance(src_volume.pool, ThinPool) and \
  308. src_volume.pool.thin_pool == self.pool.thin_pool: # NOQA
  309. cmd = ['remove', self.vid]
  310. qubes_lvm(cmd, self.log)
  311. cmd = ['clone', str(src_volume), str(self)]
  312. qubes_lvm(cmd, self.log)
  313. else:
  314. if src_volume.size != self.size:
  315. self.resize(src_volume.size)
  316. src_path = src_volume.export()
  317. cmd = ['dd', 'if=' + src_path, 'of=/dev/' + self.vid,
  318. 'conv=sparse']
  319. p = yield from asyncio.create_subprocess_exec(*cmd)
  320. yield from p.wait()
  321. if p.returncode != 0:
  322. raise qubes.storage.StoragePoolException(
  323. 'Failed to import volume {!r}, dd exit code: {}'.format(
  324. src_volume, p.returncode))
  325. reset_cache()
  326. return self
  327. def import_data(self):
  328. ''' Returns an object that can be `open()`. '''
  329. devpath = '/dev/' + self.vid
  330. return devpath
  331. def is_dirty(self):
  332. if self.save_on_stop:
  333. return os.path.exists('/dev/' + self._vid_snap)
  334. return False
  335. def is_outdated(self):
  336. if not self.snap_on_start:
  337. return False
  338. if self._vid_snap not in size_cache:
  339. return False
  340. return (size_cache[self._vid_snap]['origin'] !=
  341. self.source.vid.split('/')[1])
  342. def revert(self, revision=None):
  343. if revision is None:
  344. revision = \
  345. max(self.revisions.items(), key=operator.itemgetter(1))[0]
  346. old_path = self.path + '-' + revision
  347. if not os.path.exists(old_path):
  348. msg = "Volume {!s} has no {!s}".format(self, old_path)
  349. raise qubes.storage.StoragePoolException(msg)
  350. cmd = ['remove', self.vid]
  351. qubes_lvm(cmd, self.log)
  352. cmd = ['clone', self.vid + '-' + revision, self.vid]
  353. qubes_lvm(cmd, self.log)
  354. reset_cache()
  355. return self
  356. def resize(self, size):
  357. ''' Expands volume, throws
  358. :py:class:`qubst.storage.qubes.storage.StoragePoolException` if
  359. given size is less than current_size
  360. '''
  361. if not self.rw:
  362. msg = 'Can not resize reađonly volume {!s}'.format(self)
  363. raise qubes.storage.StoragePoolException(msg)
  364. if size < self.size:
  365. raise qubes.storage.StoragePoolException(
  366. 'For your own safety, shrinking of %s is'
  367. ' disabled. If you really know what you'
  368. ' are doing, use `lvresize` on %s manually.' %
  369. (self.name, self.vid))
  370. if size == self.size:
  371. return
  372. cmd = ['extend', self.vid, str(size)]
  373. qubes_lvm(cmd, self.log)
  374. if self.is_dirty():
  375. cmd = ['extend', self._vid_snap, str(size)]
  376. qubes_lvm(cmd, self.log)
  377. reset_cache()
  378. def _snapshot(self):
  379. try:
  380. cmd = ['remove', self._vid_snap]
  381. qubes_lvm(cmd, self.log)
  382. except: # pylint: disable=bare-except
  383. pass
  384. if self.source is None:
  385. cmd = ['clone', self.vid, self._vid_snap]
  386. else:
  387. cmd = ['clone', str(self.source), self._vid_snap]
  388. qubes_lvm(cmd, self.log)
  389. def start(self):
  390. try:
  391. if self.snap_on_start or self.save_on_stop:
  392. if not self.save_on_stop or not self.is_dirty():
  393. self._snapshot()
  394. else:
  395. self._reset()
  396. finally:
  397. reset_cache()
  398. return self
  399. def stop(self):
  400. try:
  401. if self.save_on_stop:
  402. self._commit()
  403. if self.snap_on_start or self.save_on_stop:
  404. cmd = ['remove', self._vid_snap]
  405. qubes_lvm(cmd, self.log)
  406. else:
  407. cmd = ['remove', self.vid]
  408. qubes_lvm(cmd, self.log)
  409. finally:
  410. reset_cache()
  411. return self
  412. def verify(self):
  413. ''' Verifies the volume. '''
  414. if not self.save_on_stop and not self.snap_on_start:
  415. # volatile volumes don't need any files
  416. return True
  417. if self.source is not None:
  418. vid = str(self.source)
  419. else:
  420. vid = self.vid
  421. try:
  422. vol_info = size_cache[vid]
  423. if vol_info['attr'][4] != 'a':
  424. raise qubes.storage.StoragePoolException(
  425. 'volume {} not active'.format(vid))
  426. except KeyError:
  427. raise qubes.storage.StoragePoolException(
  428. 'volume {} missing'.format(vid))
  429. return True
  430. def block_device(self):
  431. ''' Return :py:class:`qubes.storage.BlockDevice` for serialization in
  432. the libvirt XML template as <disk>.
  433. '''
  434. if self.snap_on_start or self.save_on_stop:
  435. return qubes.storage.BlockDevice(
  436. '/dev/' + self._vid_snap, self.name, self.script,
  437. self.rw, self.domain, self.devtype)
  438. return super(ThinVolume, self).block_device()
  439. @property
  440. def usage(self): # lvm thin usage always returns at least the same usage as
  441. # the parent
  442. try:
  443. return qubes.storage.lvm.size_cache[self.vid]['usage']
  444. except KeyError:
  445. return 0
  446. def pool_exists(pool_id):
  447. ''' Return true if pool exists '''
  448. try:
  449. vol_info = size_cache[pool_id]
  450. return vol_info['attr'][0] == 't'
  451. except KeyError:
  452. return False
  453. def qubes_lvm(cmd, log=logging.getLogger('qubes.storage.lvm')):
  454. ''' Call :program:`lvm` to execute an LVM operation '''
  455. action = cmd[0]
  456. if action == 'remove':
  457. lvm_cmd = ['lvremove', '-f', cmd[1]]
  458. elif action == 'clone':
  459. lvm_cmd = ['lvcreate', '-kn', '-ay', '-s', cmd[1], '-n', cmd[2]]
  460. elif action == 'create':
  461. lvm_cmd = ['lvcreate', '-T', cmd[1], '-kn', '-ay', '-n', cmd[2], '-V',
  462. str(cmd[3]) + 'B']
  463. elif action == 'extend':
  464. size = int(cmd[2]) / (1024 * 1024)
  465. lvm_cmd = ["lvextend", "-L%s" % size, cmd[1]]
  466. elif action == 'activate':
  467. lvm_cmd = ['lvchange', '-ay', cmd[1]]
  468. elif action == 'rename':
  469. lvm_cmd = ['lvrename', cmd[1], cmd[2]]
  470. else:
  471. raise NotImplementedError('unsupported action: ' + action)
  472. if lvm_is_very_old:
  473. # old lvm in trusty image used there does not support -k option
  474. lvm_cmd = [x for x in lvm_cmd if x != '-kn']
  475. if os.getuid() != 0:
  476. cmd = ['sudo', 'lvm'] + lvm_cmd
  477. else:
  478. cmd = ['lvm'] + lvm_cmd
  479. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  480. close_fds=True)
  481. out, err = p.communicate()
  482. return_code = p.returncode
  483. if out:
  484. log.debug(out)
  485. if return_code == 0 and err:
  486. log.warning(err)
  487. elif return_code != 0:
  488. assert err, "Command exited unsuccessful, but printed nothing to stderr"
  489. raise qubes.storage.StoragePoolException(err)
  490. return True
  491. def reset_cache():
  492. qubes.storage.lvm.size_cache = init_cache()