lvm.py 17 KB

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