qvm_device.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #!/usr/bin/python2
  2. # coding=utf-8
  3. # pylint: disable=C,R
  4. #
  5. # The Qubes OS Project, http://www.qubes-os.org
  6. #
  7. # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  8. # Copyright (C) 2016 Marek Marczykowski-Górecki
  9. # <marmarek@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. '''Qubes volume and block device managment'''
  25. from __future__ import print_function
  26. import argparse
  27. import os
  28. import sys
  29. import qubes
  30. import qubes.devices
  31. import qubes.exc
  32. import qubes.tools
  33. def prepare_table(dev_list):
  34. ''' Converts a list of :py:class:`qubes.devices.DeviceInfo` objects to a
  35. list of tupples for the :py:func:`qubes.tools.print_table`.
  36. If :program:`qvm-devices` is running in a TTY, it will ommit duplicate
  37. data.
  38. :param list dev_list: List of :py:class:`qubes.devices.DeviceInfo`
  39. objects.
  40. :returns: list of tupples
  41. '''
  42. output = []
  43. header = []
  44. if sys.stdout.isatty():
  45. header += [('BACKEND:DEVID', 'DESCRIPTION', 'USED BY')] # NOQA
  46. for dev in dev_list:
  47. output += [(
  48. "{!s}:{!s}".format(dev.backend_domain, dev.ident),
  49. dev.description,
  50. str(dev.frontend_domain) if dev.frontend_domain else "",
  51. )]
  52. return header + sorted(output)
  53. def list_devices(args):
  54. ''' Called by the parser to execute the qubes-devices list
  55. subcommand. '''
  56. app = args.app
  57. result = []
  58. if hasattr(args, 'domains') and args.domains:
  59. for domain in args.domains:
  60. result.extend(domain.devices[args.devclass].attached())
  61. else:
  62. for backend in app.domains:
  63. result.extend(backend.devices[args.devclass])
  64. qubes.tools.print_table(prepare_table(result))
  65. def attach_device(args):
  66. ''' Called by the parser to execute the :program:`qvm-devices attach`
  67. subcommand.
  68. '''
  69. device = args.device
  70. vm = args.domains[0]
  71. vm.devices[args.devclass].attach(device)
  72. def detach_device(args):
  73. ''' Called by the parser to execute the :program:`qvm-devices detach`
  74. subcommand.
  75. '''
  76. device = args.device
  77. vm = args.domains[0]
  78. vm.devices[args.devclass].detach(device)
  79. def init_list_parser(sub_parsers):
  80. ''' Configures the parser for the :program:`qvm-devices list` subcommand '''
  81. # pylint: disable=protected-access
  82. list_parser = sub_parsers.add_parser('list', aliases=('ls', 'l'),
  83. help='list devices')
  84. vm_name_group = qubes.tools.VmNameGroup(
  85. list_parser, required=False, vm_action=qubes.tools.VmNameAction,
  86. help='list devices assigned to specific domain(s)')
  87. list_parser._mutually_exclusive_groups.append(vm_name_group)
  88. list_parser.set_defaults(func=list_devices)
  89. class DeviceAction(qubes.tools.QubesAction):
  90. ''' Action for argument parser that gets the
  91. :py:class:``qubes.storage.Volume`` from a POOL_NAME:VOLUME_ID string.
  92. '''
  93. # pylint: disable=too-few-public-methods
  94. def __init__(self, help='A domain & device id combination',
  95. required=True, allow_unknown=False, **kwargs):
  96. # pylint: disable=redefined-builtin
  97. super(DeviceAction, self).__init__(help=help, required=required,
  98. **kwargs)
  99. self.allow_unknown = allow_unknown
  100. def __call__(self, parser, namespace, values, option_string=None):
  101. ''' Set ``namespace.device`` to ``values`` '''
  102. setattr(namespace, self.dest, values)
  103. def parse_qubes_app(self, parser, namespace):
  104. ''' Acquire the :py:class:``qubes.devices.DeviceInfo`` object from
  105. ``namespace.app``.
  106. '''
  107. assert hasattr(namespace, 'app')
  108. assert hasattr(namespace, 'devclass')
  109. app = namespace.app
  110. devclass = namespace.devclass
  111. try:
  112. backend_name, devid = getattr(namespace, self.dest).split(':', 1)
  113. try:
  114. backend = app.domains[backend_name]
  115. dev = backend.devices[devclass][devid]
  116. if not self.allow_unknown and isinstance(dev,
  117. qubes.devices.UnknownDevice):
  118. parser.error_runtime('no device {!r} in qube {!r}'.format(
  119. backend_name, devid))
  120. except KeyError:
  121. parser.error_runtime('no domain {!r}'.format(backend_name))
  122. except ValueError:
  123. parser.error('expected a domain & device id combination like '
  124. 'foo:bar')
  125. def get_parser(device_class=None):
  126. '''Create :py:class:`argparse.ArgumentParser` suitable for
  127. :program:`qvm-block`.
  128. '''
  129. parser = qubes.tools.QubesArgumentParser(description=__doc__, want_app=True)
  130. parser.register('action', 'parsers', qubes.tools.AliasedSubParsersAction)
  131. if device_class:
  132. parser.add_argument('devclass', const=device_class,
  133. action='store_const',
  134. help=argparse.SUPPRESS)
  135. else:
  136. parser.add_argument('devclass', metavar='DEVICE_CLASS', action='store',
  137. help="Device class to manage ('pci', 'usb', etc)")
  138. sub_parsers = parser.add_subparsers(
  139. title='commands',
  140. description="For more information see qvm-device command -h",
  141. dest='command')
  142. init_list_parser(sub_parsers)
  143. attach_parser = sub_parsers.add_parser(
  144. 'attach', help="Attach device to domain", aliases=('at', 'a'))
  145. attach_parser.add_argument('VMNAME', action=qubes.tools.RunningVmNameAction)
  146. attach_parser.add_argument(metavar='BACKEND:DEVICE_ID', dest='device',
  147. action=qubes.tools.VolumeAction)
  148. attach_parser.set_defaults(func=detach_device)
  149. detach_parser = sub_parsers.add_parser(
  150. "detach", help="Detach device from domain", aliases=('d', 'dt'))
  151. detach_parser.add_argument('VMNAME', action=qubes.tools.RunningVmNameAction)
  152. detach_parser.add_argument(metavar='BACKEND:DEVICE_ID', dest='device',
  153. action=qubes.tools.VolumeAction)
  154. detach_parser.set_defaults(func=detach_device)
  155. return parser
  156. def main(args=None):
  157. '''Main routine of :program:`qvm-block`.'''
  158. basename = os.path.basename(sys.argv[0])
  159. devclass = None
  160. if basename.startswith('qvm-') and basename != 'qvm-device':
  161. devclass = basename[4:]
  162. args = get_parser(devclass).parse_args(args)
  163. try:
  164. args.func(args)
  165. except qubes.exc.QubesException as e:
  166. print(e.message, file=sys.stderr)
  167. return 1
  168. return 0
  169. if __name__ == '__main__':
  170. sys.exit(main())