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