feat(docker): fail Docker calls fast while the daemon is unreachable (#9047)

A circuit breaker sits under the retry layer of both Docker clients and
counts consecutive transport failures: an I/O error or an unusable
socket, never an HTTP response or a wait for a pooled connection. After
floci.docker.breaker-failure-threshold (3) of them it pings the daemon
off the caller's thread, over a one-connection transport of its own;
only when that ping fails too does every Docker call fail at once with
DockerUnavailableException, which the retry layer never replays. While
open it pings every floci.docker.breaker-probe-interval-seconds (5), and
the first answer closes it. Any HTTP status to the ping is an answer,
and a ping that never reaches the daemon neither opens nor closes the
breaker. A threshold of 0 turns it off.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-20 14:16:14 -04:00
1 parent 3991e5ce44
commit 5cded523e3
12 files changed
+761 -2

No files matched your search

@@ -4496,6 +4496,20 @@ public interface EmulatorConfig {
@WithDefault("60")
int poolGaugeIntervalSeconds();
/**
* Consecutive Docker call attempts that must fail at the transport (an I/O error or an
* unusable socket, never an HTTP response) before Floci pings the daemon and, when the ping
* fails too, fails every Docker call at once until the daemon answers again. Each retry of a
* call is an attempt, so one call the retry layer replays can reach the threshold alone; the
* ping keeps that from opening the breaker over a daemon that answers. 0 turns this off.
*/
@WithDefault("3")
int breakerFailureThreshold();
/** Seconds between the pings that check whether an unreachable Docker daemon is back. */
@WithDefault("5")
int breakerProbeIntervalSeconds();
/**
* Optional namespace inserted into Floci-managed child container and volume names.
* Useful when multiple Floci processes share one Docker daemon.
@@ -0,0 +1,45 @@
package io.floci.aws.core.common.docker;
import com.github.dockerjava.transport.DockerHttpClient;
import java.io.IOException;
/**
* Puts {@link DockerCircuitBreaker} in front of a Docker transport: while the breaker is open a call
* fails at once with {@link DockerUnavailableException}; otherwise the call runs, an HTTP response of
* any status tells the breaker the daemon is there, and a transport failure counts toward opening it.
* It sits under {@link RetryingDockerHttpClient}, which never replays the fail-fast exception.
*/
final class CircuitBreakingDockerHttpClient implements DockerHttpClient {
private final DockerHttpClient delegate;
private final DockerCircuitBreaker breaker;
CircuitBreakingDockerHttpClient(DockerHttpClient delegate, DockerCircuitBreaker breaker) {
this.delegate = delegate;
this.breaker = breaker;
}
@Override
public Response execute(Request request) {
if (breaker.isOpen()) {
throw new RuntimeException(breaker.unavailable());
}
Response response;
try {
response = delegate.execute(request);
} catch (RuntimeException e) {
if (DockerRetry.isDaemonFailure(e)) {
breaker.recordFailure(e);
}
throw e;
}
breaker.recordResponse();
return response;
}
@Override
public void close() throws IOException {
delegate.close();
}
}
@@ -0,0 +1,234 @@
package io.floci.aws.core.common.docker;
import com.github.dockerjava.transport.DockerHttpClient;
import org.jboss.logging.Logger;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* One view of whether the Docker daemon is reachable, shared by both Docker clients. After
* {@code threshold} consecutive attempts fail at the transport (an I/O error or an unusable socket,
* never an HTTP response) it pings the daemon off the caller's thread; only when that ping fails at
* the transport too does it open, and every Docker call then fails at once with
* {@link DockerUnavailableException} instead of waiting out its own connect, response and retry
* timeouts. While open it pings every {@code probeInterval}, and the first answer closes it. A ping
* is judged by the same rules as a call: any HTTP status is an answer, and a failure that says nothing
* about the daemon (an interruption, a wait for a pooled connection) neither opens nor closes it. A
* {@code threshold} of 0 disables it.
*
* <p>The confirming ping matters because the breaker sits under the retry layer and so counts
* attempts, not calls: a burst of broken pipes during a fan-out build is a few failed attempts in a
* row that the next attempt rides out, and must not take Docker away from every service.
*/
final class DockerCircuitBreaker implements AutoCloseable {
private static final Logger LOG = Logger.getLogger(DockerCircuitBreaker.class);
/** What a ping showed about the daemon. */
enum PingResult {
/** An HTTP response, whatever its status: the daemon is there. */
ANSWERED,
/** A transport failure, as {@link DockerRetry#isDaemonFailure} classifies it. */
UNREACHABLE,
/** A failure that says nothing about the daemon, such as an interruption. */
INCONCLUSIVE
}
/** Pings the daemon. */
@FunctionalInterface
interface Probe {
PingResult ping();
}
private final int threshold;
private final Duration probeInterval;
private final AtomicInteger consecutiveFailures = new AtomicInteger();
private final AtomicBoolean probeScheduled = new AtomicBoolean();
private final AtomicInteger probesRun = new AtomicInteger();
private final Object schedulerLock = new Object();
private volatile boolean open;
private volatile String lastFailure = "";
private volatile Probe probe;
private ScheduledExecutorService scheduler;
private boolean closed;
DockerCircuitBreaker(int threshold, Duration probeInterval) {
this.threshold = threshold;
this.probeInterval = probeInterval;
}
/**
* A ping over {@code transport}, below the breaker, so it reaches the daemon while the breaker is
* open. The producer gives it a transport of its own, so a full pool never delays it and its short
* response timeout bounds how long a daemon that accepts a connection but never answers holds it.
*/
static Probe pingOver(DockerHttpClient transport) {
return () -> {
DockerHttpClient.Request ping = DockerHttpClient.Request.builder()
.method(DockerHttpClient.Request.Method.GET)
.path("/_ping")
.build();
try (DockerHttpClient.Response ignored = transport.execute(ping)) {
return PingResult.ANSWERED;
} catch (RuntimeException e) {
LOG.debugv("Docker daemon ping failed: {0}", e.getMessage());
return DockerRetry.isDaemonFailure(e) ? PingResult.UNREACHABLE : PingResult.INCONCLUSIVE;
}
};
}
boolean isEnabled() {
return threshold > 0;
}
boolean isOpen() {
return open;
}
/** Sets how the breaker pings the daemon. */
void useProbe(Probe newProbe) {
probe = newProbe;
}
/** How many pings have finished, for tests that wait on one. */
int probesRun() {
return probesRun.get();
}
/** Whether a ping is scheduled or running. */
boolean isProbeScheduled() {
return probeScheduled.get();
}
/** The exception an open breaker raises in place of a Docker call. */
DockerUnavailableException unavailable() {
return new DockerUnavailableException("Docker daemon is unreachable: " + threshold
+ " consecutive Docker call attempts failed at the transport and it has not answered a ping since"
+ " (last failure: " + lastFailure + ")");
}
/** A Docker call got an HTTP response, whatever its status: the daemon is there. */
void recordResponse() {
consecutiveFailures.set(0);
if (open) {
closeCircuit();
}
}
/** A Docker call failed at the transport, as {@link DockerRetry#isDaemonFailure} classifies it. */
void recordFailure(Throwable failure) {
if (!isEnabled()) {
return;
}
lastFailure = String.valueOf(failure.getMessage());
if (consecutiveFailures.incrementAndGet() >= threshold && !open) {
scheduleProbe(0);
}
}
private void scheduleProbe(long delayMillis) {
if (probe == null || !probeScheduled.compareAndSet(false, true)) {
return;
}
synchronized (schedulerLock) {
if (closed) {
probeScheduled.set(false);
return;
}
if (scheduler == null) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, runnable -> {
Thread thread = new Thread(runnable, "floci-docker-breaker-probe");
thread.setDaemon(true);
return thread;
});
executor.setRemoveOnCancelPolicy(true);
scheduler = executor;
}
scheduler.schedule(this::runProbe, delayMillis, TimeUnit.MILLISECONDS);
}
}
private void runProbe() {
PingResult result;
try {
result = probe.ping();
} catch (RuntimeException e) {
LOG.debugv("Docker daemon ping failed: {0}", e.getMessage());
result = DockerRetry.isDaemonFailure(e) ? PingResult.UNREACHABLE : PingResult.INCONCLUSIVE;
}
probeScheduled.set(false);
try {
switch (result) {
case ANSWERED -> {
consecutiveFailures.set(0);
if (open) {
closeCircuit();
}
}
case UNREACHABLE -> {
if (!open && !openCircuit()) {
return;
}
scheduleProbe(probeInterval.toMillis());
}
case INCONCLUSIVE -> {
// Neither opens nor closes: a closed breaker pings again on the next transport failure.
if (open) {
scheduleProbe(probeInterval.toMillis());
}
}
}
} finally {
probesRun.incrementAndGet();
}
}
/**
* Opens the breaker unless a call got an answer since the failures that triggered the ping. The
* open is written before the count is read again, and {@link #recordResponse} resets the count
* before it reads the open, so a response racing this either shows here as a reset count or sees
* the open and closes it: it can never leave the breaker open behind it.
*/
private boolean openCircuit() {
if (consecutiveFailures.get() < threshold) {
return false;
}
synchronized (schedulerLock) {
open = true;
}
if (consecutiveFailures.get() < threshold) {
closeCircuit();
return false;
}
LOG.warnv("Docker daemon is unreachable: {0} consecutive Docker call attempts failed at the transport"
+ " and a ping failed too, so Docker calls fail at once until the daemon answers a ping (tried"
+ " every {1} s). Last failure: {2}", threshold, probeInterval.toSeconds(), lastFailure);
return true;
}
private void closeCircuit() {
synchronized (schedulerLock) {
if (!open) {
return;
}
open = false;
}
LOG.info("Docker daemon answered again; Docker calls go through");
}
@Override
public void close() {
synchronized (schedulerLock) {
closed = true;
if (scheduler != null) {
scheduler.shutdownNow();
scheduler = null;
}
}
}
}
@@ -55,14 +55,23 @@ public class DockerClientProducer {
private static final ObjectMapper DOCKER_CONTEXT_JSON_MAPPER = new ObjectMapper();
/** Bounds the connect and the answer of the Docker circuit breaker's confirming ping. */
static final Duration PING_TIMEOUT = Duration.ofSeconds(5);
private final EmulatorConfig config;
private final DockerPoolGaugeLogger gaugeLogger;
private final DockerCircuitBreaker breaker;
@Inject
public DockerClientProducer(EmulatorConfig config) {
this.config = config;
this.gaugeLogger = new DockerPoolGaugeLogger(
validatePoolGaugeIntervalSeconds(config.docker().poolGaugeIntervalSeconds()));
int breakerThreshold = validateBreakerFailureThreshold(config.docker().breakerFailureThreshold());
// The probe interval only matters, and is only checked, while the breaker is on.
Duration probeInterval = breakerThreshold == 0 ? Duration.ZERO
: Duration.ofSeconds(validateBreakerProbeIntervalSeconds(config.docker().breakerProbeIntervalSeconds()));
this.breaker = new DockerCircuitBreaker(breakerThreshold, probeInterval);
}
/**
@@ -426,6 +435,20 @@ public class DockerClientProducer {
return 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;
}
static int validateBreakerProbeIntervalSeconds(int seconds) {
return requireAtLeastOne(seconds, "floci.docker.breaker-probe-interval-seconds",
"FLOCI_DOCKER_BREAKER_PROBE_INTERVAL_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);
@@ -465,9 +488,43 @@ public class DockerClientProducer {
void disposeDockerClient(@Disposes DockerClient client) throws IOException {
gaugeLogger.unregister("control-plane");
breaker.close();
client.close();
}
/**
* Gives the breaker a ping that opens a one-connection transport of its own for each ping and closes it
* after, so a ping never waits for a pooled connection behind the calls whose failures it is confirming,
* {@link #PING_TIMEOUT} bounds the connect and the answer, and no transport outlives the client whose
* build set the probe. Pings are rare: one after a run of transport failures, then one per probe
* interval while the breaker is open.
*/
private void usePingTransport(DefaultDockerClientConfig clientConfig) {
if (!breaker.isEnabled()) {
return;
}
breaker.useProbe(() -> {
try (FlociDockerHttpClient transport = newPingTransport(clientConfig, PING_TIMEOUT)) {
return DockerCircuitBreaker.pingOver(transport).ping();
} catch (IOException e) {
LOG.debugv("Closing the Docker breaker's ping transport failed: {0}", e.getMessage());
return DockerCircuitBreaker.PingResult.INCONCLUSIVE;
}
});
}
/** One connection whose connect, lease and answer are each bounded by {@code timeout}. */
static FlociDockerHttpClient newPingTransport(DefaultDockerClientConfig clientConfig, Duration timeout) {
return new FlociDockerHttpClient.Builder()
.dockerHost(clientConfig.getDockerHost())
.sslConfig(clientConfig.getSSLConfig())
.maxConnections(1)
.connectionTimeout(timeout)
.responseTimeout(timeout)
.connectionRequestTimeout(timeout)
.build();
}
void disposeStreamingDockerClient(@Disposes @StreamingDocker DockerClient client) throws IOException {
gaugeLogger.unregister("streaming");
client.close();
@@ -518,7 +575,8 @@ public class DockerClientProducer {
Duration.ofSeconds(validateConnectionRequestTimeoutSeconds(
config.docker().connectionRequestTimeoutSeconds())));
gaugeLogger.register(role, transport::gauges);
return DockerClientImpl.getInstance(clientConfig, wrapForRole(transport, role, apiTimeout));
usePingTransport(clientConfig);
return DockerClientImpl.getInstance(clientConfig, wrapForRole(transport, role, apiTimeout, breaker));
}
static FlociDockerHttpClient newHttpClient(DefaultDockerClientConfig clientConfig, int maxConnections,
@@ -543,6 +601,20 @@ 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);
}
/**
* As {@link #wrapForRole(DockerHttpClient, String, Duration)}, with {@code breaker} (shared by both
* roles) between the retry layer and the transport, so an open breaker fails a call before the
* retry layer could replay it, and every attempt's outcome reaches the breaker. A null or disabled
* breaker leaves the transport as it is.
*/
static DockerHttpClient wrapForRole(DockerHttpClient transport, String role, Duration callTimeout,
DockerCircuitBreaker breaker) {
if (breaker != null && breaker.isEnabled()) {
transport = new CircuitBreakingDockerHttpClient(transport, breaker);
}
if (!"control-plane".equals(role)) {
// The streaming transport replays only container waits, long-lived streams the call timeout never bounds.
return RetryingDockerHttpClient.forContainerWaits(transport);
@@ -96,7 +96,7 @@ public final class DockerRetry {
if (c instanceof InterruptedIOException && !(c instanceof SocketTimeoutException)) {
return false;
}
if (c instanceof LocalFailure) {
if (c instanceof LocalFailure || c instanceof DockerUnavailableException) {
return false;
}
if (isUnusableSocket(c)) {
@@ -128,6 +128,30 @@ public final class DockerRetry {
return false;
}
/**
* True when {@code t} says the daemon could not be reached at the transport, what
* {@link DockerCircuitBreaker} counts: a transient I/O failure ({@link #isTransientIo}) or a
* socket that is missing or may not be opened. A wait for a pooled connection, an interruption, a
* failure raised on this host ({@link LocalFailure}) and the breaker's own fail-fast exception say
* nothing about the daemon and do not count.
*/
static boolean isDaemonFailure(Throwable t) {
boolean unusableSocket = false;
for (Throwable c = t; c != null; c = c.getCause()) {
if (c instanceof InterruptedIOException && !(c instanceof SocketTimeoutException)) {
return false;
}
if (c instanceof LocalFailure || c instanceof DockerUnavailableException) {
return false;
}
unusableSocket |= isUnusableSocket(c);
if (c.getCause() == c) {
break;
}
}
return unusableSocket || isTransientIo(t);
}
/**
* True when {@code t} reports that the docker socket file does not exist ({@code No such
* file or directory}), as when Floci runs without a mounted docker socket, or that this
@@ -0,0 +1,16 @@
package io.floci.aws.core.common.docker;
import java.io.IOException;
/**
* Raised instead of a Docker call while {@link DockerCircuitBreaker} is open: the daemon failed
* several calls in a row at the transport and did not answer a ping since, so the call fails at once
* rather than waiting out its own timeouts. {@link DockerRetry#isTransientIo} never treats it as
* transient, so no retry layer replays it.
*/
public final class DockerUnavailableException extends IOException {
public DockerUnavailableException(String message) {
super(message);
}
}