lvm.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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 functools
  21. import logging
  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. Volumes are stored as LVM thin volumes, in thin pool specified by
  41. *volume_group*/*thin_pool* arguments. LVM volume naming scheme:
  42. vm-{vm_name}-{volume_name}[-suffix]
  43. Where suffix can be one of:
  44. "-snap" - snapshot for currently running VM, at VM shutdown will be
  45. either discarded (if save_on_stop=False), or committed
  46. (if save_on_stop=True)
  47. "-{revision_id}" - volume revision - new revision is automatically
  48. created at each VM shutdown, *revisions_to_keep* control how many
  49. old revisions (in addition to the current one) should be stored
  50. "" (no suffix) - the most recent committed volume state; also volatile
  51. volume (snap_on_start=False, save_on_stop=False)
  52. On VM startup, new volume is created, depending on volume type,
  53. according to the table below:
  54. snap_on_start, save_on_stop
  55. False, False, - no suffix, fresh empty volume
  56. False, True, - "-snap", snapshot of last committed revision
  57. True , False, - "-snap", snapshot of last committed revision
  58. of source volume (from VM's template)
  59. True, True, - unsupported configuration
  60. Volume's revision_id format is "{timestamp}-back", where timestamp is in
  61. '%s' format (seconds since unix epoch)
  62. ''' # pylint: disable=protected-access
  63. size_cache = None
  64. driver = 'lvm_thin'
  65. def __init__(self, volume_group, thin_pool, revisions_to_keep=1, **kwargs):
  66. super(ThinPool, self).__init__(revisions_to_keep=revisions_to_keep,
  67. **kwargs)
  68. self.volume_group = volume_group
  69. self.thin_pool = thin_pool
  70. self._pool_id = "{!s}/{!s}".format(volume_group, thin_pool)
  71. self.log = logging.getLogger('qubes.storage.lvm.%s' % self._pool_id)
  72. self._volume_objects_cache = {}
  73. def __repr__(self):
  74. return '<{} at {:#x} name={!r} volume_group={!r} thin_pool={!r}>'.\
  75. format(
  76. type(self).__name__, id(self),
  77. self.name, self.volume_group, self.thin_pool)
  78. @property
  79. def config(self):
  80. return {
  81. 'name': self.name,
  82. 'volume_group': self.volume_group,
  83. 'thin_pool': self.thin_pool,
  84. 'driver': ThinPool.driver,
  85. 'revisions_to_keep': self.revisions_to_keep,
  86. }
  87. def destroy(self):
  88. pass # TODO Should we remove an existing pool?
  89. def init_volume(self, vm, volume_config):
  90. ''' Initialize a :py:class:`qubes.storage.Volume` from `volume_config`.
  91. '''
  92. if 'revisions_to_keep' not in volume_config.keys():
  93. volume_config['revisions_to_keep'] = self.revisions_to_keep
  94. if 'vid' not in volume_config.keys():
  95. if vm and hasattr(vm, 'name'):
  96. vm_name = vm.name
  97. else:
  98. # for the future if we have volumes not belonging to a vm
  99. vm_name = qubes.utils.random_string()
  100. assert self.name
  101. volume_config['vid'] = "{!s}/vm-{!s}-{!s}".format(
  102. self.volume_group, vm_name, volume_config['name'])
  103. volume_config['volume_group'] = self.volume_group
  104. volume_config['pool'] = self
  105. volume = ThinVolume(**volume_config)
  106. self._volume_objects_cache[volume_config['vid']] = volume
  107. return volume
  108. def setup(self):
  109. reset_cache()
  110. cache_key = self.volume_group + '/' + self.thin_pool
  111. if cache_key not in size_cache:
  112. raise qubes.storage.StoragePoolException(
  113. 'Thin pool {} does not exist'.format(cache_key))
  114. if size_cache[cache_key]['attr'][0] != 't':
  115. raise qubes.storage.StoragePoolException(
  116. 'Volume {} is not a thin pool'.format(cache_key))
  117. # TODO Should we create a non existing pool?
  118. def get_volume(self, vid):
  119. ''' Return a volume with given vid'''
  120. if vid in self._volume_objects_cache:
  121. return self._volume_objects_cache[vid]
  122. config = {
  123. 'pool': self,
  124. 'vid': vid,
  125. 'name': vid,
  126. 'volume_group': self.volume_group,
  127. }
  128. # don't cache this object, as it doesn't carry full configuration
  129. return ThinVolume(**config)
  130. def list_volumes(self):
  131. ''' Return a list of volumes managed by this pool '''
  132. volumes = []
  133. for vid, vol_info in size_cache.items():
  134. if not vid.startswith(self.volume_group + '/'):
  135. continue
  136. if vol_info['pool_lv'] != self.thin_pool:
  137. continue
  138. if vid.endswith('-snap') or vid.endswith('-import'):
  139. # implementation detail volume
  140. continue
  141. if vid.endswith('-back'):
  142. # old revisions
  143. continue
  144. volume = self.get_volume(vid)
  145. if volume in volumes:
  146. continue
  147. volumes.append(volume)
  148. return volumes
  149. @property
  150. def size(self):
  151. try:
  152. return qubes.storage.lvm.size_cache[
  153. self.volume_group + '/' + self.thin_pool]['size']
  154. except KeyError:
  155. return 0
  156. @property
  157. def usage(self):
  158. try:
  159. return qubes.storage.lvm.size_cache[
  160. self.volume_group + '/' + self.thin_pool]['usage']
  161. except KeyError:
  162. return 0
  163. _init_cache_cmd = ['lvs', '--noheadings', '-o',
  164. 'vg_name,pool_lv,name,lv_size,data_percent,lv_attr,origin',
  165. '--units', 'b', '--separator', ';']
  166. def _parse_lvm_cache(lvm_output):
  167. result = {}
  168. for line in lvm_output.splitlines():
  169. line = line.decode().strip()
  170. pool_name, pool_lv, name, size, usage_percent, attr, \
  171. origin = line.split(';', 6)
  172. if '' in [pool_name, name, size, usage_percent]:
  173. continue
  174. name = pool_name + "/" + name
  175. size = int(size[:-1]) # Remove 'B' suffix
  176. usage = int(size / 100 * float(usage_percent))
  177. result[name] = {'size': size, 'usage': usage, 'pool_lv': pool_lv,
  178. 'attr': attr, 'origin': origin}
  179. return result
  180. def init_cache(log=logging.getLogger('qubes.storage.lvm')):
  181. cmd = _init_cache_cmd
  182. if os.getuid() != 0:
  183. cmd = ['sudo'] + cmd
  184. environ = os.environ.copy()
  185. environ['LC_ALL'] = 'C.utf8'
  186. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  187. close_fds=True, env=environ)
  188. out, err = p.communicate()
  189. return_code = p.returncode
  190. if return_code == 0 and err:
  191. log.warning(err)
  192. elif return_code != 0:
  193. raise qubes.storage.StoragePoolException(err)
  194. return _parse_lvm_cache(out)
  195. @asyncio.coroutine
  196. def init_cache_coro(log=logging.getLogger('qubes.storage.lvm')):
  197. cmd = _init_cache_cmd
  198. if os.getuid() != 0:
  199. cmd = ['sudo'] + cmd
  200. environ = os.environ.copy()
  201. environ['LC_ALL'] = 'C.utf8'
  202. p = yield from asyncio.create_subprocess_exec(*cmd,
  203. stdout=subprocess.PIPE,
  204. stderr=subprocess.PIPE,
  205. close_fds=True, env=environ)
  206. out, err = yield from p.communicate()
  207. return_code = p.returncode
  208. if return_code == 0 and err:
  209. log.warning(err)
  210. elif return_code != 0:
  211. raise qubes.storage.StoragePoolException(err)
  212. return _parse_lvm_cache(out)
  213. size_cache = init_cache()
  214. def _revision_sort_key(revision):
  215. '''Sort key for revisions. Sort them by time
  216. :returns timestamp
  217. '''
  218. if isinstance(revision, tuple):
  219. revision = revision[0]
  220. if '-' in revision:
  221. revision = revision.split('-')[0]
  222. return int(revision)
  223. def locked(method):
  224. '''Decorator running given Volume's coroutine under a lock.
  225. Needs to be added after wrapping with @asyncio.coroutine, for example:
  226. >>>@locked
  227. >>>@asyncio.coroutine
  228. >>>def start(self):
  229. >>> pass
  230. '''
  231. @asyncio.coroutine
  232. @functools.wraps(method)
  233. def wrapper(self, *args, **kwargs):
  234. with (yield from self._lock): # pylint: disable=protected-access
  235. return (yield from method(self, *args, **kwargs))
  236. return wrapper
  237. class ThinVolume(qubes.storage.Volume):
  238. ''' Default LVM thin volume implementation
  239. ''' # pylint: disable=too-few-public-methods
  240. def __init__(self, volume_group, size=0, **kwargs):
  241. self.volume_group = volume_group
  242. super(ThinVolume, self).__init__(size=size, **kwargs)
  243. self.log = logging.getLogger('qubes.storage.lvm.%s' % str(self.pool))
  244. if self.snap_on_start or self.save_on_stop:
  245. self._vid_snap = self.vid + '-snap'
  246. if self.save_on_stop:
  247. self._vid_import = self.vid + '-import'
  248. self._size = size
  249. self._lock = asyncio.Lock()
  250. @property
  251. def path(self):
  252. return '/dev/' + self._vid_current
  253. @property
  254. def _vid_current(self):
  255. if self.vid in size_cache:
  256. return self.vid
  257. vol_revisions = self.revisions
  258. if vol_revisions:
  259. last_revision = \
  260. max(vol_revisions.items(), key=_revision_sort_key)[0]
  261. return self.vid + '-' + last_revision
  262. # detached pool? return expected path
  263. return self.vid
  264. @property
  265. def revisions(self):
  266. name_prefix = self.vid + '-'
  267. revisions = {}
  268. for revision_vid in size_cache:
  269. if not revision_vid.startswith(name_prefix):
  270. continue
  271. if not revision_vid.endswith('-back'):
  272. continue
  273. revision_vid = revision_vid[len(name_prefix):]
  274. if revision_vid.count('-') > 1:
  275. # VM+volume name is a prefix of another VM, see #4680
  276. continue
  277. # get revision without suffix
  278. seconds = int(revision_vid.split('-')[0])
  279. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  280. revisions[revision_vid] = iso_date
  281. return revisions
  282. @property
  283. def size(self):
  284. try:
  285. if self.is_dirty():
  286. return qubes.storage.lvm.size_cache[self._vid_snap]['size']
  287. return qubes.storage.lvm.size_cache[self._vid_current]['size']
  288. except KeyError:
  289. return self._size
  290. @size.setter
  291. def size(self, _):
  292. raise qubes.storage.StoragePoolException(
  293. "You shouldn't use lvm size setter")
  294. @asyncio.coroutine
  295. def _reset(self):
  296. ''' Resets a volatile volume '''
  297. assert not self.snap_on_start and not self.save_on_stop, \
  298. "Not a volatile volume"
  299. self.log.debug('Resetting volatile %s', self.vid)
  300. try:
  301. cmd = ['remove', self.vid]
  302. yield from qubes_lvm_coro(cmd, self.log)
  303. except qubes.storage.StoragePoolException:
  304. pass
  305. # pylint: disable=protected-access
  306. cmd = ['create', self.pool._pool_id, self.vid.split('/')[1],
  307. str(self.size)]
  308. yield from qubes_lvm_coro(cmd, self.log)
  309. @asyncio.coroutine
  310. def _remove_revisions(self, revisions=None):
  311. '''Remove old volume revisions.
  312. If no revisions list is given, it removes old revisions according to
  313. :py:attr:`revisions_to_keep`
  314. :param revisions: list of revisions to remove
  315. '''
  316. if revisions is None:
  317. revisions = sorted(self.revisions.items(),
  318. key=_revision_sort_key)
  319. # pylint: disable=invalid-unary-operand-type
  320. revisions = revisions[:(-self.revisions_to_keep) or None]
  321. revisions = [rev_id for rev_id, _ in revisions]
  322. for rev_id in revisions:
  323. # safety check
  324. assert rev_id != self._vid_current
  325. try:
  326. cmd = ['remove', self.vid + '-' + rev_id]
  327. yield from qubes_lvm_coro(cmd, self.log)
  328. except qubes.storage.StoragePoolException:
  329. pass
  330. @asyncio.coroutine
  331. def _commit(self, vid_to_commit=None, keep=False):
  332. '''
  333. Commit temporary volume into current one. By default
  334. :py:attr:`_vid_snap` is used (which is created by :py:meth:`start()`),
  335. but can be overriden by *vid_to_commit* argument.
  336. :param vid_to_commit: LVM volume ID to commit into this one
  337. :param keep: whether to keep or not *vid_to_commit*.
  338. IOW use 'clone' or 'rename' methods.
  339. :return: None
  340. '''
  341. msg = "Trying to commit {!s}, but it has save_on_stop == False"
  342. msg = msg.format(self)
  343. assert self.save_on_stop, msg
  344. msg = "Trying to commit {!s}, but it has rw == False"
  345. msg = msg.format(self)
  346. assert self.rw, msg
  347. if vid_to_commit is None:
  348. assert hasattr(self, '_vid_snap')
  349. vid_to_commit = self._vid_snap
  350. assert self._lock.locked()
  351. if not os.path.exists('/dev/' + vid_to_commit):
  352. # nothing to commit
  353. return
  354. if self._vid_current == self.vid:
  355. cmd = ['rename', self.vid,
  356. '{}-{}-back'.format(self.vid, int(time.time()))]
  357. yield from qubes_lvm_coro(cmd, self.log)
  358. yield from reset_cache_coro()
  359. cmd = ['clone' if keep else 'rename',
  360. vid_to_commit,
  361. self.vid]
  362. yield from qubes_lvm_coro(cmd, self.log)
  363. yield from reset_cache_coro()
  364. # make sure the one we've committed right now is properly
  365. # detected as the current one - before removing anything
  366. assert self._vid_current == self.vid
  367. # and remove old snapshots, if needed
  368. yield from self._remove_revisions()
  369. @locked
  370. @asyncio.coroutine
  371. def create(self):
  372. assert self.vid
  373. assert self.size
  374. if self.save_on_stop:
  375. if self.source:
  376. cmd = ['clone', self.source.path, self.vid]
  377. else:
  378. cmd = [
  379. 'create',
  380. self.pool._pool_id, # pylint: disable=protected-access
  381. self.vid.split('/', 1)[1],
  382. str(self.size)
  383. ]
  384. yield from qubes_lvm_coro(cmd, self.log)
  385. yield from reset_cache_coro()
  386. return self
  387. @locked
  388. @asyncio.coroutine
  389. def remove(self):
  390. assert self.vid
  391. try:
  392. if os.path.exists('/dev/' + self._vid_snap):
  393. cmd = ['remove', self._vid_snap]
  394. yield from qubes_lvm_coro(cmd, self.log)
  395. except AttributeError:
  396. pass
  397. try:
  398. if os.path.exists('/dev/' + self._vid_import):
  399. cmd = ['remove', self._vid_import]
  400. yield from qubes_lvm_coro(cmd, self.log)
  401. except AttributeError:
  402. pass
  403. yield from self._remove_revisions(self.revisions.keys())
  404. if not os.path.exists(self.path):
  405. return
  406. cmd = ['remove', self.path]
  407. yield from qubes_lvm_coro(cmd, self.log)
  408. yield from reset_cache_coro()
  409. # pylint: disable=protected-access
  410. self.pool._volume_objects_cache.pop(self.vid, None)
  411. def export(self):
  412. ''' Returns an object that can be `open()`. '''
  413. # make sure the device node is available
  414. qubes_lvm(['activate', self.path], self.log)
  415. devpath = self.path
  416. return devpath
  417. @locked
  418. @asyncio.coroutine
  419. def import_volume(self, src_volume):
  420. if not src_volume.save_on_stop:
  421. return self
  422. if self.is_dirty():
  423. raise qubes.storage.StoragePoolException(
  424. 'Cannot import to dirty volume {} -'
  425. ' start and stop a qube to cleanup'.format(self.vid))
  426. self.abort_if_import_in_progress()
  427. # HACK: neat trick to speed up testing if you have same physical thin
  428. # pool assigned to two qubes-pools i.e: qubes_dom0 and test-lvm
  429. # pylint: disable=line-too-long
  430. if isinstance(src_volume.pool, ThinPool) and \
  431. src_volume.pool.thin_pool == self.pool.thin_pool: # NOQA
  432. yield from self._commit(src_volume.path[len('/dev/'):], keep=True)
  433. else:
  434. cmd = ['create',
  435. self.pool._pool_id, # pylint: disable=protected-access
  436. self._vid_import.split('/')[1],
  437. str(src_volume.size)]
  438. yield from qubes_lvm_coro(cmd, self.log)
  439. src_path = src_volume.export()
  440. cmd = ['dd', 'if=' + src_path, 'of=/dev/' + self._vid_import,
  441. 'conv=sparse', 'status=none']
  442. if not os.access('/dev/' + self._vid_import, os.W_OK) or \
  443. not os.access(src_path, os.R_OK):
  444. cmd.insert(0, 'sudo')
  445. p = yield from asyncio.create_subprocess_exec(*cmd)
  446. yield from p.wait()
  447. if p.returncode != 0:
  448. cmd = ['remove', self._vid_import]
  449. yield from qubes_lvm_coro(cmd, self.log)
  450. raise qubes.storage.StoragePoolException(
  451. 'Failed to import volume {!r}, dd exit code: {}'.format(
  452. src_volume, p.returncode))
  453. yield from self._commit(self._vid_import)
  454. return self
  455. @locked
  456. @asyncio.coroutine
  457. def import_data(self):
  458. ''' Returns an object that can be `open()`. '''
  459. if self.is_dirty():
  460. raise qubes.storage.StoragePoolException(
  461. 'Cannot import data to dirty volume {}, stop the qube first'.
  462. format(self.vid))
  463. self.abort_if_import_in_progress()
  464. # pylint: disable=protected-access
  465. cmd = ['create', self.pool._pool_id, self._vid_import.split('/')[1],
  466. str(self.size)]
  467. yield from qubes_lvm_coro(cmd, self.log)
  468. yield from reset_cache_coro()
  469. devpath = '/dev/' + self._vid_import
  470. return devpath
  471. @locked
  472. @asyncio.coroutine
  473. def import_data_end(self, success):
  474. '''Either commit imported data, or discard temporary volume'''
  475. if not os.path.exists('/dev/' + self._vid_import):
  476. raise qubes.storage.StoragePoolException(
  477. 'No import operation in progress on {}'.format(self.vid))
  478. if success:
  479. yield from self._commit(self._vid_import)
  480. else:
  481. cmd = ['remove', self._vid_import]
  482. yield from qubes_lvm_coro(cmd, self.log)
  483. def abort_if_import_in_progress(self):
  484. try:
  485. devpath = '/dev/' + self._vid_import
  486. if os.path.exists(devpath):
  487. raise qubes.storage.StoragePoolException(
  488. 'Import operation in progress on {}'.format(self.vid))
  489. except AttributeError: # self._vid_import
  490. # no vid_import - import definitely not in progress
  491. pass
  492. def is_dirty(self):
  493. if self.save_on_stop:
  494. return os.path.exists('/dev/' + self._vid_snap)
  495. return False
  496. def is_outdated(self):
  497. if not self.snap_on_start:
  498. return False
  499. if self._vid_snap not in size_cache:
  500. return False
  501. return (size_cache[self._vid_snap]['origin'] !=
  502. self.source.path.split('/')[-1])
  503. @locked
  504. @asyncio.coroutine
  505. def revert(self, revision=None):
  506. if self.is_dirty():
  507. raise qubes.storage.StoragePoolException(
  508. 'Cannot revert dirty volume {}, stop the qube first'.format(
  509. self.vid))
  510. self.abort_if_import_in_progress()
  511. if revision is None:
  512. revision = \
  513. max(self.revisions.items(), key=_revision_sort_key)[0]
  514. old_path = '/dev/' + self.vid + '-' + revision
  515. if not os.path.exists(old_path):
  516. msg = "Volume {!s} has no {!s}".format(self, old_path)
  517. raise qubes.storage.StoragePoolException(msg)
  518. if self.vid in size_cache:
  519. cmd = ['remove', self.vid]
  520. yield from qubes_lvm_coro(cmd, self.log)
  521. cmd = ['clone', self.vid + '-' + revision, self.vid]
  522. yield from qubes_lvm_coro(cmd, self.log)
  523. yield from reset_cache_coro()
  524. return self
  525. @locked
  526. @asyncio.coroutine
  527. def resize(self, size):
  528. ''' Expands volume, throws
  529. :py:class:`qubst.storage.qubes.storage.StoragePoolException` if
  530. given size is less than current_size
  531. '''
  532. if not self.rw:
  533. msg = 'Can not resize reađonly volume {!s}'.format(self)
  534. raise qubes.storage.StoragePoolException(msg)
  535. if size < self.size:
  536. raise qubes.storage.StoragePoolException(
  537. 'For your own safety, shrinking of %s is'
  538. ' disabled (%d < %d). If you really know what you'
  539. ' are doing, use `lvresize` on %s manually.' %
  540. (self.name, size, self.size, self.vid))
  541. if size == self.size:
  542. return
  543. if self.is_dirty():
  544. cmd = ['extend', self._vid_snap, str(size)]
  545. yield from qubes_lvm_coro(cmd, self.log)
  546. elif hasattr(self, '_vid_import') and \
  547. os.path.exists('/dev/' + self._vid_import):
  548. cmd = ['extend', self._vid_import, str(size)]
  549. yield from qubes_lvm_coro(cmd, self.log)
  550. elif self.save_on_stop or not self.snap_on_start:
  551. cmd = ['extend', self._vid_current, str(size)]
  552. yield from qubes_lvm_coro(cmd, self.log)
  553. yield from reset_cache_coro()
  554. @asyncio.coroutine
  555. def _snapshot(self):
  556. try:
  557. cmd = ['remove', self._vid_snap]
  558. yield from qubes_lvm_coro(cmd, self.log)
  559. except: # pylint: disable=bare-except
  560. pass
  561. if self.source is None:
  562. cmd = ['clone', self._vid_current, self._vid_snap]
  563. else:
  564. cmd = ['clone', self.source.path, self._vid_snap]
  565. yield from qubes_lvm_coro(cmd, self.log)
  566. @locked
  567. @asyncio.coroutine
  568. def start(self):
  569. self.abort_if_import_in_progress()
  570. try:
  571. if self.snap_on_start or self.save_on_stop:
  572. if not self.save_on_stop or not self.is_dirty():
  573. yield from self._snapshot()
  574. else:
  575. yield from self._reset()
  576. finally:
  577. yield from reset_cache_coro()
  578. return self
  579. @locked
  580. @asyncio.coroutine
  581. def stop(self):
  582. try:
  583. if self.save_on_stop:
  584. yield from self._commit()
  585. if self.snap_on_start and not self.save_on_stop:
  586. cmd = ['remove', self._vid_snap]
  587. yield from qubes_lvm_coro(cmd, self.log)
  588. elif not self.snap_on_start and not self.save_on_stop:
  589. cmd = ['remove', self.vid]
  590. yield from qubes_lvm_coro(cmd, self.log)
  591. finally:
  592. yield from reset_cache_coro()
  593. return self
  594. def verify(self):
  595. ''' Verifies the volume. '''
  596. if not self.save_on_stop and not self.snap_on_start:
  597. # volatile volumes don't need any files
  598. return True
  599. if self.source is not None:
  600. vid = self.source.path[len('/dev/'):]
  601. else:
  602. vid = self._vid_current
  603. try:
  604. vol_info = size_cache[vid]
  605. if vol_info['attr'][4] != 'a':
  606. raise qubes.storage.StoragePoolException(
  607. 'volume {} not active'.format(vid))
  608. except KeyError:
  609. raise qubes.storage.StoragePoolException(
  610. 'volume {} missing'.format(vid))
  611. return True
  612. def block_device(self):
  613. ''' Return :py:class:`qubes.storage.BlockDevice` for serialization in
  614. the libvirt XML template as <disk>.
  615. '''
  616. if self.snap_on_start or self.save_on_stop:
  617. return qubes.storage.BlockDevice(
  618. '/dev/' + self._vid_snap, self.name, self.script,
  619. self.rw, self.domain, self.devtype)
  620. return super(ThinVolume, self).block_device()
  621. @property
  622. def usage(self): # lvm thin usage always returns at least the same usage as
  623. # the parent
  624. try:
  625. return qubes.storage.lvm.size_cache[self._vid_current]['usage']
  626. except KeyError:
  627. return 0
  628. def pool_exists(pool_id):
  629. ''' Return true if pool exists '''
  630. try:
  631. vol_info = size_cache[pool_id]
  632. return vol_info['attr'][0] == 't'
  633. except KeyError:
  634. return False
  635. def _get_lvm_cmdline(cmd):
  636. ''' Build command line for :program:`lvm` call.
  637. The purpose of this function is to keep all the detailed lvm options in
  638. one place.
  639. :param cmd: array of str, where cmd[0] is action and the rest are arguments
  640. :return array of str appropriate for subprocess.Popen
  641. '''
  642. action = cmd[0]
  643. if action == 'remove':
  644. lvm_cmd = ['lvremove', '-f', cmd[1]]
  645. elif action == 'clone':
  646. lvm_cmd = ['lvcreate', '-kn', '-ay', '-s', cmd[1], '-n', cmd[2]]
  647. elif action == 'create':
  648. lvm_cmd = ['lvcreate', '-T', cmd[1], '-kn', '-ay', '-n', cmd[2], '-V',
  649. str(cmd[3]) + 'B']
  650. elif action == 'extend':
  651. size = int(cmd[2]) / (1024 * 1024)
  652. lvm_cmd = ["lvextend", "-L%s" % size, cmd[1]]
  653. elif action == 'activate':
  654. lvm_cmd = ['lvchange', '-ay', cmd[1]]
  655. elif action == 'rename':
  656. lvm_cmd = ['lvrename', cmd[1], cmd[2]]
  657. else:
  658. raise NotImplementedError('unsupported action: ' + action)
  659. if lvm_is_very_old:
  660. # old lvm in trusty image used there does not support -k option
  661. lvm_cmd = [x for x in lvm_cmd if x != '-kn']
  662. if os.getuid() != 0:
  663. cmd = ['sudo', 'lvm'] + lvm_cmd
  664. else:
  665. cmd = ['lvm'] + lvm_cmd
  666. return cmd
  667. def _process_lvm_output(returncode, stdout, stderr, log):
  668. '''Process output of LVM, determine if the call was successful and
  669. possibly log warnings.'''
  670. # Filter out warning about intended over-provisioning.
  671. # Upstream discussion about missing option to silence it:
  672. # https://bugzilla.redhat.com/1347008
  673. err = '\n'.join(line for line in stderr.decode().splitlines()
  674. if 'exceeds the size of thin pool' not in line)
  675. if stdout:
  676. log.debug(stdout)
  677. if returncode == 0 and err:
  678. log.warning(err)
  679. elif returncode != 0:
  680. assert err, "Command exited unsuccessful, but printed nothing to stderr"
  681. err = err.replace('%', '%%')
  682. raise qubes.storage.StoragePoolException(err)
  683. return True
  684. def qubes_lvm(cmd, log=logging.getLogger('qubes.storage.lvm')):
  685. ''' Call :program:`lvm` to execute an LVM operation '''
  686. # the only caller for this non-coroutine version is ThinVolume.export()
  687. cmd = _get_lvm_cmdline(cmd)
  688. environ = os.environ.copy()
  689. environ['LC_ALL'] = 'C.utf8'
  690. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  691. close_fds=True, env=environ)
  692. out, err = p.communicate()
  693. return _process_lvm_output(p.returncode, out, err, log)
  694. @asyncio.coroutine
  695. def qubes_lvm_coro(cmd, log=logging.getLogger('qubes.storage.lvm')):
  696. ''' Call :program:`lvm` to execute an LVM operation
  697. Coroutine version of :py:func:`qubes_lvm`'''
  698. cmd = _get_lvm_cmdline(cmd)
  699. environ = os.environ.copy()
  700. environ['LC_ALL'] = 'C.utf8'
  701. p = yield from asyncio.create_subprocess_exec(*cmd,
  702. stdout=subprocess.PIPE,
  703. stderr=subprocess.PIPE,
  704. close_fds=True, env=environ)
  705. out, err = yield from p.communicate()
  706. return _process_lvm_output(p.returncode, out, err, log)
  707. def reset_cache():
  708. qubes.storage.lvm.size_cache = init_cache()
  709. @asyncio.coroutine
  710. def reset_cache_coro():
  711. qubes.storage.lvm.size_cache = yield from init_cache_coro()