mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(lambda): report real runtime errors instead of Function.TimedOut (#3505)
RuntimeApiServer now reports real init errors, crashed processes, and the actual FunctionError instead of Function.TimedOut, and retains the fault payload so a same-cause enqueue() rejection returns it instead of a generic ContainerStopped. * Fix #3314 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
9f9a828439
commit
34062f6383
3 files changed
+395
-19
No files matched your search
+33
@@ -19,6 +19,8 @@ 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.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.WaitResponse;
|
||||
import com.github.dockerjava.core.command.WaitContainerResultCallback;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -404,6 +406,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
|
||||
// Now start the container with code in place
|
||||
lifecycleManager.startCreated(containerId, spec);
|
||||
watchForUnexpectedExit(dockerClient, containerId, runtimeApiServer);
|
||||
|
||||
// Extensions can log as soon as they start, which is before the container's own log stream
|
||||
// is attached below. Create the group/stream up front so those early lines are not dropped
|
||||
@@ -1235,6 +1238,36 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
/** Where a container's output is sent: the CloudWatch log group/stream and its region. */
|
||||
private record LogDestination(String logGroup, String logStream, String region) { }
|
||||
|
||||
/**
|
||||
* Arms an async watch (via Docker's own wait-for-exit API, not polling) that notices when
|
||||
* this container's main process dies while nothing inside the runtime reported it - a
|
||||
* stray {@code sys.exit}/{@code process.exit}/{@code System.exit} in the handler, or any
|
||||
* other crash (see #3314). Without this, a dead runtime left every pending/in-flight
|
||||
* invocation waiting out the full function timeout to be told {@code Function.TimedOut}
|
||||
* instead of the {@code Runtime.ExitError} AWS reports immediately.
|
||||
*
|
||||
* <p>Fires exactly once per container, on whatever exit eventually happens - including an
|
||||
* intentional {@code docker stop} during normal teardown. {@link RuntimeApiServer
|
||||
* #handleRuntimeProcessExited} itself distinguishes a genuine crash from that case (its own
|
||||
* {@code stopped}/{@code faulted} guard), so this method only needs to forward the event;
|
||||
* it does not need to be un-armed on the teardown path.
|
||||
*/
|
||||
private void watchForUnexpectedExit(DockerClient dockerClient, String containerId,
|
||||
RuntimeApiServer runtimeApiServer) {
|
||||
try {
|
||||
dockerClient.waitContainerCmd(containerId).exec(new WaitContainerResultCallback() {
|
||||
@Override
|
||||
public void onNext(WaitResponse response) {
|
||||
super.onNext(response);
|
||||
Integer statusCode = response.getStatusCode();
|
||||
runtimeApiServer.handleRuntimeProcessExited(statusCode != null ? statusCode : -1);
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
LOG.debugv(e, "Could not arm exit watcher for container {0}", containerId);
|
||||
}
|
||||
}
|
||||
|
||||
private void launchExtensions(DockerClient dockerClient, String containerId, String functionName,
|
||||
RuntimeApiServer runtimeApiServer, LogDestination logDestination) {
|
||||
List<String> extensionNames = listExtensionBinaries(dockerClient, containerId, functionName);
|
||||
|
||||
+141
-19
@@ -207,6 +207,25 @@ public class RuntimeApiServer {
|
||||
// rather than aborted mid-invoke. WarmPool performs the actual teardown afterwards.
|
||||
private volatile boolean faulted;
|
||||
|
||||
/**
|
||||
* The runtime's own error payload when {@code faulted} was set by {@link #handleInitError}
|
||||
* or {@link #handleRuntimeProcessExited} - i.e. by a real runtime fault, as opposed to an
|
||||
* extension init/exit error or an intentional {@link #quiesce()}. Written under {@code lock}
|
||||
* in the same block that sets {@code faulted}, so the two are always consistent.
|
||||
*
|
||||
* <p>{@code warmPool.acquire(fn)} launches the container and only returns afterward does
|
||||
* {@code LambdaExecutorService.executeSync()} create the {@code PendingInvocation} and call
|
||||
* {@link #enqueue}, so a cold-start init error or an immediate crash can fault this server
|
||||
* before any invocation exists for {@code handleInitError}/{@code handleRuntimeProcessExited}
|
||||
* to strand. Retaining the payload here lets a later {@link #enqueue} rejection return the
|
||||
* runtime's actual reported error instead of the generic {@link #CONTAINER_STOPPED_PAYLOAD}.
|
||||
*
|
||||
* <p>Left {@code null} for a fault raised by {@link #handleExtensionFatalError} and for a
|
||||
* plain {@code quiesce()} with no fault, both of which should keep returning
|
||||
* {@code CONTAINER_STOPPED_PAYLOAD} on a later {@code enqueue} rejection.
|
||||
*/
|
||||
private volatile byte[] fatalRuntimeErrorPayload;
|
||||
|
||||
// Init-readiness barrier. ContainerLauncher launches extension binaries as detached `docker
|
||||
// exec`s and returns immediately, so without this the first invocation can reach the runtime
|
||||
// before an extension is ready — the adapter never sees that invoke and silently misses it.
|
||||
@@ -384,25 +403,9 @@ public class RuntimeApiServer {
|
||||
sendStatusOk(ctx);
|
||||
});
|
||||
|
||||
// POST /runtime/invocation/{requestId}/error — failure
|
||||
router.post(ERROR_PATH).handler(ctx -> {
|
||||
String requestId = ctx.pathParam("requestId");
|
||||
PendingInvocation invocation = inFlight.remove(requestId);
|
||||
if (invocation != null) {
|
||||
byte[] payload = ctx.body().buffer() != null ? ctx.body().buffer().getBytes() : new byte[0];
|
||||
String errorType = ctx.request().getHeader("Lambda-Runtime-Function-Error-Type");
|
||||
String functionError = errorType != null && errorType.contains("Runtime") ? "Unhandled" : "Handled";
|
||||
InvokeResult result = new InvokeResult(200, functionError, payload, null, requestId);
|
||||
invocation.getResultFuture().complete(result);
|
||||
}
|
||||
sendStatusOk(ctx);
|
||||
});
|
||||
router.post(ERROR_PATH).handler(this::handleInvocationError);
|
||||
|
||||
// POST /runtime/init/error — runtime initialization failure
|
||||
router.post(INIT_ERROR_PATH).handler(ctx -> {
|
||||
LOG.warnv("Lambda runtime reported init error on port {0}", String.valueOf(port));
|
||||
sendStatusOk(ctx);
|
||||
});
|
||||
router.post(INIT_ERROR_PATH).handler(this::handleInitError);
|
||||
|
||||
// POST /extension/register — an extension process (e.g. aws-lambda-web-adapter)
|
||||
// registers to receive lifecycle events. Real AWS requires the Lambda-Extension-Name
|
||||
@@ -772,6 +775,7 @@ public class RuntimeApiServer {
|
||||
|
||||
public CompletableFuture<InvokeResult> enqueue(PendingInvocation invocation) {
|
||||
boolean rejected;
|
||||
byte[] rejectionPayload = null;
|
||||
RoutingContext waitingCtxForInvocation = null;
|
||||
|
||||
synchronized (lock) {
|
||||
@@ -781,6 +785,12 @@ public class RuntimeApiServer {
|
||||
// failing fast. Read inside the lock alongside `stopped` so the accept/reject decision
|
||||
// stays a single atomic step.
|
||||
rejected = stopped || faulted;
|
||||
if (rejected && faulted) {
|
||||
// A genuine runtime fault (init error or process exit) beats plain `stopped`: the
|
||||
// caller gets the runtime's actual reported error rather than the generic
|
||||
// CONTAINER_STOPPED_PAYLOAD used for an unfaulted, intentional quiesce().
|
||||
rejectionPayload = fatalRuntimeErrorPayload;
|
||||
}
|
||||
if (!rejected) {
|
||||
waitingCtxForInvocation = waitingContexts.poll();
|
||||
if (waitingCtxForInvocation == null) {
|
||||
@@ -795,8 +805,9 @@ public class RuntimeApiServer {
|
||||
}
|
||||
|
||||
if (rejected) {
|
||||
byte[] payload = rejectionPayload != null ? rejectionPayload : CONTAINER_STOPPED_PAYLOAD;
|
||||
invocation.getResultFuture().complete(
|
||||
new InvokeResult(200, "Unhandled", CONTAINER_STOPPED_PAYLOAD, null, invocation.getRequestId()));
|
||||
new InvokeResult(200, "Unhandled", payload, null, invocation.getRequestId()));
|
||||
return invocation.getResultFuture();
|
||||
}
|
||||
|
||||
@@ -859,6 +870,62 @@ public class RuntimeApiServer {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles {@code POST /runtime/invocation/{requestId}/error}: the runtime reports that the
|
||||
* handler itself failed (an uncaught exception, {@code callback(err)}, a response Lambda
|
||||
* could not marshal, ...).
|
||||
*
|
||||
* <p>Always completes with {@code FunctionError: Unhandled} - real AWS reports that for
|
||||
* every one of these regardless of runtime or error shape. The {@code
|
||||
* Lambda-Runtime-Function-Error-Type} header this used to be keyed on does not decide it
|
||||
* (see #3314): the Python and Node.js RICs don't even send that header on this path, and
|
||||
* the Java RIC's own vocabulary ({@code Runtime.UserException}, {@code
|
||||
* Runtime.BadFunctionCode}) is coincidentally what an earlier, narrower
|
||||
* {@code contains("Runtime")} heuristic here keyed on. {@code Handled} is a legacy value
|
||||
* current runtimes never produce.
|
||||
*/
|
||||
private void handleInvocationError(RoutingContext ctx) {
|
||||
String requestId = ctx.pathParam("requestId");
|
||||
PendingInvocation invocation = inFlight.remove(requestId);
|
||||
if (invocation != null) {
|
||||
byte[] payload = ctx.body().buffer() != null ? ctx.body().buffer().getBytes() : new byte[0];
|
||||
invocation.getResultFuture().complete(new InvokeResult(200, "Unhandled", payload, null, requestId));
|
||||
}
|
||||
sendStatusOk(ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles {@code POST /runtime/init/error}: the runtime reports a failed initialization
|
||||
* (module not importable, handler missing, a syntax error, an exception raised at import
|
||||
* time) and exits without ever calling {@code NEXT_PATH}. There is therefore no in-flight
|
||||
* invocation to fail - the one that triggered this cold start is still sitting in {@code
|
||||
* pendingQueue} - and the environment is condemned the same way an extension init/exit
|
||||
* error condemns it (see {@link #faulted}'s doc): the runtime process is gone, so nothing
|
||||
* will ever answer a {@code /next} poll on this container again.
|
||||
*/
|
||||
private void handleInitError(RoutingContext ctx) {
|
||||
byte[] payload = ctx.body().buffer() != null ? ctx.body().buffer().getBytes() : new byte[0];
|
||||
LOG.warnv("Lambda runtime reported init error on port {0}", String.valueOf(port));
|
||||
|
||||
List<PendingInvocation> stranded;
|
||||
synchronized (lock) {
|
||||
faulted = true;
|
||||
// Retained for a possible later enqueue(): the invocation that triggered this cold
|
||||
// start may not exist yet (see fatalRuntimeErrorPayload's doc), in which case
|
||||
// `stranded` below is empty and this is the only place the real error survives.
|
||||
fatalRuntimeErrorPayload = payload;
|
||||
stranded = new ArrayList<>(pendingQueue);
|
||||
pendingQueue.clear();
|
||||
stranded.addAll(inFlight.values());
|
||||
inFlight.clear();
|
||||
}
|
||||
for (PendingInvocation invocation : stranded) {
|
||||
invocation.getResultFuture().complete(
|
||||
new InvokeResult(200, "Unhandled", payload, null, invocation.getRequestId()));
|
||||
}
|
||||
sendStatusOk(ctx);
|
||||
}
|
||||
|
||||
private void sendStatusOk(RoutingContext ctx) {
|
||||
ctx.response()
|
||||
.setStatusCode(202)
|
||||
@@ -942,6 +1009,61 @@ public class RuntimeApiServer {
|
||||
+ "init/exit error\"}");
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by {@code ContainerLauncher}'s Docker exit watcher when the container's main
|
||||
* process has died - a stray {@code sys.exit}/{@code process.exit}/{@code System.exit} in
|
||||
* the handler, or any other crash - detected from outside the runtime, since a dead
|
||||
* process obviously cannot report anything itself through {@code /runtime/invocation/
|
||||
* {id}/error}. Without this, a crash left every pending/in-flight invocation waiting out
|
||||
* the full function timeout to be told {@code Function.TimedOut}, instead of the real
|
||||
* {@code Runtime.ExitError} AWS reports immediately (see #3314).
|
||||
*
|
||||
* <p>Condemns the environment like an extension init/exit error or a runtime init error
|
||||
* does: this container must never be pooled or reused, its main process is gone.
|
||||
*
|
||||
* <p>A no-op when {@code stopped} or already {@code faulted}: an intentional teardown
|
||||
* calls {@code quiesce()} (which sets {@code stopped}) before the container is actually
|
||||
* stopped/removed, so the exit event this same teardown causes must not be reinterpreted
|
||||
* as a crash.
|
||||
*/
|
||||
public void handleRuntimeProcessExited(int exitCode) {
|
||||
List<PendingInvocation> stranded;
|
||||
synchronized (lock) {
|
||||
if (stopped || faulted) {
|
||||
return;
|
||||
}
|
||||
faulted = true;
|
||||
// Retained for a possible later enqueue(): the invocation that would have hit this
|
||||
// container may not exist yet (see fatalRuntimeErrorPayload's doc), so this generic,
|
||||
// requestId-free payload is built here rather than only per-stranded-invocation below.
|
||||
fatalRuntimeErrorPayload = buildRuntimeExitErrorPayload(
|
||||
"Runtime exited with error: exit status " + exitCode);
|
||||
stranded = new ArrayList<>(pendingQueue);
|
||||
pendingQueue.clear();
|
||||
stranded.addAll(inFlight.values());
|
||||
inFlight.clear();
|
||||
}
|
||||
if (!stranded.isEmpty()) {
|
||||
LOG.warnv("Lambda runtime process on port {0} exited unexpectedly (status {1}) "
|
||||
+ "with {2} invocation(s) pending",
|
||||
String.valueOf(port), String.valueOf(exitCode), String.valueOf(stranded.size()));
|
||||
}
|
||||
for (PendingInvocation invocation : stranded) {
|
||||
String message = "RequestId: " + invocation.getRequestId()
|
||||
+ " Error: Runtime exited with error: exit status " + exitCode;
|
||||
invocation.getResultFuture().complete(new InvokeResult(
|
||||
200, "Unhandled", buildRuntimeExitErrorPayload(message), null, invocation.getRequestId()));
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] buildRuntimeExitErrorPayload(String message) {
|
||||
return new JsonObject()
|
||||
.put("errorType", "Runtime.ExitError")
|
||||
.put("errorMessage", message)
|
||||
.encode()
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private void handleExtensionFatalError(RoutingContext ctx, String phase) {
|
||||
String identifier = ctx.request().getHeader(EXTENSION_ID_HEADER);
|
||||
String errorType = ctx.request().getHeader(EXTENSION_ERROR_TYPE_HEADER);
|
||||
|
||||
Reference in new issue
Block a user