feat(docker): limit concurrent container creates and starts (#9049)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-21 12:24:20 -04:00
1 parent 1037f592fe
commit 6de2461693
10 files changed
+464 -14

No files matched your search

@@ -136,6 +136,7 @@ floci:
pool-gauge-interval-seconds: 60 # Log Docker pool use every N seconds while a pool is busy; 0 = off
breaker-failure-threshold: 3 # Consecutive Docker call attempts (each retry counts) failing at the transport before Floci pings the daemon and fails calls fast if it is gone; 0 = off
breaker-probe-interval-seconds: 5 # Seconds between pings while the daemon is unreachable
max-concurrent-launches: 0 # Most container creates and starts at once; 0 = twice the CPUs, at least 4
docker-config-path: "" # Path to dir containing Docker's config.json (e.g. /root/.docker)
registry-credentials: [] # Per-registry explicit credentials for private registries
+13
View File
@@ -135,6 +135,18 @@ floci:
Environment variables: `FLOCI_DOCKER_BREAKER_FAILURE_THRESHOLD`, `FLOCI_DOCKER_BREAKER_PROBE_INTERVAL_SECONDS`
### Concurrent container launches
Floci sends at most `max-concurrent-launches` container creates and starts to the daemon at once, so a burst of container work (a pipeline stage starting a dozen containers, a fan-out of Lambda cold starts) reaches it a few at a time instead of all at once. The rest wait up to `connection-request-timeout-seconds` for one to finish, and a launch that waits longer fails. The default, 0, means twice the CPUs Floci sees and at least 4. Image pulls, stops, removes and every other Docker call are not limited by it:
```yaml
floci:
docker:
max-concurrent-launches: 0
```
Environment variable: `FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES`
## 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.
@@ -383,6 +395,7 @@ caller keeps its existing failure handling after retries are exhausted.
| `FLOCI_DOCKER_MAX_CONNECTIONS` | `1024` | Connection pool size for Floci's short Docker calls |
| `FLOCI_DOCKER_BREAKER_FAILURE_THRESHOLD` | `3` | Docker call attempts in a row (each retry counts) that fail before the daemon answers, after which a failed ping makes every Docker call fail at once until the daemon answers again; `0` turns this off |
| `FLOCI_DOCKER_BREAKER_PROBE_INTERVAL_SECONDS` | `5` | Seconds between the pings that check whether an unreachable Docker daemon is back |
| `FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES` | `0` | Most container creates and starts sent to the daemon at once; `0` means twice the CPUs Floci sees, at least 4 |
| `FLOCI_DOCKER_STREAMING_MAX_CONNECTIONS` | `3072` | Connection pool size for streams that last a container's lifetime or a long command's run. Each live Lambda container holds two (log stream and exit watcher) plus one per extension, and each CodeBuild phase, SSM command, ECS Exec session, EKS audit follower, user data script and EMR bootstrap action one |
| `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__SERVER` | _(unset)_ | Registry hostname for credential entry 0 |
| `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__USERNAME` | _(unset)_ | Username for credential entry 0 |
@@ -151,6 +151,7 @@ This foundation release provides opt-in security-group filtering for EC2 Docker
| `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_BREAKER_FAILURE_THRESHOLD` | `3` | Docker call attempts in a row (each retry counts) that fail before the daemon answers, after which a failed ping makes every Docker call fail at once until the daemon answers again; `0` turns this off. See [Docker Configuration](docker.md#unreachable-daemon) |
| `FLOCI_DOCKER_BREAKER_PROBE_INTERVAL_SECONDS` | `5` | Seconds between the pings that check whether an unreachable Docker daemon is back |
| `FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES` | `0` | Most container creates and starts sent to the Docker daemon at once; `0` means twice the CPUs Floci sees, at least 4. See [Docker Configuration](docker.md#concurrent-container-launches) |
| `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 |
@@ -4518,6 +4518,14 @@ public interface EmulatorConfig {
@WithDefault("5")
int breakerProbeIntervalSeconds();
/**
* Most container creates and starts sent to the Docker daemon at once; more wait, up to
* {@link #connectionRequestTimeoutSeconds}, for one to finish. 0 means twice the CPUs Floci
* sees, and at least 4. Image pulls, stops, removes and every other call are not limited here.
*/
@WithDefault("0")
int maxConcurrentLaunches();
/**
* Optional namespace inserted into Floci-managed child container and volume names.
* Useful when multiple Floci processes share one Docker daemon.
@@ -428,20 +428,14 @@ public class DockerClientProducer {
/** 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;
return requireAtLeastZero(seconds, "floci.docker.pool-gauge-interval-seconds",
"FLOCI_DOCKER_POOL_GAUGE_INTERVAL_SECONDS");
}
/** 0 turns the Docker circuit breaker off; a negative threshold is a misconfiguration. */
static int validateBreakerFailureThreshold(int threshold) {
if (threshold < 0) {
throw new IllegalArgumentException("floci.docker.breaker-failure-threshold "
+ "(FLOCI_DOCKER_BREAKER_FAILURE_THRESHOLD) must be 0 or more, got: " + threshold);
}
return threshold;
return requireAtLeastZero(threshold, "floci.docker.breaker-failure-threshold",
"FLOCI_DOCKER_BREAKER_FAILURE_THRESHOLD");
}
static int validateBreakerProbeIntervalSeconds(int seconds) {
@@ -449,9 +443,23 @@ public class DockerClientProducer {
"FLOCI_DOCKER_BREAKER_PROBE_INTERVAL_SECONDS");
}
/** 0 means the default, twice the CPUs Floci sees and at least 4; a negative value is a misconfiguration. */
static int validateMaxConcurrentLaunches(int value) {
return requireAtLeastZero(value, "floci.docker.max-concurrent-launches", "FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES");
}
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);
return requireAtLeast(1, value, setting, envVar);
}
private static int requireAtLeastZero(int value, String setting, String envVar) {
return requireAtLeast(0, value, setting, envVar);
}
private static int requireAtLeast(int minimum, int value, String setting, String envVar) {
if (value < minimum) {
throw new IllegalArgumentException(setting + " (" + envVar + ") must be at least " + minimum
+ ", got: " + value);
}
return value;
}
@@ -575,8 +583,18 @@ public class DockerClientProducer {
Duration.ofSeconds(validateConnectionRequestTimeoutSeconds(
config.docker().connectionRequestTimeoutSeconds())));
gaugeLogger.register(role, transport::gauges);
int launchSlots = "control-plane".equals(role)
? LaunchBulkheadDockerHttpClient.resolveSize(
validateMaxConcurrentLaunches(config.docker().maxConcurrentLaunches()),
Runtime.getRuntime().availableProcessors())
: 0;
if (launchSlots > 0) {
LOG.infov("At most {0} container creates and starts run at once", launchSlots);
}
Duration launchWait = Duration.ofSeconds(config.docker().connectionRequestTimeoutSeconds());
usePingTransport(clientConfig);
return DockerClientImpl.getInstance(clientConfig, wrapForRole(transport, role, apiTimeout, breaker));
return DockerClientImpl.getInstance(clientConfig,
wrapForRole(transport, role, apiTimeout, breaker, launchSlots, launchWait));
}
static FlociDockerHttpClient newHttpClient(DefaultDockerClientConfig clientConfig, int maxConnections,
@@ -601,7 +619,7 @@ public class DockerClientProducer {
* silent daemon, not the length of each of its attempts.
*/
static DockerHttpClient wrapForRole(DockerHttpClient transport, String role, Duration callTimeout) {
return wrapForRole(transport, role, callTimeout, null);
return wrapForRole(transport, role, callTimeout, null, 0, Duration.ZERO);
}
/**
@@ -612,6 +630,29 @@ public class DockerClientProducer {
*/
static DockerHttpClient wrapForRole(DockerHttpClient transport, String role, Duration callTimeout,
DockerCircuitBreaker breaker) {
return wrapForRole(transport, role, callTimeout, breaker, 0, Duration.ZERO);
}
/**
* As {@link #wrapForRole(DockerHttpClient, String, Duration)}, with the control-plane transport's
* container creates and starts limited to {@code launchSlots} at once ({@link
* LaunchBulkheadDockerHttpClient}), each waiting up to {@code launchWait} for a slot. The bulkhead sits
* under the retry layer, so a backoff never holds a slot. 0 slots leaves launches unbounded.
*/
static DockerHttpClient wrapForRole(DockerHttpClient transport, String role, Duration callTimeout,
int launchSlots, Duration launchWait) {
return wrapForRole(transport, role, callTimeout, null, launchSlots, launchWait);
}
/**
* Both of the above. The bulkhead sits under the breaker, so an open breaker fails a launch at once
* instead of after a wait for a slot.
*/
static DockerHttpClient wrapForRole(DockerHttpClient transport, String role, Duration callTimeout,
DockerCircuitBreaker breaker, int launchSlots, Duration launchWait) {
if (launchSlots > 0 && "control-plane".equals(role)) {
transport = new LaunchBulkheadDockerHttpClient(transport, launchSlots, launchWait);
}
if (breaker != null && breaker.isEnabled()) {
transport = new CircuitBreakingDockerHttpClient(transport, breaker);
}
@@ -0,0 +1,104 @@
package io.floci.aws.core.common.docker;
import com.github.dockerjava.transport.DockerHttpClient;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.time.Duration;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* Bounds how many container creates and starts reach the Docker daemon at once. A burst of container
* work (a pipeline stage starting a dozen containers, a fan-out of Lambda cold starts) otherwise hits
* the daemon all at once and relies on the retry layer to absorb what it drops. Every other call,
* including image pulls (already one per image) and container stops and removes, passes straight
* through.
*
* <p>It sits in the control-plane transport, under {@link RetryingDockerHttpClient}, so a permit is held
* for exactly one HTTP request: never across a pull, a network attach, a file copy or a retry's backoff,
* and never twice by one thread, so a launch that starts a helper container inside it cannot deadlock.
* Every create and start goes through here, including the few call sites that bypass
* {@code ContainerLifecycleManager}. A call that cannot get a permit within the wait fails with
* {@link LaunchSlotTimeoutException}, which the retry layer does not replay.
*/
final class LaunchBulkheadDockerHttpClient implements DockerHttpClient {
private static final Pattern LAUNCH_ROUTE = Pattern.compile("(/v[0-9.]+)?/containers/(create|[^/]+/start)");
private final DockerHttpClient delegate;
private final Semaphore slots;
private final int size;
private final Duration acquireTimeout;
LaunchBulkheadDockerHttpClient(DockerHttpClient delegate, int size, Duration acquireTimeout) {
this.delegate = delegate;
this.slots = new Semaphore(size, true);
this.size = size;
this.acquireTimeout = acquireTimeout;
}
/** {@code floci.docker.max-concurrent-launches}: 0 means twice the CPUs Floci sees, at least 4. */
static int resolveSize(int configured, int availableProcessors) {
return configured > 0 ? configured : Math.max(4, 2 * availableProcessors);
}
/** Raised when no launch slot frees up within the wait; an {@link InterruptedIOException}, so it is never retried. */
static final class LaunchSlotTimeoutException extends InterruptedIOException {
LaunchSlotTimeoutException(String message) {
super(message);
}
}
@Override
public Response execute(Request request) {
if (!isLaunch(request)) {
return delegate.execute(request);
}
acquire(request);
try {
return delegate.execute(request);
} finally {
slots.release();
}
}
private void acquire(Request request) {
try {
if (!slots.tryAcquire(acquireTimeout.toMillis(), TimeUnit.MILLISECONDS)) {
throw new RuntimeException(new LaunchSlotTimeoutException("No container launch slot freed up within "
+ acquireTimeout.toSeconds() + " s: " + size + " container creates and starts are already"
+ " running (floci.docker.max-concurrent-launches); not sent: " + request.method() + " "
+ route(request.path())));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for a container launch slot", e);
}
}
/** {@code POST /containers/create} or {@code POST /containers/{id}/start}, after an optional API version. */
static boolean isLaunch(Request request) {
return "POST".equals(request.method()) && LAUNCH_ROUTE.matcher(route(request.path())).matches();
}
int availableSlots() {
return slots.availablePermits();
}
/** Launches waiting for a slot; an estimate, as {@link Semaphore#getQueueLength()} is. */
int queuedLaunches() {
return slots.getQueueLength();
}
private static String route(String path) {
int query = path.indexOf('?');
return query < 0 ? path : path.substring(0, query);
}
@Override
public void close() throws IOException {
delegate.close();
}
}
+5
View File
@@ -440,6 +440,11 @@ floci:
# here WINS over the annotation.
breaker-failure-threshold: 3
breaker-probe-interval-seconds: 5
# FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES: most container creates and starts sent to the daemon at
# once; more wait up to connection-request-timeout-seconds for one to finish. 0 = twice the CPUs
# Floci sees, at least 4. Keep in step with the @WithDefault on
# EmulatorConfig.DockerConfig.maxConcurrentLaunches: a value set here WINS over the annotation.
max-concurrent-launches: 0
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
@@ -234,4 +234,16 @@ class ApplicationDefaultsTest {
assertEquals("5", EmulatorConfig.DockerConfig.class.getMethod("breakerProbeIntervalSeconds")
.getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml");
}
// Catches: max-concurrent-launches missing from the shipped application.yml, or a yml value that
// silently disagrees with its @WithDefault fallback.
@Test
void productionConfigDeclaresTheContainerLaunchBoundAtItsDefault() throws IOException, NoSuchMethodException {
JsonNode launches = productionConfig().path("floci").path("docker").path("max-concurrent-launches");
assertFalse(launches.isMissingNode(), "max-concurrent-launches should be declared in application.yml");
assertEquals(0, launches.asInt(-1));
assertEquals("0", EmulatorConfig.DockerConfig.class.getMethod("maxConcurrentLaunches")
.getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml");
}
}
@@ -716,6 +716,37 @@ class DockerClientProducerTest {
assertEquals(60, DockerClientProducer.validatePoolGaugeIntervalSeconds(60));
}
@Test
void validateMaxConcurrentLaunches_negative_throwsNamingTheSetting() {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> DockerClientProducer.validateMaxConcurrentLaunches(-1));
assertThat(e.getMessage(), containsString("floci.docker.max-concurrent-launches"));
assertThat(e.getMessage(), containsString("FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES"));
}
@Test
void validateMaxConcurrentLaunches_zeroOrPositive_returnsItUnchanged() {
assertEquals(0, DockerClientProducer.validateMaxConcurrentLaunches(0));
assertEquals(8, DockerClientProducer.validateMaxConcurrentLaunches(8));
}
@Test
void validateBreakerFailureThreshold_negative_throwsNamingTheSetting() {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> DockerClientProducer.validateBreakerFailureThreshold(-1));
assertThat(e.getMessage(), containsString("floci.docker.breaker-failure-threshold"));
assertThat(e.getMessage(), containsString("FLOCI_DOCKER_BREAKER_FAILURE_THRESHOLD"));
assertThat(e.getMessage(), containsString("must be at least 0"));
}
@Test
void validateBreakerFailureThreshold_zeroOrPositive_returnsItUnchanged() {
assertEquals(0, DockerClientProducer.validateBreakerFailureThreshold(0));
assertEquals(3, DockerClientProducer.validateBreakerFailureThreshold(3));
}
@Test
void validateImagePullTimeoutSeconds_positive_returnsItUnchanged() {
assertEquals(1, DockerClientProducer.validateImagePullTimeoutSeconds(1));
@@ -0,0 +1,234 @@
package io.floci.aws.core.common.docker;
import com.github.dockerjava.transport.DockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient.Request;
import com.github.dockerjava.transport.DockerHttpClient.Response;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.IntSupplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LaunchBulkheadDockerHttpClientTest {
private static Request post(String path) {
return Request.builder().method(Request.Method.POST).path(path).build();
}
// Catches: the bulkhead gating calls it was never meant to (stops, exec starts, image creates) or
// missing a create or start behind an API version prefix.
@Test
void onlyContainerCreatesAndStartsAreLaunches() {
assertTrue(LaunchBulkheadDockerHttpClient.isLaunch(post("/containers/create")));
assertTrue(LaunchBulkheadDockerHttpClient.isLaunch(post("/v1.47/containers/create?name=floci-x")));
assertTrue(LaunchBulkheadDockerHttpClient.isLaunch(post("/v1.47/containers/abc123/start")));
assertFalse(LaunchBulkheadDockerHttpClient.isLaunch(post("/v1.47/containers/abc123/stop")));
assertFalse(LaunchBulkheadDockerHttpClient.isLaunch(post("/v1.47/exec/abc123/start")));
assertFalse(LaunchBulkheadDockerHttpClient.isLaunch(post("/v1.47/images/create?fromImage=busybox")));
assertFalse(LaunchBulkheadDockerHttpClient.isLaunch(post("/v1.47/images/quay.io/containers/create")));
assertFalse(LaunchBulkheadDockerHttpClient.isLaunch(
Request.builder().method(Request.Method.GET).path("/v1.47/containers/abc123/json").build()));
}
// Catches: a burst of launches reaching the daemon all at once.
@Test
void runsAtMostItsSizeOfLaunchesAtOnceAndCompletesThemAll() throws Exception {
CountDownLatch release = new CountDownLatch(1);
AtomicInteger inFlight = new AtomicInteger();
AtomicInteger maxInFlight = new AtomicInteger();
FakeTransport transport = new FakeTransport(request -> {
maxInFlight.accumulateAndGet(inFlight.incrementAndGet(), Math::max);
try {
release.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
inFlight.decrementAndGet();
}
return new StatusResponse(201);
});
LaunchBulkheadDockerHttpClient bulkhead = new LaunchBulkheadDockerHttpClient(transport, 2, Duration.ofSeconds(10));
ExecutorService pool = Executors.newFixedThreadPool(5);
try {
List<Future<Response>> launches = new ArrayList<>();
for (int i = 0; i < 5; i++) {
launches.add(pool.submit(() -> bulkhead.execute(post("/v1.47/containers/create?name=c"))));
}
awaitEquals(2, inFlight::get, "two launches should be in flight");
awaitEquals(3, bulkhead::queuedLaunches, "the other three should be waiting for a slot");
assertEquals(2, inFlight.get(), "a size-2 bulkhead must hold the other three back");
release.countDown();
for (Future<Response> launch : launches) {
assertEquals(201, launch.get(5, TimeUnit.SECONDS).getStatusCode());
}
} finally {
pool.shutdownNow();
}
assertEquals(2, maxInFlight.get());
assertEquals(5, transport.calls.get());
assertEquals(2, bulkhead.availableSlots(), "every slot comes back once the launches end");
}
// Catches: a pull, stop or inspect waiting behind launches that hold every slot.
@Test
void otherCallsPassWhileEverySlotIsHeld() throws Exception {
CountDownLatch release = new CountDownLatch(1);
FakeTransport transport = new FakeTransport(request -> {
if (LaunchBulkheadDockerHttpClient.isLaunch(request)) {
try {
release.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
return new StatusResponse(200);
});
LaunchBulkheadDockerHttpClient bulkhead = new LaunchBulkheadDockerHttpClient(transport, 1, Duration.ofSeconds(10));
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Future<Response> launch = pool.submit(() -> bulkhead.execute(post("/containers/abc/start")));
awaitEquals(0, bulkhead::availableSlots, "the launch should hold the only slot");
assertEquals(200, bulkhead.execute(post("/v1.47/images/create?fromImage=busybox")).getStatusCode());
assertEquals(200, bulkhead.execute(post("/v1.47/containers/abc/stop")).getStatusCode());
release.countDown();
launch.get(5, TimeUnit.SECONDS);
} finally {
pool.shutdownNow();
}
}
// Catches: a launch waiting forever for a slot, or its timeout being replayed by the retry layer.
@Test
void aLaunchThatGetsNoSlotInTimeFailsAndIsNotRetried() throws Exception {
CountDownLatch release = new CountDownLatch(1);
FakeTransport transport = new FakeTransport(request -> {
try {
release.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return new StatusResponse(201);
});
LaunchBulkheadDockerHttpClient bulkhead = new LaunchBulkheadDockerHttpClient(transport, 1, Duration.ofMillis(100));
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Future<Response> holder = pool.submit(() -> bulkhead.execute(post("/containers/create")));
awaitEquals(0, bulkhead::availableSlots, "the first launch should hold the only slot");
RuntimeException e = assertThrows(RuntimeException.class,
() -> bulkhead.execute(post("/containers/create")));
assertInstanceOf(LaunchBulkheadDockerHttpClient.LaunchSlotTimeoutException.class, e.getCause());
assertFalse(DockerRetry.isTransientIo(e), "a slot timeout must not be replayed");
release.countDown();
holder.get(5, TimeUnit.SECONDS);
} finally {
pool.shutdownNow();
}
assertEquals(1, transport.calls.get(), "the launch that got no slot never reached the daemon");
}
// Catches: the bulkhead above the retry layer, where a launch would keep its slot through every
// backoff, or the producer leaving it out of the control-plane transport.
@Test
void theProducerPutsTheBulkheadUnderTheControlPlaneRetryLayer() {
AtomicInteger attempts = new AtomicInteger();
FakeTransport transport = new FakeTransport(request -> {
if (attempts.incrementAndGet() == 1) {
throw new RuntimeException(new SocketException("Broken pipe"));
}
return new StatusResponse(201);
});
DockerHttpClient control = DockerClientProducer.wrapForRole(transport, "control-plane",
Duration.ofSeconds(30), 1, Duration.ofMillis(200));
assertEquals(201, control.execute(post("/v1.47/containers/create?name=retried")).getStatusCode());
assertEquals(2, attempts.get(), "a named create is retried after a broken pipe");
assertEquals(201, control.execute(post("/v1.47/containers/abc/start")).getStatusCode(),
"the retried create must have released its only slot");
}
@Test
void sizeDefaultsToTwiceTheCpusAndAtLeastFour() {
assertEquals(16, LaunchBulkheadDockerHttpClient.resolveSize(0, 8));
assertEquals(4, LaunchBulkheadDockerHttpClient.resolveSize(0, 1));
assertEquals(3, LaunchBulkheadDockerHttpClient.resolveSize(3, 8));
}
private static void awaitEquals(int expected, IntSupplier actual, String message)
throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (actual.getAsInt() != expected) {
if (System.nanoTime() > deadline) {
throw new AssertionError(message + ": expected " + expected + " but was " + actual.getAsInt());
}
Thread.sleep(5);
}
}
private static final class FakeTransport implements DockerHttpClient {
private final Function<Request, Response> behaviour;
final AtomicInteger calls = new AtomicInteger();
FakeTransport(Function<Request, Response> behaviour) {
this.behaviour = behaviour;
}
@Override
public Response execute(Request request) {
calls.incrementAndGet();
return behaviour.apply(request);
}
@Override
public void close() throws IOException {
// Nothing to release.
}
}
private record StatusResponse(int status) implements Response {
@Override
public int getStatusCode() {
return status;
}
@Override
public Map<String, List<String>> getHeaders() {
return Map.of();
}
@Override
public InputStream getBody() {
return new ByteArrayInputStream(new byte[0]);
}
@Override
public void close() {
// Nothing to release.
}
}
}