lvm.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program 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
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. #
  20. ''' Driver for storing vm images in a LVM thin pool '''
  21. import logging
  22. import os
  23. import subprocess
  24. import qubes
  25. import qubes.storage
  26. import qubes.utils
  27. def check_lvm_version():
  28. #Check if lvm is very very old, like in Travis-CI
  29. try:
  30. lvm_help = subprocess.check_output(['lvm', 'lvcreate', '--help'],
  31. stderr=subprocess.DEVNULL).decode()
  32. return '--setactivationskip' not in lvm_help
  33. except (subprocess.CalledProcessError, FileNotFoundError):
  34. pass
  35. lvm_is_very_old = check_lvm_version()
  36. class ThinPool(qubes.storage.Pool):
  37. ''' LVM Thin based pool implementation
  38. ''' # pylint: disable=protected-access
  39. size_cache = None
  40. driver = 'lvm_thin'
  41. def __init__(self, volume_group, thin_pool, revisions_to_keep=1, **kwargs):
  42. super(ThinPool, self).__init__(revisions_to_keep=revisions_to_keep,
  43. **kwargs)
  44. self.volume_group = volume_group
  45. self.thin_pool = thin_pool
  46. self._pool_id = "{!s}/{!s}".format(volume_group, thin_pool)
  47. self.log = logging.getLogger('qube.storage.lvm.%s' % self._pool_id)
  48. @property
  49. def config(self):
  50. return {
  51. 'name': self.name,
  52. 'volume_group': self.volume_group,
  53. 'thin_pool': self.thin_pool,
  54. 'driver': ThinPool.driver
  55. }
  56. def destroy(self):
  57. pass # TODO Should we remove an existing pool?
  58. def init_volume(self, vm, volume_config):
  59. ''' Initialize a :py:class:`qubes.storage.Volume` from `volume_config`.
  60. '''
  61. if 'vid' not in volume_config.keys():
  62. if vm and hasattr(vm, 'name'):
  63. vm_name = vm.name
  64. else:
  65. # for the future if we have volumes not belonging to a vm
  66. vm_name = qubes.utils.random_string()
  67. assert self.name
  68. volume_config['vid'] = "{!s}/vm-{!s}-{!s}".format(
  69. self.volume_group, vm_name, volume_config['name'])
  70. volume_config['volume_group'] = self.volume_group
  71. volume_config['pool'] = self
  72. return ThinVolume(**volume_config)
  73. def rename(self, volume, old_name, new_name):
  74. ''' Called when the domain changes its name '''
  75. new_vid = "{!s}/vm-{!s}-{!s}".format(self.volume_group, new_name,
  76. volume.name)
  77. if volume.save_on_stop:
  78. cmd = ['clone', volume.vid, new_vid]
  79. qubes_lvm(cmd, self.log)
  80. cmd = ['remove', volume.vid]
  81. qubes_lvm(cmd, self.log)
  82. volume.vid = new_vid
  83. if volume.snap_on_start:
  84. volume._vid_snap = volume.vid + '-snap'
  85. reset_cache()
  86. return volume
  87. def setup(self):
  88. pass # TODO Should we create a non existing pool?
  89. def list_volumes(self):
  90. ''' Return a list of volumes managed by this pool '''
  91. volumes = []
  92. for vid, vol_info in size_cache.items():
  93. if not vid.startswith(self.volume_group + '/'):
  94. continue
  95. if vol_info['pool_lv'] != self.thin_pool:
  96. continue
  97. if vid.endswith('-snap'):
  98. # implementation detail volume
  99. continue
  100. config = {
  101. 'pool': self,
  102. 'vid': vid,
  103. 'name': vid,
  104. 'volume_group': self.volume_group,
  105. 'rw': vol_info['attr'][1] == 'w',
  106. }
  107. volumes += [ThinVolume(**config)]
  108. return volumes
  109. def init_cache(log=logging.getLogger('qube.storage.lvm')):
  110. cmd = ['lvs', '--noheadings', '-o',
  111. 'vg_name,pool_lv,name,lv_size,data_percent,lv_attr',
  112. '--units', 'b', '--separator', ',']
  113. if os.getuid() != 0:
  114. cmd.insert(0, 'sudo')
  115. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  116. close_fds=True)
  117. out, err = p.communicate()
  118. return_code = p.returncode
  119. if return_code == 0 and err:
  120. log.warning(err)
  121. elif return_code != 0:
  122. raise qubes.storage.StoragePoolException(err)
  123. result = {}
  124. for line in out.splitlines():
  125. line = line.decode().strip()
  126. pool_name, pool_lv, name, size, usage_percent, attr = line.split(',', 5)
  127. if '' in [pool_name, pool_lv, name, size, usage_percent]:
  128. continue
  129. name = pool_name + "/" + name
  130. size = int(size[:-1])
  131. usage = int(size / 100 * float(usage_percent))
  132. result[name] = {'size': size, 'usage': usage, 'pool_lv': pool_lv,
  133. 'attr': attr}
  134. return result
  135. size_cache = init_cache()
  136. class ThinVolume(qubes.storage.Volume):
  137. ''' Default LVM thin volume implementation
  138. ''' # pylint: disable=too-few-public-methods
  139. def __init__(self, volume_group, size=0, **kwargs):
  140. self.volume_group = volume_group
  141. super(ThinVolume, self).__init__(size=size, **kwargs)
  142. self.log = logging.getLogger('qube.storage.lvm.%s' % str(self.pool))
  143. if self.snap_on_start and self.source is None:
  144. msg = "snap_on_start specified on {!r} but no volume source set"
  145. msg = msg.format(self.name)
  146. raise qubes.storage.StoragePoolException(msg)
  147. elif not self.snap_on_start and self.source is not None:
  148. msg = "source specified on {!r} but no snap_on_start set"
  149. msg = msg.format(self.name)
  150. raise qubes.storage.StoragePoolException(msg)
  151. if self.snap_on_start:
  152. self._vid_snap = self.vid + '-snap'
  153. self._size = size
  154. @property
  155. def path(self):
  156. return '/dev/' + self.vid
  157. @property
  158. def revisions(self):
  159. path = self.path + '-back'
  160. if os.path.exists(path):
  161. seconds = os.path.getctime(path)
  162. iso_date = qubes.storage.isodate(seconds).split('.', 1)[0]
  163. return {iso_date: path}
  164. return {}
  165. @property
  166. def _is_origin(self):
  167. return not self.snap_on_start and self.save_on_stop
  168. @property
  169. def _is_origin_snapshot(self):
  170. return self.snap_on_start and self.save_on_stop
  171. @property
  172. def _is_snapshot(self):
  173. return self.snap_on_start and not self.save_on_stop
  174. @property
  175. def _is_volatile(self):
  176. return not self.snap_on_start and not self.save_on_stop
  177. @property
  178. def size(self):
  179. try:
  180. return qubes.storage.lvm.size_cache[self.vid]['size']
  181. except KeyError:
  182. return self._size
  183. @size.setter
  184. def size(self, _):
  185. raise qubes.storage.StoragePoolException(
  186. "You shouldn't use lvm size setter")
  187. def _reset(self):
  188. ''' Resets a volatile volume '''
  189. assert self._is_volatile, \
  190. 'Expected a volatile volume, but got {!r}'.format(self)
  191. self.log.debug('Resetting volatile ' + self.vid)
  192. try:
  193. cmd = ['remove', self.vid]
  194. qubes_lvm(cmd, self.log)
  195. except qubes.storage.StoragePoolException:
  196. pass
  197. # pylint: disable=protected-access
  198. cmd = ['create', self.pool._pool_id, self.vid.split('/')[1],
  199. str(self.size)]
  200. qubes_lvm(cmd, self.log)
  201. def _commit(self):
  202. msg = "Trying to commit {!s}, but it has save_on_stop == False"
  203. msg = msg.format(self)
  204. assert self.save_on_stop, msg
  205. msg = "Trying to commit {!s}, but it has rw == False"
  206. msg = msg.format(self)
  207. assert self.rw, msg
  208. assert hasattr(self, '_vid_snap')
  209. try:
  210. cmd = ['remove', self.vid + "-back"]
  211. qubes_lvm(cmd, self.log)
  212. except qubes.storage.StoragePoolException:
  213. pass
  214. cmd = ['clone', self.vid, self.vid + "-back"]
  215. qubes_lvm(cmd, self.log)
  216. cmd = ['remove', self.vid]
  217. qubes_lvm(cmd, self.log)
  218. cmd = ['clone', self._vid_snap, self.vid]
  219. qubes_lvm(cmd, self.log)
  220. def create(self):
  221. assert self.vid
  222. assert self.size
  223. if self.save_on_stop:
  224. if self.source:
  225. cmd = ['clone', str(self.source), self.vid]
  226. else:
  227. cmd = [
  228. 'create',
  229. self.pool._pool_id, # pylint: disable=protected-access
  230. self.vid.split('/', 1)[1],
  231. str(self.size)
  232. ]
  233. qubes_lvm(cmd, self.log)
  234. reset_cache()
  235. return self
  236. def remove(self):
  237. assert self.vid
  238. if self.is_dirty():
  239. cmd = ['remove', self._vid_snap]
  240. qubes_lvm(cmd, self.log)
  241. if not os.path.exists(self.path):
  242. return
  243. cmd = ['remove', self.vid]
  244. qubes_lvm(cmd, self.log)
  245. reset_cache()
  246. def export(self):
  247. ''' Returns an object that can be `open()`. '''
  248. devpath = '/dev/' + self.vid
  249. return devpath
  250. def import_volume(self, src_volume):
  251. if not src_volume.save_on_stop:
  252. return self
  253. # HACK: neat trick to speed up testing if you have same physical thin
  254. # pool assigned to two qubes-pools i.e: qubes_dom0 and test-lvm
  255. # pylint: disable=line-too-long
  256. if isinstance(src_volume.pool, ThinPool) and \
  257. src_volume.pool.thin_pool == self.pool.thin_pool: # NOQA
  258. cmd = ['remove', self.vid]
  259. qubes_lvm(cmd, self.log)
  260. cmd = ['clone', str(src_volume), str(self)]
  261. qubes_lvm(cmd, self.log)
  262. else:
  263. src_path = src_volume.export()
  264. cmd = ['sudo', 'dd', 'if=' + src_path, 'of=/dev/' + self.vid,
  265. 'conv=sparse']
  266. subprocess.check_call(cmd)
  267. reset_cache()
  268. return self
  269. def import_data(self):
  270. ''' Returns an object that can be `open()`. '''
  271. devpath = '/dev/' + self.vid
  272. return devpath
  273. def is_dirty(self):
  274. if self.save_on_stop:
  275. return os.path.exists(self.path + '-snap')
  276. return False
  277. def revert(self, revision=None):
  278. old_path = self.path + '-back'
  279. if not os.path.exists(old_path):
  280. msg = "Volume {!s} has no {!s}".format(self, old_path)
  281. raise qubes.storage.StoragePoolException(msg)
  282. cmd = ['remove', self.vid]
  283. qubes_lvm(cmd, self.log)
  284. cmd = ['clone', self.vid + '-back', self.vid]
  285. qubes_lvm(cmd, self.log)
  286. reset_cache()
  287. return self
  288. def resize(self, size):
  289. ''' Expands volume, throws
  290. :py:class:`qubst.storage.qubes.storage.StoragePoolException` if
  291. given size is less than current_size
  292. '''
  293. if not self.rw:
  294. msg = 'Can not resize reađonly volume {!s}'.format(self)
  295. raise qubes.storage.StoragePoolException(msg)
  296. if size <= self.size:
  297. raise qubes.storage.StoragePoolException(
  298. 'For your own safety, shrinking of %s is'
  299. ' disabled. If you really know what you'
  300. ' are doing, use `lvresize` on %s manually.' %
  301. (self.name, self.vid))
  302. cmd = ['extend', self.vid, str(size)]
  303. qubes_lvm(cmd, self.log)
  304. reset_cache()
  305. def _snapshot(self):
  306. try:
  307. cmd = ['remove', self._vid_snap]
  308. qubes_lvm(cmd, self.log)
  309. except: # pylint: disable=bare-except
  310. pass
  311. if self.source is None:
  312. cmd = ['clone', self.vid, self._vid_snap]
  313. else:
  314. cmd = ['clone', str(self.source), self._vid_snap]
  315. qubes_lvm(cmd, self.log)
  316. def start(self):
  317. if self.snap_on_start:
  318. if not self.save_on_stop or not self.is_dirty():
  319. self._snapshot()
  320. elif not self.save_on_stop:
  321. self._reset()
  322. reset_cache()
  323. return self
  324. def stop(self):
  325. if self.save_on_stop and self.snap_on_start:
  326. self._commit()
  327. if self.snap_on_start:
  328. cmd = ['remove', self._vid_snap]
  329. qubes_lvm(cmd, self.log)
  330. elif not self.save_on_stop:
  331. cmd = ['remove', self.vid]
  332. qubes_lvm(cmd, self.log)
  333. reset_cache()
  334. return self
  335. def verify(self):
  336. ''' Verifies the volume. '''
  337. try:
  338. vol_info = size_cache[self.vid]
  339. return vol_info['attr'][4] == 'a'
  340. except KeyError:
  341. return False
  342. def block_device(self):
  343. ''' Return :py:class:`qubes.storage.BlockDevice` for serialization in
  344. the libvirt XML template as <disk>.
  345. '''
  346. if self.snap_on_start:
  347. return qubes.storage.BlockDevice(
  348. '/dev/' + self._vid_snap, self.name, self.script,
  349. self.rw, self.domain, self.devtype)
  350. return super(ThinVolume, self).block_device()
  351. @property
  352. def usage(self): # lvm thin usage always returns at least the same usage as
  353. # the parent
  354. try:
  355. return qubes.storage.lvm.size_cache[self.vid]['usage']
  356. except KeyError:
  357. return 0
  358. def pool_exists(pool_id):
  359. ''' Return true if pool exists '''
  360. try:
  361. vol_info = size_cache[pool_id]
  362. return vol_info['attr'][0] == 't'
  363. except KeyError:
  364. return False
  365. def qubes_lvm(cmd, log=logging.getLogger('qubes.storage.lvm')):
  366. ''' Call :program:`lvm` to execute an LVM operation '''
  367. action = cmd[0]
  368. if action == 'remove':
  369. lvm_cmd = ['lvremove', '-f', cmd[1]]
  370. elif action == 'clone':
  371. lvm_cmd = ['lvcreate', '-kn', '-ay', '-s', cmd[1], '-n', cmd[2]]
  372. elif action == 'create':
  373. lvm_cmd = ['lvcreate', '-T', cmd[1], '-kn', '-ay', '-n', cmd[2], '-V',
  374. str(cmd[3]) + 'B']
  375. elif action == 'extend':
  376. size = int(cmd[2]) / (1000 * 1000)
  377. lvm_cmd = ["lvextend", "-L%s" % size, cmd[1]]
  378. else:
  379. raise NotImplementedError('unsupported action: ' + action)
  380. if lvm_is_very_old:
  381. # old lvm in trusty image used there does not support -k option
  382. lvm_cmd = [x for x in lvm_cmd if x != '-kn']
  383. if os.getuid() != 0:
  384. cmd = ['sudo', 'lvm'] + lvm_cmd
  385. else:
  386. cmd = ['lvm'] + lvm_cmd
  387. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  388. close_fds=True)
  389. out, err = p.communicate()
  390. return_code = p.returncode
  391. if out:
  392. log.debug(out)
  393. if return_code == 0 and err:
  394. log.warning(err)
  395. elif return_code != 0:
  396. assert err, "Command exited unsuccessful, but printed nothing to stderr"
  397. raise qubes.storage.StoragePoolException(err)
  398. return True
  399. def reset_cache():
  400. qubes.storage.lvm.size_cache = init_cache()