blob: 64fe38617d74a7d98ef7621ab0f97465bd1d888a [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
330 def finish(timed_out, _, ov):
331 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
337 return not timed_out
338
339 self._cache[ov.address] = (f, ov, None, finish)
340 return f
341
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700342 def _register_with_iocp(self, obj):
343 # To get notifications of finished ops on this objects sent to the
344 # completion port, were must register the handle.
345 if obj not in self._registered:
346 self._registered.add(obj)
347 _overlapped.CreateIoCompletionPort(obj.fileno(), self._iocp, 0, 0)
348 # XXX We could also use SetFileCompletionNotificationModes()
349 # to avoid sending notifications to completion port of ops
350 # that succeed immediately.
351
352 def _register(self, ov, obj, callback, wait_for_post=False):
353 # Return a future which will be set with the result of the
354 # operation when it completes. The future's value is actually
355 # the value returned by callback().
356 f = _OverlappedFuture(ov, loop=self._loop)
357 if ov.pending or wait_for_post:
358 # Register the overlapped operation for later. Note that
359 # we only store obj to prevent it from being garbage
360 # collected too early.
361 self._cache[ov.address] = (f, ov, obj, callback)
362 else:
363 # The operation has completed, so no need to postpone the
364 # work. We cannot take this short cut if we need the
365 # NumberOfBytes, CompletionKey values returned by
366 # PostQueuedCompletionStatus().
367 try:
368 value = callback(None, None, ov)
369 except OSError as e:
370 f.set_exception(e)
371 else:
372 f.set_result(value)
373 return f
374
375 def _get_accept_socket(self, family):
376 s = socket.socket(family)
377 s.settimeout(0)
378 return s
379
380 def _poll(self, timeout=None):
381 if timeout is None:
382 ms = INFINITE
383 elif timeout < 0:
384 raise ValueError("negative timeout")
385 else:
386 ms = int(timeout * 1000 + 0.5)
387 if ms >= INFINITE:
388 raise ValueError("timeout too big")
389 while True:
390 status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
391 if status is None:
392 return
393 err, transferred, key, address = status
394 try:
395 f, ov, obj, callback = self._cache.pop(address)
396 except KeyError:
397 # key is either zero, or it is used to return a pipe
398 # handle which should be closed to avoid a leak.
399 if key not in (0, _overlapped.INVALID_HANDLE_VALUE):
400 _winapi.CloseHandle(key)
401 ms = 0
402 continue
403 if obj in self._stopped_serving:
404 f.cancel()
405 elif not f.cancelled():
406 try:
407 value = callback(transferred, key, ov)
408 except OSError as e:
409 f.set_exception(e)
410 self._results.append(f)
411 else:
412 f.set_result(value)
413 self._results.append(f)
414 ms = 0
415
416 def _stop_serving(self, obj):
417 # obj is a socket or pipe handle. It will be closed in
418 # BaseProactorEventLoop._stop_serving() which will make any
419 # pending operations fail quickly.
420 self._stopped_serving.add(obj)
421
422 def close(self):
423 # Cancel remaining registered operations.
424 for address, (f, ov, obj, callback) in list(self._cache.items()):
425 if obj is None:
426 # The operation was started with connect_pipe() which
427 # queues a task to Windows' thread pool. This cannot
428 # be cancelled, so just forget it.
429 del self._cache[address]
430 else:
431 try:
432 ov.cancel()
433 except OSError:
434 pass
435
436 while self._cache:
437 if not self._poll(1):
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700438 logger.debug('taking long time to close proactor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700439
440 self._results = []
441 if self._iocp is not None:
442 _winapi.CloseHandle(self._iocp)
443 self._iocp = None
Guido van Rossum59691282013-10-30 14:52:03 -0700444
445
446class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
447
448 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
449 self._proc = windows_utils.Popen(
450 args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
451 bufsize=bufsize, **kwargs)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700452
Guido van Rossum59691282013-10-30 14:52:03 -0700453 def callback(f):
454 returncode = self._proc.poll()
455 self._process_exited(returncode)
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700456
Guido van Rossum59691282013-10-30 14:52:03 -0700457 f = self._loop._proactor.wait_for_handle(int(self._proc._handle))
458 f.add_done_callback(callback)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800459
460
461SelectorEventLoop = _WindowsSelectorEventLoop
462
463
464class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
465 _loop_factory = SelectorEventLoop
466
467
468DefaultEventLoopPolicy = _WindowsDefaultEventLoopPolicy