mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambda): support kubernetes as the lambda runner (#1941)
* feat(lambda): support kubernetes as the lambda runner * fix(lambda): keep the port reserved when a failed launch cannot confirm pod deletion * fix(lambda): carry the owning account in the layer Content.Location URL The URL is fetched unsigned. Without an X-Amz-Credential query the account filter falls back to the default account, so a layer published under another account resolves the wrong bucket namespace and 404s. Mirror the credential query the kubernetes executor already appends to its download URLs. * chore(build): raise the surefire heap to 6g The suite outgrew the 4g default heap of 16g CI runners. At OOM a full GC reclaims almost nothing, so the live set is real. The heap dump shows 192 surviving QuarkusClassLoader instances, each pinned test app keeping its own copy of the Jandex index. This PR widens the classpath with the kubernetes client, which made each pinned copy heavier and tipped CI over the edge. Verified locally that the full suite passes with 6g and fails with 4g. Unpinning the leaked classloaders remains follow-up work on main.
This commit is contained in:
1 parent
a732e26bc5
commit
bc13801121
25 files changed
+2557
-37
No files matched your search
+63
@@ -77,6 +77,9 @@ class LambdaLayerIntegrationTest {
|
||||
.body("CompatibleArchitectures", hasItem("x86_64"))
|
||||
.body("Content.CodeSize", greaterThan(0))
|
||||
.body("Content.CodeSha256", not(emptyString()))
|
||||
.body("Content.Location", containsString("awslambda-us-east-1-tasks/layers/"))
|
||||
.body("Content.Location", endsWith("/" + LAYER_NAME
|
||||
+ "/1?X-Amz-Credential=000000000000%2F00010101%2Fus-east-1%2Fs3%2Faws4_request"))
|
||||
.body("CreatedDate", not(emptyString()));
|
||||
}
|
||||
|
||||
@@ -293,6 +296,66 @@ class LambdaLayerIntegrationTest {
|
||||
.statusCode(204);
|
||||
}
|
||||
|
||||
// ── Stored layer archive in Floci's S3 ────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@Order(17)
|
||||
void layerArchive_version2_isDownloadableFromTasksBucket() {
|
||||
// Publish stores the archive in Floci's S3; the kubernetes executor's init
|
||||
// container downloads it from exactly this path. Version 2 is still present here.
|
||||
given()
|
||||
.when()
|
||||
.get("/awslambda-us-east-1-tasks/layers/000000000000/" + LAYER_NAME + "/2")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(18)
|
||||
void layerArchive_version1_isDeletedWithTheVersion() {
|
||||
// Version 1 was deleted at @Order(13); its stored archive must be gone too.
|
||||
given()
|
||||
.when()
|
||||
.get("/awslambda-us-east-1-tasks/layers/000000000000/" + LAYER_NAME + "/1")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(19)
|
||||
void contentLocation_ofNonDefaultAccountLayer_isFetchable() throws Exception {
|
||||
// The Location URL is fetched unsigned, so it must carry the owning account in
|
||||
// X-Amz-Credential. Without it the download resolves the default account's
|
||||
// bucket namespace and 404s for a layer published under another account.
|
||||
String location = given()
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/lambda/aws4_request, SignedHeaders=host, Signature=abc")
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{ "Content": { "ZipFile": "%s" } }
|
||||
""".formatted(layerZipBase64()))
|
||||
.when()
|
||||
.post("/2018-10-31/layers/" + LAYER_NAME + "-alt/versions")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("Content.Location", containsString("/layers/000000000001/"))
|
||||
.body("Content.Location", containsString("X-Amz-Credential=000000000001%2F"))
|
||||
.extract().path("Content.Location");
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(location)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/lambda/aws4_request, SignedHeaders=host, Signature=abc")
|
||||
.when()
|
||||
.delete("/2018-10-31/layers/" + LAYER_NAME + "-alt/versions/1")
|
||||
.then()
|
||||
.statusCode(204);
|
||||
}
|
||||
|
||||
// ── PublishLayerVersion validation ────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -2,7 +2,7 @@ package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ContainerHandle;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ContainerLauncher;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.LambdaRuntimeLauncher;
|
||||
import io.github.hectorvent.floci.services.lambda.model.ContainerState;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
|
||||
@@ -32,7 +32,7 @@ import static org.mockito.Mockito.when;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WarmPoolTest {
|
||||
|
||||
@Mock ContainerLauncher containerLauncher;
|
||||
@Mock LambdaRuntimeLauncher containerLauncher;
|
||||
@Mock EmulatorConfig config;
|
||||
|
||||
private WarmPool buildPool() {
|
||||
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package io.github.hectorvent.floci.services.lambda.launcher;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.kubernetes.KubernetesPodLauncher;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class LambdaRuntimeLauncherProducerTest {
|
||||
|
||||
@Mock EmulatorConfig config;
|
||||
@Mock Instance<ContainerLauncher> dockerInstance;
|
||||
@Mock Instance<KubernetesPodLauncher> kubernetesInstance;
|
||||
@Mock ContainerLauncher containerLauncher;
|
||||
@Mock KubernetesPodLauncher kubernetesPodLauncher;
|
||||
|
||||
private EmulatorConfig.LambdaServiceConfig lambda;
|
||||
private final LambdaRuntimeLauncherProducer producer = new LambdaRuntimeLauncherProducer();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
var services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.lambda()).thenReturn(lambda);
|
||||
when(dockerInstance.get()).thenReturn(containerLauncher);
|
||||
when(kubernetesInstance.get()).thenReturn(kubernetesPodLauncher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dockerExecutorSelectsContainerLauncher() {
|
||||
when(lambda.executor()).thenReturn("docker");
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance))
|
||||
.isSameAs(containerLauncher);
|
||||
verify(kubernetesInstance, never()).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void kubernetesExecutorSelectsPodLauncher() {
|
||||
when(lambda.executor()).thenReturn("kubernetes");
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance))
|
||||
.isSameAs(kubernetesPodLauncher);
|
||||
verify(dockerInstance, never()).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void executorValueIsCaseInsensitiveAndTrimmed() {
|
||||
when(lambda.executor()).thenReturn(" Kubernetes\n");
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance))
|
||||
.isSameAs(kubernetesPodLauncher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownExecutorFailsWithValidValues() {
|
||||
when(lambda.executor()).thenReturn("podman");
|
||||
assertThatThrownBy(() -> producer.launcher(config, dockerInstance, kubernetesInstance))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("docker, kubernetes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupValidationRejectsUnknownExecutorBeforeFirstInvoke() {
|
||||
when(lambda.executor()).thenReturn("podman");
|
||||
assertThatThrownBy(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupValidationAcceptsValidExecutors() {
|
||||
when(lambda.executor()).thenReturn("docker");
|
||||
assertThatCode(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance))
|
||||
.doesNotThrowAnyException();
|
||||
verify(kubernetesPodLauncher, never()).initializeClient();
|
||||
when(lambda.executor()).thenReturn("kubernetes");
|
||||
assertThatCode(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance))
|
||||
.doesNotThrowAnyException();
|
||||
verify(kubernetesPodLauncher).initializeClient();
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package io.github.hectorvent.floci.services.lambda.launcher.kubernetes;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class KubernetesFlociAddressResolverTest {
|
||||
|
||||
@Mock EmulatorConfig config;
|
||||
private EmulatorConfig.LambdaServiceConfig.KubernetesExecutor kubernetes;
|
||||
private EmulatorConfig.TlsConfig tls;
|
||||
private KubernetesFlociAddressResolver resolver;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
var services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
var lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
|
||||
kubernetes = mock(EmulatorConfig.LambdaServiceConfig.KubernetesExecutor.class);
|
||||
tls = mock(EmulatorConfig.TlsConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.lambda()).thenReturn(lambda);
|
||||
when(lambda.kubernetes()).thenReturn(kubernetes);
|
||||
when(lambda.runtimeApiBasePort()).thenReturn(9200);
|
||||
when(lambda.runtimeApiMaxPort()).thenReturn(9299);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(tls.enabled()).thenReturn(false);
|
||||
when(config.port()).thenReturn(4566);
|
||||
resolver = new KubernetesFlociAddressResolver(config);
|
||||
}
|
||||
|
||||
@Test
|
||||
void configuredAddressIsUsedVerbatim() {
|
||||
when(kubernetes.flociAddress()).thenReturn(Optional.of("192.168.1.20"));
|
||||
assertThat(resolver.resolve()).isEqualTo("192.168.1.20");
|
||||
assertThat(resolver.flociBaseUrl()).isEqualTo("http://192.168.1.20:4566");
|
||||
}
|
||||
|
||||
@Test
|
||||
void addressWithSchemeIsRejectedEarly() {
|
||||
when(kubernetes.flociAddress()).thenReturn(Optional.of("http://192.168.1.20"));
|
||||
assertThatThrownBy(resolver::resolve)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("bare host or IP");
|
||||
}
|
||||
|
||||
@Test
|
||||
void addressWithPortIsRejectedEarly() {
|
||||
when(kubernetes.flociAddress()).thenReturn(Optional.of("192.168.1.20:4566"));
|
||||
assertThatThrownBy(resolver::resolve)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("bare host or IP");
|
||||
}
|
||||
|
||||
@Test
|
||||
void addressWithShellHostileCharactersIsRejectedEarly() {
|
||||
// resolve() output is embedded in single-quoted init-container commands,
|
||||
// so anything beyond hostname/IP characters must fail fast.
|
||||
when(kubernetes.flociAddress()).thenReturn(Optional.of("10.0.0.5'; reboot;'"));
|
||||
assertThatThrownBy(resolver::resolve)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("bare host or IP");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tlsSwitchesBaseUrlScheme() {
|
||||
when(kubernetes.flociAddress()).thenReturn(Optional.of("floci.internal"));
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
assertThat(resolver.flociBaseUrl()).isEqualTo("https://floci.internal:4566");
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadBaseUrlStaysPlainHttpEvenWithTls() {
|
||||
when(kubernetes.flociAddress()).thenReturn(Optional.of("floci.internal"));
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
assertThat(resolver.downloadBaseUrl()).isEqualTo("http://floci.internal:4566");
|
||||
}
|
||||
}
|
||||
+376
@@ -0,0 +1,376 @@
|
||||
package io.github.hectorvent.floci.services.lambda.launcher.kubernetes;
|
||||
|
||||
import io.fabric8.kubernetes.api.model.EnvVar;
|
||||
import io.fabric8.kubernetes.api.model.PodBuilder;
|
||||
import io.fabric8.kubernetes.api.model.PodStatusBuilder;
|
||||
import io.fabric8.kubernetes.client.KubernetesClient;
|
||||
import io.fabric8.kubernetes.client.server.mock.EnableKubernetesMockClient;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ContainerHandle;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ImageResolver;
|
||||
import io.github.hectorvent.floci.services.lambda.model.ContainerState;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
|
||||
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServerFactory;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.tuple;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@EnableKubernetesMockClient(crud = true)
|
||||
class KubernetesPodLauncherTest {
|
||||
KubernetesClient client;
|
||||
|
||||
private EmulatorConfig config;
|
||||
private RuntimeApiServerFactory runtimeApiServerFactory;
|
||||
private RuntimeApiServer runtimeApiServer;
|
||||
private ImageResolver imageResolver;
|
||||
private KubernetesFlociAddressResolver addressResolver;
|
||||
private LaunchedContainerAwsEnv awsEnv;
|
||||
private LambdaLayerService layerService;
|
||||
private KubernetesPodLogStreamer logStreamer;
|
||||
private S3Service s3Service;
|
||||
private KubernetesPodLauncher launcher;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
config = mock(EmulatorConfig.class);
|
||||
var services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
var lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
|
||||
var kubernetes = mock(EmulatorConfig.LambdaServiceConfig.KubernetesExecutor.class);
|
||||
var tls = mock(EmulatorConfig.TlsConfig.class);
|
||||
lenient().when(config.services()).thenReturn(services);
|
||||
lenient().when(services.lambda()).thenReturn(lambda);
|
||||
lenient().when(lambda.kubernetes()).thenReturn(kubernetes);
|
||||
lenient().when(lambda.awsConfigPath()).thenReturn(Optional.empty());
|
||||
lenient().when(config.tls()).thenReturn(tls);
|
||||
lenient().when(tls.enabled()).thenReturn(false);
|
||||
lenient().when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
lenient().when(kubernetes.namespace()).thenReturn("default");
|
||||
lenient().when(kubernetes.initImage()).thenReturn("busybox:1.36");
|
||||
lenient().when(kubernetes.labels()).thenReturn(Optional.empty());
|
||||
|
||||
runtimeApiServerFactory = mock(RuntimeApiServerFactory.class);
|
||||
runtimeApiServer = mock(RuntimeApiServer.class);
|
||||
lenient().when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);
|
||||
lenient().when(runtimeApiServer.getPort()).thenReturn(9200);
|
||||
lenient().when(runtimeApiServer.stop()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
imageResolver = mock(ImageResolver.class);
|
||||
lenient().when(imageResolver.resolve("python3.12")).thenReturn("public.ecr.aws/lambda/python:3.12");
|
||||
|
||||
addressResolver = mock(KubernetesFlociAddressResolver.class);
|
||||
lenient().when(addressResolver.resolve()).thenReturn("10.0.0.5");
|
||||
lenient().when(addressResolver.flociBaseUrl()).thenReturn("http://10.0.0.5:4566");
|
||||
lenient().when(addressResolver.downloadBaseUrl()).thenReturn("http://10.0.0.5:4566");
|
||||
|
||||
awsEnv = mock(LaunchedContainerAwsEnv.class);
|
||||
lenient().when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString()))
|
||||
.thenReturn(List.of("AWS_REGION=us-east-1"));
|
||||
|
||||
layerService = mock(LambdaLayerService.class);
|
||||
logStreamer = mock(KubernetesPodLogStreamer.class);
|
||||
lenient().when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), anyString())).thenReturn(() -> { });
|
||||
lenient().when(logStreamer.logStreamName(anyString())).thenReturn("2026/07/25/[$LATEST]test");
|
||||
s3Service = mock(S3Service.class);
|
||||
|
||||
launcher = new KubernetesPodLauncher(client, config, runtimeApiServerFactory, imageResolver,
|
||||
addressResolver, awsEnv, layerService, new LambdaPodSpecFactory(config),
|
||||
logStreamer, s3Service);
|
||||
}
|
||||
|
||||
private LambdaFunction function() {
|
||||
var fn = new LambdaFunction();
|
||||
fn.setFunctionName("my-fn");
|
||||
fn.setAccountId("000000000000");
|
||||
fn.setFunctionArn("arn:aws:lambda:us-east-1:000000000000:function:my-fn");
|
||||
fn.setRuntime("python3.12");
|
||||
fn.setHandler("index.handler");
|
||||
fn.setMemorySize(128);
|
||||
fn.setTimeout(3);
|
||||
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)));
|
||||
var pod = client.pods().inNamespace("default").list().getItems().stream()
|
||||
.filter(p -> p.getMetadata().getName().startsWith(namePrefix))
|
||||
.findFirst().orElseThrow();
|
||||
pod.setStatus(new PodStatusBuilder().withPhase(phase).build());
|
||||
client.pods().inNamespace("default").resource(pod).updateStatus();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchCreatesPodAndReturnsHandle() {
|
||||
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
|
||||
|
||||
var handle = launcher.launch(function());
|
||||
|
||||
assertThat(handle).isNotNull();
|
||||
assertThat(handle.getFunctionName()).isEqualTo("my-fn");
|
||||
assertThat(handle.getContainerId()).startsWith("floci-lambda-my-fn-");
|
||||
|
||||
var pod = client.pods().inNamespace("default").withName(handle.getContainerId()).get();
|
||||
assertThat(pod).isNotNull();
|
||||
assertThat(pod.getMetadata().getLabels())
|
||||
.containsEntry("app.kubernetes.io/managed-by", "floci");
|
||||
assertThat(pod.getSpec().getInitContainers()).hasSize(1);
|
||||
assertThat(pod.getSpec().getContainers().getFirst().getEnv())
|
||||
.extracting(EnvVar::getName, EnvVar::getValue)
|
||||
.contains(tuple("AWS_LAMBDA_RUNTIME_API", "10.0.0.5:9200"));
|
||||
assertThat(pod.getSpec().getInitContainers().getFirst().getCommand().get(2))
|
||||
.contains("http://10.0.0.5:4566/awslambda-us-east-1-tasks/snapshots/000000000000/my-fn");
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadUrlCarriesTheOwningAccountForNonDefaultAccounts() {
|
||||
var fn = function();
|
||||
fn.setAccountId("111122223333");
|
||||
fn.setFunctionArn("arn:aws:lambda:us-east-1:111122223333:function:my-fn");
|
||||
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
|
||||
|
||||
var handle = launcher.launch(fn);
|
||||
|
||||
// The init container fetches unauthenticated, so the download URL must carry the
|
||||
// owning account or the object resolves under the default account and 404s.
|
||||
var pod = client.pods().inNamespace("default").withName(handle.getContainerId()).get();
|
||||
assertThat(pod.getSpec().getInitContainers().getFirst().getCommand().get(2))
|
||||
.contains("snapshots/111122223333/my-fn?X-Amz-Credential=111122223333%2F");
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchFailureReleasesPortAndDeletesPod() {
|
||||
markPodPhaseInBackground("floci-lambda-my-fn-", "Failed");
|
||||
|
||||
assertThatThrownBy(() -> launcher.launch(function()))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("failed to start");
|
||||
|
||||
verify(runtimeApiServer).stop();
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
Awaitility.await().atMost(Duration.ofSeconds(5)).until(
|
||||
() -> client.pods().inNamespace("default").list().getItems().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchFailureKeepsPortReservedWhenPodDeleteIsNotConfirmed() {
|
||||
// Once the pod is parked in Failed, every further Kubernetes API call fails, so
|
||||
// the cleanup delete can never confirm the pod is gone. The pod could still reach
|
||||
// Running later and poll AWS_LAMBDA_RUNTIME_API, so the port must stay reserved
|
||||
// instead of going back to the pool for another environment.
|
||||
var failingClient = spy(client);
|
||||
doAnswer(invocation -> {
|
||||
var failedPodExists = client.pods().inNamespace("default").list().getItems().stream()
|
||||
.anyMatch(p -> p.getStatus() != null && "Failed".equals(p.getStatus().getPhase()));
|
||||
if (failedPodExists) {
|
||||
throw new RuntimeException("kube api down");
|
||||
}
|
||||
return invocation.callRealMethod();
|
||||
}).when(failingClient).pods();
|
||||
var failingLauncher = new KubernetesPodLauncher(failingClient, config,
|
||||
runtimeApiServerFactory, imageResolver, addressResolver, awsEnv, layerService,
|
||||
new LambdaPodSpecFactory(config), logStreamer, s3Service);
|
||||
markPodPhaseInBackground("floci-lambda-my-fn-", "Failed");
|
||||
|
||||
assertThatThrownBy(() -> failingLauncher.launch(function()))
|
||||
.isInstanceOf(RuntimeException.class);
|
||||
|
||||
verify(runtimeApiServer).stop();
|
||||
verify(runtimeApiServerFactory, never()).release(runtimeApiServer);
|
||||
assertThat(client.pods().inNamespace("default").list().getItems())
|
||||
.as("the unconfirmed pod is left for a later sweep")
|
||||
.isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
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");
|
||||
|
||||
assertThatThrownBy(() -> launcher.launch(function()))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("failed to start");
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hotReloadIsRejectedBeforeAllocatingAnything() {
|
||||
var fn = function();
|
||||
fn.setHotReloadHostPath("/tmp/code");
|
||||
|
||||
assertThatThrownBy(() -> launcher.launch(fn))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("Hot reload");
|
||||
verify(runtimeApiServerFactory, never()).create();
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingCodeSnapshotFailsWithActionableMessage() {
|
||||
when(s3Service.headObject(anyString(), anyString()))
|
||||
.thenThrow(new AwsException("NoSuchKey", "not found", 404));
|
||||
|
||||
assertThatThrownBy(() -> launcher.launch(function()))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("Re-deploy the function code");
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopDeletesPodAndReleasesRuntimeApiPort() {
|
||||
var pod = new PodBuilder()
|
||||
.withNewMetadata().withName("floci-lambda-my-fn-abc12345").endMetadata()
|
||||
.build();
|
||||
client.pods().inNamespace("default").resource(pod).create();
|
||||
|
||||
var handle = new ContainerHandle("floci-lambda-my-fn-abc12345", "my-fn",
|
||||
runtimeApiServer, ContainerState.WARM);
|
||||
launcher.stop(handle);
|
||||
|
||||
assertThat(client.pods().inNamespace("default").withName("floci-lambda-my-fn-abc12345").get())
|
||||
.isNull();
|
||||
verify(runtimeApiServer).stop();
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
assertThat(handle.getState()).isEqualTo(ContainerState.STOPPED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isAliveReflectsPodPhase() {
|
||||
var running = new PodBuilder()
|
||||
.withNewMetadata().withName("pod-running").endMetadata()
|
||||
.withStatus(new PodStatusBuilder().withPhase("Running").build())
|
||||
.build();
|
||||
var pending = new PodBuilder()
|
||||
.withNewMetadata().withName("pod-pending").endMetadata()
|
||||
.withStatus(new PodStatusBuilder().withPhase("Pending").build())
|
||||
.build();
|
||||
client.pods().inNamespace("default").resource(running).create();
|
||||
client.pods().inNamespace("default").resource(pending).create();
|
||||
|
||||
assertThat(launcher.isAlive(handleFor("pod-running"))).isTrue();
|
||||
assertThat(launcher.isAlive(handleFor("pod-pending"))).isFalse();
|
||||
assertThat(launcher.isAlive(handleFor("pod-absent"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void orphanSweepDeletesOnlyManagedPods() {
|
||||
var orphan = new PodBuilder()
|
||||
.withNewMetadata().withName("floci-lambda-old-fn-dead1234")
|
||||
.withLabels(Map.of(
|
||||
"app.kubernetes.io/managed-by", "floci",
|
||||
"floci.io/service", "lambda"))
|
||||
.endMetadata()
|
||||
.build();
|
||||
var unrelated = new PodBuilder()
|
||||
.withNewMetadata().withName("some-other-pod").endMetadata()
|
||||
.build();
|
||||
client.pods().inNamespace("default").resource(orphan).create();
|
||||
client.pods().inNamespace("default").resource(unrelated).create();
|
||||
|
||||
// Fail the launch right after the sweep so the test doesn't need a running pod.
|
||||
when(imageResolver.resolve(anyString())).thenThrow(new RuntimeException("no image"));
|
||||
assertThatThrownBy(() -> launcher.launch(function()))
|
||||
.isInstanceOf(RuntimeException.class);
|
||||
|
||||
Awaitility.await().atMost(Duration.ofSeconds(5)).until(
|
||||
() -> client.pods().inNamespace("default").withName("floci-lambda-old-fn-dead1234").get() == null);
|
||||
assertThat(client.pods().inNamespace("default").withName("some-other-pod").get()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopDeletesPodEvenWhenPortReleaseThrows() {
|
||||
var pod = new PodBuilder()
|
||||
.withNewMetadata().withName("floci-lambda-my-fn-abc12345").endMetadata()
|
||||
.build();
|
||||
client.pods().inNamespace("default").resource(pod).create();
|
||||
doThrow(new IllegalStateException("release failed"))
|
||||
.when(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
var streamClosed = new AtomicBoolean();
|
||||
var handle = new ContainerHandle("floci-lambda-my-fn-abc12345", "my-fn",
|
||||
runtimeApiServer, ContainerState.WARM);
|
||||
handle.setLogStream(() -> streamClosed.set(true));
|
||||
|
||||
launcher.stop(handle);
|
||||
|
||||
assertThat(client.pods().inNamespace("default").withName("floci-lambda-my-fn-abc12345").get())
|
||||
.isNull();
|
||||
assertThat(streamClosed).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedOrphanSweepIsRetriedWithoutKillingOwnPods() {
|
||||
var orphan = new PodBuilder()
|
||||
.withNewMetadata().withName("floci-lambda-old-fn-dead1234")
|
||||
.withLabels(Map.of(
|
||||
"app.kubernetes.io/managed-by", "floci",
|
||||
"floci.io/service", "lambda"))
|
||||
.endMetadata()
|
||||
.build();
|
||||
client.pods().inNamespace("default").resource(orphan).create();
|
||||
|
||||
// First Kubernetes API access (the sweep's pod list) fails once.
|
||||
var failedOnce = new AtomicBoolean();
|
||||
var flakyClient = spy(client);
|
||||
doAnswer(invocation -> {
|
||||
if (failedOnce.compareAndSet(false, true)) {
|
||||
throw new RuntimeException("kube api down");
|
||||
}
|
||||
return invocation.callRealMethod();
|
||||
}).when(flakyClient).pods();
|
||||
var retryingLauncher = new KubernetesPodLauncher(flakyClient, config,
|
||||
runtimeApiServerFactory, imageResolver, addressResolver, awsEnv, layerService,
|
||||
new LambdaPodSpecFactory(config), logStreamer, s3Service);
|
||||
|
||||
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
|
||||
var handle = retryingLauncher.launch(function());
|
||||
assertThat(client.pods().inNamespace("default").withName("floci-lambda-old-fn-dead1234").get())
|
||||
.as("orphan survives the failed sweep")
|
||||
.isNotNull();
|
||||
|
||||
// The next launch retries the sweep. Fail it right after the sweep so the
|
||||
// test does not need a second running pod.
|
||||
when(imageResolver.resolve(anyString())).thenThrow(new RuntimeException("no image"));
|
||||
assertThatThrownBy(() -> retryingLauncher.launch(function()))
|
||||
.isInstanceOf(RuntimeException.class);
|
||||
|
||||
Awaitility.await().atMost(Duration.ofSeconds(5)).until(
|
||||
() -> client.pods().inNamespace("default").withName("floci-lambda-old-fn-dead1234").get() == null);
|
||||
assertThat(client.pods().inNamespace("default").withName(handle.getContainerId()).get())
|
||||
.as("the retried sweep must not delete this process's own pod")
|
||||
.isNotNull();
|
||||
}
|
||||
|
||||
private ContainerHandle handleFor(String podName) {
|
||||
return new ContainerHandle(podName, "my-fn", runtimeApiServer, ContainerState.WARM);
|
||||
}
|
||||
}
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
package io.github.hectorvent.floci.services.lambda.launcher.kubernetes;
|
||||
|
||||
import io.fabric8.kubernetes.api.model.EnvVar;
|
||||
import io.fabric8.kubernetes.api.model.Pod;
|
||||
import io.fabric8.kubernetes.api.model.Volume;
|
||||
import io.fabric8.kubernetes.api.model.VolumeMount;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.tuple;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class LambdaPodSpecFactoryTest {
|
||||
|
||||
@Mock
|
||||
EmulatorConfig config;
|
||||
private LambdaPodSpecFactory factory;
|
||||
|
||||
private EmulatorConfig.LambdaServiceConfig.KubernetesExecutor kubernetes;
|
||||
private EmulatorConfig.TlsConfig tls;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
var services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
var lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
|
||||
kubernetes = mock(EmulatorConfig.LambdaServiceConfig.KubernetesExecutor.class);
|
||||
tls = mock(EmulatorConfig.TlsConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.lambda()).thenReturn(lambda);
|
||||
when(lambda.kubernetes()).thenReturn(kubernetes);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(tls.enabled()).thenReturn(false);
|
||||
when(kubernetes.initImage()).thenReturn("busybox:1.36");
|
||||
when(kubernetes.labels()).thenReturn(Optional.empty());
|
||||
factory = new LambdaPodSpecFactory(config);
|
||||
}
|
||||
|
||||
private Pod buildZipPod() {
|
||||
return factory.buildPod("floci-lambda-my-fn-abc12345", "my-fn",
|
||||
"public.ecr.aws/lambda/python:3.12",
|
||||
List.of("AWS_LAMBDA_RUNTIME_API=10.0.0.5:9200", "_HANDLER=index.handler"),
|
||||
"http://10.0.0.5:4566/awslambda-us-east-1-tasks/snapshots/000000000000/my-fn",
|
||||
List.of(), false, "index.handler", null, 256, Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void zipFunctionPodHasInitContainerTaskVolumeAndEnv() {
|
||||
var spec = buildZipPod().getSpec();
|
||||
|
||||
assertThat(spec.getRestartPolicy()).isEqualTo("Never");
|
||||
assertThat(spec.getTerminationGracePeriodSeconds()).isEqualTo(5L);
|
||||
assertThat(spec.getInitContainers()).hasSize(1);
|
||||
|
||||
var init = spec.getInitContainers().getFirst();
|
||||
assertThat(init.getImage()).isEqualTo("busybox:1.36");
|
||||
assertThat(init.getCommand().get(2))
|
||||
.contains("wget -q -O /tmp/code.zip")
|
||||
.contains("unzip -oq /tmp/code.zip -d /var/task")
|
||||
.doesNotContain("--no-check-certificate");
|
||||
assertThat(init.getVolumeMounts())
|
||||
.extracting(VolumeMount::getName, VolumeMount::getMountPath)
|
||||
.containsExactly(tuple("task", "/var/task"));
|
||||
|
||||
var runtime = spec.getContainers().getFirst();
|
||||
assertThat(runtime.getName()).isEqualTo("runtime");
|
||||
assertThat(runtime.getArgs()).containsExactly("index.handler");
|
||||
assertThat(runtime.getResources().getLimits().get("memory")).hasToString("256Mi");
|
||||
assertThat(runtime.getResources().getRequests().get("memory")).hasToString("256Mi");
|
||||
assertThat(runtime.getVolumeMounts())
|
||||
.extracting(VolumeMount::getName, VolumeMount::getMountPath)
|
||||
.contains(tuple("task", "/var/task"));
|
||||
assertThat(runtime.getEnv())
|
||||
.extracting(EnvVar::getName, EnvVar::getValue)
|
||||
.contains(tuple("AWS_LAMBDA_RUNTIME_API", "10.0.0.5:9200"));
|
||||
|
||||
assertThat(spec.getVolumes()).extracting(Volume::getName).containsExactly("task");
|
||||
}
|
||||
|
||||
@Test
|
||||
void standardLabelsAreApplied() {
|
||||
var labels = buildZipPod().getMetadata().getLabels();
|
||||
assertThat(labels)
|
||||
.containsEntry("app.kubernetes.io/managed-by", "floci")
|
||||
.containsEntry("floci.io/service", "lambda")
|
||||
.containsEntry("floci.io/function-name", "my-fn");
|
||||
}
|
||||
|
||||
@Test
|
||||
void userLabelsAreParsedAndApplied() {
|
||||
when(kubernetes.labels()).thenReturn(Optional.of(
|
||||
List.of("team=platform", "floci.io/env=ci", "empty-ok=")));
|
||||
var labels = buildZipPod().getMetadata().getLabels();
|
||||
assertThat(labels)
|
||||
.containsEntry("team", "platform")
|
||||
.containsEntry("floci.io/env", "ci")
|
||||
.containsEntry("empty-ok", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidUserLabelsAreDroppedNotSanitized() {
|
||||
// '=' in a value and spaces in a key are rejected by the API server, so
|
||||
// such entries must never reach the pod spec.
|
||||
when(kubernetes.labels()).thenReturn(Optional.of(
|
||||
List.of("malformed", "a=b=c", "bad key=x", "team=platform")));
|
||||
var labels = buildZipPod().getMetadata().getLabels();
|
||||
assertThat(labels)
|
||||
.containsEntry("team", "platform")
|
||||
.doesNotContainKeys("malformed", "a", "bad key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void layersAreDownloadedInOrderIntoOpt() {
|
||||
var pod = factory.buildPod("floci-lambda-my-fn-abc12345", "my-fn",
|
||||
"public.ecr.aws/lambda/nodejs:20",
|
||||
List.of(),
|
||||
"http://10.0.0.5:4566/awslambda-us-east-1-tasks/snapshots/000000000000/my-fn",
|
||||
List.of("http://10.0.0.5:4566/b/layers/1", "http://10.0.0.5:4566/b/layers/2"),
|
||||
false, "index.handler", null, 128, Optional.empty());
|
||||
|
||||
var spec = pod.getSpec();
|
||||
assertThat(spec.getVolumes()).extracting(Volume::getName).contains("opt");
|
||||
assertThat(spec.getContainers().getFirst().getVolumeMounts())
|
||||
.extracting(VolumeMount::getName, VolumeMount::getMountPath)
|
||||
.contains(tuple("opt", "/opt"));
|
||||
assertThat(spec.getInitContainers().getFirst().getVolumeMounts())
|
||||
.extracting(VolumeMount::getName, VolumeMount::getMountPath)
|
||||
.contains(tuple("opt", "/opt"));
|
||||
|
||||
assertThat(spec.getInitContainers().getFirst().getCommand().get(2))
|
||||
.contains("unzip -oq /tmp/layer0.zip -d /opt")
|
||||
.containsSubsequence(
|
||||
"wget -q -O /tmp/layer0.zip 'http://10.0.0.5:4566/b/layers/1'",
|
||||
"wget -q -O /tmp/layer1.zip 'http://10.0.0.5:4566/b/layers/2'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void providedRuntimeCopiesBootstrapIntoVarRuntime() {
|
||||
// The provided.* entrypoint execs /var/runtime/bootstrap with no /var/task
|
||||
// fallback, so the init container must copy it there and restore the exec bit.
|
||||
var pod = factory.buildPod("floci-lambda-custom-abc12345", "custom",
|
||||
"public.ecr.aws/lambda/provided:al2023",
|
||||
List.of(),
|
||||
"http://10.0.0.5:4566/awslambda-us-east-1-tasks/snapshots/000000000000/custom",
|
||||
List.of(), true, "bootstrap", null, 128, Optional.empty());
|
||||
|
||||
var spec = pod.getSpec();
|
||||
assertThat(spec.getVolumes()).extracting(Volume::getName).contains("runtime");
|
||||
assertThat(spec.getContainers().getFirst().getVolumeMounts())
|
||||
.extracting(VolumeMount::getName, VolumeMount::getMountPath)
|
||||
.contains(tuple("runtime", "/var/runtime"));
|
||||
assertThat(spec.getInitContainers().getFirst().getVolumeMounts())
|
||||
.extracting(VolumeMount::getName)
|
||||
.contains("runtime");
|
||||
assertThat(spec.getInitContainers().getFirst().getCommand().get(2))
|
||||
.contains("cp /var/task/bootstrap /var/runtime/bootstrap")
|
||||
.contains("chmod +x /var/runtime/bootstrap");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonProvidedRuntimeDoesNotMaskVarRuntime() {
|
||||
// Masking /var/runtime on a normal runtime would delete the runtime interface client.
|
||||
assertThat(buildZipPod().getSpec().getVolumes())
|
||||
.extracting(Volume::getName)
|
||||
.doesNotContain("runtime");
|
||||
}
|
||||
|
||||
@Test
|
||||
void managedLabelsCannotBeOverriddenByUserLabels() {
|
||||
when(kubernetes.labels()).thenReturn(Optional.of(
|
||||
List.of("app.kubernetes.io/managed-by=evil", "floci.io/service=other")));
|
||||
var labels = buildZipPod().getMetadata().getLabels();
|
||||
assertThat(labels)
|
||||
.containsEntry("app.kubernetes.io/managed-by", "floci")
|
||||
.containsEntry("floci.io/service", "lambda");
|
||||
}
|
||||
|
||||
@Test
|
||||
void dollarSignsInEnvValuesAreEscapedForKubernetesExpansion() {
|
||||
var pod = factory.buildPod("floci-lambda-my-fn-abc12345", "my-fn",
|
||||
"public.ecr.aws/lambda/python:3.12",
|
||||
List.of("SECRET=pa$$word", "TEMPLATE=$(HOME)/x"),
|
||||
"http://10.0.0.5:4566/b/k", List.of(), false, "h", null, 128, Optional.empty());
|
||||
assertThat(pod.getSpec().getContainers().getFirst().getEnv())
|
||||
.extracting(EnvVar::getName, EnvVar::getValue)
|
||||
.contains(
|
||||
tuple("SECRET", "pa$$$$word"),
|
||||
tuple("TEMPLATE", "$$(HOME)/x"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tlsMountsCaCertAndStillDownloadsWithPlainWget() {
|
||||
// Downloads stay plain HTTP even in TLS mode (busybox wget cannot TLS-handshake
|
||||
// with Floci); the CA mount is for SDK calls made from inside the function.
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
var pod = factory.buildPod("floci-lambda-my-fn-abc12345", "my-fn",
|
||||
"public.ecr.aws/lambda/python:3.12",
|
||||
List.of(),
|
||||
"http://10.0.0.5:4566/awslambda-us-east-1-tasks/snapshots/000000000000/my-fn",
|
||||
List.of(), false, "index.handler", null, 128,
|
||||
Optional.of(KubernetesPodLauncher.CA_CONFIG_MAP_NAME));
|
||||
|
||||
var spec = pod.getSpec();
|
||||
assertThat(spec.getVolumes()).anySatisfy(volume -> {
|
||||
assertThat(volume.getName()).isEqualTo("floci-ca");
|
||||
assertThat(volume.getConfigMap().getName()).isEqualTo(KubernetesPodLauncher.CA_CONFIG_MAP_NAME);
|
||||
});
|
||||
assertThat(spec.getContainers().getFirst().getVolumeMounts()).anySatisfy(volumeMount -> {
|
||||
assertThat(volumeMount.getName()).isEqualTo("floci-ca");
|
||||
assertThat(volumeMount.getMountPath()).isEqualTo("/etc/floci-ca.crt");
|
||||
assertThat(volumeMount.getSubPath()).isEqualTo(KubernetesPodLauncher.CA_CONFIG_MAP_KEY);
|
||||
});
|
||||
assertThat(spec.getInitContainers().getFirst().getCommand().get(2))
|
||||
.contains("wget -q")
|
||||
.doesNotContain("--no-check-certificate");
|
||||
}
|
||||
|
||||
@Test
|
||||
void dollarSignsInCommandAndArgsAreEscapedForKubernetesExpansion() {
|
||||
var pod = factory.buildPod("floci-lambda-img-abc12345", "img",
|
||||
"123456789012.dkr.ecr.us-east-1.amazonaws.com/my-image:latest",
|
||||
List.of(), null, List.of(), false, null,
|
||||
new LambdaPodSpecFactory.ImageConfig(
|
||||
List.of("/entry.sh"), List.of("run('$(AWS_REGION)')", "pa$$word"), "/work"),
|
||||
512, Optional.empty());
|
||||
assertThat(pod.getSpec().getContainers().getFirst().getArgs())
|
||||
.containsExactly("run('$$(AWS_REGION)')", "pa$$$$word");
|
||||
}
|
||||
|
||||
@Test
|
||||
void imagePackageTypeHasNoInitContainerAndMapsImageConfig() {
|
||||
var pod = factory.buildPod("floci-lambda-img-abc12345", "img",
|
||||
"123456789012.dkr.ecr.us-east-1.amazonaws.com/my-image:latest",
|
||||
List.of(), null, List.of(), false, null,
|
||||
new LambdaPodSpecFactory.ImageConfig(
|
||||
List.of("/entry.sh"), List.of("arg1", "arg2"), "/work"),
|
||||
512, Optional.empty());
|
||||
|
||||
var spec = pod.getSpec();
|
||||
assertThat(spec.getInitContainers()).isEmpty();
|
||||
assertThat(spec.getVolumes()).isEmpty();
|
||||
|
||||
var runtime = spec.getContainers().getFirst();
|
||||
assertThat(runtime.getCommand()).containsExactly("/entry.sh");
|
||||
assertThat(runtime.getArgs()).containsExactly("arg1", "arg2");
|
||||
assertThat(runtime.getWorkingDir()).isEqualTo("/work");
|
||||
}
|
||||
|
||||
@Test
|
||||
void envEntriesSplitOnFirstEquals() {
|
||||
var pod = factory.buildPod("floci-lambda-my-fn-abc12345", "my-fn",
|
||||
"public.ecr.aws/lambda/python:3.12",
|
||||
List.of("KEY=a=b", "EMPTY="),
|
||||
"http://10.0.0.5:4566/b/k", List.of(), false, "h", null, 128, Optional.empty());
|
||||
assertThat(pod.getSpec().getContainers().getFirst().getEnv())
|
||||
.extracting(EnvVar::getName, EnvVar::getValue)
|
||||
.contains(
|
||||
tuple("KEY", "a=b"),
|
||||
tuple("EMPTY", ""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void envEntriesWithEmptyNamesAreDropped() {
|
||||
// The API server rejects a pod whose env var has an empty name.
|
||||
var pod = factory.buildPod("floci-lambda-my-fn-abc12345", "my-fn",
|
||||
"public.ecr.aws/lambda/python:3.12",
|
||||
List.of("=oops", "KEY=1"),
|
||||
"http://10.0.0.5:4566/b/k", List.of(), false, "h", null, 128, Optional.empty());
|
||||
assertThat(pod.getSpec().getContainers().getFirst().getEnv())
|
||||
.extracting(EnvVar::getName)
|
||||
.containsExactly("KEY");
|
||||
}
|
||||
|
||||
@Test
|
||||
void podNameIsDnsSafeAndClamped() {
|
||||
var name = LambdaPodSpecFactory.podName("My_Function.With.Dots", "abc12345");
|
||||
assertThat(name).isEqualTo("floci-lambda-my-function-with-dots-abc12345");
|
||||
assertThat(name).hasSizeLessThanOrEqualTo(63);
|
||||
|
||||
var longName = LambdaPodSpecFactory.podName("a".repeat(100), "abc12345");
|
||||
assertThat(longName)
|
||||
.hasSizeLessThanOrEqualTo(63)
|
||||
.endsWith("-abc12345")
|
||||
.matches("[a-z0-9]([a-z0-9-]*[a-z0-9])?");
|
||||
|
||||
assertThat(LambdaPodSpecFactory.podName("_foo", "abc12345"))
|
||||
.isEqualTo("floci-lambda-foo-abc12345");
|
||||
assertThat(LambdaPodSpecFactory.podName("___", "abc12345"))
|
||||
.isEqualTo("floci-lambda-fn-abc12345");
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelValueSanitization() {
|
||||
assertThat(LambdaPodSpecFactory.sanitizeLabelValue("fn:name")).isEqualTo("fn-name");
|
||||
assertThat(LambdaPodSpecFactory.sanitizeLabelValue("-fn-")).isEqualTo("fn");
|
||||
assertThat(LambdaPodSpecFactory.sanitizeLabelValue("x".repeat(100))).hasSizeLessThanOrEqualTo(63);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user