qvm_device.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. # pylint: disable=C,R
  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) 2016 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 General Public License as published by
  11. # the Free Software Foundation; either version 2 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 General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. '''Qubes volume and block device managment'''
  23. from __future__ import print_function
  24. import argparse
  25. import os
  26. import sys
  27. import qubes
  28. import qubes.devices
  29. import qubes.exc
  30. import qubes.tools
  31. def prepare_table(dev_list):
  32. ''' Converts a list of :py:class:`qubes.devices.DeviceInfo` objects to a
  33. list of tupples for the :py:func:`qubes.tools.print_table`.
  34. If :program:`qvm-devices` is running in a TTY, it will ommit duplicate
  35. data.
  36. :param list dev_list: List of :py:class:`qubes.devices.DeviceInfo`
  37. objects.
  38. :returns: list of tupples
  39. '''
  40. output = []
  41. header = []
  42. if sys.stdout.isatty():
  43. header += [('VMNAME:DEVID', 'DESCRIPTION', 'USED BY', 'ASSIGNED')] # NOQA
  44. for dev in dev_list:
  45. output += [(
  46. dev.id,
  47. dev.description,
  48. str(dev.attached_to),
  49. dev.assignments
  50. )]
  51. return header + sorted(output)
  52. class Line(object):
  53. def __init__(self, device: qubes.devices.DeviceInfo, attached_to = None):
  54. self.id = "{!s}:{!s}".format(device.backend_domain, device.ident)
  55. self.description = device.description
  56. self.attached_to = attached_to if attached_to else ""
  57. self.frontends = []
  58. @property
  59. def assignments(self):
  60. return ', '.join(self.frontends)
  61. def list_devices(args):
  62. ''' Called by the parser to execute the qubes-devices list
  63. subcommand. '''
  64. app = args.app
  65. result = []
  66. devices = set()
  67. if hasattr(args, 'domains') and args.domains:
  68. for domain in args.domains:
  69. for dev in domain.devices[args.devclass].attached():
  70. devices.add(dev)
  71. for dev in domain.devices[args.devclass].available():
  72. devices.add(dev)
  73. else:
  74. for domain in app.domains:
  75. for dev in domain.devices[args.devclass].available():
  76. devices.add(dev)
  77. result = {dev: Line(dev) for dev in devices}
  78. for dev in result:
  79. for domain in app.domains:
  80. if domain == dev.backend_domain:
  81. continue
  82. elif dev in domain.devices[args.devclass].attached():
  83. result[dev].attached_to = str(domain)
  84. if dev in domain.devices[args.devclass].assignments():
  85. if dev in domain.devices[args.devclass].persistent():
  86. result[dev].frontends.append(str(domain))
  87. qubes.tools.print_table(prepare_table(result.values()))
  88. def attach_device(args):
  89. ''' Called by the parser to execute the :program:`qvm-devices attach`
  90. subcommand.
  91. '''
  92. device_assignment = args.device_assignment
  93. vm = args.domains[0]
  94. app = args.app
  95. device_assignment.persistent = args.persistent
  96. vm.devices[args.devclass].attach(device_assignment)
  97. if device_assignment.persistent:
  98. app.save()
  99. def detach_device(args):
  100. ''' Called by the parser to execute the :program:`qvm-devices detach`
  101. subcommand.
  102. '''
  103. device_assignment = args.device_assignment
  104. vm = args.domains[0]
  105. before = len(vm.devices[args.devclass].persistent())
  106. vm.devices[args.devclass].detach(device_assignment)
  107. after = len(vm.devices[args.devclass].persistent())
  108. if after < before:
  109. args.app.save()
  110. def init_list_parser(sub_parsers):
  111. ''' Configures the parser for the :program:`qvm-devices list` subcommand '''
  112. # pylint: disable=protected-access
  113. list_parser = sub_parsers.add_parser('list', aliases=('ls', 'l'),
  114. help='list devices')
  115. vm_name_group = qubes.tools.VmNameGroup(
  116. list_parser, required=False, vm_action=qubes.tools.VmNameAction,
  117. help='list devices assigned to specific domain(s)')
  118. list_parser._mutually_exclusive_groups.append(vm_name_group)
  119. list_parser.set_defaults(func=list_devices)
  120. class DeviceAction(qubes.tools.QubesAction):
  121. ''' Action for argument parser that gets the
  122. :py:class:``qubes.device.DeviceInfo`` from a BACKEND:DEVICE_ID string.
  123. ''' # pylint: disable=too-few-public-methods
  124. def __init__(self, help='A pool & volume id combination',
  125. required=True, **kwargs):
  126. # pylint: disable=redefined-builtin
  127. super(DeviceAction, self).__init__(help=help, required=required,
  128. **kwargs)
  129. def __call__(self, parser, namespace, values, option_string=None):
  130. ''' Set ``namespace.vmname`` to ``values`` '''
  131. setattr(namespace, self.dest, values)
  132. def parse_qubes_app(self, parser, namespace):
  133. assert hasattr(namespace, 'app')
  134. app = namespace.app
  135. assert hasattr(namespace, 'device')
  136. backend_device_id = getattr(namespace, self.dest)
  137. assert hasattr(namespace, 'devclass')
  138. devclass = namespace.devclass
  139. try:
  140. vmname, device_id = backend_device_id.split(':', 1)
  141. try:
  142. vm = app.domains[vmname]
  143. except KeyError:
  144. parser.error_runtime("no backend vm {!r}".format(vmname))
  145. try:
  146. vm.devices[devclass][device_id]
  147. except KeyError:
  148. parser.error_runtime(
  149. "backend vm {!r} doesn't expose device {!r}"
  150. .format(vmname, device_id))
  151. device_assignment = qubes.devices.DeviceAssignment(vm, device_id,)
  152. setattr(namespace, 'device_assignment', device_assignment)
  153. except ValueError:
  154. parser.error('expected a backend vm & device id combination ' \
  155. 'like foo:bar got %s' % backend_device_id)
  156. def get_parser(device_class=None):
  157. '''Create :py:class:`argparse.ArgumentParser` suitable for
  158. :program:`qvm-block`.
  159. '''
  160. parser = qubes.tools.QubesArgumentParser(description=__doc__, want_app=True)
  161. parser.register('action', 'parsers', qubes.tools.AliasedSubParsersAction)
  162. if device_class:
  163. parser.add_argument('devclass', const=device_class,
  164. action='store_const',
  165. help=argparse.SUPPRESS)
  166. else:
  167. parser.add_argument('devclass', metavar='DEVICE_CLASS', action='store',
  168. help="Device class to manage ('pci', 'usb', etc)")
  169. sub_parsers = parser.add_subparsers(
  170. title='commands',
  171. description="For more information see qvm-device command -h",
  172. dest='command')
  173. init_list_parser(sub_parsers)
  174. attach_parser = sub_parsers.add_parser(
  175. 'attach', help="Attach device to domain", aliases=('at', 'a'))
  176. detach_parser = sub_parsers.add_parser(
  177. "detach", help="Detach device from domain", aliases=('d', 'dt'))
  178. attach_parser.add_argument('VMNAME', action=qubes.tools.VmNameAction)
  179. detach_parser.add_argument('VMNAME', action=qubes.tools.VmNameAction)
  180. if device_class == 'block':
  181. attach_parser.add_argument(metavar='BACKEND:DEVICE_ID', dest='device',
  182. action=qubes.tools.VolumeAction)
  183. detach_parser.add_argument(metavar='BACKEND:DEVICE_ID', dest='device',
  184. action=qubes.tools.VolumeAction)
  185. else:
  186. attach_parser.add_argument(metavar='BACKEND:DEVICE_ID',
  187. dest='device',
  188. action=DeviceAction)
  189. attach_parser.add_argument('-p', '--persistent', default=False,
  190. help='device will attached on each start of the VMNAME',
  191. action='store_true')
  192. detach_parser.add_argument(metavar='BACKEND:DEVICE_ID',
  193. dest='device',
  194. action=DeviceAction)
  195. attach_parser.set_defaults(func=attach_device)
  196. detach_parser.set_defaults(func=detach_device)
  197. return parser
  198. def main(args=None):
  199. '''Main routine of :program:`qvm-block`.'''
  200. basename = os.path.basename(sys.argv[0])
  201. devclass = None
  202. if basename.startswith('qvm-') and basename != 'qvm-device':
  203. devclass = basename[4:]
  204. args = get_parser(devclass).parse_args(args)
  205. try:
  206. args.func(args)
  207. except qubes.exc.QubesException as e:
  208. print(str(e), file=sys.stderr)
  209. return 1
  210. return 0
  211. if __name__ == '__main__':
  212. sys.exit(main())