lvm.py 19 KB

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