diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index f54fd58ce6..d91603361c 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -350,6 +350,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s | `FLOCI_SERVICES_LAMBDA_KUBERNETES_TOLERATIONS` | _(none)_ | Pod tolerations as comma-separated taints in `kubectl taint` syntax: `key=value:Effect` (operator `Equal`) or `key:Effect` (operator `Exists`); leave out `:Effect` to tolerate every effect | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_FLOCI_ADDRESS` | _(none)_ | Host/IP Lambda pods use to reach Floci; auto-detected when Floci runs in-cluster | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_INIT_IMAGE` | `busybox:1.36` | Init-container image that downloads function code into the pod (needs `sh`, `wget`, `unzip`) | +| `FLOCI_SERVICES_LAMBDA_KUBERNETES_UNSCHEDULABLE_GRACE_SECONDS` | `0` | Seconds a pod the scheduler reports Unschedulable may wait while a cluster autoscaler adds a node, measured from when Floci first observes the reason; `0` fails the cold start immediately | ### API Gateway diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 49cdcecc66..a435375b01 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -762,6 +762,7 @@ Configuration resource reads and `ListFunctionsByCodeSigningConfig` return | `FLOCI_SERVICES_LAMBDA_KUBERNETES_TOLERATIONS` | *(unset)* | Pod tolerations as comma-separated taints in `kubectl taint` syntax: `key=value:Effect` (operator `Equal`) or `key:Effect` (operator `Exists`); leave out `:Effect` to tolerate every effect | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_FLOCI_ADDRESS` | *(unset)* | Host/IP pods use to reach Floci; auto-detected when Floci runs in-cluster | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_INIT_IMAGE` | `busybox:1.36` | Init-container image that downloads function code (needs `sh`, `wget`, `unzip`) | +| `FLOCI_SERVICES_LAMBDA_KUBERNETES_UNSCHEDULABLE_GRACE_SECONDS` | `0` | Seconds a pod the scheduler reports Unschedulable may wait while a cluster autoscaler adds a node, measured from when Floci first observes the reason (the PodScheduled condition's lastTransitionTime records status transitions only, so it is not used); `0` fails the cold start immediately | !!! note "Changing the container name prefix" Code volumes are resolved by name, and a Floci process only manages resources under its diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index c7582a5019..27b42a9af9 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -3860,6 +3860,20 @@ public interface EmulatorConfig { */ @WithDefault("busybox:1.36") String initImage(); + + /** + * Seconds a Lambda pod the scheduler marks Unschedulable may stay that way before + * its cold start is failed, so a cluster autoscaler has time to add a node. The + * grace is measured from when this launcher first observes the Unschedulable + * reason (the PodScheduled condition's lastTransitionTime records status + * transitions only, so a SchedulingGated to Unschedulable flip keeps the older + * timestamp), and {@code 0}, the default, keeps failing the cold start the + * moment the pod is reported Unschedulable. + * + * Env var: FLOCI_SERVICES_LAMBDA_KUBERNETES_UNSCHEDULABLE_GRACE_SECONDS + */ + @WithDefault("0") + int unschedulableGraceSeconds(); } HotReload hotReload(); diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java index a98e2482bd..8e6c29123f 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java @@ -32,6 +32,7 @@ import org.jboss.logging.Logger; import java.io.Closeable; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -43,6 +44,7 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.LongSupplier; /** * Runs each Lambda execution environment as a Kubernetes pod. Mirrors @@ -104,6 +106,18 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { private volatile boolean orphansSwept = false; /** Names of pods created by this process, so a retried orphan sweep never deletes them. */ private final Set ownPodNames = ConcurrentHashMap.newKeySet(); + /** + * When each pod was first observed Unschedulable, keyed by pod name, so the grace period is + * measured from an observation this process can vouch for; cleared when the pod's cold-start + * wait ends. + */ + private final ConcurrentHashMap unschedulableObservedAt = new ConcurrentHashMap<>(); + /** + * Nanosecond clock the grace is measured on, a package-private constructor argument so a test + * can advance it and simulate a grace expiry without waiting it out in real time, as + * {@code LambdaExitWatcher}'s {@code nanoClock} does. + */ + private final LongSupplier unschedulableClock; private final AtomicBoolean caConfigMapApplied = new AtomicBoolean(false); private final AtomicBoolean awsConfigPathWarned = new AtomicBoolean(false); @@ -120,6 +134,23 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { KubernetesPodLogStreamer logStreamer, S3Service s3Service, PreSignedUrlGenerator presignGenerator) { + this(client, config, regionResolver, runtimeApiServerFactory, imageResolver, addressResolver, awsEnv, + layerService, podSpecFactory, logStreamer, s3Service, presignGenerator, System::nanoTime); + } + + KubernetesPodLauncher(KubernetesApiClient client, + EmulatorConfig config, + RegionResolver regionResolver, + RuntimeApiServerFactory runtimeApiServerFactory, + ImageResolver imageResolver, + KubernetesFlociAddressResolver addressResolver, + LaunchedContainerAwsEnv awsEnv, + LambdaLayerService layerService, + LambdaPodSpecFactory podSpecFactory, + KubernetesPodLogStreamer logStreamer, + S3Service s3Service, + PreSignedUrlGenerator presignGenerator, + LongSupplier unschedulableClock) { this.client = client; this.config = config; this.regionResolver = regionResolver; @@ -132,6 +163,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { this.logStreamer = logStreamer; this.s3Service = s3Service; this.presignGenerator = presignGenerator; + this.unschedulableClock = unschedulableClock; } /** @@ -426,6 +458,8 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { } catch (Exception e) { throw new RuntimeException("Pod " + podName + " for function '" + functionName + "' did not reach Running within " + timeoutSeconds + "s: " + e.getMessage(), e); + } finally { + unschedulableObservedAt.remove(podName); } if (pod == null || !isRunning(pod)) { throw new RuntimeException("Pod " + podName + " for function '" + functionName @@ -437,13 +471,13 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { return "Running".equals(pod.path("status").path("phase").asText(null)); } - private static boolean hasTerminalFailure(JsonNode pod) { + private boolean hasTerminalFailure(JsonNode pod) { String phase = pod.path("status").path("phase").asText(null); // Succeeded means the runtime exited before serving — terminal for a server pod. if ("Failed".equals(phase) || "Succeeded".equals(phase)) { return true; } - return unschedulableReason(pod) != null || describeTerminalReason(pod) != null; + return unschedulableFailure(pod) != null || describeTerminalReason(pod) != null; } private static String unschedulableReason(JsonNode pod) { @@ -460,6 +494,37 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { return null; } + /** + * Why a cold start must fail because the pod is Unschedulable, or null while the pod may + * still wait. With {@code unschedulable-grace-seconds} set, a pod the scheduler could not + * place gets that long for a cluster autoscaler to add a node, measured from when this + * launcher first observes the reason. The PodScheduled condition's lastTransitionTime is + * not usable as that anchor: per the Kubernetes API it records status transitions only, + * so a reason flip from SchedulingGated to Unschedulable keeps the gating's older + * timestamp, which can exhaust the grace before the autoscaler has had its configured + * time. A pod already Unschedulable when the invocation arrives gets the grace from its + * first poll, and the startup timeout still bounds the wait. Once the grace is out, the + * pod is terminal as before. + */ + private String unschedulableFailure(JsonNode pod) { + String reason = unschedulableReason(pod); + if (reason == null) { + return null; + } + int grace = config.services().lambda().kubernetes().unschedulableGraceSeconds(); + if (grace <= 0) { + return reason; + } + long firstObserved = unschedulableObservedAt.computeIfAbsent(podName(pod), + ignored -> unschedulableClock.getAsLong()); + return unschedulableClock.getAsLong() - firstObserved >= Duration.ofSeconds(grace).toNanos() + ? reason : null; + } + + private static String podName(JsonNode pod) { + return pod.path("metadata").path("name").asText(); + } + private static String describeTerminalReason(JsonNode pod) { for (JsonNode statuses : List.of(pod.path("status").path("initContainerStatuses"), pod.path("status").path("containerStatuses"))) { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 9a999283cc..6d46815dfb 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -559,6 +559,7 @@ floci: # - workload-type=lambda:NoSchedule # floci-address: # Host/IP pods use to reach Floci; auto-detected in-cluster # init-image: busybox:1.36 # Init container image (needs sh, wget, unzip) + # unschedulable-grace-seconds: 0 # Seconds an Unschedulable pod may wait while a cluster autoscaler adds a node (0 = fail the cold start immediately) hot-reload: enabled: false reactive-s3-sync: diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java index b34c2a7ce7..f83e4c6888 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java @@ -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 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 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 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"));