blob: 0a2d981003c413f1d7845a2c9a03524d1cff1dae [file] [log] [blame]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001"""Selector and proactor eventloops for Windows."""
2
Victor Stinnerf2e17682014-01-31 16:25:24 +01003import _winapi
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07004import errno
Victor Stinnerf2e17682014-01-31 16:25:24 +01005import math
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07006import socket
Victor Stinnerf2e17682014-01-31 16:25:24 +01007import struct
Guido van Rossum59691282013-10-30 14:52:03 -07008import subprocess
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07009import weakref
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070010
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -080011from . import events
Guido van Rossum59691282013-10-30 14:52:03 -070012from . import base_subprocess
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070013from . import futures
14from . import proactor_events
15from . import selector_events
16from . import tasks
17from . import windows_utils
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070018from .log import logger
Guido van Rossum59691282013-10-30 14:52:03 -070019from . import _overlapped
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070020
21
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -080022__all__ = ['SelectorEventLoop', 'ProactorEventLoop', 'IocpProactor',
23 'DefaultEventLoopPolicy',
24 ]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070025
26
27NULL = 0
28INFINITE = 0xffffffff
29ERROR_CONNECTION_REFUSED = 1225
30ERROR_CONNECTION_ABORTED = 1236
31
32
33class _OverlappedFuture(futures.Future):
34 """Subclass of Future which represents an overlapped operation.
35
36 Cancelling it will immediately cancel the overlapped operation.
37 """
38
39 def __init__(self, ov, *, loop=None):
40 super().__init__(loop=loop)
41 self.ov = ov
42
43 def cancel(self):
44 try:
45 self.ov.cancel()
46 except OSError:
47 pass
48 return super().cancel()
49
50
Guido van Rossum90fb9142013-10-30 14:44:05 -070051class _WaitHandleFuture(futures.Future):
52 """Subclass of Future which represents a wait handle."""
53
54 def __init__(self, wait_handle, *, loop=None):
55 super().__init__(loop=loop)
56 self._wait_handle = wait_handle
57
58 def cancel(self):
59 super().cancel()
60 try:
61 _overlapped.UnregisterWait(self._wait_handle)
62 except OSError as e:
63 if e.winerror != _overlapped.ERROR_IO_PENDING:
64 raise
65
66
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070067class PipeServer(object):
68 """Class representing a pipe server.
69
70 This is much like a bound, listening socket.
71 """
72 def __init__(self, address):
73 self._address = address
74 self._free_instances = weakref.WeakSet()
75 self._pipe = self._server_pipe_handle(True)
76
77 def _get_unconnected_pipe(self):
78 # Create new instance and return previous one. This ensures
79 # that (until the server is closed) there is always at least
80 # one pipe handle for address. Therefore if a client attempt
81 # to connect it will not fail with FileNotFoundError.
82 tmp, self._pipe = self._pipe, self._server_pipe_handle(False)
83 return tmp
84
85 def _server_pipe_handle(self, first):
86 # Return a wrapper for a new pipe handle.
87 if self._address is None:
88 return None
89 flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
90 if first:
91 flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
92 h = _winapi.CreateNamedPipe(
93 self._address, flags,
94 _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
95 _winapi.PIPE_WAIT,
96 _winapi.PIPE_UNLIMITED_INSTANCES,
97 windows_utils.BUFSIZE, windows_utils.BUFSIZE,
98 _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
99 pipe = windows_utils.PipeHandle(h)
100 self._free_instances.add(pipe)
101 return pipe
102
103 def close(self):
104 # Close all instances which have not been connected to by a client.
105 if self._address is not None:
106 for pipe in self._free_instances:
107 pipe.close()
108 self._pipe = None
109 self._address = None
110 self._free_instances.clear()
111
112 __del__ = close
113
114
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800115class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700116 """Windows version of selector event loop."""
117
118 def _socketpair(self):
119 return windows_utils.socketpair()
120
121
122class ProactorEventLoop(proactor_events.BaseProactorEventLoop):
123 """Windows version of proactor event loop using IOCP."""
124
125 def __init__(self, proactor=None):
126 if proactor is None:
127 proactor = IocpProactor()
128 super().__init__(proactor)
129
130 def _socketpair(self):
131 return windows_utils.socketpair()
132
133 @tasks.coroutine
134 def create_pipe_connection(self, protocol_factory, address):
135 f = self._proactor.connect_pipe(address)
136 pipe = yield from f
137 protocol = protocol_factory()
138 trans = self._make_duplex_pipe_transport(pipe, protocol,
139 extra={'addr': address})
140 return trans, protocol
141
142 @tasks.coroutine
143 def start_serving_pipe(self, protocol_factory, address):
144 server = PipeServer(address)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700145
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700146 def loop(f=None):
147 pipe = None
148 try:
149 if f:
150 pipe = f.result()
151 server._free_instances.discard(pipe)
152 protocol = protocol_factory()
153 self._make_duplex_pipe_transport(
154 pipe, protocol, extra={'addr': address})
155 pipe = server._get_unconnected_pipe()
156 if pipe is None:
157 return
158 f = self._proactor.accept_pipe(pipe)
159 except OSError:
160 if pipe and pipe.fileno() != -1:
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700161 logger.exception('Pipe accept failed')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700162 pipe.close()
163 except futures.CancelledError:
164 if pipe:
165 pipe.close()
166 else:
167 f.add_done_callback(loop)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700168
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700169 self.call_soon(loop)
170 return [server]
171
Guido van Rossum59691282013-10-30 14:52:03 -0700172 @tasks.coroutine
173 def _make_subprocess_transport(self, protocol, args, shell,
174 stdin, stdout, stderr, bufsize,
175 extra=None, **kwargs):
176 transp = _WindowsSubprocessTransport(self, protocol, args, shell,
177 stdin, stdout, stderr, bufsize,
Victor Stinner73f10fd2014-01-29 14:32:20 -0800178 extra=extra, **kwargs)
Guido van Rossum59691282013-10-30 14:52:03 -0700179 yield from transp._post_init()
180 return transp
181
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700182
183class IocpProactor:
184 """Proactor implementation using IOCP."""
185
186 def __init__(self, concurrency=0xffffffff):
187 self._loop = None
188 self._results = []
189 self._iocp = _overlapped.CreateIoCompletionPort(
190 _overlapped.INVALID_HANDLE_VALUE, NULL, 0, concurrency)
191 self._cache = {}
192 self._registered = weakref.WeakSet()
193 self._stopped_serving = weakref.WeakSet()
194
195 def set_loop(self, loop):
196 self._loop = loop
197
198 def select(self, timeout=None):
199 if not self._results:
200 self._poll(timeout)
201 tmp = self._results
202 self._results = []
203 return tmp
204
205 def recv(self, conn, nbytes, flags=0):
206 self._register_with_iocp(conn)
207 ov = _overlapped.Overlapped(NULL)
208 if isinstance(conn, socket.socket):
209 ov.WSARecv(conn.fileno(), nbytes, flags)
210 else:
211 ov.ReadFile(conn.fileno(), nbytes)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700212
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213 def finish(trans, key, ov):
214 try:
215 return ov.getresult()
216 except OSError as exc:
217 if exc.winerror == _overlapped.ERROR_NETNAME_DELETED:
218 raise ConnectionResetError(*exc.args)
219 else:
220 raise
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700221
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700222 return self._register(ov, conn, finish)
223
224 def send(self, conn, buf, flags=0):
225 self._register_with_iocp(conn)
226 ov = _overlapped.Overlapped(NULL)
227 if isinstance(conn, socket.socket):
228 ov.WSASend(conn.fileno(), buf, flags)
229 else:
230 ov.WriteFile(conn.fileno(), buf)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700231
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700232 def finish(trans, key, ov):
233 try:
234 return ov.getresult()
235 except OSError as exc:
236 if exc.winerror == _overlapped.ERROR_NETNAME_DELETED:
237 raise ConnectionResetError(*exc.args)
238 else:
239 raise
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700240
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700241 return self._register(ov, conn, finish)
242
243 def accept(self, listener):
244 self._register_with_iocp(listener)
245 conn = self._get_accept_socket(listener.family)
246 ov = _overlapped.Overlapped(NULL)
247 ov.AcceptEx(listener.fileno(), conn.fileno())
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700248
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700249 def finish_accept(trans, key, ov):
250 ov.getresult()
251 # Use SO_UPDATE_ACCEPT_CONTEXT so getsockname() etc work.
252 buf = struct.pack('@P', listener.fileno())
253 conn.setsockopt(socket.SOL_SOCKET,
254 _overlapped.SO_UPDATE_ACCEPT_CONTEXT, buf)
255 conn.settimeout(listener.gettimeout())
256 return conn, conn.getpeername()
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700257
Victor Stinner7de26462014-01-11 00:03:21 +0100258 @tasks.coroutine
259 def accept_coro(future, conn):
260 # Coroutine closing the accept socket if the future is cancelled
261 try:
262 yield from future
263 except futures.CancelledError:
264 conn.close()
265 raise
266
267 future = self._register(ov, listener, finish_accept)
268 coro = accept_coro(future, conn)
269 tasks.async(coro, loop=self._loop)
270 return future
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700271
272 def connect(self, conn, address):
273 self._register_with_iocp(conn)
274 # The socket needs to be locally bound before we call ConnectEx().
275 try:
276 _overlapped.BindLocal(conn.fileno(), conn.family)
277 except OSError as e:
278 if e.winerror != errno.WSAEINVAL:
279 raise
280 # Probably already locally bound; check using getsockname().
281 if conn.getsockname()[1] == 0:
282 raise
283 ov = _overlapped.Overlapped(NULL)
284 ov.ConnectEx(conn.fileno(), address)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700285
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700286 def finish_connect(trans, key, ov):
287 ov.getresult()
288 # Use SO_UPDATE_CONNECT_CONTEXT so getsockname() etc work.
289 conn.setsockopt(socket.SOL_SOCKET,
290 _overlapped.SO_UPDATE_CONNECT_CONTEXT, 0)
291 return conn
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700292
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700293 return self._register(ov, conn, finish_connect)
294
295 def accept_pipe(self, pipe):
296 self._register_with_iocp(pipe)
297 ov = _overlapped.Overlapped(NULL)
298 ov.ConnectNamedPipe(pipe.fileno())
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700299
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700300 def finish(trans, key, ov):
301 ov.getresult()
302 return pipe
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700303
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700304 return self._register(ov, pipe, finish)
305
306 def connect_pipe(self, address):
307 ov = _overlapped.Overlapped(NULL)
308 ov.WaitNamedPipeAndConnect(address, self._iocp, ov.address)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700309
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700310 def finish(err, handle, ov):
311 # err, handle were arguments passed to PostQueuedCompletionStatus()
312 # in a function run in a thread pool.
313 if err == _overlapped.ERROR_SEM_TIMEOUT:
314 # Connection did not succeed within time limit.
315 msg = _overlapped.FormatMessage(err)
316 raise ConnectionRefusedError(0, msg, None, err)
317 elif err != 0:
318 msg = _overlapped.FormatMessage(err)
319 raise OSError(0, msg, None, err)
320 else:
321 return windows_utils.PipeHandle(handle)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700322
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700323 return self._register(ov, None, finish, wait_for_post=True)
324
Guido van Rossum90fb9142013-10-30 14:44:05 -0700325 def wait_for_handle(self, handle, timeout=None):
326 if timeout is None:
327 ms = _winapi.INFINITE
328 else:
Victor Stinnerf2e17682014-01-31 16:25:24 +0100329 # RegisterWaitForSingleObject() has a resolution of 1 millisecond,
330 # round away from zero to wait *at least* timeout seconds.
331 ms = math.ceil(timeout * 1e3)
Guido van Rossum90fb9142013-10-30 14:44:05 -0700332
333 # We only create ov so we can use ov.address as a key for the cache.
334 ov = _overlapped.Overlapped(NULL)
335 wh = _overlapped.RegisterWaitWithQueue(
336 handle, self._iocp, ov.address, ms)
337 f = _WaitHandleFuture(wh, loop=self._loop)
338
Richard Oudkerk71196e72013-11-24 17:50:40 +0000339 def finish(trans, key, ov):
Guido van Rossum90fb9142013-10-30 14:44:05 -0700340 if not f.cancelled():
341 try:
342 _overlapped.UnregisterWait(wh)
343 except OSError as e:
344 if e.winerror != _overlapped.ERROR_IO_PENDING:
345 raise
Richard Oudkerk71196e72013-11-24 17:50:40 +0000346 # Note that this second wait means that we should only use
347 # this with handles types where a successful wait has no
348 # effect. So events or processes are all right, but locks
349 # or semaphores are not. Also note if the handle is
350 # signalled and then quickly reset, then we may return
351 # False even though we have not timed out.
352 return (_winapi.WaitForSingleObject(handle, 0) ==
353 _winapi.WAIT_OBJECT_0)
Guido van Rossum90fb9142013-10-30 14:44:05 -0700354
355 self._cache[ov.address] = (f, ov, None, finish)
356 return f
357
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700358 def _register_with_iocp(self, obj):
359 # To get notifications of finished ops on this objects sent to the
360 # completion port, were must register the handle.
361 if obj not in self._registered:
362 self._registered.add(obj)
363 _overlapped.CreateIoCompletionPort(obj.fileno(), self._iocp, 0, 0)
364 # XXX We could also use SetFileCompletionNotificationModes()
365 # to avoid sending notifications to completion port of ops
366 # that succeed immediately.
367
368 def _register(self, ov, obj, callback, wait_for_post=False):
369 # Return a future which will be set with the result of the
370 # operation when it completes. The future's value is actually
371 # the value returned by callback().
372 f = _OverlappedFuture(ov, loop=self._loop)
373 if ov.pending or wait_for_post:
374 # Register the overlapped operation for later. Note that
375 # we only store obj to prevent it from being garbage
376 # collected too early.
377 self._cache[ov.address] = (f, ov, obj, callback)
378 else:
379 # The operation has completed, so no need to postpone the
380 # work. We cannot take this short cut if we need the
381 # NumberOfBytes, CompletionKey values returned by
382 # PostQueuedCompletionStatus().
383 try:
384 value = callback(None, None, ov)
385 except OSError as e:
386 f.set_exception(e)
387 else:
388 f.set_result(value)
389 return f
390
391 def _get_accept_socket(self, family):
392 s = socket.socket(family)
393 s.settimeout(0)
394 return s
395
396 def _poll(self, timeout=None):
397 if timeout is None:
398 ms = INFINITE
399 elif timeout < 0:
400 raise ValueError("negative timeout")
401 else:
Victor Stinnerf2e17682014-01-31 16:25:24 +0100402 # GetQueuedCompletionStatus() has a resolution of 1 millisecond,
403 # round away from zero to wait *at least* timeout seconds.
404 ms = math.ceil(timeout * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700405 if ms >= INFINITE:
406 raise ValueError("timeout too big")
407 while True:
408 status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
409 if status is None:
410 return
411 err, transferred, key, address = status
412 try:
413 f, ov, obj, callback = self._cache.pop(address)
414 except KeyError:
415 # key is either zero, or it is used to return a pipe
416 # handle which should be closed to avoid a leak.
417 if key not in (0, _overlapped.INVALID_HANDLE_VALUE):
418 _winapi.CloseHandle(key)
419 ms = 0
420 continue
421 if obj in self._stopped_serving:
422 f.cancel()
423 elif not f.cancelled():
424 try:
425 value = callback(transferred, key, ov)
426 except OSError as e:
427 f.set_exception(e)
428 self._results.append(f)
429 else:
430 f.set_result(value)
431 self._results.append(f)
432 ms = 0
433
434 def _stop_serving(self, obj):
435 # obj is a socket or pipe handle. It will be closed in
436 # BaseProactorEventLoop._stop_serving() which will make any
437 # pending operations fail quickly.
438 self._stopped_serving.add(obj)
439
440 def close(self):
441 # Cancel remaining registered operations.
442 for address, (f, ov, obj, callback) in list(self._cache.items()):
443 if obj is None:
444 # The operation was started with connect_pipe() which
445 # queues a task to Windows' thread pool. This cannot
446 # be cancelled, so just forget it.
447 del self._cache[address]
448 else:
449 try:
450 ov.cancel()
451 except OSError:
452 pass
453
454 while self._cache:
455 if not self._poll(1):
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700456 logger.debug('taking long time to close proactor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700457
458 self._results = []
459 if self._iocp is not None:
460 _winapi.CloseHandle(self._iocp)
461 self._iocp = None
Guido van Rossum59691282013-10-30 14:52:03 -0700462
463
464class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
465
466 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
467 self._proc = windows_utils.Popen(
468 args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
469 bufsize=bufsize, **kwargs)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700470
Guido van Rossum59691282013-10-30 14:52:03 -0700471 def callback(f):
472 returncode = self._proc.poll()
473 self._process_exited(returncode)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700474
Guido van Rossum59691282013-10-30 14:52:03 -0700475 f = self._loop._proactor.wait_for_handle(int(self._proc._handle))
476 f.add_done_callback(callback)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800477
478
479SelectorEventLoop = _WindowsSelectorEventLoop
480
481
482class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
483 _loop_factory = SelectorEventLoop
484
485
486DefaultEventLoopPolicy = _WindowsDefaultEventLoopPolicy