Skip to content

Commit 558fdbf

Browse files
committed
Improve consume_socket_output perf (n²⇒n)
1 parent 0ab8626 commit 558fdbf

File tree

1 file changed

+17
-19
lines changed

1 file changed

+17
-19
lines changed

docker/utils/socket.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def read(socket, n=4096):
4040
poll.poll()
4141

4242
try:
43-
if hasattr(socket, 'recv'):
43+
if hasattr(socket, "recv"):
4444
return socket.recv(n)
4545
if isinstance(socket, pysocket.SocketIO):
4646
return socket.read(n)
@@ -49,13 +49,15 @@ def read(socket, n=4096):
4949
if e.errno not in recoverable_errors:
5050
raise
5151
except Exception as e:
52-
is_pipe_ended = (isinstance(socket, NpipeSocket) and
53-
len(e.args) > 0 and
54-
e.args[0] == NPIPE_ENDED)
52+
is_pipe_ended = (
53+
isinstance(socket, NpipeSocket)
54+
and len(e.args) > 0
55+
and e.args[0] == NPIPE_ENDED
56+
)
5557
if is_pipe_ended:
5658
# npipes don't support duplex sockets, so we interpret
5759
# a PIPE_ENDED error as a close operation (0-length read).
58-
return ''
60+
return ""
5961
raise
6062

6163

@@ -85,7 +87,7 @@ def next_frame_header(socket):
8587
except SocketError:
8688
return (-1, -1)
8789

88-
stream, actual = struct.unpack('>BxxxL', data)
90+
stream, actual = struct.unpack(">BxxxL", data)
8991
return (stream, actual)
9092

9193

@@ -156,22 +158,18 @@ def consume_socket_output(frames, demux=False):
156158

157159
# If the streams are demultiplexed, the generator yields tuples
158160
# (stdout, stderr)
159-
out = [None, None]
160-
for frame in frames:
161+
stdout = []
162+
stderr = []
163+
for stdout_frame, stderr_frame in frames:
161164
# It is guaranteed that for each frame, one and only one stream
162165
# is not None.
163-
assert frame != (None, None)
164-
if frame[0] is not None:
165-
if out[0] is None:
166-
out[0] = frame[0]
167-
else:
168-
out[0] += frame[0]
166+
if stdout_frame:
167+
stdout.append(stdout_frame)
169168
else:
170-
if out[1] is None:
171-
out[1] = frame[1]
172-
else:
173-
out[1] += frame[1]
174-
return tuple(out)
169+
stderr.append(stderr_frame)
170+
stdout = b"".join(stdout) if len(stdout) > 0 else None
171+
stderr = b"".join(stderr) if len(stderr) > 0 else None
172+
return stdout, stderr
175173

176174

177175
def demux_adaptor(stream_id, data):

0 commit comments

Comments
 (0)