mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(lambdaweb): send what a Web Function writes to its log groups as AWS does (#5919)
* feat(lambdaweb): send what a Web Function writes to its log groups as AWS does * chore(lambdaweb): write the Web Function runtime as an ES module * fix(lambdaweb): create a log group or stream only when an event finds it missing * fix(lambdaweb): cut a log line by its UTF-8 size after replacing bytes that are not UTF-8 * test(lambdaweb): wait for the last log line instead of a fixed sleep
This commit is contained in:
1 parent
8972b21e1b
commit
8067ecf1de
9 files changed
+681
-13
No files matched your search
+53
-10
@@ -6,6 +6,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.command.WaitContainerResultCallback;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.ContainerTeardown;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
@@ -35,6 +36,7 @@ import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -46,6 +48,7 @@ import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -65,14 +68,17 @@ import java.util.stream.Stream;
|
||||
/**
|
||||
* The execution environments of Web Function endpoints: Node.js server containers of a revision,
|
||||
* started by requests that find no room, reused while requests keep coming and removed after the
|
||||
* Lambda idle timeout. The runtime loads {@code index.js}, or the file {@code AWS_LAMBDA_NODEJS_ENTRYPOINT} names,
|
||||
* from {@code /var/task} with the node flags AWS uses.
|
||||
* Lambda idle timeout. Node starts {@code /var/runtime/index.js} with the flags AWS uses, as on AWS. That runtime
|
||||
* turns console output into log events and imports {@code index.js}, or the file {@code AWS_LAMBDA_NODEJS_ENTRYPOINT}
|
||||
* names, from {@code /var/task}. What the process writes goes to the revision's log group.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
|
||||
static final int APP_PORT = 3000;
|
||||
static final String TASK_DIR = "/var/task";
|
||||
static final String RUNTIME_DIR = "/var/runtime";
|
||||
private static final String RUNTIME_RESOURCE = "lambdaweb/index.mjs";
|
||||
static final int MEMORY_MB = 2048;
|
||||
static final Duration LISTEN_TIMEOUT = Duration.ofSeconds(10);
|
||||
static final List<String> NODE_FLAGS = List.of("--expose-gc", "--max-http-header-size", "135168",
|
||||
@@ -104,6 +110,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
private volatile String host;
|
||||
private volatile int port;
|
||||
private volatile String logStream;
|
||||
private volatile LambdaWebLogs.Sink logs;
|
||||
private volatile SessionCreds roleCredentials;
|
||||
private final AtomicInteger inFlight = new AtomicInteger();
|
||||
private final AtomicLong lastUsed = new AtomicLong(System.nanoTime());
|
||||
@@ -202,6 +209,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
private final ZipExtractor zipExtractor;
|
||||
private final LaunchedContainerAwsEnv awsEnv;
|
||||
private final LambdaExecutionRoleCredentials executionRoleCredentials;
|
||||
private final LambdaWebLogs logs;
|
||||
private final byte[] runtime;
|
||||
/** The environments of each endpoint in each region. A list is only touched inside a map operation on its key. */
|
||||
private final ConcurrentHashMap<String, List<Environment>> pools = new ConcurrentHashMap<>();
|
||||
private final ScheduledExecutorService reaper = Executors.newSingleThreadScheduledExecutor(task -> {
|
||||
@@ -216,7 +225,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
@StreamingDocker DockerClient streamingDocker, ImageResolver imageResolver,
|
||||
EcrRegistryManager ecrRegistryManager, S3Service s3Service,
|
||||
ZipExtractor zipExtractor, LaunchedContainerAwsEnv awsEnv,
|
||||
LambdaExecutionRoleCredentials executionRoleCredentials) {
|
||||
LambdaExecutionRoleCredentials executionRoleCredentials, LambdaWebLogs logs) {
|
||||
this.config = config;
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
@@ -227,6 +236,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
this.zipExtractor = zipExtractor;
|
||||
this.awsEnv = awsEnv;
|
||||
this.executionRoleCredentials = executionRoleCredentials;
|
||||
this.logs = logs;
|
||||
this.runtime = runtimeScript();
|
||||
long period = Math.max(1, Math.min(30, config.services().lambda().containerIdleTimeoutSeconds() / 2 + 1));
|
||||
reaper.scheduleWithFixedDelay(this::reapIdle, period, period, TimeUnit.SECONDS);
|
||||
}
|
||||
@@ -427,7 +438,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
Map<String, String> userEnv = revision.serviceConfig.environmentVariables == null
|
||||
? Map.of() : revision.serviceConfig.environmentVariables;
|
||||
List<String> cmd = new ArrayList<>(NODE_FLAGS);
|
||||
cmd.add(userEnv.getOrDefault("AWS_LAMBDA_NODEJS_ENTRYPOINT", "index.js"));
|
||||
cmd.add(RUNTIME_DIR + "/index.js");
|
||||
Optional<SessionCreds> roleCredentials = executionRoleCredentials.forRole(
|
||||
revision.serviceConfig.executionRoleArn, accountId, fn.functionName);
|
||||
ContainerSpec spec = containerBuilder.newContainer(image)
|
||||
@@ -453,6 +464,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
}
|
||||
try {
|
||||
copyCode(containerId, accountId, region, fn, revision);
|
||||
RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, RUNTIME_DIR, "index.js",
|
||||
runtime, 0644);
|
||||
ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
|
||||
EndpointInfo endpoint = info.getEndpoint(APP_PORT);
|
||||
awaitListening(containerId);
|
||||
@@ -462,7 +475,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
environment.logStream = LOG_STREAM_DATE.format(Instant.now()) + "/" + fn.functionName + "["
|
||||
+ revision.revisionId + "]" + UUID.randomUUID().toString().replace("-", "");
|
||||
environment.roleCredentials = roleCredentials.orElse(null);
|
||||
watchExit(environment);
|
||||
environment.logs = logs.open(accountId, region, revision.serviceConfig.logGroup, environment.logStream);
|
||||
watchExit(environment, true);
|
||||
LOG.infov("Started the Lambda Web environment {0} of {1} revision {2} at {3}:{4}",
|
||||
containerId, fn.functionName, revision.revisionId, endpoint.host(), endpoint.port());
|
||||
} catch (RuntimeException e) {
|
||||
@@ -643,23 +657,34 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
/**
|
||||
* A process that exits between requests is invisible to clients: the next request starts anew.
|
||||
* The attach stream ends when the process exits, and Floci times that on its own clock. The exit
|
||||
* time Docker records comes from the daemon's clock, which can be seconds off. The output is
|
||||
* dropped here. A reader that falls behind would block the app's writes.
|
||||
* time Docker records comes from the daemon's clock, which can be seconds off. The stream also
|
||||
* carries the output, which only goes into a queue here. A reader that falls behind would block
|
||||
* the app's writes. {@code fromStart} replays what the app wrote while it started.
|
||||
*/
|
||||
private void watchExit(Environment environment) {
|
||||
private void watchExit(Environment environment, boolean fromStart) {
|
||||
Map<StreamType, LambdaWebOutputLines> streams = new EnumMap<>(StreamType.class);
|
||||
try {
|
||||
streamingDocker.attachContainerCmd(environment.containerId)
|
||||
.withStdOut(true).withStdErr(true).withFollowStream(true)
|
||||
.withStdOut(true).withStdErr(true).withFollowStream(true).withLogs(fromStart)
|
||||
.exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
LambdaWebOutputLines lines = streams.computeIfAbsent(frame.getStreamType(),
|
||||
type -> new LambdaWebOutputLines());
|
||||
lines.append(frame.getPayload()).forEach(event -> deliver(environment, event));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
super.onComplete();
|
||||
streams.values().forEach(lines -> lines.flush().forEach(event -> deliver(environment, event)));
|
||||
exited(environment, System.nanoTime());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable throwable) {
|
||||
super.onError(throwable);
|
||||
streams.values().forEach(lines -> lines.flush().forEach(event -> deliver(environment, event)));
|
||||
LOG.debugv(throwable, "The exit watch of the Lambda Web environment {0} dropped",
|
||||
environment.containerId);
|
||||
rearmExitWatch(environment);
|
||||
@@ -689,10 +714,28 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
exited(environment, System.nanoTime());
|
||||
return;
|
||||
}
|
||||
watchExit(environment);
|
||||
watchExit(environment, false);
|
||||
}, EXIT_WATCH_REARM.toMillis(), TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/** AWS writes no event for a line that is empty or only spaces. */
|
||||
private static void deliver(Environment environment, String event) {
|
||||
if (!event.isBlank()) {
|
||||
environment.logs.accept(event);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] runtimeScript() {
|
||||
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(RUNTIME_RESOURCE)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException(RUNTIME_RESOURCE + " is missing from the classpath");
|
||||
}
|
||||
return in.readAllBytes();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Could not read " + RUNTIME_RESOURCE, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The environment leaves the pool before waiters hear of the exit, so the request after a failed one starts anew. */
|
||||
private void exited(Environment environment, long seenAt) {
|
||||
boolean running = environment.alive.compareAndSet(true, false);
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Delivers the log events of Web Function environments. Each event goes to the stream of its
|
||||
* environment in the {@code .local} companion of the revision's log group, and to the same stream
|
||||
* with an {@code -<account>-<region>} suffix in the log group itself, where AWS centralizes the
|
||||
* regions an endpoint serves. A group or stream is created when its first event arrives.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaWebLogs {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LambdaWebLogs.class);
|
||||
private static final int MAX_QUEUED_EVENTS = 10_000;
|
||||
private static final int MAX_BATCH_EVENTS = 1_000;
|
||||
|
||||
private final CloudWatchLogsService logs;
|
||||
private final ExecutorService writers = Executors.newVirtualThreadPerTaskExecutor();
|
||||
|
||||
@Inject
|
||||
public LambdaWebLogs(CloudWatchLogsService logs) {
|
||||
this.logs = logs;
|
||||
}
|
||||
|
||||
public Sink open(String accountId, String region, String logGroup, String logStream) {
|
||||
return new Sink(accountId, region, List.of(
|
||||
new Destination(logGroup + ".local", logStream),
|
||||
new Destination(logGroup, logStream + "-" + accountId + "-" + region)));
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
writers.shutdownNow();
|
||||
}
|
||||
|
||||
private record Destination(String logGroup, String logStream) {
|
||||
}
|
||||
|
||||
private record Event(long timestamp, String message) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The events of one environment. {@link #accept} only queues, because the app blocks on its
|
||||
* output while the Docker stream that carries it waits. Past {@code MAX_QUEUED_EVENTS} events are dropped.
|
||||
*/
|
||||
public final class Sink {
|
||||
private final String accountId;
|
||||
private final String region;
|
||||
private final List<Destination> destinations;
|
||||
private final ConcurrentLinkedQueue<Event> queue = new ConcurrentLinkedQueue<>();
|
||||
private final AtomicInteger queued = new AtomicInteger();
|
||||
private final AtomicBoolean writing = new AtomicBoolean();
|
||||
|
||||
private Sink(String accountId, String region, List<Destination> destinations) {
|
||||
this.accountId = accountId;
|
||||
this.region = region;
|
||||
this.destinations = destinations;
|
||||
}
|
||||
|
||||
public void accept(String message) {
|
||||
if (queued.incrementAndGet() > MAX_QUEUED_EVENTS) {
|
||||
queued.decrementAndGet();
|
||||
LOG.debugv("Dropped a log event of {0}: too many are waiting", destinations.getFirst().logStream());
|
||||
return;
|
||||
}
|
||||
queue.add(new Event(System.currentTimeMillis(), message));
|
||||
schedule();
|
||||
}
|
||||
|
||||
private void schedule() {
|
||||
if (!writing.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
writers.execute(this::write);
|
||||
} catch (RuntimeException e) {
|
||||
writing.set(false);
|
||||
LOG.debugv(e, "Could not deliver the log events of {0}", destinations.getFirst().logStream());
|
||||
}
|
||||
}
|
||||
|
||||
private void write() {
|
||||
try {
|
||||
List<Map<String, Object>> batch = new ArrayList<>();
|
||||
Event event;
|
||||
while ((event = queue.poll()) != null) {
|
||||
queued.decrementAndGet();
|
||||
batch.add(Map.of("timestamp", event.timestamp(), "message", event.message()));
|
||||
if (batch.size() == MAX_BATCH_EVENTS) {
|
||||
put(batch);
|
||||
batch = new ArrayList<>();
|
||||
}
|
||||
}
|
||||
if (!batch.isEmpty()) {
|
||||
put(batch);
|
||||
}
|
||||
} finally {
|
||||
writing.set(false);
|
||||
if (!queue.isEmpty()) {
|
||||
schedule();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void put(List<Map<String, Object>> batch) {
|
||||
for (Destination destination : destinations) {
|
||||
try {
|
||||
putTo(destination, batch);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not deliver {0} log events to {1}", batch.size(), destination.logGroup());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The group and the stream are created when an event finds one of them missing, also after a delete. */
|
||||
private void putTo(Destination destination, List<Map<String, Object>> batch) {
|
||||
try {
|
||||
logs.putLogEventsForAccount(accountId, destination.logGroup(), destination.logStream(), batch, region);
|
||||
} catch (AwsException e) {
|
||||
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
createLogGroup(destination);
|
||||
createLogStream(destination);
|
||||
logs.putLogEventsForAccount(accountId, destination.logGroup(), destination.logStream(), batch, region);
|
||||
}
|
||||
}
|
||||
|
||||
private void createLogGroup(Destination destination) {
|
||||
try {
|
||||
logs.createLogGroupForAccount(accountId, destination.logGroup(), null, null, region);
|
||||
} catch (AwsException e) {
|
||||
ignoreAlreadyExists(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void createLogStream(Destination destination) {
|
||||
try {
|
||||
logs.createLogStreamForAccount(accountId, destination.logGroup(), destination.logStream(), region);
|
||||
} catch (AwsException e) {
|
||||
ignoreAlreadyExists(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ignoreAlreadyExists(AwsException e) {
|
||||
if (!"ResourceAlreadyExistsException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Cuts what one output stream of an environment writes into log events. An event keeps its
|
||||
* newline. Bytes that are not UTF-8 become U+FFFD, and a line whose text is longer than
|
||||
* {@link #MAX_EVENT_BYTES} in UTF-8 is cut before the character that would pass it, without its
|
||||
* newline, as on AWS.
|
||||
*/
|
||||
final class LambdaWebOutputLines {
|
||||
|
||||
/** The CloudWatch Logs event limit of 256 KiB less the 26 bytes it charges for each event. */
|
||||
static final int MAX_EVENT_BYTES = 262_118;
|
||||
|
||||
private final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPLACE)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPLACE);
|
||||
/** The start of a character whose other bytes come in the next payload. */
|
||||
private ByteBuffer undecoded = ByteBuffer.allocate(0);
|
||||
private final StringBuilder pending = new StringBuilder();
|
||||
private int pendingBytes;
|
||||
|
||||
List<String> append(byte[] payload) {
|
||||
ByteBuffer in = ByteBuffer.allocate(undecoded.remaining() + payload.length).put(undecoded).put(payload).flip();
|
||||
CharBuffer out = CharBuffer.allocate(in.remaining());
|
||||
decoder.decode(in, out, false);
|
||||
undecoded = ByteBuffer.allocate(in.remaining()).put(in).flip();
|
||||
return cut(out.flip());
|
||||
}
|
||||
|
||||
/** The output after the last newline, when the stream ends without one. */
|
||||
List<String> flush() {
|
||||
CharBuffer out = CharBuffer.allocate(undecoded.remaining() + 1);
|
||||
decoder.decode(undecoded, out, true);
|
||||
decoder.flush(out);
|
||||
decoder.reset();
|
||||
undecoded = ByteBuffer.allocate(0);
|
||||
List<String> events = cut(out.flip());
|
||||
if (!pending.isEmpty()) {
|
||||
events.add(take());
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
private List<String> cut(CharBuffer text) {
|
||||
List<String> events = new ArrayList<>();
|
||||
text.codePoints().forEach(codePoint -> {
|
||||
int length = utf8Length(codePoint);
|
||||
if (MAX_EVENT_BYTES < pendingBytes + length) {
|
||||
events.add(take());
|
||||
}
|
||||
pending.appendCodePoint(codePoint);
|
||||
pendingBytes += length;
|
||||
if (codePoint == '\n') {
|
||||
events.add(take());
|
||||
}
|
||||
});
|
||||
return events;
|
||||
}
|
||||
|
||||
private static int utf8Length(int codePoint) {
|
||||
if (codePoint < 0x80) {
|
||||
return 1;
|
||||
}
|
||||
if (codePoint < 0x800) {
|
||||
return 2;
|
||||
}
|
||||
return codePoint < 0x10000 ? 3 : 4;
|
||||
}
|
||||
|
||||
private String take() {
|
||||
String event = pending.toString();
|
||||
pending.setLength(0);
|
||||
pendingBytes = 0;
|
||||
return event;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user