feat(lambda): implement the Lambda Extensions API (#1773)

* feat(lambda): implement the Lambda Extensions API
This commit is contained in:
Jay authored and GitHub committed 2026-08-01 15:59:34 -05:00
1 parent bb7c45ce1b
commit 9f0dec9317
10 files changed
+2354 -73

No files matched your search

@@ -5,6 +5,7 @@ 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.model.ContainerState;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
@@ -14,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -157,6 +159,80 @@ class WarmPoolTest {
pool.shutdown();
}
/**
* An extension reporting init/exit error is fatal to the execution environment in real AWS,
* so the container must be retired after the invocation rather than returned to the pool.
*/
@Test
void releaseAfterExtensionFatalError_retiresContainerInsteadOfPooling() {
WarmPool pool = buildPool();
pool.init();
LambdaFunction fn = mock(LambdaFunction.class);
when(fn.getFunctionName()).thenReturn("faulted-fn");
RuntimeApiServer faultedServer = mock(RuntimeApiServer.class);
when(faultedServer.isFaulted()).thenReturn(true);
ContainerHandle faulted = new ContainerHandle("cid-faulted", "faulted-fn", faultedServer, ContainerState.WARM);
ContainerHandle fresh = new ContainerHandle("cid-fresh", "faulted-fn", null, ContainerState.WARM);
// Both acquires below cold-start (the pool is empty, then the faulted handle is discarded
// before any liveness check), so no isAlive stubbing is needed.
when(containerLauncher.launch(any())).thenReturn(faulted, fresh);
ContainerHandle first = pool.acquire(fn);
assertSame(faulted, first);
// The extension died during this invocation; releasing must tear the container down.
pool.release(first);
verify(containerLauncher, times(1)).stop(faulted);
// The next acquire cold-starts rather than handing the condemned container back out.
ContainerHandle second = pool.acquire(fn);
assertSame(fresh, second);
assertNotSame(faulted, second);
verify(containerLauncher, times(2)).launch(any());
pool.shutdown();
}
/**
* A container whose extension faults while it sits WARM in the pool is still *running*, so the
* liveness probe alone would hand it back out. It must be skipped and discarded on acquire.
*/
@Test
void acquire_discardsPooledHandleWhoseExtensionFaulted() {
WarmPool pool = buildPool();
pool.init();
LambdaFunction fn = mock(LambdaFunction.class);
when(fn.getFunctionName()).thenReturn("pooled-fault-fn");
RuntimeApiServer server = mock(RuntimeApiServer.class);
ContainerHandle pooled = new ContainerHandle("cid-pooled", "pooled-fault-fn", server, ContainerState.WARM);
ContainerHandle fresh = new ContainerHandle("cid-fresh", "pooled-fault-fn", null, ContainerState.WARM);
when(containerLauncher.launch(any())).thenReturn(pooled, fresh);
// Healthy at release time, so it goes into the pool as normal.
when(server.isFaulted()).thenReturn(false);
ContainerHandle seeded = pool.acquire(fn);
assertSame(pooled, seeded);
pool.release(seeded);
// The extension now faults while the container sits idle in the pool. isAlive() is stubbed
// true so the container is unambiguously still running: if the faulted check were removed,
// this handle would be considered reusable and handed straight back out.
when(server.isFaulted()).thenReturn(true);
lenient().when(containerLauncher.isAlive(pooled)).thenReturn(true);
ContainerHandle acquired = pool.acquire(fn);
assertSame(fresh, acquired);
assertNotSame(pooled, acquired);
verify(containerLauncher, times(1)).stop(pooled);
pool.shutdown();
}
@Test
void acquire_discardsDeadPooledHandleAndColdStarts() {
WarmPool pool = buildPool();
@@ -14,9 +14,19 @@ 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 com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.ExecStartCmd;
import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import com.github.dockerjava.api.model.Mount;
import com.github.dockerjava.api.model.MountType;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -26,11 +36,16 @@ import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -38,6 +53,8 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@@ -565,4 +582,334 @@ class ContainerLauncherTest {
verify(lifecycleManager, never()).create(any());
verify(lifecycleManager, never()).startCreated(any(), any());
}
/** Builds a tar archive matching what {@code docker cp}/{@code copyArchiveFromContainerCmd}
* returns for a directory: the directory itself as a leading entry, then each name as a direct
* child, executable. */
private static byte[] tarOf(String... binaryNames) throws IOException {
var entries = new java.util.LinkedHashMap<String, Boolean>();
for (String name : binaryNames) {
entries.put(name, true);
}
return tarOfRaw(entries);
}
/** Like {@link #tarOf}, but lets each entry's executable bit be controlled individually
* (name -> executable), so filtering logic (non-executable files, nested paths) can be
* exercised. Names containing "/" are written as-is (not prefixed), to model entries nested
* more than one level below the extensions directory. */
private static byte[] tarOfRaw(java.util.Map<String, Boolean> nameToExecutable) throws IOException {
var bos = new java.io.ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) {
TarArchiveEntry dir = new TarArchiveEntry("extensions/");
tar.putArchiveEntry(dir);
tar.closeArchiveEntry();
for (var e : nameToExecutable.entrySet()) {
TarArchiveEntry entry = new TarArchiveEntry("extensions/" + e.getKey());
entry.setMode(e.getValue() ? 0100755 : 0100644); // executable vs. non-executable regular file
entry.setSize(0);
tar.putArchiveEntry(entry);
tar.closeArchiveEntry();
}
}
return bos.toByteArray();
}
/** Stubs container-123's /opt/extensions listing (via the Docker archive API, not exec) to
* return the given binary names, and stubs exec of each resulting /opt/extensions/<name> path
* to succeed immediately. */
private List<ExecCreateCmd> stubExtensionDiscovery(String... binaryNames) throws IOException {
return stubExtensionDiscoveryFromTar(tarOf(binaryNames));
}
/** Same as {@link #stubExtensionDiscovery}, but takes a caller-built tar so tests can exercise
* {@code listExtensionBinaries}' entry filtering (non-executable files, nested paths) rather
* than only the convenience all-executable-direct-children shape. Returns the {@code ExecCreateCmd}
* mock for each launched binary, in launch order — pass it to {@link #capturedLaunchPaths} after
* calling {@code launch()} to assert on exactly which discovered names were (and weren't) launched. */
private List<ExecCreateCmd> stubExtensionDiscoveryFromTar(byte[] tar) {
CopyArchiveFromContainerCmd copyCmd = mock(CopyArchiveFromContainerCmd.class);
when(copyCmd.exec()).thenReturn(new java.io.ByteArrayInputStream(tar));
when(dockerClient.copyArchiveFromContainerCmd("container-123", "/opt/extensions"))
.thenReturn(copyCmd);
List<ExecCreateCmd> launchCmds = new java.util.ArrayList<>();
lenient().when(dockerClient.execCreateCmd("container-123"))
.thenAnswer(invocation -> {
ExecCreateCmd launchCmd = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
ExecCreateCmdResponse launchResponse = mock(ExecCreateCmdResponse.class);
when(launchResponse.getId()).thenReturn("exec-launch-" + java.util.UUID.randomUUID());
when(launchCmd.exec()).thenReturn(launchResponse);
launchCmds.add(launchCmd);
return launchCmd;
});
lenient().when(dockerClient.execStartCmd(argThat(id -> id != null && id.startsWith("exec-launch-"))))
.thenAnswer(invocation -> {
ExecStartCmd start = mock(ExecStartCmd.class);
when(start.exec(any())).thenAnswer(startInvocation -> {
@SuppressWarnings("unchecked")
ResultCallback<Frame> cb = startInvocation.getArgument(0);
cb.onComplete();
return cb;
});
return start;
});
// launcher.launch(fn) populates this list after this method returns.
return launchCmds;
}
/** Overrides the default exec-start stub so the callback the launcher supplies is driven with a
* real STDOUT {@link Frame} carrying {@code output}, exercising the frame-to-CloudWatch path
* rather than only completing the callback. */
private void stubExecStartEmittingFrame(String output) {
lenient().when(dockerClient.execStartCmd(argThat(id -> id != null && id.startsWith("exec-launch-"))))
.thenAnswer(invocation -> {
ExecStartCmd start = mock(ExecStartCmd.class);
when(start.exec(any())).thenAnswer(startInvocation -> {
@SuppressWarnings("unchecked")
ResultCallback<Frame> cb = startInvocation.getArgument(0);
cb.onNext(new Frame(StreamType.STDOUT, output.getBytes(StandardCharsets.UTF_8)));
cb.onComplete();
return cb;
});
return start;
});
}
/** Extracts the single command-line argument each mock in {@code launchCmds} was called with
* via {@code withCmd(String...)}, in call order — the {@code /opt/extensions/<name>} path
* each discovered extension binary was launched with. */
private static List<String> capturedLaunchPaths(List<ExecCreateCmd> launchCmds) {
List<String> paths = new java.util.ArrayList<>();
for (ExecCreateCmd cmd : launchCmds) {
ArgumentCaptor<String[]> captor = ArgumentCaptor.forClass(String[].class);
verify(cmd).withCmd(captor.capture());
paths.add(captor.getValue()[0]);
}
return paths;
}
@Test
void launchFunction_discoversAndLaunchesExtensionBinaries() throws Exception {
stubExtensionDiscovery("lambda-adapter");
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("with-extension-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
launcher.launch(fn);
// The extension binary was discovered via the archive API and execed by its full
// /opt/extensions path, after the container was started (real AWS starts extensions once
// the container is up, alongside the runtime).
verify(dockerClient).copyArchiveFromContainerCmd("container-123", "/opt/extensions");
verify(dockerClient, atLeastOnce()).execCreateCmd(eq("container-123"));
InOrder inOrder = inOrder(lifecycleManager, dockerClient);
inOrder.verify(lifecycleManager).startCreated(eq("container-123"), any());
inOrder.verify(dockerClient).copyArchiveFromContainerCmd("container-123", "/opt/extensions");
inOrder.verify(dockerClient, atLeastOnce()).execCreateCmd("container-123");
}
/**
* Extension stdout/stderr must reach the function's CloudWatch log group. `docker logs` — and
* therefore ContainerLogStreamer.attach(), which uses logContainerCmd — only covers the
* container's PID 1 output, so an exec's stream never reaches the container log. Without
* explicit forwarding an observability extension's output is dropped entirely.
*
* <p>Uses a real ContainerLogStreamer over a mocked CloudWatchLogsService so the assertion
* covers the actual frame-to-log-event path rather than just that a mock was called.
*/
@Test
void launchFunction_forwardsExtensionOutputToCloudWatchLogs() throws Exception {
CloudWatchLogsService cloudWatchLogs = mock(CloudWatchLogsService.class);
ContainerReachableEndpoint reachableEndpoint =
new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer);
ContainerLauncher launcherWithRealStreamer = new ContainerLauncher(
new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer),
lifecycleManager,
new ContainerLogStreamer(dockerClient, cloudWatchLogs),
imageResolver, runtimeApiServerFactory, dockerHostResolver, config,
ecrRegistryManager,
mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class),
new LaunchedContainerAwsEnv(reachableEndpoint));
stubExtensionDiscovery("otel-collector");
// Feed a real stdout frame through whatever callback the launcher hands to execStartCmd.
stubExecStartEmittingFrame("extension started on :8080\n");
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("observability-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
launcherWithRealStreamer.launch(fn);
// The frame became a CloudWatch log event in the function's own log group.
ArgumentCaptor<List<Map<String, Object>>> events = ArgumentCaptor.forClass(List.class);
verify(cloudWatchLogs, atLeastOnce()).putLogEvents(
eq("/aws/lambda/observability-fn"), anyString(), events.capture(), anyString());
assertTrue(events.getAllValues().stream()
.flatMap(List::stream)
.anyMatch(e -> "extension started on :8080".equals(e.get("message"))),
"extension stdout must be forwarded to the function's CloudWatch log group");
}
/**
* The log group and stream must exist before extensions are launched: they can log immediately,
* and putLogEvents against a missing stream is swallowed at debug level — silently losing
* exactly the early startup output this forwarding exists to capture.
*/
@Test
void launchFunction_createsLogGroupBeforeLaunchingExtensions() throws Exception {
stubExtensionDiscovery("lambda-adapter");
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("ordering-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
launcher.launch(fn);
InOrder inOrder = inOrder(logStreamer, dockerClient);
inOrder.verify(logStreamer).ensureLogGroupAndStream(
eq("/aws/lambda/ordering-fn"), anyString(), anyString());
inOrder.verify(dockerClient, atLeastOnce()).execCreateCmd("container-123");
}
/**
* The init-readiness barrier abanna asked for on PR #1773: extension processes are started as
* detached execs, so without waiting the caller could enqueue the first invocation before an
* extension was ready for it and the adapter would silently miss that invoke. The launch must
* arm the barrier with the discovered binary count *before* starting any exec (so a
* fast-starting extension can't become ready before there is a latch to count it down), and
* must not return until the extensions are init-ready.
*/
@Test
void launchFunction_waitsForExtensionsToBecomeReadyBeforeReturning() throws Exception {
stubExtensionDiscovery("lambda-adapter", "otel-collector");
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("barrier-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
// Readiness is delayed: awaitExtensionsReady only reports success after a pause, standing
// in for extension processes that take a moment to start up and poll for their first event.
AtomicBoolean readinessComplete = new AtomicBoolean(false);
when(runtimeApiServer.awaitExtensionsReady(anyLong())).thenAnswer(inv -> {
Thread.sleep(150);
readinessComplete.set(true);
return true;
});
launcher.launch(fn);
assertTrue(readinessComplete.get(),
"launch() must not return before the extensions are init-ready");
// The barrier is armed with the number of binaries actually discovered, and armed before
// any extension process is started.
verify(runtimeApiServer).expectExtensions(2);
InOrder inOrder = inOrder(runtimeApiServer, dockerClient);
inOrder.verify(runtimeApiServer).expectExtensions(2);
inOrder.verify(dockerClient, atLeastOnce()).execCreateCmd("container-123");
inOrder.verify(runtimeApiServer).awaitExtensionsReady(anyLong());
}
/**
* A slow or crashed extension must degrade to "invocations run without it", not fail the whole
* function launch — the same outcome as before the barrier existed.
*/
@Test
void launchFunction_extensionReadinessTimeout_doesNotFailLaunch() throws Exception {
stubExtensionDiscovery("never-registers");
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("timeout-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
when(runtimeApiServer.awaitExtensionsReady(anyLong())).thenReturn(false);
ContainerHandle handle = launcher.launch(fn);
assertNotNull(handle, "a readiness timeout must not fail the launch");
assertEquals("container-123", handle.getContainerId());
}
/**
* The common case — no /opt/extensions directory — must not wait at all: the barrier is armed
* with zero and the launch proceeds immediately.
*/
@Test
void launchFunction_noExtensions_armsBarrierWithZeroAndDoesNotBlock() throws Exception {
CopyArchiveFromContainerCmd copyCmd = mock(CopyArchiveFromContainerCmd.class);
when(copyCmd.exec()).thenThrow(new NotFoundException("no such directory"));
when(dockerClient.copyArchiveFromContainerCmd("container-123", "/opt/extensions"))
.thenReturn(copyCmd);
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("no-extension-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
launcher.launch(fn);
verify(runtimeApiServer).expectExtensions(0);
}
@Test
void launchFunction_noExtensionsDirectory_doesNotFailLaunch() throws Exception {
CopyArchiveFromContainerCmd copyCmd = mock(CopyArchiveFromContainerCmd.class);
when(copyCmd.exec()).thenThrow(new NotFoundException("no such directory"));
when(dockerClient.copyArchiveFromContainerCmd("container-123", "/opt/extensions"))
.thenReturn(copyCmd);
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("no-extension-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
launcher.launch(fn);
// The discovery probe still runs (best-effort), but nothing beyond it — no extension
// binary path is ever execed since the directory doesn't exist.
verify(dockerClient, never()).execCreateCmd("container-123");
}
@Test
void launchFunction_extensionDiscovery_filtersNonExecutableAndNestedEntries() throws Exception {
var entries = new java.util.LinkedHashMap<String, Boolean>();
entries.put("lambda-adapter", true); // direct child, executable: launched
entries.put("README.md", false); // direct child, not executable: skipped
entries.put("nested/inner-binary", true); // nested (not a direct child): skipped
List<ExecCreateCmd> launchCmds = stubExtensionDiscoveryFromTar(tarOfRaw(entries));
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("mixed-extensions-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
launcher.launch(fn);
assertEquals(List.of("/opt/extensions/lambda-adapter"), capturedLaunchPaths(launchCmds),
"only the direct, executable entry should be launched");
}
@Test
void launchFunction_multipleExtensionBinaries_allDiscoveredAndLaunched() throws Exception {
List<ExecCreateCmd> launchCmds = stubExtensionDiscoveryFromTar(tarOf("lambda-adapter", "otel-collector"));
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("multi-extension-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
launcher.launch(fn);
assertEquals(List.of("/opt/extensions/lambda-adapter", "/opt/extensions/otel-collector"),
capturedLaunchPaths(launchCmds));
}
}