feat(docker): per-service container budgets that answer with each service's capacity error (#9176)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-22 14:26:03 -04:00
1 parent 5c62948838
commit 8183404fbd
18 files changed
+490 -8

No files matched your search

+15
View File
@@ -149,6 +149,20 @@ floci:
Environment variable: `FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES`
### Per-service container budgets
`service-max-containers` caps how many containers one service may run at once, keyed by the service's `io.floci.service` label, so one busy service cannot take every container the Docker host can hold. A request that would start one more fails at once with the capacity or limit error that service's API declares, so the SDK reports it the way it would on AWS: Lambda `Invoke` answers `TooManyRequestsException` (429, retried by the SDKs, and an asynchronous invocation is retried like a throttled one), RDS `InsufficientDBInstanceCapacity`, ElastiCache `InsufficientCacheClusterCapacity`, Redshift `InsufficientClusterCapacity`, MemoryDB `InsufficientClusterCapacityFault`, DocumentDB and Neptune `DBClusterQuotaExceededFault`, MSK `TooManyRequestsException`, OpenSearch `LimitExceededException`, CodeBuild `AccountLimitExceededException`, SageMaker `ResourceLimitExceeded` and Glue `ConcurrentRunsExceededException`; a service without such an error gets `ThrottlingException`. A job that starts its container after the request returns (a build, a training job, a Glue run, an ECS task) fails the job instead. A Lambda container left warm counts until a launch needs its slot: the least recently used idle container of any function is stopped first, and an invoke is throttled only when none is idle. The count is of the containers Floci created and has not removed, so one removed outside Floci (`docker rm`, a prune) keeps its slot until Floci restarts. No service is limited by default:
```yaml
floci:
docker:
service-max-containers:
lambda: 50
rds: 4
```
Environment variables: `FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_<SERVICE>`, with the label in upper case (`FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_LAMBDA=50`)
## 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.
@@ -409,6 +423,7 @@ caller keeps its existing failure handling after retries are exhausted.
| `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_SERVICE_MAX_CONTAINERS_<SERVICE>` | _(none)_ | Most containers one service runs at once, by its `io.floci.service` label; unset means unlimited |
| `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 |
@@ -152,6 +152,7 @@ This foundation release provides opt-in security-group filtering for EC2 Docker
| `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_SERVICE_MAX_CONTAINERS_<SERVICE>` | _(none)_ | Most containers one service runs at once, named by its `io.floci.service` label in upper case (`FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_LAMBDA=50`); a create past it fails with that service's own capacity error. A service not set is not limited. See [Docker Configuration](docker.md#per-service-container-budgets) |
| `FLOCI_DOCKER_LOG_POLL_INTERVAL_MILLIS` | `1000` | Milliseconds between the reads of a long-lived service container's log, read on a timer instead of followed; at least 100. See [Docker Configuration](docker.md#container-log-settings) |
| `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`) |
@@ -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);
@@ -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
@@ -0,0 +1,111 @@
package io.floci.aws.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.lambda.launcher.ImageCacheService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class DockerServiceBudgetTest {
private static final String SERVICE = "budget-test-rds";
@AfterEach
void forgetContainers() {
for (int i = 0; i < 4; i++) {
DockerContainerServices.forget("budget-container-" + i);
}
}
// Catches: the AWS error a client sees for an exhausted budget, which decides whether its SDK backs off.
@Test
void anExhaustedBudgetIsTheServicesOwnCapacityError() {
DockerCapacityExceededException lambda = new DockerCapacityExceededException("lambda", 2);
assertEquals("TooManyRequestsException", lambda.getErrorCode());
assertEquals(429, lambda.getHttpStatus());
DockerCapacityExceededException rds = new DockerCapacityExceededException("rds", 2);
assertEquals("InsufficientDBInstanceCapacity", rds.getErrorCode());
assertEquals(400, rds.getHttpStatus());
assertTrue(rds.getMessage().contains("floci.docker.service-max-containers.rds"), rds.getMessage());
// botocore models DBClusterQuotaExceededFault as a 403 for both DocumentDB and Neptune.
assertEquals(403, new DockerCapacityExceededException("docdb", 1).getHttpStatus());
assertEquals(403, new DockerCapacityExceededException("neptune", 1).getHttpStatus());
assertEquals("ThrottlingException", new DockerCapacityExceededException("ecs", 1).getErrorCode());
}
// Catches: a service's removed containers still counting against it, or a reservation never coming back.
@Test
void liveContainersAndReservationsCountUntilRemovedOrReleased() {
DockerContainerServices.record("budget-container-0", "budget-name-0",
Map.of(ContainerStorageHelper.SERVICE_LABEL, SERVICE));
DockerServiceBudget.reserve(SERVICE, 2);
assertThrows(DockerCapacityExceededException.class, () -> DockerServiceBudget.reserve(SERVICE, 2),
"one live container and one reservation fill a budget of two");
DockerServiceBudget.release(SERVICE);
assertDoesNotThrow(() -> DockerServiceBudget.reserve(SERVICE, 2));
DockerServiceBudget.release(SERVICE);
DockerContainerServices.forget("budget-name-0");
assertEquals(0, DockerContainerServices.liveContainers(SERVICE), "a remove by name forgets the container");
}
// Catches: the budget not enforced at the one place every container create passes, or a create over
// budget still reaching the daemon.
@Test
void aCreatePastTheBudgetFailsBeforeReachingTheDaemon() {
DockerClient docker = mock(DockerClient.class);
CreateContainerCmd create = mock(CreateContainerCmd.class, RETURNS_SELF);
when(docker.createContainerCmd(any())).thenReturn(create);
AtomicInteger ids = new AtomicInteger();
when(create.exec()).thenAnswer(invocation -> {
CreateContainerResponse response = mock(CreateContainerResponse.class);
when(response.getId()).thenReturn("budget-container-" + ids.getAndIncrement());
return response;
});
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.DockerConfig dockerConfig = mock(EmulatorConfig.DockerConfig.class);
when(config.docker()).thenReturn(dockerConfig);
when(config.tls()).thenReturn(mock(EmulatorConfig.TlsConfig.class));
when(dockerConfig.resourceNamespace()).thenReturn(Optional.empty());
when(dockerConfig.serviceMaxContainers()).thenReturn(Map.of(SERVICE, 1));
ImageCacheService images = mock(ImageCacheService.class);
when(images.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, images, null, config);
ContainerSpec spec = new ContainerSpec(
"busybox:stable", null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null,
List.of(), List.of(), List.of(), Map.of(ContainerStorageHelper.SERVICE_LABEL, SERVICE), null, false,
null, List.of(), null, null, List.of());
assertEquals("budget-container-0", manager.create(spec));
DockerCapacityExceededException e = assertThrows(DockerCapacityExceededException.class,
() -> manager.create(spec));
assertEquals(SERVICE, e.service());
verify(create, times(1)).exec();
DockerContainerServices.forget("budget-container-0");
assertEquals("budget-container-1", manager.create(spec), "a removed container frees its place");
}
}
@@ -3,6 +3,7 @@ package io.floci.aws.services.lambda;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.DelayedTaskScheduler;
import io.floci.aws.core.common.docker.DockerCapacityExceededException;
import io.floci.aws.services.lambda.launcher.ContainerHandle;
import io.floci.aws.services.lambda.model.ContainerState;
import io.floci.aws.services.lambda.model.FunctionEventInvokeConfig;
@@ -748,6 +749,44 @@ class LambdaExecutorServiceTest {
verify(warmPool, never()).acquire(any());
}
// Catches: a launch refused by Lambda's Docker budget answered as an Unhandled function error
// instead of the throttle an SDK backs off from, or the refusal lost when the launch wraps it.
@Test
void syncInvocation_overTheDockerBudget_answersTooManyRequests() {
when(warmPool.acquire(fn)).thenThrow(
new IllegalStateException("launch failed", new DockerCapacityExceededException("lambda", 2)));
AwsException ex = assertThrows(AwsException.class,
() -> executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse));
assertEquals("TooManyRequestsException", ex.getErrorCode());
assertEquals(429, ex.getHttpStatus());
}
// Catches: an event refused by Lambda's Docker budget routed as a failure, or retried at once
// instead of backed off like a throttled one without spending an attempt.
@Test
void eventInvocation_overTheDockerBudget_backsOffWithoutSpendingAnAttempt() throws Exception {
AsyncInvokeDestinationRouter router = mock(AsyncInvokeDestinationRouter.class);
ManualRetries retries = new ManualRetries();
LambdaExecutorService retryExecutor = manualRetryExecutor(router, eventInvokeConfig(0, 21600), retries);
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
List<Long> enqueuedAt = failEveryAttempt(rtas, failedAttempt("req-over-budget"));
ContainerHandle handle = warmPool.acquire(fn);
when(warmPool.acquire(any()))
.thenThrow(new DockerCapacityExceededException("lambda", 2))
.thenReturn(handle);
CountDownLatch routed = countRoutes(router);
byte[] payload = "{}".getBytes();
retryExecutor.invoke(fn, payload, InvocationType.Event);
retries.runUntil(routed);
assertEquals(List.of(1000L), retries.delays);
assertEquals(1, enqueuedAt.size());
verify(router).route(eq(fn), eq(payload), any(InvokeResult.class), eq(1), eq(0), isNull());
}
@Test
void syncInvocation_withZeroReservedConcurrency_isThrottled() {
fn.setReservedConcurrentExecutions(0);
@@ -2,6 +2,7 @@ package io.floci.aws.services.lambda;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
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;
@@ -1123,6 +1124,50 @@ class WarmPoolTest {
pool.shutdown();
}
// Catches: other functions' idle warm containers holding every slot of Lambda's Docker budget, so a
// new function is throttled while nothing runs, or the refusal surviving when an idle one could go.
@Test
void aFullDockerBudgetStopsTheLeastRecentlyUsedIdleContainerAndLaunchesAgain() {
WarmPool pool = buildPool();
pool.init();
LambdaFunction fnA = function("fn-a");
LambdaFunction fnB = function("fn-b");
ContainerHandle a1 = new ContainerHandle("cid-a1", "fn-a", null, ContainerState.WARM);
ContainerHandle a2 = new ContainerHandle("cid-a2", "fn-a", null, ContainerState.WARM);
ContainerHandle b1 = new ContainerHandle("cid-b1", "fn-b", null, ContainerState.WARM);
when(containerLauncher.launch(fnA)).thenReturn(a1, a2);
ContainerHandle leasedA1 = pool.acquire(fnA);
ContainerHandle leasedA2 = pool.acquire(fnA);
pool.release(leasedA1);
nextMillisecond();
pool.release(leasedA2);
when(containerLauncher.launch(fnB))
.thenThrow(new IllegalStateException("launch failed", new DockerCapacityExceededException("lambda", 2)))
.thenReturn(b1);
assertSame(b1, pool.acquire(fnB));
verify(containerLauncher).stop(a1);
verify(containerLauncher, never()).stop(a2);
verify(containerLauncher, times(2)).launch(fnB);
pool.shutdown();
}
// Catches: a budget refusal swallowed, or retried, when no idle container could make room.
@Test
void aFullDockerBudgetWithNothingIdleStillRefuses() {
WarmPool pool = buildPool();
pool.init();
LambdaFunction fnB = function("fn-b");
DockerCapacityExceededException full = new DockerCapacityExceededException("lambda", 2);
when(containerLauncher.launch(fnB)).thenThrow(full);
assertSame(full, assertThrows(DockerCapacityExceededException.class, () -> pool.acquire(fnB)));
verify(containerLauncher, times(1)).launch(fnB);
pool.shutdown();
}
@Test
void totalCap_evictsLeastRecentlyUsedAcrossFunctions() {
WarmPool pool = buildPool(Optional.empty(), 2);
@@ -52,6 +52,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.clearInvocations;
@@ -244,6 +245,21 @@ class RedshiftContainerManagerTest {
assertEquals(400, ex.getHttpStatus());
}
// Catches: a Redshift cluster's container without its io.floci.service label, which leaves it outside
// floci.docker.service-max-containers.redshift and its InsufficientClusterCapacity error.
@Test
void theClusterContainerCarriesTheRedshiftServiceLabel() {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(
new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432))));
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
verify(specBuilder).withLabels(argThat(labels -> "redshift".equals(labels.get("io.floci.service"))
&& "test-cluster".equals(labels.get("io.floci.resource-id"))));
}
@Test
void takeSnapshotSuccess() throws Exception {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
@@ -6,6 +6,7 @@ import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.sagemaker.model.SageMakerEntities.EndpointResource;
import io.floci.aws.services.sagemaker.model.SageMakerEntities.ModelResource;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
@@ -13,9 +14,15 @@ import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* A state reset runs the container teardown, which shuts the worker pool down, then
@@ -67,6 +74,39 @@ class SageMakerEndpointManagerTest {
manager.stopManagedContainers();
}
// Catches: an endpoint's container without its io.floci.service label, which leaves it outside
// floci.docker.service-max-containers.sagemaker and its ResourceLimitExceeded error.
@Test
void anEndpointContainerCarriesTheSageMakerServiceLabel() throws InterruptedException {
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.create(any())).thenThrow(new IllegalStateException("stop after the spec"));
SageMakerEndpointManager manager = new SageMakerEndpointManager(containerBuilder, lifecycleManager,
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), mock(ContainerDetector.class), mock(S3Service.class));
SageMakerService service = mock(SageMakerService.class);
EndpointResource endpoint = new EndpointResource();
endpoint.endpointName = "labelled";
endpoint.region = "us-east-1";
endpoint.accountId = "000000000000";
ModelResource model = new ModelResource();
model.primaryContainer.put("Image", "example/serve:1");
when(service.modelForEndpoint(endpoint)).thenReturn(model);
CountDownLatch published = new CountDownLatch(1);
doAnswer(invocation -> {
published.countDown();
return true;
}).when(service).finalizeEndpointStart(endpoint);
manager.startEndpointAsync(endpoint, service);
assertTrue(published.await(5, TimeUnit.SECONDS));
verify(specBuilder).withLabels(argThat(labels -> "sagemaker".equals(labels.get("io.floci.service"))
&& "labelled".equals(labels.get("io.floci.resource-id"))));
manager.stopManagedContainers();
}
private static SageMakerEndpointManager manager() {
return new SageMakerEndpointManager(mock(ContainerBuilder.class), mock(ContainerLifecycleManager.class),
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), mock(ContainerDetector.class), mock(S3Service.class));