blob: b2ed2415e4baa5a35a9ec173883b91e96f93aa9c [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
171 def _stop_serving(self, server):
172 server.close()
173
Guido van Rossum59691282013-10-30 14:52:03 -0700174 @tasks.coroutine
175 def _make_subprocess_transport(self, protocol, args, shell,
176 stdin, stdout, stderr, bufsize,
177 extra=None, **kwargs):
178 transp = _WindowsSubprocessTransport(self, protocol, args, shell,
179 stdin, stdout, stderr, bufsize,
180 extra=None, **kwargs)
181 yield from transp._post_init()
182 return transp
183
184 def _subprocess_closed(self, transport):
185 pass
186
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700187
188class IocpProactor:
189 """Proactor implementation using IOCP."""
190
191 def __init__(self, concurrency=0xffffffff):
192 self._loop = None
193 self._results = []
194 self._iocp = _overlapped.CreateIoCompletionPort(
195 _overlapped.INVALID_HANDLE_VALUE, NULL, 0, concurrency)
196 self._cache = {}
197 self._registered = weakref.WeakSet()
198 self._stopped_serving = weakref.WeakSet()
199
200 def set_loop(self, loop):
201 self._loop = loop
202
203 def select(self, timeout=None):
204 if not self._results:
205 self._poll(timeout)
206 tmp = self._results
207 self._results = []
208 return tmp
209
210 def recv(self, conn, nbytes, flags=0):
211 self._register_with_iocp(conn)
212 ov = _overlapped.Overlapped(NULL)
213 if isinstance(conn, socket.socket):
214 ov.WSARecv(conn.fileno(), nbytes, flags)
215 else:
216 ov.ReadFile(conn.fileno(), nbytes)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700217
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700218 def finish(trans, key, ov):
219 try:
220 return ov.getresult()
221 except OSError as exc:
222 if exc.winerror == _overlapped.ERROR_NETNAME_DELETED:
223 raise ConnectionResetError(*exc.args)
224 else:
225 raise
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700226
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700227 return self._register(ov, conn, finish)
228
229 def send(self, conn, buf, flags=0):
230 self._register_with_iocp(conn)
231 ov = _overlapped.Overlapped(NULL)
232 if isinstance(conn, socket.socket):
233 ov.WSASend(conn.fileno(), buf, flags)
234 else:
235 ov.WriteFile(conn.fileno(), buf)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700236
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700237 def finish(trans, key, ov):
238 try:
239 return ov.getresult()
240 except OSError as exc:
241 if exc.winerror == _overlapped.ERROR_NETNAME_DELETED:
242 raise ConnectionResetError(*exc.args)
243 else:
244 raise
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700245
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700246 return self._register(ov, conn, finish)
247
248 def accept(self, listener):
249 self._register_with_iocp(listener)
250 conn = self._get_accept_socket(listener.family)
251 ov = _overlapped.Overlapped(NULL)
252 ov.AcceptEx(listener.fileno(), conn.fileno())
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700253
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700254 def finish_accept(trans, key, ov):
255 ov.getresult()
256 # Use SO_UPDATE_ACCEPT_CONTEXT so getsockname() etc work.
257 buf = struct.pack('@P', listener.fileno())
258 conn.setsockopt(socket.SOL_SOCKET,
259 _overlapped.SO_UPDATE_ACCEPT_CONTEXT, buf)
260 conn.settimeout(listener.gettimeout())
261 return conn, conn.getpeername()
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700262
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700263 return self._register(ov, listener, finish_accept)
264
265 def connect(self, conn, address):
266 self._register_with_iocp(conn)
267 # The socket needs to be locally bound before we call ConnectEx().
268 try:
269 _overlapped.BindLocal(conn.fileno(), conn.family)
270 except OSError as e:
271 if e.winerror != errno.WSAEINVAL:
272 raise
273 # Probably already locally bound; check using getsockname().
274 if conn.getsockname()[1] == 0:
275 raise
276 ov = _overlapped.Overlapped(NULL)
277 ov.ConnectEx(conn.fileno(), address)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700278
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700279 def finish_connect(trans, key, ov):
280 ov.getresult()
281 # Use SO_UPDATE_CONNECT_CONTEXT so getsockname() etc work.
282 conn.setsockopt(socket.SOL_SOCKET,
283 _overlapped.SO_UPDATE_CONNECT_CONTEXT, 0)
284 return conn
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700285
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700286 return self._register(ov, conn, finish_connect)
287
288 def accept_pipe(self, pipe):
289 self._register_with_iocp(pipe)
290 ov = _overlapped.Overlapped(NULL)
291 ov.ConnectNamedPipe(pipe.fileno())
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700292
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700293 def finish(trans, key, ov):
294 ov.getresult()
295 return pipe
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700296
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700297 return self._register(ov, pipe, finish)
298
299 def connect_pipe(self, address):
300 ov = _overlapped.Overlapped(NULL)
301 ov.WaitNamedPipeAndConnect(address, self._iocp, ov.address)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700302
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700303 def finish(err, handle, ov):
304 # err, handle were arguments passed to PostQueuedCompletionStatus()
305 # in a function run in a thread pool.
306 if err == _overlapped.ERROR_SEM_TIMEOUT:
307 # Connection did not succeed within time limit.
308 msg = _overlapped.FormatMessage(err)
309 raise ConnectionRefusedError(0, msg, None, err)
310 elif err != 0:
311 msg = _overlapped.FormatMessage(err)
312 raise OSError(0, msg, None, err)
313 else:
314 return windows_utils.PipeHandle(handle)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700315
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700316 return self._register(ov, None, finish, wait_for_post=True)
317
Guido van Rossum90fb9142013-10-30 14:44:05 -0700318 def wait_for_handle(self, handle, timeout=None):
319 if timeout is None:
320 ms = _winapi.INFINITE
321 else:
322 ms = int(timeout * 1000 + 0.5)
323
324 # We only create ov so we can use ov.address as a key for the cache.
325 ov = _overlapped.Overlapped(NULL)
326 wh = _overlapped.RegisterWaitWithQueue(
327 handle, self._iocp, ov.address, ms)
328 f = _WaitHandleFuture(wh, loop=self._loop)
329
Richard Oudkerk71196e72013-11-24 17:50:40 +0000330 def finish(trans, key, ov):
Guido van Rossum90fb9142013-10-30 14:44:05 -0700331 if not f.cancelled():
332 try:
333 _overlapped.UnregisterWait(wh)
334 except OSError as e:
335 if e.winerror != _overlapped.ERROR_IO_PENDING:
336 raise
Richard Oudkerk71196e72013-11-24 17:50:40 +0000337 # Note that this second wait means that we should only use
338 # this with handles types where a successful wait has no
339 # effect. So events or processes are all right, but locks
340 # or semaphores are not. Also note if the handle is
341 # signalled and then quickly reset, then we may return
342 # False even though we have not timed out.
343 return (_winapi.WaitForSingleObject(handle, 0) ==
344 _winapi.WAIT_OBJECT_0)
Guido van Rossum90fb9142013-10-30 14:44:05 -0700345
346 self._cache[ov.address] = (f, ov, None, finish)
347 return f
348
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700349 def _register_with_iocp(self, obj):
350 # To get notifications of finished ops on this objects sent to the
351 # completion port, were must register the handle.
352 if obj not in self._registered:
353 self._registered.add(obj)
354 _overlapped.CreateIoCompletionPort(obj.fileno(), self._iocp, 0, 0)
355 # XXX We could also use SetFileCompletionNotificationModes()
356 # to avoid sending notifications to completion port of ops
357 # that succeed immediately.
358
359 def _register(self, ov, obj, callback, wait_for_post=False):
360 # Return a future which will be set with the result of the
361 # operation when it completes. The future's value is actually
362 # the value returned by callback().
363 f = _OverlappedFuture(ov, loop=self._loop)
364 if ov.pending or wait_for_post:
365 # Register the overlapped operation for later. Note that
366 # we only store obj to prevent it from being garbage
367 # collected too early.
368 self._cache[ov.address] = (f, ov, obj, callback)
369 else:
370 # The operation has completed, so no need to postpone the
371 # work. We cannot take this short cut if we need the
372 # NumberOfBytes, CompletionKey values returned by
373 # PostQueuedCompletionStatus().
374 try:
375 value = callback(None, None, ov)
376 except OSError as e:
377 f.set_exception(e)
378 else:
379 f.set_result(value)
380 return f
381
382 def _get_accept_socket(self, family):
383 s = socket.socket(family)
384 s.settimeout(0)
385 return s
386
387 def _poll(self, timeout=None):
388 if timeout is None:
389 ms = INFINITE
390 elif timeout < 0:
391 raise ValueError("negative timeout")
392 else:
393 ms = int(timeout * 1000 + 0.5)
394 if ms >= INFINITE:
395 raise ValueError("timeout too big")
396 while True:
397 status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
398 if status is None:
399 return
400 err, transferred, key, address = status
401 try:
402 f, ov, obj, callback = self._cache.pop(address)
403 except KeyError:
404 # key is either zero, or it is used to return a pipe
405 # handle which should be closed to avoid a leak.
406 if key not in (0, _overlapped.INVALID_HANDLE_VALUE):
407 _winapi.CloseHandle(key)
408 ms = 0
409 continue
410 if obj in self._stopped_serving:
411 f.cancel()
412 elif not f.cancelled():
413 try:
414 value = callback(transferred, key, ov)
415 except OSError as e:
416 f.set_exception(e)
417 self._results.append(f)
418 else:
419 f.set_result(value)
420 self._results.append(f)
421 ms = 0
422
423 def _stop_serving(self, obj):
424 # obj is a socket or pipe handle. It will be closed in
425 # BaseProactorEventLoop._stop_serving() which will make any
426 # pending operations fail quickly.
427 self._stopped_serving.add(obj)
428
429 def close(self):
430 # Cancel remaining registered operations.
431 for address, (f, ov, obj, callback) in list(self._cache.items()):
432 if obj is None:
433 # The operation was started with connect_pipe() which
434 # queues a task to Windows' thread pool. This cannot
435 # be cancelled, so just forget it.
436 del self._cache[address]
437 else:
438 try:
439 ov.cancel()
440 except OSError:
441 pass
442
443 while self._cache:
444 if not self._poll(1):
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700445 logger.debug('taking long time to close proactor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700446
447 self._results = []
448 if self._iocp is not None:
449 _winapi.CloseHandle(self._iocp)
450 self._iocp = None
Guido van Rossum59691282013-10-30 14:52:03 -0700451
452
453class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
454
455 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
456 self._proc = windows_utils.Popen(
457 args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
458 bufsize=bufsize, **kwargs)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700459
Guido van Rossum59691282013-10-30 14:52:03 -0700460 def callback(f):
461 returncode = self._proc.poll()
462 self._process_exited(returncode)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700463
Guido van Rossum59691282013-10-30 14:52:03 -0700464 f = self._loop._proactor.wait_for_handle(int(self._proc._handle))
465 f.add_done_callback(callback)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800466
467
468SelectorEventLoop = _WindowsSelectorEventLoop
469
470
471class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
472 _loop_factory = SelectorEventLoop
473
474
475DefaultEventLoopPolicy = _WindowsDefaultEventLoopPolicy