blob: b8574fa059b4b3fd53169ca4012584849ad78b29 [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()
Victor Stinner1506df22014-01-31 16:26:38 +0100194 self.resolution = 1e-3
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700195
196 def set_loop(self, loop):
197 self._loop = loop
198
199 def select(self, timeout=None):
200 if not self._results:
201 self._poll(timeout)
202 tmp = self._results
203 self._results = []
204 return tmp
205
206 def recv(self, conn, nbytes, flags=0):
207 self._register_with_iocp(conn)
208 ov = _overlapped.Overlapped(NULL)
209 if isinstance(conn, socket.socket):
210 ov.WSARecv(conn.fileno(), nbytes, flags)
211 else:
212 ov.ReadFile(conn.fileno(), nbytes)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700213
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700214 def finish(trans, key, ov):
215 try:
216 return ov.getresult()
217 except OSError as exc:
218 if exc.winerror == _overlapped.ERROR_NETNAME_DELETED:
219 raise ConnectionResetError(*exc.args)
220 else:
221 raise
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700222
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700223 return self._register(ov, conn, finish)
224
225 def send(self, conn, buf, flags=0):
226 self._register_with_iocp(conn)
227 ov = _overlapped.Overlapped(NULL)
228 if isinstance(conn, socket.socket):
229 ov.WSASend(conn.fileno(), buf, flags)
230 else:
231 ov.WriteFile(conn.fileno(), buf)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700232
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700233 def finish(trans, key, ov):
234 try:
235 return ov.getresult()
236 except OSError as exc:
237 if exc.winerror == _overlapped.ERROR_NETNAME_DELETED:
238 raise ConnectionResetError(*exc.args)
239 else:
240 raise
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700241
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700242 return self._register(ov, conn, finish)
243
244 def accept(self, listener):
245 self._register_with_iocp(listener)
246 conn = self._get_accept_socket(listener.family)
247 ov = _overlapped.Overlapped(NULL)
248 ov.AcceptEx(listener.fileno(), conn.fileno())
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700249
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700250 def finish_accept(trans, key, ov):
251 ov.getresult()
252 # Use SO_UPDATE_ACCEPT_CONTEXT so getsockname() etc work.
253 buf = struct.pack('@P', listener.fileno())
254 conn.setsockopt(socket.SOL_SOCKET,
255 _overlapped.SO_UPDATE_ACCEPT_CONTEXT, buf)
256 conn.settimeout(listener.gettimeout())
257 return conn, conn.getpeername()
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700258
Victor Stinner7de26462014-01-11 00:03:21 +0100259 @tasks.coroutine
260 def accept_coro(future, conn):
261 # Coroutine closing the accept socket if the future is cancelled
262 try:
263 yield from future
264 except futures.CancelledError:
265 conn.close()
266 raise
267
268 future = self._register(ov, listener, finish_accept)
269 coro = accept_coro(future, conn)
270 tasks.async(coro, loop=self._loop)
271 return future
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700272
273 def connect(self, conn, address):
274 self._register_with_iocp(conn)
275 # The socket needs to be locally bound before we call ConnectEx().
276 try:
277 _overlapped.BindLocal(conn.fileno(), conn.family)
278 except OSError as e:
279 if e.winerror != errno.WSAEINVAL:
280 raise
281 # Probably already locally bound; check using getsockname().
282 if conn.getsockname()[1] == 0:
283 raise
284 ov = _overlapped.Overlapped(NULL)
285 ov.ConnectEx(conn.fileno(), address)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700286
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700287 def finish_connect(trans, key, ov):
288 ov.getresult()
289 # Use SO_UPDATE_CONNECT_CONTEXT so getsockname() etc work.
290 conn.setsockopt(socket.SOL_SOCKET,
291 _overlapped.SO_UPDATE_CONNECT_CONTEXT, 0)
292 return conn
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700293
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700294 return self._register(ov, conn, finish_connect)
295
296 def accept_pipe(self, pipe):
297 self._register_with_iocp(pipe)
298 ov = _overlapped.Overlapped(NULL)
299 ov.ConnectNamedPipe(pipe.fileno())
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700300
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700301 def finish(trans, key, ov):
302 ov.getresult()
303 return pipe
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700304
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700305 return self._register(ov, pipe, finish)
306
307 def connect_pipe(self, address):
308 ov = _overlapped.Overlapped(NULL)
309 ov.WaitNamedPipeAndConnect(address, self._iocp, ov.address)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700310
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700311 def finish(err, handle, ov):
312 # err, handle were arguments passed to PostQueuedCompletionStatus()
313 # in a function run in a thread pool.
314 if err == _overlapped.ERROR_SEM_TIMEOUT:
315 # Connection did not succeed within time limit.
316 msg = _overlapped.FormatMessage(err)
317 raise ConnectionRefusedError(0, msg, None, err)
318 elif err != 0:
319 msg = _overlapped.FormatMessage(err)
320 raise OSError(0, msg, None, err)
321 else:
322 return windows_utils.PipeHandle(handle)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700323
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700324 return self._register(ov, None, finish, wait_for_post=True)
325
Guido van Rossum90fb9142013-10-30 14:44:05 -0700326 def wait_for_handle(self, handle, timeout=None):
327 if timeout is None:
328 ms = _winapi.INFINITE
329 else:
Victor Stinnerf2e17682014-01-31 16:25:24 +0100330 # RegisterWaitForSingleObject() has a resolution of 1 millisecond,
331 # round away from zero to wait *at least* timeout seconds.
332 ms = math.ceil(timeout * 1e3)
Guido van Rossum90fb9142013-10-30 14:44:05 -0700333
334 # We only create ov so we can use ov.address as a key for the cache.
335 ov = _overlapped.Overlapped(NULL)
336 wh = _overlapped.RegisterWaitWithQueue(
337 handle, self._iocp, ov.address, ms)
338 f = _WaitHandleFuture(wh, loop=self._loop)
339
Richard Oudkerk71196e72013-11-24 17:50:40 +0000340 def finish(trans, key, ov):
Guido van Rossum90fb9142013-10-30 14:44:05 -0700341 if not f.cancelled():
342 try:
343 _overlapped.UnregisterWait(wh)
344 except OSError as e:
345 if e.winerror != _overlapped.ERROR_IO_PENDING:
346 raise
Richard Oudkerk71196e72013-11-24 17:50:40 +0000347 # Note that this second wait means that we should only use
348 # this with handles types where a successful wait has no
349 # effect. So events or processes are all right, but locks
350 # or semaphores are not. Also note if the handle is
351 # signalled and then quickly reset, then we may return
352 # False even though we have not timed out.
353 return (_winapi.WaitForSingleObject(handle, 0) ==
354 _winapi.WAIT_OBJECT_0)
Guido van Rossum90fb9142013-10-30 14:44:05 -0700355
356 self._cache[ov.address] = (f, ov, None, finish)
357 return f
358
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700359 def _register_with_iocp(self, obj):
360 # To get notifications of finished ops on this objects sent to the
361 # completion port, were must register the handle.
362 if obj not in self._registered:
363 self._registered.add(obj)
364 _overlapped.CreateIoCompletionPort(obj.fileno(), self._iocp, 0, 0)
365 # XXX We could also use SetFileCompletionNotificationModes()
366 # to avoid sending notifications to completion port of ops
367 # that succeed immediately.
368
369 def _register(self, ov, obj, callback, wait_for_post=False):
370 # Return a future which will be set with the result of the
371 # operation when it completes. The future's value is actually
372 # the value returned by callback().
373 f = _OverlappedFuture(ov, loop=self._loop)
374 if ov.pending or wait_for_post:
375 # Register the overlapped operation for later. Note that
376 # we only store obj to prevent it from being garbage
377 # collected too early.
378 self._cache[ov.address] = (f, ov, obj, callback)
379 else:
380 # The operation has completed, so no need to postpone the
381 # work. We cannot take this short cut if we need the
382 # NumberOfBytes, CompletionKey values returned by
383 # PostQueuedCompletionStatus().
384 try:
385 value = callback(None, None, ov)
386 except OSError as e:
387 f.set_exception(e)
388 else:
389 f.set_result(value)
390 return f
391
392 def _get_accept_socket(self, family):
393 s = socket.socket(family)
394 s.settimeout(0)
395 return s
396
397 def _poll(self, timeout=None):
398 if timeout is None:
399 ms = INFINITE
400 elif timeout < 0:
401 raise ValueError("negative timeout")
402 else:
Victor Stinnerf2e17682014-01-31 16:25:24 +0100403 # GetQueuedCompletionStatus() has a resolution of 1 millisecond,
404 # round away from zero to wait *at least* timeout seconds.
405 ms = math.ceil(timeout * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700406 if ms >= INFINITE:
407 raise ValueError("timeout too big")
408 while True:
409 status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
410 if status is None:
411 return
412 err, transferred, key, address = status
413 try:
414 f, ov, obj, callback = self._cache.pop(address)
415 except KeyError:
416 # key is either zero, or it is used to return a pipe
417 # handle which should be closed to avoid a leak.
418 if key not in (0, _overlapped.INVALID_HANDLE_VALUE):
419 _winapi.CloseHandle(key)
420 ms = 0
421 continue
422 if obj in self._stopped_serving:
423 f.cancel()
424 elif not f.cancelled():
425 try:
426 value = callback(transferred, key, ov)
427 except OSError as e:
428 f.set_exception(e)
429 self._results.append(f)
430 else:
431 f.set_result(value)
432 self._results.append(f)
433 ms = 0
434
435 def _stop_serving(self, obj):
436 # obj is a socket or pipe handle. It will be closed in
437 # BaseProactorEventLoop._stop_serving() which will make any
438 # pending operations fail quickly.
439 self._stopped_serving.add(obj)
440
441 def close(self):
442 # Cancel remaining registered operations.
443 for address, (f, ov, obj, callback) in list(self._cache.items()):
444 if obj is None:
445 # The operation was started with connect_pipe() which
446 # queues a task to Windows' thread pool. This cannot
447 # be cancelled, so just forget it.
448 del self._cache[address]
449 else:
450 try:
451 ov.cancel()
452 except OSError:
453 pass
454
455 while self._cache:
456 if not self._poll(1):
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700457 logger.debug('taking long time to close proactor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700458
459 self._results = []
460 if self._iocp is not None:
461 _winapi.CloseHandle(self._iocp)
462 self._iocp = None
Guido van Rossum59691282013-10-30 14:52:03 -0700463
464
465class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
466
467 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
468 self._proc = windows_utils.Popen(
469 args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
470 bufsize=bufsize, **kwargs)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700471
Guido van Rossum59691282013-10-30 14:52:03 -0700472 def callback(f):
473 returncode = self._proc.poll()
474 self._process_exited(returncode)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700475
Guido van Rossum59691282013-10-30 14:52:03 -0700476 f = self._loop._proactor.wait_for_handle(int(self._proc._handle))
477 f.add_done_callback(callback)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800478
479
480SelectorEventLoop = _WindowsSelectorEventLoop
481
482
483class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
484 _loop_factory = SelectorEventLoop
485
486
487DefaultEventLoopPolicy = _WindowsDefaultEventLoopPolicy