qvm_volume.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # encoding=utf-8
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  6. # Copyright (C) 2017 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU Lesser General Public License as published by
  11. # the Free Software Foundation; either version 2.1 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public License along
  20. # with this program; if not, see <http://www.gnu.org/licenses/>.
  21. '''Qubes volume management'''
  22. from __future__ import print_function
  23. import argparse
  24. import sys
  25. import collections
  26. import qubesadmin
  27. import qubesadmin.exc
  28. import qubesadmin.tools
  29. import qubesadmin.utils
  30. def prepare_table(vd_list, full=False):
  31. ''' Converts a list of :py:class:`VolumeData` objects to a list of tupples
  32. for the :py:func:`qubes.tools.print_table`.
  33. If :program:`qvm-volume` is running in a TTY, it will ommit duplicate
  34. data.
  35. :param list vd_list: List of :py:class:`VolumeData` objects.
  36. :param bool full: If set to true duplicate data is printed even when
  37. running from TTY.
  38. :returns: list of tupples
  39. '''
  40. output = []
  41. output += [('POOL:VOLUME', 'VMNAME', 'VOLUME_NAME', 'REVERT_POSSIBLE')]
  42. for volume in sorted(vd_list):
  43. if volume.domains:
  44. vmname, volume_name = volume.domains.pop()
  45. output += [(str(volume), vmname, volume_name, volume.revisions)]
  46. for tupple in volume.domains:
  47. vmname, volume_name = tupple
  48. if full or not sys.stdout.isatty():
  49. output += [(str(volume), vmname, volume_name,
  50. volume.revisions)]
  51. else:
  52. output += [('', vmname, volume_name, volume.revisions)]
  53. else:
  54. output += [(str(volume), "")]
  55. return output
  56. class VolumeData(object):
  57. ''' Wrapper object around :py:class:`qubes.storage.Volume`, mainly to track
  58. the domains a volume is attached to.
  59. '''
  60. # pylint: disable=too-few-public-methods
  61. def __init__(self, volume):
  62. self.pool = volume.pool
  63. self.vid = volume.vid
  64. if volume.revisions:
  65. self.revisions = 'Yes'
  66. else:
  67. self.revisions = 'No'
  68. self.domains = []
  69. def __lt__(self, other):
  70. return (self.pool, self.vid) < (other.pool, other.vid)
  71. def __str__(self):
  72. return "{!s}:{!s}".format(self.pool, self.vid)
  73. def info_volume(args):
  74. ''' Show info about selected volume '''
  75. volume = args.volume
  76. info_items = ('pool', 'vid', 'rw', 'source', 'save_on_stop',
  77. 'snap_on_start', 'size', 'usage', 'revisions_to_keep')
  78. if args.property:
  79. if args.property == 'revisions':
  80. for rev in volume.revisions:
  81. print(rev)
  82. elif args.property == 'is_outdated':
  83. print(volume.is_outdated())
  84. elif args.property in info_items:
  85. value = getattr(volume, args.property)
  86. if value is None:
  87. value = ''
  88. print(value)
  89. else:
  90. raise qubesadmin.exc.StoragePoolException(
  91. 'No such property: {}'.format(args.property))
  92. else:
  93. info = collections.OrderedDict()
  94. for item in info_items:
  95. value = getattr(volume, item)
  96. if value is None:
  97. value = ''
  98. info[item] = str(value)
  99. info['is_outdated'] = str(volume.is_outdated())
  100. qubesadmin.tools.print_table(info.items())
  101. revisions = volume.revisions
  102. if revisions:
  103. print('Available revisions (for revert):')
  104. for rev in revisions:
  105. print(' ' + rev)
  106. else:
  107. print('Available revisions (for revert): none')
  108. def config_volume(args):
  109. ''' Change property of selected volume '''
  110. volume = args.volume
  111. if not args.property in ('rw', 'revisions_to_keep'):
  112. raise qubesadmin.exc.QubesNoSuchPropertyError(
  113. 'Invalid property: {}'.format(args.property))
  114. setattr(volume, args.property, args.value)
  115. def list_volumes(args):
  116. ''' Called by the parser to execute the qvm-volume list subcommand. '''
  117. app = args.app
  118. if hasattr(args, 'domains') and args.domains:
  119. domains = args.domains
  120. else:
  121. domains = app.domains
  122. volumes = [v for vm in domains for v in vm.volumes.values()]
  123. if getattr(args, 'pools', None):
  124. # only specified pools
  125. volumes = [v for v in volumes if v.pool in args.pools]
  126. vd_dict = {}
  127. for volume in volumes:
  128. volume_data = VolumeData(volume)
  129. try:
  130. vd_dict[volume.pool][volume.vid] = volume_data
  131. except KeyError:
  132. vd_dict[volume.pool] = {volume.vid: volume_data}
  133. for domain in domains: # gather the domain names
  134. try:
  135. for name, volume in domain.volumes.items():
  136. try:
  137. volume_data = vd_dict[volume.pool][volume.vid]
  138. volume_data.domains += [(domain.name, name)]
  139. except KeyError:
  140. # Skipping volume
  141. continue
  142. except AttributeError:
  143. # Skipping domain without volumes
  144. continue
  145. if hasattr(args, 'domains') and args.domains:
  146. result = [x # reduce to only VolumeData with assigned domains
  147. for p in vd_dict.values() for x in p.values()
  148. if x.domains]
  149. else:
  150. result = [x for p in vd_dict.values() for x in p.values()]
  151. qubesadmin.tools.print_table(
  152. prepare_table(result, full=getattr(args, 'full', False)))
  153. def revert_volume(args):
  154. ''' Revert volume to previous state '''
  155. volume = args.volume
  156. if args.revision:
  157. revision = args.revision
  158. else:
  159. revisions = volume.revisions
  160. if not revisions:
  161. raise qubesadmin.exc.StoragePoolException(
  162. 'No snapshots available')
  163. revision = volume.revisions[-1]
  164. volume.revert(revision)
  165. def extend_volumes(args):
  166. ''' Called by the parser to execute the :program:`qvm-block extend`
  167. subcommand
  168. '''
  169. volume = args.volume
  170. size = qubesadmin.utils.parse_size(args.size)
  171. if not args.force and size < volume.size:
  172. raise qubesadmin.exc.StoragePoolException(
  173. 'For your own safety, shrinking of %s is'
  174. ' disabled (%d < %d). If you really know what you'
  175. ' are doing, resize filesystem manually first, then use `-f` '
  176. 'option.' %
  177. (volume.name, size, volume.size))
  178. volume.resize(size)
  179. def init_list_parser(sub_parsers):
  180. ''' Configures the parser for the :program:`qvm-block list` subcommand '''
  181. # pylint: disable=protected-access
  182. list_parser = sub_parsers.add_parser('list', aliases=('ls', 'l'),
  183. help='list storage volumes')
  184. list_parser.add_argument('-p', '--pool', dest='pools',
  185. action=qubesadmin.tools.PoolsAction)
  186. list_parser.add_argument(
  187. '--full', action='store_true',
  188. help='print full line for each POOL_NAME:VOLUME_ID & vm combination')
  189. vm_name_group = qubesadmin.tools.VmNameGroup(
  190. list_parser, required=False, vm_action=qubesadmin.tools.VmNameAction,
  191. help='list volumes from specified domain(s)')
  192. list_parser._mutually_exclusive_groups.append(vm_name_group)
  193. list_parser.set_defaults(func=list_volumes)
  194. def init_revert_parser(sub_parsers):
  195. ''' Add 'revert' action related options '''
  196. revert_parser = sub_parsers.add_parser(
  197. 'revert', aliases=('rv', 'r'),
  198. help='revert volume to previous revision')
  199. revert_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  200. action=qubesadmin.tools.VMVolumeAction)
  201. revert_parser.add_argument(metavar='REVISION', dest='revision',
  202. help='Optional revision to revert to; '
  203. 'if not specified, latest one is assumed',
  204. action='store', nargs='?')
  205. revert_parser.set_defaults(func=revert_volume)
  206. def init_extend_parser(sub_parsers):
  207. ''' Add 'extend' action related options '''
  208. extend_parser = sub_parsers.add_parser(
  209. "resize", aliases=('extend', ), help="resize volume for domain")
  210. extend_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  211. action=qubesadmin.tools.VMVolumeAction)
  212. extend_parser.add_argument('size', help='New size in bytes')
  213. extend_parser.add_argument('--force', '-f', action='store_true',
  214. help='Force operation, even if new size is smaller than the current '
  215. 'one')
  216. extend_parser.set_defaults(func=extend_volumes)
  217. def init_info_parser(sub_parsers):
  218. ''' Add 'info' action related options '''
  219. info_parser = sub_parsers.add_parser(
  220. 'info', aliases=('i',), help='info about volume')
  221. info_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  222. action=qubesadmin.tools.VMVolumeAction)
  223. info_parser.add_argument(dest='property', action='store',
  224. nargs=argparse.OPTIONAL,
  225. help='Show only this property instead of all of them; use '
  226. '\'revisions\' to list available revisions')
  227. info_parser.set_defaults(func=info_volume)
  228. def init_config_parser(sub_parsers):
  229. ''' Add 'info' action related options '''
  230. info_parser = sub_parsers.add_parser(
  231. 'config', aliases=('c', 'set', 's'),
  232. help='set config option for a volume')
  233. info_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  234. action=qubesadmin.tools.VMVolumeAction)
  235. info_parser.add_argument(dest='property', action='store')
  236. info_parser.add_argument(dest='value', action='store')
  237. info_parser.set_defaults(func=config_volume)
  238. def get_parser():
  239. '''Create :py:class:`argparse.ArgumentParser` suitable for
  240. :program:`qvm-volume`.
  241. '''
  242. parser = qubesadmin.tools.QubesArgumentParser(description=__doc__,
  243. want_app=True)
  244. parser.register('action', 'parsers',
  245. qubesadmin.tools.AliasedSubParsersAction)
  246. sub_parsers = parser.add_subparsers(
  247. title='commands',
  248. description="For more information see qvm-volume command -h",
  249. dest='command')
  250. init_info_parser(sub_parsers)
  251. init_config_parser(sub_parsers)
  252. init_extend_parser(sub_parsers)
  253. init_list_parser(sub_parsers)
  254. init_revert_parser(sub_parsers)
  255. # default action
  256. parser.set_defaults(func=list_volumes)
  257. return parser
  258. def main(args=None, app=None):
  259. '''Main routine of :program:`qvm-volume`.'''
  260. parser = get_parser()
  261. try:
  262. args = parser.parse_args(args, app=app)
  263. args.func(args)
  264. except qubesadmin.exc.QubesException as e:
  265. parser.print_error(str(e))
  266. return 1
  267. return 0
  268. if __name__ == '__main__':
  269. sys.exit(main())