qvm_pool.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # pylint: disable=too-few-public-methods
  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 Lesser General Public License as published by
  9. # the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License along
  18. # with this program; if not, see <http://www.gnu.org/licenses/>.
  19. '''Manages Qubes pools and their options'''
  20. from __future__ import print_function
  21. import argparse
  22. import sys
  23. import qubesadmin
  24. import qubesadmin.exc
  25. import qubesadmin.tools
  26. import qubesadmin.tools.qvm_pool_legacy
  27. def list_drivers(args):
  28. ''' Lists all drivers with their options '''
  29. result = [('DRIVER', 'OPTIONS')]
  30. for driver in sorted(args.app.pool_drivers):
  31. params = args.app.pool_driver_parameters(driver)
  32. driver_options = ', '.join(params)
  33. result += [(driver, driver_options)]
  34. qubesadmin.tools.print_table(result)
  35. def list_pools(args):
  36. ''' Lists all available pools '''
  37. result = [('NAME', 'DRIVER')]
  38. for pool in args.app.pools.values():
  39. result += [(pool.name, pool.driver)]
  40. qubesadmin.tools.print_table(result)
  41. def info_pools(args):
  42. ''' Prints info about the specified pools '''
  43. data = []
  44. for idx, pool in enumerate(args.pools):
  45. data += [("", "")] if idx > 0 else []
  46. data += [("name", pool.name)]
  47. data += [i for i in sorted(pool.config.items()) if i[0] != 'name']
  48. qubesadmin.tools.print_table(data)
  49. def add_pool(args):
  50. ''' Adds a new pool '''
  51. options = dict(opt.split('=', 1) for opt in args.option or [])
  52. try:
  53. args.app.add_pool(name=args.pool_name, driver=args.driver, **options)
  54. except qubesadmin.exc.QubesException as e:
  55. raise qubesadmin.exc.QubesException('Failed to add pool %s: %s\n',
  56. args.pool_name, str(e))
  57. def remove_pools(args):
  58. ''' Removes the specified pools '''
  59. errors = []
  60. for pool_name in args.pool_names:
  61. try:
  62. args.app.remove_pool(pool_name)
  63. except KeyError:
  64. errors.append('No such pool %s\n' % pool_name)
  65. except qubesadmin.exc.QubesException as e:
  66. errors.append(
  67. 'Failed to remove pool %s: %s\n' % (pool_name, str(e)))
  68. if errors:
  69. raise qubesadmin.exc.QubesException('\n'.join(errors))
  70. def set_pool(args):
  71. ''' Modifies driver options for a pool '''
  72. options = (opt.split('=', 1) for opt in args.option or [])
  73. pool = args.app.pools[args.pool_name]
  74. errors = []
  75. for opt, value in options:
  76. if not hasattr(type(pool), opt):
  77. errors.append(
  78. 'Setting option %s is not supported for pool %s\n' % (
  79. opt, pool.name))
  80. try:
  81. setattr(pool, opt, value)
  82. except qubesadmin.exc.QubesException as e:
  83. errors.append('Failed to set option %s for pool %s: %s\n' % (
  84. opt, pool.name, str(e)))
  85. if errors:
  86. raise qubesadmin.exc.QubesException('\n'.join(errors))
  87. def init_list_parser(sub_parsers):
  88. ''' Adds 'list' action related options '''
  89. l_parser = sub_parsers.add_parser(
  90. 'list', aliases=('l', 'ls'), help='List all available pools')
  91. l_parser.set_defaults(func=list_pools)
  92. def init_info_parser(sub_parsers):
  93. ''' Adds 'info' action related options '''
  94. i_parser = sub_parsers.add_parser(
  95. 'info', aliases=('i',), help='Print info about the specified pools')
  96. i_parser.add_argument(metavar='POOL_NAME', dest='pools',
  97. action=qubesadmin.tools.PoolsAction)
  98. i_parser.set_defaults(func=info_pools)
  99. def init_add_parser(sub_parsers):
  100. ''' Adds 'add' action related options '''
  101. a_parser = sub_parsers.add_parser(
  102. 'add', aliases=('a',), help='Add a new pool')
  103. a_parser.add_argument(metavar='POOL_NAME', dest='pool_name')
  104. a_parser.add_argument(metavar='DRIVER', dest='driver')
  105. a_parser.add_argument('--option', '-o', action='append',
  106. help="Set option for the driver in opt=value form"
  107. "(can be specified multiple times) --"
  108. "see `man qvm-pool` for details")
  109. a_parser.set_defaults(func=add_pool)
  110. def init_remove_parser(sub_parsers):
  111. ''' Adds 'remove' action related options '''
  112. r_parser = sub_parsers.add_parser(
  113. 'remove', aliases=('r', 'rm'), help='Remove the specified pools')
  114. r_parser.add_argument(metavar='POOL_NAME', dest='pool_names', nargs='+')
  115. r_parser.set_defaults(func=remove_pools)
  116. def init_set_parser(sub_parsers):
  117. ''' Adds 'set' action related options '''
  118. s_parser = sub_parsers.add_parser(
  119. 'set', aliases=('s',), help='Modify driver options for a pool')
  120. s_parser.add_argument(metavar='POOL_NAME', dest='pool_name')
  121. s_parser.add_argument('--option', '-o', action='append',
  122. help="Set option for the driver in opt=value form"
  123. "(can be specified multiple times) --"
  124. "see `man qvm-pool` for details")
  125. s_parser.set_defaults(func=set_pool)
  126. def get_parser():
  127. ''' Creates :py:class:`argparse.ArgumentParser` suitable for
  128. :program:`qvm-pool`.
  129. '''
  130. parser = qubesadmin.tools.QubesArgumentParser(description=__doc__,
  131. want_app=True)
  132. parser.register('action', 'parsers',
  133. qubesadmin.tools.AliasedSubParsersAction)
  134. sub_parsers = parser.add_subparsers(
  135. title='commands', dest='command',
  136. description="For more information see qvm-pool <command> -h")
  137. d_parser = sub_parsers.add_parser(
  138. 'drivers', aliases=('d',), help='List all drivers with their options')
  139. d_parser.set_defaults(func=list_drivers)
  140. init_list_parser(sub_parsers)
  141. init_info_parser(sub_parsers)
  142. init_add_parser(sub_parsers)
  143. init_remove_parser(sub_parsers)
  144. init_set_parser(sub_parsers)
  145. # default action
  146. parser.set_defaults(func=list_pools)
  147. return parser
  148. def uses_legacy_options(args, app):
  149. ''' Checks if legacy options and used, and invokes the legacy tool '''
  150. parser = argparse.ArgumentParser(description=__doc__,
  151. usage=argparse.SUPPRESS)
  152. parser.add_argument('-a', '--add',
  153. dest='has_legacy_options', action='store_true',
  154. help=argparse.SUPPRESS)
  155. parser.add_argument('-i', '--info',
  156. dest='has_legacy_options', action='store_true',
  157. help=argparse.SUPPRESS)
  158. parser.add_argument('-l', '--list',
  159. dest='has_legacy_options', action='store_true',
  160. help=argparse.SUPPRESS)
  161. parser.add_argument('-r', '--remove',
  162. dest='has_legacy_options', action='store_true',
  163. help=argparse.SUPPRESS)
  164. parser.add_argument('-s', '--set',
  165. dest='has_legacy_options', action='store_true',
  166. help=argparse.SUPPRESS)
  167. parser.add_argument('--help-drivers',
  168. dest='has_legacy_options', action='store_true',
  169. help=argparse.SUPPRESS)
  170. parsed_args, _ = parser.parse_known_args(args)
  171. if parsed_args.has_legacy_options:
  172. qubesadmin.tools.qvm_pool_legacy.main(args, app)
  173. return True
  174. return False
  175. def main(args=None, app=None):
  176. '''Main routine of :program:`qvm-pool`.'''
  177. if uses_legacy_options(args, app):
  178. return 0
  179. parser = get_parser()
  180. args = parser.parse_args(args, app=app)
  181. try:
  182. args.func(args)
  183. except qubesadmin.exc.QubesException as e:
  184. parser.error_runtime(str(e))
  185. return 1
  186. return 0
  187. if __name__ == '__main__':
  188. sys.exit(main())