mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambda): add a process executor for provided runtimes (#9006)
This commit is contained in:
1 parent
3205a62cf7
commit
3aba098ee8
16 files changed
+993
-80
No files matched your search
@@ -332,7 +332,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s
|
||||
| `FLOCI_SERVICES_LAMBDA_CONTAINER_NAME_PREFIX` | `floci` | Base name prefix for Lambda-spawned containers and code volumes (must match `[A-Za-z0-9][A-Za-z0-9_.-]*`) |
|
||||
| `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE` | _(none)_ | Explicit host/IP Lambda containers use to reach the Runtime API, bypassing auto-detection (e.g. rootless Podman) |
|
||||
| `FLOCI_SERVICES_LAMBDA_AWS_CONFIG_PATH` | _(none)_ | Host path bind-mounted read-only at `/opt/aws-config` inside Lambda containers for real credential discovery |
|
||||
| `FLOCI_SERVICES_LAMBDA_EXECUTOR` | `docker` | Execution backend for Lambda environments: `docker` (containers) or `kubernetes` (pods) |
|
||||
| `FLOCI_SERVICES_LAMBDA_EXECUTOR` | `docker` | Execution backend for Lambda environments: `docker` (containers), `kubernetes` (pods) or `process` (local processes for `provided.*` runtimes) |
|
||||
| `FLOCI_SERVICES_LAMBDA_KUBERNETES_NAMESPACE` | `default` | Namespace Lambda pods are created in |
|
||||
| `FLOCI_SERVICES_LAMBDA_KUBERNETES_LABELS` | _(none)_ | Extra pod labels as comma-separated `key=value` entries |
|
||||
| `FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR` | _(none)_ | Pod node selector as comma-separated `key=value` entries; an invalid entry fails the cold start to avoid scheduling the pod on unsupported nodes |
|
||||
|
||||
+59
-2
@@ -726,7 +726,7 @@ Configuration resource reads and `ListFunctionsByCodeSigningConfig` return
|
||||
| `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE` | *(unset)* | Explicit host/IP that spawned Lambda containers use to reach Floci's Runtime API, bypassing auto-detection |
|
||||
| `FLOCI_SERVICES_LAMBDA_CONTAINER_NAME_PREFIX` | `floci` | Base name prefix for spawned Lambda containers and code volumes (e.g. `acme` → `acme-<function>-<id>` containers, `acme-code-<function>-<hash>` volumes; with `FLOCI_DOCKER_RESOURCE_NAMESPACE` set, the namespace follows the prefix and a short hash of it ends the volume name, e.g. `acme-<namespace>-code-<function>-<hash>-<namespace hash>`). Must be a valid Docker name segment (`[A-Za-z0-9][A-Za-z0-9_.-]*`); invalid values are ignored with a warning |
|
||||
| `FLOCI_SERVICES_LAMBDA_CODE_VOLUME_POPULATE_CONCURRENCY` | `max(2, cpus/2)` | Maximum concurrent first-time code-volume populates. See the note below |
|
||||
| `FLOCI_SERVICES_LAMBDA_EXECUTOR` | `docker` | Execution backend: `docker` (containers) or `kubernetes` (pods) |
|
||||
| `FLOCI_SERVICES_LAMBDA_EXECUTOR` | `docker` | Execution backend: `docker` (containers), `kubernetes` (pods) or `process` (local processes, see [Process executor](#process-executor)) |
|
||||
| `FLOCI_SERVICES_LAMBDA_KUBERNETES_NAMESPACE` | `default` | Namespace Lambda pods are created in |
|
||||
| `FLOCI_SERVICES_LAMBDA_KUBERNETES_LABELS` | *(unset)* | Extra pod labels as comma-separated `key=value` entries |
|
||||
| `FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR` | *(unset)* | Pod node selector as comma-separated `key=value` entries; an invalid entry fails the cold start to avoid scheduling the pod on unsupported nodes |
|
||||
@@ -872,7 +872,9 @@ services:
|
||||
|
||||
If mounting the Docker socket is not acceptable (for example on a hardened
|
||||
Kubernetes cluster), use the [Kubernetes executor](#kubernetes-executor)
|
||||
instead — it needs no privileged access and no socket.
|
||||
instead. It needs no privileged access and no socket. On a development
|
||||
machine without Docker, the [process executor](#process-executor) runs
|
||||
`provided.*` functions as local processes.
|
||||
|
||||
### Kubernetes executor
|
||||
|
||||
@@ -1040,6 +1042,61 @@ entries; only clients of the emulator itself use port 4566.
|
||||
- Layers published by Floci versions before this feature have no stored
|
||||
archive; re-publish them once to make them downloadable by pods.
|
||||
|
||||
### Process executor
|
||||
|
||||
Set `FLOCI_SERVICES_LAMBDA_EXECUTOR=process` to run each Lambda execution
|
||||
environment as a process on the machine Floci runs on, without Docker. It
|
||||
follows the [custom runtime](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html)
|
||||
contract: Floci starts the package's `bootstrap` in the package directory, and
|
||||
the bootstrap polls the Lambda Runtime API at `AWS_LAMBDA_RUNTIME_API`. Each
|
||||
execution environment runs from its own copy of a .zip package, in the system
|
||||
temporary directory, so a code update does not change an environment that is
|
||||
already running. The copy is deleted when the environment stops.
|
||||
|
||||
The process gets:
|
||||
|
||||
- `AWS_LAMBDA_RUNTIME_API` on `127.0.0.1`, `_HANDLER`, `LAMBDA_TASK_ROOT` and
|
||||
the other `AWS_LAMBDA_*` variables, as with the other executors.
|
||||
- `TZ=:UTC` and `LANG=en_US.UTF-8`, as Lambda sets them. The function's own
|
||||
`Environment` can override both.
|
||||
- The function's `Environment` variables, and an AWS SDK endpoint and region
|
||||
pointing at Floci. A function whose execution role Floci knows gets that
|
||||
role's credentials, as with the docker executor.
|
||||
- `PATH` from Floci's own environment. No other variable is passed, so Floci's
|
||||
own environment variables, credentials included, do not reach the function.
|
||||
The process can still read anything your user can, such as `~/.aws`.
|
||||
|
||||
Its output goes to Floci's log and the function's CloudWatch Logs stream, one
|
||||
event per line, with lines longer than 256 KB split into several events.
|
||||
Hot-reload functions run from their host directory directly.
|
||||
|
||||
The process runs with the permissions of the user Floci runs as, with no
|
||||
isolation and no memory limit, so this executor is meant for local
|
||||
development only.
|
||||
|
||||
Limitations:
|
||||
|
||||
- Only `provided.*` runtimes from a .zip package or a hot-reload directory are
|
||||
supported. Other runtimes, container images, functions with layers and
|
||||
functions that mount a file system fail to launch with a clear error.
|
||||
- The bootstrap in a .zip package's copy is made executable when it starts,
|
||||
since Floci does not keep file modes when it extracts a package. Other files
|
||||
in the package keep the modes extraction gave them. A hot-reload bootstrap must
|
||||
already be executable.
|
||||
- Floci refuses to start with this executor when it runs inside a container,
|
||||
where the processes would run in that container instead of on your machine.
|
||||
- Invocations with `LogType=Tail` return no log tail.
|
||||
- The bootstrap runs on Linux and macOS only, and must be built for the
|
||||
machine Floci runs on: a binary built for Lambda's Linux runs only on a
|
||||
Linux host of the same architecture. The function's `Architectures` is
|
||||
ignored.
|
||||
- Stopping an environment stops its bootstrap and the processes it started.
|
||||
Processes a bootstrap left behind after it exited on its own are not
|
||||
tracked and keep running until you stop them, and so are bootstraps still
|
||||
running when Floci itself is killed, along with their code copies. Nothing
|
||||
removes them when Floci starts again, as the Docker and Kubernetes executors
|
||||
do for their leftovers.
|
||||
|
||||
### S3 virtual-hosted-style addressing inside Lambda containers
|
||||
|
||||
AWS SDKs use **virtual-hosted-style** S3 addressing by default, forming URLs like
|
||||
|
||||
@@ -3693,7 +3693,9 @@ public interface EmulatorConfig {
|
||||
/**
|
||||
* Execution backend for Lambda environments: {@code docker} (default) runs each
|
||||
* environment as a Docker container, {@code kubernetes} runs it as a pod in the
|
||||
* cluster Floci is configured against (in-cluster config or local kubeconfig).
|
||||
* cluster Floci is configured against (in-cluster config or local kubeconfig), and
|
||||
* {@code process} runs a {@code provided.*} function's bootstrap as a process on the
|
||||
* machine Floci runs on, for local development without Docker.
|
||||
*
|
||||
* Env var: FLOCI_SERVICES_LAMBDA_EXECUTOR
|
||||
*/
|
||||
|
||||
@@ -103,7 +103,7 @@ public class DockerAvailabilityReport {
|
||||
/** A service whose container work goes somewhere other than the local daemon. */
|
||||
boolean runsWithoutLocalDocker(String service) {
|
||||
return switch (service) {
|
||||
case "lambda" -> "kubernetes".equalsIgnoreCase(config.services().lambda().executor().trim());
|
||||
case "lambda" -> !"docker".equalsIgnoreCase(config.services().lambda().executor().trim());
|
||||
case "athena" -> isSet(config.services().duck().url());
|
||||
case "verifiedpermissions" -> isSet(config.services().verifiedpermissions().cedarUrl());
|
||||
default -> false;
|
||||
|
||||
@@ -95,7 +95,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
EmulatorConfig config) {
|
||||
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, lambdaServiceInstance, null, clock,
|
||||
Duration.ofSeconds(config.services().lambda().asyncRetryDelaySeconds()),
|
||||
!"kubernetes".equalsIgnoreCase(config.services().lambda().executor().trim()),
|
||||
"docker".equalsIgnoreCase(config.services().lambda().executor().trim()),
|
||||
config.services().lambda().initTimeoutSeconds());
|
||||
}
|
||||
|
||||
|
||||
@@ -281,28 +281,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
env.addAll(awsEnv.sdkBaselineEnv(lambdaRegion,
|
||||
awsConfigPath.isPresent() ? Optional.of("/opt/aws-config") : Optional.empty(),
|
||||
awsEnv.flociEndpoint(dockerFlags.dnsServers().isEmpty()), roleCredentials, lambdaAccountId));
|
||||
if (fn.getEnvironment() != null) {
|
||||
boolean hasExecutionRoleCredentials = roleCredentials.isPresent();
|
||||
boolean userDefinesFullCredentialTriad = definesFullCredentialTriad(fn.getEnvironment());
|
||||
fn.getEnvironment().forEach((k, v) -> {
|
||||
if (isAwsCredentialVariable(k)) {
|
||||
// Credential injection is all-or-nothing: a partial override (e.g. only
|
||||
// AWS_ACCESS_KEY_ID set) must never join the baseline's other two values —
|
||||
// that pairs a user-chosen key with the owner-account/execution-role secret
|
||||
// and session token, a tuple nothing can verify. Only let the user's triad
|
||||
// through when it is complete, and only when there is no execution role
|
||||
// (which is already the authoritative credential source).
|
||||
if (!hasExecutionRoleCredentials && userDefinesFullCredentialTriad) {
|
||||
env.add(k + "=" + v);
|
||||
}
|
||||
} else {
|
||||
env.add(k + "=" + v);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
env.removeIf(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION="));
|
||||
env.add("AWS_LAMBDA_FUNCTION_VERSION=" + fn.getVersion());
|
||||
LambdaRuntimeEnv.addFunctionEnvironment(env, fn, roleCredentials.isPresent());
|
||||
if (provisioned) {
|
||||
env.removeIf(value -> value.startsWith("AWS_LAMBDA_INITIALIZATION_TYPE="));
|
||||
env.add("AWS_LAMBDA_INITIALIZATION_TYPE=provisioned-concurrency");
|
||||
@@ -549,16 +528,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
// null by then); otherwise the failure happened before Docker ever saw the volume, so
|
||||
// its in-flight reference must be released here or cleanup would wait on it forever.
|
||||
releaseCodeVolumeReference(reservedCodeVolume);
|
||||
// Stop the server before releasing its port, or the still-listening Vert.x server
|
||||
// makes a later cold start that reuses the port serve this runtime too.
|
||||
try {
|
||||
runtimeApiServer.stop().get(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (Exception stopFailure) {
|
||||
LOG.debugv("Runtime API server stop failed during launch cleanup: {0}",
|
||||
stopFailure.getMessage());
|
||||
}
|
||||
RuntimeApiServerFactory.stopBeforeRelease(runtimeApiServer);
|
||||
try {
|
||||
runtimeApiServerFactory.release(runtimeApiServer);
|
||||
} catch (Exception cleanupError) {
|
||||
|
||||
@@ -33,4 +33,27 @@ public final class LambdaRuntimeEnv {
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the function's own {@code Environment} and its version after the SDK baseline. Credential
|
||||
* injection is all-or-nothing: a partial override (only {@code AWS_ACCESS_KEY_ID}, say) must never
|
||||
* join the baseline's other two values, which would pair a user-chosen key with the baseline's
|
||||
* secret and session token, a tuple nothing can verify. The function's credentials apply only as a
|
||||
* complete triad, and only without an execution role session, which is then the authoritative
|
||||
* credential source.
|
||||
*/
|
||||
public static void addFunctionEnvironment(List<String> env, LambdaFunction fn,
|
||||
boolean hasExecutionRoleCredentials) {
|
||||
if (fn.getEnvironment() != null) {
|
||||
boolean functionCredentialsApply = !hasExecutionRoleCredentials
|
||||
&& ContainerLauncher.definesFullCredentialTriad(fn.getEnvironment());
|
||||
fn.getEnvironment().forEach((key, value) -> {
|
||||
if (!ContainerLauncher.isAwsCredentialVariable(key) || functionCredentialsApply) {
|
||||
env.add(key + "=" + value);
|
||||
}
|
||||
});
|
||||
}
|
||||
env.removeIf(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION="));
|
||||
env.add("AWS_LAMBDA_FUNCTION_VERSION=" + fn.getVersion());
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ import io.floci.aws.services.lambda.model.LambdaFunction;
|
||||
|
||||
/**
|
||||
* Starts and stops Lambda execution environments. Implementations back each
|
||||
* environment with a concrete runtime: a Docker container ({@link ContainerLauncher})
|
||||
* or a Kubernetes pod ({@code KubernetesPodLauncher}). Selected at startup by
|
||||
* environment with a concrete runtime: a Docker container ({@link ContainerLauncher}),
|
||||
* a Kubernetes pod ({@code KubernetesPodLauncher}) or a local process ({@link ProcessLauncher}). Selected at startup by
|
||||
* {@code floci.services.lambda.executor}.
|
||||
*/
|
||||
public interface LambdaRuntimeLauncher {
|
||||
|
||||
+20
-5
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.lambda.launcher;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.services.lambda.launcher.kubernetes.KubernetesPodLauncher;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -30,12 +31,21 @@ public class LambdaRuntimeLauncherProducer {
|
||||
* HTTP client would be created on a request's Vert.x context and closed with
|
||||
* the HTTP server verticles at shutdown, so the WarmPool drain could no longer
|
||||
* delete pods ("Client is closed").
|
||||
*
|
||||
* <p>The process executor is refused inside a container, where the host it would run
|
||||
* functions on is that container rather than the machine the user develops on.
|
||||
*/
|
||||
void validateExecutor(@Observes StartupEvent event, EmulatorConfig config,
|
||||
Instance<KubernetesPodLauncher> kubernetes) {
|
||||
if (requireValidExecutor(config).equals("kubernetes")) {
|
||||
Instance<KubernetesPodLauncher> kubernetes, ContainerDetector containerDetector) {
|
||||
String executor = requireValidExecutor(config);
|
||||
if (executor.equals("kubernetes")) {
|
||||
kubernetes.get().initializeClient();
|
||||
}
|
||||
if (executor.equals("process") && containerDetector.isRunningInContainer()) {
|
||||
throw new IllegalStateException("floci.services.lambda.executor=process runs functions as processes "
|
||||
+ "of the machine Floci runs on, but Floci is running inside a container. "
|
||||
+ "Use the docker or kubernetes executor there.");
|
||||
}
|
||||
}
|
||||
|
||||
void reconcileDockerContainers(@Observes StartupEvent event, EmulatorConfig config,
|
||||
@@ -50,21 +60,26 @@ public class LambdaRuntimeLauncherProducer {
|
||||
@ApplicationScoped
|
||||
LambdaRuntimeLauncher launcher(EmulatorConfig config,
|
||||
Instance<ContainerLauncher> docker,
|
||||
Instance<KubernetesPodLauncher> kubernetes) {
|
||||
Instance<KubernetesPodLauncher> kubernetes,
|
||||
Instance<ProcessLauncher> process) {
|
||||
String executor = requireValidExecutor(config);
|
||||
if (executor.equals("kubernetes")) {
|
||||
LOG.info("Lambda executor: kubernetes (environments run as pods)");
|
||||
return kubernetes.get();
|
||||
}
|
||||
if (executor.equals("process")) {
|
||||
LOG.info("Lambda executor: process (environments run as local processes)");
|
||||
return process.get();
|
||||
}
|
||||
return docker.get();
|
||||
}
|
||||
|
||||
private static String requireValidExecutor(EmulatorConfig config) {
|
||||
String executor = config.services().lambda().executor().trim().toLowerCase(Locale.ROOT);
|
||||
if (!executor.equals("docker") && !executor.equals("kubernetes")) {
|
||||
if (!executor.equals("docker") && !executor.equals("kubernetes") && !executor.equals("process")) {
|
||||
throw new IllegalArgumentException(
|
||||
"Unknown floci.services.lambda.executor '" + executor
|
||||
+ "'. Valid values: docker, kubernetes");
|
||||
+ "'. Valid values: docker, kubernetes, process");
|
||||
}
|
||||
return executor;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
package io.floci.aws.services.lambda.launcher;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.FileTrees;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.floci.aws.services.iam.model.SessionCreds;
|
||||
import io.floci.aws.services.lambda.LambdaLogDestinations;
|
||||
import io.floci.aws.services.lambda.model.ContainerState;
|
||||
import io.floci.aws.services.lambda.model.LambdaFunction;
|
||||
import io.floci.aws.services.lambda.runtime.RuntimeApiServer;
|
||||
import io.floci.aws.services.lambda.runtime.RuntimeApiServerFactory;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Typed;
|
||||
import jakarta.inject.Inject;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Runs each Lambda execution environment as a process on the host Floci runs on, following the
|
||||
* custom runtime contract: the package's {@code bootstrap} starts in the package directory with
|
||||
* {@code AWS_LAMBDA_RUNTIME_API}, {@code _HANDLER}, {@code LAMBDA_TASK_ROOT} and the function's
|
||||
* environment, and polls the Runtime API server Floci started for it.
|
||||
*
|
||||
* <p>Only {@code provided.*} runtimes from a .zip package, or a hot-reload directory, are served.
|
||||
* The process has no isolation and no memory limit: it runs with the permissions of the user Floci
|
||||
* runs as, so this executor is meant for local development on a machine without Docker.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
@Typed(ProcessLauncher.class)
|
||||
public class ProcessLauncher implements LambdaRuntimeLauncher {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ProcessLauncher.class);
|
||||
|
||||
private static final String LOOPBACK = "127.0.0.1";
|
||||
|
||||
/** How long a stopped environment's process gets to exit before it is killed, and then to die. */
|
||||
private static final long STOP_GRACE_SECONDS = 2;
|
||||
|
||||
/** Output longer than a CloudWatch Logs event is split into several events. */
|
||||
private static final int MAX_LOG_EVENT_CHARS = 256 * 1024;
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
private final RuntimeApiServerFactory runtimeApiServerFactory;
|
||||
private final LaunchedContainerAwsEnv awsEnv;
|
||||
private final ContainerLogStreamer logStreamer;
|
||||
private final LambdaExecutionRoleCredentials executionRoleCredentials;
|
||||
private final String flociEndpoint;
|
||||
private final Map<String, Process> processes = new ConcurrentHashMap<>();
|
||||
private final Map<String, Path> codeCopies = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public ProcessLauncher(EmulatorConfig config,
|
||||
RegionResolver regionResolver,
|
||||
RuntimeApiServerFactory runtimeApiServerFactory,
|
||||
LaunchedContainerAwsEnv awsEnv,
|
||||
ContainerLogStreamer logStreamer,
|
||||
LambdaExecutionRoleCredentials executionRoleCredentials,
|
||||
@ConfigProperty(name = "quarkus.http.host", defaultValue = "0.0.0.0") String flociHttpHost,
|
||||
@ConfigProperty(name = "quarkus.http.port") int flociHttpPort) {
|
||||
this.config = config;
|
||||
this.regionResolver = regionResolver;
|
||||
this.runtimeApiServerFactory = runtimeApiServerFactory;
|
||||
this.awsEnv = awsEnv;
|
||||
this.logStreamer = logStreamer;
|
||||
this.executionRoleCredentials = executionRoleCredentials;
|
||||
this.flociEndpoint = "http://" + connectHost(flociHttpHost) + ":" + flociHttpPort;
|
||||
}
|
||||
|
||||
/** The address a process on this machine reaches Floci's HTTP listener on. */
|
||||
private static String connectHost(String bindHost) {
|
||||
String host = bindHost.strip();
|
||||
if (host.isEmpty() || host.equals("0.0.0.0") || host.equals("::") || host.equals("[::]")) {
|
||||
return LOOPBACK;
|
||||
}
|
||||
return host.contains(":") && !host.startsWith("[") ? "[" + host + "]" : host;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ContainerHandle launch(LambdaFunction fn) {
|
||||
Path code = codeDirectory(fn);
|
||||
Path taskRoot = fn.isHotReload() ? code : copyOf(fn, code);
|
||||
Path codeCopy = fn.isHotReload() ? null : taskRoot;
|
||||
Path bootstrap = taskRoot.resolve("bootstrap");
|
||||
try {
|
||||
requireExecutableBootstrap(fn, bootstrap);
|
||||
} catch (RuntimeException e) {
|
||||
deleteCopy(codeCopy);
|
||||
throw e;
|
||||
}
|
||||
LOG.infov("Launching process for function: {0}", fn.getFunctionName());
|
||||
|
||||
RuntimeApiServer runtimeApiServer = runtimeApiServerFactory.create();
|
||||
runtimeApiServer.setFunctionMetadata(fn.getFunctionName(), fn.getVersion(), fn.getHandler(),
|
||||
fn.getAccountId());
|
||||
|
||||
Process process = null;
|
||||
Optional<SessionCreds> roleCredentials = Optional.empty();
|
||||
String sessionAccountId = LambdaExecutionRoleCredentials.sessionAccountId(fn);
|
||||
try {
|
||||
String shortId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
String region = regionResolver.regionOf(fn.getFunctionArn());
|
||||
String accountId = AwsArnUtils.accountOrDefault(fn.getFunctionArn(), config.defaultAccountId());
|
||||
String logGroup = LambdaLogDestinations.logGroup(fn);
|
||||
String logStream = logStreamer.generateLogStreamName(LambdaLogDestinations.logStreamSuffix(fn, shortId));
|
||||
|
||||
ProcessBuilder builder = new ProcessBuilder(bootstrap.toString())
|
||||
.directory(taskRoot.toFile())
|
||||
.redirectErrorStream(true);
|
||||
Map<String, String> environment = builder.environment();
|
||||
environment.clear();
|
||||
String path = System.getenv("PATH");
|
||||
if (path != null) {
|
||||
environment.put("PATH", path);
|
||||
}
|
||||
roleCredentials = executionRoleCredentials.forFunction(fn);
|
||||
for (String entry : environment(fn, taskRoot, runtimeApiServer, region, accountId, logGroup, logStream,
|
||||
roleCredentials)) {
|
||||
int separator = entry.indexOf('=');
|
||||
environment.put(entry.substring(0, separator), entry.substring(separator + 1));
|
||||
}
|
||||
|
||||
process = builder.start();
|
||||
process.getOutputStream().close();
|
||||
runtimeApiServer.markContainerStarted();
|
||||
process.onExit().thenAccept(exited -> runtimeApiServer.handleRuntimeProcessExited(exited.exitValue()));
|
||||
forwardOutput(process, fn.getFunctionName(), accountId, logGroup, logStream, region);
|
||||
|
||||
String processId = "process-" + fn.getFunctionName() + "-" + shortId;
|
||||
processes.put(processId, process);
|
||||
if (codeCopy != null) {
|
||||
codeCopies.put(processId, codeCopy);
|
||||
}
|
||||
return new ContainerHandle(processId, fn.getFunctionName(), runtimeApiServer, ContainerState.WARM,
|
||||
fn.isHotReload(), roleCredentials.map(SessionCreds::accessKeyId).orElse(null), sessionAccountId);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
LOG.errorv(e, "Process launch failed for function {0}; cleaning up", fn.getFunctionName());
|
||||
boolean processGone = process == null || destroy(process);
|
||||
roleCredentials.ifPresent(credentials ->
|
||||
executionRoleCredentials.unregister(sessionAccountId, credentials.accessKeyId()));
|
||||
RuntimeApiServerFactory.stopBeforeRelease(runtimeApiServer);
|
||||
releaseWhenGone(runtimeApiServer, codeCopy, process, processGone);
|
||||
if (e instanceof RuntimeException runtimeException) {
|
||||
throw runtimeException;
|
||||
}
|
||||
throw new RuntimeException("Could not start the bootstrap of function '" + fn.getFunctionName()
|
||||
+ "': " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(ContainerHandle handle) {
|
||||
LOG.infov("Stopping process {0}", handle.getContainerId());
|
||||
handle.setState(ContainerState.STOPPED);
|
||||
RuntimeApiServer server = handle.getRuntimeApiServer();
|
||||
// Quiesce first, so the exit this stop causes is not reported as a runtime crash.
|
||||
server.quiesce();
|
||||
Process process = processes.remove(handle.getContainerId());
|
||||
boolean processGone = process == null || destroy(process);
|
||||
executionRoleCredentials.unregister(handle.getExecutionRoleSessionAccountId(),
|
||||
handle.getExecutionRoleAccessKeyId());
|
||||
try {
|
||||
server.close().get(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (ExecutionException | TimeoutException | CancellationException e) {
|
||||
LOG.warnv(e, "RuntimeApiServer did not close cleanly for process {0}", handle.getContainerId());
|
||||
}
|
||||
if (!processGone) {
|
||||
LOG.warnv("Process {0} did not exit yet; its Runtime API port is released once it does",
|
||||
handle.getContainerId());
|
||||
}
|
||||
releaseWhenGone(server, codeCopies.remove(handle.getContainerId()), process, processGone);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Runtime API port to the pool and deletes the code copy once the process is gone. A
|
||||
* process that is still alive may still use both, so they are released only when it exits.
|
||||
*/
|
||||
private void releaseWhenGone(RuntimeApiServer server, Path codeCopy, Process process, boolean processGone) {
|
||||
Runnable release = () -> {
|
||||
runtimeApiServerFactory.release(server);
|
||||
deleteCopy(codeCopy);
|
||||
};
|
||||
if (processGone) {
|
||||
release.run();
|
||||
} else {
|
||||
process.onExit().thenRun(release);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAlive(ContainerHandle handle) {
|
||||
Process process = processes.get(handle.getContainerId());
|
||||
return process != null && process.isAlive();
|
||||
}
|
||||
|
||||
private static Path codeDirectory(LambdaFunction fn) {
|
||||
if ("Image".equals(fn.getPackageType())) {
|
||||
throw new RuntimeException("Function '" + fn.getFunctionName() + "' is a container image; the process "
|
||||
+ "Lambda executor runs .zip packages only. Use the docker or kubernetes executor.");
|
||||
}
|
||||
if (fn.getRuntime() == null || !fn.getRuntime().startsWith("provided")) {
|
||||
throw new RuntimeException("Function '" + fn.getFunctionName() + "' uses runtime " + fn.getRuntime()
|
||||
+ "; the process Lambda executor runs provided.* runtimes only.");
|
||||
}
|
||||
if (fn.getLayers() != null && !fn.getLayers().isEmpty()) {
|
||||
throw new RuntimeException("Function '" + fn.getFunctionName() + "' has layers, which the process "
|
||||
+ "Lambda executor does not support.");
|
||||
}
|
||||
if (fn.getFileSystemConfigs() != null && !fn.getFileSystemConfigs().isEmpty()) {
|
||||
throw new RuntimeException("Function '" + fn.getFunctionName() + "' mounts a file system, which the "
|
||||
+ "process Lambda executor does not support.");
|
||||
}
|
||||
String location = fn.isHotReload() ? fn.getHotReloadHostPath() : fn.getCodeLocalPath();
|
||||
if (location == null) {
|
||||
throw new RuntimeException("No code location for function '" + fn.getFunctionName()
|
||||
+ "' (function has no deployed code)");
|
||||
}
|
||||
Path code = Path.of(location).toAbsolutePath().normalize();
|
||||
if (!Files.isDirectory(code)) {
|
||||
throw new RuntimeException("Code directory not found for function '" + fn.getFunctionName() + "': "
|
||||
+ code);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a deployed package for one execution environment, as the docker executor copies it into
|
||||
* the container, so a code update or a write by another environment does not change it while it runs.
|
||||
*/
|
||||
private static Path copyOf(LambdaFunction fn, Path code) {
|
||||
Path copy = null;
|
||||
try {
|
||||
copy = Files.createTempDirectory("floci-lambda-" + fn.getFunctionName() + "-");
|
||||
try (Stream<Path> paths = Files.walk(code)) {
|
||||
for (Path source : (Iterable<Path>) paths::iterator) {
|
||||
Path target = copy.resolve(code.relativize(source).toString());
|
||||
if (Files.isDirectory(source, LinkOption.NOFOLLOW_LINKS)) {
|
||||
Files.createDirectories(target);
|
||||
} else {
|
||||
Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES, LinkOption.NOFOLLOW_LINKS);
|
||||
}
|
||||
}
|
||||
}
|
||||
return copy;
|
||||
} catch (IOException | RuntimeException e) {
|
||||
deleteCopy(copy);
|
||||
throw new RuntimeException("Could not copy the code of function '" + fn.getFunctionName() + "': "
|
||||
+ e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteCopy(Path copy) {
|
||||
if (copy == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
FileTrees.delete(copy);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not delete the code copy {0}: {1}", copy, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Floci extracts a .zip package without its file modes, so the environment's copy of {@code bootstrap}
|
||||
* is made executable here, as the docker executor's copy into the container does. A hot-reload directory
|
||||
* belongs to the user and is used as it is.
|
||||
*/
|
||||
private static void requireExecutableBootstrap(LambdaFunction fn, Path bootstrap) {
|
||||
if (!Files.isRegularFile(bootstrap)) {
|
||||
throw new RuntimeException("Function '" + fn.getFunctionName() + "' has no bootstrap at " + bootstrap);
|
||||
}
|
||||
if (!fn.isHotReload() && !Files.isExecutable(bootstrap)) {
|
||||
try {
|
||||
Set<PosixFilePermission> permissions = new HashSet<>(Files.getPosixFilePermissions(bootstrap));
|
||||
permissions.add(PosixFilePermission.OWNER_EXECUTE);
|
||||
Files.setPosixFilePermissions(bootstrap, permissions);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Could not make " + bootstrap + " executable: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
if (!Files.isExecutable(bootstrap)) {
|
||||
throw new RuntimeException("The bootstrap of function '" + fn.getFunctionName() + "' is not executable: "
|
||||
+ bootstrap);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> environment(LambdaFunction fn, Path taskRoot, RuntimeApiServer runtimeApiServer,
|
||||
String region, String accountId, String logGroup, String logStream,
|
||||
Optional<SessionCreds> roleCredentials) {
|
||||
List<String> env = LambdaRuntimeEnv.of(fn, LOOPBACK + ":" + runtimeApiServer.getPort(), logGroup, logStream);
|
||||
env.add("LAMBDA_TASK_ROOT=" + taskRoot);
|
||||
// Lambda's defaults, which the Lambda images set and a host process would otherwise take from the host.
|
||||
env.add("TZ=:UTC");
|
||||
env.add("LANG=en_US.UTF-8");
|
||||
env.addAll(awsEnv.sdkBaselineEnv(region, Optional.empty(), flociEndpoint, roleCredentials, accountId));
|
||||
LambdaRuntimeEnv.addFunctionEnvironment(env, fn, roleCredentials.isPresent());
|
||||
return env;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the process's output until it ends, to Floci's log and the function's CloudWatch stream.
|
||||
* The reader always starts: a pipe nobody drains blocks the process once its buffer fills.
|
||||
*/
|
||||
private void forwardOutput(Process process, String functionName, String accountId, String logGroup,
|
||||
String logStream, String region) {
|
||||
// A platform thread: a virtual thread blocked on a pipe read keeps its carrier, and enough of
|
||||
// them would stall every other virtual thread in Floci.
|
||||
Thread.ofPlatform().daemon().name("lambda-process-logs-" + functionName).start(() -> {
|
||||
try {
|
||||
logStreamer.ensureLogGroupAndStreamForAccount(accountId, logGroup, logStream, region);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Could not create the log stream of function {0}: {1}", functionName, e.getMessage());
|
||||
}
|
||||
try (Reader output = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
char[] buffer = new char[8192];
|
||||
StringBuilder line = new StringBuilder();
|
||||
int read;
|
||||
while ((read = output.read(buffer)) != -1) {
|
||||
for (int i = 0; i < read; i++) {
|
||||
if (buffer[i] != '\n') {
|
||||
line.append(buffer[i]);
|
||||
}
|
||||
if (buffer[i] == '\n' || line.length() >= MAX_LOG_EVENT_CHARS) {
|
||||
forwardLine(line, functionName, accountId, logGroup, logStream, region);
|
||||
}
|
||||
}
|
||||
}
|
||||
forwardLine(line, functionName, accountId, logGroup, logStream, region);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
LOG.debugv("Output of the {0} process ended: {1}", functionName, e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void forwardLine(StringBuilder line, String functionName, String accountId, String logGroup,
|
||||
String logStream, String region) {
|
||||
String trimmed = line.toString().stripTrailing();
|
||||
line.setLength(0);
|
||||
if (trimmed.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
LOG.infov("[lambda:{0}] {1}", functionName, trimmed);
|
||||
logStreamer.streamToCloudWatchLogsForAccount(accountId, logGroup, logStream, region, trimmed);
|
||||
}
|
||||
|
||||
/** Stops the process and its children, returning whether the process is confirmed gone. */
|
||||
private static boolean destroy(Process process) {
|
||||
List<ProcessHandle> descendants = process.descendants().toList();
|
||||
descendants.forEach(ProcessHandle::destroy);
|
||||
process.destroy();
|
||||
try {
|
||||
if (process.waitFor(STOP_GRACE_SECONDS, TimeUnit.SECONDS) && allExited(descendants)) {
|
||||
return true;
|
||||
}
|
||||
descendants.forEach(ProcessHandle::destroyForcibly);
|
||||
process.destroyForcibly();
|
||||
return process.waitFor(STOP_GRACE_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
descendants.forEach(ProcessHandle::destroyForcibly);
|
||||
process.destroyForcibly();
|
||||
return !process.isAlive();
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits out the stop grace period for processes that were already asked to stop. */
|
||||
private static boolean allExited(List<ProcessHandle> handles) throws InterruptedException {
|
||||
CompletableFuture<?>[] exits = handles.stream().map(ProcessHandle::onExit).toArray(CompletableFuture[]::new);
|
||||
try {
|
||||
CompletableFuture.allOf(exits).get(STOP_GRACE_SECONDS, TimeUnit.SECONDS);
|
||||
return true;
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-26
@@ -193,22 +193,8 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
addressResolver.resolve() + ":" + runtimeApiServer.getPort(), cwLogGroup, cwLogStream);
|
||||
env.addAll(awsEnv.sdkBaselineEnv(region, Optional.empty(), addressResolver.flociBaseUrl(),
|
||||
Optional.empty(), AwsArnUtils.accountOrDefault(fn.getFunctionArn(), config.defaultAccountId())));
|
||||
if (fn.getEnvironment() != null) {
|
||||
// Same all-or-nothing rule as ContainerLauncher: this launcher never has
|
||||
// execution-role credentials, so the function's own Environment may only supply
|
||||
// AWS credential vars when it defines the full triad — a partial set must never
|
||||
// join the owner-account baseline and split its credential tuple.
|
||||
boolean userDefinesFullCredentialTriad =
|
||||
ContainerLauncher.definesFullCredentialTriad(fn.getEnvironment());
|
||||
fn.getEnvironment().forEach((k, v) -> {
|
||||
if (!ContainerLauncher.isAwsCredentialVariable(k) || userDefinesFullCredentialTriad) {
|
||||
env.add(k + "=" + v);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
env.removeIf(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION="));
|
||||
env.add("AWS_LAMBDA_FUNCTION_VERSION=" + fn.getVersion());
|
||||
// This launcher never has execution-role credentials.
|
||||
LambdaRuntimeEnv.addFunctionEnvironment(env, fn, false);
|
||||
|
||||
LambdaPodSpecFactory.ImageConfig imageConfig = imagePackage
|
||||
? new LambdaPodSpecFactory.ImageConfig(fn.getImageConfigEntryPoint(),
|
||||
@@ -247,16 +233,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
} catch (RuntimeException e) {
|
||||
LOG.errorv(e, "Pod launch failed for function {0}; cleaning up", fn.getFunctionName());
|
||||
boolean podGone = podName == null || deletePod(namespace, podName);
|
||||
// Stop the server before releasing its port number, or the still-listening
|
||||
// Vert.x server makes the port unusable for every later cold start.
|
||||
try {
|
||||
runtimeApiServer.stop().get(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (Exception stopFailure) {
|
||||
LOG.debugv("Runtime API server stop failed during launch cleanup: {0}",
|
||||
stopFailure.getMessage());
|
||||
}
|
||||
RuntimeApiServerFactory.stopBeforeRelease(runtimeApiServer);
|
||||
// Same rule as stop(): the port number goes back to the pool only once the pod
|
||||
// is confirmed gone. A half-created pod that later reaches Running polls
|
||||
// AWS_LAMBDA_RUNTIME_API on this port, and a released port could by then be
|
||||
|
||||
@@ -47,4 +47,19 @@ public class RuntimeApiServerFactory {
|
||||
public void release(RuntimeApiServer server) {
|
||||
portAllocator.release(server.getPort());
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a server whose environment failed to launch, waiting up to five seconds. Stop it before
|
||||
* releasing its port, or the still-listening server makes a later cold start that reuses the port
|
||||
* serve this runtime too.
|
||||
*/
|
||||
public static void stopBeforeRelease(RuntimeApiServer server) {
|
||||
try {
|
||||
server.stop().get(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Runtime API server stop failed during launch cleanup: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -512,7 +512,7 @@ floci:
|
||||
# extra-hosts: # Extra /etc/hosts entries for Lambda containers, "hostname:ip" ("host-gateway" allowed as ip)
|
||||
# container-name-prefix: floci # FLOCI_SERVICES_LAMBDA_CONTAINER_NAME_PREFIX — base name prefix for spawned containers and code volumes ([A-Za-z0-9][A-Za-z0-9_.-]*; invalid values fall back to "floci")
|
||||
# code-volume-populate-concurrency: # FLOCI_SERVICES_LAMBDA_CODE_VOLUME_POPULATE_CONCURRENCY — max concurrent first-time code-volume populates (default max(2, cpus/2), which a CPU-constrained container collapses to 2)
|
||||
executor: docker # docker | kubernetes (run Lambda environments as pods)
|
||||
executor: docker # docker | kubernetes (run Lambda environments as pods) | process (run provided.* bootstraps on this machine)
|
||||
durable-sweep-enabled: true # FLOCI_SERVICES_LAMBDA_DURABLE_SWEEP_ENABLED - fire durable execution timers (waits, step retries, execution timeouts, retention)
|
||||
durable-sweep-interval-seconds: 1 # FLOCI_SERVICES_LAMBDA_DURABLE_SWEEP_INTERVAL_SECONDS
|
||||
# kubernetes:
|
||||
|
||||
@@ -91,6 +91,13 @@ class DockerAvailabilityReportTest {
|
||||
assertThat(report.failOnUse(Set.of("lambda", "athena", "verifiedpermissions", "ecs")), contains("ecs"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaOnTheProcessExecutorIsNotReported() {
|
||||
when(config.services().lambda().executor()).thenReturn("process");
|
||||
|
||||
assertThat(report.failOnUse(Set.of("lambda", "ecs")), contains("ecs"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2RunsAsMetadataOnlyByDefault() {
|
||||
when(config.network().securityGroupEnforcement().enabled()).thenReturn(false);
|
||||
|
||||
+50
-8
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.lambda.launcher;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.services.lambda.launcher.kubernetes.KubernetesPodLauncher;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
@@ -27,8 +28,11 @@ class LambdaRuntimeLauncherProducerTest {
|
||||
@Mock EmulatorConfig config;
|
||||
@Mock Instance<ContainerLauncher> dockerInstance;
|
||||
@Mock Instance<KubernetesPodLauncher> kubernetesInstance;
|
||||
@Mock Instance<ProcessLauncher> processInstance;
|
||||
@Mock ContainerLauncher containerLauncher;
|
||||
@Mock KubernetesPodLauncher kubernetesPodLauncher;
|
||||
@Mock ProcessLauncher processLauncher;
|
||||
@Mock ContainerDetector containerDetector;
|
||||
|
||||
private EmulatorConfig.LambdaServiceConfig lambda;
|
||||
private final LambdaRuntimeLauncherProducer producer = new LambdaRuntimeLauncherProducer();
|
||||
@@ -42,12 +46,13 @@ class LambdaRuntimeLauncherProducerTest {
|
||||
when(lambda.reconcileContainersOnStartup()).thenReturn(true);
|
||||
when(dockerInstance.get()).thenReturn(containerLauncher);
|
||||
when(kubernetesInstance.get()).thenReturn(kubernetesPodLauncher);
|
||||
when(processInstance.get()).thenReturn(processLauncher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dockerExecutorSelectsContainerLauncher() {
|
||||
when(lambda.executor()).thenReturn("docker");
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance))
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance, processInstance))
|
||||
.isSameAs(containerLauncher);
|
||||
verify(kubernetesInstance, never()).get();
|
||||
}
|
||||
@@ -55,41 +60,78 @@ class LambdaRuntimeLauncherProducerTest {
|
||||
@Test
|
||||
void kubernetesExecutorSelectsPodLauncher() {
|
||||
when(lambda.executor()).thenReturn("kubernetes");
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance))
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance, processInstance))
|
||||
.isSameAs(kubernetesPodLauncher);
|
||||
verify(dockerInstance, never()).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void processExecutorSelectsProcessLauncher() {
|
||||
when(lambda.executor()).thenReturn("process");
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance, processInstance))
|
||||
.isSameAs(processLauncher);
|
||||
verify(dockerInstance, never()).get();
|
||||
verify(kubernetesInstance, never()).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupRefusesTheProcessExecutorInsideAContainer() {
|
||||
when(lambda.executor()).thenReturn("process");
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
assertThatThrownBy(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance,
|
||||
containerDetector))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("inside a container");
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupAcceptsTheProcessExecutorOutsideAContainer() {
|
||||
when(lambda.executor()).thenReturn("process");
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
assertThatCode(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance,
|
||||
containerDetector))
|
||||
.doesNotThrowAnyException();
|
||||
verify(kubernetesInstance, never()).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void processStartupDoesNotInstantiateDocker() {
|
||||
when(lambda.enabled()).thenReturn(true);
|
||||
when(lambda.executor()).thenReturn("process");
|
||||
producer.reconcileDockerContainers(new StartupEvent(), config, dockerInstance);
|
||||
verify(dockerInstance, never()).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void executorValueIsCaseInsensitiveAndTrimmed() {
|
||||
when(lambda.executor()).thenReturn(" Kubernetes\n");
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance))
|
||||
assertThat(producer.launcher(config, dockerInstance, kubernetesInstance, processInstance))
|
||||
.isSameAs(kubernetesPodLauncher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownExecutorFailsWithValidValues() {
|
||||
when(lambda.executor()).thenReturn("podman");
|
||||
assertThatThrownBy(() -> producer.launcher(config, dockerInstance, kubernetesInstance))
|
||||
assertThatThrownBy(() -> producer.launcher(config, dockerInstance, kubernetesInstance, processInstance))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("docker, kubernetes");
|
||||
.hasMessageContaining("docker, kubernetes, process");
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupValidationRejectsUnknownExecutorBeforeFirstInvoke() {
|
||||
when(lambda.executor()).thenReturn("podman");
|
||||
assertThatThrownBy(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance))
|
||||
assertThatThrownBy(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance, containerDetector))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupValidationAcceptsValidExecutors() {
|
||||
when(lambda.executor()).thenReturn("docker");
|
||||
assertThatCode(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance))
|
||||
assertThatCode(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance, containerDetector))
|
||||
.doesNotThrowAnyException();
|
||||
verify(kubernetesPodLauncher, never()).initializeClient();
|
||||
when(lambda.executor()).thenReturn("kubernetes");
|
||||
assertThatCode(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance))
|
||||
assertThatCode(() -> producer.validateExecutor(new StartupEvent(), config, kubernetesInstance, containerDetector))
|
||||
.doesNotThrowAnyException();
|
||||
verify(kubernetesPodLauncher).initializeClient();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
package io.floci.aws.services.lambda.launcher;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.floci.aws.core.common.port.PortAllocator;
|
||||
import io.floci.aws.services.iam.model.SessionCreds;
|
||||
import io.floci.aws.services.lambda.model.InvokeResult;
|
||||
import io.floci.aws.services.lambda.model.LambdaFileSystemConfig;
|
||||
import io.floci.aws.services.lambda.model.LambdaFunction;
|
||||
import io.floci.aws.services.lambda.model.PendingInvocation;
|
||||
import io.floci.aws.services.lambda.runtime.RuntimeApiServer;
|
||||
import io.floci.aws.services.lambda.runtime.RuntimeApiServerFactory;
|
||||
import io.vertx.core.Vertx;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.DisabledOnOs;
|
||||
import org.junit.jupiter.api.condition.OS;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@DisabledOnOs(OS.WINDOWS)
|
||||
class ProcessLauncherTest {
|
||||
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":function:fn";
|
||||
|
||||
/** Answers each invocation with its event, handler and SDK endpoint, polling the Runtime API with curl. */
|
||||
private static final String CURL_BOOTSTRAP = """
|
||||
set -eu
|
||||
api="http://$AWS_LAMBDA_RUNTIME_API/2018-06-01/runtime/invocation"
|
||||
while true; do
|
||||
headers=$(mktemp)
|
||||
event=$(curl -sS -D "$headers" "$api/next")
|
||||
request_id=$(grep -i '^lambda-runtime-aws-request-id:' "$headers" | tr -d '\\r' | cut -d' ' -f2)
|
||||
rm -f "$headers"
|
||||
curl -sS -X POST "$api/$request_id/response" \\
|
||||
-d "{\\"event\\":$event,\\"handler\\":\\"$_HANDLER\\",\\"endpoint\\":\\"$AWS_ENDPOINT_URL\\"}" > /dev/null
|
||||
done
|
||||
""";
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@TempDir
|
||||
Path output;
|
||||
|
||||
private RuntimeApiServerFactory runtimeApiServerFactory;
|
||||
private RuntimeApiServer runtimeApiServer;
|
||||
private LaunchedContainerAwsEnv awsEnv;
|
||||
private ContainerLogStreamer logStreamer;
|
||||
private LambdaExecutionRoleCredentials roleCredentials;
|
||||
private ProcessLauncher launcher;
|
||||
private final List<ContainerHandle> launched = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
runtimeApiServerFactory = mock(RuntimeApiServerFactory.class);
|
||||
runtimeApiServer = mock(RuntimeApiServer.class);
|
||||
when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);
|
||||
when(runtimeApiServer.getPort()).thenReturn(12000);
|
||||
when(runtimeApiServer.stop()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(runtimeApiServer.close()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
awsEnv = mock(LaunchedContainerAwsEnv.class);
|
||||
when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString()))
|
||||
.thenReturn(List.of("AWS_REGION=" + REGION, "AWS_ENDPOINT_URL=http://127.0.0.1:4566"));
|
||||
logStreamer = mock(ContainerLogStreamer.class);
|
||||
when(logStreamer.generateLogStreamName(anyString())).thenReturn("2026/01/01/[$LATEST]stream");
|
||||
|
||||
roleCredentials = mock(LambdaExecutionRoleCredentials.class);
|
||||
|
||||
launcher = launcherBoundTo("127.0.0.1");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopLaunched() {
|
||||
launched.forEach(launcher::stop);
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchRunsTheBootstrapWithOnlyTheLambdaEnvironment() throws IOException {
|
||||
Path code = codeDirectory(writeOutput("env", "env") + "exec sleep 30\n", false);
|
||||
LambdaFunction fn = function(code);
|
||||
fn.setEnvironment(Map.of("GREETING", "hello", "AWS_ACCESS_KEY_ID", "partial"));
|
||||
|
||||
ContainerHandle handle = launch(fn);
|
||||
|
||||
List<String> env = awaitOutput("env");
|
||||
assertThat(env).contains(
|
||||
"AWS_LAMBDA_RUNTIME_API=127.0.0.1:12000",
|
||||
"_HANDLER=function.handler",
|
||||
"AWS_LAMBDA_FUNCTION_NAME=fn",
|
||||
"AWS_LAMBDA_FUNCTION_VERSION=$LATEST",
|
||||
"AWS_ENDPOINT_URL=http://127.0.0.1:4566",
|
||||
"GREETING=hello",
|
||||
"TZ=:UTC",
|
||||
"LANG=en_US.UTF-8");
|
||||
assertThat(env).noneMatch(line -> line.startsWith("AWS_ACCESS_KEY_ID="));
|
||||
assertThat(env).noneMatch(line -> line.startsWith("HOME="));
|
||||
verify(awsEnv).sdkBaselineEnv(eq(REGION), eq(Optional.empty()), eq("http://127.0.0.1:4566"),
|
||||
eq(Optional.empty()), eq(ACCOUNT));
|
||||
verify(runtimeApiServer).markContainerStarted();
|
||||
assertThat(launcher.isAlive(handle)).isTrue();
|
||||
assertThat(handle.isHotReload()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aZipPackageRunsFromACopyThatStopDeletes() throws IOException {
|
||||
Path code = codeDirectory(writeOutput("pwd", "pwd") + "exec sleep 30\n", false);
|
||||
Files.writeString(code.resolve("handler.txt"), "v1");
|
||||
ContainerHandle handle = launcher.launch(function(code));
|
||||
|
||||
Path copy = Path.of(awaitOutput("pwd").getFirst());
|
||||
Files.writeString(code.resolve("handler.txt"), "v2");
|
||||
|
||||
assertThat(copy.toRealPath()).isNotEqualTo(code.toRealPath());
|
||||
assertThat(Files.readString(copy.resolve("handler.txt"))).isEqualTo("v1");
|
||||
assertThat(Files.isExecutable(code.resolve("bootstrap"))).isFalse();
|
||||
launcher.stop(handle);
|
||||
assertThat(copy).doesNotExist();
|
||||
}
|
||||
|
||||
@Test
|
||||
void longOutputWithoutNewlinesIsSplitIntoLogEvents() throws IOException {
|
||||
launch(function(codeDirectory("head -c 300000 /dev/zero | tr '\\0' a\necho\nexec sleep 30\n", true)));
|
||||
|
||||
verify(logStreamer, timeout(10_000)).streamToCloudWatchLogsForAccount(eq(ACCOUNT), eq("/aws/lambda/fn"),
|
||||
eq("2026/01/01/[$LATEST]stream"), eq(REGION), argThat(event -> event.length() == 256 * 1024));
|
||||
verify(logStreamer, timeout(10_000)).streamToCloudWatchLogsForAccount(eq(ACCOUNT), eq("/aws/lambda/fn"),
|
||||
eq("2026/01/01/[$LATEST]stream"), eq(REGION),
|
||||
argThat(event -> event.length() == 300_000 - 256 * 1024));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBootstrapAnswersAnInvocationThroughTheRuntimeApi() throws Exception {
|
||||
String path = System.getenv("PATH");
|
||||
assumeTrue(path != null && Arrays.stream(path.split(File.pathSeparator))
|
||||
.anyMatch(dir -> Files.isExecutable(Path.of(dir, "curl"))), "the bootstrap needs curl");
|
||||
Vertx vertx = Vertx.vertx();
|
||||
try {
|
||||
PortAllocator ports = mock(PortAllocator.class);
|
||||
when(ports.allocate()).thenReturn(freePort());
|
||||
RuntimeApiServer server = new RuntimeApiServerFactory(vertx, ports).create();
|
||||
when(runtimeApiServerFactory.create()).thenReturn(server);
|
||||
ContainerHandle handle = launch(function(codeDirectory(CURL_BOOTSTRAP, true)));
|
||||
|
||||
InvokeResult result = server.enqueue(new PendingInvocation("request-1",
|
||||
"{\"n\":1}".getBytes(StandardCharsets.UTF_8), System.currentTimeMillis() + 60_000,
|
||||
FUNCTION_ARN, new CompletableFuture<>())).get(20, TimeUnit.SECONDS);
|
||||
|
||||
assertThat(result.getFunctionError()).isNull();
|
||||
assertThat(new String(result.getPayload(), StandardCharsets.UTF_8)).isEqualTo(
|
||||
"{\"event\":{\"n\":1},\"handler\":\"function.handler\",\"endpoint\":\"http://127.0.0.1:4566\"}");
|
||||
launched.remove(handle);
|
||||
launcher.stop(handle);
|
||||
} finally {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExecutionRoleSessionReplacesTheFunctionsCredentials() throws IOException {
|
||||
SessionCreds session = new SessionCreds("ASIAEXAMPLE", "secret", "token");
|
||||
LambdaFunction fn = function(codeDirectory(writeOutput("env", "env") + "exec sleep 30\n", true));
|
||||
when(roleCredentials.forFunction(fn)).thenReturn(Optional.of(session));
|
||||
when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), eq(Optional.of(session)), anyString()))
|
||||
.thenReturn(List.of("AWS_ACCESS_KEY_ID=ASIAEXAMPLE"));
|
||||
fn.setEnvironment(Map.of("AWS_ACCESS_KEY_ID", "user", "AWS_SECRET_ACCESS_KEY", "user",
|
||||
"AWS_SESSION_TOKEN", "user"));
|
||||
|
||||
ContainerHandle handle = launcher.launch(fn);
|
||||
List<String> env = awaitOutput("env");
|
||||
launcher.stop(handle);
|
||||
|
||||
assertThat(env).contains("AWS_ACCESS_KEY_ID=ASIAEXAMPLE");
|
||||
assertThat(env).noneMatch(line -> line.endsWith("=user"));
|
||||
verify(roleCredentials).unregister(ACCOUNT, "ASIAEXAMPLE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSpecificBindAddressIsTheEndpointTheFunctionUses() throws IOException {
|
||||
launcher = launcherBoundTo("192.168.1.10");
|
||||
|
||||
launch(function(codeDirectory("exec sleep 30\n", true)));
|
||||
|
||||
verify(awsEnv).sdkBaselineEnv(eq(REGION), eq(Optional.empty()), eq("http://192.168.1.10:4566"),
|
||||
eq(Optional.empty()), eq(ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopKillsChildrenThatIgnoreTermination() throws IOException {
|
||||
Path code = codeDirectory("(trap '' TERM; exec sleep 30) &\n"
|
||||
+ writeOutput("echo $!", "child") + "exec sleep 30\n", true);
|
||||
ContainerHandle handle = launcher.launch(function(code));
|
||||
long childPid = Long.parseLong(awaitOutput("child").getFirst().strip());
|
||||
|
||||
launcher.stop(handle);
|
||||
|
||||
Awaitility.await().atMost(Duration.ofSeconds(10)).until(() ->
|
||||
ProcessHandle.of(childPid).map(child -> !child.isAlive()).orElse(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopEndsTheProcessAndReleasesThePort() throws IOException {
|
||||
ContainerHandle handle = launcher.launch(function(codeDirectory("exec sleep 30\n", true)));
|
||||
assertThat(launcher.isAlive(handle)).isTrue();
|
||||
|
||||
launcher.stop(handle);
|
||||
|
||||
assertThat(launcher.isAlive(handle)).isFalse();
|
||||
verify(runtimeApiServer).quiesce();
|
||||
verify(runtimeApiServer).close();
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBootstrapThatExitsIsReportedAsARuntimeExit() throws IOException {
|
||||
launch(function(codeDirectory("exit 3\n", true)));
|
||||
|
||||
verify(runtimeApiServer, timeout(10_000)).handleRuntimeProcessExited(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputReachesTheFunctionsLogStream() throws IOException {
|
||||
launch(function(codeDirectory("echo ready\nexec sleep 30\n", true)));
|
||||
|
||||
verify(logStreamer, timeout(10_000)).ensureLogGroupAndStreamForAccount(ACCOUNT, "/aws/lambda/fn",
|
||||
"2026/01/01/[$LATEST]stream", REGION);
|
||||
verify(logStreamer, timeout(10_000)).streamToCloudWatchLogsForAccount(ACCOUNT, "/aws/lambda/fn",
|
||||
"2026/01/01/[$LATEST]stream", REGION, "ready");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBootstrapThatCannotStartReleasesItsRuntimeApiServer() throws IOException {
|
||||
Path code = Files.createTempDirectory(tempDir, "code");
|
||||
Path bootstrap = code.resolve("bootstrap");
|
||||
Files.writeString(bootstrap, "#!/nonexistent/interpreter\n");
|
||||
Files.setPosixFilePermissions(bootstrap, PosixFilePermissions.fromString("rwxr-xr-x"));
|
||||
|
||||
assertThatThrownBy(() -> launcher.launch(function(code))).isInstanceOf(RuntimeException.class);
|
||||
|
||||
verify(runtimeApiServer).stop();
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hotReloadRunsFromTheHostDirectory() throws IOException {
|
||||
Path hostDirectory = codeDirectory("pwd > pwd.tmp && mv pwd.tmp pwd.out\nexec sleep 30\n", true);
|
||||
LambdaFunction fn = function(null);
|
||||
fn.setHotReloadHostPath(hostDirectory.toString());
|
||||
|
||||
ContainerHandle handle = launch(fn);
|
||||
|
||||
Path pwdFile = hostDirectory.resolve("pwd.out");
|
||||
Awaitility.await().atMost(Duration.ofSeconds(10)).until(() -> Files.exists(pwdFile));
|
||||
assertThat(Path.of(Files.readString(pwdFile).strip()).toRealPath()).isEqualTo(hostDirectory.toRealPath());
|
||||
assertThat(handle.isHotReload()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonExecutableHotReloadBootstrapIsRejected() throws IOException {
|
||||
LambdaFunction fn = function(null);
|
||||
fn.setHotReloadHostPath(codeDirectory("exec sleep 30\n", false).toString());
|
||||
|
||||
assertRejected(fn, "is not executable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerImagesAreRejected() throws IOException {
|
||||
LambdaFunction fn = function(codeDirectory("exec sleep 30\n", true));
|
||||
fn.setPackageType("Image");
|
||||
|
||||
assertRejected(fn, "container image");
|
||||
}
|
||||
|
||||
@Test
|
||||
void managedRuntimesAreRejected() throws IOException {
|
||||
LambdaFunction fn = function(codeDirectory("exec sleep 30\n", true));
|
||||
fn.setRuntime("python3.13");
|
||||
|
||||
assertRejected(fn, "provided.* runtimes only");
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionsWithLayersAreRejected() throws IOException {
|
||||
LambdaFunction fn = function(codeDirectory("exec sleep 30\n", true));
|
||||
fn.setLayers(List.of("arn:aws:lambda:us-east-1:" + ACCOUNT + ":layer:tools:1"));
|
||||
|
||||
assertRejected(fn, "has layers");
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionsWithFileSystemsAreRejected() throws IOException {
|
||||
LambdaFunction fn = function(codeDirectory("exec sleep 30\n", true));
|
||||
fn.setFileSystemConfigs(List.of(new LambdaFileSystemConfig(
|
||||
"arn:aws:elasticfilesystem:us-east-1:" + ACCOUNT + ":access-point/fsap-1", "/mnt/data")));
|
||||
|
||||
assertRejected(fn, "mounts a file system");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPackageWithoutABootstrapIsRejected() throws IOException {
|
||||
Path code = Files.createDirectories(tempDir.resolve("empty"));
|
||||
|
||||
assertRejected(function(code), "has no bootstrap");
|
||||
}
|
||||
|
||||
private ProcessLauncher launcherBoundTo(String host) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.regionOf(FUNCTION_ARN)).thenReturn(REGION);
|
||||
return new ProcessLauncher(config, regionResolver, runtimeApiServerFactory, awsEnv, logStreamer,
|
||||
roleCredentials, host, 4566);
|
||||
}
|
||||
|
||||
private ContainerHandle launch(LambdaFunction fn) {
|
||||
ContainerHandle handle = launcher.launch(fn);
|
||||
launched.add(handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
private void assertRejected(LambdaFunction fn, String message) {
|
||||
assertThatThrownBy(() -> launcher.launch(fn)).hasMessageContaining(message);
|
||||
verify(runtimeApiServerFactory, never()).create();
|
||||
}
|
||||
|
||||
/** A shell line that writes {@code command}'s output to the output file {@code name}, all at once. */
|
||||
private String writeOutput(String command, String name) {
|
||||
Path file = output.resolve(name);
|
||||
return command + " > '" + file + ".tmp' && mv '" + file + ".tmp' '" + file + "'\n";
|
||||
}
|
||||
|
||||
private List<String> awaitOutput(String name) throws IOException {
|
||||
Path file = output.resolve(name);
|
||||
Awaitility.await().atMost(Duration.ofSeconds(10)).until(() -> Files.exists(file));
|
||||
return Files.readAllLines(file);
|
||||
}
|
||||
|
||||
private static int freePort() throws IOException {
|
||||
try (ServerSocket socket = new ServerSocket(0)) {
|
||||
return socket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
private Path codeDirectory(String script, boolean executable) throws IOException {
|
||||
Path code = Files.createTempDirectory(tempDir, "code");
|
||||
Path bootstrap = code.resolve("bootstrap");
|
||||
Files.writeString(bootstrap, "#!/bin/sh\n" + script);
|
||||
Files.setPosixFilePermissions(bootstrap, PosixFilePermissions.fromString(executable ? "rwxr-xr-x" : "rw-r--r--"));
|
||||
return code;
|
||||
}
|
||||
|
||||
private static LambdaFunction function(Path code) {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("fn");
|
||||
fn.setFunctionArn(FUNCTION_ARN);
|
||||
fn.setRuntime("provided.al2023");
|
||||
fn.setHandler("function.handler");
|
||||
fn.setPackageType("Zip");
|
||||
if (code != null) {
|
||||
fn.setCodeLocalPath(code.toString());
|
||||
}
|
||||
return fn;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user