selectors.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. """Selectors module.
  2. This module allows high-level and efficient I/O multiplexing, built upon the
  3. `select` module primitives.
  4. """
  5. from abc import ABCMeta, abstractmethod
  6. from collections import namedtuple
  7. from collections.abc import Mapping
  8. import math
  9. import select
  10. import sys
  11. # generic events, that must be mapped to implementation-specific ones
  12. EVENT_READ = (1 << 0)
  13. EVENT_WRITE = (1 << 1)
  14. def _fileobj_to_fd(fileobj):
  15. """Return a file descriptor from a file object.
  16. Parameters:
  17. fileobj -- file object or file descriptor
  18. Returns:
  19. corresponding file descriptor
  20. Raises:
  21. ValueError if the object is invalid
  22. """
  23. if isinstance(fileobj, int):
  24. fd = fileobj
  25. else:
  26. try:
  27. fd = int(fileobj.fileno())
  28. except (AttributeError, TypeError, ValueError):
  29. raise ValueError("Invalid file object: "
  30. "{!r}".format(fileobj)) from None
  31. if fd < 0:
  32. raise ValueError("Invalid file descriptor: {}".format(fd))
  33. return fd
  34. SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data'])
  35. SelectorKey.__doc__ = """SelectorKey(fileobj, fd, events, data)
  36. Object used to associate a file object to its backing
  37. file descriptor, selected event mask, and attached data.
  38. """
  39. SelectorKey.fileobj.__doc__ = 'File object registered.'
  40. SelectorKey.fd.__doc__ = 'Underlying file descriptor.'
  41. SelectorKey.events.__doc__ = 'Events that must be waited for on this file object.'
  42. SelectorKey.data.__doc__ = ('''Optional opaque data associated to this file object.
  43. For example, this could be used to store a per-client session ID.''')
  44. class _SelectorMapping(Mapping):
  45. """Mapping of file objects to selector keys."""
  46. def __init__(self, selector):
  47. self._selector = selector
  48. def __len__(self):
  49. return len(self._selector._fd_to_key)
  50. def __getitem__(self, fileobj):
  51. try:
  52. fd = self._selector._fileobj_lookup(fileobj)
  53. return self._selector._fd_to_key[fd]
  54. except KeyError:
  55. raise KeyError("{!r} is not registered".format(fileobj)) from None
  56. def __iter__(self):
  57. return iter(self._selector._fd_to_key)
  58. class BaseSelector(metaclass=ABCMeta):
  59. """Selector abstract base class.
  60. A selector supports registering file objects to be monitored for specific
  61. I/O events.
  62. A file object is a file descriptor or any object with a `fileno()` method.
  63. An arbitrary object can be attached to the file object, which can be used
  64. for example to store context information, a callback, etc.
  65. A selector can use various implementations (select(), poll(), epoll()...)
  66. depending on the platform. The default `Selector` class uses the most
  67. efficient implementation on the current platform.
  68. """
  69. @abstractmethod
  70. def register(self, fileobj, events, data=None):
  71. """Register a file object.
  72. Parameters:
  73. fileobj -- file object or file descriptor
  74. events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE)
  75. data -- attached data
  76. Returns:
  77. SelectorKey instance
  78. Raises:
  79. ValueError if events is invalid
  80. KeyError if fileobj is already registered
  81. OSError if fileobj is closed or otherwise is unacceptable to
  82. the underlying system call (if a system call is made)
  83. Note:
  84. OSError may or may not be raised
  85. """
  86. raise NotImplementedError
  87. @abstractmethod
  88. def unregister(self, fileobj):
  89. """Unregister a file object.
  90. Parameters:
  91. fileobj -- file object or file descriptor
  92. Returns:
  93. SelectorKey instance
  94. Raises:
  95. KeyError if fileobj is not registered
  96. Note:
  97. If fileobj is registered but has since been closed this does
  98. *not* raise OSError (even if the wrapped syscall does)
  99. """
  100. raise NotImplementedError
  101. def modify(self, fileobj, events, data=None):
  102. """Change a registered file object monitored events or attached data.
  103. Parameters:
  104. fileobj -- file object or file descriptor
  105. events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE)
  106. data -- attached data
  107. Returns:
  108. SelectorKey instance
  109. Raises:
  110. Anything that unregister() or register() raises
  111. """
  112. self.unregister(fileobj)
  113. return self.register(fileobj, events, data)
  114. @abstractmethod
  115. def select(self, timeout=None):
  116. """Perform the actual selection, until some monitored file objects are
  117. ready or a timeout expires.
  118. Parameters:
  119. timeout -- if timeout > 0, this specifies the maximum wait time, in
  120. seconds
  121. if timeout <= 0, the select() call won't block, and will
  122. report the currently ready file objects
  123. if timeout is None, select() will block until a monitored
  124. file object becomes ready
  125. Returns:
  126. list of (key, events) for ready file objects
  127. `events` is a bitwise mask of EVENT_READ|EVENT_WRITE
  128. """
  129. raise NotImplementedError
  130. def close(self):
  131. """Close the selector.
  132. This must be called to make sure that any underlying resource is freed.
  133. """
  134. pass
  135. def get_key(self, fileobj):
  136. """Return the key associated to a registered file object.
  137. Returns:
  138. SelectorKey for this file object
  139. """
  140. mapping = self.get_map()
  141. if mapping is None:
  142. raise RuntimeError('Selector is closed')
  143. try:
  144. return mapping[fileobj]
  145. except KeyError:
  146. raise KeyError("{!r} is not registered".format(fileobj)) from None
  147. @abstractmethod
  148. def get_map(self):
  149. """Return a mapping of file objects to selector keys."""
  150. raise NotImplementedError
  151. def __enter__(self):
  152. return self
  153. def __exit__(self, *args):
  154. self.close()
  155. class _BaseSelectorImpl(BaseSelector):
  156. """Base selector implementation."""
  157. def __init__(self):
  158. # this maps file descriptors to keys
  159. self._fd_to_key = {}
  160. # read-only mapping returned by get_map()
  161. self._map = _SelectorMapping(self)
  162. def _fileobj_lookup(self, fileobj):
  163. """Return a file descriptor from a file object.
  164. This wraps _fileobj_to_fd() to do an exhaustive search in case
  165. the object is invalid but we still have it in our map. This
  166. is used by unregister() so we can unregister an object that
  167. was previously registered even if it is closed. It is also
  168. used by _SelectorMapping.
  169. """
  170. try:
  171. return _fileobj_to_fd(fileobj)
  172. except ValueError:
  173. # Do an exhaustive search.
  174. for key in self._fd_to_key.values():
  175. if key.fileobj is fileobj:
  176. return key.fd
  177. # Raise ValueError after all.
  178. raise
  179. def register(self, fileobj, events, data=None):
  180. if (not events) or (events & ~(EVENT_READ | EVENT_WRITE)):
  181. raise ValueError("Invalid events: {!r}".format(events))
  182. key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)
  183. if key.fd in self._fd_to_key:
  184. raise KeyError("{!r} (FD {}) is already registered"
  185. .format(fileobj, key.fd))
  186. self._fd_to_key[key.fd] = key
  187. return key
  188. def unregister(self, fileobj):
  189. try:
  190. key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))
  191. except KeyError:
  192. raise KeyError("{!r} is not registered".format(fileobj)) from None
  193. return key
  194. def modify(self, fileobj, events, data=None):
  195. try:
  196. key = self._fd_to_key[self._fileobj_lookup(fileobj)]
  197. except KeyError:
  198. raise KeyError("{!r} is not registered".format(fileobj)) from None
  199. if events != key.events:
  200. self.unregister(fileobj)
  201. key = self.register(fileobj, events, data)
  202. elif data != key.data:
  203. # Use a shortcut to update the data.
  204. key = key._replace(data=data)
  205. self._fd_to_key[key.fd] = key
  206. return key
  207. def close(self):
  208. self._fd_to_key.clear()
  209. self._map = None
  210. def get_map(self):
  211. return self._map
  212. def _key_from_fd(self, fd):
  213. """Return the key associated to a given file descriptor.
  214. Parameters:
  215. fd -- file descriptor
  216. Returns:
  217. corresponding key, or None if not found
  218. """
  219. try:
  220. return self._fd_to_key[fd]
  221. except KeyError:
  222. return None
  223. class SelectSelector(_BaseSelectorImpl):
  224. """Select-based selector."""
  225. def __init__(self):
  226. super().__init__()
  227. self._readers = set()
  228. self._writers = set()
  229. def register(self, fileobj, events, data=None):
  230. key = super().register(fileobj, events, data)
  231. if events & EVENT_READ:
  232. self._readers.add(key.fd)
  233. if events & EVENT_WRITE:
  234. self._writers.add(key.fd)
  235. return key
  236. def unregister(self, fileobj):
  237. key = super().unregister(fileobj)
  238. self._readers.discard(key.fd)
  239. self._writers.discard(key.fd)
  240. return key
  241. if sys.platform == 'win32':
  242. def _select(self, r, w, _, timeout=None):
  243. r, w, x = select.select(r, w, w, timeout)
  244. return r, w + x, []
  245. else:
  246. _select = select.select
  247. def select(self, timeout=None):
  248. timeout = None if timeout is None else max(timeout, 0)
  249. ready = []
  250. try:
  251. r, w, _ = self._select(self._readers, self._writers, [], timeout)
  252. except InterruptedError:
  253. return ready
  254. r = set(r)
  255. w = set(w)
  256. for fd in r | w:
  257. events = 0
  258. if fd in r:
  259. events |= EVENT_READ
  260. if fd in w:
  261. events |= EVENT_WRITE
  262. key = self._key_from_fd(fd)
  263. if key:
  264. ready.append((key, events & key.events))
  265. return ready
  266. class _PollLikeSelector(_BaseSelectorImpl):
  267. """Base class shared between poll, epoll and devpoll selectors."""
  268. _selector_cls = None
  269. _EVENT_READ = None
  270. _EVENT_WRITE = None
  271. def __init__(self):
  272. super().__init__()
  273. self._selector = self._selector_cls()
  274. def register(self, fileobj, events, data=None):
  275. key = super().register(fileobj, events, data)
  276. poller_events = 0
  277. if events & EVENT_READ:
  278. poller_events |= self._EVENT_READ
  279. if events & EVENT_WRITE:
  280. poller_events |= self._EVENT_WRITE
  281. try:
  282. self._selector.register(key.fd, poller_events)
  283. except:
  284. super().unregister(fileobj)
  285. raise
  286. return key
  287. def unregister(self, fileobj):
  288. key = super().unregister(fileobj)
  289. try:
  290. self._selector.unregister(key.fd)
  291. except OSError:
  292. # This can happen if the FD was closed since it
  293. # was registered.
  294. pass
  295. return key
  296. def modify(self, fileobj, events, data=None):
  297. try:
  298. key = self._fd_to_key[self._fileobj_lookup(fileobj)]
  299. except KeyError:
  300. raise KeyError(f"{fileobj!r} is not registered") from None
  301. changed = False
  302. if events != key.events:
  303. selector_events = 0
  304. if events & EVENT_READ:
  305. selector_events |= self._EVENT_READ
  306. if events & EVENT_WRITE:
  307. selector_events |= self._EVENT_WRITE
  308. try:
  309. self._selector.modify(key.fd, selector_events)
  310. except:
  311. super().unregister(fileobj)
  312. raise
  313. changed = True
  314. if data != key.data:
  315. changed = True
  316. if changed:
  317. key = key._replace(events=events, data=data)
  318. self._fd_to_key[key.fd] = key
  319. return key
  320. def select(self, timeout=None):
  321. # This is shared between poll() and epoll().
  322. # epoll() has a different signature and handling of timeout parameter.
  323. if timeout is None:
  324. timeout = None
  325. elif timeout <= 0:
  326. timeout = 0
  327. else:
  328. # poll() has a resolution of 1 millisecond, round away from
  329. # zero to wait *at least* timeout seconds.
  330. timeout = math.ceil(timeout * 1e3)
  331. ready = []
  332. try:
  333. fd_event_list = self._selector.poll(timeout)
  334. except InterruptedError:
  335. return ready
  336. for fd, event in fd_event_list:
  337. events = 0
  338. if event & ~self._EVENT_READ:
  339. events |= EVENT_WRITE
  340. if event & ~self._EVENT_WRITE:
  341. events |= EVENT_READ
  342. key = self._key_from_fd(fd)
  343. if key:
  344. ready.append((key, events & key.events))
  345. return ready
  346. if hasattr(select, 'poll'):
  347. class PollSelector(_PollLikeSelector):
  348. """Poll-based selector."""
  349. _selector_cls = select.poll
  350. _EVENT_READ = select.POLLIN
  351. _EVENT_WRITE = select.POLLOUT
  352. if hasattr(select, 'epoll'):
  353. class EpollSelector(_PollLikeSelector):
  354. """Epoll-based selector."""
  355. _selector_cls = select.epoll
  356. _EVENT_READ = select.EPOLLIN
  357. _EVENT_WRITE = select.EPOLLOUT
  358. def fileno(self):
  359. return self._selector.fileno()
  360. def select(self, timeout=None):
  361. if timeout is None:
  362. timeout = -1
  363. elif timeout <= 0:
  364. timeout = 0
  365. else:
  366. # epoll_wait() has a resolution of 1 millisecond, round away
  367. # from zero to wait *at least* timeout seconds.
  368. timeout = math.ceil(timeout * 1e3) * 1e-3
  369. # epoll_wait() expects `maxevents` to be greater than zero;
  370. # we want to make sure that `select()` can be called when no
  371. # FD is registered.
  372. max_ev = max(len(self._fd_to_key), 1)
  373. ready = []
  374. try:
  375. fd_event_list = self._selector.poll(timeout, max_ev)
  376. except InterruptedError:
  377. return ready
  378. for fd, event in fd_event_list:
  379. events = 0
  380. if event & ~select.EPOLLIN:
  381. events |= EVENT_WRITE
  382. if event & ~select.EPOLLOUT:
  383. events |= EVENT_READ
  384. key = self._key_from_fd(fd)
  385. if key:
  386. ready.append((key, events & key.events))
  387. return ready
  388. def close(self):
  389. self._selector.close()
  390. super().close()
  391. if hasattr(select, 'devpoll'):
  392. class DevpollSelector(_PollLikeSelector):
  393. """Solaris /dev/poll selector."""
  394. _selector_cls = select.devpoll
  395. _EVENT_READ = select.POLLIN
  396. _EVENT_WRITE = select.POLLOUT
  397. def fileno(self):
  398. return self._selector.fileno()
  399. def close(self):
  400. self._selector.close()
  401. super().close()
  402. if hasattr(select, 'kqueue'):
  403. class KqueueSelector(_BaseSelectorImpl):
  404. """Kqueue-based selector."""
  405. def __init__(self):
  406. super().__init__()
  407. self._selector = select.kqueue()
  408. def fileno(self):
  409. return self._selector.fileno()
  410. def register(self, fileobj, events, data=None):
  411. key = super().register(fileobj, events, data)
  412. try:
  413. if events & EVENT_READ:
  414. kev = select.kevent(key.fd, select.KQ_FILTER_READ,
  415. select.KQ_EV_ADD)
  416. self._selector.control([kev], 0, 0)
  417. if events & EVENT_WRITE:
  418. kev = select.kevent(key.fd, select.KQ_FILTER_WRITE,
  419. select.KQ_EV_ADD)
  420. self._selector.control([kev], 0, 0)
  421. except:
  422. super().unregister(fileobj)
  423. raise
  424. return key
  425. def unregister(self, fileobj):
  426. key = super().unregister(fileobj)
  427. if key.events & EVENT_READ:
  428. kev = select.kevent(key.fd, select.KQ_FILTER_READ,
  429. select.KQ_EV_DELETE)
  430. try:
  431. self._selector.control([kev], 0, 0)
  432. except OSError:
  433. # This can happen if the FD was closed since it
  434. # was registered.
  435. pass
  436. if key.events & EVENT_WRITE:
  437. kev = select.kevent(key.fd, select.KQ_FILTER_WRITE,
  438. select.KQ_EV_DELETE)
  439. try:
  440. self._selector.control([kev], 0, 0)
  441. except OSError:
  442. # See comment above.
  443. pass
  444. return key
  445. def select(self, timeout=None):
  446. timeout = None if timeout is None else max(timeout, 0)
  447. # If max_ev is 0, kqueue will ignore the timeout. For consistent
  448. # behavior with the other selector classes, we prevent that here
  449. # (using max). See https://bugs.python.org/issue29255
  450. max_ev = max(len(self._fd_to_key), 1)
  451. ready = []
  452. try:
  453. kev_list = self._selector.control(None, max_ev, timeout)
  454. except InterruptedError:
  455. return ready
  456. for kev in kev_list:
  457. fd = kev.ident
  458. flag = kev.filter
  459. events = 0
  460. if flag == select.KQ_FILTER_READ:
  461. events |= EVENT_READ
  462. if flag == select.KQ_FILTER_WRITE:
  463. events |= EVENT_WRITE
  464. key = self._key_from_fd(fd)
  465. if key:
  466. ready.append((key, events & key.events))
  467. return ready
  468. def close(self):
  469. self._selector.close()
  470. super().close()
  471. def _can_use(method):
  472. """Check if we can use the selector depending upon the
  473. operating system. """
  474. # Implementation based upon https://github.com/sethmlarson/selectors2/blob/master/selectors2.py
  475. selector = getattr(select, method, None)
  476. if selector is None:
  477. # select module does not implement method
  478. return False
  479. # check if the OS and Kernel actually support the method. Call may fail with
  480. # OSError: [Errno 38] Function not implemented
  481. try:
  482. selector_obj = selector()
  483. if method == 'poll':
  484. # check that poll actually works
  485. selector_obj.poll(0)
  486. else:
  487. # close epoll, kqueue, and devpoll fd
  488. selector_obj.close()
  489. return True
  490. except OSError:
  491. return False
  492. # Choose the best implementation, roughly:
  493. # epoll|kqueue|devpoll > poll > select.
  494. # select() also can't accept a FD > FD_SETSIZE (usually around 1024)
  495. if _can_use('kqueue'):
  496. DefaultSelector = KqueueSelector
  497. elif _can_use('epoll'):
  498. DefaultSelector = EpollSelector
  499. elif _can_use('devpoll'):
  500. DefaultSelector = DevpollSelector
  501. elif _can_use('poll'):
  502. DefaultSelector = PollSelector
  503. else:
  504. DefaultSelector = SelectSelector