qvm_pool.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 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. '''Manages Qubes pools and their options'''
  22. from __future__ import print_function
  23. import argparse
  24. import sys
  25. import qubes
  26. import qubes.ext
  27. import qubes.storage
  28. import qubes.tools
  29. drivers = qubes.storage.pool_drivers()
  30. class _HelpDrivers(argparse.Action):
  31. ''' Action for argument parser that displays all drivers and their options
  32. and exits.
  33. '''
  34. def __init__(self,
  35. option_strings,
  36. dest=argparse.SUPPRESS,
  37. default=argparse.SUPPRESS):
  38. super(_HelpDrivers, self).__init__(
  39. option_strings=option_strings,
  40. dest=dest,
  41. default=default,
  42. nargs=0,
  43. help='list all drivers with their options and exit')
  44. def __call__(self, parser, namespace, values, option_string=None):
  45. result = []
  46. for driver in drivers:
  47. params = driver_parameters(driver)
  48. driver_options = ', '.join(params)
  49. result += [(driver, 'driver options', driver_options)]
  50. qubes.tools.print_table(result)
  51. parser.exit(0)
  52. class _Info(qubes.tools.PoolsAction):
  53. ''' Action for argument parser that displays pool info and exits. '''
  54. def __init__(self, option_strings, help='print pool info and exit',
  55. **kwargs):
  56. # pylint: disable=redefined-builtin
  57. super(_Info, self).__init__(option_strings, help=help, **kwargs)
  58. def __call__(self, parser, namespace, values, option_string=None):
  59. setattr(namespace, 'command', 'info')
  60. super(_Info, self).__call__(parser, namespace, values, option_string)
  61. def pool_info(pool):
  62. ''' Prints out pool name and config '''
  63. data = [("name", pool.name)]
  64. data += [i for i in pool.config.items() if i[0] != 'name']
  65. qubes.tools.print_table(data)
  66. def list_pools(app):
  67. ''' Prints out all known pools and their drivers '''
  68. result = [('NAME', 'DRIVER')]
  69. for pool in app.pools.values():
  70. if not pool.volumes and issubclass(
  71. pool.__class__, qubes.storage.domain.DomainPool):
  72. # skip empty DomainPools
  73. continue
  74. result += [(pool.name, pool.driver)]
  75. qubes.tools.print_table(result)
  76. class _Remove(argparse.Action):
  77. ''' Action for argument parser that removes a pool '''
  78. def __init__(self, option_strings, dest=None, default=None, metavar=None):
  79. super(_Remove, self).__init__(option_strings=option_strings,
  80. dest=dest,
  81. metavar=metavar,
  82. default=default,
  83. help='remove pool')
  84. def __call__(self, parser, namespace, name, option_string=None):
  85. setattr(namespace, 'command', 'remove')
  86. setattr(namespace, 'name', name)
  87. class _Add(argparse.Action):
  88. ''' Action for argument parser that adds a pool. '''
  89. def __init__(self, option_strings, dest=None, default=None, metavar=None):
  90. super(_Add, self).__init__(option_strings=option_strings,
  91. dest=dest,
  92. metavar=metavar,
  93. default=default,
  94. nargs=2,
  95. help='add pool')
  96. def __call__(self, parser, namespace, values, option_string=None):
  97. name, driver = values
  98. if driver not in drivers:
  99. parser.error('driver %s is unknown \n' % driver)
  100. else:
  101. setattr(namespace, 'command', 'add')
  102. setattr(namespace, 'name', name)
  103. setattr(namespace, 'driver', driver)
  104. class _Options(argparse.Action):
  105. ''' Action for argument parser that parsers options. '''
  106. def __init__(self, option_strings, dest, default, metavar='options'):
  107. super(_Options, self).__init__(
  108. option_strings=option_strings,
  109. dest=dest,
  110. metavar=metavar,
  111. default=default,
  112. help='comma-separated list of driver options')
  113. def __call__(self, parser, namespace, options, option_string=None):
  114. setattr(namespace, 'options',
  115. dict([option.split('=', 1) for option in options.split(',')]))
  116. def get_parser():
  117. ''' Parses the provided args '''
  118. epilog = 'available pool drivers: ' \
  119. + ', '.join(drivers)
  120. parser = qubes.tools.QubesArgumentParser(description=__doc__,
  121. epilog=epilog)
  122. parser.add_argument('--help-drivers', action=_HelpDrivers)
  123. parser.add_argument('-o', action=_Options, dest='options', default={})
  124. group = parser.add_mutually_exclusive_group()
  125. group.add_argument('-l',
  126. '--list',
  127. dest='command',
  128. const='list',
  129. action='store_const',
  130. help='list all pools and exit (default action)')
  131. group.add_argument('-i', '--info', metavar='POOLNAME', dest='pools',
  132. action=_Info, default=[])
  133. group.add_argument('-a',
  134. '--add',
  135. action=_Add,
  136. dest='command',
  137. metavar=('NAME', 'DRIVER'))
  138. group.add_argument('-r', '--remove', metavar='NAME', action=_Remove)
  139. return parser
  140. def driver_parameters(name):
  141. ''' Get __init__ parameters from a driver with out `self` & `name`. '''
  142. init_function = qubes.utils.get_entry_point_one(
  143. qubes.storage.STORAGE_ENTRY_POINT, name).__init__
  144. params = init_function.func_code.co_varnames
  145. ignored_params = ['self', 'name']
  146. return [p for p in params if p not in ignored_params]
  147. def main(args=None):
  148. '''Main routine of :program:`qvm-pools`.
  149. :param list args: Optional arguments to override those delivered from \
  150. command line.
  151. '''
  152. parser = get_parser()
  153. try:
  154. args = parser.parse_args(args)
  155. except qubes.exc.QubesException as e:
  156. parser.print_error(str(e))
  157. return 1
  158. if args.command is None or args.command == 'list':
  159. list_pools(args.app)
  160. elif args.command == 'add':
  161. if args.name in args.app.pools.keys():
  162. parser.error('pool named %s already exists \n' % args.name)
  163. args.app.add_pool(name=args.name, driver=args.driver, **args.options)
  164. args.app.save()
  165. elif args.command == 'remove':
  166. if args.name in args.app.pools.keys():
  167. args.app.remove_pool(args.name)
  168. args.app.save()
  169. else:
  170. parser.print_error('no such pool %s\n' % args.name)
  171. elif args.command == 'info':
  172. pool_info(args.pools)
  173. return 0
  174. if __name__ == '__main__':
  175. sys.exit(main())