selectors.py 19 KB

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