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

@@ -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));