mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 09:47:56 -05:00
feat(docker): per-service container budgets that answer with each service's capacity error (#9176)
This commit is contained in:
1 parent
5c62948838
commit
8183404fbd
18 files changed
+490
-8
No files matched your search
@@ -4583,6 +4583,14 @@ public interface EmulatorConfig {
|
||||
@WithDefault("0")
|
||||
int maxConcurrentLaunches();
|
||||
|
||||
/**
|
||||
* Most containers a service may run at once, keyed by its {@code io.floci.service} label
|
||||
* ({@code lambda}, {@code rds}, {@code elasticache}, ...). A create past it fails at once with the
|
||||
* capacity or limit error that service's API declares (Lambda's {@code TooManyRequestsException},
|
||||
* RDS's {@code InsufficientDBInstanceCapacity}). A service not listed is not limited; none is by default.
|
||||
*/
|
||||
Map<String, Integer> serviceMaxContainers();
|
||||
|
||||
/**
|
||||
* Milliseconds between the reads of a long-lived service container's log (a database, a broker, a
|
||||
* registry), which Floci reads on a timer instead of holding a follow stream open for the
|
||||
|
||||
@@ -396,20 +396,41 @@ public class ContainerLifecycleManager {
|
||||
labels.put(CREATE_ATTEMPT_LABEL, createAttemptId);
|
||||
createCmd.withLabels(labels);
|
||||
|
||||
String budgetedService = serviceBudget(labels);
|
||||
if (budgetedService != null) {
|
||||
DockerServiceBudget.reserve(budgetedService, config.docker().serviceMaxContainers().get(budgetedService));
|
||||
}
|
||||
String containerId;
|
||||
try {
|
||||
containerId = createWithConflictRecovery(createCmd, spec, createAttemptId);
|
||||
DockerContainerServices.record(containerId, spec.name(), labels);
|
||||
} catch (DockerException e) {
|
||||
if (ContainerRejectedException.isRejection(e)) {
|
||||
throw new ContainerRejectedException(e);
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
if (budgetedService != null) {
|
||||
DockerServiceBudget.release(budgetedService);
|
||||
}
|
||||
}
|
||||
DockerContainerServices.record(containerId, spec.name(), labels);
|
||||
LOG.infov("Created container {0} (name={1}, not yet started)", containerId, spec.name());
|
||||
return containerId;
|
||||
}
|
||||
|
||||
/** The service of a container to create when {@code floci.docker.service-max-containers} gives it a budget. */
|
||||
private String serviceBudget(Map<String, String> labels) {
|
||||
if (config == null || config.docker() == null) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Integer> budgets = config.docker().serviceMaxContainers();
|
||||
if (budgets == null || budgets.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String service = ContainerStorageHelper.labelValue(labels, ContainerStorageHelper.SERVICE_LABEL);
|
||||
return service != null && budgets.containsKey(service) ? service : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the create, recovering the container when a replay of it lost the race with its own
|
||||
* earlier attempt.
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A container a service asked for would take it past its {@code floci.docker.service-max-containers}
|
||||
* budget. It is the {@link AwsException} the service's own API declares for running out of capacity or
|
||||
* hitting a limit, so the error reaches the caller in the shape its SDK knows (and, for the throttling
|
||||
* codes, backs off from), not as a transport failure or an internal error.
|
||||
*/
|
||||
public final class DockerCapacityExceededException extends AwsException {
|
||||
|
||||
/** Error code and HTTP status per {@code io.floci.service} label, from each service's botocore model. */
|
||||
private static final Map<String, Error> ERRORS = Map.ofEntries(
|
||||
Map.entry("lambda", new Error("TooManyRequestsException", 429)),
|
||||
Map.entry("msk", new Error("TooManyRequestsException", 429)),
|
||||
Map.entry("opensearch", new Error("LimitExceededException", 409)),
|
||||
Map.entry("codebuild", new Error("AccountLimitExceededException", 400)),
|
||||
Map.entry("sagemaker", new Error("ResourceLimitExceeded", 400)),
|
||||
Map.entry("glue", new Error("ConcurrentRunsExceededException", 400)),
|
||||
Map.entry("rds", new Error("InsufficientDBInstanceCapacity", 400)),
|
||||
Map.entry("docdb", new Error("DBClusterQuotaExceededFault", 403)),
|
||||
Map.entry("neptune", new Error("DBClusterQuotaExceededFault", 403)),
|
||||
Map.entry("elasticache", new Error("InsufficientCacheClusterCapacity", 400)),
|
||||
Map.entry("redshift", new Error("InsufficientClusterCapacity", 400)),
|
||||
Map.entry("memorydb", new Error("InsufficientClusterCapacityFault", 400)));
|
||||
|
||||
/** Services without a modelled capacity error, such as ECS, Batch and EMR, get a generic throttle. */
|
||||
private static final Error FALLBACK = new Error("ThrottlingException", 400);
|
||||
|
||||
private final String service;
|
||||
|
||||
public DockerCapacityExceededException(String service, int limit) {
|
||||
super(errorFor(service).code(), "Floci's Docker budget for " + service + " is " + limit
|
||||
+ " running containers (floci.docker.service-max-containers." + service
|
||||
+ "), and every one is in use", errorFor(service).status());
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
public String service() {
|
||||
return service;
|
||||
}
|
||||
|
||||
/** The refusal {@code failure} is or carries as a cause, or null; a failed launch can wrap it. */
|
||||
public static DockerCapacityExceededException findIn(Throwable failure) {
|
||||
for (Throwable cause = failure; cause != null; cause = cause.getCause() == cause ? null : cause.getCause()) {
|
||||
if (cause instanceof DockerCapacityExceededException exceeded) {
|
||||
return exceeded;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Error errorFor(String service) {
|
||||
return ERRORS.getOrDefault(service, FALLBACK);
|
||||
}
|
||||
|
||||
private record Error(String code, int status) {
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ final class DockerContainerServices {
|
||||
static final String UNATTRIBUTED = "unattributed";
|
||||
|
||||
private static final Map<String, Owner> OWNERS = new ConcurrentHashMap<>();
|
||||
/** Each recorded container's service, by container id only, so a service's containers can be counted. */
|
||||
private static final Map<String, String> SERVICE_BY_ID = new ConcurrentHashMap<>();
|
||||
|
||||
private DockerContainerServices() {
|
||||
}
|
||||
@@ -31,6 +33,7 @@ final class DockerContainerServices {
|
||||
return;
|
||||
}
|
||||
boolean named = containerName != null && !containerName.isBlank();
|
||||
SERVICE_BY_ID.put(containerId, service);
|
||||
OWNERS.put(containerId, new Owner(service, named ? containerName : null));
|
||||
if (named) {
|
||||
Owner previous = OWNERS.put(containerName, new Owner(service, containerId));
|
||||
@@ -49,9 +52,26 @@ final class DockerContainerServices {
|
||||
return owner == null ? UNATTRIBUTED : owner.service();
|
||||
}
|
||||
|
||||
/** How many recorded containers of {@code service} have not been seen removed. */
|
||||
static int liveContainers(String service) {
|
||||
int count = 0;
|
||||
for (String owner : SERVICE_BY_ID.values()) {
|
||||
if (owner.equals(service)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** Forgets a removed container, given by its id or its name. */
|
||||
static void forget(String container) {
|
||||
Owner owner = OWNERS.remove(container);
|
||||
if (container != null && SERVICE_BY_ID.remove(container) == null) {
|
||||
Owner byName = OWNERS.get(container);
|
||||
if (byName != null && byName.alias() != null) {
|
||||
SERVICE_BY_ID.remove(byName.alias());
|
||||
}
|
||||
}
|
||||
Owner owner = container == null ? null : OWNERS.remove(container);
|
||||
if (owner != null && owner.alias() != null) {
|
||||
// Only while the other key still points back here: a newer container may hold the name now.
|
||||
OWNERS.remove(owner.alias(), new Owner(owner.service(), container));
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* How many containers each service may run at once ({@code floci.docker.service-max-containers.<service>}),
|
||||
* so one service cannot take every container the daemon can hold and leave the others to time out. A
|
||||
* service's live containers are the ones {@link DockerContainerServices} has recorded and not yet seen
|
||||
* removed; a create in progress holds a reservation, so concurrent creates cannot both take the last
|
||||
* one. A service with no budget is not limited, and neither is a container without a service label.
|
||||
*/
|
||||
final class DockerServiceBudget {
|
||||
|
||||
private static final Map<String, Integer> RESERVED = new HashMap<>();
|
||||
|
||||
private DockerServiceBudget() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reserves one container for {@code service}, or throws {@link DockerCapacityExceededException} when
|
||||
* its running containers and reservations already reach {@code limit}. Release the reservation with
|
||||
* {@link #release} once the create has succeeded or failed.
|
||||
*/
|
||||
static void reserve(String service, int limit) {
|
||||
synchronized (RESERVED) {
|
||||
int reserved = RESERVED.getOrDefault(service, 0);
|
||||
if (DockerContainerServices.liveContainers(service) + reserved >= limit) {
|
||||
throw new DockerCapacityExceededException(service, limit);
|
||||
}
|
||||
RESERVED.put(service, reserved + 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void release(String service) {
|
||||
synchronized (RESERVED) {
|
||||
RESERVED.computeIfPresent(service, (key, reserved) -> reserved > 1 ? reserved - 1 : null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.DelayedTaskScheduler;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.core.common.docker.DockerCapacityExceededException;
|
||||
import io.floci.aws.services.lambda.launcher.ContainerHandle;
|
||||
import io.floci.aws.services.lambda.launcher.LambdaInitException;
|
||||
import io.floci.aws.services.lambda.model.FunctionEventInvokeConfig;
|
||||
@@ -378,6 +379,10 @@ public class LambdaExecutorService implements Resettable {
|
||||
InvokeResult result;
|
||||
try (permit) {
|
||||
result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier(), null, null, false);
|
||||
} catch (DockerCapacityExceededException throttled) {
|
||||
// Lambda's Docker budget is full: backed off like a throttled event, which it is to the caller.
|
||||
schedule(event, throttledWaitMs, attempt, previous, Math.min(throttledWaitMs * 2, throttledRetryMaxWaitMs));
|
||||
return;
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Error in async Lambda execution for {0}: {1}", event.fn().getFunctionName(), e.getMessage());
|
||||
// Stops retrying, as upstream did: routes the previous attempt's result, or UnknownError when
|
||||
@@ -463,6 +468,11 @@ public class LambdaExecutorService implements Resettable {
|
||||
handle = warmPool.acquire(fn);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
DockerCapacityExceededException overBudget = DockerCapacityExceededException.findIn(e);
|
||||
if (overBudget != null) {
|
||||
// Out of Floci's Docker budget for Lambda is AWS's throttle, not a function error.
|
||||
throw overBudget;
|
||||
}
|
||||
LOG.warnv("Failed to acquire container for function {0}: {1}", fn.getFunctionName(), e.getMessage());
|
||||
return new InvokeResult(200, "Unhandled",
|
||||
buildErrorPayload(initFailureMessage(e, dockerExecutor), initFailureType(e)),
|
||||
|
||||
@@ -5,6 +5,7 @@ import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.ContainerTeardown;
|
||||
import io.floci.aws.core.common.ContainerTeardowns;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.core.common.docker.DockerCapacityExceededException;
|
||||
import io.floci.aws.services.lambda.launcher.ContainerHandle;
|
||||
import io.floci.aws.services.lambda.launcher.LambdaRuntimeLauncher;
|
||||
import io.floci.aws.services.lambda.model.ContainerState;
|
||||
@@ -292,7 +293,7 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
if (launching) {
|
||||
LOG.debugv(ephemeral ? "Ephemeral start for function: {0}" : "Cold start for function: {0}",
|
||||
fn.getFunctionName());
|
||||
handle = lambdaRuntimeLauncher.launch(fn);
|
||||
handle = launchWithinBudget(fn);
|
||||
owned.add(handle);
|
||||
} else {
|
||||
LOG.debugv("Reusing warm container for function: {0}", fn.getFunctionName());
|
||||
@@ -410,6 +411,48 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Launches a container for {@code fn}. When Lambda's Docker budget
|
||||
* ({@code floci.docker.service-max-containers.lambda}) refuses it, the least recently used idle
|
||||
* container of any function is stopped and the launch tried once more, so the budget bounds the
|
||||
* containers doing work rather than the warm ones; the refusal stands only when none is idle.
|
||||
*/
|
||||
private ContainerHandle launchWithinBudget(LambdaFunction fn) {
|
||||
try {
|
||||
return lambdaRuntimeLauncher.launch(fn);
|
||||
} catch (RuntimeException e) {
|
||||
if (DockerCapacityExceededException.findIn(e) == null) {
|
||||
throw e;
|
||||
}
|
||||
List<ContainerHandle> evicted;
|
||||
synchronized (capLock) {
|
||||
int idle = idleTotal();
|
||||
evicted = idle == 0 ? List.of() : evictIdleBeyond(idle - 1);
|
||||
}
|
||||
if (evicted.isEmpty()) {
|
||||
throw e;
|
||||
}
|
||||
for (ContainerHandle victim : evicted) {
|
||||
LOG.infov("Lambda''s Docker budget is full; stopping least-recently-used idle container {0} of"
|
||||
+ " function {1} to launch one for {2}", victim.getContainerId(), victim.getFunctionName(),
|
||||
fn.getFunctionName());
|
||||
stopQuietly(victim);
|
||||
}
|
||||
return lambdaRuntimeLauncher.launch(fn);
|
||||
}
|
||||
}
|
||||
|
||||
/** Idle containers across every function. Must be called under {@link #capLock}. */
|
||||
private int idleTotal() {
|
||||
int total = 0;
|
||||
for (PoolState poolState : poolStates.values()) {
|
||||
synchronized (poolState) {
|
||||
total += idleSize(poolState);
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes idle containers, oldest {@code lastUsed} first across every function, until at
|
||||
* most {@code keep} remain, and returns the removed handles for the caller to stop outside
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.DockerCapacityExceededException;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.core.common.docker.DockerPlatforms;
|
||||
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
|
||||
@@ -509,8 +510,13 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
// leaks one per attempt and exhausts the pool) and reap any half-built container (leaked
|
||||
// "Created" containers bog the daemon and starve reuse). containerId is null when we
|
||||
// failed before the container was created (e.g. an ensureCodeVolume populate failure).
|
||||
LOG.errorv("Container launch failed for function {0}; cleaning up: {1}",
|
||||
fn.getFunctionName(), e.getMessage());
|
||||
if (e instanceof DockerCapacityExceededException) {
|
||||
// A full Docker budget is a throttle the caller sees, not a failed launch.
|
||||
LOG.warnv("Not launching a container for function {0}: {1}", fn.getFunctionName(), e.getMessage());
|
||||
} else {
|
||||
LOG.errorv("Container launch failed for function {0}; cleaning up: {1}",
|
||||
fn.getFunctionName(), e.getMessage());
|
||||
}
|
||||
if (containerId != null) {
|
||||
try {
|
||||
lifecycleManager.stopAndRemoveStrict(containerId, null);
|
||||
|
||||
+2
-1
@@ -101,7 +101,8 @@ public class RedshiftContainerManager {
|
||||
.withEnv(envVars)
|
||||
.withCmd(List.of("postgres", "-c", "allow_system_table_mods=on", "-c", "max_connections=" + maxConnections))
|
||||
.withDockerNetwork(config.services().redshift().dockerNetwork())
|
||||
.withLogRotation();
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels("redshift", clusterIdentifier, accountId, null));
|
||||
|
||||
int enginePort = 5432; // Default postgres port
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
|
||||
@@ -96,7 +96,9 @@ public class SageMakerEndpointManager implements ContainerTeardown, Resettable {
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withEmbeddedDns()
|
||||
.withPortBinding(PORT, 0)
|
||||
.withLogRotation();
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"sagemaker", endpoint.endpointName, endpoint.accountId, endpoint.region));
|
||||
applyEntrypoint(builder, c, "serve");
|
||||
ContainerSpec spec = builder.build();
|
||||
containerId = lifecycleManager.create(spec);
|
||||
|
||||
@@ -101,7 +101,9 @@ public class SageMakerTrainingRunner implements ContainerTeardown, Resettable {
|
||||
.withDockerNetwork(config.services().sagemaker().dockerNetwork())
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withEmbeddedDns()
|
||||
.withLogRotation();
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"sagemaker", job.trainingJobName, job.accountId, job.region));
|
||||
SageMakerEndpointManager.applyEntrypoint(builder, job.algorithmSpecification, "train");
|
||||
// Throws when the requested instance type asks for hardware this host cannot
|
||||
// stand in for, so the job fails with a reason rather than quietly training
|
||||
|
||||
Reference in new issue
Block a user