feat(docker): log how busy the Docker connection pools are (#8829)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-18 07:22:12 -04:00
1 parent 51fd7950e1
commit 9c8734b41f
13 files changed
+438 -17

No files matched your search

@@ -133,6 +133,7 @@ floci:
docker-host: unix:///var/run/docker.sock # Docker daemon socket (shared by Lambda, RDS, ElastiCache)
max-connections: 1024 # Docker client connection pool for short calls
streaming-max-connections: 2048 # Separate pool for streams; each live Lambda container holds 2, plus 1 per extension
pool-gauge-interval-seconds: 60 # Log Docker pool use every N seconds while a pool is busy; 0 = off
docker-config-path: "" # Path to dir containing Docker's config.json (e.g. /root/.docker)
registry-credentials: [] # Per-registry explicit credentials for private registries
+16
View File
@@ -104,6 +104,22 @@ floci:
Environment variable: `FLOCI_DOCKER_IMAGE_PULL_TIMEOUT_SECONDS`
To see how close Floci is to those limits, it logs a line every `pool-gauge-interval-seconds` (60 by default) while a pool is in use, and nothing while both are idle. Each pool reports its leased, available and pending connections against its limit and its open streams by kind, followed by the number of docker-java stream threads:
```
Docker pools: control-plane leased=2 available=6 pending=0 max=1024; streaming leased=40 available=0 pending=0 max=2048 streams[logs=20 wait=20]; stream threads=40
```
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
floci:
docker:
pool-gauge-interval-seconds: 0
```
Environment variable: `FLOCI_DOCKER_POOL_GAUGE_INTERVAL_SECONDS`
## Private Registry Authentication
Any service that pulls a container image from a private registry (Lambda image functions, custom OpenSearch images, private Postgres images, etc.) needs Docker credentials. Two approaches are supported and can be combined.
@@ -148,6 +148,7 @@ This foundation release provides opt-in security-group filtering for EC2 Docker
| `FLOCI_DOCKER_DOCKER_CONFIG_PATH` | _(none)_ | Path to a directory containing Docker's `config.json` for registry auth |
| `FLOCI_DOCKER_MAX_CONNECTIONS` | `1024` | Connection pool size for Floci's short Docker calls, plus CodeBuild phase commands, EKS audit log followers and ECS Exec sessions. See [Docker Configuration](docker.md#connection-pool) |
| `FLOCI_DOCKER_STREAMING_MAX_CONNECTIONS` | `2048` | Connection pool size for streams that last a container's lifetime, kept apart from the main pool so they never starve create, start, stop and remove. Each live Lambda container holds two (log stream and exit watcher) plus one per extension. See [Docker Configuration](docker.md#connection-pool) |
| `FLOCI_DOCKER_POOL_GAUGE_INTERVAL_SECONDS` | `60` | Seconds between the log lines that report each Docker pool's leased, available and pending connections and its open streams, written only while a pool is in use; `0` turns them off. See [Docker Configuration](docker.md#connection-pool) |
| `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` | _(none)_ | Optional registry/repository base for every Docker image Floci launches. When set, `postgres:16-alpine` resolves as `<base>/postgres:16-alpine` and `public.ecr.aws/docker/library/ubuntu:24.04` resolves as `<base>/public.ecr.aws/docker/library/ubuntu:24.04`. An image in a registry on `localhost` or a loopback address, Floci's own ECR among them, is launched as it is |
| `FLOCI_DOCKER_LOG_MAX_SIZE` | `10m` | Log rotation max size for spawned containers (e.g. `10m`, `1g`) |
| `FLOCI_DOCKER_LOG_MAX_FILE` | `3` | Number of rotated log files to keep for spawned containers |
@@ -4400,6 +4400,15 @@ public interface EmulatorConfig {
@WithDefault("300")
int imagePullTimeoutSeconds();
/**
* Seconds between the log lines that report how busy the Docker connection pools are: each
* pool's leased, available and pending connections against its limit, its open long-lived
* streams by kind, and the docker-java stream threads. A line is written only while a pool is in
* use, so an idle emulator logs nothing. 0 turns the lines off.
*/
@WithDefault("60")
int poolGaugeIntervalSeconds();
/**
* Optional namespace inserted into Floci-managed child container and volume names.
* Useful when multiple Floci processes share one Docker daemon.
@@ -56,10 +56,13 @@ public class DockerClientProducer {
private static final ObjectMapper DOCKER_CONTEXT_JSON_MAPPER = new ObjectMapper();
private final EmulatorConfig config;
private final DockerPoolGaugeLogger gaugeLogger;
@Inject
public DockerClientProducer(EmulatorConfig config) {
this.config = config;
this.gaugeLogger = new DockerPoolGaugeLogger(
validatePoolGaugeIntervalSeconds(config.docker().poolGaugeIntervalSeconds()));
}
/**
@@ -414,6 +417,15 @@ public class DockerClientProducer {
"FLOCI_DOCKER_IMAGE_PULL_TIMEOUT_SECONDS");
}
/** 0 turns the pool gauge lines off; a negative interval names no schedule. */
static int validatePoolGaugeIntervalSeconds(int seconds) {
if (seconds < 0) {
throw new IllegalArgumentException("floci.docker.pool-gauge-interval-seconds "
+ "(FLOCI_DOCKER_POOL_GAUGE_INTERVAL_SECONDS) must be 0 or more, got: " + seconds);
}
return seconds;
}
private static int requireAtLeastOne(int value, String setting, String envVar) {
if (value < 1) {
throw new IllegalArgumentException(setting + " (" + envVar + ") must be at least 1, got: " + value);
@@ -452,10 +464,12 @@ public class DockerClientProducer {
}
void disposeDockerClient(@Disposes DockerClient client) throws IOException {
gaugeLogger.unregister("control-plane");
client.close();
}
void disposeStreamingDockerClient(@Disposes @StreamingDocker DockerClient client) throws IOException {
gaugeLogger.unregister("streaming");
client.close();
}
@@ -499,10 +513,12 @@ public class DockerClientProducer {
LOG.infov("Creating {0} DockerClient pool (maxConnections={1}) for host: {2}",
role, maxConnections, clientConfig.getDockerHost());
return DockerClientImpl.getInstance(clientConfig, wrapForRole(newHttpClient(clientConfig, maxConnections,
FlociDockerHttpClient transport = newHttpClient(clientConfig, maxConnections,
Duration.ofSeconds(validateApiTimeoutSeconds(config.docker().apiTimeoutSeconds())),
Duration.ofSeconds(validateConnectionRequestTimeoutSeconds(
config.docker().connectionRequestTimeoutSeconds()))), role));
config.docker().connectionRequestTimeoutSeconds())));
gaugeLogger.register(role, transport::gauges);
return DockerClientImpl.getInstance(clientConfig, wrapForRole(transport, role));
}
static FlociDockerHttpClient newHttpClient(DefaultDockerClientConfig clientConfig, int maxConnections,
@@ -0,0 +1,127 @@
package io.floci.aws.core.common.docker;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
/**
* Logs how busy the Docker connection pools are, once per interval: for each pool its leased,
* available and pending connections against its limit and its open long-lived streams by kind, then
* the number of docker-java stream threads. A line is written only while some pool has a lease, a
* caller waiting for one, or an open stream, so an idle emulator logs nothing. It is the measurement
* the Docker admission work is sized from (BL-215); there is no metrics endpoint.
*
* <p>Owned by {@link DockerClientProducer}, which registers each pool as its client is built and
* removes it when the client is disposed. The background thread starts with the first pool and
* stops with the last; an interval of 0 never starts it.
*/
final class DockerPoolGaugeLogger {
private static final Logger LOG = Logger.getLogger(DockerPoolGaugeLogger.class);
/** docker-java names the threads that read stream callbacks with this prefix. */
static final String STREAM_THREAD_PREFIX = "docker-java-stream-";
private final long intervalSeconds;
private final Map<String, Supplier<FlociDockerHttpClient.PoolGauges>> pools = new ConcurrentSkipListMap<>();
private ScheduledExecutorService executor;
/** @param intervalSeconds seconds between readings, or 0 to never log */
DockerPoolGaugeLogger(long intervalSeconds) {
this.intervalSeconds = intervalSeconds;
}
synchronized void register(String role, Supplier<FlociDockerHttpClient.PoolGauges> gauges) {
pools.put(role, gauges);
if (intervalSeconds > 0 && executor == null) {
executor = Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, "docker-pool-gauges");
thread.setDaemon(true);
return thread;
});
executor.scheduleWithFixedDelay(this::logSafely, intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
}
}
synchronized void unregister(String role) {
pools.remove(role);
if (pools.isEmpty() && executor != null) {
executor.shutdownNow();
executor = null;
}
}
private void logSafely() {
try {
String line = line(readings(), DockerPoolGaugeLogger::countStreamThreads);
if (line != null) {
LOG.infov("Docker pools: {0}", line);
}
} catch (RuntimeException e) {
LOG.debugv(e, "Could not read the Docker pool gauges");
}
}
private Map<String, FlociDockerHttpClient.PoolGauges> readings() {
Map<String, FlociDockerHttpClient.PoolGauges> readings = new ConcurrentSkipListMap<>();
pools.forEach((role, gauges) -> readings.put(role, gauges.get()));
return readings;
}
/**
* The text of one reading, pools in name order, or null when every pool is idle, in which case the
* stream threads are not counted. For example
* {@code control-plane leased=2 available=6 pending=0 max=1024; streaming leased=40 available=0
* pending=0 max=2048 streams[logs=20 wait=20]; stream threads=40}.
*/
static String line(Map<String, FlociDockerHttpClient.PoolGauges> readings, IntSupplier streamThreads) {
if (readings.values().stream().allMatch(FlociDockerHttpClient.PoolGauges::idle)) {
return null;
}
List<String> parts = new ArrayList<>();
readings.forEach((role, reading) -> {
StringBuilder part = new StringBuilder(role)
.append(" leased=").append(reading.leased())
.append(" available=").append(reading.available())
.append(" pending=").append(reading.pending())
.append(" max=").append(reading.max());
if (!reading.openStreams().isEmpty()) {
List<String> streams = new ArrayList<>();
reading.openStreams().forEach((kind, open) -> streams.add(kind + "=" + open));
part.append(" streams[").append(String.join(" ", streams)).append(']');
}
parts.add(part.toString());
});
parts.add("stream threads=" + streamThreads.getAsInt());
return String.join("; ", parts);
}
/** Counts the live docker-java stream threads by name, without capturing any thread's stack. */
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;
}
}
@@ -42,6 +42,7 @@ import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.http.protocol.HttpCoreContext;
import org.apache.hc.core5.net.URIAuthority;
import org.apache.hc.core5.pool.PoolStats;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.jboss.logging.Logger;
@@ -55,7 +56,11 @@ import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -87,6 +92,9 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
static final TimeValue EVICT_IDLE_AFTER = TimeValue.ofSeconds(30);
private final CloseableHttpClient httpClient;
private final PoolingHttpClientConnectionManager connectionManager;
/** Responses still open per {@link #streamKind} of the request that opened them. */
private final Map<String, AtomicInteger> openStreams = new ConcurrentHashMap<>();
private final HttpHost host;
private final String pathPrefix;
/** The same settings with no response timeout, for requests that hold a stream open (see isLongLivedStream). */
@@ -111,7 +119,7 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
String rawPath = "tcp".equals(dockerHost.getScheme()) ? dockerHost.getRawPath() : "";
pathPrefix = rawPath.endsWith("/") ? rawPath.substring(0, rawPath.length() - 1) : rawPath;
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
connectionManager = new PoolingHttpClientConnectionManager(
connectionOperator, null, null, null,
new ManagedHttpClientConnectionFactory(null, null, null, null,
FlociDockerHttpClient::determineLength, null));
@@ -198,7 +206,8 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
httpRequest.setEntity(new InputStreamEntity(request.body(), null));
}
if (isLongLivedStream(request)) {
String streamKind = streamKind(request);
if (streamKind != null) {
httpRequest.setConfig(streamRequestConfig);
}
@@ -211,7 +220,12 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
try {
boolean ttyExec = isTtyExec(request);
ClassicHttpResponse response = httpClient.executeOpen(host, httpRequest, context);
return new FlociResponse(httpRequest, response, ttyExec && response.getCode() == 200);
AtomicInteger openOfKind = null;
if (streamKind != null) {
openOfKind = openStreams.computeIfAbsent(streamKind, kind -> new AtomicInteger());
openOfKind.incrementAndGet();
}
return new FlociResponse(httpRequest, response, ttyExec && response.getCode() == 200, openOfKind);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (LinkageError e) {
@@ -230,6 +244,31 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
httpClient.close();
}
/**
* The pool's leased, available and pending connections and its limit, and the long-lived stream
* responses still open by kind (only kinds with an open stream are listed), read at this moment.
*/
public PoolGauges gauges() {
PoolStats stats = connectionManager.getTotalStats();
Map<String, Integer> streams = new TreeMap<>();
openStreams.forEach((kind, open) -> {
int count = open.get();
if (count > 0) {
streams.put(kind, count);
}
});
return new PoolGauges(stats.getLeased(), stats.getAvailable(), stats.getPending(), stats.getMax(), streams);
}
/** A point-in-time reading of one pool, see {@link #gauges()}. */
public record PoolGauges(int leased, int available, int pending, int max, Map<String, Integer> openStreams) {
/** Whether nothing is in use: no lease, no caller waiting for one and no stream open. */
public boolean idle() {
return leased == 0 && pending == 0 && openStreams.isEmpty();
}
}
private static boolean isTtyExec(Request request) throws IOException {
String route = request.path().split("\\?", 2)[0];
if (!"POST".equals(request.method()) || !route.contains("/exec/") || !route.endsWith("/start")
@@ -248,22 +287,47 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
* none. Every other call keeps the response timeout.
*/
static boolean isLongLivedStream(Request request) {
if (request.hijackedInput() != null) {
return true;
}
return streamKind(request) != null;
}
/**
* The kind of long-lived stream a request opens ({@code wait}, {@code attach}, {@code exec},
* {@code build}, {@code pull}, {@code events}, {@code logs}, {@code stats}, or {@code hijacked} for
* another upgraded connection), or null for an ordinary call. See {@link #isLongLivedStream}.
*/
static String streamKind(Request request) {
String path = request.path();
int queryStart = path.indexOf('?');
String route = queryStart < 0 ? path : path.substring(0, queryStart);
String query = queryStart < 0 ? "" : path.substring(queryStart + 1);
return switch (request.method()) {
case "POST" -> route.endsWith("/wait") || route.endsWith("/attach") || route.endsWith("/build")
|| route.endsWith("/images/create")
|| (route.contains("/exec/") && route.endsWith("/start"));
case "GET" -> route.endsWith("/events")
|| (route.endsWith("/logs") && queryFlag(query, "follow", false))
|| (route.endsWith("/stats") && queryFlag(query, "stream", true));
default -> false;
String kind = switch (request.method()) {
case "POST" -> {
if (route.endsWith("/wait")) {
yield "wait";
} else if (route.endsWith("/attach")) {
yield "attach";
} else if (route.endsWith("/build")) {
yield "build";
} else if (route.endsWith("/images/create")) {
yield "pull";
} else if (route.contains("/exec/") && route.endsWith("/start")) {
yield "exec";
}
yield null;
}
case "GET" -> {
if (route.endsWith("/events")) {
yield "events";
} else if (route.endsWith("/logs") && queryFlag(query, "follow", false)) {
yield "logs";
} else if (route.endsWith("/stats") && queryFlag(query, "stream", true)) {
yield "stats";
}
yield null;
}
default -> null;
};
return kind == null && request.hijackedInput() != null ? "hijacked" : kind;
}
/** A boolean query parameter as Docker reads it ({@code 1} or {@code true}), or its default when absent. */
@@ -335,12 +399,17 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
private final HttpUriRequestBase request;
private final ClassicHttpResponse response;
private final boolean ttyExec;
/** The open-stream count this response is in, or null for an ordinary call. */
private final AtomicInteger openOfKind;
private final AtomicBoolean closed = new AtomicBoolean();
private InputStream body;
FlociResponse(HttpUriRequestBase request, ClassicHttpResponse response, boolean ttyExec) {
FlociResponse(HttpUriRequestBase request, ClassicHttpResponse response, boolean ttyExec,
AtomicInteger openOfKind) {
this.request = request;
this.response = response;
this.ttyExec = ttyExec;
this.openOfKind = openOfKind;
}
@Override
@@ -377,6 +446,9 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
@Override
public void close() {
if (openOfKind != null && closed.compareAndSet(false, true)) {
openOfKind.decrementAndGet();
}
try {
request.abort();
} catch (Exception e) {
+5
View File
@@ -427,6 +427,11 @@ floci:
# Keep in step with the @WithDefault on EmulatorConfig.DockerConfig.imagePullTimeoutSeconds: a value
# set here WINS over the annotation.
image-pull-timeout-seconds: 300
# FLOCI_DOCKER_POOL_GAUGE_INTERVAL_SECONDS: seconds between the log lines that report each Docker
# pool's leased, available and pending connections, its open streams by kind and the stream
# threads, written only while a pool is in use; 0 turns them off. Keep in step with the
# @WithDefault on EmulatorConfig.DockerConfig.poolGaugeIntervalSeconds: a value set here WINS over the annotation.
pool-gauge-interval-seconds: 60
resource-namespace: "" # FLOCI_DOCKER_RESOURCE_NAMESPACE; scopes child container/volume names
docker-config-path: ""
# extra-labels: # Extra Docker labels applied to every Floci-created container and volume
@@ -202,4 +202,22 @@ class ApplicationDefaultsTest {
assertEquals("300", fallback.value(),
"the @WithDefault must match application.yml, which wins over it");
}
// Catches: pool-gauge-interval-seconds missing from the shipped application.yml, or a yml value
// that silently disagrees with the @WithDefault fallback.
@Test
void productionConfigDeclaresTheDockerPoolGaugeIntervalAtItsDefault() throws IOException, NoSuchMethodException {
JsonNode interval = productionConfig()
.path("floci").path("docker").path("pool-gauge-interval-seconds");
assertFalse(interval.isMissingNode(), "pool-gauge-interval-seconds should be declared in application.yml");
assertEquals(60, interval.asInt());
WithDefault fallback = EmulatorConfig.DockerConfig.class
.getMethod("poolGaugeIntervalSeconds")
.getAnnotation(WithDefault.class);
assertNotNull(fallback, "poolGaugeIntervalSeconds should declare a fallback default");
assertEquals("60", fallback.value(),
"the @WithDefault must match application.yml, which wins over it");
}
}
@@ -702,6 +702,20 @@ class DockerClientProducerTest {
assertThat(e.getMessage(), containsString("floci.docker.image-pull-timeout-seconds"));
}
@Test
void validatePoolGaugeIntervalSeconds_negative_throwsNamingTheSetting() {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> DockerClientProducer.validatePoolGaugeIntervalSeconds(-1));
assertThat(e.getMessage(), containsString("floci.docker.pool-gauge-interval-seconds"));
}
@Test
void validatePoolGaugeIntervalSeconds_zeroOrPositive_returnsItUnchanged() {
assertEquals(0, DockerClientProducer.validatePoolGaugeIntervalSeconds(0));
assertEquals(60, DockerClientProducer.validatePoolGaugeIntervalSeconds(60));
}
@Test
void validateImagePullTimeoutSeconds_positive_returnsItUnchanged() {
assertEquals(1, DockerClientProducer.validateImagePullTimeoutSeconds(1));
@@ -0,0 +1,69 @@
package io.floci.aws.core.common.docker;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.TreeMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class DockerPoolGaugeLoggerTest {
private static final FlociDockerHttpClient.PoolGauges IDLE =
new FlociDockerHttpClient.PoolGauges(0, 3, 0, 1024, Map.of());
// Catches: an idle emulator writing a pool line every interval, or paying for a thread scan on a
// reading that writes nothing.
@Test
void noLineAndNoThreadCountWhileEveryPoolIsIdle() {
assertNull(DockerPoolGaugeLogger.line(Map.of("control-plane", IDLE, "streaming", IDLE), () -> {
throw new AssertionError("stream threads counted for an idle reading");
}));
}
@Test
void aBusyPoolReportsEveryPoolInNameOrderWithItsStreamsAndTheStreamThreads() {
Map<String, FlociDockerHttpClient.PoolGauges> readings = new TreeMap<>();
readings.put("streaming", new FlociDockerHttpClient.PoolGauges(40, 0, 0, 2048,
new TreeMap<>(Map.of("wait", 20, "logs", 20))));
readings.put("control-plane", IDLE);
assertEquals("control-plane leased=0 available=3 pending=0 max=1024; "
+ "streaming leased=40 available=0 pending=0 max=2048 streams[logs=20 wait=20]; "
+ "stream threads=40",
DockerPoolGaugeLogger.line(readings, () -> 40));
}
// Catches: callers waiting on a full pool reading as idle because no connection is leased yet.
@Test
void aCallerWaitingForAConnectionIsNotIdle() {
FlociDockerHttpClient.PoolGauges waiting = new FlociDockerHttpClient.PoolGauges(0, 0, 2, 1, Map.of());
assertEquals("control-plane leased=0 available=0 pending=2 max=1; stream threads=0",
DockerPoolGaugeLogger.line(Map.of("control-plane", waiting), () -> 0));
}
@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.
}
}
}, DockerPoolGaugeLogger.STREAM_THREAD_PREFIX + "test");
thread.setDaemon(true);
thread.start();
try {
assertEquals(before + 1, DockerPoolGaugeLogger.countStreamThreads());
} finally {
thread.interrupt();
thread.join(5_000);
}
}
}
@@ -23,7 +23,9 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
@@ -33,6 +35,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -323,6 +326,75 @@ class FlociDockerHttpClientTest {
}
}
@Test
void streamKindNamesEachLongLivedStream() {
Map<String, String> expected = new LinkedHashMap<>();
expected.put("POST /containers/abc/wait", "wait");
expected.put("POST /containers/abc/attach?stream=1", "attach");
expected.put("POST /exec/abc/start", "exec");
expected.put("POST /build?t=x", "build");
expected.put("POST /images/create?fromImage=alpine", "pull");
expected.put("GET /events", "events");
expected.put("GET /containers/abc/logs?follow=1&stdout=1", "logs");
expected.put("GET /containers/abc/stats", "stats");
expected.forEach((methodAndPath, kind) ->
assertEquals(kind, FlociDockerHttpClient.streamKind(request(methodAndPath)), methodAndPath));
assertNull(FlociDockerHttpClient.streamKind(request("GET /containers/abc/logs?stdout=1")));
assertNull(FlociDockerHttpClient.streamKind(request("GET /containers/abc/stats?stream=0")));
assertNull(FlociDockerHttpClient.streamKind(request("POST /containers/abc/start")));
}
// Catches: gauges that do not follow the pool, so a held stream reads as idle or a closed one
// stays counted, and the pool log line would report the wrong pressure.
@Test
@Timeout(30)
void gaugesCountALeaseAndItsOpenStreamUntilTheResponseCloses() throws Exception {
List<Socket> accepted = new CopyOnWriteArrayList<>();
try (ServerSocket server = new ServerSocket(0)) {
Thread acceptor = Thread.ofVirtual().start(() -> {
try {
while (true) {
Socket socket = server.accept();
accepted.add(socket);
// Answer the headers of a chunked body that never ends, as a container wait does.
socket.getOutputStream().write(("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
+ "Transfer-Encoding: chunked\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
socket.getOutputStream().flush();
}
} catch (IOException expected) {
// The server socket closed at the end of the test.
}
});
try (FlociDockerHttpClient client = new FlociDockerHttpClient.Builder()
.dockerHost(URI.create("tcp://127.0.0.1:" + server.getLocalPort()))
.maxConnections(4)
.responseTimeout(Duration.ofSeconds(30))
.connectionRequestTimeout(Duration.ofSeconds(5))
.build()) {
assertTrue(client.gauges().idle(), "a new pool should be idle: " + client.gauges());
DockerHttpClient.Response wait = client.execute(request("POST /containers/held/wait"));
FlociDockerHttpClient.PoolGauges held = client.gauges();
assertEquals(1, held.leased(), held.toString());
assertEquals(4, held.max(), held.toString());
assertEquals(Map.of("wait", 1), held.openStreams());
assertFalse(held.idle());
wait.close();
wait.close();
FlociDockerHttpClient.PoolGauges released = client.gauges();
assertEquals(0, released.leased(), released.toString());
assertEquals(Map.of(), released.openStreams(), "a closed stream, closed twice, counts once");
assertTrue(released.idle(), released.toString());
} finally {
for (Socket socket : accepted) {
socket.close();
}
acceptor.interrupt();
}
}
}
private static DockerHttpClient.Request request(String methodAndPath) {
String[] parts = methodAndPath.split(" ", 2);
return DockerHttpClient.Request.builder().method(parts[0]).path(parts[1]).build();
+1
View File
@@ -137,6 +137,7 @@ floci:
log-max-size: "10m"
log-max-file: "3"
resource-namespace: ""
pool-gauge-interval-seconds: 0 # no pool gauge lines in test output
services:
ssm: