Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_api/utils/socket.py

raw
1 # This code is part of the Ansible collection community.docker, but is an independent component.
2 # This particular file, and this file only, is based on the Docker SDK for Python (https://github.com/docker/docker-py/)
3 #
4 # Copyright (c) 2016-2022 Docker, Inc.
5 #
6 # It is licensed under the Apache 2.0 license (see LICENSES/Apache-2.0.txt in this collection)
7 # SPDX-License-Identifier: Apache-2.0
8
9 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
10 # Do not use this from other collections or standalone plugins/modules!
11
12 from __future__ import annotations
13
14 import errno
15 import os
16 import select
17 import socket as pysocket
18 import struct
19 import typing as t
20
21 from ..transport.npipesocket import NpipeSocket
22
23 if t.TYPE_CHECKING:
24 from collections.abc import Sequence
25
26 from ..._socket_helper import SocketLike
27
28
29 STDOUT = 1
30 STDERR = 2
31
32
33 class SocketError(Exception):
34 pass
35
36
37 # NpipeSockets have their own error types
38 # pywintypes.error: (109, 'ReadFile', 'The pipe has been ended.')
39 NPIPE_ENDED = 109
40
41
42 def read(socket: SocketLike, n: int = 4096) -> bytes | None:
43 """
44 Reads at most n bytes from socket
45 """
46
47 recoverable_errors = (errno.EINTR, errno.EDEADLK, errno.EWOULDBLOCK)
48
49 if not isinstance(socket, NpipeSocket): # type: ignore[unreachable]
50 if not hasattr(select, "poll"):
51 # Limited to 1024
52 select.select([socket], [], [])
53 else:
54 poll = select.poll()
55 poll.register(socket, select.POLLIN | select.POLLPRI)
56 poll.poll()
57
58 try:
59 if hasattr(socket, "recv"):
60 return socket.recv(n)
61 if isinstance(socket, pysocket.SocketIO): # type: ignore
62 return socket.read(n) # type: ignore[unreachable]
63 return os.read(socket.fileno(), n)
64 except EnvironmentError as e:
65 if e.errno not in recoverable_errors:
66 raise
67 return None # TODO ???
68 except Exception as e:
69 is_pipe_ended = (
70 isinstance(socket, NpipeSocket) # type: ignore[unreachable]
71 and len(e.args) > 0
72 and e.args[0] == NPIPE_ENDED
73 )
74 if is_pipe_ended:
75 # npipes do not support duplex sockets, so we interpret
76 # a PIPE_ENDED error as a close operation (0-length read).
77 return b""
78 raise
79
80
81 def read_exactly(socket: SocketLike, n: int) -> bytes:
82 """
83 Reads exactly n bytes from socket
84 Raises SocketError if there is not enough data
85 """
86 data = b""
87 while len(data) < n:
88 next_data = read(socket, n - len(data))
89 if not next_data:
90 raise SocketError("Unexpected EOF")
91 data += next_data
92 return data
93
94
95 def next_frame_header(socket: SocketLike) -> tuple[int, int]:
96 """
97 Returns the stream and size of the next frame of data waiting to be read
98 from socket, according to the protocol defined here:
99
100 https://docs.docker.com/engine/api/v1.24/#attach-to-a-container
101 """
102 try:
103 data = read_exactly(socket, 8)
104 except SocketError:
105 return (-1, -1)
106
107 stream, actual = struct.unpack(">BxxxL", data)
108 return (stream, actual)
109
110
111 def frames_iter(socket: SocketLike, tty: bool) -> t.Generator[tuple[int, bytes]]:
112 """
113 Return a generator of frames read from socket. A frame is a tuple where
114 the first item is the stream number and the second item is a chunk of data.
115
116 If the tty setting is enabled, the streams are multiplexed into the stdout
117 stream.
118 """
119 if tty:
120 return ((STDOUT, frame) for frame in frames_iter_tty(socket))
121 return frames_iter_no_tty(socket)
122
123
124 def frames_iter_no_tty(socket: SocketLike) -> t.Generator[tuple[int, bytes]]:
125 """
126 Returns a generator of data read from the socket when the tty setting is
127 not enabled.
128 """
129 while True:
130 stream, n = next_frame_header(socket)
131 if n < 0:
132 break
133 while n > 0:
134 result = read(socket, n)
135 if result is None:
136 continue
137 data_length = len(result)
138 if data_length == 0:
139 # We have reached EOF
140 return
141 n -= data_length
142 yield (stream, result)
143
144
145 def frames_iter_tty(socket: SocketLike) -> t.Generator[bytes]:
146 """
147 Return a generator of data read from the socket when the tty setting is
148 enabled.
149 """
150 while True:
151 result = read(socket)
152 if not result:
153 # We have reached EOF
154 return
155 yield result
156
157
158 @t.overload
159 def consume_socket_output(
160 frames: Sequence[bytes] | t.Generator[bytes], demux: t.Literal[False] = False
161 ) -> bytes: ...
162
163
164 @t.overload
165 def consume_socket_output(
166 frames: (
167 Sequence[tuple[bytes | None, bytes | None]]
168 | t.Generator[tuple[bytes | None, bytes | None]]
169 ),
170 demux: t.Literal[True],
171 ) -> tuple[bytes, bytes]: ...
172
173
174 @t.overload
175 def consume_socket_output(
176 frames: (
177 Sequence[bytes]
178 | Sequence[tuple[bytes | None, bytes | None]]
179 | t.Generator[bytes]
180 | t.Generator[tuple[bytes | None, bytes | None]]
181 ),
182 demux: bool = False,
183 ) -> bytes | tuple[bytes, bytes]: ...
184
185
186 def consume_socket_output(
187 frames: (
188 Sequence[bytes]
189 | Sequence[tuple[bytes | None, bytes | None]]
190 | t.Generator[bytes]
191 | t.Generator[tuple[bytes | None, bytes | None]]
192 ),
193 demux: bool = False,
194 ) -> bytes | tuple[bytes, bytes]:
195 """
196 Iterate through frames read from the socket and return the result.
197
198 Args:
199
200 demux (bool):
201 If False, stdout and stderr are multiplexed, and the result is the
202 concatenation of all the frames. If True, the streams are
203 demultiplexed, and the result is a 2-tuple where each item is the
204 concatenation of frames belonging to the same stream.
205 """
206 if demux is False:
207 # If the streams are multiplexed, the generator returns strings, that
208 # we just need to concatenate.
209 return b"".join(frames) # type: ignore
210
211 # If the streams are demultiplexed, the generator yields tuples
212 # (stdout, stderr)
213 out: list[bytes | None] = [None, None]
214 frame: tuple[bytes | None, bytes | None]
215 for frame in frames: # type: ignore
216 # It is guaranteed that for each frame, one and only one stream
217 # is not None.
218 if frame == (None, None):
219 raise AssertionError(f"frame must be (None, None), but got {frame}")
220 if frame[0] is not None:
221 if out[0] is None:
222 out[0] = frame[0]
223 else:
224 out[0] += frame[0]
225 else:
226 if out[1] is None:
227 out[1] = frame[1]
228 else:
229 out[1] += frame[1] # type: ignore[operator]
230 return tuple(out) # type: ignore
231
232
233 def demux_adaptor(stream_id: int, data: bytes) -> tuple[bytes | None, bytes | None]:
234 """
235 Utility to demultiplex stdout and stderr when reading frames from the
236 socket.
237 """
238 if stream_id == STDOUT:
239 return (data, None)
240 if stream_id == STDERR:
241 return (None, data)
242 raise ValueError(f"{stream_id} is not a valid stream")