feat(lambda): give Unschedulable pods a kubernetes grace period (#9109)

With floci.services.lambda.kubernetes.unschedulable-grace-seconds (FLOCI_SERVICES_LAMBDA_KUBERNETES_UNSCHEDULABLE_GRACE_SECONDS, default 0), a Lambda pod the Kubernetes scheduler reports Unschedulable gets that long before its cold start fails, so a node autoscaler such as Karpenter can add a node. The grace is measured from when Floci first observes the reason, since the PodScheduled condition's lastTransitionTime keeps an older timestamp across a SchedulingGated to Unschedulable flip, and the pod startup timeout still bounds the wait. The default keeps the immediate failure.

Closes #8995
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-11-24 11:36:23 -04:00
1 parent 6c451bbcc5
commit 19d0955c7c
6 files changed
+236 -32

No files matched your search

@@ -4,9 +4,12 @@ import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodConditionBuilder;
import io.fabric8.kubernetes.api.model.PodStatus;
import io.fabric8.kubernetes.api.model.PodStatusBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.server.mock.EnableKubernetesMockClient;
import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.TlsConfigSource;
import io.floci.aws.core.common.AwsException;
@@ -43,12 +46,14 @@ import java.nio.file.Path;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -79,11 +84,14 @@ import static org.mockito.Mockito.when;
class KubernetesPodLauncherTest {
KubernetesClient client;
KubernetesMockServer mockServer;
@TempDir
Path tempDir;
private KubernetesApiClient apiClient;
private EmulatorConfig config;
private EmulatorConfig.LambdaServiceConfig.KubernetesExecutor kubernetes;
private final RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
private RuntimeApiServerFactory runtimeApiServerFactory;
private RuntimeApiServer runtimeApiServer;
@@ -101,7 +109,7 @@ class KubernetesPodLauncherTest {
config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
EmulatorConfig.LambdaServiceConfig.KubernetesExecutor kubernetes = mock(EmulatorConfig.LambdaServiceConfig.KubernetesExecutor.class);
kubernetes = mock(EmulatorConfig.LambdaServiceConfig.KubernetesExecutor.class);
EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
lenient().when(config.services()).thenReturn(services);
lenient().when(services.lambda()).thenReturn(lambda);
@@ -148,7 +156,7 @@ class KubernetesPodLauncherTest {
URI.create(client.getConfiguration().getMasterUrl()), trustAllHttpClient(), null);
launcher = new KubernetesPodLauncher(apiClient, config, regionResolver, runtimeApiServerFactory, imageResolver,
addressResolver, awsEnv, layerService, new LambdaPodSpecFactory(config),
logStreamer, s3Service, presignGenerator);
logStreamer, s3Service, presignGenerator, System::nanoTime);
}
@ParameterizedTest
@@ -163,12 +171,13 @@ class KubernetesPodLauncherTest {
defaultAccount, region, Map.of(defaultAccount, defaultLayer, owner, ownerLayer));
KubernetesPodLauncher backgroundLauncher = new KubernetesPodLauncher(
apiClient, config, regionResolver, runtimeApiServerFactory, imageResolver, addressResolver, awsEnv,
layers, new LambdaPodSpecFactory(config), logStreamer, s3Service, presignGenerator);
layers, new LambdaPodSpecFactory(config), logStreamer, s3Service, presignGenerator,
System::nanoTime);
LambdaFunction fn = function();
fn.setAccountId(account);
fn.setFunctionArn("arn:aws:lambda:" + region + ":" + account + ":function:my-fn");
fn.setLayers(List.of((defaultAccount.equals(account) ? defaultLayer : ownerLayer).getLayerVersionArn()));
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
markPodPhaseInBackground("Running");
ContainerHandle handle = CompletableFuture.supplyAsync(() -> backgroundLauncher.launch(fn))
.get(10, TimeUnit.SECONDS);
@@ -219,24 +228,27 @@ class KubernetesPodLauncherTest {
return fn;
}
/** Plays the kubelet: waits for a pod with the given name prefix, then sets its phase. */
private void markPodPhaseInBackground(String namePrefix, String phase) {
CompletableFuture.runAsync(() -> {
Awaitility.await().atMost(Duration.ofSeconds(5)).until(
() -> client.pods().inNamespace("default").list().getItems().stream()
.anyMatch(p -> p.getMetadata().getName().startsWith(namePrefix)));
Pod pod = client.pods().inNamespace("default").list().getItems().stream()
.filter(p -> p.getMetadata().getName().startsWith(namePrefix))
.findFirst().orElseThrow();
pod.setStatus(new PodStatusBuilder().withPhase(phase).build());
/**
* Plays the kubelet for the launcher's pod: waits for it, writes {@code status}, and
* completes once the mock server has accepted the write.
*/
private CompletableFuture<Void> markPodInBackground(PodStatus status) {
return CompletableFuture.runAsync(() -> {
awaitFlociLambdaPod();
Pod pod = flociLambdaPod();
pod.setStatus(status);
client.pods().inNamespace("default").resource(pod).updateStatus();
});
}
private void markPodPhaseInBackground(String phase) {
markPodInBackground(new PodStatusBuilder().withPhase(phase).build());
}
@ParameterizedTest
@CsvSource({"$LATEST, $$LATEST", "1, 1", "7, 7"})
void launchExposesTheExecutingVersionInThePodAndRuntimeApi(String version, String podValue) {
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
markPodPhaseInBackground("Running");
LambdaFunction fn = function();
fn.setVersion(version);
fn.setEnvironment(Map.of("AWS_LAMBDA_FUNCTION_VERSION", "user-override"));
@@ -254,7 +266,7 @@ class KubernetesPodLauncherTest {
@Test
void launchPassesTheLoggingConfigToTheRuntime() {
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
markPodPhaseInBackground("Running");
LambdaFunction fn = function();
fn.setLogFormat("JSON");
fn.setApplicationLogLevel("DEBUG");
@@ -274,7 +286,7 @@ class KubernetesPodLauncherTest {
// A pod-launched Lambda is subject to the same placeholder-credential bug as a
// Docker-launched one: without the owning account it resolves to the emulator's
// default account and reads the wrong partition.
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
markPodPhaseInBackground("Running");
LambdaFunction fn = function();
fn.setAccountId("222222222222");
fn.setFunctionArn("arn:aws:lambda:us-east-1:222222222222:function:my-fn");
@@ -291,7 +303,7 @@ class KubernetesPodLauncherTest {
// owner-account/placeholder baseline. If the function's own Environment config defines
// only AWS_ACCESS_KEY_ID (no matching secret or session token), that partial value must
// not override just the baseline's access key and leave its secret/token in place.
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
markPodPhaseInBackground("Running");
lenient().when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString()))
.thenReturn(List.of(
"AWS_ACCESS_KEY_ID=000000000000",
@@ -302,9 +314,7 @@ class KubernetesPodLauncherTest {
launcher.launch(fn);
Pod pod = client.pods().inNamespace("default").list().getItems().stream()
.filter(p -> p.getMetadata().getName().startsWith("floci-lambda-my-fn-"))
.findFirst().orElseThrow();
Pod pod = flociLambdaPod();
List<EnvVar> envVars = pod.getSpec().getContainers().getFirst().getEnv();
assertThat(envVars).extracting(EnvVar::getName, EnvVar::getValue)
.contains(tuple("AWS_ACCESS_KEY_ID", "000000000000"))
@@ -313,7 +323,7 @@ class KubernetesPodLauncherTest {
@Test
void launchCreatesPodAndReturnsHandle() {
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
markPodPhaseInBackground("Running");
ContainerHandle handle = launcher.launch(function());
@@ -342,7 +352,7 @@ class KubernetesPodLauncherTest {
LambdaFunction fn = function();
fn.setAccountId("111122223333");
fn.setFunctionArn("arn:aws:lambda:us-east-1:111122223333:function:my-fn");
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
markPodPhaseInBackground("Running");
ContainerHandle handle = launcher.launch(fn);
@@ -358,7 +368,7 @@ class KubernetesPodLauncherTest {
@Test
void launchFailureReleasesPortAndDeletesPod() {
markPodPhaseInBackground("floci-lambda-my-fn-", "Failed");
markPodPhaseInBackground("Failed");
assertThatThrownBy(() -> launcher.launch(function()))
.isInstanceOf(RuntimeException.class)
@@ -380,8 +390,8 @@ class KubernetesPodLauncherTest {
doThrow(new RuntimeException("kube api down")).when(failingApiClient).deletePod(anyString(), anyString());
KubernetesPodLauncher failingLauncher = new KubernetesPodLauncher(failingApiClient, config, regionResolver,
runtimeApiServerFactory, imageResolver, addressResolver, awsEnv, layerService,
new LambdaPodSpecFactory(config), logStreamer, s3Service, presignGenerator);
markPodPhaseInBackground("floci-lambda-my-fn-", "Failed");
new LambdaPodSpecFactory(config), logStreamer, s3Service, presignGenerator, System::nanoTime);
markPodPhaseInBackground("Failed");
assertThatThrownBy(() -> failingLauncher.launch(function()))
.isInstanceOf(RuntimeException.class);
@@ -397,7 +407,7 @@ class KubernetesPodLauncherTest {
void podThatExitsCleanlyIsTerminalNotATimeout() {
// A runtime that exits before serving parks the pod in Succeeded; the launch
// must fail fast instead of blocking for the full startup timeout.
markPodPhaseInBackground("floci-lambda-my-fn-", "Succeeded");
markPodPhaseInBackground("Succeeded");
assertThatThrownBy(() -> launcher.launch(function()))
.isInstanceOf(RuntimeException.class)
@@ -405,6 +415,118 @@ class KubernetesPodLauncherTest {
verify(runtimeApiServerFactory).release(runtimeApiServer);
}
@Test
void unschedulablePodFailsTheColdStartImmediately() {
markUnschedulableInBackground(Instant.now());
assertThatThrownBy(() -> launcher.launch(function()))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("Unschedulable");
verify(runtimeApiServerFactory).release(runtimeApiServer);
}
@Test
void unschedulablePodIsGivenTheGracePeriodWhileTheAutoscalerAddsANode() {
// With the grace period on, the pod reported Unschedulable moments ago is not
// terminal yet: the autoscaler needs it in that state to add a node, and the pod
// reaches Running once the node joins.
lenient().when(kubernetes.unschedulableGraceSeconds()).thenReturn(30);
markUnschedulableThenRunningInBackground(Instant.now());
ContainerHandle handle = launcher.launch(function());
assertThat(handle.getContainerId()).startsWith("floci-lambda-");
}
@Test
void unschedulablePodFailsOnceTheGracePeriodIsOut() {
AtomicLong clock = new AtomicLong(System.nanoTime());
launcher = new KubernetesPodLauncher(apiClient, config, regionResolver,
runtimeApiServerFactory, imageResolver, addressResolver, awsEnv, layerService,
new LambdaPodSpecFactory(config), logStreamer, s3Service, presignGenerator, clock::get);
lenient().when(kubernetes.unschedulableGraceSeconds()).thenReturn(5);
// Once the launcher has read the Unschedulable status twice (anchoring the grace, then
// handling that read), advancing its clock past the configured seconds fails the cold
// start without waiting it out.
CompletableFuture.runAsync(() -> {
markUnschedulableInBackground(Instant.now()).join();
awaitLauncherPodRead();
awaitLauncherPodRead();
clock.addAndGet(Duration.ofSeconds(60).toNanos());
});
assertThatThrownBy(() -> launcher.launch(function()))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("Unschedulable");
verify(runtimeApiServerFactory).release(runtimeApiServer);
}
@Test
void aStalePodScheduledTransitionDoesNotExhaustTheGraceBeforeTheReasonFlipIsObserved() {
// PodScheduled.lastTransitionTime records status transitions only, so a
// SchedulingGated to Unschedulable flip keeps the gating's old timestamp; the grace
// is measured from when the launcher first observes the reason instead, and a pod
// reported Unschedulable with a ten minute old timestamp still reaches Running.
lenient().when(kubernetes.unschedulableGraceSeconds()).thenReturn(30);
markUnschedulableThenRunningInBackground(Instant.now().minusSeconds(600));
ContainerHandle handle = launcher.launch(function());
assertThat(handle.getContainerId()).startsWith("floci-lambda-");
}
/** The Unschedulable status Karpenter's cluster leaves, reported since {@code since}. */
private static PodStatus unschedulableStatus(Instant since) {
return new PodStatusBuilder()
.withPhase("Pending")
.withConditions(new PodConditionBuilder()
.withType("PodScheduled")
.withStatus("False")
.withReason("Unschedulable")
.withMessage("Insufficient memory")
.withLastTransitionTime(since.toString())
.build())
.build();
}
private CompletableFuture<Void> markUnschedulableInBackground(Instant since) {
return markPodInBackground(unschedulableStatus(since));
}
/**
* Reports the pod Unschedulable since {@code since}, then Running once the launcher has
* read that status: the mock server's request count rising past the write proves the
* launcher's poll observed Unschedulable, so the grace is anchored before the node joins,
* without a fixed sleep.
*/
private void markUnschedulableThenRunningInBackground(Instant since) {
CompletableFuture.runAsync(() -> {
markUnschedulableInBackground(since).join();
awaitLauncherPodRead();
markPodInBackground(new PodStatusBuilder().withPhase("Running").build());
});
}
private void awaitLauncherPodRead() {
int readsAfterWrite = mockServer.getRequestCount();
Awaitility.await().atMost(Duration.ofSeconds(10)).until(
() -> mockServer.getRequestCount() > readsAfterWrite);
}
/** The pod this launcher created for {@code my-fn}, by its managed name prefix. */
private Pod flociLambdaPod() {
return client.pods().inNamespace("default").list().getItems().stream()
.filter(p -> p.getMetadata().getName().startsWith("floci-lambda-my-fn-"))
.findFirst().orElseThrow();
}
private void awaitFlociLambdaPod() {
Awaitility.await().atMost(Duration.ofSeconds(5)).until(
() -> client.pods().inNamespace("default").list().getItems().stream()
.anyMatch(p -> p.getMetadata().getName().startsWith("floci-lambda-my-fn-")));
}
@Test
void hotReloadIsRejectedBeforeAllocatingAnything() {
LambdaFunction fn = function();
@@ -530,9 +652,9 @@ class KubernetesPodLauncherTest {
}).when(flakyApiClient).listPods(anyString(), anyMap());
KubernetesPodLauncher retryingLauncher = new KubernetesPodLauncher(flakyApiClient, config, regionResolver,
runtimeApiServerFactory, imageResolver, addressResolver, awsEnv, layerService,
new LambdaPodSpecFactory(config), logStreamer, s3Service, presignGenerator);
new LambdaPodSpecFactory(config), logStreamer, s3Service, presignGenerator, System::nanoTime);
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
markPodPhaseInBackground("Running");
ContainerHandle handle = retryingLauncher.launch(function());
assertThat(client.pods().inNamespace("default").withName("floci-lambda-old-fn-dead1234").get())
.as("orphan survives the failed sweep")
@@ -558,7 +680,7 @@ class KubernetesPodLauncherTest {
@Test
void tlsOnPublishesTheCaBundleAsAConfigMapAndTheFunctionEnvWins() throws Exception {
String bundlePem = enableTlsWithBundle();
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
markPodPhaseInBackground("Running");
LambdaFunction fn = function();
fn.setEnvironment(Map.of("SSL_CERT_FILE", "/my/own.pem"));