devices.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2015-2016 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  7. # Copyright (C) 2017 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU Lesser General Public License as published by
  12. # the Free Software Foundation; either version 2.1 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU Lesser General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU Lesser General Public License along
  21. # with this program; if not, see <http://www.gnu.org/licenses/>.
  22. '''API for various types of devices.
  23. Main concept is that some domain main
  24. expose (potentially multiple) devices, which can be attached to other domains.
  25. Devices can be of different classes (like 'pci', 'usb', etc). Each device
  26. class is implemented by an extension.
  27. Devices are identified by pair of (backend domain, `ident`), where `ident` is
  28. :py:class:`str`.
  29. '''
  30. class DeviceAssignment(object): # pylint: disable=too-few-public-methods
  31. ''' Maps a device to a frontend_domain. '''
  32. def __init__(self, backend_domain, ident, options=None, persistent=False,
  33. frontend_domain=None):
  34. self.backend_domain = backend_domain
  35. self.ident = ident
  36. self.options = options or {}
  37. self.persistent = persistent
  38. self.frontend_domain = frontend_domain
  39. def __repr__(self):
  40. return "[%s]:%s" % (self.backend_domain, self.ident)
  41. def __hash__(self):
  42. return hash((self.backend_domain, self.ident))
  43. def __eq__(self, other):
  44. if not isinstance(self, other.__class__):
  45. return NotImplemented
  46. return self.backend_domain == other.backend_domain \
  47. and self.ident == other.ident
  48. class DeviceInfo(object):
  49. ''' Holds all information about a device '''
  50. # pylint: disable=too-few-public-methods
  51. def __init__(self, backend_domain, ident, description=None,
  52. options=None, **kwargs):
  53. #: domain providing this device
  54. self.backend_domain = backend_domain
  55. #: device identifier (unique for given domain and device type)
  56. self.ident = ident
  57. #: human readable description/name of the device
  58. self.description = description
  59. self.options = options or dict()
  60. self.data = kwargs
  61. def __hash__(self):
  62. return hash((str(self.backend_domain), self.ident))
  63. def __eq__(self, other):
  64. return (
  65. self.backend_domain == other.backend_domain and
  66. self.ident == other.ident
  67. )
  68. def __str__(self):
  69. return '{!s}:{!s}'.format(self.backend_domain, self.ident)
  70. class UnknownDevice(DeviceInfo):
  71. # pylint: disable=too-few-public-methods
  72. '''Unknown device - for example exposed by domain not running currently'''
  73. def __init__(self, backend_domain, ident, description=None,
  74. **kwargs):
  75. if description is None:
  76. description = "Unknown device"
  77. super(UnknownDevice, self).__init__(backend_domain, ident, description,
  78. **kwargs)
  79. class DeviceCollection(object):
  80. '''Bag for devices.
  81. Used as default value for :py:meth:`DeviceManager.__missing__` factory.
  82. :param vm: VM for which we manage devices
  83. :param class_: device class
  84. '''
  85. def __init__(self, vm, class_):
  86. self._vm = vm
  87. self._class = class_
  88. self._dev_cache = {}
  89. def attach(self, device_assignment):
  90. '''Attach (add) device to domain.
  91. :param DeviceAssignment device_assignment: device object
  92. '''
  93. if not device_assignment.frontend_domain:
  94. device_assignment.frontend_domain = self._vm
  95. else:
  96. assert device_assignment.frontend_domain == self._vm, \
  97. "Trying to attach DeviceAssignment belonging to other domain"
  98. options = device_assignment.options.copy()
  99. if device_assignment.persistent:
  100. options['persistent'] = 'yes'
  101. options_str = ' '.join('{}={}'.format(opt,
  102. val) for opt, val in sorted(options.items()))
  103. self._vm.qubesd_call(None,
  104. 'mgmt.vm.device.{}.Attach'.format(self._class),
  105. '{!s}+{!s}'.format(device_assignment.backend_domain,
  106. device_assignment.ident),
  107. options_str.encode('utf-8'))
  108. def detach(self, device_assignment):
  109. '''Detach (remove) device from domain.
  110. :param DeviceAssignment device_assignment: device to detach
  111. (obtained from :py:meth:`assignments`)
  112. '''
  113. if not device_assignment.frontend_domain:
  114. device_assignment.frontend_domain = self._vm
  115. else:
  116. assert device_assignment.frontend_domain == self._vm, \
  117. "Trying to detach DeviceAssignment belonging to other domain"
  118. self._vm.qubesd_call(None,
  119. 'mgmt.vm.device.{}.Detach'.format(self._class),
  120. '{!s}+{!s}'.format(device_assignment.backend_domain,
  121. device_assignment.ident))
  122. def assignments(self, persistent=None):
  123. '''List assignments for devices which are (or may be) attached to the
  124. vm.
  125. Devices may be attached persistently (so they are included in
  126. :file:`qubes.xml`) or not. Device can also be in :file:`qubes.xml`,
  127. but be temporarily detached.
  128. :param bool persistent: only include devices which are or are not
  129. attached persistently.
  130. '''
  131. assignments_str = self._vm.qubesd_call(None,
  132. 'mgmt.vm.device.{}.List'.format(self._class)).decode()
  133. for assignment_str in assignments_str.splitlines():
  134. device, _, options_all = assignment_str.partition(' ')
  135. backend_domain, ident = device.split('+', 1)
  136. options = dict(opt_single.split('=', 1)
  137. for opt_single in options_all.split(' ') if opt_single)
  138. dev_persistent = (options.pop('persistent', False) in
  139. ['True', 'yes', True])
  140. if persistent is not None and dev_persistent != persistent:
  141. continue
  142. backend_domain = self._vm.app.domains[backend_domain]
  143. yield DeviceAssignment(backend_domain, ident, options,
  144. persistent=dev_persistent, frontend_domain=self._vm)
  145. def attached(self):
  146. '''List devices which are (or may be) attached to this vm '''
  147. for assignment in self.assignments():
  148. yield self._device(assignment)
  149. def persistent(self):
  150. ''' Devices persistently attached and safe to access before libvirt
  151. bootstrap.
  152. '''
  153. for assignment in self.assignments(True):
  154. yield self._device(assignment)
  155. def _device(self, assignment):
  156. ''' Helper method for geting a `qubes.devices.DeviceInfo` object from
  157. `qubes.devices.DeviceAssignment`. '''
  158. return assignment.backend_domain.devices[self._class][assignment.ident]
  159. def available(self):
  160. '''List devices exposed by this vm'''
  161. devices_str = self._vm.qubesd_call(None,
  162. 'mgmt.vm.device.{}.Available'.format(self._class)).decode()
  163. for dev_str in devices_str.splitlines():
  164. ident, _, info = dev_str.partition(' ')
  165. # description is special that it can contain spaces
  166. info, _, description = info.partition('description=')
  167. info_dict = dict(info_single.split('=', 1)
  168. for info_single in info.split(' ') if info_single)
  169. yield DeviceInfo(self._vm, ident, description=description,
  170. options=None, **info_dict)
  171. __iter__ = available
  172. def clear_cache(self):
  173. '''Clear cache of available devices'''
  174. self._dev_cache.clear()
  175. def __getitem__(self, item):
  176. '''Get device object with given ident.
  177. :returns: py:class:`DeviceInfo`
  178. If domain isn't running, it is impossible to check device validity,
  179. so return UnknownDevice object. Also do the same for non-existing
  180. devices - otherwise it will be impossible to detach already
  181. disconnected device.
  182. '''
  183. # fist, check if we have cached device info
  184. if item in self._dev_cache:
  185. return self._dev_cache[item]
  186. # then look for available devices
  187. for dev in self.available():
  188. if dev.ident == item:
  189. self._dev_cache[item] = dev
  190. return dev
  191. # if still nothing, return UnknownDevice instance for the reason
  192. # explained in docstring, but don't cache it
  193. return UnknownDevice(self._vm, item)
  194. class DeviceManager(dict):
  195. '''Device manager that hold all devices by their classess.
  196. :param vm: VM for which we manage devices
  197. '''
  198. def __init__(self, vm):
  199. super(DeviceManager, self).__init__()
  200. self._vm = vm
  201. def __missing__(self, key):
  202. self[key] = DeviceCollection(self._vm, key)
  203. return self[key]