mirror of
https://github.com/floci-io/floci.git
synced 2026-12-03 18:18:02 -05:00
feat(docker): limit concurrent container creates and starts (#9049)
This commit is contained in:
1 parent
1037f592fe
commit
6de2461693
10 files changed
+464
-14
No files matched your search
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user