lvm.py 29 KB

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