mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(docker): read Docker streams on virtual threads (#9174)
docker-java read every stream (a log follow, a container wait, an exec's output, the events stream) on a platform thread of its own, so the threads grew with the containers. Floci now builds its DockerClients with FlociDockerCmdExecFactory, adapted from docker-java 3.7.1's DefaultDockerCmdExecFactory, DefaultInvocationBuilder and FramedInputStreamConsumer (Apache License 2.0), whose one change runs each stream on a virtual thread. Closing a stream still interrupts its thread and closes the response, and the client is still built over the launch bulkhead, the circuit breaker and the retry layer. The pool gauge's stream-thread count, which listed threads by name and cannot see virtual ones, now counts the running stream callbacks.
This commit is contained in:
1 parent
a9d0aab496
commit
c4238de1c1
8 files changed
+708
-38
No files matched your search
@@ -112,6 +112,8 @@ Docker pools: control-plane leased=2 available=6 pending=0 max=1024; streaming l
|
||||
|
||||
A stream is `unattributed` when it follows no container (an exec, an image pull or build, daemon events), or a container this Floci process did not start with a service label: one started before a restart, by a tool other than Floci, or by a Floci helper that labels no service.
|
||||
|
||||
Each open stream is read on a virtual thread of its own, so `stream threads` counts the streams being read and costs no platform thread each. Virtual threads do not appear in a plain `jstack`; `jcmd <pid> Thread.dump_to_file -format=json <file>` lists them.
|
||||
|
||||
A `pending` above 0 means calls are waiting for a connection, and a call that waits longer than `connection-request-timeout-seconds` fails. To turn the lines off, set the interval to 0:
|
||||
|
||||
```yaml
|
||||
|
||||
@@ -593,10 +593,21 @@ public class DockerClientProducer {
|
||||
}
|
||||
Duration launchWait = Duration.ofSeconds(config.docker().connectionRequestTimeoutSeconds());
|
||||
usePingTransport(clientConfig);
|
||||
return DockerClientImpl.getInstance(clientConfig,
|
||||
return newDockerClient(clientConfig,
|
||||
wrapForRole(transport, role, apiTimeout, breaker, launchSlots, launchWait));
|
||||
}
|
||||
|
||||
/**
|
||||
* A DockerClient over {@code httpClient} whose stream callbacks run on virtual threads
|
||||
* ({@link FlociDockerCmdExecFactory}). docker-java offers no other way to give its streams a thread of
|
||||
* Floci's choosing than its deprecated exec-factory hook.
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
static DockerClient newDockerClient(DefaultDockerClientConfig clientConfig, DockerHttpClient httpClient) {
|
||||
return DockerClientImpl.getInstance(clientConfig)
|
||||
.withDockerCmdExecFactory(new FlociDockerCmdExecFactory(httpClient, clientConfig.getObjectMapper()));
|
||||
}
|
||||
|
||||
static FlociDockerHttpClient newHttpClient(DefaultDockerClientConfig clientConfig, int maxConnections,
|
||||
Duration apiTimeout, Duration connectionRequestTimeout) {
|
||||
return new FlociDockerHttpClient.Builder()
|
||||
|
||||
@@ -110,24 +110,8 @@ final class DockerPoolGaugeLogger {
|
||||
return String.join("; ", parts);
|
||||
}
|
||||
|
||||
/** Counts the live docker-java stream threads by name, without capturing any thread's stack. */
|
||||
/** The live docker-java stream callbacks, each on its own virtual thread. */
|
||||
static int countStreamThreads() {
|
||||
ThreadGroup root = Thread.currentThread().getThreadGroup();
|
||||
while (root.getParent() != null) {
|
||||
root = root.getParent();
|
||||
}
|
||||
Thread[] threads = new Thread[root.activeCount() + 16];
|
||||
int listed = root.enumerate(threads, true);
|
||||
while (listed == threads.length) {
|
||||
threads = new Thread[threads.length * 2];
|
||||
listed = root.enumerate(threads, true);
|
||||
}
|
||||
int count = 0;
|
||||
for (int i = 0; i < listed; i++) {
|
||||
if (threads[i].getName().startsWith(STREAM_THREAD_PREFIX)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
return FlociInvocationBuilder.activeStreams();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
* Adapted from docker-java com.github.dockerjava.core.DefaultDockerCmdExecFactory (version 3.7.1, Apache License 2.0,
|
||||
* https://github.com/docker-java/docker-java). Final there; the copy hands out FlociInvocationBuilder, so stream callbacks run on virtual threads.
|
||||
*/
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.dockerjava.core.AbstractDockerCmdExecFactory;
|
||||
import com.github.dockerjava.core.InvocationBuilder;
|
||||
import com.github.dockerjava.core.RemoteApiVersion;
|
||||
import com.github.dockerjava.core.WebTarget;
|
||||
import com.github.dockerjava.transport.DockerHttpClient;
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.MultimapBuilder;
|
||||
import com.google.common.collect.SetMultimap;
|
||||
import com.google.common.escape.Escaper;
|
||||
import com.google.common.net.UrlEscapers;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
final class FlociDockerCmdExecFactory extends AbstractDockerCmdExecFactory {
|
||||
|
||||
private final DockerHttpClient dockerHttpClient;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
FlociDockerCmdExecFactory(
|
||||
DockerHttpClient dockerHttpClient,
|
||||
ObjectMapper objectMapper
|
||||
) {
|
||||
this.dockerHttpClient = dockerHttpClient;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public DockerHttpClient getDockerHttpClient() {
|
||||
return dockerHttpClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected WebTarget getBaseResource() {
|
||||
return new FlociWebTarget();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
dockerHttpClient.close();
|
||||
}
|
||||
|
||||
private class FlociWebTarget implements WebTarget {
|
||||
|
||||
final ImmutableList<String> path;
|
||||
|
||||
final SetMultimap<String, String> queryParams;
|
||||
|
||||
FlociWebTarget() {
|
||||
this(
|
||||
ImmutableList.of(),
|
||||
MultimapBuilder.hashKeys().hashSetValues().build()
|
||||
);
|
||||
}
|
||||
|
||||
FlociWebTarget(
|
||||
ImmutableList<String> path,
|
||||
SetMultimap<String, String> queryParams
|
||||
) {
|
||||
this.path = path;
|
||||
this.queryParams = queryParams;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("FlociWebTarget{path=%s, queryParams=%s}", path, queryParams);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InvocationBuilder request() {
|
||||
String resource = StringUtils.join(path, "/");
|
||||
|
||||
if (!resource.startsWith("/")) {
|
||||
resource = "/" + resource;
|
||||
}
|
||||
|
||||
RemoteApiVersion apiVersion = getDockerClientConfig().getApiVersion();
|
||||
if (apiVersion != RemoteApiVersion.UNKNOWN_VERSION) {
|
||||
resource = "/" + apiVersion.asWebPathPart() + resource;
|
||||
}
|
||||
|
||||
if (!queryParams.isEmpty()) {
|
||||
Escaper urlFormParameterEscaper = UrlEscapers.urlFormParameterEscaper();
|
||||
resource = queryParams.asMap().entrySet().stream()
|
||||
.flatMap(entry -> {
|
||||
return entry.getValue().stream().map(s -> {
|
||||
return entry.getKey() + "=" + urlFormParameterEscaper.escape(s);
|
||||
});
|
||||
})
|
||||
.collect(Collectors.joining("&", resource + "?", ""));
|
||||
}
|
||||
|
||||
return new FlociInvocationBuilder(
|
||||
dockerHttpClient, objectMapper, resource
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FlociWebTarget path(String... components) {
|
||||
ImmutableList<String> newPath = ImmutableList.<String>builder()
|
||||
.addAll(path)
|
||||
.add(components)
|
||||
.build();
|
||||
return new FlociWebTarget(newPath, queryParams);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FlociWebTarget resolveTemplate(String name, Object value) {
|
||||
ImmutableList.Builder<String> newPath = ImmutableList.builder();
|
||||
for (String component : path) {
|
||||
component = component.replaceAll(
|
||||
"\\{" + name + "\\}",
|
||||
UrlEscapers.urlPathSegmentEscaper().escape(value.toString())
|
||||
);
|
||||
newPath.add(component);
|
||||
}
|
||||
|
||||
return new FlociWebTarget(newPath.build(), queryParams);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FlociWebTarget queryParam(String name, Object value) {
|
||||
if (value == null) {
|
||||
return this;
|
||||
}
|
||||
|
||||
SetMultimap<String, String> newQueryParams = HashMultimap.create(queryParams);
|
||||
newQueryParams.put(name, value.toString());
|
||||
|
||||
return new FlociWebTarget(path, newQueryParams);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FlociWebTarget queryParamsSet(String name, Set<?> values) {
|
||||
SetMultimap<String, String> newQueryParams = HashMultimap.create(queryParams);
|
||||
newQueryParams.replaceValues(name, values.stream().filter(Objects::nonNull).map(Object::toString).collect(Collectors.toSet()));
|
||||
|
||||
return new FlociWebTarget(path, newQueryParams);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FlociWebTarget queryParamsJsonMap(String name, Map<String, String> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return this;
|
||||
}
|
||||
|
||||
// when param value is JSON string
|
||||
try {
|
||||
return queryParam(name, objectMapper.writeValueAsString(values));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Adapted from docker-java com.github.dockerjava.core.FramedInputStreamConsumer (version 3.7.1, Apache License 2.0,
|
||||
* https://github.com/docker-java/docker-java). Package-private there, and FlociInvocationBuilder needs it to read multiplexed stream frames.
|
||||
*/
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import com.github.dockerjava.transport.DockerHttpClient;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
final class FlociFramedInputStreamConsumer implements Consumer<DockerHttpClient.Response> {
|
||||
|
||||
private final ResultCallback<Frame> resultCallback;
|
||||
|
||||
FlociFramedInputStreamConsumer(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
/*
|
||||
* Adapted from docker-java com.github.dockerjava.core.DefaultInvocationBuilder (version 3.7.1, Apache License 2.0,
|
||||
* https://github.com/docker-java/docker-java). Package-private there; the copy runs each stream callback on a virtual thread (see executeAndStream).
|
||||
*/
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.MappingIterator;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.exception.BadRequestException;
|
||||
import com.github.dockerjava.api.exception.ConflictException;
|
||||
import com.github.dockerjava.api.exception.DockerException;
|
||||
import com.github.dockerjava.api.exception.InternalServerErrorException;
|
||||
import com.github.dockerjava.api.exception.NotAcceptableException;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.exception.NotModifiedException;
|
||||
import com.github.dockerjava.api.exception.UnauthorizedException;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.core.InvocationBuilder;
|
||||
import com.github.dockerjava.core.MediaType;
|
||||
import com.github.dockerjava.transport.DockerHttpClient;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import java.io.FilterInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
final class FlociInvocationBuilder implements InvocationBuilder {
|
||||
|
||||
/** docker-java stream callbacks running now, each on its own virtual thread. */
|
||||
private static final AtomicInteger ACTIVE_STREAMS = new AtomicInteger();
|
||||
|
||||
private final DockerHttpClient.Request.Builder requestBuilder;
|
||||
private final DockerHttpClient dockerHttpClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
FlociInvocationBuilder(DockerHttpClient dockerHttpClient, ObjectMapper objectMapper, String path) {
|
||||
this.requestBuilder = DockerHttpClient.Request.builder().path(path);
|
||||
this.dockerHttpClient = dockerHttpClient;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FlociInvocationBuilder accept(MediaType mediaType) {
|
||||
return header("accept", mediaType.getMediaType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public FlociInvocationBuilder header(String name, String value) {
|
||||
requestBuilder.putHeader(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete() {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.DELETE)
|
||||
.build();
|
||||
|
||||
execute(request).close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void get(ResultCallback<Frame> resultCallback) {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.GET)
|
||||
.build();
|
||||
|
||||
executeAndStream(
|
||||
request,
|
||||
resultCallback,
|
||||
new FlociFramedInputStreamConsumer(resultCallback)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T get(TypeReference<T> typeReference) {
|
||||
try (InputStream inputStream = get()) {
|
||||
return objectMapper.readValue(inputStream, typeReference);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void get(TypeReference<T> typeReference, ResultCallback<T> resultCallback) {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.GET)
|
||||
.build();
|
||||
|
||||
executeAndStream(
|
||||
request,
|
||||
resultCallback,
|
||||
new JsonSink<>(typeReference, resultCallback)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream post(Object entity) {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.POST)
|
||||
.putHeader("content-type", "application/json")
|
||||
.bodyBytes(encode(entity))
|
||||
.build();
|
||||
|
||||
DockerHttpClient.Response response = execute(request);
|
||||
return new FilterInputStream(response.getBody()) {
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
try {
|
||||
super.close();
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T post(Object entity, TypeReference<T> typeReference) {
|
||||
try {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.POST)
|
||||
.putHeader("content-type", "application/json")
|
||||
.bodyBytes(encode(entity))
|
||||
.build();
|
||||
|
||||
try (DockerHttpClient.Response response = execute(request)) {
|
||||
return objectMapper.readValue(response.getBody(), typeReference);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void post(Object entity, TypeReference<T> typeReference, ResultCallback<T> resultCallback) {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.POST)
|
||||
.putHeader("content-type", "application/json")
|
||||
.bodyBytes(encode(entity))
|
||||
.build();
|
||||
|
||||
executeAndStream(
|
||||
request,
|
||||
resultCallback,
|
||||
new JsonSink<>(typeReference, resultCallback)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T post(TypeReference<T> typeReference, InputStream body) {
|
||||
try (InputStream inputStream = post(body)) {
|
||||
return objectMapper.readValue(inputStream, typeReference);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void post(Object entity, InputStream stdin, ResultCallback<Frame> resultCallback) {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.POST)
|
||||
.putHeader("content-type", "application/json")
|
||||
.bodyBytes(encode(entity))
|
||||
.hijackedInput(stdin)
|
||||
.build();
|
||||
|
||||
executeAndStream(
|
||||
request,
|
||||
resultCallback,
|
||||
new FlociFramedInputStreamConsumer(resultCallback)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void post(TypeReference<T> typeReference, ResultCallback<T> resultCallback, InputStream body) {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.POST)
|
||||
.body(body)
|
||||
.build();
|
||||
|
||||
executeAndStream(
|
||||
request,
|
||||
resultCallback,
|
||||
new JsonSink<>(typeReference, resultCallback)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postStream(InputStream body) {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.POST)
|
||||
.body(body)
|
||||
.build();
|
||||
|
||||
execute(request).close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream get() {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.GET)
|
||||
.build();
|
||||
|
||||
DockerHttpClient.Response response = execute(request);
|
||||
return new FilterInputStream(response.getBody()) {
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
try {
|
||||
super.close();
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(InputStream body, MediaType mediaType) {
|
||||
DockerHttpClient.Request request = requestBuilder
|
||||
.method(DockerHttpClient.Request.Method.PUT)
|
||||
.putHeader("content-type", mediaType.toString())
|
||||
.body(body)
|
||||
.build();
|
||||
|
||||
execute(request).close();
|
||||
}
|
||||
|
||||
private DockerHttpClient.Response execute(DockerHttpClient.Request request) {
|
||||
try {
|
||||
DockerHttpClient.Response response = dockerHttpClient.execute(request);
|
||||
int statusCode = response.getStatusCode();
|
||||
if (statusCode < 200 || statusCode > 299) {
|
||||
try {
|
||||
String body = IOUtils.toString(response.getBody(), StandardCharsets.UTF_8);
|
||||
switch (statusCode) {
|
||||
case 304:
|
||||
throw new NotModifiedException(body);
|
||||
case 400:
|
||||
throw new BadRequestException(body);
|
||||
case 401:
|
||||
throw new UnauthorizedException(body);
|
||||
case 404:
|
||||
throw new NotFoundException(body);
|
||||
case 406:
|
||||
throw new NotAcceptableException(body);
|
||||
case 409:
|
||||
throw new ConflictException(body);
|
||||
case 500:
|
||||
throw new InternalServerErrorException(body);
|
||||
default:
|
||||
throw new DockerException(body, statusCode);
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
} else {
|
||||
return response;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** How many stream callbacks are running, for the pool gauge line; virtual threads are not enumerable. */
|
||||
static int activeStreams() {
|
||||
return ACTIVE_STREAMS.get();
|
||||
}
|
||||
|
||||
// The one change from docker-java: the stream runs on a virtual thread instead of a platform thread of
|
||||
// its own, so a container's log follow, wait or exec stream no longer costs a platform thread while it
|
||||
// waits. Closing the stream interrupts the thread as before; a virtual thread blocked in a socket read is
|
||||
// released by the interrupt as well as by the close.
|
||||
private <T> void executeAndStream(
|
||||
DockerHttpClient.Request request,
|
||||
ResultCallback<T> callback,
|
||||
Consumer<DockerHttpClient.Response> sourceConsumer
|
||||
) {
|
||||
Thread.ofVirtual().name(DockerPoolGaugeLogger.STREAM_THREAD_PREFIX + Objects.hashCode(request)).start(() -> {
|
||||
ACTIVE_STREAMS.incrementAndGet();
|
||||
Thread streamingThread = Thread.currentThread();
|
||||
try (DockerHttpClient.Response response = execute(request)) {
|
||||
callback.onStart(() -> {
|
||||
streamingThread.interrupt();
|
||||
response.close();
|
||||
});
|
||||
|
||||
sourceConsumer.accept(response);
|
||||
callback.onComplete();
|
||||
} catch (Exception e) {
|
||||
callback.onError(e);
|
||||
} finally {
|
||||
ACTIVE_STREAMS.decrementAndGet();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private byte[] encode(Object entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return objectMapper.writeValueAsBytes(entity);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private class JsonSink<T> implements Consumer<DockerHttpClient.Response> {
|
||||
|
||||
private final TypeReference<T> typeReference;
|
||||
|
||||
private final ResultCallback<T> resultCallback;
|
||||
|
||||
JsonSink(TypeReference<T> typeReference, ResultCallback<T> resultCallback) {
|
||||
this.typeReference = typeReference;
|
||||
this.resultCallback = resultCallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(DockerHttpClient.Response response) {
|
||||
try {
|
||||
InputStream body = response.getBody();
|
||||
MappingIterator<Object> iterator = objectMapper.readerFor(typeReference).readValues(body);
|
||||
while (iterator.hasNextValue()) {
|
||||
resultCallback.onNext((T) iterator.nextValue());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
resultCallback.onError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,24 @@
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.core.DefaultDockerClientConfig;
|
||||
import com.github.dockerjava.transport.DockerHttpClient;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class DockerPoolGaugeLoggerTest {
|
||||
|
||||
@@ -47,26 +59,74 @@ class DockerPoolGaugeLoggerTest {
|
||||
DockerPoolGaugeLogger.line(Map.of("control-plane", waiting), () -> 0));
|
||||
}
|
||||
|
||||
// Catches: a docker-java stream read on a platform thread of its own again, or the gauge losing count
|
||||
// of the virtual ones, which no thread-group listing sees.
|
||||
@Test
|
||||
void streamThreadsAreCountedByTheDockerJavaPrefix() throws InterruptedException {
|
||||
int before = DockerPoolGaugeLogger.countStreamThreads();
|
||||
Object release = new Object();
|
||||
Thread thread = new Thread(() -> {
|
||||
synchronized (release) {
|
||||
try {
|
||||
release.wait();
|
||||
} catch (InterruptedException expected) {
|
||||
// The test interrupts it once counted.
|
||||
}
|
||||
void aStreamCallbackRunsOnAVirtualThreadAndIsCountedWhileItRuns() throws Exception {
|
||||
CountDownLatch inCallback = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicBoolean virtual = new AtomicBoolean();
|
||||
byte[] frame = {1, 0, 0, 0, 0, 0, 0, 5, 'h', 'e', 'l', 'l', 'o'};
|
||||
DockerHttpClient transport = new DockerHttpClient() {
|
||||
@Override
|
||||
public Response execute(Request request) {
|
||||
return new Response() {
|
||||
@Override
|
||||
public int getStatusCode() {
|
||||
return 200;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, List<String>> getHeaders() {
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getBody() {
|
||||
return new ByteArrayInputStream(frame);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
// Nothing to release.
|
||||
}
|
||||
};
|
||||
}
|
||||
}, DockerPoolGaugeLogger.STREAM_THREAD_PREFIX + "test");
|
||||
thread.setDaemon(true);
|
||||
thread.start();
|
||||
try {
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
// Nothing to release.
|
||||
}
|
||||
};
|
||||
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
|
||||
.withDockerHost("tcp://127.0.0.1:2375").build();
|
||||
int before = DockerPoolGaugeLogger.countStreamThreads();
|
||||
|
||||
try (DockerClient client = DockerClientProducer.newDockerClient(config, transport);
|
||||
ResultCallback.Adapter<Frame> callback = client.logContainerCmd("c1").withStdOut(true)
|
||||
.withFollowStream(true).exec(new ResultCallback.Adapter<>() {
|
||||
@Override
|
||||
public void onNext(Frame received) {
|
||||
virtual.set(Thread.currentThread().isVirtual());
|
||||
inCallback.countDown();
|
||||
try {
|
||||
release.await(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
})) {
|
||||
assertTrue(inCallback.await(5, TimeUnit.SECONDS), "the frame should reach the callback");
|
||||
assertTrue(virtual.get(), "the stream callback should run on a virtual thread");
|
||||
assertEquals(before + 1, DockerPoolGaugeLogger.countStreamThreads());
|
||||
} finally {
|
||||
thread.interrupt();
|
||||
thread.join(5_000);
|
||||
|
||||
release.countDown();
|
||||
assertTrue(callback.awaitCompletion(5, TimeUnit.SECONDS));
|
||||
}
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (DockerPoolGaugeLogger.countStreamThreads() != before && System.nanoTime() < deadline) {
|
||||
Thread.onSpinWait();
|
||||
}
|
||||
assertEquals(before, DockerPoolGaugeLogger.countStreamThreads(), "an ended stream is no longer counted");
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -94,7 +94,7 @@ class DockerPoolSaturationNightlyIntegrationTest {
|
||||
// Two streams per container, the log follow and the wait, and not one connection more.
|
||||
streamingTransport = DockerClientProducer.newHttpClient(clientConfig, 2 * CONTAINERS, RESPONSE_TIMEOUT,
|
||||
LEASE_TIMEOUT);
|
||||
streaming = DockerClientImpl.getInstance(clientConfig,
|
||||
streaming = DockerClientProducer.newDockerClient(clientConfig,
|
||||
DockerClientProducer.wrapForRole(streamingTransport, "streaming", RESPONSE_TIMEOUT));
|
||||
dockerAvailable = DockerAvailability.answers(control);
|
||||
Assumptions.assumeTrue(dockerAvailable, "Docker daemon is unavailable");
|
||||
@@ -164,7 +164,7 @@ class DockerPoolSaturationNightlyIntegrationTest {
|
||||
FlociDockerHttpClient.PoolGauges quiet = streamingTransport.gauges();
|
||||
assertEquals(2 * CONTAINERS, quiet.leased(), "every container should hold both of its streams: " + quiet);
|
||||
assertEquals(Map.of("logs", CONTAINERS, "wait", CONTAINERS), quiet.openStreams());
|
||||
// docker-java reads each stream on a thread of its own, so the threads grow with the streams too.
|
||||
// Each stream is read on a virtual thread of its own, counted while its callback runs.
|
||||
int streamThreads = DockerPoolGaugeLogger.countStreamThreads();
|
||||
assertTrue(streamThreads >= 2 * CONTAINERS, "one docker-java stream thread per open stream, counted "
|
||||
+ streamThreads);
|
||||
|
||||
Reference in new issue
Block a user