qubes_lvm.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #!/usr/bin/python2
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. ''' Manage pools and volumes managed by the 'lvm_thin' driver. '''
  22. from __future__ import print_function
  23. import datetime
  24. import logging
  25. import os
  26. import subprocess
  27. import sys
  28. import time
  29. import lvm
  30. import qubes
  31. log = logging.getLogger('qubes.storage.lvm')
  32. def lvm_image_changed(vm):
  33. ''' Returns true if source image changed '''
  34. # TODO: reimplement lvm_image_changed
  35. vm_root = vm.root_img
  36. tp_root = vm.template.root_img
  37. if not os.path.exists(vm_root):
  38. return False
  39. cmd = 'date +"%%s" -d "' + \
  40. '`sudo tune2fs %s -l|grep "Last write time"|cut -d":" -f2,3,4`"'
  41. result1 = subprocess.check_output(cmd % vm_root, shell=True).strip()
  42. result2 = subprocess.check_output(cmd % tp_root, shell=True).strip()
  43. result1 = datetime.datetime.strptime(result1, '%c')
  44. result2 = datetime.datetime.strptime(result2, '%c')
  45. return result2 > result1
  46. def pool_exists(args):
  47. """ Check if given name is an lvm thin volume. """
  48. # TODO Implement a faster and proper working version pool_exists
  49. vg_name, thin_pool_name = args.pool_id.split('/', 1)
  50. volume_group = lvm.vgOpen(vg_name)
  51. for p in volume_group.listLVs():
  52. if p.getAttr()[0] == 't' and p.getName() == thin_pool_name:
  53. volume_group.close()
  54. return True
  55. volume_group.close()
  56. return False
  57. def volume_exists(volume):
  58. """ Check if the given volume exists and is a thin volume """
  59. log.debug("Checking if the %s thin volume exists", volume)
  60. assert volume is not None
  61. vg_name, volume_name = volume.split('/', 1)
  62. volume_group = lvm.vgOpen(vg_name)
  63. for p in volume_group.listLVs():
  64. if p.getAttr()[0] == 'V' and p.getName() == volume_name:
  65. volume_group.close()
  66. return True
  67. volume_group.close()
  68. return False
  69. def remove_volume(args):
  70. """ Tries to remove the specified logical volume.
  71. If the removal fails it will try up to 3 times waiting 1, 2 and 3
  72. seconds between tries. Most of the time this function fails if some
  73. process still has the volume locked.
  74. """
  75. img = args.name
  76. if not volume_exists(img):
  77. log.info("Expected to remove %s, but volume does not exist", img)
  78. return
  79. tries = 1
  80. successful = False
  81. cmd = ['sudo', 'lvremove', '-f', img]
  82. while tries <= 3 and not successful:
  83. log.info("Trying to remove LVM %s", img)
  84. try:
  85. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  86. log.debug(output)
  87. successful = True
  88. except subprocess.CalledProcessError:
  89. successful = False
  90. if successful:
  91. break
  92. else:
  93. time.sleep(tries)
  94. tries += 1
  95. if not successful:
  96. log.error('Could not remove volume ' + img)
  97. def clone_volume(args):
  98. """ Calls lvcreate and creates new snapshot. """
  99. old = args.source
  100. new_name = args.destination
  101. cmd = ["sudo", "lvcreate", "-kn", "-ay", "-s", old, "-n", new_name]
  102. return subprocess.call(cmd)
  103. def new_volume(args):
  104. ''' Creates a new volume in the specified thin pool, formated with ext4 '''
  105. thin_pool = args.pool_id
  106. name = args.name
  107. size = args.size
  108. log.info('Creating new Thin LVM %s in %s VG %s bytes', name, thin_pool,
  109. size)
  110. cmd = ['sudo', 'lvcreate', '-T', thin_pool, '-kn', '-ay', '-n', name, '-V',
  111. str(size) + 'B']
  112. return subprocess.call(cmd)
  113. def rename_volume(old_name, new_name):
  114. ''' Rename volume '''
  115. log.debug("Renaming LVM %s to %s ", old_name, new_name)
  116. retcode = subprocess.call(["sudo", "lvrename", old_name, new_name])
  117. if retcode != 0:
  118. raise IOError("Error renaming LVM %s to %s " % (old_name, new_name))
  119. return new_name
  120. def init_pool_parser(sub_parsers):
  121. ''' Initialize pool subparser '''
  122. pool_parser = sub_parsers.add_parser(
  123. 'pool', aliases=('p', 'pl'),
  124. help="Exit with exit code 0 if pool exists")
  125. pool_parser.add_argument('pool_id', metavar='VG/POOL',
  126. help="volume_group/pool_name")
  127. pool_parser.set_defaults(func=pool_exists)
  128. def init_new_parser(sub_parsers):
  129. ''' Initialize the 'new' subparser '''
  130. new_parser = sub_parsers.add_parser(
  131. 'new', aliases=('n', 'create'),
  132. help='Creates a new thin ThinPoolLogicalVolume')
  133. new_parser.add_argument('pool_id', metavar='VG/POOL',
  134. help="volume_group/pool_name")
  135. new_parser.add_argument('name',
  136. help='name of the new ThinPoolLogicalVolume')
  137. new_parser.add_argument(
  138. 'size', help='size in bytes of the new ThinPoolLogicalVolume')
  139. new_parser.set_defaults(func=new_volume)
  140. def init_import_parser(sub_parsers):
  141. ''' Initialize import subparser '''
  142. import_parser = sub_parsers.add_parser(
  143. 'import', aliases=('imp', 'i'),
  144. help='sparse copy data from stdin to a thin volume')
  145. import_parser.add_argument('name', metavar='VG/VID',
  146. help='volume_group/volume_name')
  147. import_parser.set_defaults(func=import_volume)
  148. def init_clone_parser(sub_parsers):
  149. ''' Initialize clone subparser '''
  150. clone_parser = sub_parsers.add_parser(
  151. 'clone', aliases=('cln', 'c'),
  152. help='sparse copy data from stdin to a thin volume')
  153. clone_parser.add_argument('source', metavar='VG/VID',
  154. help='volume_group/volume_name')
  155. clone_parser.add_argument('destination', metavar='VG/VID',
  156. help='volume_group/volume_name')
  157. clone_parser.set_defaults(func=clone_volume)
  158. def import_volume(args):
  159. ''' Imports from stdin to a thin volume '''
  160. name = args.name
  161. src = sys.stdin
  162. blk_size = 4096
  163. zeros = '\x00' * blk_size
  164. dst_path = '/dev/%s' % name
  165. with open(dst_path, 'wb') as dst:
  166. while True:
  167. tmp = src.read(blk_size)
  168. if not tmp:
  169. break
  170. elif tmp == zeros:
  171. dst.seek(blk_size, 1)
  172. else:
  173. dst.write(tmp)
  174. def list_volumes(args):
  175. ''' lists volumes '''
  176. vg_name, _ = args.name.split('/')
  177. volume_group = lvm.vgOpen(vg_name)
  178. for p in volume_group.listLVs():
  179. if p.getAttr()[0] == 'V':
  180. print(vg_name + "/" + p.getName() + ' ' + p.getAttr())
  181. volume_group.close()
  182. def init_volumes_parser(sub_parsers):
  183. ''' Initialize volumes subparser '''
  184. parser = sub_parsers.add_parser('volumes', aliases=('v', 'vol'),
  185. help='list volumes in a pool')
  186. parser.add_argument('name', metavar='VG/THIN_POOL',
  187. help='volume_group/thin_pool_name')
  188. parser.set_defaults(func=list_volumes)
  189. def init_remove_parser(sub_parsers):
  190. ''' Initialize remove subparser '''
  191. remove_parser = sub_parsers.add_parser('remove', aliases=('rm', 'r'),
  192. help='Removes a LogicalVolume')
  193. remove_parser.add_argument('name', metavar='VG/VID',
  194. help='volume_group/volume_name')
  195. remove_parser.set_defaults(func=remove_volume)
  196. def get_parser():
  197. '''Create :py:class:`argparse.ArgumentParser` suitable for
  198. :program:`qubes-lvm`.
  199. '''
  200. parser = qubes.tools.QubesArgumentParser(description=__doc__, want_app=True)
  201. parser.register('action', 'parsers', qubes.tools.AliasedSubParsersAction)
  202. sub_parsers = parser.add_subparsers(
  203. title='commands',
  204. description="For more information see qubes-lvm command -h",
  205. dest='command')
  206. init_pool_parser(sub_parsers)
  207. init_import_parser(sub_parsers)
  208. init_new_parser(sub_parsers)
  209. init_volumes_parser(sub_parsers)
  210. init_remove_parser(sub_parsers)
  211. init_clone_parser(sub_parsers)
  212. return parser
  213. def main(args=None):
  214. '''Main routine of :program:`qubes-lvm`.'''
  215. args = get_parser().parse_args(args)
  216. return args.func(args)
  217. if __name__ == '__main__':
  218. sys.exit(main())