lvm.py 19 KB

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