mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(lambdaweb): publish the Web Function metrics (#5976)
* feat(lambdaweb): publish the Web Function metrics to CloudWatch AWS counts a request that reached an environment in ExecutedRequests, also one answered with Runtime.OriginRequestError or Runtime.RequestTimeout. The status classes count the platform pages too, except the 400, 404 and 505 pages. Each environment has a datapoint at init, also a failed one, then one each minute and one when it ends. * fix(lambdaweb): bound the waiting metric writes and store them before shutdown * fix(lambdaweb): report each answer before it goes out and build datapoints with MetricDatum.of A test can then wait for the publisher once and read the metrics without polling. RDS and SES build their datapoints with the same factory. * fix(lambdaweb): wait for the metric writes even when their queue is full The wait now takes the last accepted write instead of a slot in the queue. The writes run one at a time in order, so once it is done all are. Only PutMetricData stores a zero timestamp as the current time, so the MetricDatum.of comment says so.
This commit is contained in:
1 parent
e06013e1fe
commit
6e5b1569fe
13 files changed
+608
-41
No files matched your search
+15
@@ -23,6 +23,21 @@ public class MetricDatum {
|
||||
|
||||
public MetricDatum() {}
|
||||
|
||||
/**
|
||||
* One value as a service publishes it. Only {@code putMetricData} turns a {@code timestamp} of 0
|
||||
* into the time it is stored.
|
||||
*/
|
||||
public static MetricDatum of(String metricName, String unit, double value, List<Dimension> dimensions,
|
||||
long timestamp) {
|
||||
MetricDatum datum = new MetricDatum();
|
||||
datum.setMetricName(metricName);
|
||||
datum.setUnit(unit);
|
||||
datum.setValue(value);
|
||||
datum.setDimensions(dimensions);
|
||||
datum.setTimestamp(timestamp);
|
||||
return datum;
|
||||
}
|
||||
|
||||
public String getNamespace() { return namespace; }
|
||||
public void setNamespace(String namespace) { this.namespace = namespace; }
|
||||
|
||||
|
||||
+30
-13
@@ -73,6 +73,7 @@ public class LambdaWebDataPlane {
|
||||
private final LambdaWebService service;
|
||||
private final LambdaWebEnvironmentManager environments;
|
||||
private final LambdaWebIamAuth iamAuth;
|
||||
private final LambdaWebMetrics metrics;
|
||||
private final ServiceConfigAccess serviceConfigAccess;
|
||||
private final Vertx vertx;
|
||||
private final HttpClient client;
|
||||
@@ -80,10 +81,12 @@ public class LambdaWebDataPlane {
|
||||
|
||||
@Inject
|
||||
public LambdaWebDataPlane(LambdaWebService service, LambdaWebEnvironmentManager environments,
|
||||
LambdaWebIamAuth iamAuth, ServiceConfigAccess serviceConfigAccess, Vertx vertx) {
|
||||
LambdaWebIamAuth iamAuth, LambdaWebMetrics metrics,
|
||||
ServiceConfigAccess serviceConfigAccess, Vertx vertx) {
|
||||
this.service = service;
|
||||
this.environments = environments;
|
||||
this.iamAuth = iamAuth;
|
||||
this.metrics = metrics;
|
||||
this.serviceConfigAccess = serviceConfigAccess;
|
||||
this.vertx = vertx;
|
||||
this.client = vertx.createHttpClient(new HttpClientOptions()
|
||||
@@ -120,6 +123,7 @@ public class LambdaWebDataPlane {
|
||||
WebFunctionTarget target = located.get();
|
||||
Integer rateLimit = target.endpoint().throttleConfig == null ? null : target.endpoint().throttleConfig.rateLimit;
|
||||
if (Integer.valueOf(0).equals(rateLimit)) {
|
||||
metrics.answered(target, LambdaWebErrorPages.ENDPOINT_DISABLED.status());
|
||||
page(request, LambdaWebErrorPages.ENDPOINT_DISABLED, requestId, false);
|
||||
return;
|
||||
}
|
||||
@@ -138,9 +142,11 @@ public class LambdaWebDataPlane {
|
||||
request.resume();
|
||||
if (allowed.failed()) {
|
||||
LOG.errorv(allowed.cause(), "Could not check the caller of {0}", host);
|
||||
metrics.answered(target, 502);
|
||||
internalError(request, requestId);
|
||||
return;
|
||||
}
|
||||
metrics.answered(target, LambdaWebErrorPages.FORBIDDEN.status());
|
||||
page(request, LambdaWebErrorPages.FORBIDDEN, requestId, false);
|
||||
});
|
||||
}
|
||||
@@ -149,12 +155,14 @@ public class LambdaWebDataPlane {
|
||||
Integer rateLimit = target.endpoint().throttleConfig == null ? null : target.endpoint().throttleConfig.rateLimit;
|
||||
if (rateLimit != null && !rateLimiter.tryAcquire(endpointKey(target), rateLimit)) {
|
||||
request.resume();
|
||||
metrics.throttled(target, LambdaWebMetrics.REQUEST_THROTTLES);
|
||||
page(request, LambdaWebErrorPages.ENDPOINT_REQUEST_THROTTLE, requestId, false);
|
||||
return;
|
||||
}
|
||||
WebFunctionRevision revision = LambdaWebService.pickRevision(target);
|
||||
if (revision == null) {
|
||||
request.resume();
|
||||
metrics.answered(target, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR.status());
|
||||
page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);
|
||||
return;
|
||||
}
|
||||
@@ -186,14 +194,17 @@ public class LambdaWebDataPlane {
|
||||
.onFailure(error -> {
|
||||
request.resume();
|
||||
if (error instanceof StartFailure failure) {
|
||||
metrics.answered(target, failure.page().status());
|
||||
page(request, failure.page(), requestId, false);
|
||||
return;
|
||||
}
|
||||
if (error instanceof Throttled) {
|
||||
metrics.throttled(target, LambdaWebMetrics.ACTIVE_ENVIRONMENT_THROTTLES);
|
||||
page(request, LambdaWebErrorPages.ENDPOINT_MAX_ENV_THROTTLE, requestId, false);
|
||||
return;
|
||||
}
|
||||
LOG.errorv(error, "Could not start an environment for {0}", host);
|
||||
metrics.answered(target, 502);
|
||||
internalError(request, requestId);
|
||||
});
|
||||
}
|
||||
@@ -206,7 +217,7 @@ public class LambdaWebDataPlane {
|
||||
private void forward(HttpServerRequest request, String host, WebFunctionTarget target,
|
||||
WebFunctionRevision revision, Environment environment, String requestId, boolean firstTry) {
|
||||
long started = System.nanoTime();
|
||||
Exchange exchange = new Exchange(request, environment, requestId, target.endpoint().endpointName, started);
|
||||
Exchange exchange = new Exchange(request, environment, requestId, target, started);
|
||||
boolean hasBody = hasRequestBody(request);
|
||||
AtomicBoolean bodyIn = new AtomicBoolean(!hasBody);
|
||||
AtomicBoolean expired = new AtomicBoolean();
|
||||
@@ -224,11 +235,11 @@ public class LambdaWebDataPlane {
|
||||
if (exchange.finish()) {
|
||||
upstream.reset();
|
||||
if (request.response().headWritten()) {
|
||||
request.response().close();
|
||||
exchange.relayed(LambdaWebErrorPages.REQUEST_TIMEOUT.errorType());
|
||||
request.response().close();
|
||||
} else {
|
||||
page(request, LambdaWebErrorPages.REQUEST_TIMEOUT, requestId, false);
|
||||
exchange.replaced(LambdaWebErrorPages.REQUEST_TIMEOUT);
|
||||
page(request, LambdaWebErrorPages.REQUEST_TIMEOUT, requestId, false);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -252,8 +263,8 @@ public class LambdaWebDataPlane {
|
||||
environment.containerId(), requestId, error.toString());
|
||||
if (request.response().headWritten()) {
|
||||
if (exchange.finish()) {
|
||||
request.response().close();
|
||||
exchange.relayed(null);
|
||||
request.response().close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -289,8 +300,8 @@ public class LambdaWebDataPlane {
|
||||
return;
|
||||
}
|
||||
request.resume();
|
||||
page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);
|
||||
exchange.replaced(LambdaWebErrorPages.ORIGIN_REQUEST_ERROR);
|
||||
page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -306,58 +317,64 @@ public class LambdaWebDataPlane {
|
||||
if (response.getHeader("Content-Length") == null && hasBody(request.method(), response.statusCode())) {
|
||||
out.setChunked(true);
|
||||
}
|
||||
response.pipeTo(out).onComplete(piped -> {
|
||||
response.pipe().endOnSuccess(false).to(out).onComplete(piped -> {
|
||||
if (!exchange.finish()) {
|
||||
return;
|
||||
}
|
||||
if (piped.succeeded()) {
|
||||
exchange.relayed(null);
|
||||
out.end();
|
||||
return;
|
||||
}
|
||||
if (out.headWritten()) {
|
||||
out.close();
|
||||
exchange.relayed(null);
|
||||
out.close();
|
||||
} else {
|
||||
page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);
|
||||
exchange.replaced(LambdaWebErrorPages.ORIGIN_REQUEST_ERROR);
|
||||
page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* One request against one environment. The first finisher releases the reservation and the deadline, and reports
|
||||
* the request in {@code platform.requestComplete}.
|
||||
* the request in {@code platform.requestComplete} and the request metrics. Every answer is reported before its
|
||||
* last bytes go out, so a client that has the answer finds its metrics queued.
|
||||
*/
|
||||
private final class Exchange {
|
||||
private final HttpServerRequest request;
|
||||
private final Environment environment;
|
||||
private final String requestId;
|
||||
private final WebFunctionTarget target;
|
||||
private final String endpointName;
|
||||
private final long started;
|
||||
private final AtomicBoolean finished = new AtomicBoolean();
|
||||
private long deadline = -1;
|
||||
|
||||
Exchange(HttpServerRequest request, Environment environment, String requestId, String endpointName,
|
||||
Exchange(HttpServerRequest request, Environment environment, String requestId, WebFunctionTarget target,
|
||||
long started) {
|
||||
this.request = request;
|
||||
this.environment = environment;
|
||||
this.requestId = requestId;
|
||||
this.endpointName = endpointName;
|
||||
this.target = target;
|
||||
this.endpointName = target.endpoint().endpointName;
|
||||
this.started = started;
|
||||
environment.exchangeOpened();
|
||||
}
|
||||
|
||||
/** The answer of the app, cut when {@code errorType} is set. */
|
||||
/** The answer of the app, cut when {@code errorType} is set. A cut answer counts under its first status. */
|
||||
void relayed(String errorType) {
|
||||
HttpServerResponse response = request.response();
|
||||
environment.requestComplete(requestId, endpointName, response.getStatusCode(), errorType,
|
||||
System.nanoTime() - started, response.bytesWritten());
|
||||
metrics.executed(target, response.getStatusCode(), environments.environmentCount(endpointKey(target)));
|
||||
}
|
||||
|
||||
/** A page in place of the app's answer. AWS counts none of its bytes. */
|
||||
void replaced(LambdaWebErrorPages.Page page) {
|
||||
environment.requestComplete(requestId, endpointName, page.status(), page.errorType(),
|
||||
System.nanoTime() - started, 0);
|
||||
metrics.executed(target, page.status(), environments.environmentCount(endpointKey(target)));
|
||||
}
|
||||
|
||||
boolean finish() {
|
||||
|
||||
+18
-2
@@ -107,6 +107,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
private static final int INIT_ERROR_MAX_BYTES = 64;
|
||||
/** Longer than the data plane waits to see an exit, so a request the exit failed is counted. */
|
||||
private static final Duration EXCHANGES_WAIT = Duration.ofSeconds(2);
|
||||
private static final Duration METRICS_WAIT = Duration.ofSeconds(5);
|
||||
|
||||
/**
|
||||
* One container of an endpoint's pool. It joins the pool before it starts, so requests that
|
||||
@@ -265,6 +266,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
private final LaunchedContainerAwsEnv awsEnv;
|
||||
private final LambdaExecutionRoleCredentials executionRoleCredentials;
|
||||
private final LambdaWebLogs logs;
|
||||
private final LambdaWebMetrics metrics;
|
||||
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<>();
|
||||
@@ -280,7 +282,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
@StreamingDocker DockerClient streamingDocker, ImageResolver imageResolver,
|
||||
EcrRegistryManager ecrRegistryManager, S3Service s3Service,
|
||||
ZipExtractor zipExtractor, LaunchedContainerAwsEnv awsEnv,
|
||||
LambdaExecutionRoleCredentials executionRoleCredentials, LambdaWebLogs logs) {
|
||||
LambdaExecutionRoleCredentials executionRoleCredentials, LambdaWebLogs logs,
|
||||
LambdaWebMetrics metrics) {
|
||||
this.config = config;
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
@@ -292,6 +295,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
this.awsEnv = awsEnv;
|
||||
this.executionRoleCredentials = executionRoleCredentials;
|
||||
this.logs = logs;
|
||||
this.metrics = metrics;
|
||||
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);
|
||||
@@ -370,6 +374,16 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
return new Pick(started, true, retired);
|
||||
}
|
||||
|
||||
/** The live environments of the endpoint, also those that are starting. */
|
||||
int environmentCount(String endpointKey) {
|
||||
AtomicInteger count = new AtomicInteger();
|
||||
pools.computeIfPresent(endpointKey, (key, pool) -> {
|
||||
count.set((int) pool.stream().filter(Environment::isAlive).count());
|
||||
return pool;
|
||||
});
|
||||
return count.get();
|
||||
}
|
||||
|
||||
private static boolean isIdle(Environment environment, long idleNanos) {
|
||||
return environment.isAlive() && environment.isReady() && environment.inFlight.get() == 0
|
||||
&& System.nanoTime() - environment.lastUsed.get() >= idleNanos;
|
||||
@@ -476,6 +490,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
@Override
|
||||
public void stopManagedContainers() {
|
||||
allEnvironments().forEach(this::discard);
|
||||
metrics.awaitPublished(METRICS_WAIT);
|
||||
}
|
||||
|
||||
/** The live environment that writes {@code logStream}, the one a response names. */
|
||||
@@ -569,7 +584,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
|
||||
environment.logs = logs.open(accountId, region, revision.serviceConfig.logGroup, environment.logStream,
|
||||
revision.serviceConfig.systemLogLevel);
|
||||
platform = new LambdaWebPlatformLog(environment.logs, region, fn.functionName, revision.revisionId,
|
||||
revision.buildConfig.runtime, revision.serviceConfig.applicationLogLevel);
|
||||
revision.buildConfig.runtime, revision.serviceConfig.applicationLogLevel,
|
||||
metrics.environment(accountId, region, fn.functionName));
|
||||
environment.platformLog = platform;
|
||||
ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
|
||||
platform.initStart();
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService.WebFunctionTarget;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The CloudWatch metrics of Web Functions: one datapoint per request when it is answered, and one
|
||||
* per environment when it starts, each minute and when it ends. Floci serves an endpoint in its
|
||||
* home region only, so both namespaces go there.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaWebMetrics {
|
||||
|
||||
static final String NAMESPACE = "AWS/Lambda/Web";
|
||||
static final String USAGE_NAMESPACE = "AWS/Lambda/Web/Usage";
|
||||
static final String REQUEST_THROTTLES = "EndpointRequestThrottles";
|
||||
static final String ACTIVE_ENVIRONMENT_THROTTLES = "EndpointActiveEnvironmentThrottles";
|
||||
static final int MAX_QUEUED = 10_000;
|
||||
private static final Logger LOG = Logger.getLogger(LambdaWebMetrics.class);
|
||||
|
||||
/** One datapoint of each environment metric, for the time since the previous one. */
|
||||
interface EnvironmentMetrics {
|
||||
void publish(long activeMillis, long cpuMillis, long maxMemoryMb, int concurrentRequests, long responseBytes);
|
||||
}
|
||||
|
||||
private record Datapoint(String namespace, MetricDatum datum) {
|
||||
}
|
||||
|
||||
private final CloudWatchMetricsService cloudWatch;
|
||||
/**
|
||||
* A persistent store writes to disk on each datapoint, which must not happen on the event loop.
|
||||
* The datapoints of one request or one window are one write. Once {@code maxQueued} writes wait,
|
||||
* new ones are dropped.
|
||||
*/
|
||||
private final ThreadPoolExecutor publisher;
|
||||
/** The writes run one at a time in order, so once the last one is done all are. */
|
||||
private Future<?> lastWrite = CompletableFuture.completedFuture(null);
|
||||
private boolean dropping;
|
||||
|
||||
@Inject
|
||||
public LambdaWebMetrics(CloudWatchMetricsService cloudWatch) {
|
||||
this(cloudWatch, MAX_QUEUED);
|
||||
}
|
||||
|
||||
LambdaWebMetrics(CloudWatchMetricsService cloudWatch, int maxQueued) {
|
||||
this.cloudWatch = cloudWatch;
|
||||
this.publisher = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(maxQueued),
|
||||
task -> {
|
||||
Thread thread = new Thread(task, "lambda-web-metrics");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
}
|
||||
|
||||
/** A request that reached an environment, with the status the caller got. */
|
||||
void executed(WebFunctionTarget target, int status, int activeEnvironments) {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
List<Dimension> request = requestDimensions(target);
|
||||
List<Dimension> usage = usageDimensions(target);
|
||||
List<Datapoint> datapoints = new ArrayList<>();
|
||||
datapoints.add(new Datapoint(NAMESPACE, MetricDatum.of("ExecutedRequests", "Count", 1, request, now)));
|
||||
datapoints.add(new Datapoint(USAGE_NAMESPACE, MetricDatum.of("ExecutedRequests", "Count", 1, usage, now)));
|
||||
datapoints.add(new Datapoint(USAGE_NAMESPACE,
|
||||
MetricDatum.of("EndpointActiveEnvironments", "Count", activeEnvironments, usage, now)));
|
||||
statusClass(datapoints, status, request, now);
|
||||
publish(target.accountId(), target.region(), datapoints);
|
||||
}
|
||||
|
||||
/** A request the platform answered without an environment. */
|
||||
void answered(WebFunctionTarget target, int status) {
|
||||
List<Datapoint> datapoints = new ArrayList<>();
|
||||
statusClass(datapoints, status, requestDimensions(target), Instant.now().getEpochSecond());
|
||||
publish(target.accountId(), target.region(), datapoints);
|
||||
}
|
||||
|
||||
/** A request refused with 429. {@code metric} names the limit it hit. */
|
||||
void throttled(WebFunctionTarget target, String metric) {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
List<Datapoint> datapoints = new ArrayList<>();
|
||||
datapoints.add(new Datapoint(USAGE_NAMESPACE,
|
||||
MetricDatum.of(metric, "Count", 1, usageDimensions(target), now)));
|
||||
statusClass(datapoints, 429, requestDimensions(target), now);
|
||||
publish(target.accountId(), target.region(), datapoints);
|
||||
}
|
||||
|
||||
EnvironmentMetrics environment(String accountId, String region, String functionName) {
|
||||
List<Dimension> dimensions = List.of(new Dimension("FunctionName", functionName));
|
||||
return (activeMillis, cpuMillis, maxMemoryMb, concurrentRequests, responseBytes) -> {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
publish(accountId, region, Stream.of(
|
||||
MetricDatum.of("EnvironmentActiveTime", "Milliseconds", activeMillis, dimensions, now),
|
||||
MetricDatum.of("EnvironmentCPUTime", "Milliseconds", cpuMillis, dimensions, now),
|
||||
MetricDatum.of("EnvironmentMaxMemoryUsage", "Megabytes", maxMemoryMb, dimensions, now),
|
||||
MetricDatum.of("EnvironmentConcurrentRequests", "Count", concurrentRequests, dimensions, now),
|
||||
MetricDatum.of("ResponseBytes", "Bytes", responseBytes, dimensions, now))
|
||||
.map(datum -> new Datapoint(NAMESPACE, datum)).toList());
|
||||
};
|
||||
}
|
||||
|
||||
/** Waits until what is queued is stored, so the last flush of the store at shutdown has it. */
|
||||
void awaitPublished(Duration limit) {
|
||||
Future<?> last;
|
||||
synchronized (this) {
|
||||
last = lastWrite;
|
||||
}
|
||||
try {
|
||||
last.get(limit.toMillis(), TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
LOG.warnv(e, "Lambda Web metrics still waiting to be stored may be lost");
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
publisher.shutdown();
|
||||
}
|
||||
|
||||
/** The status classes have no datapoint of 0. */
|
||||
private static void statusClass(List<Datapoint> datapoints, int status, List<Dimension> dimensions, long now) {
|
||||
if (400 <= status && status <= 499) {
|
||||
datapoints.add(new Datapoint(NAMESPACE,
|
||||
MetricDatum.of("HTTPResponseStatusClass4XX", "Count", 1, dimensions, now)));
|
||||
} else if (500 <= status && status <= 599) {
|
||||
datapoints.add(new Datapoint(NAMESPACE,
|
||||
MetricDatum.of("HTTPResponseStatusClass5XX", "Count", 1, dimensions, now)));
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Dimension> requestDimensions(WebFunctionTarget target) {
|
||||
return List.of(new Dimension("FunctionName", target.function().functionName),
|
||||
new Dimension("EndpointName", target.endpoint().endpointName));
|
||||
}
|
||||
|
||||
private static List<Dimension> usageDimensions(WebFunctionTarget target) {
|
||||
return List.of(new Dimension("FunctionName", target.function().functionName),
|
||||
new Dimension("EndpointName", target.endpoint().endpointName),
|
||||
new Dimension("ExecutionRegion", target.region()));
|
||||
}
|
||||
|
||||
private synchronized void publish(String accountId, String region, List<Datapoint> datapoints) {
|
||||
if (datapoints.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
lastWrite = publisher.submit(() -> {
|
||||
for (Datapoint datapoint : datapoints) {
|
||||
store(accountId, region, datapoint);
|
||||
}
|
||||
});
|
||||
dropping = false;
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
if (!publisher.isShutdown() && !dropping) {
|
||||
dropping = true;
|
||||
LOG.warnv("Dropping Lambda Web metrics while {0} writes wait", publisher.getQueue().size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void store(String accountId, String region, Datapoint datapoint) {
|
||||
try {
|
||||
cloudWatch.publishMetricForAccount(accountId, datapoint.namespace(), datapoint.datum(), region,
|
||||
UUID.randomUUID().toString());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not publish {0} {1} in {2}", datapoint.namespace(), datapoint.datum().getMetricName(),
|
||||
region);
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-6
@@ -6,15 +6,17 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* The {@code platform.*} events of one environment. AWS reports the CPU time and the peak memory of
|
||||
* the whole environment, which Floci reads from the container's cgroup. A reading that fails keeps
|
||||
* the last one, so CPU time after the last reading is lost when the process exits on its own.
|
||||
* The {@code platform.*} events and the environment metrics of one environment. AWS reports the CPU
|
||||
* time and the peak memory of the whole environment, which Floci reads from the container's cgroup. A
|
||||
* reading that fails keeps the last one, so CPU time after the last reading is lost when the process
|
||||
* exits on its own.
|
||||
*/
|
||||
final class LambdaWebPlatformLog {
|
||||
|
||||
@@ -35,12 +37,14 @@ final class LambdaWebPlatformLog {
|
||||
private final String revisionId;
|
||||
private final String runtime;
|
||||
private final String applicationLogLevel;
|
||||
private final LambdaWebMetrics.EnvironmentMetrics environmentMetrics;
|
||||
private final String instanceId = UUID.randomUUID().toString();
|
||||
private long initStarted;
|
||||
private long invokeStarted;
|
||||
private Instant windowStart;
|
||||
private int windowRequests;
|
||||
private int windowConcurrency;
|
||||
private long windowBytes;
|
||||
private int totalRequests;
|
||||
private int totalConcurrency;
|
||||
private long cpuMicros;
|
||||
@@ -51,13 +55,15 @@ final class LambdaWebPlatformLog {
|
||||
private boolean ended;
|
||||
|
||||
LambdaWebPlatformLog(LambdaWebLogs.Sink sink, String region, String functionName, String revisionId,
|
||||
String runtime, String applicationLogLevel) {
|
||||
String runtime, String applicationLogLevel,
|
||||
LambdaWebMetrics.EnvironmentMetrics environmentMetrics) {
|
||||
this.sink = sink;
|
||||
this.region = region;
|
||||
this.functionName = functionName;
|
||||
this.revisionId = revisionId;
|
||||
this.runtime = runtime;
|
||||
this.applicationLogLevel = applicationLogLevel;
|
||||
this.environmentMetrics = environmentMetrics;
|
||||
}
|
||||
|
||||
synchronized void initStart() {
|
||||
@@ -76,14 +82,16 @@ final class LambdaWebPlatformLog {
|
||||
/** {@code errorType} is null when the app listens. */
|
||||
synchronized void initReport(String errorType, Usage usage) {
|
||||
read(usage);
|
||||
long initNanos = System.nanoTime() - initStarted;
|
||||
ObjectNode record = status(errorType);
|
||||
record.put("instanceId", instanceId);
|
||||
record.put("initializationType", INIT_TYPE);
|
||||
ObjectNode metrics = record.putObject("metrics");
|
||||
metrics.put("totalDurationMs", wholeMillis(System.nanoTime() - initStarted));
|
||||
metrics.put("totalDurationMs", wholeMillis(initNanos));
|
||||
metrics.put("totalCpuTimeMs", wholeMillis(cpuMicros * 1000));
|
||||
metrics.put("maxMemoryUsageMb", peakMemoryMb);
|
||||
sink.platform(Instant.now(), errorType == null ? "INFO" : "WARN", "platform.initReport", record);
|
||||
environmentMetrics.publish(millis(initNanos), millis(cpuMicros * 1000), peakMemoryMb, 0, 0);
|
||||
}
|
||||
|
||||
/** A failure AWS writes in the shape of console output, with the time as Node prints it, and drops at FATAL. */
|
||||
@@ -129,6 +137,7 @@ final class LambdaWebPlatformLog {
|
||||
long durationNanos, long responseBytes) {
|
||||
windowRequests++;
|
||||
totalRequests++;
|
||||
windowBytes += responseBytes;
|
||||
ObjectNode record = JSON.createObjectNode();
|
||||
record.put("requestId", requestId);
|
||||
record.put("endpointName", endpointName);
|
||||
@@ -159,8 +168,11 @@ final class LambdaWebPlatformLog {
|
||||
metrics.put("cpuTimeMs", wholeMillis((cpuMicros - cpuAtWindowStart) * 1000));
|
||||
metrics.put("maxMemoryUsageMb", peakMemoryMb);
|
||||
sink.platform(now, "INFO", "platform.invokeSummary", record);
|
||||
environmentMetrics.publish(Duration.between(windowStart, now).toMillis(),
|
||||
millis((cpuMicros - cpuAtWindowStart) * 1000), peakMemoryMb, windowConcurrency, windowBytes);
|
||||
windowStart = now;
|
||||
windowRequests = 0;
|
||||
windowBytes = 0;
|
||||
windowConcurrency = inFlight;
|
||||
cpuAtWindowStart = cpuMicros;
|
||||
}
|
||||
@@ -218,8 +230,12 @@ final class LambdaWebPlatformLog {
|
||||
return record;
|
||||
}
|
||||
|
||||
private static long millis(long nanos) {
|
||||
return Math.round(nanos / 1_000_000.0);
|
||||
}
|
||||
|
||||
/** AWS writes these durations in whole milliseconds with three decimals. */
|
||||
private static BigDecimal wholeMillis(long nanos) {
|
||||
return BigDecimal.valueOf(Math.round(nanos / 1_000_000.0)).setScale(3);
|
||||
return BigDecimal.valueOf(millis(nanos)).setScale(3);
|
||||
}
|
||||
}
|
||||
@@ -4672,12 +4672,9 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
|
||||
private void publishZeroCapacity(String accountId, String region, Dimension dimension, Instant at) {
|
||||
for (String metricName : List.of("ServerlessDatabaseCapacity", "ACUUtilization", "CPUUtilization")) {
|
||||
MetricDatum datum = new MetricDatum();
|
||||
datum.setMetricName(metricName);
|
||||
datum.setUnit("ServerlessDatabaseCapacity".equals(metricName) ? "Count" : "Percent");
|
||||
datum.setDimensions(List.of(dimension));
|
||||
datum.setTimestamp(at.getEpochSecond());
|
||||
datum.setValue(0.0);
|
||||
MetricDatum datum = MetricDatum.of(metricName,
|
||||
"ServerlessDatabaseCapacity".equals(metricName) ? "Count" : "Percent", 0.0, List.of(dimension),
|
||||
at.getEpochSecond());
|
||||
metricsService.publishMetricForAccount(accountId, "AWS/RDS", datum, region,
|
||||
"rds-auto-pause:" + dimension.name() + "=" + dimension.value() + ":" + metricName + ":" + at);
|
||||
}
|
||||
|
||||
@@ -294,14 +294,10 @@ public class SesEventPublisher {
|
||||
dimensions.add(new Dimension(cfg.getDimensionName(), value));
|
||||
}
|
||||
}
|
||||
MetricDatum datum = new MetricDatum();
|
||||
datum.setNamespace(SES_METRIC_NAMESPACE);
|
||||
datum.setMetricName(SesEventPayload.cloudWatchMetricName(eventType));
|
||||
datum.setValue(1.0);
|
||||
datum.setUnit("Count");
|
||||
datum.setDimensions(dimensions);
|
||||
// Leave timestamp unset: CloudWatchMetricsService.putMetricData defaults a zero
|
||||
// timestamp to Instant.now().getEpochSecond() (epoch seconds, not milliseconds).
|
||||
// A zero timestamp: CloudWatchMetricsService.putMetricData defaults it to
|
||||
// Instant.now().getEpochSecond() (epoch seconds, not milliseconds).
|
||||
MetricDatum datum = MetricDatum.of(SesEventPayload.cloudWatchMetricName(eventType), "Count", 1.0,
|
||||
dimensions, 0);
|
||||
try {
|
||||
cloudWatchMetricsService.putMetricData(SES_METRIC_NAMESPACE, List.of(datum),
|
||||
defaultRegion);
|
||||
|
||||
Reference in new issue
Block a user