Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(core): reuse pooled Docker connections and validate them after a second idle (#5333)

Hector Ventura3b36a4d0d8c1
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/FlociDockerHttpClient.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/FlociDockerHttpClient.java
index c972ac6aae..6ed549fa8c 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/FlociDockerHttpClient.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/FlociDockerHttpClient.java
@@ -62,14 +62,24 @@ import java.util.stream.Stream;
* {@code ApacheDockerHttpClient} builds, owned here so Floci can set what that builder does not
* expose (idle-connection validation and eviction, the connection-lease timeout). It applies
* docker-java's settings (npipe and tcp hosts, TLS from the SSL config, a pool of
- * {@code maxConnections} for one route, no socket read timeout on the pool, no stale-connection
- * validation, hijacked exec/attach upgrades through {@link HijackingHttpRequestExecutor}) with two
- * differences: a {@code unix://} host connects through {@link UnixDomainSocket}, which honours read
+ * {@code maxConnections} for one route, no socket read timeout on the pool, hijacked exec/attach
+ * upgrades through {@link HijackingHttpRequestExecutor}), validates a pooled connection idle over a
+ * second before reusing it and evicts idle ones, where docker-java disabled both, and differs in two
+ * more ways: a {@code unix://} host connects through {@link UnixDomainSocket}, which honours read
* timeouts where docker-java's socket ignored them, and requests that hold a stream open get no
* response timeout ({@link #isLongLivedStream}), while every other call keeps it.
*/
public final class FlociDockerHttpClient implements DockerHttpClient {
+ /**
+ * A pooled connection idle this long is checked before it is leased again, so a socket the daemon
+ * (or Podman) already closed is replaced instead of failing on its next write. The check reads with
+ * a 1 ms timeout, which {@link UnixDomainSocket} honours.
+ */
+ static final TimeValue VALIDATE_AFTER_INACTIVITY = TimeValue.ofSeconds(1);
+ /** Idle pooled connections are closed in the background after this long. */
+ static final TimeValue EVICT_IDLE_AFTER = TimeValue.ofSeconds(30);
+
private final CloseableHttpClient httpClient;
private final HttpHost host;
private final String pathPrefix;
@@ -108,7 +118,7 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
connectionManager.setMaxTotal(maxConnections);
connectionManager.setDefaultMaxPerRoute(maxConnections);
connectionManager.setDefaultConnectionConfig(ConnectionConfig.custom()
- .setValidateAfterInactivity(TimeValue.NEG_ONE_SECOND)
+ .setValidateAfterInactivity(VALIDATE_AFTER_INACTIVITY)
.setConnectTimeout(connectionTimeout != null
? Timeout.of(connectionTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
.build());
@@ -124,6 +134,7 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
.setRequestExecutor(new HijackingHttpRequestExecutor(null))
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
+ .evictIdleConnections(EVICT_IDLE_AFTER)
.disableConnectionState()
.build();
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/RetryingDockerHttpClient.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/RetryingDockerHttpClient.java
index 632c9b1507..9db845dab2 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/RetryingDockerHttpClient.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/RetryingDockerHttpClient.java
@@ -6,8 +6,6 @@ import com.github.dockerjava.transport.DockerHttpClient;
import org.jboss.logging.Logger;
import java.io.IOException;
-import java.util.LinkedHashMap;
-import java.util.Map;
/**
* Decorates a {@link DockerHttpClient} with the {@link DockerRetry} policy so every docker call
@@ -56,9 +54,6 @@ public final class RetryingDockerHttpClient implements DockerHttpClient {
private static final Logger LOG = Logger.getLogger(RetryingDockerHttpClient.class);
private static final ObjectMapper JSON = new ObjectMapper();
- static final String CONNECTION_HEADER = "Connection";
- static final String CONNECTION_CLOSE = "close";
-
/**
* Mirrors the per-call-site policy this decorator replaces: six attempts at 500ms
* exponential backoff (capped by {@link DockerRetry#BACKOFF_CAP_MS}) rides out the
@@ -83,46 +78,10 @@ public final class RetryingDockerHttpClient implements DockerHttpClient {
@Override
public Response execute(Request request) {
- Request effectiveRequest = withConnectionClose(request);
- if (!isReplayable(effectiveRequest)) {
- return delegate.execute(effectiveRequest);
- }
- return DockerRetry.call(maxAttempts, backoffMillis, () -> delegate.execute(effectiveRequest));
- }
-
- /**
- * Retires every non-hijacked control-plane connection after its response instead of returning
- * it to docker-java's pool. The upstream Apache transport disables stale-connection validation,
- * so a Podman-closed pooled socket can otherwise be leased again and fail on its next write.
- *
- * <p>This is independent of retry eligibility: one-shot archive uploads and {@code /exec}
- * requests must not be replayed, but their successfully completed connections must not be
- * returned to the pool either. Hijacked requests remain unchanged because docker-java upgrades
- * those connections and manages their lifetime as streams.
- */
- static Request withConnectionClose(Request request) {
- if (request.hijackedInput() != null) {
- return request;
- }
-
- Map<String, String> headers = new LinkedHashMap<>();
- request.headers().forEach((name, value) -> {
- if (!CONNECTION_HEADER.equalsIgnoreCase(name)) {
- headers.put(name, value);
- }
- });
- headers.put(CONNECTION_HEADER, CONNECTION_CLOSE);
-
- Request.Builder builder = Request.builder()
- .method(request.method())
- .path(request.path())
- .headers(headers);
- if (request.bodyBytes() != null) {
- builder.bodyBytes(request.bodyBytes());
- } else if (request.body() != null) {
- builder.body(request.body());
+ if (!isReplayable(request)) {
+ return delegate.execute(request);
}
- return builder.build();
+ return DockerRetry.call(maxAttempts, backoffMillis, () -> delegate.execute(request));
}
/**
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/FlociDockerHttpClientTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/FlociDockerHttpClientTest.java
index 63ccd47cf6..e4d7efc3bf 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/FlociDockerHttpClientTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/FlociDockerHttpClientTest.java
@@ -25,6 +25,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -141,6 +142,107 @@ class FlociDockerHttpClientTest {
}
}
+ // Catches: a call that opens a new connection every time (as Connection: close forced) instead of
+ // reusing the pooled one.
+ @Test
+ @Timeout(60)
+ void consecutiveCallsReuseOnePooledConnection(@TempDir Path dir) throws Exception {
+ try (KeepAliveServer server = new KeepAliveServer(dir.resolve("docker.sock"), false);
+ FlociDockerHttpClient client = new FlociDockerHttpClient.Builder()
+ .dockerHost(URI.create("unix://" + server.path))
+ .responseTimeout(Duration.ofSeconds(5))
+ .build()) {
+ for (int i = 0; i < 3; i++) {
+ try (DockerHttpClient.Response response = client.execute(get("/_ping"))) {
+ assertEquals("ok", new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8));
+ }
+ }
+ assertEquals(1, server.connections.get(), "three calls should share one connection");
+ }
+ }
+
+ // Catches: leasing a pooled connection the daemon closed while it sat idle, which then fails on
+ // its next write; the validation after a second of inactivity must replace it.
+ @Test
+ @Timeout(60)
+ void aConnectionTheDaemonClosedWhileIdleIsReplacedBeforeReuse(@TempDir Path dir) throws Exception {
+ try (KeepAliveServer server = new KeepAliveServer(dir.resolve("docker.sock"), true);
+ FlociDockerHttpClient client = new FlociDockerHttpClient.Builder()
+ .dockerHost(URI.create("unix://" + server.path))
+ .responseTimeout(Duration.ofSeconds(5))
+ .build()) {
+ try (DockerHttpClient.Response response = client.execute(get("/_ping"))) {
+ response.getBody().readAllBytes();
+ }
+ Thread.sleep(1_500);
+ // A POST, which httpclient5 never re-sends by itself, so only the validation can save it.
+ try (DockerHttpClient.Response response = client.execute(DockerHttpClient.Request.builder()
+ .method(DockerHttpClient.Request.Method.POST).path("/containers/abc/stop").build())) {
+ assertEquals("ok", new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8));
+ }
+ assertEquals(2, server.connections.get(), "the closed connection should have been replaced");
+ }
+ }
+
+ /** Answers every request with a keep-alive 200 "ok"; optionally closes each connection after one answer. */
+ private static final class KeepAliveServer implements AutoCloseable {
+
+ private final Path path;
+ private final ServerSocketChannel server;
+ private final AtomicInteger connections = new AtomicInteger();
+ private final List<SocketChannel> channels = new CopyOnWriteArrayList<>();
+
+ KeepAliveServer(Path path, boolean closeAfterOneAnswer) throws IOException {
+ this.path = path;
+ this.server = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
+ server.bind(UnixDomainSocketAddress.of(path));
+ Thread.ofVirtual().start(() -> {
+ try {
+ while (true) {
+ SocketChannel channel = server.accept();
+ connections.incrementAndGet();
+ channels.add(channel);
+ Thread.ofVirtual().start(() -> serve(channel, closeAfterOneAnswer));
+ }
+ } catch (IOException expected) {
+ // The server channel closed at the end of the test.
+ }
+ });
+ }
+
+ private static void serve(SocketChannel channel, boolean closeAfterOneAnswer) {
+ try {
+ ByteBuffer buffer = ByteBuffer.allocate(4096);
+ StringBuilder pending = new StringBuilder();
+ while (channel.read(buffer) != -1) {
+ buffer.flip();
+ pending.append(StandardCharsets.UTF_8.decode(buffer));
+ buffer.clear();
+ int end;
+ while ((end = pending.indexOf("\r\n\r\n")) >= 0) {
+ pending.delete(0, end + 4);
+ channel.write(ByteBuffer.wrap(("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
+ .getBytes(StandardCharsets.UTF_8)));
+ if (closeAfterOneAnswer) {
+ channel.close();
+ return;
+ }
+ }
+ }
+ } catch (IOException expected) {
+ // The client or the test closed the connection.
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ server.close();
+ for (SocketChannel channel : channels) {
+ channel.close();
+ }
+ }
+ }
+
@Test
void streamingEndpointsAreRecognisedAndOrdinaryCallsAreNot() {
for (String streaming : List.of("POST /v1.43/containers/abc/wait", "POST /exec/xyz/start",
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/RetryingDockerHttpClientTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/RetryingDockerHttpClientTest.java
index ebcefa5356..43b266275c 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/RetryingDockerHttpClientTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/RetryingDockerHttpClientTest.java
@@ -113,30 +113,21 @@ class RetryingDockerHttpClientTest {
}
@Test
- void injectsCanonicalCloseWhilePreservingRequestDataAndHeaders() {
+ void passesTheRequestToTheTransportUnchanged() {
+ // Catches: the wrapper rebuilding requests (it once forced Connection: close on each one, which
+ // stopped the pool from ever reusing a connection).
Response ok = mock(Response.class);
FakeTransport delegate = new FakeTransport(attempt -> ok);
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
-
- byte[] body = "{\"Image\":\"busybox\"}".getBytes(StandardCharsets.UTF_8);
Request create = Request.builder()
.method(Request.Method.POST)
- .path("/containers/create")
- .bodyBytes(body)
+ .path("/containers/create?name=floci-x")
+ .bodyBytes("{\"Image\":\"busybox\"}".getBytes(StandardCharsets.UTF_8))
.putHeader("Content-Type", "application/json")
- .putHeader("connection", "keep-alive")
.build();
assertSame(ok, client.execute(create));
- Request effective = delegate.seenRequests.get(0);
- assertEquals(create.method(), effective.method());
- assertEquals(create.path(), effective.path());
- assertSame(body, effective.bodyBytes());
- assertEquals("application/json", effective.headers().get("Content-Type"));
- assertEquals("close", effective.headers().get("Connection"));
- assertEquals(1, effective.headers().entrySet().stream()
- .filter(entry -> "Connection".equalsIgnoreCase(entry.getKey()))
- .count(), "the transport must receive one unambiguous Connection header");
+ assertSame(create, delegate.seenRequests.get(0));
}
@Test
@@ -161,8 +152,7 @@ class RetryingDockerHttpClientTest {
assertEquals(1, delegate.calls.get(),
"a one-shot stream body cannot be replayed; the transport must not retry it");
assertSame(tar, delegate.seenRequests.get(0).body(),
- "adding Connection: close must preserve the one-shot stream object");
- assertEquals("close", delegate.seenRequests.get(0).headers().get("Connection"));
+ "the one-shot stream object must reach the transport");
}
@Test
@@ -205,8 +195,6 @@ class RetryingDockerHttpClientTest {
assertThrows(RuntimeException.class, () -> startClient.execute(execStart));
assertEquals(1, startDelegate.calls.get(),
"exec-start re-runs the command if replayed; it must surface after one attempt");
- assertEquals("close", startDelegate.seenRequests.get(0).headers().get("Connection"),
- "non-replayable exec control calls must still retire their connection");
// The exclusion is contains("/exec"), not startsWith: exec-create
// (POST /containers/{id}/exec) is also excluded, and this pins that breadth so a later