lvm.py 15 KB

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