qvm_pool.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. parser.register('action', 'parsers',
  132. qubesadmin.tools.AliasedSubParsersAction)
  133. sub_parsers = parser.add_subparsers(
  134. title='commands', dest='command',
  135. description="For more information see qvm-pool <command> -h")
  136. d_parser = sub_parsers.add_parser(
  137. 'drivers', aliases=('d',), help='List all drivers with their options')
  138. d_parser.set_defaults(func=list_drivers)
  139. init_list_parser(sub_parsers)
  140. init_info_parser(sub_parsers)
  141. init_add_parser(sub_parsers)
  142. init_remove_parser(sub_parsers)
  143. init_set_parser(sub_parsers)
  144. # default action
  145. parser.set_defaults(func=list_pools)
  146. return parser
  147. def uses_legacy_options(args, app):
  148. ''' Checks if legacy options and used, and invokes the legacy tool '''
  149. parser = argparse.ArgumentParser(description=__doc__,
  150. usage=argparse.SUPPRESS)
  151. parser.add_argument('-a', '--add',
  152. dest='has_legacy_options', action='store_true',
  153. help=argparse.SUPPRESS)
  154. parser.add_argument('-i', '--info',
  155. dest='has_legacy_options', action='store_true',
  156. help=argparse.SUPPRESS)
  157. parser.add_argument('-l', '--list',
  158. dest='has_legacy_options', action='store_true',
  159. help=argparse.SUPPRESS)
  160. parser.add_argument('-r', '--remove',
  161. dest='has_legacy_options', action='store_true',
  162. help=argparse.SUPPRESS)
  163. parser.add_argument('-s', '--set',
  164. dest='has_legacy_options', action='store_true',
  165. help=argparse.SUPPRESS)
  166. parser.add_argument('--help-drivers',
  167. dest='has_legacy_options', action='store_true',
  168. help=argparse.SUPPRESS)
  169. parsed_args, _ = parser.parse_known_args(args)
  170. if parsed_args.has_legacy_options:
  171. qubesadmin.tools.qvm_pool_legacy.main(args, app)
  172. return True
  173. return False
  174. def main(args=None, app=None):
  175. '''Main routine of :program:`qvm-pool`.'''
  176. if uses_legacy_options(args, app):
  177. return 0
  178. parser = get_parser()
  179. args = parser.parse_args(args, app=app)
  180. try:
  181. args.func(args)
  182. except qubesadmin.exc.QubesException as e:
  183. parser.error_runtime(str(e))
  184. return 1
  185. return 0
  186. if __name__ == '__main__':
  187. sys.exit(main())