fix(lambda): return invocation log tails for LogType=Tail (#8618) (#8661)

This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-17 05:50:15 -04:00
1 parent 7ed62b2597
commit c2401d7e06
23 files changed
+1100 -28

No files matched your search

@@ -271,8 +271,13 @@ public class LambdaController {
? decodeClientContext(headers.getHeaderString("X-Amz-Client-Context")) : null;
String durableExecutionName = headers.getHeaderString("X-Amz-Durable-Execution-Name");
InvokeResult result = lambdaService.invoke(region, functionName, qualifier, payload, type, clientContext,
durableExecutionName, headers.getHeaderString("X-Amzn-Trace-Id"));
boolean logTail = type == InvocationType.RequestResponse
&& "Tail".equals(headers.getHeaderString("X-Amz-Log-Type"));
InvokeResult result = logTail
? lambdaService.invoke(region, functionName, qualifier, payload, type, clientContext,
durableExecutionName, headers.getHeaderString("X-Amzn-Trace-Id"), true)
: lambdaService.invoke(region, functionName, qualifier, payload, type, clientContext,
durableExecutionName, headers.getHeaderString("X-Amzn-Trace-Id"));
if (type != InvocationType.Event
&& result.getPayload() != null
@@ -288,7 +293,7 @@ public class LambdaController {
if (result.getFunctionError() != null) {
builder.header("X-Amz-Function-Error", result.getFunctionError());
}
if (result.getLogResult() != null) {
if (logTail && result.getLogResult() != null) {
builder.header("X-Amz-Log-Result", result.getLogResult());
}
builder.header("X-Amz-Executed-Version", result.getExecutedVersion());
@@ -21,6 +21,7 @@ import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.UncheckedIOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.time.Clock;
@@ -37,6 +38,7 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
/**
* Orchestrates Lambda function invocations.
@@ -176,6 +178,11 @@ public class LambdaExecutorService implements Resettable {
return invoke(fn, payload, type, 0, null, null, requestId, null, traceId);
}
public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, String requestId,
String traceId, boolean logTail) {
return invoke(fn, payload, type, 0, null, null, requestId, null, traceId, logTail);
}
/**
* Invokes {@code fn}, carrying the number of invocations that the same originating event has
* already caused. A direct invoke starts at zero; each destination delivery adds one, whether
@@ -201,6 +208,12 @@ public class LambdaExecutorService implements Resettable {
null, null);
}
InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth,
String invokedQualifier, String clientContext, boolean logTail) {
return invoke(fn, payload, type, chainDepth, invokedQualifier, clientContext, UUID.randomUUID().toString(),
null, null, logTail);
}
/**
* A synchronous invocation whose response, if the runtime streams it, goes to {@code listener}
* as it arrives rather than into the returned result.
@@ -214,6 +227,12 @@ public class LambdaExecutorService implements Resettable {
private InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth,
String invokedQualifier, String clientContext, String requestId,
ResponseStreamListener listener, String traceId) {
return invoke(fn, payload, type, chainDepth, invokedQualifier, clientContext, requestId, listener, traceId, false);
}
private InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth,
String invokedQualifier, String clientContext, String requestId,
ResponseStreamListener listener, String traceId, boolean logTail) {
if (type == InvocationType.DryRun) {
return new InvokeResult(204, null, new byte[0], null, requestId);
}
@@ -265,7 +284,7 @@ public class LambdaExecutorService implements Resettable {
}
try {
return executeSync(fn, payload, requestId, clientContext, invokedQualifier, listener, traceId);
return executeSync(fn, payload, requestId, clientContext, invokedQualifier, listener, traceId, logTail);
} finally {
permit.close();
}
@@ -321,7 +340,7 @@ public class LambdaExecutorService implements Resettable {
}
InvokeResult result;
try (permit) {
result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier(), null, null);
result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier(), null, null, false);
} catch (RuntimeException e) {
LOG.warnv("Error in async Lambda execution for {0}: {1}", event.fn().getFunctionName(), e.getMessage());
// Stops retrying, as upstream did: routes the previous attempt's result, or UnknownError when
@@ -399,7 +418,7 @@ public class LambdaExecutorService implements Resettable {
private InvokeResult executeSync(LambdaFunction fn, byte[] payload, String requestId,
String clientContext, String invokedQualifier,
ResponseStreamListener listener, String traceId) {
ResponseStreamListener listener, String traceId, boolean logTail) {
ContainerHandle handle;
try {
handle = warmPool.acquireProvisioned(fn, invokedQualifier);
@@ -423,7 +442,9 @@ public class LambdaExecutorService implements Resettable {
boolean initializing = !runtimeApiServer.hasRuntimePolled();
long dispatchWaitMs = dispatchWaitMs(fn.getTimeout(), initializing,
runtimeApiServer.getContainerStartedAtMs(), System.currentTimeMillis());
Supplier<String> logs = null;
try {
logs = beginLogTail(handle, logTail);
runtimeApiServer.enqueue(invocation);
CompletableFuture.anyOf(
@@ -431,6 +452,7 @@ public class LambdaExecutorService implements Resettable {
.get(dispatchWaitMs, TimeUnit.MILLISECONDS);
InvokeResult result = invocation.getResultFuture().get();
includeLogTail(result, handle, logs);
warmPool.release(handle);
return result;
@@ -447,10 +469,12 @@ public class LambdaExecutorService implements Resettable {
} else {
LOG.warnv("Function {0} timed out after {1}s", fn.getFunctionName(), fn.getTimeout());
}
warmPool.destroyHandle(handle);
return new InvokeResult(200, "Unhandled",
InvokeResult result = new InvokeResult(200, "Unhandled",
buildErrorPayload("Task timed out after " + fn.getTimeout() + " seconds", "Function.TimedOut"),
null, requestId);
includeLogTail(result, handle, logs);
warmPool.destroyHandle(handle);
return result;
}
LOG.warnv("Invocation error for function {0}: {1}", fn.getFunctionName(), cause.getMessage());
warmPool.destroyHandle(handle);
@@ -459,6 +483,25 @@ public class LambdaExecutorService implements Resettable {
}
}
private Supplier<String> beginLogTail(ContainerHandle handle, boolean requested) {
try {
return handle.beginInvocation(requested);
} catch (IllegalStateException | UncheckedIOException e) {
LOG.warnv(e, "Could not begin invocation log capture for function {0}", handle.getFunctionName());
return null;
}
}
private void includeLogTail(InvokeResult result, ContainerHandle handle, Supplier<String> logs) {
if (logs != null) {
try {
result.setLogResult(logs.get());
} catch (IllegalStateException | UncheckedIOException e) {
LOG.warnv(e, "Could not read invocation logs for function {0}", handle.getFunctionName());
}
}
}
/**
* How long an invocation waits for its runtime to take it. A runtime that has never polled /next
* is still in its Init phase, which runs from its container's start for the Init budget; once the
@@ -80,6 +80,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
@@ -1457,6 +1458,13 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
public InvokeResult invoke(String region, String functionName, String queryQualifier, byte[] payload,
InvocationType type, String clientContext, String durableExecutionName,
String traceHeader) {
return invoke(region, functionName, queryQualifier, payload, type, clientContext, durableExecutionName,
traceHeader, false);
}
public InvokeResult invoke(String region, String functionName, String queryQualifier, byte[] payload,
InvocationType type, String clientContext, String durableExecutionName,
String traceHeader, boolean logTail) {
validateInvokeQualifier(queryQualifier);
LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, queryQualifier);
String name = ref.name();
@@ -1471,12 +1479,15 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
}
reportCustomResourceLiveness(payload);
InvokeResult durable = invokeIfDurable(fn, region, qualifier, durableExecutionName, payload, type,
traceHeader);
traceHeader, logTail);
if (durable != null) {
return durable;
}
InvokeResult result = executorService.invoke(fn, payload, type,
LambdaInvocationChain.currentDepth(), qualifier, clientContext);
InvokeResult result = logTail
? executorService.invoke(fn, payload, type,
LambdaInvocationChain.currentDepth(), qualifier, clientContext, true)
: executorService.invoke(fn, payload, type,
LambdaInvocationChain.currentDepth(), qualifier, clientContext);
result.setExecutedVersion(fn.getVersion());
return result;
}
@@ -1484,7 +1495,7 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
/** Null for a plain function, and for a DryRun, which only checks the qualifier. */
private InvokeResult invokeIfDurable(LambdaFunction fn, String region, String qualifier,
String durableExecutionName, byte[] payload, InvocationType type,
String traceHeader) {
String traceHeader, boolean logTail) {
if (!fn.isDurable()) {
return null;
}
@@ -1495,7 +1506,7 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
if (type == InvocationType.DryRun) {
return null;
}
InvokeResult result = invokeDurable(fn, region, durableExecutionName, payload, type, traceHeader);
InvokeResult result = invokeDurable(fn, region, durableExecutionName, payload, type, traceHeader, logTail);
result.setExecutedVersion(fn.getVersion());
return result;
}
@@ -1505,7 +1516,7 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
* limit. Event answers 202 as soon as the execution exists.
*/
private InvokeResult invokeDurable(LambdaFunction fn, String region, String executionName, byte[] payload,
InvocationType type, String traceHeader) {
InvocationType type, String traceHeader, boolean logTail) {
boolean synchronous = type == InvocationType.RequestResponse;
if (synchronous && fn.getDurableExecutionTimeout() > MAX_FUNCTION_TIMEOUT_SECONDS) {
throw new AwsException("InvalidParameterValueException",
@@ -1520,23 +1531,35 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
String input = payload == null || payload.length == 0 ? "{}" : new String(payload, StandardCharsets.UTF_8);
DurableExecution execution = durableExecutionService.start(new DurableExecutionService.StartRequest(
fn.getAccountId(), region, fn.getFunctionName(), fn.getVersion(), executionName, input, synchronous,
traceHeader));
traceHeader, logTail));
String requestId = UUID.randomUUID().toString();
InvokeResult result;
if (!synchronous) {
result = new InvokeResult(202, null, new byte[0], null, requestId);
} else {
result = awaitDurableResult(execution.getExecutionArn(), requestId);
try {
result = awaitDurableResult(execution.getExecutionArn(), requestId, logTail);
} finally {
if (logTail) {
durableExecutionService.releaseInvocationLogs(execution.getExecutionArn());
}
}
}
result.setDurableExecutionArn(execution.getExecutionArn());
return result;
}
private InvokeResult awaitDurableResult(String executionArn, String requestId) {
DurableExecution finished;
private InvokeResult awaitDurableResult(String executionArn, String requestId, boolean logTail) {
try {
// A little past the limit, so an execution that times out at 900 s reports its own error.
finished = durableExecutionService.awaitCompletion(executionArn)
return durableExecutionService.awaitCompletion(executionArn)
.thenCompose(finished -> {
InvokeResult result = durableResult(finished, requestId);
return logTail ? durableExecutionService.invocationLogs(executionArn).thenApply(logs -> {
result.setLogResult(logs);
return result;
}) : CompletableFuture.completedFuture(result);
})
.get(MAX_FUNCTION_TIMEOUT_SECONDS + SYNC_DURABLE_GRACE_SECONDS, TimeUnit.SECONDS);
} catch (TimeoutException e) {
return unhandledDurableResult(DurableErrorObject.of(
@@ -1549,6 +1572,9 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
return unhandledDurableResult(DurableErrorObject.of(
e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), "InvocationError"), requestId);
}
}
private InvokeResult durableResult(DurableExecution finished, String requestId) {
if (finished.getStatus() == DurableExecutionStatus.SUCCEEDED) {
byte[] body = finished.getResult() == null ? new byte[0]
: finished.getResult().getBytes(StandardCharsets.UTF_8);
@@ -1605,7 +1631,7 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionArn);
LambdaFunction fn = targetResolver.resolveInvokeTargetForAccount(
arn.accountId(), arn.region(), ref.name(), ref.qualifier());
InvokeResult durable = invokeIfDurable(fn, arn.region(), ref.qualifier(), null, payload, type, null);
InvokeResult durable = invokeIfDurable(fn, arn.region(), ref.qualifier(), null, payload, type, null, false);
if (durable != null) {
return durable;
}
@@ -91,6 +91,7 @@ public class DurableExecutionService implements Resettable {
private final Object[] executionLocks = newLocks(LOCK_STRIPES);
private final ConcurrentHashMap<String, Object> startLocks = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, CompletableFuture<DurableExecution>> completions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, DurableInvocationLogs> logCaptures = new ConcurrentHashMap<>();
/** Moves on reset and shutdown so an invocation result from before cannot be written afterwards. */
private final AtomicLong generation = new AtomicLong();
@@ -116,7 +117,11 @@ public class DurableExecutionService implements Resettable {
public record StartRequest(String accountId, String region, String functionName, String qualifier,
String executionName, String inputPayload, boolean synchronous,
String traceHeader) {
String traceHeader, boolean logTail) {
public StartRequest(String accountId, String region, String functionName, String qualifier,
String executionName, String inputPayload, boolean synchronous, String traceHeader) {
this(accountId, region, functionName, qualifier, executionName, inputPayload, synchronous, traceHeader, false);
}
}
public record ListRequest(String accountId, String region, String functionName, String version,
@@ -158,17 +163,41 @@ public class DurableExecutionService implements Resettable {
throw new AwsException("DurableExecutionAlreadyStartedException",
"Execution already started: " + existing.get().getExecutionArn(), 409);
}
captureLogs(request, existing.get());
return existing.get();
}
long now = clock.millis();
execution = newExecution(request, target, name, now);
trigger(execution, effects);
store.putForAccount(request.accountId(), storeKey(execution), execution);
captureLogs(request, execution);
}
runEffects(effects);
return execution;
}
private void captureLogs(StartRequest request, DurableExecution execution) {
if (request.synchronous() && request.logTail()) {
logCaptures.compute(execution.getExecutionArn(), (arn, existing) -> {
DurableInvocationLogs logs = existing != null ? existing : new DurableInvocationLogs();
logs.acquire();
return logs;
});
}
}
public CompletableFuture<String> invocationLogs(String executionArn) {
DurableInvocationLogs logs = logCaptures.get(executionArn);
return logs == null ? CompletableFuture.completedFuture("") : logs.snapshot();
}
public void releaseInvocationLogs(String executionArn) {
logCaptures.computeIfPresent(executionArn, (arn, logs) -> {
logs.release();
return logs.unused() ? null : logs;
});
}
public CompletableFuture<DurableExecution> awaitCompletion(String executionArn) {
ArnParts arn = parseArn(executionArn);
synchronized (lockFor(arn)) {
@@ -523,11 +552,15 @@ public class DurableExecutionService implements Resettable {
waiter.completeExceptionally(new AwsException("ResourceNotFoundException", NOT_FOUND, 404));
}
completions.clear();
logCaptures.values().forEach(DurableInvocationLogs::cancel);
logCaptures.clear();
}
@PreDestroy
void shutdown() {
generation.incrementAndGet();
logCaptures.values().forEach(DurableInvocationLogs::cancel);
logCaptures.clear();
}
// ──────────────────────────── invocation lane ────────────────────────────
@@ -551,6 +584,8 @@ public class DurableExecutionService implements Resettable {
byte[] payload;
String traceId = null;
long startedAt;
DurableInvocationLogs logs;
String logArn;
synchronized (lockFor(accountId, key)) {
DurableExecution execution = store.getForAccount(accountId, key).orElse(null);
if (execution == null || execution.isClosed() || launchGeneration != generation.get()
@@ -575,13 +610,20 @@ public class DurableExecutionService implements Resettable {
}
// The event carries every operation, so the handler has now seen everything up to here.
execution.setSeenSequence(execution.getChangeSequence());
logArn = execution.getExecutionArn();
logs = logCaptures.get(logArn);
if (logs != null) {
logs.beginInvocation();
}
}
DurableInvocationResult result;
if (target == null) {
result = new DurableInvocationResult(null, null, "ResourceNotFoundException");
} else {
try {
result = invoker.invoke(target, payload, invocationId, traceId);
result = logs != null
? invoker.invoke(target, payload, invocationId, traceId, true)
: invoker.invoke(target, payload, invocationId, traceId);
} catch (AwsException e) {
result = new DurableInvocationResult(null, DurableWire.functionErrorPayload(
DurableErrorObject.of(e.getMessage(), e.getErrorCode())),
@@ -593,6 +635,11 @@ public class DurableExecutionService implements Resettable {
"InvocationError");
}
}
if (logs != null) {
logs.complete(result.logResult());
logCaptures.computeIfPresent(logArn, (arn, current) ->
current == logs && logs.unused() ? null : current);
}
List<Runnable> effects = new ArrayList<>();
synchronized (lockFor(accountId, key)) {
DurableExecution execution = store.getForAccount(accountId, key).orElse(null);
@@ -12,6 +12,11 @@ public interface DurableFunctionInvoker {
DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId, String traceId);
default DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId,
String traceId, boolean logTail) {
return invoke(target, payload, requestId, traceId);
}
record ResolvedDurableTarget(String accountId,
String region,
String functionName,
@@ -23,6 +28,9 @@ public interface DurableFunctionInvoker {
boolean activeTracing) {
}
record DurableInvocationResult(String requestId, byte[] payload, String functionError) {
record DurableInvocationResult(String requestId, byte[] payload, String functionError, String logResult) {
public DurableInvocationResult(String requestId, byte[] payload, String functionError) {
this(requestId, payload, functionError, null);
}
}
}
@@ -0,0 +1,50 @@
package io.floci.aws.services.lambda.durable;
import io.floci.aws.services.lambda.launcher.InvocationLogTail;
import java.util.concurrent.CompletableFuture;
/** Transient log capture shared by synchronous Tail callers attached to one durable execution. */
final class DurableInvocationLogs {
private final InvocationLogTail tail = new InvocationLogTail();
private CompletableFuture<Void> pending = CompletableFuture.completedFuture(null);
private int callers;
synchronized void acquire() {
callers++;
}
synchronized void release() {
callers--;
}
synchronized boolean unused() {
return callers == 0 && pending.isDone();
}
synchronized void beginInvocation() {
pending = new CompletableFuture<>();
}
void complete(String encodedLogs) {
CompletableFuture<Void> finished;
synchronized (this) {
tail.appendEncoded(encodedLogs);
finished = pending;
}
finished.complete(null);
}
synchronized CompletableFuture<String> snapshot() {
return pending.thenApply(ignored -> encoded());
}
private synchronized String encoded() {
return tail.encoded();
}
synchronized void cancel() {
pending.cancel(false);
}
}
@@ -41,10 +41,19 @@ public class LambdaDurableFunctionInvoker implements DurableFunctionInvoker {
@Override
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId,
String traceId) {
return invoke(target, payload, requestId, traceId, false);
}
@Override
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId,
String traceId, boolean logTail) {
LambdaFunction fn = targetResolver.resolveInvokeTargetForAccount(target.accountId(), target.region(),
target.functionName(), target.version());
InvokeResult result = RequestScopes.callAs(target.accountId(),
() -> executorService.invoke(fn, payload, InvocationType.RequestResponse, requestId, traceId));
return new DurableInvocationResult(result.getRequestId(), result.getPayload(), result.getFunctionError());
() -> logTail
? executorService.invoke(fn, payload, InvocationType.RequestResponse, requestId, traceId, true)
: executorService.invoke(fn, payload, InvocationType.RequestResponse, requestId, traceId));
return new DurableInvocationResult(result.getRequestId(), result.getPayload(), result.getFunctionError(),
result.getLogResult());
}
}
@@ -4,6 +4,9 @@ import io.floci.aws.services.lambda.model.ContainerState;
import io.floci.aws.services.lambda.runtime.RuntimeApiServer;
import java.io.Closeable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Wraps a running Lambda Docker container and its associated Runtime API server.
@@ -20,6 +23,8 @@ public class ContainerHandle {
private volatile ContainerState state;
private volatile long lastUsedMs;
private Closeable logStream;
private Function<Boolean, Supplier<String>> logTailReader = initialization -> () -> "";
private final AtomicBoolean invoked = new AtomicBoolean();
public ContainerHandle(String containerId, String functionName,
RuntimeApiServer runtimeApiServer, ContainerState state) {
@@ -60,6 +65,14 @@ public class ContainerHandle {
public Closeable getLogStream() { return logStream; }
public void setLogStream(Closeable logStream) { this.logStream = logStream; }
public void setLogTailReader(Function<Boolean, Supplier<String>> reader) { this.logTailReader = reader; }
/** The first invocation also owns the environment's initialization logs. */
public Supplier<String> beginInvocation(boolean captureLogs) {
boolean initialization = !invoked.getAndSet(true);
return captureLogs ? logTailReader.apply(initialization) : null;
}
/**
* True once an extension in this container reported an init or exit error. Real AWS treats
* both as fatal to the execution environment, so {@code WarmPool} must retire the container
@@ -516,6 +516,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
lambdaAccountId, containerId, cwLogGroup, cwLogStream,
lambdaRegion, "lambda:" + fn.getFunctionName());
handle.setLogStream(logHandle);
handle.setLogTailReader(initialization -> InvocationLogTail.captureDocker(dockerClient, handle.getContainerId(), initialization));
return handle;
} catch (RuntimeException e) {
@@ -0,0 +1,179 @@
package io.floci.aws.services.lambda.launcher;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.LogContainerCmd;
import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.Base64;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/** A byte-bounded invocation log snapshot, independent of asynchronous CloudWatch forwarding. */
public final class InvocationLogTail {
static final int LIMIT = 4096;
private final byte[] tail = new byte[LIMIT];
private int position;
private int size;
private final TimestampedParser parser = new TimestampedParser();
private Instant lastTimestamp = Instant.EPOCH;
public static Supplier<String> captureDocker(DockerClient docker, String containerId, boolean initialization) {
Instant since = initialization ? Instant.EPOCH
: dockerSnapshot(docker, containerId, Instant.EPOCH, 1).lastTimestamp().plusNanos(1);
return () -> readDocker(docker, containerId, since);
}
public static String readDocker(DockerClient docker, String containerId, Instant since) {
return dockerSnapshot(docker, containerId, since, LIMIT).encoded();
}
private static InvocationLogTail dockerSnapshot(DockerClient docker, String containerId, Instant since, int lines) {
InvocationLogTail tail = new InvocationLogTail();
Map<StreamType, TimestampedParser> parsers = new EnumMap<>(StreamType.class);
try (LogContainerCmd command = docker.logContainerCmd(containerId)
.withStdOut(true).withStdErr(true).withFollowStream(false).withTimestamps(true)
.withSince((int) Math.min(Integer.MAX_VALUE, since.getEpochSecond())).withTail(lines);
ResultCallback.Adapter<Frame> callback = new ResultCallback.Adapter<>() {
@Override
public void onNext(Frame frame) {
parsers.computeIfAbsent(frame.getStreamType(), ignored -> tail.new TimestampedParser())
.acceptFrame(frame.getPayload(), since);
}
}) {
if (!command.exec(callback).awaitCompletion(2, TimeUnit.SECONDS)) {
throw new IllegalStateException("Timed out reading Lambda invocation logs");
}
parsers.values().forEach(TimestampedParser::finish);
return tail;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted reading Lambda invocation logs", e);
} catch (IOException | DockerException e) {
throw new IllegalStateException("Could not read Lambda invocation logs", e);
}
}
public static String read(InputStream logs) throws IOException {
InvocationLogTail tail = new InvocationLogTail();
byte[] chunk = new byte[LIMIT];
int count;
while ((count = logs.read(chunk)) != -1) {
tail.append(chunk, 0, count);
}
return tail.encoded();
}
public static InvocationLogTail readTimestamped(InputStream logs, Instant since) throws IOException {
InvocationLogTail tail = new InvocationLogTail();
byte[] chunk = new byte[LIMIT];
int count;
while ((count = logs.read(chunk)) != -1) {
tail.parser.accept(chunk, 0, count, since);
}
tail.parser.finish();
return tail;
}
public Instant lastTimestamp() {
return lastTimestamp;
}
void appendTimestamped(byte[] bytes, Instant since) {
parser.accept(bytes, 0, bytes.length, since);
}
public void appendEncoded(String logs) {
if (logs != null) {
byte[] bytes = Base64.getDecoder().decode(logs);
append(bytes, 0, bytes.length);
}
}
void append(byte[] bytes, int offset, int length) {
int count = Math.min(length, LIMIT);
int start = offset + length - count;
int first = Math.min(count, LIMIT - position);
System.arraycopy(bytes, start, tail, position, first);
System.arraycopy(bytes, start + first, tail, 0, count - first);
position = (position + count) % LIMIT;
size = Math.min(LIMIT, size + count);
}
public String encoded() {
parser.finish();
byte[] bytes = new byte[size];
int start = (position - size + LIMIT) % LIMIT;
int first = Math.min(size, LIMIT - start);
System.arraycopy(tail, start, bytes, 0, first);
System.arraycopy(tail, 0, bytes, first, size - first);
return Base64.getEncoder().encodeToString(bytes);
}
private final class TimestampedParser {
private final byte[] prefix = new byte[40];
private int prefixSize;
private boolean readingPrefix = true;
private boolean include;
void acceptFrame(byte[] bytes, Instant since) {
// Docker timestamps each record, including records that continue an unterminated line.
// A prefix already in progress belongs to a transport-split record and must be retained.
readingPrefix = true;
accept(bytes, 0, bytes.length, since);
}
void accept(byte[] bytes, int offset, int length, Instant since) {
int end = offset + length;
while (offset < end) {
if (readingPrefix) {
byte next = bytes[offset++];
prefix[prefixSize++] = next;
if (next == ' ' || next == '\n' || prefixSize == prefix.length) {
try {
Instant timestamp = Instant.parse(new String(prefix, 0, prefixSize - 1, StandardCharsets.US_ASCII));
include = !timestamp.isBefore(since);
if (timestamp.isAfter(lastTimestamp)) {
lastTimestamp = timestamp;
}
} catch (DateTimeParseException expected) {
// A log record can continue without a timestamp prefix.
if (include) {
append(prefix, 0, prefixSize);
}
}
prefixSize = 0;
readingPrefix = next == '\n';
}
} else {
int next = offset;
while (next < end && bytes[next++] != '\n') {
// Append payload bytes in bulk, including any terminating newline.
}
if (include) {
append(bytes, offset, next - offset);
}
readingPrefix = bytes[next - 1] == '\n';
offset = next;
}
}
}
void finish() {
if (prefixSize > 0 && include) {
append(prefix, 0, prefixSize);
}
prefixSize = 0;
}
}
}
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.floci.aws.services.lambda.launcher.InvocationLogTail;
import jakarta.enterprise.context.ApplicationScoped;
import javax.net.ssl.KeyManager;
@@ -36,6 +37,8 @@ import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
@@ -199,9 +202,35 @@ public class KubernetesApiClient {
* underlying connection and the kubelet stops the follow.
*/
public InputStream openPodLogStream(String namespace, String podName, String containerName) {
return openPodLogs(namespace, podName, containerName, "&follow=true");
}
public String readPodLogTail(String namespace, String podName, Instant since) {
return podLogSnapshot(namespace, podName, since, 4096).encoded();
}
public Supplier<String> capturePodLogTail(String namespace, String podName, boolean initialization) {
Instant since = initialization ? Instant.EPOCH
: podLogSnapshot(namespace, podName, Instant.EPOCH, 1).lastTimestamp().plusNanos(1);
return () -> readPodLogTail(namespace, podName, since);
}
private InvocationLogTail podLogSnapshot(String namespace, String podName, Instant since, int lines) {
String options = "&follow=false&timestamps=true&tailLines=" + lines + "&sinceTime="
+ URLEncoder.encode(since.truncatedTo(ChronoUnit.SECONDS).toString(), StandardCharsets.UTF_8);
try (InputStream logs = openPodLogs(namespace, podName, "runtime", options)) {
return InvocationLogTail.readTimestamped(logs, since);
} catch (IOException e) {
throw new UncheckedIOException("Could not read invocation logs for pod " + podName, e);
} catch (KubernetesApiException e) {
throw new IllegalStateException("Could not read invocation logs for pod " + podName, e);
}
}
private InputStream openPodLogs(String namespace, String podName, String containerName, String options) {
ensureInitialized();
String path = podPath(namespace, podName) + "/log?container="
+ URLEncoder.encode(containerName, StandardCharsets.UTF_8) + "&follow=true";
+ URLEncoder.encode(containerName, StandardCharsets.UTF_8) + options;
try {
HttpResponse<InputStream> response = http.send(requestBuilder(path).GET().build(), HttpResponse.BodyHandlers.ofInputStream());
if (response.statusCode() != 200) {
@@ -226,6 +226,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
ContainerHandle handle = new ContainerHandle(podName, fn.getFunctionName(),
runtimeApiServer, ContainerState.WARM, false);
handle.setLogTailReader(initialization -> client.capturePodLogTail(namespace, handle.getContainerId(), initialization));
// Log streaming is non-essential and runs after the pod is already Running,
// so a failure here (e.g. a missing pods/log RBAC verb) must not tear down a
// healthy execution environment.