lvm.py 25 KB

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