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