forked from docker-java/docker-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFramedInputStreamConsumer.java
More file actions
99 lines (83 loc) · 3.35 KB
/
Copy pathFramedInputStreamConsumer.java
File metadata and controls
99 lines (83 loc) · 3.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.github.dockerjava.core;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import java.io.InputStream;
import java.util.Arrays;
import java.util.function.Consumer;
class FramedInputStreamConsumer implements Consumer<DockerHttpClient.Response> {
private final ResultCallback<Frame> resultCallback;
FramedInputStreamConsumer(ResultCallback<Frame> resultCallback) {
this.resultCallback = resultCallback;
}
@Override
public void accept(DockerHttpClient.Response response) {
try {
InputStream body = response.getBody();
byte[] buffer = new byte[1024];
while (true) {
// See https://docs.docker.com/engine/api/v1.37/#operation/ContainerAttach
// [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}[]byte{OUTPUT}
int streamTypeByte = body.read();
if (streamTypeByte < 0) {
return;
}
StreamType streamType = streamType(streamTypeByte);
if (streamType == StreamType.RAW) {
resultCallback.onNext(new Frame(StreamType.RAW, new byte[]{(byte) streamTypeByte}));
int readBytes;
while ((readBytes = body.read(buffer)) >= 0) {
if (readBytes == buffer.length) {
resultCallback.onNext(new Frame(StreamType.RAW, buffer));
} else {
resultCallback.onNext(new Frame(StreamType.RAW, Arrays.copyOf(buffer, readBytes)));
}
}
return;
}
// Skip 3 bytes
for (int i = 0; i < 3; i++) {
if (body.read() < 0) {
return;
}
}
// uint32 encoded as big endian.
int bytesToRead = 0;
for (int i = 0; i < 4; i++) {
int readByte = body.read();
if (readByte < 0) {
return;
}
bytesToRead |= (readByte & 0xff) << (8 * (3 - i));
}
do {
int readBytes = body.read(buffer, 0, Math.min(buffer.length, bytesToRead));
if (readBytes < 0) {
// TODO log?
return;
}
if (readBytes == buffer.length) {
resultCallback.onNext(new Frame(streamType, buffer));
} else {
resultCallback.onNext(new Frame(streamType, Arrays.copyOf(buffer, readBytes)));
}
bytesToRead -= readBytes;
} while (bytesToRead > 0);
}
} catch (Exception e) {
resultCallback.onError(e);
}
}
private static StreamType streamType(int streamType) {
switch (streamType) {
case 0:
return StreamType.STDIN;
case 1:
return StreamType.STDOUT;
case 2:
return StreamType.STDERR;
default:
return StreamType.RAW;
}
}
}