feat: add CloudWatch OTLP metrics ingestion (#7781)

This commit is contained in:
Aditya Upadhye authored and GitHub committed 2026-11-10 18:39:55 -04:00
1 parent 00d2ab3207
commit 2d8cdeb343
28 files changed
+2706 -4

No files matched your search

@@ -3,6 +3,7 @@ package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.cloudtrail.CloudTrailService;
import io.floci.aws.services.cloudwatch.metrics.OtlpMetricsController;
import io.floci.aws.services.iam.AccessDeniedMessages;
import io.floci.aws.services.iam.AccessDeniedMessages.PolicyType;
import io.floci.aws.services.iam.IamActionRegistry;
@@ -364,6 +365,12 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (auth == null || emptyHeader) {
auth = requestAuthorization(null, ctx.getUriInfo().getQueryParameters());
}
if (resourceInfo != null && resourceInfo.getResourceClass() == OtlpMetricsController.class
&& (auth == null || !claimsSigV4(auth))) {
ctx.abortWith(AwsProtocolClaimFilter.errorResponse(403, "MissingAuthenticationTokenException",
"Request is missing Authentication Token"));
return;
}
if (auth == null) {
if (emptyHeader) {
// An empty header is not a missing one: "Authorization header cannot be empty" is
@@ -0,0 +1,16 @@
package io.floci.aws.core.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** The generated IAM operation a REST controller serves when AWS has no model for its route. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IamOperation {
String namespace();
String operation();
}
@@ -0,0 +1,50 @@
package io.floci.aws.core.common;
import io.floci.aws.services.cloudwatch.metrics.OtlpMetricsResponses;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
/**
* Reformats authentication error responses for OTLP metrics requests.
* Auth filters produce standard JSON errors; this filter translates them to the OTLP
* {@code Status} envelope the OTLP spec requires.
*/
@Provider
@Priority(Priorities.AUTHENTICATION)
@ApplicationScoped
public class OtlpMetricsAuthResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
if (!OtlpMetricsResponses.isRequest(request)) {
return;
}
int status = response.getStatus();
boolean incompleteSignature = status == 400 && response.getEntity() instanceof AwsErrorResponse error
&& "IncompleteSignatureException".equals(error.type());
if (status != 401 && status != 403 && !incompleteSignature) {
return;
}
String message = extractMessage(response);
Response otlpError = OtlpMetricsResponses.error(request.getMediaType(), 403, 7, message);
response.setStatus(403);
response.setEntity(otlpError.getEntity());
String contentType = otlpError.getMediaType() != null
? otlpError.getMediaType().toString() : "application/json";
response.getHeaders().putSingle("Content-Type", contentType);
}
private static String extractMessage(ContainerResponseContext response) {
Object entity = response.getEntity();
if (entity instanceof AwsErrorResponse err) {
return err.message();
}
return "Authentication failed.";
}
}
@@ -27,6 +27,7 @@ import io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreToolsContro
import io.floci.aws.services.bedrockruntime.BedrockRuntimeController;
import io.floci.aws.services.cloudfront.CloudFrontController;
import io.floci.aws.services.cloudfront.CloudFrontServingController;
import io.floci.aws.services.cloudwatch.metrics.OtlpMetricsController;
import io.floci.aws.services.codeartifact.CodeArtifactController;
import io.floci.aws.services.codeartifact.CodeArtifactMavenController;
import io.floci.aws.services.codeartifact.CodeArtifactPypiController;
@@ -302,7 +303,7 @@ public class ResolvedServiceCatalog {
config.storage().services().cloudwatchmetrics().flushIntervalMs(), AwsNamespaces.CW, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY, ServiceProtocol.JSON, ServiceProtocol.CBOR),
Set.of("GraniteServiceVersion20100801."), Set.of("monitoring"),
Set.of("GraniteServiceVersion20100801"), Set.of(), "CloudWatchVersion20130116."),
Set.of("GraniteServiceVersion20100801"), Set.of(OtlpMetricsController.class), "CloudWatchVersion20130116."),
descriptor("paymentcryptography", "paymentcryptography",
config.services().paymentcryptography().enabled(), true,
"paymentcryptography",
@@ -0,0 +1,197 @@
package io.floci.aws.services.cloudwatch.metrics;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.DescriptorValidationException;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Descriptors.OneofDescriptor;
import io.apicurio.registry.utils.protobuf.schema.FileDescriptorUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;
/** Descriptors for the OTLP metrics proto types, loaded at startup from vendored proto files. */
final class OtlpDescriptors {
static final Descriptor EXPORT_REQUEST;
static final Descriptor EXPORT_RESPONSE;
static final Descriptor PARTIAL_SUCCESS;
static final FieldDescriptor RESOURCE_METRICS_LIST;
static final FieldDescriptor RESPONSE_PARTIAL_SUCCESS;
static final FieldDescriptor REJECTED_DATA_POINTS;
static final FieldDescriptor PARTIAL_ERROR_MESSAGE;
static final FieldDescriptor RESOURCE_FIELD;
static final FieldDescriptor SCOPE_METRICS_LIST;
static final FieldDescriptor SCOPE_FIELD;
static final FieldDescriptor METRICS_LIST;
static final OneofDescriptor METRIC_DATA_ONEOF;
static final FieldDescriptor GAUGE_FIELD;
static final FieldDescriptor SUM_FIELD;
static final FieldDescriptor HISTOGRAM_FIELD;
static final FieldDescriptor EXPONENTIAL_HISTOGRAM_FIELD;
static final FieldDescriptor SUMMARY_FIELD;
static final FieldDescriptor METRIC_NAME;
static final FieldDescriptor METRIC_UNIT;
static final FieldDescriptor GAUGE_DATA_POINTS;
static final FieldDescriptor SUM_DATA_POINTS;
static final FieldDescriptor HISTOGRAM_DATA_POINTS;
static final FieldDescriptor EXPONENTIAL_HISTOGRAM_DATA_POINTS;
static final FieldDescriptor SUMMARY_DATA_POINTS;
static final FieldDescriptor NUMBER_POINT_TIME_UNIX_NANO;
static final FieldDescriptor NUMBER_POINT_ATTRIBUTES;
static final FieldDescriptor HISTOGRAM_POINT_TIME_UNIX_NANO;
static final FieldDescriptor HISTOGRAM_POINT_ATTRIBUTES;
static final FieldDescriptor EXP_HISTOGRAM_POINT_TIME_UNIX_NANO;
static final FieldDescriptor EXP_HISTOGRAM_POINT_ATTRIBUTES;
static final FieldDescriptor SUMMARY_POINT_TIME_UNIX_NANO;
static final FieldDescriptor SUMMARY_POINT_ATTRIBUTES;
static final FieldDescriptor RESOURCE_ATTRIBUTES;
static final FieldDescriptor SCOPE_ATTRIBUTES;
static final FieldDescriptor SCOPE_NAME;
static final FieldDescriptor SCOPE_VERSION;
static final FieldDescriptor KV_KEY;
static final FieldDescriptor KV_VALUE;
static final OneofDescriptor ANY_VALUE_ONEOF;
static final FieldDescriptor STRING_VALUE;
static final FieldDescriptor BOOL_VALUE;
static final FieldDescriptor INT_VALUE;
static final FieldDescriptor DOUBLE_VALUE;
static final FieldDescriptor BYTES_VALUE;
static final FieldDescriptor ARRAY_VALUE;
static final FieldDescriptor KVLIST_VALUE;
static final FieldDescriptor ARRAY_VALUES;
static final FieldDescriptor KVLIST_VALUES;
static {
try {
String common = "opentelemetry/proto/common/v1/common.proto";
String resource = "opentelemetry/proto/resource/v1/resource.proto";
String metrics = "opentelemetry/proto/metrics/v1/metrics.proto";
String service = "opentelemetry/proto/collector/metrics/v1/metrics_service.proto";
String commonText = schema(common);
String resourceText = schema(resource);
String metricsText = schema(metrics);
String serviceText = schema(service);
Map<String, String> commonSchema = Map.of("opentelemetry.proto.common.v1/common.proto", commonText);
Map<String, String> metricSchemas = Map.of(
"opentelemetry.proto.common.v1/common.proto", commonText,
"opentelemetry.proto.resource.v1/resource.proto", resourceText);
Map<String, String> serviceSchemas = Map.of(
"opentelemetry.proto.common.v1/common.proto", commonText,
"opentelemetry.proto.resource.v1/resource.proto", resourceText,
"opentelemetry.proto.metrics.v1/metrics.proto", metricsText);
FileDescriptor commonFile = descriptor(common, commonText, Map.of());
FileDescriptor resourceFile = descriptor(resource, resourceText, commonSchema, commonFile);
FileDescriptor metricsFile = descriptor(metrics, metricsText, metricSchemas, commonFile, resourceFile);
FileDescriptor serviceFile = descriptor(service, serviceText, serviceSchemas, commonFile, resourceFile,
metricsFile);
EXPORT_REQUEST = serviceFile.findMessageTypeByName("ExportMetricsServiceRequest");
EXPORT_RESPONSE = serviceFile.findMessageTypeByName("ExportMetricsServiceResponse");
PARTIAL_SUCCESS = serviceFile.findMessageTypeByName("ExportMetricsPartialSuccess");
Descriptor metricDesc = metricsFile.findMessageTypeByName("Metric");
Descriptor numberPointDesc = metricsFile.findMessageTypeByName("NumberDataPoint");
Descriptor histPointDesc = metricsFile.findMessageTypeByName("HistogramDataPoint");
Descriptor expHistPointDesc = metricsFile.findMessageTypeByName("ExponentialHistogramDataPoint");
Descriptor summaryPointDesc = metricsFile.findMessageTypeByName("SummaryDataPoint");
Descriptor resourceMetricsDesc = metricsFile.findMessageTypeByName("ResourceMetrics");
Descriptor scopeMetricsDesc = metricsFile.findMessageTypeByName("ScopeMetrics");
Descriptor keyValueDesc = commonFile.findMessageTypeByName("KeyValue");
Descriptor anyValueDesc = commonFile.findMessageTypeByName("AnyValue");
Descriptor arrayValueDesc = commonFile.findMessageTypeByName("ArrayValue");
Descriptor kvListDesc = commonFile.findMessageTypeByName("KeyValueList");
Descriptor scopeDesc = commonFile.findMessageTypeByName("InstrumentationScope");
Descriptor resourceDesc = resourceFile.findMessageTypeByName("Resource");
RESOURCE_METRICS_LIST = EXPORT_REQUEST.findFieldByName("resource_metrics");
RESPONSE_PARTIAL_SUCCESS = EXPORT_RESPONSE.findFieldByName("partial_success");
REJECTED_DATA_POINTS = PARTIAL_SUCCESS.findFieldByName("rejected_data_points");
PARTIAL_ERROR_MESSAGE = PARTIAL_SUCCESS.findFieldByName("error_message");
RESOURCE_FIELD = resourceMetricsDesc.findFieldByName("resource");
SCOPE_METRICS_LIST = resourceMetricsDesc.findFieldByName("scope_metrics");
SCOPE_FIELD = scopeMetricsDesc.findFieldByName("scope");
METRICS_LIST = scopeMetricsDesc.findFieldByName("metrics");
METRIC_DATA_ONEOF = metricDesc.getOneofs().get(0);
GAUGE_FIELD = metricDesc.findFieldByName("gauge");
SUM_FIELD = metricDesc.findFieldByName("sum");
HISTOGRAM_FIELD = metricDesc.findFieldByName("histogram");
EXPONENTIAL_HISTOGRAM_FIELD = metricDesc.findFieldByName("exponential_histogram");
SUMMARY_FIELD = metricDesc.findFieldByName("summary");
METRIC_NAME = metricDesc.findFieldByName("name");
METRIC_UNIT = metricDesc.findFieldByName("unit");
GAUGE_DATA_POINTS = metricsFile.findMessageTypeByName("Gauge").findFieldByName("data_points");
SUM_DATA_POINTS = metricsFile.findMessageTypeByName("Sum").findFieldByName("data_points");
HISTOGRAM_DATA_POINTS = metricsFile.findMessageTypeByName("Histogram").findFieldByName("data_points");
EXPONENTIAL_HISTOGRAM_DATA_POINTS =
metricsFile.findMessageTypeByName("ExponentialHistogram").findFieldByName("data_points");
SUMMARY_DATA_POINTS = metricsFile.findMessageTypeByName("Summary").findFieldByName("data_points");
NUMBER_POINT_TIME_UNIX_NANO = numberPointDesc.findFieldByName("time_unix_nano");
NUMBER_POINT_ATTRIBUTES = numberPointDesc.findFieldByName("attributes");
HISTOGRAM_POINT_TIME_UNIX_NANO = histPointDesc.findFieldByName("time_unix_nano");
HISTOGRAM_POINT_ATTRIBUTES = histPointDesc.findFieldByName("attributes");
EXP_HISTOGRAM_POINT_TIME_UNIX_NANO = expHistPointDesc.findFieldByName("time_unix_nano");
EXP_HISTOGRAM_POINT_ATTRIBUTES = expHistPointDesc.findFieldByName("attributes");
SUMMARY_POINT_TIME_UNIX_NANO = summaryPointDesc.findFieldByName("time_unix_nano");
SUMMARY_POINT_ATTRIBUTES = summaryPointDesc.findFieldByName("attributes");
RESOURCE_ATTRIBUTES = resourceDesc.findFieldByName("attributes");
SCOPE_ATTRIBUTES = scopeDesc.findFieldByName("attributes");
SCOPE_NAME = scopeDesc.findFieldByName("name");
SCOPE_VERSION = scopeDesc.findFieldByName("version");
KV_KEY = keyValueDesc.findFieldByName("key");
KV_VALUE = keyValueDesc.findFieldByName("value");
ANY_VALUE_ONEOF = anyValueDesc.getOneofs().get(0);
STRING_VALUE = anyValueDesc.findFieldByName("string_value");
BOOL_VALUE = anyValueDesc.findFieldByName("bool_value");
INT_VALUE = anyValueDesc.findFieldByName("int_value");
DOUBLE_VALUE = anyValueDesc.findFieldByName("double_value");
BYTES_VALUE = anyValueDesc.findFieldByName("bytes_value");
ARRAY_VALUE = anyValueDesc.findFieldByName("array_value");
KVLIST_VALUE = anyValueDesc.findFieldByName("kvlist_value");
ARRAY_VALUES = arrayValueDesc.findFieldByName("values");
KVLIST_VALUES = kvListDesc.findFieldByName("values");
} catch (DescriptorValidationException | IOException e) {
throw new IllegalStateException("Failed to load OTLP proto descriptors", e);
}
}
private static FileDescriptor descriptor(String name, String text, Map<String, String> dependencies,
FileDescriptor... files) throws DescriptorValidationException {
String packageName = name.substring(0, name.lastIndexOf('/')).replace('/', '.');
String fileName = name.substring(name.lastIndexOf('/') + 1);
return FileDescriptor.buildFrom(FileDescriptorUtils.toFileDescriptorProto(text, fileName,
Optional.of(packageName), dependencies).toBuilder().setName(name).build(), files);
}
private static String schema(String name) throws IOException {
try (InputStream input = OtlpDescriptors.class.getClassLoader().getResourceAsStream("proto/" + name)) {
if (input == null) {
throw new IOException("OTLP proto file not found: " + name);
}
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
}
private OtlpDescriptors() {}
}
@@ -0,0 +1,114 @@
package io.floci.aws.services.cloudwatch.metrics;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.DynamicMessage;
import com.google.protobuf.util.JsonFormat;
import io.floci.aws.core.common.IamOperation;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.common.ServiceRegistry;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.zip.GZIPInputStream;
@Path("/v1/metrics")
@IamOperation(namespace = "cloudwatch", operation = "PutMetricData")
public class OtlpMetricsController {
private static final int MAX_REQUEST_BYTES = 5 * 1024 * 1024;
private static final String PROTOBUF = "application/x-protobuf";
private final OtlpMetricsService service;
private final RequestContext requestContext;
private final ServiceRegistry serviceRegistry;
private final OtlpMetricsDecoder decoder = new OtlpMetricsDecoder();
private final OtlpMetricsValidation validation = new OtlpMetricsValidation();
@Inject
public OtlpMetricsController(OtlpMetricsService service, RequestContext requestContext,
ServiceRegistry serviceRegistry) {
this.service = service;
this.requestContext = requestContext;
this.serviceRegistry = serviceRegistry;
}
@POST
@Consumes(MediaType.WILDCARD)
public Response ingest(@Context HttpHeaders headers, InputStream input) {
if (!serviceRegistry.isServiceEnabled("monitoring")) {
return OtlpMetricsResponses.error(headers.getMediaType(), 404, 5, "CloudWatch metrics service is disabled.");
}
MediaType mediaType = headers.getMediaType();
boolean json = mediaType != null && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
boolean protobuf = mediaType != null && mediaType.isCompatible(MediaType.valueOf(PROTOBUF));
if (!json && !protobuf) {
return OtlpMetricsResponses.error(mediaType, 415, 3, "Unsupported content type.");
}
String encoding = headers.getHeaderString(HttpHeaders.CONTENT_ENCODING);
if (encoding != null && !encoding.isBlank() && !"identity".equalsIgnoreCase(encoding)
&& !"gzip".equalsIgnoreCase(encoding)) {
return OtlpMetricsResponses.error(mediaType, 415, 3, "Unsupported content encoding.");
}
try {
InputStream body = "gzip".equalsIgnoreCase(encoding) ? new GZIPInputStream(input) : input;
byte[] bytes = body.readNBytes(MAX_REQUEST_BYTES + 1);
if (bytes.length > MAX_REQUEST_BYTES) {
return OtlpMetricsResponses.error(mediaType, 413, 8, "Request exceeds maximum size of 5 MB.");
}
DynamicMessage request = json ? decoder.decodeJson(bytes) : decoder.decodeProtobuf(bytes);
OtlpMetricsValidation.Result result = validation.validate(request);
if (result.rejectedDataPoints() > 0 && result.rejectedDataPoints() == dataPointCount(request)) {
return OtlpMetricsResponses.error(mediaType, 400, 3, result.errorMessage());
}
service.ingest(requestContext.getRegion(), result.requestBytes());
DynamicMessage response = buildResponse(result);
return successResponse(json, response);
} catch (IOException e) {
return OtlpMetricsResponses.error(mediaType, 400, 3, "Bad request.");
}
}
private DynamicMessage buildResponse(OtlpMetricsValidation.Result result) {
if (result.hasErrors()) {
DynamicMessage.Builder psBuilder = DynamicMessage.newBuilder(OtlpDescriptors.PARTIAL_SUCCESS);
psBuilder.setField(OtlpDescriptors.REJECTED_DATA_POINTS, (long) result.rejectedDataPoints());
psBuilder.setField(OtlpDescriptors.PARTIAL_ERROR_MESSAGE, result.errorMessage());
DynamicMessage.Builder respBuilder = DynamicMessage.newBuilder(OtlpDescriptors.EXPORT_RESPONSE);
respBuilder.setField(OtlpDescriptors.RESPONSE_PARTIAL_SUCCESS, psBuilder.build());
return respBuilder.build();
}
return DynamicMessage.newBuilder(OtlpDescriptors.EXPORT_RESPONSE).build();
}
private Response successResponse(boolean json, DynamicMessage response) throws IOException {
byte[] responseBody = json ? JsonFormat.printer().print(response).getBytes(StandardCharsets.UTF_8)
: response.toByteArray();
return Response.ok(responseBody).type(json ? MediaType.APPLICATION_JSON : PROTOBUF).build();
}
private int dataPointCount(DynamicMessage request) {
int count = 0;
for (DynamicMessage resource : getList(request, OtlpDescriptors.RESOURCE_METRICS_LIST)) {
for (DynamicMessage scope : getList(resource, OtlpDescriptors.SCOPE_METRICS_LIST)) {
for (DynamicMessage metric : getList(scope, OtlpDescriptors.METRICS_LIST)) {
count += OtlpMetricsValidation.metricDataPointCount(metric);
}
}
}
return count;
}
@SuppressWarnings("unchecked")
private static List<DynamicMessage> getList(DynamicMessage msg, FieldDescriptor field) {
return (List<DynamicMessage>) msg.getField(field);
}
}
@@ -0,0 +1,72 @@
package io.floci.aws.services.cloudwatch.metrics;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.protobuf.DynamicMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
final class OtlpMetricsDecoder {
private static final ObjectMapper MAPPER = new ObjectMapper()
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
private static final List<String> METRIC_TYPES = List.of("gauge", "sum", "histogram", "exponentialHistogram");
DynamicMessage decodeJson(byte[] body) throws InvalidProtocolBufferException {
try {
JsonNode root = MAPPER.readTree(body);
if (root == null) {
throw new InvalidProtocolBufferException("Empty OTLP metrics request");
}
convertExemplarIds(root);
DynamicMessage.Builder request = DynamicMessage.newBuilder(OtlpDescriptors.EXPORT_REQUEST);
JsonFormat.parser().ignoringUnknownFields().merge(MAPPER.writeValueAsString(root), request);
return request.build();
} catch (InvalidProtocolBufferException e) {
throw e;
} catch (IOException | IllegalArgumentException e) {
throw new InvalidProtocolBufferException(e);
}
}
private void convertExemplarIds(JsonNode root) {
for (JsonNode resource : root.path("resourceMetrics")) {
for (JsonNode scope : resource.path("scopeMetrics")) {
for (JsonNode metric : scope.path("metrics")) {
for (String metricType : METRIC_TYPES) {
for (JsonNode point : metric.path(metricType).path("dataPoints")) {
for (JsonNode exemplar : point.path("exemplars")) {
if (exemplar instanceof ObjectNode object) {
convertHexField(object, "traceId");
convertHexField(object, "spanId");
}
}
}
}
}
}
}
}
private void convertHexField(ObjectNode exemplar, String field) {
JsonNode value = exemplar.get(field);
if (value != null && value.isTextual()) {
byte[] decoded = HexFormat.of().parseHex(value.textValue());
exemplar.put(field, Base64.getEncoder().encodeToString(decoded));
}
}
DynamicMessage decodeProtobuf(byte[] body) throws InvalidProtocolBufferException {
if (body.length == 0) {
throw new InvalidProtocolBufferException("Empty OTLP metrics request");
}
return DynamicMessage.parseFrom(OtlpDescriptors.EXPORT_REQUEST, body);
}
}
@@ -0,0 +1,9 @@
package io.floci.aws.services.cloudwatch.metrics;
import com.google.protobuf.Any;
import com.google.rpc.Status;
import io.quarkus.runtime.annotations.RegisterForReflection;
/** Registers protobuf message accessors used reflectively by protobuf's JSON codec. */
@RegisterForReflection(targets = {Any.class, Status.class})
public class OtlpMetricsNativeSupport {}
@@ -0,0 +1,40 @@
package io.floci.aws.services.cloudwatch.metrics;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.google.rpc.Status;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.nio.charset.StandardCharsets;
/** OTLP status responses shared by the endpoint and the authentication filters. */
public final class OtlpMetricsResponses {
private static final String PROTOBUF = "application/x-protobuf";
private OtlpMetricsResponses() {}
public static boolean isRequest(ContainerRequestContext context) {
if (!"POST".equalsIgnoreCase(context.getMethod()) || context.getUriInfo() == null) {
return false;
}
String path = context.getUriInfo().getPath();
return "v1/metrics".equals(path) || "v1/metrics/".equals(path)
|| "/v1/metrics".equals(path) || "/v1/metrics/".equals(path);
}
public static Response error(MediaType requestType, int httpStatus, int code, String message) {
boolean json = requestType != null && requestType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
Status status = Status.newBuilder().setCode(code).setMessage(message).build();
try {
byte[] body = json ? JsonFormat.printer().print(status).getBytes(StandardCharsets.UTF_8)
: status.toByteArray();
return Response.status(httpStatus).entity(body)
.type(json ? MediaType.APPLICATION_JSON : PROTOBUF).build();
} catch (InvalidProtocolBufferException e) {
throw new IllegalStateException("OTLP status response could not be encoded", e);
}
}
}
@@ -0,0 +1,91 @@
package io.floci.aws.services.cloudwatch.metrics;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.core.storage.WriteProfile;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Clock;
import java.time.Duration;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@ApplicationScoped
public class OtlpMetricsService {
private static final long RETENTION_MILLIS = Duration.ofDays(14).toMillis();
private static final long SWEEP_INTERVAL_MILLIS = Duration.ofMinutes(1).toMillis();
private final StorageBackend<String, String> store;
private final RequestContext requestContext;
private final Clock clock;
private final Map<String, Long> nextSweeps = new HashMap<>();
@Inject
public OtlpMetricsService(StorageFactory storageFactory, RequestContext requestContext) {
this(storageFactory, requestContext, Clock.systemUTC());
}
OtlpMetricsService(StorageFactory storageFactory) {
this(storageFactory, null, Clock.systemUTC());
}
OtlpMetricsService(StorageFactory storageFactory, Clock clock) {
this(storageFactory, null, clock);
}
OtlpMetricsService(StorageFactory storageFactory, RequestContext requestContext, Clock clock) {
this.store = storageFactory.create("cloudwatchmetrics", "cw-otlp-metrics.json",
new TypeReference<Map<String, String>>() {}, WriteProfile.APPEND_HEAVY);
this.requestContext = requestContext;
this.clock = clock;
}
void ingest(String region, byte[] requestBytes) {
if (requestBytes != null && requestBytes.length > 0) {
long now = clock.millis();
pruneExpired(region, now);
store.put(region + "::" + now + "::" + UUID.randomUUID(),
Base64.getEncoder().encodeToString(requestBytes));
}
}
private synchronized void pruneExpired(String region, long now) {
String account = requestContext == null ? "" : requestContext.getAccountId();
String scope = account + "/" + region;
if (now < nextSweeps.getOrDefault(scope, Long.MIN_VALUE)) {
return;
}
String prefix = region + "::";
for (String key : store.keys()) {
if (!key.startsWith(prefix)) {
continue;
}
String suffix = key.substring(prefix.length());
int delimiter = suffix.indexOf("::");
if (delimiter < 0) {
continue;
}
try {
long created = Long.parseLong(suffix.substring(0, delimiter));
if (created < now - RETENTION_MILLIS) {
store.delete(key);
}
} catch (NumberFormatException ignored) {
// Preserve unrecognized keys rather than deleting data with an unknown age.
}
}
nextSweeps.put(scope, now + SWEEP_INTERVAL_MILLIS);
}
List<byte[]> requests(String region) {
return store.scan(key -> key.startsWith(region + "::")).stream()
.map(encoded -> Base64.getDecoder().decode(encoded))
.toList();
}
}
@@ -0,0 +1,325 @@
package io.floci.aws.services.cloudwatch.metrics;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.DynamicMessage;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
final class OtlpMetricsValidation {
private static final int MAX_DATA_POINTS = 1000;
private static final int MAX_ATTRIBUTES = 150;
private static final int MAX_METADATA_BYTES = 40_000;
private static final int MAX_ATTRIBUTE_LENGTH = 1024;
private static final int MAX_METRIC_NAME_LENGTH = 256;
private static final long NANOS_PER_SECOND = 1_000_000_000L;
private static final Duration MAX_AGE = Duration.ofDays(14);
private static final Duration MAX_FUTURE = Duration.ofHours(2);
record Result(byte[] requestBytes, int rejectedDataPoints, List<String> errors) {
boolean hasErrors() {
return !errors.isEmpty();
}
String errorMessage() {
return String.join("\n", errors);
}
}
private record PointContext(DynamicMessage resource, DynamicMessage scope, DynamicMessage metric,
String path, long oldestNanos, long newestNanos) {}
Result validate(DynamicMessage request) {
List<DynamicMessage> resourceList = getList(request, OtlpDescriptors.RESOURCE_METRICS_LIST);
int count = resourceList.stream().mapToInt(this::dataPointCount).sum();
if (count > MAX_DATA_POINTS) {
return new Result(null, count, List.of("Maximum number of datapoints per request exceeded: 1000."));
}
Instant now = Instant.now();
long oldest = epochNanos(now.minus(MAX_AGE));
long newest = epochNanos(now.plus(MAX_FUTURE));
int rejected = 0;
List<String> errors = new ArrayList<>();
DynamicMessage.Builder accepted = request.toBuilder().clearField(OtlpDescriptors.RESOURCE_METRICS_LIST);
int resourceIndex = 0;
for (DynamicMessage resource : resourceList) {
String resourcePath = "ResourceMetrics." + ++resourceIndex;
int resourcePoints = dataPointCount(resource);
DynamicMessage resourceProto = getSubMessage(resource, OtlpDescriptors.RESOURCE_FIELD);
List<DynamicMessage> resourceAttributes = getList(resourceProto, OtlpDescriptors.RESOURCE_ATTRIBUTES);
boolean resourceInvalid = resourcePoints > 0 && hasOversizedStringAttribute(resourceAttributes);
if (resourceInvalid) {
errors.add(sharedAttributeError(resourcePath, resourcePoints));
}
DynamicMessage.Builder acceptedResource = resource.toBuilder()
.clearField(OtlpDescriptors.SCOPE_METRICS_LIST);
int scopeIndex = 0;
for (DynamicMessage scope : getList(resource, OtlpDescriptors.SCOPE_METRICS_LIST)) {
String scopePath = resourcePath + ".ScopeMetrics." + ++scopeIndex;
int scopePoints = scopeDataPointCount(scope);
DynamicMessage scopeProto = getSubMessage(scope, OtlpDescriptors.SCOPE_FIELD);
List<DynamicMessage> scopeAttributes = getList(scopeProto, OtlpDescriptors.SCOPE_ATTRIBUTES);
boolean scopeInvalid = scopePoints > 0 && hasOversizedStringAttribute(scopeAttributes);
if (scopeInvalid) {
errors.add(sharedAttributeError(scopePath, scopePoints));
}
DynamicMessage.Builder acceptedScope = scope.toBuilder()
.clearField(OtlpDescriptors.METRICS_LIST);
int metricIndex = 0;
for (DynamicMessage metric : getList(scope, OtlpDescriptors.METRICS_LIST)) {
String metricPath = scopePath + ".Metrics." + ++metricIndex;
int metricPoints = metricDataPointCount(metric);
if (metricPoints == 0) {
errors.add("Invalid OTel metric type [" + metricPath + "].");
continue;
}
String metricName = (String) metric.getField(OtlpDescriptors.METRIC_NAME);
boolean metricInvalid = metricName.length() > MAX_METRIC_NAME_LENGTH;
if (metricInvalid) {
errors.add("Metric name exceeds maximum length: 256 [" + metricPath + "] ("
+ rejectedCount(metricPoints) + ").");
}
DynamicMessage.Builder acceptedMetric = metric.toBuilder();
PointContext context = new PointContext(resource, scope, metric, metricPath, oldest, newest);
List<String> pointErrors = filterMetric(acceptedMetric, context);
errors.addAll(pointErrors);
boolean sharedInvalid = resourceInvalid || scopeInvalid || metricInvalid;
rejected += sharedInvalid ? metricPoints : pointErrors.size();
if (!sharedInvalid && metricDataPointCount(acceptedMetric.build()) > 0) {
acceptedScope.addRepeatedField(OtlpDescriptors.METRICS_LIST, acceptedMetric.build());
}
}
if (!getList(acceptedScope.build(), OtlpDescriptors.METRICS_LIST).isEmpty()) {
acceptedResource.addRepeatedField(OtlpDescriptors.SCOPE_METRICS_LIST, acceptedScope.build());
}
}
if (!getList(acceptedResource.build(), OtlpDescriptors.SCOPE_METRICS_LIST).isEmpty()) {
accepted.addRepeatedField(OtlpDescriptors.RESOURCE_METRICS_LIST, acceptedResource.build());
}
}
errors.sort(String::compareTo);
return new Result(accepted.build().toByteArray(), rejected, List.copyOf(errors));
}
private List<String> filterMetric(DynamicMessage.Builder accepted, PointContext context) {
DynamicMessage metric = context.metric();
List<String> errors = new ArrayList<>();
FieldDescriptor activeField = metric.getOneofFieldDescriptor(OtlpDescriptors.METRIC_DATA_ONEOF);
if (activeField == null) {
return errors;
}
DynamicMessage data = (DynamicMessage) metric.getField(activeField);
FieldDescriptor dataPointsField = dataPointsFieldFor(activeField);
DynamicMessage.Builder dataBuilder = data.toBuilder().clearField(dataPointsField);
FieldDescriptor timestampField = timestampFieldFor(activeField);
FieldDescriptor attributesField = attributesFieldFor(activeField);
int pointIndex = 0;
for (DynamicMessage point : getList(data, dataPointsField)) {
String path = context.path() + ".Datapoint." + ++pointIndex;
long timestamp = (Long) point.getField(timestampField);
String error = pointError(timestamp, getList(point, attributesField), context, path);
if (error == null) {
dataBuilder.addRepeatedField(dataPointsField, point);
} else {
errors.add(error);
}
}
accepted.setField(activeField, dataBuilder.build());
return errors;
}
private static FieldDescriptor dataPointsFieldFor(FieldDescriptor metricField) {
if (metricField == OtlpDescriptors.GAUGE_FIELD) {
return OtlpDescriptors.GAUGE_DATA_POINTS;
}
if (metricField == OtlpDescriptors.SUM_FIELD) {
return OtlpDescriptors.SUM_DATA_POINTS;
}
if (metricField == OtlpDescriptors.HISTOGRAM_FIELD) {
return OtlpDescriptors.HISTOGRAM_DATA_POINTS;
}
if (metricField == OtlpDescriptors.EXPONENTIAL_HISTOGRAM_FIELD) {
return OtlpDescriptors.EXPONENTIAL_HISTOGRAM_DATA_POINTS;
}
return OtlpDescriptors.SUMMARY_DATA_POINTS;
}
private static FieldDescriptor timestampFieldFor(FieldDescriptor metricField) {
if (metricField == OtlpDescriptors.GAUGE_FIELD || metricField == OtlpDescriptors.SUM_FIELD) {
return OtlpDescriptors.NUMBER_POINT_TIME_UNIX_NANO;
}
if (metricField == OtlpDescriptors.HISTOGRAM_FIELD) {
return OtlpDescriptors.HISTOGRAM_POINT_TIME_UNIX_NANO;
}
if (metricField == OtlpDescriptors.EXPONENTIAL_HISTOGRAM_FIELD) {
return OtlpDescriptors.EXP_HISTOGRAM_POINT_TIME_UNIX_NANO;
}
return OtlpDescriptors.SUMMARY_POINT_TIME_UNIX_NANO;
}
private static FieldDescriptor attributesFieldFor(FieldDescriptor metricField) {
if (metricField == OtlpDescriptors.GAUGE_FIELD || metricField == OtlpDescriptors.SUM_FIELD) {
return OtlpDescriptors.NUMBER_POINT_ATTRIBUTES;
}
if (metricField == OtlpDescriptors.HISTOGRAM_FIELD) {
return OtlpDescriptors.HISTOGRAM_POINT_ATTRIBUTES;
}
if (metricField == OtlpDescriptors.EXPONENTIAL_HISTOGRAM_FIELD) {
return OtlpDescriptors.EXP_HISTOGRAM_POINT_ATTRIBUTES;
}
return OtlpDescriptors.SUMMARY_POINT_ATTRIBUTES;
}
private String pointError(long timestamp, List<DynamicMessage> attributes,
PointContext context, String path) {
if (hasOversizedStringAttribute(attributes)) {
return "Attribute string value exceeds maximum length: 1024 [" + path + "].";
}
DynamicMessage resourceProto = getSubMessage(context.resource(), OtlpDescriptors.RESOURCE_FIELD);
List<DynamicMessage> resourceAttributes = getList(resourceProto, OtlpDescriptors.RESOURCE_ATTRIBUTES);
DynamicMessage scopeProto = getSubMessage(context.scope(), OtlpDescriptors.SCOPE_FIELD);
List<DynamicMessage> scopeAttributes = getList(scopeProto, OtlpDescriptors.SCOPE_ATTRIBUTES);
if (resourceAttributes.size() + scopeAttributes.size() + attributes.size() > MAX_ATTRIBUTES) {
return "Maximum number of attributes exceeded: 150 [" + path + "].";
}
String metricName = (String) context.metric().getField(OtlpDescriptors.METRIC_NAME);
String metricUnit = (String) context.metric().getField(OtlpDescriptors.METRIC_UNIT);
String scopeName = (String) scopeProto.getField(OtlpDescriptors.SCOPE_NAME);
String scopeVersion = (String) scopeProto.getField(OtlpDescriptors.SCOPE_VERSION);
long metadataSize = utf8Size(metricName) + utf8Size(metricUnit)
+ utf8Size(scopeName) + utf8Size(scopeVersion)
+ attributesSize(resourceAttributes) + attributesSize(scopeAttributes) + attributesSize(attributes);
if (metadataSize > MAX_METADATA_BYTES) {
return "Maximum size of datapoint metadata exceeded: 40 KB [" + path + "].";
}
if (Long.compareUnsigned(timestamp, context.oldestNanos()) >= 0
&& Long.compareUnsigned(timestamp, context.newestNanos()) <= 0) {
return null;
}
String direction = Long.compareUnsigned(timestamp, context.oldestNanos()) < 0
? "too far in the past" : "too far in the future";
String serviceNameValue = resourceAttributes.stream()
.filter(kv -> "service.name".equals(kv.getField(OtlpDescriptors.KV_KEY)))
.map(kv -> {
DynamicMessage value = (DynamicMessage) kv.getField(OtlpDescriptors.KV_VALUE);
return "service.name='" + value.getField(OtlpDescriptors.STRING_VALUE) + "'";
})
.findFirst().orElse("service.name is not present");
String displayName = metricName.length() > 60 ? metricName.substring(0, 60) + "..." : metricName;
return "TimeUnixNano " + Long.toUnsignedString(timestamp) + " is " + direction + " for metric '"
+ displayName + "' for resource where " + serviceNameValue + " at [" + path + "].";
}
private long epochNanos(Instant instant) {
return instant.getEpochSecond() * NANOS_PER_SECOND + instant.getNano();
}
int dataPointCount(DynamicMessage resource) {
return getList(resource, OtlpDescriptors.SCOPE_METRICS_LIST).stream()
.mapToInt(this::scopeDataPointCount).sum();
}
private int scopeDataPointCount(DynamicMessage scope) {
return getList(scope, OtlpDescriptors.METRICS_LIST).stream()
.mapToInt(OtlpMetricsValidation::metricDataPointCount).sum();
}
static int metricDataPointCount(DynamicMessage metric) {
FieldDescriptor activeField = metric.getOneofFieldDescriptor(OtlpDescriptors.METRIC_DATA_ONEOF);
if (activeField == null) {
return 0;
}
DynamicMessage data = (DynamicMessage) metric.getField(activeField);
return getList(data, dataPointsFieldFor(activeField)).size();
}
private boolean hasOversizedStringAttribute(List<DynamicMessage> attributes) {
// CloudWatch counts UTF-16 code units here; the metadata limit counts UTF-8 bytes.
return attributes.stream()
.map(kv -> (DynamicMessage) kv.getField(OtlpDescriptors.KV_VALUE))
.anyMatch(this::hasOversizedString);
}
private boolean hasOversizedString(DynamicMessage value) {
FieldDescriptor active = value.getOneofFieldDescriptor(OtlpDescriptors.ANY_VALUE_ONEOF);
if (active == null) {
return false;
}
if (active == OtlpDescriptors.STRING_VALUE) {
return ((String) value.getField(active)).length() > MAX_ATTRIBUTE_LENGTH;
}
if (active == OtlpDescriptors.ARRAY_VALUE) {
DynamicMessage array = (DynamicMessage) value.getField(active);
return getList(array, OtlpDescriptors.ARRAY_VALUES).stream().anyMatch(this::hasOversizedString);
}
if (active == OtlpDescriptors.KVLIST_VALUE) {
DynamicMessage kvList = (DynamicMessage) value.getField(active);
return hasOversizedStringAttribute(getList(kvList, OtlpDescriptors.KVLIST_VALUES));
}
return false;
}
private long attributesSize(List<DynamicMessage> attributes) {
long size = 0;
for (DynamicMessage kv : attributes) {
size += utf8Size((String) kv.getField(OtlpDescriptors.KV_KEY));
size += valueSize((DynamicMessage) kv.getField(OtlpDescriptors.KV_VALUE));
}
return size;
}
private long valueSize(DynamicMessage value) {
FieldDescriptor active = value.getOneofFieldDescriptor(OtlpDescriptors.ANY_VALUE_ONEOF);
if (active == null) {
return 0;
}
if (active == OtlpDescriptors.STRING_VALUE) {
return utf8Size((String) value.getField(active));
}
if (active == OtlpDescriptors.BOOL_VALUE) {
return 1;
}
if (active == OtlpDescriptors.INT_VALUE || active == OtlpDescriptors.DOUBLE_VALUE) {
return 8;
}
if (active == OtlpDescriptors.BYTES_VALUE) {
return ((ByteString) value.getField(active)).size();
}
if (active == OtlpDescriptors.ARRAY_VALUE) {
DynamicMessage array = (DynamicMessage) value.getField(active);
return getList(array, OtlpDescriptors.ARRAY_VALUES).stream().mapToLong(this::valueSize).sum();
}
if (active == OtlpDescriptors.KVLIST_VALUE) {
DynamicMessage kvList = (DynamicMessage) value.getField(active);
return attributesSize(getList(kvList, OtlpDescriptors.KVLIST_VALUES));
}
return 0;
}
private int utf8Size(String value) {
return value.getBytes(StandardCharsets.UTF_8).length;
}
private String sharedAttributeError(String path, int count) {
return "Attribute string value exceeds maximum length: 1024 [" + path + "] ("
+ rejectedCount(count) + ").";
}
private String rejectedCount(int count) {
return count + (count == 1 ? " datapoint rejected" : " datapoints rejected");
}
@SuppressWarnings("unchecked")
static List<DynamicMessage> getList(DynamicMessage msg, FieldDescriptor field) {
return (List<DynamicMessage>) msg.getField(field);
}
private static DynamicMessage getSubMessage(DynamicMessage msg, FieldDescriptor field) {
return (DynamicMessage) msg.getField(field);
}
}
@@ -3,6 +3,7 @@ package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsProtocolClaimFilter;
import io.floci.aws.core.common.AwsQueryServiceResolver;
import io.floci.aws.core.common.IamOperation;
import io.floci.aws.core.common.ProtocolClaim;
import io.floci.aws.core.common.RequestResources;
import io.floci.aws.core.common.WireProtocol;
@@ -674,7 +675,14 @@ public class IamActionRegistry {
&& resourceInfo.getResourceMethod() != null) {
return ROUTE53_DELEGATION_ACTIONS.get(resourceInfo.getResourceMethod().getName());
}
return null;
if (resourceInfo == null || resourceInfo.getResourceClass() == null) {
return null;
}
IamOperation iamOperation = resourceInfo.getResourceClass().getAnnotation(IamOperation.class);
if (iamOperation == null || !credentialScope.equals(iamOperation.namespace())) {
return null;
}
return IamAuthorizedActions.actionFor(iamOperation.namespace(), iamOperation.operation());
}
/**