devices.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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,
  33. persistent=False, frontend_domain=None, devclass=None):
  34. self.backend_domain = backend_domain
  35. self.ident = ident
  36. self.devclass = devclass
  37. self.options = options or {}
  38. self.persistent = persistent
  39. self.frontend_domain = frontend_domain
  40. def __repr__(self):
  41. return "[%s]:%s" % (self.backend_domain, self.ident)
  42. def __hash__(self):
  43. return hash((self.backend_domain, self.ident))
  44. def __eq__(self, other):
  45. if not isinstance(self, other.__class__):
  46. return NotImplemented
  47. return self.backend_domain == other.backend_domain \
  48. and self.ident == other.ident
  49. def clone(self):
  50. '''Clone object instance'''
  51. return self.__class__(
  52. self.backend_domain,
  53. self.ident,
  54. self.options,
  55. self.persistent,
  56. self.frontend_domain,
  57. self.devclass,
  58. )
  59. @property
  60. def device(self):
  61. '''Get DeviceInfo object corresponding to this DeviceAssignment'''
  62. return self.backend_domain.devices[self.devclass][self.ident]
  63. class DeviceInfo(object):
  64. ''' Holds all information about a device '''
  65. # pylint: disable=too-few-public-methods
  66. def __init__(self, backend_domain, ident, description=None,
  67. options=None, **kwargs):
  68. #: domain providing this device
  69. self.backend_domain = backend_domain
  70. #: device identifier (unique for given domain and device type)
  71. self.ident = ident
  72. #: human readable description/name of the device
  73. self.description = description
  74. self.options = options or dict()
  75. self.data = kwargs
  76. def __hash__(self):
  77. return hash((str(self.backend_domain), self.ident))
  78. def __eq__(self, other):
  79. return (
  80. self.backend_domain == other.backend_domain and
  81. self.ident == other.ident
  82. )
  83. def __str__(self):
  84. return '{!s}:{!s}'.format(self.backend_domain, self.ident)
  85. class UnknownDevice(DeviceInfo):
  86. # pylint: disable=too-few-public-methods
  87. '''Unknown device - for example exposed by domain not running currently'''
  88. def __init__(self, backend_domain, ident, description=None,
  89. **kwargs):
  90. if description is None:
  91. description = "Unknown device"
  92. super(UnknownDevice, self).__init__(backend_domain, ident, description,
  93. **kwargs)
  94. class DeviceCollection(object):
  95. '''Bag for devices.
  96. Used as default value for :py:meth:`DeviceManager.__missing__` factory.
  97. :param vm: VM for which we manage devices
  98. :param class_: device class
  99. '''
  100. def __init__(self, vm, class_):
  101. self._vm = vm
  102. self._class = class_
  103. self._dev_cache = {}
  104. def attach(self, device_assignment):
  105. '''Attach (add) device to domain.
  106. :param DeviceAssignment device_assignment: device object
  107. '''
  108. if not device_assignment.frontend_domain:
  109. device_assignment.frontend_domain = self._vm
  110. else:
  111. assert device_assignment.frontend_domain == self._vm, \
  112. "Trying to attach DeviceAssignment belonging to other domain"
  113. if device_assignment.devclass is None:
  114. device_assignment.devclass = self._class
  115. else:
  116. assert device_assignment.devclass == self._class
  117. options = device_assignment.options.copy()
  118. if device_assignment.persistent:
  119. options['persistent'] = 'True'
  120. options_str = ' '.join('{}={}'.format(opt,
  121. val) for opt, val in sorted(options.items()))
  122. self._vm.qubesd_call(None,
  123. 'admin.vm.device.{}.Attach'.format(self._class),
  124. '{!s}+{!s}'.format(device_assignment.backend_domain,
  125. device_assignment.ident),
  126. options_str.encode('utf-8'))
  127. def detach(self, device_assignment):
  128. '''Detach (remove) device from domain.
  129. :param DeviceAssignment device_assignment: device to detach
  130. (obtained from :py:meth:`assignments`)
  131. '''
  132. if not device_assignment.frontend_domain:
  133. device_assignment.frontend_domain = self._vm
  134. else:
  135. assert device_assignment.frontend_domain == self._vm, \
  136. "Trying to detach DeviceAssignment belonging to other domain"
  137. if device_assignment.devclass is None:
  138. device_assignment.devclass = self._class
  139. else:
  140. assert device_assignment.devclass == self._class
  141. self._vm.qubesd_call(None,
  142. 'admin.vm.device.{}.Detach'.format(self._class),
  143. '{!s}+{!s}'.format(device_assignment.backend_domain,
  144. device_assignment.ident))
  145. def assignments(self, persistent=None):
  146. '''List assignments for devices which are (or may be) attached to the
  147. vm.
  148. Devices may be attached persistently (so they are included in
  149. :file:`qubes.xml`) or not. Device can also be in :file:`qubes.xml`,
  150. but be temporarily detached.
  151. :param bool persistent: only include devices which are or are not
  152. attached persistently.
  153. '''
  154. assignments_str = self._vm.qubesd_call(None,
  155. 'admin.vm.device.{}.List'.format(self._class)).decode()
  156. for assignment_str in assignments_str.splitlines():
  157. device, _, options_all = assignment_str.partition(' ')
  158. backend_domain, ident = device.split('+', 1)
  159. options = dict(opt_single.split('=', 1)
  160. for opt_single in options_all.split(' ') if opt_single)
  161. dev_persistent = (options.pop('persistent', False) in
  162. ['True', 'yes', True])
  163. if persistent is not None and dev_persistent != persistent:
  164. continue
  165. backend_domain = self._vm.app.domains[backend_domain]
  166. yield DeviceAssignment(backend_domain, ident, options,
  167. persistent=dev_persistent, frontend_domain=self._vm,
  168. devclass=self._class)
  169. def attached(self):
  170. '''List devices which are (or may be) attached to this vm '''
  171. for assignment in self.assignments():
  172. yield assignment.device
  173. def persistent(self):
  174. ''' Devices persistently attached and safe to access before libvirt
  175. bootstrap.
  176. '''
  177. for assignment in self.assignments(True):
  178. yield assignment.device
  179. def available(self):
  180. '''List devices exposed by this vm'''
  181. devices_str = self._vm.qubesd_call(None,
  182. 'admin.vm.device.{}.Available'.format(self._class)).decode()
  183. for dev_str in devices_str.splitlines():
  184. ident, _, info = dev_str.partition(' ')
  185. # description is special that it can contain spaces
  186. info, _, description = info.partition('description=')
  187. info_dict = dict(info_single.split('=', 1)
  188. for info_single in info.split(' ') if info_single)
  189. yield DeviceInfo(self._vm, ident, description=description,
  190. options=None, **info_dict)
  191. def update_persistent(self, device, persistent):
  192. '''Update `persistent` flag of already attached device.
  193. :param DeviceInfo device: device for which change persistent flag
  194. :param bool persistent: new persistent flag
  195. '''
  196. self._vm.qubesd_call(None,
  197. 'admin.vm.device.{}.Set.persistent'.format(self._class),
  198. '{!s}+{!s}'.format(device.backend_domain,
  199. device.ident),
  200. str(persistent).encode('utf-8'))
  201. __iter__ = available
  202. def clear_cache(self):
  203. '''Clear cache of available devices'''
  204. self._dev_cache.clear()
  205. def __getitem__(self, item):
  206. '''Get device object with given ident.
  207. :returns: py:class:`DeviceInfo`
  208. If domain isn't running, it is impossible to check device validity,
  209. so return UnknownDevice object. Also do the same for non-existing
  210. devices - otherwise it will be impossible to detach already
  211. disconnected device.
  212. '''
  213. # fist, check if we have cached device info
  214. if item in self._dev_cache:
  215. return self._dev_cache[item]
  216. # then look for available devices
  217. for dev in self.available():
  218. if dev.ident == item:
  219. self._dev_cache[item] = dev
  220. return dev
  221. # if still nothing, return UnknownDevice instance for the reason
  222. # explained in docstring, but don't cache it
  223. return UnknownDevice(self._vm, item)
  224. class DeviceManager(dict):
  225. '''Device manager that hold all devices by their classess.
  226. :param vm: VM for which we manage devices
  227. '''
  228. def __init__(self, vm):
  229. super(DeviceManager, self).__init__()
  230. self._vm = vm
  231. def __missing__(self, key):
  232. self[key] = DeviceCollection(self._vm, key)
  233. return self[key]