devices.py 10 KB

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