selectors.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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, Mapping
  7. import math
  8. import select
  9. import sys
  10. # generic events, that must be mapped to implementation-specific ones
  11. EVENT_READ = (1 << 0)
  12. EVENT_WRITE = (1 << 1)
  13. def _fileobj_to_fd(fileobj):
  14. """Return a file descriptor from a file object.
  15. Parameters:
  16. fileobj -- file object or file descriptor
  17. Returns:
  18. corresponding file descriptor
  19. Raises:
  20. ValueError if the object is invalid
  21. """
  22. if isinstance(fileobj, int):
  23. fd = fileobj
  24. else:
  25. try:
  26. fd = int(fileobj.fileno())
  27. except (AttributeError, TypeError, ValueError):
  28. raise ValueError("Invalid file object: "
  29. "{!r}".format(fileobj)) from None
  30. if fd < 0:
  31. raise ValueError("Invalid file descriptor: {}".format(fd))
  32. return fd
  33. SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data'])
  34. SelectorKey.__doc__ = """SelectorKey(fileobj, fd, events, data)
  35. Object used to associate a file object to its backing
  36. file descriptor, selected event mask, and attached data.
  37. """
  38. if sys.version_info >= (3, 5):
  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. # TODO: Subclasses can probably optimize this even further.
  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. if hasattr(select, 'poll'):
  268. class PollSelector(_BaseSelectorImpl):
  269. """Poll-based selector."""
  270. def __init__(self):
  271. super().__init__()
  272. self._poll = select.poll()
  273. def register(self, fileobj, events, data=None):
  274. key = super().register(fileobj, events, data)
  275. poll_events = 0
  276. if events & EVENT_READ:
  277. poll_events |= select.POLLIN
  278. if events & EVENT_WRITE:
  279. poll_events |= select.POLLOUT
  280. self._poll.register(key.fd, poll_events)
  281. return key
  282. def unregister(self, fileobj):
  283. key = super().unregister(fileobj)
  284. self._poll.unregister(key.fd)
  285. return key
  286. def select(self, timeout=None):
  287. if timeout is None:
  288. timeout = None
  289. elif timeout <= 0:
  290. timeout = 0
  291. else:
  292. # poll() has a resolution of 1 millisecond, round away from
  293. # zero to wait *at least* timeout seconds.
  294. timeout = math.ceil(timeout * 1e3)
  295. ready = []
  296. try:
  297. fd_event_list = self._poll.poll(timeout)
  298. except InterruptedError:
  299. return ready
  300. for fd, event in fd_event_list:
  301. events = 0
  302. if event & ~select.POLLIN:
  303. events |= EVENT_WRITE
  304. if event & ~select.POLLOUT:
  305. events |= EVENT_READ
  306. key = self._key_from_fd(fd)
  307. if key:
  308. ready.append((key, events & key.events))
  309. return ready
  310. if hasattr(select, 'epoll'):
  311. class EpollSelector(_BaseSelectorImpl):
  312. """Epoll-based selector."""
  313. def __init__(self):
  314. super().__init__()
  315. self._epoll = select.epoll()
  316. def fileno(self):
  317. return self._epoll.fileno()
  318. def register(self, fileobj, events, data=None):
  319. key = super().register(fileobj, events, data)
  320. epoll_events = 0
  321. if events & EVENT_READ:
  322. epoll_events |= select.EPOLLIN
  323. if events & EVENT_WRITE:
  324. epoll_events |= select.EPOLLOUT
  325. self._epoll.register(key.fd, epoll_events)
  326. return key
  327. def unregister(self, fileobj):
  328. key = super().unregister(fileobj)
  329. try:
  330. self._epoll.unregister(key.fd)
  331. except OSError:
  332. # This can happen if the FD was closed since it
  333. # was registered.
  334. pass
  335. return key
  336. def select(self, timeout=None):
  337. if timeout is None:
  338. timeout = -1
  339. elif timeout <= 0:
  340. timeout = 0
  341. else:
  342. # epoll_wait() has a resolution of 1 millisecond, round away
  343. # from zero to wait *at least* timeout seconds.
  344. timeout = math.ceil(timeout * 1e3) * 1e-3
  345. # epoll_wait() expects `maxevents` to be greater than zero;
  346. # we want to make sure that `select()` can be called when no
  347. # FD is registered.
  348. max_ev = max(len(self._fd_to_key), 1)
  349. ready = []
  350. try:
  351. fd_event_list = self._epoll.poll(timeout, max_ev)
  352. except InterruptedError:
  353. return ready
  354. for fd, event in fd_event_list:
  355. events = 0
  356. if event & ~select.EPOLLIN:
  357. events |= EVENT_WRITE
  358. if event & ~select.EPOLLOUT:
  359. events |= EVENT_READ
  360. key = self._key_from_fd(fd)
  361. if key:
  362. ready.append((key, events & key.events))
  363. return ready
  364. def close(self):
  365. self._epoll.close()
  366. super().close()
  367. if hasattr(select, 'devpoll'):
  368. class DevpollSelector(_BaseSelectorImpl):
  369. """Solaris /dev/poll selector."""
  370. def __init__(self):
  371. super().__init__()
  372. self._devpoll = select.devpoll()
  373. def fileno(self):
  374. return self._devpoll.fileno()
  375. def register(self, fileobj, events, data=None):
  376. key = super().register(fileobj, events, data)
  377. poll_events = 0
  378. if events & EVENT_READ:
  379. poll_events |= select.POLLIN
  380. if events & EVENT_WRITE:
  381. poll_events |= select.POLLOUT
  382. self._devpoll.register(key.fd, poll_events)
  383. return key
  384. def unregister(self, fileobj):
  385. key = super().unregister(fileobj)
  386. self._devpoll.unregister(key.fd)
  387. return key
  388. def select(self, timeout=None):
  389. if timeout is None:
  390. timeout = None
  391. elif timeout <= 0:
  392. timeout = 0
  393. else:
  394. # devpoll() has a resolution of 1 millisecond, round away from
  395. # zero to wait *at least* timeout seconds.
  396. timeout = math.ceil(timeout * 1e3)
  397. ready = []
  398. try:
  399. fd_event_list = self._devpoll.poll(timeout)
  400. except InterruptedError:
  401. return ready
  402. for fd, event in fd_event_list:
  403. events = 0
  404. if event & ~select.POLLIN:
  405. events |= EVENT_WRITE
  406. if event & ~select.POLLOUT:
  407. events |= EVENT_READ
  408. key = self._key_from_fd(fd)
  409. if key:
  410. ready.append((key, events & key.events))
  411. return ready
  412. def close(self):
  413. self._devpoll.close()
  414. super().close()
  415. if hasattr(select, 'kqueue'):
  416. class KqueueSelector(_BaseSelectorImpl):
  417. """Kqueue-based selector."""
  418. def __init__(self):
  419. super().__init__()
  420. self._kqueue = select.kqueue()
  421. def fileno(self):
  422. return self._kqueue.fileno()
  423. def register(self, fileobj, events, data=None):
  424. key = super().register(fileobj, events, data)
  425. if events & EVENT_READ:
  426. kev = select.kevent(key.fd, select.KQ_FILTER_READ,
  427. select.KQ_EV_ADD)
  428. self._kqueue.control([kev], 0, 0)
  429. if events & EVENT_WRITE:
  430. kev = select.kevent(key.fd, select.KQ_FILTER_WRITE,
  431. select.KQ_EV_ADD)
  432. self._kqueue.control([kev], 0, 0)
  433. return key
  434. def unregister(self, fileobj):
  435. key = super().unregister(fileobj)
  436. if key.events & EVENT_READ:
  437. kev = select.kevent(key.fd, select.KQ_FILTER_READ,
  438. select.KQ_EV_DELETE)
  439. try:
  440. self._kqueue.control([kev], 0, 0)
  441. except OSError:
  442. # This can happen if the FD was closed since it
  443. # was registered.
  444. pass
  445. if key.events & EVENT_WRITE:
  446. kev = select.kevent(key.fd, select.KQ_FILTER_WRITE,
  447. select.KQ_EV_DELETE)
  448. try:
  449. self._kqueue.control([kev], 0, 0)
  450. except OSError:
  451. # See comment above.
  452. pass
  453. return key
  454. def select(self, timeout=None):
  455. timeout = None if timeout is None else max(timeout, 0)
  456. max_ev = len(self._fd_to_key)
  457. ready = []
  458. try:
  459. kev_list = self._kqueue.control(None, max_ev, timeout)
  460. except InterruptedError:
  461. return ready
  462. for kev in kev_list:
  463. fd = kev.ident
  464. flag = kev.filter
  465. events = 0
  466. if flag == select.KQ_FILTER_READ:
  467. events |= EVENT_READ
  468. if flag == select.KQ_FILTER_WRITE:
  469. events |= EVENT_WRITE
  470. key = self._key_from_fd(fd)
  471. if key:
  472. ready.append((key, events & key.events))
  473. return ready
  474. def close(self):
  475. self._kqueue.close()
  476. super().close()
  477. # Choose the best implementation, roughly:
  478. # epoll|kqueue|devpoll > poll > select.
  479. # select() also can't accept a FD > FD_SETSIZE (usually around 1024)
  480. if 'KqueueSelector' in globals():
  481. DefaultSelector = KqueueSelector
  482. elif 'EpollSelector' in globals():
  483. DefaultSelector = EpollSelector
  484. elif 'DevpollSelector' in globals():
  485. DefaultSelector = DevpollSelector
  486. elif 'PollSelector' in globals():
  487. DefaultSelector = PollSelector
  488. else:
  489. DefaultSelector = SelectSelector