From 2d8cdeb343f0fc0f3a811aa566f87859731c832d Mon Sep 17 00:00:00 2001 From: Aditya Upadhye <85622937+aditya-upadhye@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:39:55 -0500 Subject: [PATCH] feat: add CloudWatch OTLP metrics ingestion (#7781) --- docs/services/cloudwatch.md | 18 +- pom.xml | 14 + .../aws/core/common/IamEnforcementFilter.java | 7 + .../floci/aws/core/common/IamOperation.java | 16 + .../common/OtlpMetricsAuthResponseFilter.java | 50 ++ .../core/common/ResolvedServiceCatalog.java | 3 +- .../cloudwatch/metrics/OtlpDescriptors.java | 197 +++++ .../metrics/OtlpMetricsController.java | 114 +++ .../metrics/OtlpMetricsDecoder.java | 72 ++ .../metrics/OtlpMetricsNativeSupport.java | 9 + .../metrics/OtlpMetricsResponses.java | 40 + .../metrics/OtlpMetricsService.java | 91 +++ .../metrics/OtlpMetricsValidation.java | 325 ++++++++ .../aws/services/iam/IamActionRegistry.java | 10 +- src/main/resources/application.yml | 1 + .../metrics/v1/metrics_service.proto | 79 ++ .../proto/common/v1/common.proto | 81 ++ .../proto/metrics/v1/metrics.proto | 691 ++++++++++++++++++ .../proto/resource/v1/resource.proto | 37 + ...QueryGetIamEnforcementIntegrationTest.java | 35 + .../metrics/OtlpMetricsDecoderTest.java | 75 ++ .../metrics/OtlpMetricsIntegrationTest.java | 242 ++++++ .../metrics/OtlpMetricsServiceTest.java | 115 +++ .../OtlpMetricsSignatureIntegrationTest.java | 87 +++ .../metrics/OtlpMetricsStorageReloadTest.java | 52 ++ .../metrics/OtlpMetricsValidationTest.java | 245 +++++++ .../iam/IamRestRouteCoverageTest.java | 3 +- tools/aws/regen_rest_routes.py | 1 + 28 files changed, 2706 insertions(+), 4 deletions(-) create mode 100644 src/main/java/io/floci/aws/core/common/IamOperation.java create mode 100644 src/main/java/io/floci/aws/core/common/OtlpMetricsAuthResponseFilter.java create mode 100644 src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpDescriptors.java create mode 100644 src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsController.java create mode 100644 src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsDecoder.java create mode 100644 src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsNativeSupport.java create mode 100644 src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsResponses.java create mode 100644 src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsService.java create mode 100644 src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsValidation.java create mode 100644 src/main/resources/proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto create mode 100644 src/main/resources/proto/opentelemetry/proto/common/v1/common.proto create mode 100644 src/main/resources/proto/opentelemetry/proto/metrics/v1/metrics.proto create mode 100644 src/main/resources/proto/opentelemetry/proto/resource/v1/resource.proto create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsDecoderTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsServiceTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsSignatureIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsStorageReloadTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsValidationTest.java diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 7085948afb..8155cb66a9 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -400,7 +400,23 @@ aws logs put-retention-policy \ ## CloudWatch Metrics {#metrics} -**Protocol:** Query (XML) and JSON 1.0 (both supported) +**Protocol:** Query (XML), JSON 1.0, and OTLP/HTTP. + +The OTLP HTTP metrics endpoint accepts `POST /v1/metrics` with `application/json` or +`application/x-protobuf`, optionally gzip-compressed. Requests are stored separately from classic +CloudWatch metrics, retaining their OTLP resource, scope and metric data. The uncompressed request +limit is 5 MiB and a request may contain at most 1,000 data points. Floci checks each datapoint's +timestamp, the limit of 150 resource, scope and datapoint attributes combined, and the 40,000-byte +metadata limit. Attribute strings are limited to 1,024 UTF-16 code units. Storage follows the +`cloudwatchmetrics` storage configuration. Metric querying through PromQL is not yet supported, and +the endpoint does not yet implement every CloudWatch OTLP validation rule. Invalid requests return OTLP `google.rpc.Status` +bodies. When only part of a request is invalid, Floci returns an OTLP partial-success response and +stores only the accepted datapoints. Empty or untyped metrics produce a partial-success message +without increasing the rejected datapoint count. +Stored batches expire 14 days after ingestion and are removed on a later ingestion in the same account +and region. Cleanup runs at most once per minute for each account and region. +With IAM enforcement enabled, requests require AWS credentials and the `cloudwatch:PutMetricData` +permission. Bearer-token authentication for this endpoint is not implemented. CloudWatch Query operations accept form-encoded POST requests and root GET requests with URL query parameters. GET uses the existing handlers, signature validation and IAM policy checks. A `monitoring` diff --git a/pom.xml b/pom.xml index c06fb5d11c..c6ce737b60 100644 --- a/pom.xml +++ b/pom.xml @@ -92,6 +92,20 @@ + + io.opentelemetry.proto + opentelemetry-proto + 1.3.2-alpha + test + + + com.google.protobuf + protobuf-java-util + + + com.google.api.grpc + proto-google-common-protos + software.amazon.awssdk quicksight diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 5f3fb382d1..3105a9fe3d 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -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 diff --git a/src/main/java/io/floci/aws/core/common/IamOperation.java b/src/main/java/io/floci/aws/core/common/IamOperation.java new file mode 100644 index 0000000000..fd4d321ca1 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/IamOperation.java @@ -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(); +} diff --git a/src/main/java/io/floci/aws/core/common/OtlpMetricsAuthResponseFilter.java b/src/main/java/io/floci/aws/core/common/OtlpMetricsAuthResponseFilter.java new file mode 100644 index 0000000000..23eff81879 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/OtlpMetricsAuthResponseFilter.java @@ -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."; + } +} diff --git a/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java index 409529bdbc..6f29ff0bff 100644 --- a/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java @@ -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", diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpDescriptors.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpDescriptors.java new file mode 100644 index 0000000000..8ca785de6b --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpDescriptors.java @@ -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 commonSchema = Map.of("opentelemetry.proto.common.v1/common.proto", commonText); + Map metricSchemas = Map.of( + "opentelemetry.proto.common.v1/common.proto", commonText, + "opentelemetry.proto.resource.v1/resource.proto", resourceText); + Map 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 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() {} +} diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsController.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsController.java new file mode 100644 index 0000000000..bf3b2133c6 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsController.java @@ -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 getList(DynamicMessage msg, FieldDescriptor field) { + return (List) msg.getField(field); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsDecoder.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsDecoder.java new file mode 100644 index 0000000000..ca74d413fa --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsDecoder.java @@ -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 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); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsNativeSupport.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsNativeSupport.java new file mode 100644 index 0000000000..d8d625cbd2 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsNativeSupport.java @@ -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 {} diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsResponses.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsResponses.java new file mode 100644 index 0000000000..01f4c76e5c --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsResponses.java @@ -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); + } + } +} diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsService.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsService.java new file mode 100644 index 0000000000..0aca37a0f2 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsService.java @@ -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 store; + private final RequestContext requestContext; + private final Clock clock; + private final Map 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>() {}, 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 requests(String region) { + return store.scan(key -> key.startsWith(region + "::")).stream() + .map(encoded -> Base64.getDecoder().decode(encoded)) + .toList(); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsValidation.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsValidation.java new file mode 100644 index 0000000000..fa7582e3cc --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsValidation.java @@ -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 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 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 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 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 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 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 filterMetric(DynamicMessage.Builder accepted, PointContext context) { + DynamicMessage metric = context.metric(); + List 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 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 resourceAttributes = getList(resourceProto, OtlpDescriptors.RESOURCE_ATTRIBUTES); + DynamicMessage scopeProto = getSubMessage(context.scope(), OtlpDescriptors.SCOPE_FIELD); + List 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 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 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 getList(DynamicMessage msg, FieldDescriptor field) { + return (List) msg.getField(field); + } + + private static DynamicMessage getSubMessage(DynamicMessage msg, FieldDescriptor field) { + return (DynamicMessage) msg.getField(field); + } +} diff --git a/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java b/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java index af9f3cab27..931c577c5f 100644 --- a/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java +++ b/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java @@ -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()); } /** diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 4c58ae6f91..32199f84fb 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -92,6 +92,7 @@ quarkus: - bedrock/*.yaml - eks/*.json - aws/*.json + - proto/**/*.proto - iam/service-linked-roles.tsv - cloudformation/*.json - redshift/*.sql diff --git a/src/main/resources/proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto b/src/main/resources/proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto new file mode 100644 index 0000000000..dd48f1ad3a --- /dev/null +++ b/src/main/resources/proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto @@ -0,0 +1,79 @@ +// Copyright 2019, OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package opentelemetry.proto.collector.metrics.v1; + +import "opentelemetry/proto/metrics/v1/metrics.proto"; + +option csharp_namespace = "OpenTelemetry.Proto.Collector.Metrics.V1"; +option java_multiple_files = true; +option java_package = "io.opentelemetry.proto.collector.metrics.v1"; +option java_outer_classname = "MetricsServiceProto"; +option go_package = "go.opentelemetry.io/proto/otlp/collector/metrics/v1"; + +// Service that can be used to push metrics between one Application +// instrumented with OpenTelemetry and a collector, or between a collector and a +// central collector. +service MetricsService { + // For performance reasons, it is recommended to keep this RPC + // alive for the entire life of the application. + rpc Export(ExportMetricsServiceRequest) returns (ExportMetricsServiceResponse) {} +} + +message ExportMetricsServiceRequest { + // An array of ResourceMetrics. + // For data coming from a single resource this array will typically contain one + // element. Intermediary nodes (such as OpenTelemetry Collector) that receive + // data from multiple origins typically batch the data before forwarding further and + // in that case this array will contain multiple elements. + repeated opentelemetry.proto.metrics.v1.ResourceMetrics resource_metrics = 1; +} + +message ExportMetricsServiceResponse { + // The details of a partially successful export request. + // + // If the request is only partially accepted + // (i.e. when the server accepts only parts of the data and rejects the rest) + // the server MUST initialize the `partial_success` field and MUST + // set the `rejected_` with the number of items it rejected. + // + // Servers MAY also make use of the `partial_success` field to convey + // warnings/suggestions to senders even when the request was fully accepted. + // In such cases, the `rejected_` MUST have a value of `0` and + // the `error_message` MUST be non-empty. + // + // A `partial_success` message with an empty value (rejected_ = 0 and + // `error_message` = "") is equivalent to it not being set/present. Senders + // SHOULD interpret it the same way as in the full success case. + ExportMetricsPartialSuccess partial_success = 1; +} + +message ExportMetricsPartialSuccess { + // The number of rejected data points. + // + // A `rejected_` field holding a `0` value indicates that the + // request was fully accepted. + int64 rejected_data_points = 1; + + // A developer-facing human-readable message in English. It should be used + // either to explain why the server rejected parts of the data during a partial + // success or to convey warnings/suggestions during a full success. The message + // should offer guidance on how users can address such issues. + // + // error_message is an optional field. An error_message with an empty value + // is equivalent to it not being set. + string error_message = 2; +} diff --git a/src/main/resources/proto/opentelemetry/proto/common/v1/common.proto b/src/main/resources/proto/opentelemetry/proto/common/v1/common.proto new file mode 100644 index 0000000000..ff8a21a1fa --- /dev/null +++ b/src/main/resources/proto/opentelemetry/proto/common/v1/common.proto @@ -0,0 +1,81 @@ +// Copyright 2019, OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package opentelemetry.proto.common.v1; + +option csharp_namespace = "OpenTelemetry.Proto.Common.V1"; +option java_multiple_files = true; +option java_package = "io.opentelemetry.proto.common.v1"; +option java_outer_classname = "CommonProto"; +option go_package = "go.opentelemetry.io/proto/otlp/common/v1"; + +// AnyValue is used to represent any type of attribute value. AnyValue may contain a +// primitive value such as a string or integer or it may contain an arbitrary nested +// object containing arrays, key-value lists and primitives. +message AnyValue { + // The value is one of the listed fields. It is valid for all values to be unspecified + // in which case this AnyValue is considered to be "empty". + oneof value { + string string_value = 1; + bool bool_value = 2; + int64 int_value = 3; + double double_value = 4; + ArrayValue array_value = 5; + KeyValueList kvlist_value = 6; + bytes bytes_value = 7; + } +} + +// ArrayValue is a list of AnyValue messages. We need ArrayValue as a message +// since oneof in AnyValue does not allow repeated fields. +message ArrayValue { + // Array of values. The array may be empty (contain 0 elements). + repeated AnyValue values = 1; +} + +// KeyValueList is a list of KeyValue messages. We need KeyValueList as a message +// since `oneof` in AnyValue does not allow repeated fields. Everywhere else where we need +// a list of KeyValue messages (e.g. in Span) we use `repeated KeyValue` directly to +// avoid unnecessary extra wrapping (which slows down the protocol). The 2 approaches +// are semantically equivalent. +message KeyValueList { + // A collection of key/value pairs of key-value pairs. The list may be empty (may + // contain 0 elements). + // The keys MUST be unique (it is not allowed to have more than one + // value with the same key). + repeated KeyValue values = 1; +} + +// KeyValue is a key-value pair that is used to store Span attributes, Link +// attributes, etc. +message KeyValue { + string key = 1; + AnyValue value = 2; +} + +// InstrumentationScope is a message representing the instrumentation scope information +// such as the fully qualified name and version. +message InstrumentationScope { + // An empty instrumentation scope name means the name is unknown. + string name = 1; + string version = 2; + + // Additional attributes that describe the scope. [Optional]. + // Attribute keys MUST be unique (it is not allowed to have more than one + // attribute with the same key). + repeated KeyValue attributes = 3; + uint32 dropped_attributes_count = 4; +} diff --git a/src/main/resources/proto/opentelemetry/proto/metrics/v1/metrics.proto b/src/main/resources/proto/opentelemetry/proto/metrics/v1/metrics.proto new file mode 100644 index 0000000000..19bb7ff8d5 --- /dev/null +++ b/src/main/resources/proto/opentelemetry/proto/metrics/v1/metrics.proto @@ -0,0 +1,691 @@ +// Copyright 2019, OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package opentelemetry.proto.metrics.v1; + +import "opentelemetry/proto/common/v1/common.proto"; +import "opentelemetry/proto/resource/v1/resource.proto"; + +option csharp_namespace = "OpenTelemetry.Proto.Metrics.V1"; +option java_multiple_files = true; +option java_package = "io.opentelemetry.proto.metrics.v1"; +option java_outer_classname = "MetricsProto"; +option go_package = "go.opentelemetry.io/proto/otlp/metrics/v1"; + +// MetricsData represents the metrics data that can be stored in a persistent +// storage, OR can be embedded by other protocols that transfer OTLP metrics +// data but do not implement the OTLP protocol. +// +// The main difference between this message and collector protocol is that +// in this message there will not be any "control" or "metadata" specific to +// OTLP protocol. +// +// When new fields are added into this message, the OTLP request MUST be updated +// as well. +message MetricsData { + // An array of ResourceMetrics. + // For data coming from a single resource this array will typically contain + // one element. Intermediary nodes that receive data from multiple origins + // typically batch the data before forwarding further and in that case this + // array will contain multiple elements. + repeated ResourceMetrics resource_metrics = 1; +} + +// A collection of ScopeMetrics from a Resource. +message ResourceMetrics { + reserved 1000; + + // The resource for the metrics in this message. + // If this field is not set then no resource info is known. + opentelemetry.proto.resource.v1.Resource resource = 1; + + // A list of metrics that originate from a resource. + repeated ScopeMetrics scope_metrics = 2; + + // The Schema URL, if known. This is the identifier of the Schema that the resource data + // is recorded in. To learn more about Schema URL see + // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url + // This schema_url applies to the data in the "resource" field. It does not apply + // to the data in the "scope_metrics" field which have their own schema_url field. + string schema_url = 3; +} + +// A collection of Metrics produced by an Scope. +message ScopeMetrics { + // The instrumentation scope information for the metrics in this message. + // Semantically when InstrumentationScope isn't set, it is equivalent with + // an empty instrumentation scope name (unknown). + opentelemetry.proto.common.v1.InstrumentationScope scope = 1; + + // A list of metrics that originate from an instrumentation library. + repeated Metric metrics = 2; + + // The Schema URL, if known. This is the identifier of the Schema that the metric data + // is recorded in. To learn more about Schema URL see + // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url + // This schema_url applies to all metrics in the "metrics" field. + string schema_url = 3; +} + +// Defines a Metric which has one or more timeseries. The following is a +// brief summary of the Metric data model. For more details, see: +// +// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md +// +// +// The data model and relation between entities is shown in the +// diagram below. Here, "DataPoint" is the term used to refer to any +// one of the specific data point value types, and "points" is the term used +// to refer to any one of the lists of points contained in the Metric. +// +// - Metric is composed of a metadata and data. +// - Metadata part contains a name, description, unit. +// - Data is one of the possible types (Sum, Gauge, Histogram, Summary). +// - DataPoint contains timestamps, attributes, and one of the possible value type +// fields. +// +// Metric +// +------------+ +// |name | +// |description | +// |unit | +------------------------------------+ +// |data |---> |Gauge, Sum, Histogram, Summary, ... | +// +------------+ +------------------------------------+ +// +// Data [One of Gauge, Sum, Histogram, Summary, ...] +// +-----------+ +// |... | // Metadata about the Data. +// |points |--+ +// +-----------+ | +// | +---------------------------+ +// | |DataPoint 1 | +// v |+------+------+ +------+ | +// +-----+ ||label |label |...|label | | +// | 1 |-->||value1|value2|...|valueN| | +// +-----+ |+------+------+ +------+ | +// | . | |+-----+ | +// | . | ||value| | +// | . | |+-----+ | +// | . | +---------------------------+ +// | . | . +// | . | . +// | . | . +// | . | +---------------------------+ +// | . | |DataPoint M | +// +-----+ |+------+------+ +------+ | +// | M |-->||label |label |...|label | | +// +-----+ ||value1|value2|...|valueN| | +// |+------+------+ +------+ | +// |+-----+ | +// ||value| | +// |+-----+ | +// +---------------------------+ +// +// Each distinct type of DataPoint represents the output of a specific +// aggregation function, the result of applying the DataPoint's +// associated function of to one or more measurements. +// +// All DataPoint types have three common fields: +// - Attributes includes key-value pairs associated with the data point +// - TimeUnixNano is required, set to the end time of the aggregation +// - StartTimeUnixNano is optional, but strongly encouraged for DataPoints +// having an AggregationTemporality field, as discussed below. +// +// Both TimeUnixNano and StartTimeUnixNano values are expressed as +// UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970. +// +// # TimeUnixNano +// +// This field is required, having consistent interpretation across +// DataPoint types. TimeUnixNano is the moment corresponding to when +// the data point's aggregate value was captured. +// +// Data points with the 0 value for TimeUnixNano SHOULD be rejected +// by consumers. +// +// # StartTimeUnixNano +// +// StartTimeUnixNano in general allows detecting when a sequence of +// observations is unbroken. This field indicates to consumers the +// start time for points with cumulative and delta +// AggregationTemporality, and it should be included whenever possible +// to support correct rate calculation. Although it may be omitted +// when the start time is truly unknown, setting StartTimeUnixNano is +// strongly encouraged. +message Metric { + reserved 4, 6, 8; + + // name of the metric. + string name = 1; + + // description of the metric, which can be used in documentation. + string description = 2; + + // unit in which the metric value is reported. Follows the format + // described by http://unitsofmeasure.org/ucum.html. + string unit = 3; + + // Data determines the aggregation type (if any) of the metric, what is the + // reported value type for the data points, as well as the relatationship to + // the time interval over which they are reported. + oneof data { + Gauge gauge = 5; + Sum sum = 7; + Histogram histogram = 9; + ExponentialHistogram exponential_histogram = 10; + Summary summary = 11; + } + + // Additional metadata attributes that describe the metric. [Optional]. + // Attributes are non-identifying. + // Consumers SHOULD NOT need to be aware of these attributes. + // These attributes MAY be used to encode information allowing + // for lossless roundtrip translation to / from another data model. + // Attribute keys MUST be unique (it is not allowed to have more than one + // attribute with the same key). + repeated opentelemetry.proto.common.v1.KeyValue metadata = 12; +} + +// Gauge represents the type of a scalar metric that always exports the +// "current value" for every data point. It should be used for an "unknown" +// aggregation. +// +// A Gauge does not support different aggregation temporalities. Given the +// aggregation is unknown, points cannot be combined using the same +// aggregation, regardless of aggregation temporalities. Therefore, +// AggregationTemporality is not included. Consequently, this also means +// "StartTimeUnixNano" is ignored for all data points. +message Gauge { + repeated NumberDataPoint data_points = 1; +} + +// Sum represents the type of a scalar metric that is calculated as a sum of all +// reported measurements over a time interval. +message Sum { + repeated NumberDataPoint data_points = 1; + + // aggregation_temporality describes if the aggregator reports delta changes + // since last report time, or cumulative changes since a fixed start time. + AggregationTemporality aggregation_temporality = 2; + + // If "true" means that the sum is monotonic. + bool is_monotonic = 3; +} + +// Histogram represents the type of a metric that is calculated by aggregating +// as a Histogram of all reported measurements over a time interval. +message Histogram { + repeated HistogramDataPoint data_points = 1; + + // aggregation_temporality describes if the aggregator reports delta changes + // since last report time, or cumulative changes since a fixed start time. + AggregationTemporality aggregation_temporality = 2; +} + +// ExponentialHistogram represents the type of a metric that is calculated by aggregating +// as a ExponentialHistogram of all reported double measurements over a time interval. +message ExponentialHistogram { + repeated ExponentialHistogramDataPoint data_points = 1; + + // aggregation_temporality describes if the aggregator reports delta changes + // since last report time, or cumulative changes since a fixed start time. + AggregationTemporality aggregation_temporality = 2; +} + +// Summary metric data are used to convey quantile summaries, +// a Prometheus (see: https://prometheus.io/docs/concepts/metric_types/#summary) +// and OpenMetrics (see: https://github.com/OpenObservability/OpenMetrics/blob/4dbf6075567ab43296eed941037c12951faafb92/protos/prometheus.proto#L45) +// data type. These data points cannot always be merged in a meaningful way. +// While they can be useful in some applications, histogram data points are +// recommended for new applications. +message Summary { + repeated SummaryDataPoint data_points = 1; +} + +// AggregationTemporality defines how a metric aggregator reports aggregated +// values. It describes how those values relate to the time interval over +// which they are aggregated. +enum AggregationTemporality { + // UNSPECIFIED is the default AggregationTemporality, it MUST not be used. + AGGREGATION_TEMPORALITY_UNSPECIFIED = 0; + + // DELTA is an AggregationTemporality for a metric aggregator which reports + // changes since last report time. Successive metrics contain aggregation of + // values from continuous and non-overlapping intervals. + // + // The values for a DELTA metric are based only on the time interval + // associated with one measurement cycle. There is no dependency on + // previous measurements like is the case for CUMULATIVE metrics. + // + // For example, consider a system measuring the number of requests that + // it receives and reports the sum of these requests every second as a + // DELTA metric: + // + // 1. The system starts receiving at time=t_0. + // 2. A request is received, the system measures 1 request. + // 3. A request is received, the system measures 1 request. + // 4. A request is received, the system measures 1 request. + // 5. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_0 to + // t_0+1 with a value of 3. + // 6. A request is received, the system measures 1 request. + // 7. A request is received, the system measures 1 request. + // 8. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_0+1 to + // t_0+2 with a value of 2. + AGGREGATION_TEMPORALITY_DELTA = 1; + + // CUMULATIVE is an AggregationTemporality for a metric aggregator which + // reports changes since a fixed start time. This means that current values + // of a CUMULATIVE metric depend on all previous measurements since the + // start time. Because of this, the sender is required to retain this state + // in some form. If this state is lost or invalidated, the CUMULATIVE metric + // values MUST be reset and a new fixed start time following the last + // reported measurement time sent MUST be used. + // + // For example, consider a system measuring the number of requests that + // it receives and reports the sum of these requests every second as a + // CUMULATIVE metric: + // + // 1. The system starts receiving at time=t_0. + // 2. A request is received, the system measures 1 request. + // 3. A request is received, the system measures 1 request. + // 4. A request is received, the system measures 1 request. + // 5. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_0 to + // t_0+1 with a value of 3. + // 6. A request is received, the system measures 1 request. + // 7. A request is received, the system measures 1 request. + // 8. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_0 to + // t_0+2 with a value of 5. + // 9. The system experiences a fault and loses state. + // 10. The system recovers and resumes receiving at time=t_1. + // 11. A request is received, the system measures 1 request. + // 12. The 1 second collection cycle ends. A metric is exported for the + // number of requests received over the interval of time t_1 to + // t_0+1 with a value of 1. + // + // Note: Even though, when reporting changes since last report time, using + // CUMULATIVE is valid, it is not recommended. This may cause problems for + // systems that do not use start_time to determine when the aggregation + // value was reset (e.g. Prometheus). + AGGREGATION_TEMPORALITY_CUMULATIVE = 2; +} + +// DataPointFlags is defined as a protobuf 'uint32' type and is to be used as a +// bit-field representing 32 distinct boolean flags. Each flag defined in this +// enum is a bit-mask. To test the presence of a single flag in the flags of +// a data point, for example, use an expression like: +// +// (point.flags & DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK) == DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK +// +enum DataPointFlags { + // The zero value for the enum. Should not be used for comparisons. + // Instead use bitwise "and" with the appropriate mask as shown above. + DATA_POINT_FLAGS_DO_NOT_USE = 0; + + // This DataPoint is valid but has no recorded value. This value + // SHOULD be used to reflect explicitly missing data in a series, as + // for an equivalent to the Prometheus "staleness marker". + DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK = 1; + + // Bits 2-31 are reserved for future use. +} + +// NumberDataPoint is a single data point in a timeseries that describes the +// time-varying scalar value of a metric. +message NumberDataPoint { + reserved 1; + + // The set of key/value pairs that uniquely identify the timeseries from + // where this point belongs. The list may be empty (may contain 0 elements). + // Attribute keys MUST be unique (it is not allowed to have more than one + // attribute with the same key). + repeated opentelemetry.proto.common.v1.KeyValue attributes = 7; + + // StartTimeUnixNano is optional but strongly encouraged, see the + // the detailed comments above Metric. + // + // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January + // 1970. + fixed64 start_time_unix_nano = 2; + + // TimeUnixNano is required, see the detailed comments above Metric. + // + // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January + // 1970. + fixed64 time_unix_nano = 3; + + // The value itself. A point is considered invalid when one of the recognized + // value fields is not present inside this oneof. + oneof value { + double as_double = 4; + sfixed64 as_int = 6; + } + + // (Optional) List of exemplars collected from + // measurements that were used to form the data point + repeated Exemplar exemplars = 5; + + // Flags that apply to this specific data point. See DataPointFlags + // for the available flags and their meaning. + uint32 flags = 8; +} + +// HistogramDataPoint is a single data point in a timeseries that describes the +// time-varying values of a Histogram. A Histogram contains summary statistics +// for a population of values, it may optionally contain the distribution of +// those values across a set of buckets. +// +// If the histogram contains the distribution of values, then both +// "explicit_bounds" and "bucket counts" fields must be defined. +// If the histogram does not contain the distribution of values, then both +// "explicit_bounds" and "bucket_counts" must be omitted and only "count" and +// "sum" are known. +message HistogramDataPoint { + reserved 1; + + // The set of key/value pairs that uniquely identify the timeseries from + // where this point belongs. The list may be empty (may contain 0 elements). + // Attribute keys MUST be unique (it is not allowed to have more than one + // attribute with the same key). + repeated opentelemetry.proto.common.v1.KeyValue attributes = 9; + + // StartTimeUnixNano is optional but strongly encouraged, see the + // the detailed comments above Metric. + // + // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January + // 1970. + fixed64 start_time_unix_nano = 2; + + // TimeUnixNano is required, see the detailed comments above Metric. + // + // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January + // 1970. + fixed64 time_unix_nano = 3; + + // count is the number of values in the population. Must be non-negative. This + // value must be equal to the sum of the "count" fields in buckets if a + // histogram is provided. + fixed64 count = 4; + + // sum of the values in the population. If count is zero then this field + // must be zero. + // + // Note: Sum should only be filled out when measuring non-negative discrete + // events, and is assumed to be monotonic over the values of these events. + // Negative events *can* be recorded, but sum should not be filled out when + // doing so. This is specifically to enforce compatibility w/ OpenMetrics, + // see: https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#histogram + optional double sum = 5; + + // bucket_counts is an optional field contains the count values of histogram + // for each bucket. + // + // The sum of the bucket_counts must equal the value in the count field. + // + // The number of elements in bucket_counts array must be by one greater than + // the number of elements in explicit_bounds array. + repeated fixed64 bucket_counts = 6; + + // explicit_bounds specifies buckets with explicitly defined bounds for values. + // + // The boundaries for bucket at index i are: + // + // (-infinity, explicit_bounds[i]] for i == 0 + // (explicit_bounds[i-1], explicit_bounds[i]] for 0 < i < size(explicit_bounds) + // (explicit_bounds[i-1], +infinity) for i == size(explicit_bounds) + // + // The values in the explicit_bounds array must be strictly increasing. + // + // Histogram buckets are inclusive of their upper boundary, except the last + // bucket where the boundary is at infinity. This format is intentionally + // compatible with the OpenMetrics histogram definition. + repeated double explicit_bounds = 7; + + // (Optional) List of exemplars collected from + // measurements that were used to form the data point + repeated Exemplar exemplars = 8; + + // Flags that apply to this specific data point. See DataPointFlags + // for the available flags and their meaning. + uint32 flags = 10; + + // min is the minimum value over (start_time, end_time]. + optional double min = 11; + + // max is the maximum value over (start_time, end_time]. + optional double max = 12; +} + +// ExponentialHistogramDataPoint is a single data point in a timeseries that describes the +// time-varying values of a ExponentialHistogram of double values. A ExponentialHistogram contains +// summary statistics for a population of values, it may optionally contain the +// distribution of those values across a set of buckets. +// +message ExponentialHistogramDataPoint { + // The set of key/value pairs that uniquely identify the timeseries from + // where this point belongs. The list may be empty (may contain 0 elements). + // Attribute keys MUST be unique (it is not allowed to have more than one + // attribute with the same key). + repeated opentelemetry.proto.common.v1.KeyValue attributes = 1; + + // StartTimeUnixNano is optional but strongly encouraged, see the + // the detailed comments above Metric. + // + // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January + // 1970. + fixed64 start_time_unix_nano = 2; + + // TimeUnixNano is required, see the detailed comments above Metric. + // + // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January + // 1970. + fixed64 time_unix_nano = 3; + + // count is the number of values in the population. Must be + // non-negative. This value must be equal to the sum of the "bucket_counts" + // values in the positive and negative Buckets plus the "zero_count" field. + fixed64 count = 4; + + // sum of the values in the population. If count is zero then this field + // must be zero. + // + // Note: Sum should only be filled out when measuring non-negative discrete + // events, and is assumed to be monotonic over the values of these events. + // Negative events *can* be recorded, but sum should not be filled out when + // doing so. This is specifically to enforce compatibility w/ OpenMetrics, + // see: https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#histogram + optional double sum = 5; + + // scale describes the resolution of the histogram. Boundaries are + // located at powers of the base, where: + // + // base = (2^(2^-scale)) + // + // The histogram bucket identified by `index`, a signed integer, + // contains values that are greater than (base^index) and + // less than or equal to (base^(index+1)). + // + // The positive and negative ranges of the histogram are expressed + // separately. Negative values are mapped by their absolute value + // into the negative range using the same scale as the positive range. + // + // scale is not restricted by the protocol, as the permissible + // values depend on the range of the data. + sint32 scale = 6; + + // zero_count is the count of values that are either exactly zero or + // within the region considered zero by the instrumentation at the + // tolerated degree of precision. This bucket stores values that + // cannot be expressed using the standard exponential formula as + // well as values that have been rounded to zero. + // + // Implementations MAY consider the zero bucket to have probability + // mass equal to (zero_count / count). + fixed64 zero_count = 7; + + // positive carries the positive range of exponential bucket counts. + Buckets positive = 8; + + // negative carries the negative range of exponential bucket counts. + Buckets negative = 9; + + // Buckets are a set of bucket counts, encoded in a contiguous array + // of counts. + message Buckets { + // Offset is the bucket index of the first entry in the bucket_counts array. + // + // Note: This uses a varint encoding as a simple form of compression. + sint32 offset = 1; + + // bucket_counts is an array of count values, where bucket_counts[i] carries + // the count of the bucket at index (offset+i). bucket_counts[i] is the count + // of values greater than base^(offset+i) and less than or equal to + // base^(offset+i+1). + // + // Note: By contrast, the explicit HistogramDataPoint uses + // fixed64. This field is expected to have many buckets, + // especially zeros, so uint64 has been selected to ensure + // varint encoding. + repeated uint64 bucket_counts = 2; + } + + // Flags that apply to this specific data point. See DataPointFlags + // for the available flags and their meaning. + uint32 flags = 10; + + // (Optional) List of exemplars collected from + // measurements that were used to form the data point + repeated Exemplar exemplars = 11; + + // min is the minimum value over (start_time, end_time]. + optional double min = 12; + + // max is the maximum value over (start_time, end_time]. + optional double max = 13; + + // ZeroThreshold may be optionally set to convey the width of the zero + // region. Where the zero region is defined as the closed interval + // [-ZeroThreshold, ZeroThreshold]. + // When ZeroThreshold is 0, zero count bucket stores values that cannot be + // expressed using the standard exponential formula as well as values that + // have been rounded to zero. + double zero_threshold = 14; +} + +// SummaryDataPoint is a single data point in a timeseries that describes the +// time-varying values of a Summary metric. +message SummaryDataPoint { + reserved 1; + + // The set of key/value pairs that uniquely identify the timeseries from + // where this point belongs. The list may be empty (may contain 0 elements). + // Attribute keys MUST be unique (it is not allowed to have more than one + // attribute with the same key). + repeated opentelemetry.proto.common.v1.KeyValue attributes = 7; + + // StartTimeUnixNano is optional but strongly encouraged, see the + // the detailed comments above Metric. + // + // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January + // 1970. + fixed64 start_time_unix_nano = 2; + + // TimeUnixNano is required, see the detailed comments above Metric. + // + // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January + // 1970. + fixed64 time_unix_nano = 3; + + // count is the number of values in the population. Must be non-negative. + fixed64 count = 4; + + // sum of the values in the population. If count is zero then this field + // must be zero. + // + // Note: Sum should only be filled out when measuring non-negative discrete + // events, and is assumed to be monotonic over the values of these events. + // Negative events *can* be recorded, but sum should not be filled out when + // doing so. This is specifically to enforce compatibility w/ OpenMetrics, + // see: https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#summary + double sum = 5; + + // Represents the value at a given quantile of a distribution. + // + // To record Min and Max values following conventions are used: + // - The 1.0 quantile is equivalent to the maximum value observed. + // - The 0.0 quantile is equivalent to the minimum value observed. + // + // See the following issue for more context: + // https://github.com/open-telemetry/opentelemetry-proto/issues/125 + message ValueAtQuantile { + // The quantile of a distribution. Must be in the interval + // [0.0, 1.0]. + double quantile = 1; + + // The value at the given quantile of a distribution. + // + // Quantile values must NOT be negative. + double value = 2; + } + + // (Optional) list of values at different quantiles of the distribution calculated + // from the current snapshot. The quantiles must be strictly increasing. + repeated ValueAtQuantile quantile_values = 6; + + // Flags that apply to this specific data point. See DataPointFlags + // for the available flags and their meaning. + uint32 flags = 8; +} + +// A representation of an exemplar, which is a sample input measurement. +// Exemplars also hold information about the environment when the measurement +// was recorded, for example the span and trace ID of the active span when the +// exemplar was recorded. +message Exemplar { + reserved 1; + + // The set of key/value pairs that were filtered out by the aggregator, but + // recorded alongside the original measurement. Only key/value pairs that were + // filtered out by the aggregator should be included + repeated opentelemetry.proto.common.v1.KeyValue filtered_attributes = 7; + + // time_unix_nano is the exact time when this exemplar was recorded + // + // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January + // 1970. + fixed64 time_unix_nano = 2; + + // The value of the measurement that was recorded. An exemplar is + // considered invalid when one of the recognized value fields is not present + // inside this oneof. + oneof value { + double as_double = 3; + sfixed64 as_int = 6; + } + + // (Optional) Span ID of the exemplar trace. + // span_id may be missing if the measurement is not recorded inside a trace + // or if the trace is not sampled. + bytes span_id = 4; + + // (Optional) Trace ID of the exemplar trace. + // trace_id may be missing if the measurement is not recorded inside a trace + // or if the trace is not sampled. + bytes trace_id = 5; +} diff --git a/src/main/resources/proto/opentelemetry/proto/resource/v1/resource.proto b/src/main/resources/proto/opentelemetry/proto/resource/v1/resource.proto new file mode 100644 index 0000000000..6637560bc3 --- /dev/null +++ b/src/main/resources/proto/opentelemetry/proto/resource/v1/resource.proto @@ -0,0 +1,37 @@ +// Copyright 2019, OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package opentelemetry.proto.resource.v1; + +import "opentelemetry/proto/common/v1/common.proto"; + +option csharp_namespace = "OpenTelemetry.Proto.Resource.V1"; +option java_multiple_files = true; +option java_package = "io.opentelemetry.proto.resource.v1"; +option java_outer_classname = "ResourceProto"; +option go_package = "go.opentelemetry.io/proto/otlp/resource/v1"; + +// Resource information. +message Resource { + // Set of attributes that describe the resource. + // Attribute keys MUST be unique (it is not allowed to have more than one + // attribute with the same key). + repeated opentelemetry.proto.common.v1.KeyValue attributes = 1; + + // dropped_attributes_count is the number of dropped attributes. If the value is 0, then + // no attributes were dropped. + uint32 dropped_attributes_count = 2; +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchQueryGetIamEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchQueryGetIamEnforcementIntegrationTest.java index e7ff56e672..8c6ee683e2 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchQueryGetIamEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchQueryGetIamEnforcementIntegrationTest.java @@ -1,5 +1,6 @@ package io.floci.aws.services.cloudwatch.metrics; +import com.google.rpc.Status; import io.floci.aws.testing.EnforcementFixtures; import io.floci.aws.testing.IamEnforcementProfile; import io.floci.aws.testing.PartitionCleanup; @@ -25,6 +26,7 @@ import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; @QuarkusTest @TestProfile(IamEnforcementProfile.class) @@ -89,6 +91,39 @@ class CloudWatchQueryGetIamEnforcementIntegrationTest { .body(not(containsString(namespace))); } + @Test + void otlpIngestionRequiresPutMetricData() throws Exception { + given().contentType("application/json").body("{}").post("/v1/metrics").then().statusCode(403) + .body("code", equalTo(7)).body("message", equalTo("Request is missing Authentication Token")); + byte[] unsigned = given().contentType("application/x-protobuf").body(new byte[] {10, 0}) + .post("/v1/metrics").then().statusCode(403).extract().asByteArray(); + assertEquals(7, Status.parseFrom(unsigned).getCode()); + given().header("Authorization", "Bearer invalid").contentType("application/json") + .body("{}").post("/v1/metrics").then().statusCode(403).body("code", equalTo(7)); + String user = "otlp-" + UUID.randomUUID(); + String admin = auth("000000000000", "iam"); + String accessKey = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), admin, user).accessKeyId(); + for (String path : new String[] {"/v1/metrics", "/v1/metrics;ignored=yes", "/v1;ignored=yes/metrics", + "/v1/%6detrics"}) { + given().urlEncodingEnabled(false).contentType("application/json").body("{}").post(path) + .then().statusCode(403).body("code", equalTo(7)); + given().urlEncodingEnabled(false).header("Authorization", auth(accessKey, "monitoring")) + .contentType("application/json").body("{}").post(path).then().statusCode(403) + .body("code", equalTo(7)); + } + given().header("Authorization", admin).contentType("application/x-www-form-urlencoded") + .formParam("Action", "PutUserPolicy").formParam("Version", "2010-05-08") + .formParam("UserName", user).formParam("PolicyName", "otlp") + .formParam("PolicyDocument", """ + {"Version":"2012-10-17","Statement":[{ + "Effect":"Allow","Action":"cloudwatch:PutMetricData","Resource":"*" + }]} + """) + .post("/").then().statusCode(200); + given().header("Authorization", auth(accessKey, "monitoring")) + .contentType("application/json").body("{}").post("/v1/metrics").then().statusCode(200); + } + @Test void internalRouteCannotBeCalledDirectly() { given().header("Authorization", auth("000000000000", "monitoring")) diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsDecoderTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsDecoderTest.java new file mode 100644 index 0000000000..f5a3180fb5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsDecoderTest.java @@ -0,0 +1,75 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import com.google.protobuf.DynamicMessage; +import com.google.protobuf.InvalidProtocolBufferException; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.opentelemetry.proto.metrics.v1.Metric; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.HexFormat; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class OtlpMetricsDecoderTest { + + private final OtlpMetricsDecoder decoder = new OtlpMetricsDecoder(); + + @Test + void jsonAndProtobufPreserveMetricData() throws Exception { + String json = """ + {"resourceMetrics":[{"resource":{"attributes":[{"key":"service.name", + "value":{"stringValue":"checkout"}}]},"scopeMetrics":[{"scope":{"name":"app"}, + "metrics":[{"name":"requests","sum":{"aggregationTemporality":2,"isMonotonic":true, + "dataPoints":[{"timeUnixNano":"1700000000123456789","asInt":"42"}]}}]}]}]} + """; + DynamicMessage decoded = decoder.decodeJson(json.getBytes(StandardCharsets.UTF_8)); + DynamicMessage roundTrip = decoder.decodeProtobuf(decoded.toByteArray()); + assertEquals(decoded, roundTrip); + ExportMetricsServiceRequest parsed = ExportMetricsServiceRequest.parseFrom(roundTrip.toByteArray()); + assertEquals("checkout", parsed.getResourceMetrics(0).getResource().getAttributes(0) + .getValue().getStringValue()); + assertEquals("app", parsed.getResourceMetrics(0).getScopeMetrics(0).getScope().getName()); + Metric metric = parsed.getResourceMetrics(0).getScopeMetrics(0).getMetrics(0); + assertEquals("requests", metric.getName()); + assertEquals(1700000000123456789L, metric.getSum().getDataPoints(0).getTimeUnixNano()); + assertEquals(42L, metric.getSum().getDataPoints(0).getAsInt()); + } + + @Test + void decodesHexEncodedExemplarIdentifiers() throws Exception { + String json = """ + {"resourceMetrics":[{"scopeMetrics":[{"metrics":[{"name":"latency","histogram":{ + "dataPoints":[{"exemplars":[{"traceId":"5B8EFFF798038103D269B633813FC60C", + "spanId":"0123456789abcdef","asDouble":2}]}]}}]}]}]} + """; + DynamicMessage decoded = decoder.decodeJson(json.getBytes(StandardCharsets.UTF_8)); + ExportMetricsServiceRequest request = ExportMetricsServiceRequest.parseFrom(decoded.toByteArray()); + Metric metric = request.getResourceMetrics(0).getScopeMetrics(0).getMetrics(0); + assertEquals("5b8efff798038103d269b633813fc60c", HexFormat.of().formatHex( + metric.getHistogram().getDataPoints(0).getExemplars(0).getTraceId().toByteArray())); + assertEquals("0123456789abcdef", HexFormat.of().formatHex( + metric.getHistogram().getDataPoints(0).getExemplars(0).getSpanId().toByteArray())); + assertEquals(decoded, decoder.decodeProtobuf(decoded.toByteArray())); + String invalid = json.replace("0123456789abcdef", "not-hex"); + assertThrows(InvalidProtocolBufferException.class, + () -> decoder.decodeJson(invalid.getBytes(StandardCharsets.UTF_8))); + } + + @Test + void rejectsMalformedAndEmptyBodies() { + assertThrows(InvalidProtocolBufferException.class, () -> decoder.decodeJson(new byte[0])); + assertThrows(InvalidProtocolBufferException.class, () -> decoder.decodeJson("{".getBytes(StandardCharsets.UTF_8))); + assertThrows(InvalidProtocolBufferException.class, () -> decoder.decodeProtobuf(new byte[0])); + assertThrows(InvalidProtocolBufferException.class, () -> decoder.decodeProtobuf(new byte[] {(byte) 0xff})); + } + + @Test + @SuppressWarnings("unchecked") + void acceptsEmptyJsonRequest() throws Exception { + DynamicMessage result = decoder.decodeJson("{}".getBytes(StandardCharsets.UTF_8)); + assertEquals(0, ((List) result.getField(OtlpDescriptors.RESOURCE_METRICS_LIST)).size()); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsIntegrationTest.java new file mode 100644 index 0000000000..a7ac86a562 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsIntegrationTest.java @@ -0,0 +1,242 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.rpc.Status; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse; +import io.opentelemetry.proto.common.v1.AnyValue; +import io.opentelemetry.proto.common.v1.KeyValue; +import io.opentelemetry.proto.metrics.v1.AggregationTemporality; +import io.opentelemetry.proto.metrics.v1.ExponentialHistogram; +import io.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint; +import io.opentelemetry.proto.metrics.v1.Gauge; +import io.opentelemetry.proto.metrics.v1.Histogram; +import io.opentelemetry.proto.metrics.v1.HistogramDataPoint; +import io.opentelemetry.proto.metrics.v1.Metric; +import io.opentelemetry.proto.metrics.v1.NumberDataPoint; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import io.opentelemetry.proto.metrics.v1.ScopeMetrics; +import io.opentelemetry.proto.metrics.v1.Sum; +import io.opentelemetry.proto.metrics.v1.Summary; +import io.opentelemetry.proto.metrics.v1.SummaryDataPoint; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.stream.Stream; +import java.util.zip.GZIPOutputStream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class OtlpMetricsIntegrationTest { + + @Inject + OtlpMetricsService service; + + @Test + void ingestsJsonAndCompressedProtobuf() throws Exception { + String name = "requests_" + UUID.randomUUID().toString().replace("-", ""); + long timestamp = Instant.now().toEpochMilli() * 1_000_000L; + String json = """ + {"resourceMetrics":[{"resource":{"attributes":[{"key":"service.name", + "value":{"stringValue":"checkout"}}]},"scopeMetrics":[{"scope":{"name":"app"}, + "metrics":[{"name":"%s","gauge":{"dataPoints":[{"timeUnixNano":"%d", + "asDouble":1.5}]}}]}]}]} + """.formatted(name, timestamp); + byte[] payload = json.getBytes(StandardCharsets.UTF_8); + byte[] requestBytes = new OtlpMetricsDecoder().decodeJson(payload).toByteArray(); + given().contentType("application/json").body(payload).post("/v1/metrics").then().statusCode(200); + ByteArrayOutputStream compressed = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(compressed)) { + gzip.write(requestBytes); + } + given().contentType("application/x-protobuf").header("Content-Encoding", "gzip") + .body(compressed.toByteArray()).post("/v1/metrics").then().statusCode(200); + long count = service.requests("us-east-1").stream().filter(b -> Arrays.equals(b, requestBytes)).count(); + assertTrue(count >= 2); + } + + @Test + void rejectsInvalidBodiesAndContentTypes() throws Exception { + given().contentType("application/json").body("{").post("/v1/metrics").then().statusCode(400) + .body("code", equalTo(3)).body("message", equalTo("Bad request.")); + byte[] errorBody = given().contentType("application/x-protobuf").body(new byte[0]) + .post("/v1/metrics").then().statusCode(400).extract().asByteArray(); + assertEquals(3, Status.parseFrom(errorBody).getCode()); + given().contentType("text/plain").body("{}").post("/v1/metrics").then().statusCode(415); + given().contentType("application/json").header("Content-Encoding", "gzip").body("not gzip") + .post("/v1/metrics").then().statusCode(400); + } + + @Test + void rejectsRequestsWithTooManyDataPoints() throws Exception { + Gauge.Builder gauge = Gauge.newBuilder(); + for (int i = 0; i < 1001; i++) { + gauge.addDataPoints(NumberDataPoint.newBuilder().setAsInt(i)); + } + ExportMetricsServiceRequest request = ExportMetricsServiceRequest.newBuilder() + .addResourceMetrics(ResourceMetrics.newBuilder().addScopeMetrics(ScopeMetrics.newBuilder() + .addMetrics(Metric.newBuilder().setName("too_many").setGauge(gauge)))).build(); + byte[] errorBody = given().contentType("application/x-protobuf").body(request.toByteArray()) + .post("/v1/metrics").then().statusCode(400).extract().asByteArray(); + Status status = Status.parseFrom(errorBody); + assertEquals(3, status.getCode()); + assertEquals("Maximum number of datapoints per request exceeded: 1000.", status.getMessage()); + } + + @Test + void rejectsAnOldPointAndStoresTheValidPoint() { + String name = "partial_" + UUID.randomUUID().toString().replace("-", ""); + long now = Instant.now().toEpochMilli() * 1_000_000L; + String json = """ + {"resourceMetrics":[{"resource":{"attributes":[{"key":"service.name", + "value":{"stringValue":"checkout"}}]},"scopeMetrics":[{"scope":{"name":"app"}, + "metrics":[{"name":"%s","gauge":{"dataPoints":[{"timeUnixNano":"%d","asDouble":1}, + {"timeUnixNano":"%d","asDouble":2}]}}]}]}]} + """.formatted(name, now, now - 30L * 24 * 60 * 60 * 1_000_000_000); + long old = now - 30L * 24 * 60 * 60 * 1_000_000_000; + given().contentType("application/json").body(json).post("/v1/metrics").then().statusCode(200) + .body("partialSuccess.rejectedDataPoints", equalTo("1")) + .body("partialSuccess.errorMessage", equalTo("TimeUnixNano " + old + + " is too far in the past for metric '" + name + + "' for resource where service.name='checkout' at " + + "[ResourceMetrics.1.ScopeMetrics.1.Metrics.1.Datapoint.2].")); + assertTrue(metricsStream(service.requests("us-east-1")) + .filter(metric -> name.equals(metric.getName())) + .anyMatch(metric -> metric.getGauge().getDataPointsCount() == 1)); + } + + @Test + void rejectsAnOverlongResourceAttribute() { + String json = """ + {"resourceMetrics":[{"resource":{"attributes":[{"key":"service.name", + "value":{"stringValue":"%s"}}]},"scopeMetrics":[{"metrics":[{"name":"requests", + "gauge":{"dataPoints":[{"timeUnixNano":"%d","asDouble":1}]}}]}]}]} + """.formatted("x".repeat(1025), Instant.now().toEpochMilli() * 1_000_000L); + given().contentType("application/json").body(json).post("/v1/metrics").then().statusCode(400) + .body("code", equalTo(3)) + .body("message", equalTo("Attribute string value exceeds maximum length: 1024 " + + "[ResourceMetrics.1] (1 datapoint rejected).")); + } + + @Test + void reportsPartialSuccessForADataPointWithTooManyAttributes() throws Exception { + String name = "labels_" + UUID.randomUUID().toString().replace("-", ""); + NumberDataPoint.Builder valid = NumberDataPoint.newBuilder() + .setTimeUnixNano(Instant.now().toEpochMilli() * 1_000_000L).setAsDouble(1); + NumberDataPoint.Builder invalid = valid.clone(); + for (int i = 0; i < 151; i++) { + invalid.addAttributes(KeyValue.newBuilder().setKey("attr" + i) + .setValue(AnyValue.newBuilder().setStringValue("v"))); + } + ExportMetricsServiceRequest request = ExportMetricsServiceRequest.newBuilder() + .addResourceMetrics(ResourceMetrics.newBuilder().addScopeMetrics(ScopeMetrics.newBuilder() + .addMetrics(Metric.newBuilder().setName(name) + .setGauge(Gauge.newBuilder().addDataPoints(valid).addDataPoints(invalid))))) + .build(); + byte[] response = given().contentType("application/x-protobuf").body(request.toByteArray()) + .post("/v1/metrics").then().statusCode(200).extract().asByteArray(); + ExportMetricsServiceResponse decoded = ExportMetricsServiceResponse.parseFrom(response); + assertEquals(1, decoded.getPartialSuccess().getRejectedDataPoints()); + assertEquals("Maximum number of attributes exceeded: 150 " + + "[ResourceMetrics.1.ScopeMetrics.1.Metrics.1.Datapoint.2].", + decoded.getPartialSuccess().getErrorMessage()); + assertTrue(metricsStream(service.requests("us-east-1")) + .anyMatch(metric -> name.equals(metric.getName()) && metric.getGauge().getDataPointsCount() == 1)); + } + + @Test + void reportsEmptyMetricWithoutRejectingTheValidPoint() { + String name = "nonempty_" + UUID.randomUUID().toString().replace("-", ""); + String body = """ + {"resourceMetrics":[{"scopeMetrics":[{"metrics":[{"name":"empty","gauge":{}}, + {"name":"%s","gauge":{"dataPoints":[{"timeUnixNano":"%d","asDouble":1}]}}]}]}]} + """.formatted(name, Instant.now().toEpochMilli() * 1_000_000L); + given().contentType("application/json").body(body).post("/v1/metrics").then().statusCode(200) + .body("partialSuccess.rejectedDataPoints", nullValue()) + .body("partialSuccess.errorMessage", + equalTo("Invalid OTel metric type [ResourceMetrics.1.ScopeMetrics.1.Metrics.1].")); + assertTrue(metricsStream(service.requests("us-east-1")) + .anyMatch(metric -> name.equals(metric.getName()))); + } + + @Test + void acceptsIdentityEncodingAndRejectsOtherEncodings() { + byte[] body = "{}".getBytes(StandardCharsets.UTF_8); + given().contentType("application/json").header("Content-Encoding", "identity") + .body(body).post("/v1/metrics").then().statusCode(200); + given().contentType("application/json").header("Content-Encoding", "br") + .body(body).post("/v1/metrics").then().statusCode(415); + given().contentType("application/json").header("Content-Encoding", "deflate") + .body(body).post("/v1/metrics").then().statusCode(415); + } + + @Test + void ingestsAllMetricTypes() { + long timestamp = Instant.now().toEpochMilli() * 1_000_000L; + String sumName = "sum_" + UUID.randomUUID().toString().replace("-", ""); + String histName = "hist_" + UUID.randomUUID().toString().replace("-", ""); + String summaryName = "summary_" + UUID.randomUUID().toString().replace("-", ""); + String expHistName = "exphist_" + UUID.randomUUID().toString().replace("-", ""); + ExportMetricsServiceRequest request = ExportMetricsServiceRequest.newBuilder() + .addResourceMetrics(ResourceMetrics.newBuilder().addScopeMetrics(ScopeMetrics.newBuilder() + .addMetrics(Metric.newBuilder().setName(sumName).setSum(Sum.newBuilder() + .setAggregationTemporality(AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE) + .setIsMonotonic(true) + .addDataPoints(NumberDataPoint.newBuilder().setTimeUnixNano(timestamp).setAsInt(100)))) + .addMetrics(Metric.newBuilder().setName(histName).setHistogram(Histogram.newBuilder() + .setAggregationTemporality(AggregationTemporality.AGGREGATION_TEMPORALITY_DELTA) + .addDataPoints(HistogramDataPoint.newBuilder().setTimeUnixNano(timestamp).setCount(5) + .setSum(42.0)))) + .addMetrics(Metric.newBuilder().setName(summaryName).setSummary( + Summary.newBuilder() + .addDataPoints(SummaryDataPoint.newBuilder().setTimeUnixNano(timestamp).setCount(3) + .setSum(9.0)))) + .addMetrics(Metric.newBuilder().setName(expHistName).setExponentialHistogram( + ExponentialHistogram.newBuilder() + .setAggregationTemporality(AggregationTemporality.AGGREGATION_TEMPORALITY_DELTA) + .addDataPoints(ExponentialHistogramDataPoint.newBuilder() + .setTimeUnixNano(timestamp).setCount(7).setSum(21.0)))))) + .build(); + given().contentType("application/x-protobuf").body(request.toByteArray()) + .post("/v1/metrics").then().statusCode(200); + assertTrue(metricsStream(service.requests("us-east-1")) + .anyMatch(metric -> sumName.equals(metric.getName()) + && metric.getSum().getDataPoints(0).getAsInt() == 100)); + assertTrue(metricsStream(service.requests("us-east-1")) + .anyMatch(metric -> histName.equals(metric.getName()) + && metric.getHistogram().getDataPoints(0).getCount() == 5)); + assertTrue(metricsStream(service.requests("us-east-1")) + .anyMatch(metric -> summaryName.equals(metric.getName()) + && metric.getSummary().getDataPoints(0).getCount() == 3)); + assertTrue(metricsStream(service.requests("us-east-1")) + .anyMatch(metric -> expHistName.equals(metric.getName()) + && metric.getExponentialHistogram().getDataPoints(0).getCount() == 7)); + } + + private static Stream metricsStream(List rawRequests) { + List all = new ArrayList<>(); + for (byte[] bytes : rawRequests) { + try { + ExportMetricsServiceRequest.parseFrom(bytes).getResourceMetricsList() + .forEach(r -> r.getScopeMetricsList() + .forEach(s -> all.addAll(s.getMetricsList()))); + } catch (InvalidProtocolBufferException e) { + throw new AssertionError("Could not parse stored OTLP metrics", e); + } + } + return all.stream(); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsServiceTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsServiceTest.java new file mode 100644 index 0000000000..26b63f295c --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsServiceTest.java @@ -0,0 +1,115 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.protobuf.InvalidProtocolBufferException; +import io.floci.aws.core.common.RequestContext; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.core.storage.WriteProfile; +import io.floci.aws.testing.StorageFactories; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class OtlpMetricsServiceTest { + + @TempDir + Path directory; + + @ParameterizedTest + @ValueSource(strings = {"memory", "persistent", "hybrid", "wal"}) + void expiresOldBatchesPerRegion(String mode) { + Instant now = Instant.parse("2026-01-01T00:00:00Z"); + ExportMetricsServiceRequest old = request("old"); + ExportMetricsServiceRequest fresh = request("fresh"); + StorageFactory factory = StorageFactories.open(directory, mode, "111111111111"); + try { + OtlpMetricsService initial = new OtlpMetricsService(factory, Clock.fixed(now, ZoneOffset.UTC)); + initial.ingest("eu-west-1", old.toByteArray()); + initial.ingest("us-east-1", old.toByteArray()); + assertEquals(1, initial.requests("eu-west-1").size()); + + Instant boundary = now.plus(Duration.ofDays(14)); + OtlpMetricsService atBoundary = new OtlpMetricsService(factory, Clock.fixed(boundary, ZoneOffset.UTC)); + atBoundary.ingest("eu-west-1", fresh.toByteArray()); + assertEquals(2, atBoundary.requests("eu-west-1").size()); + + OtlpMetricsService expired = new OtlpMetricsService(factory, + Clock.fixed(boundary.plusMillis(1), ZoneOffset.UTC)); + expired.ingest("eu-west-1", fresh.toByteArray()); + assertEquals(List.of(fresh, fresh), parsed(expired.requests("eu-west-1"))); + assertEquals(List.of(old), parsed(expired.requests("us-east-1"))); + expired.ingest("us-east-1", fresh.toByteArray()); + assertEquals(List.of(fresh), parsed(expired.requests("us-east-1"))); + } finally { + factory.shutdownAll(); + } + } + + @Test + @SuppressWarnings("unchecked") + void expiresOnlyTheCurrentAccountsBatches() { + RequestContext context = new RequestContext(); + Instance contextInstance = mock(Instance.class); + when(contextInstance.get()).thenReturn(context); + AccountAwareStorageBackend store = new AccountAwareStorageBackend<>( + new InMemoryStorage<>(), contextInstance, "000000000000"); + StorageFactory factory = mock(StorageFactory.class); + when(factory.create(eq("cloudwatchmetrics"), eq("cw-otlp-metrics.json"), + any(TypeReference.class), eq(WriteProfile.APPEND_HEAVY))).thenReturn(store); + Clock clock = mock(Clock.class); + long now = Instant.parse("2026-01-01T00:00:00Z").toEpochMilli(); + when(clock.millis()).thenReturn(now); + OtlpMetricsService service = new OtlpMetricsService(factory, context, clock); + ExportMetricsServiceRequest old = request("old"); + ExportMetricsServiceRequest fresh = request("fresh"); + context.setAccountId("111111111111"); + service.ingest("eu-west-1", old.toByteArray()); + context.setAccountId("222222222222"); + service.ingest("eu-west-1", old.toByteArray()); + + when(clock.millis()).thenReturn(now + Duration.ofDays(14).toMillis() + 1); + context.setAccountId("111111111111"); + service.ingest("eu-west-1", fresh.toByteArray()); + assertEquals(List.of(fresh), parsed(service.requests("eu-west-1"))); + context.setAccountId("222222222222"); + assertEquals(List.of(old), parsed(service.requests("eu-west-1"))); + service.ingest("eu-west-1", fresh.toByteArray()); + assertEquals(List.of(fresh), parsed(service.requests("eu-west-1"))); + } + + private List parsed(List raw) { + return raw.stream().map(b -> { + try { + return ExportMetricsServiceRequest.parseFrom(b); + } catch (InvalidProtocolBufferException e) { + throw new AssertionError("Could not parse stored OTLP metrics", e); + } + }).toList(); + } + + private ExportMetricsServiceRequest request(String name) { + return ExportMetricsServiceRequest.newBuilder() + .addResourceMetrics(ResourceMetrics.newBuilder().setSchemaUrl(name)).build(); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsSignatureIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsSignatureIntegrationTest.java new file mode 100644 index 0000000000..50d0d52a96 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsSignatureIntegrationTest.java @@ -0,0 +1,87 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.rpc.Status; +import io.floci.aws.testing.SignedIamEnforcementProfile; +import io.floci.aws.testutil.AwsRequestSigner; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestProfile(SignedIamEnforcementProfile.class) +class OtlpMetricsSignatureIntegrationTest { + + @TestHTTPResource("/v1/metrics") + URI endpoint; + + @Inject + OtlpMetricsService service; + + @Test + void acceptsSignedRequestsAndEncodesSignatureErrorsAsOtlpStatus() throws Exception { + AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "monitoring"); + byte[] json = "{}".getBytes(StandardCharsets.UTF_8); + Map signedHeaders = Map.of(); + given().contentType("application/json").headers(root.headersFor("POST", endpoint, signedHeaders, json)) + .body(json).post(endpoint).then().statusCode(200); + given().contentType("application/json").headers(root.withSecret("wrong-secret") + .headersFor("POST", endpoint, signedHeaders, json)) + .body(json).post(endpoint).then().statusCode(403).body("code", equalTo(7)); + + byte[] protobuf = {10, 0}; + byte[] response = given().contentType("application/x-protobuf").headers(root.withSecret("wrong-secret") + .headersFor("POST", endpoint, signedHeaders, protobuf)) + .body(protobuf).post(endpoint).then().statusCode(403).extract().asByteArray(); + assertEquals(7, Status.parseFrom(response).getCode()); + } + + @Test + void rejectsIncompleteSignaturesAsOtlpStatus() { + given().contentType("application/json") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=invalid") + .body("{}").post(endpoint).then().statusCode(403).body("code", equalTo(7)); + given().contentType("application/json").header("Authorization", "Bearer invalid") + .body("{}").post(endpoint).then().statusCode(403).body("code", equalTo(7)); + } + + @Test + void storesPresignedRequestsInTheirSigningRegion() throws Exception { + String name = "presigned_" + UUID.randomUUID().toString().replace("-", ""); + byte[] json = """ + {"resourceMetrics":[{"scopeMetrics":[{"metrics":[{"name":"%s", + "gauge":{"dataPoints":[{"timeUnixNano":"%d","asInt":"1"}]}}]}]}]} + """.formatted(name, Instant.now().toEpochMilli() * 1_000_000L).getBytes(StandardCharsets.UTF_8); + AwsRequestSigner signer = AwsRequestSigner.signedAs("test", "test", "monitoring").inRegion("eu-west-1"); + given().urlEncodingEnabled(false).contentType("application/json").body(json) + .post(signer.presignedUri("POST", endpoint, Map.of(), json)).then().statusCode(200); + assertTrue(hasMetric("eu-west-1", name)); + assertFalse(hasMetric("us-east-1", name)); + } + + private boolean hasMetric(String region, String name) { + return service.requests(region).stream().flatMap(bytes -> { + try { + return ExportMetricsServiceRequest.parseFrom(bytes).getResourceMetricsList().stream(); + } catch (InvalidProtocolBufferException e) { + throw new AssertionError("Could not parse stored OTLP metrics", e); + } + }).flatMap(resource -> resource.getScopeMetricsList().stream()) + .flatMap(scope -> scope.getMetricsList().stream()).anyMatch(metric -> name.equals(metric.getName())); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsStorageReloadTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsStorageReloadTest.java new file mode 100644 index 0000000000..0d2e41318e --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsStorageReloadTest.java @@ -0,0 +1,52 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import com.google.protobuf.InvalidProtocolBufferException; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.testing.StorageFactories; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class OtlpMetricsStorageReloadTest { + + @TempDir + Path directory; + + @ParameterizedTest + @ValueSource(strings = {"persistent", "hybrid", "wal"}) + void storedRequestsSurviveReloadAndRemainRegionScoped(String mode) throws InvalidProtocolBufferException { + ExportMetricsServiceRequest request = ExportMetricsServiceRequest.newBuilder() + .addResourceMetrics(ResourceMetrics.newBuilder().setSchemaUrl("https://example.org/schema")) + .build(); + StorageFactory first = StorageFactories.open(directory, mode, "111111111111"); + try { + new OtlpMetricsService(first).ingest("eu-west-1", request.toByteArray()); + } finally { + first.shutdownAll(); + } + StorageFactory second = StorageFactories.open(directory, mode, "111111111111"); + try { + OtlpMetricsService service = new OtlpMetricsService(second); + List stored = service.requests("eu-west-1"); + assertEquals(1, stored.size()); + assertEquals(request, ExportMetricsServiceRequest.parseFrom(stored.get(0))); + assertTrue(service.requests("us-east-1").isEmpty()); + } finally { + second.shutdownAll(); + } + StorageFactory otherAccount = StorageFactories.open(directory, mode, "222222222222"); + try { + assertTrue(new OtlpMetricsService(otherAccount).requests("eu-west-1").isEmpty()); + } finally { + otherAccount.shutdownAll(); + } + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsValidationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsValidationTest.java new file mode 100644 index 0000000000..d8fe7c6c41 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/OtlpMetricsValidationTest.java @@ -0,0 +1,245 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import com.google.protobuf.ByteString; +import com.google.protobuf.DynamicMessage; +import com.google.protobuf.InvalidProtocolBufferException; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.opentelemetry.proto.common.v1.AnyValue; +import io.opentelemetry.proto.common.v1.ArrayValue; +import io.opentelemetry.proto.common.v1.InstrumentationScope; +import io.opentelemetry.proto.common.v1.KeyValue; +import io.opentelemetry.proto.common.v1.KeyValueList; +import io.opentelemetry.proto.metrics.v1.Gauge; +import io.opentelemetry.proto.metrics.v1.Metric; +import io.opentelemetry.proto.metrics.v1.NumberDataPoint; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import io.opentelemetry.proto.metrics.v1.ScopeMetrics; +import io.opentelemetry.proto.resource.v1.Resource; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.function.UnaryOperator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class OtlpMetricsValidationTest { + + private final OtlpMetricsValidation validation = new OtlpMetricsValidation(); + + @Test + void countsAttributesAcrossResourceScopeAndDatapoint() { + List resource = attributes("r", 50); + List scope = attributes("s", 50); + List point = attributes("p", 50); + assertFalse(validation.validate(toDynamic(request(resource, scope, point))).hasErrors()); + point.add(attribute("r0", "x")); + OtlpMetricsValidation.Result result = validation.validate(toDynamic(request(resource, scope, point))); + assertEquals(1, result.rejectedDataPoints()); + assertEquals("Maximum number of attributes exceeded: 150 " + + "[ResourceMetrics.1.ScopeMetrics.1.Metrics.1.Datapoint.1].", result.errorMessage()); + } + + @Test + void countsUtf8MetadataAndMetricScopeNamesAtTheObservedBoundary() { + List attributes = metadataAttributes(40_000 - 15); + KeyValue first = attributes.getFirst(); + attributes.set(0, attribute(first.getKey(), "é".repeat(first.getValue().getStringValue().length() / 2))); + assertFalse(validation.validate(toDynamic(request(List.of(), List.of(), attributes))).hasErrors()); + KeyValue last = attributes.getLast(); + attributes.set(attributes.size() - 1, attribute(last.getKey(), last.getValue().getStringValue() + "x")); + OtlpMetricsValidation.Result result = validation.validate(toDynamic(request(List.of(), List.of(), attributes))); + assertEquals("Maximum size of datapoint metadata exceeded: 40 KB " + + "[ResourceMetrics.1.ScopeMetrics.1.Metrics.1.Datapoint.1].", result.errorMessage()); + } + + @Test + void countsTypedAttributeValuesAtTheObservedBoundary() { + List attributes = metadataAttributes(39_961); + attributes.add(KeyValue.newBuilder().setKey("num") + .setValue(AnyValue.newBuilder().setIntValue(Long.MAX_VALUE)).build()); + attributes.add(KeyValue.newBuilder().setKey("flag") + .setValue(AnyValue.newBuilder().setBoolValue(true)).build()); + attributes.add(KeyValue.newBuilder().setKey("blob") + .setValue(AnyValue.newBuilder().setBytesValue(ByteString.copyFrom(new byte[] {1, 2, 3, 4}))).build()); + assertFalse(validation.validate(toDynamic(request(List.of(), List.of(), attributes))).hasErrors()); + KeyValue lastString = attributes.get(39); + attributes.set(39, attribute(lastString.getKey(), lastString.getValue().getStringValue() + "x")); + assertTrue(validation.validate(toDynamic(request(List.of(), List.of(), attributes))).errorMessage() + .startsWith("Maximum size of datapoint metadata exceeded: 40 KB")); + } + + @Test + void rejectsOverlongScopeAndDatapointValuesAtTheirOwnPaths() { + List longValue = List.of(attribute("key", "x".repeat(1025))); + OtlpMetricsValidation.Result scope = validation.validate(toDynamic(request(List.of(), longValue, List.of()))); + assertEquals("Attribute string value exceeds maximum length: 1024 " + + "[ResourceMetrics.1.ScopeMetrics.1] (1 datapoint rejected).", scope.errorMessage()); + OtlpMetricsValidation.Result point = validation.validate(toDynamic(request(List.of(), List.of(), longValue))); + assertEquals("Attribute string value exceeds maximum length: 1024 " + + "[ResourceMetrics.1.ScopeMetrics.1.Metrics.1.Datapoint.1].", point.errorMessage()); + assertFalse(validation.validate(toDynamic(request(List.of(), List.of(), + List.of(attribute("key", "é".repeat(1024)))))).hasErrors()); + assertFalse(validation.validate(toDynamic(request(List.of(), List.of(), + List.of(attribute("key", "😀".repeat(512)))))).hasErrors()); + assertTrue(validation.validate(toDynamic(request(List.of(), List.of(), + List.of(attribute("key", "😀".repeat(513)))))).hasErrors()); + } + + @Test + void retainsValidPointWhenAnotherHasTooManyAttributes() throws InvalidProtocolBufferException { + ExportMetricsServiceRequest original = request(List.of(), List.of(), List.of()); + ExportMetricsServiceRequest updated = withFirstGauge(original, gauge -> gauge.addDataPoints( + gauge.getDataPoints(0).toBuilder().addAllAttributes(attributes("a", 151)))); + OtlpMetricsValidation.Result result = validation.validate(toDynamic(updated)); + assertEquals(1, result.rejectedDataPoints()); + ExportMetricsServiceRequest accepted = ExportMetricsServiceRequest.parseFrom(result.requestBytes()); + assertEquals(1, accepted.getResourceMetrics(0).getScopeMetrics(0).getMetrics(0) + .getGauge().getDataPointsCount()); + assertTrue(result.errorMessage().endsWith("[ResourceMetrics.1.ScopeMetrics.1.Metrics.1.Datapoint.2].")); + } + + @Test + void identifiesMissingServiceNameInTimestampError() { + ExportMetricsServiceRequest original = request(List.of(), List.of(), List.of()); + ExportMetricsServiceRequest updated = withFirstGauge(original, + gauge -> gauge.setDataPoints(0, gauge.getDataPoints(0).toBuilder().setTimeUnixNano(0))); + OtlpMetricsValidation.Result result = validation.validate(toDynamic(updated)); + assertEquals("TimeUnixNano 0 is too far in the past for metric 'metric' " + + "for resource where service.name is not present at " + + "[ResourceMetrics.1.ScopeMetrics.1.Metrics.1.Datapoint.1].", result.errorMessage()); + } + + @Test + void reportsSharedAndDatapointErrorsButRejectsEachPointOnce() { + ExportMetricsServiceRequest original = request(List.of(attribute("resource", "x".repeat(1025))), + List.of(), List.of()); + ExportMetricsServiceRequest updated = withFirstGauge(original, + gauge -> gauge.setDataPoints(0, gauge.getDataPoints(0).toBuilder().setTimeUnixNano(0))); + OtlpMetricsValidation.Result result = validation.validate(toDynamic(updated)); + assertEquals(1, result.rejectedDataPoints()); + assertEquals("Attribute string value exceeds maximum length: 1024 " + + "[ResourceMetrics.1] (1 datapoint rejected).\n" + + "TimeUnixNano 0 is too far in the past for metric 'metric' " + + "for resource where service.name is not present at " + + "[ResourceMetrics.1.ScopeMetrics.1.Metrics.1.Datapoint.1].", + result.errorMessage()); + } + + @Test + void countsMetricNameLengthInUtf16CodeUnits() { + ExportMetricsServiceRequest original = request(List.of(), List.of(), List.of()); + ResourceMetrics.Builder resource = original.getResourceMetrics(0).toBuilder(); + ScopeMetrics.Builder scope = resource.getScopeMetrics(0).toBuilder(); + Metric.Builder metric = scope.getMetrics(0).toBuilder().setName("m" + "😀".repeat(127)); + scope.setMetrics(0, metric); + resource.setScopeMetrics(0, scope); + assertFalse(validation.validate(toDynamic(original.toBuilder().setResourceMetrics(0, resource).build())) + .hasErrors()); + metric.setName("m" + "😀".repeat(128)); + scope.setMetrics(0, metric); + resource.setScopeMetrics(0, scope); + assertEquals("Metric name exceeds maximum length: 256 " + + "[ResourceMetrics.1.ScopeMetrics.1.Metrics.1] (1 datapoint rejected).", + validation.validate(toDynamic(original.toBuilder().setResourceMetrics(0, resource).build())) + .errorMessage()); + } + + @Test + void ignoresInvalidAttributesOnEmptyEnvelopes() { + KeyValue longValue = attribute("resource", "x".repeat(1025)); + ExportMetricsServiceRequest request = ExportMetricsServiceRequest.newBuilder() + .addResourceMetrics(ResourceMetrics.newBuilder().setResource(Resource.newBuilder().addAttributes(longValue)) + .addScopeMetrics(ScopeMetrics.newBuilder().setScope(InstrumentationScope.newBuilder() + .addAttributes(longValue)))) + .build(); + OtlpMetricsValidation.Result result = validation.validate(toDynamic(request)); + assertFalse(result.hasErrors()); + assertEquals(0, result.rejectedDataPoints()); + } + + @Test + void checksNestedStringsInResourceScopeAndDatapointAttributes() { + AnyValue nested = AnyValue.newBuilder().setArrayValue(ArrayValue.newBuilder().addValues( + AnyValue.newBuilder().setKvlistValue(KeyValueList.newBuilder() + .addValues(attribute("inner", "x".repeat(1025)))))).build(); + KeyValue attribute = KeyValue.newBuilder().setKey("outer").setValue(nested).build(); + assertTrue(validation.validate(toDynamic(request(List.of(attribute), List.of(), List.of()))).errorMessage() + .contains("[ResourceMetrics.1]")); + assertTrue(validation.validate(toDynamic(request(List.of(), List.of(attribute), List.of()))).errorMessage() + .contains("[ResourceMetrics.1.ScopeMetrics.1]")); + assertTrue(validation.validate(toDynamic(request(List.of(), List.of(), List.of(attribute)))).errorMessage() + .contains("[ResourceMetrics.1.ScopeMetrics.1.Metrics.1.Datapoint.1]")); + } + + @Test + void countsNestedKeysAndValuesTowardsMetadataLimit() { + List attributes = metadataAttributes(39_985 - 11); + AnyValue nested = AnyValue.newBuilder().setArrayValue(ArrayValue.newBuilder().addValues( + AnyValue.newBuilder().setKvlistValue(KeyValueList.newBuilder() + .addValues(attribute("inner", "value"))))).build(); + attributes.add(KeyValue.newBuilder().setKey("o").setValue(nested).build()); + assertFalse(validation.validate(toDynamic(request(List.of(), List.of(), attributes))).hasErrors()); + attributes.add(attribute("x", "")); + assertTrue(validation.validate(toDynamic(request(List.of(), List.of(), attributes))).errorMessage() + .startsWith("Maximum size of datapoint metadata exceeded: 40 KB")); + } + + private DynamicMessage toDynamic(ExportMetricsServiceRequest req) { + try { + return DynamicMessage.parseFrom(OtlpDescriptors.EXPORT_REQUEST, req.toByteArray()); + } catch (InvalidProtocolBufferException e) { + throw new AssertionError("Could not convert to DynamicMessage", e); + } + } + + private ExportMetricsServiceRequest withFirstGauge(ExportMetricsServiceRequest request, + UnaryOperator edit) { + ResourceMetrics.Builder resource = request.getResourceMetrics(0).toBuilder(); + ScopeMetrics.Builder scope = resource.getScopeMetrics(0).toBuilder(); + Metric.Builder metric = scope.getMetrics(0).toBuilder(); + metric.setGauge(edit.apply(metric.getGauge().toBuilder())); + scope.setMetrics(0, metric); + resource.setScopeMetrics(0, scope); + return request.toBuilder().setResourceMetrics(0, resource).build(); + } + + private ExportMetricsServiceRequest request(List resource, List scope, List point) { + NumberDataPoint datum = NumberDataPoint.newBuilder().setTimeUnixNano(Instant.now().toEpochMilli() * 1_000_000L) + .setAsDouble(1).addAllAttributes(point).build(); + Metric metric = Metric.newBuilder().setName("metric").setUnit("ms") + .setGauge(Gauge.newBuilder().addDataPoints(datum)).build(); + ScopeMetrics scopeMetrics = ScopeMetrics.newBuilder() + .setScope(InstrumentationScope.newBuilder().setName("scope").setVersion("v1").addAllAttributes(scope)) + .addMetrics(metric).build(); + return ExportMetricsServiceRequest.newBuilder().addResourceMetrics(ResourceMetrics.newBuilder() + .setResource(Resource.newBuilder().addAllAttributes(resource)).addScopeMetrics(scopeMetrics)).build(); + } + + private List attributes(String prefix, int count) { + List attrs = new ArrayList<>(); + for (int i = 0; i < count; i++) { + attrs.add(attribute(prefix + i, "x")); + } + return attrs; + } + + private List metadataAttributes(int totalBytes) { + List attrs = attributes("k", 40); + int remaining = totalBytes - attrs.stream().mapToInt(attribute -> attribute.getKey().length()).sum(); + for (int i = 0; i < attrs.size(); i++) { + int size = Math.min(1024, remaining); + attrs.set(i, attribute(attrs.get(i).getKey(), "x".repeat(size))); + remaining -= size; + } + assertEquals(0, remaining); + return attrs; + } + + private KeyValue attribute(String key, String value) { + return KeyValue.newBuilder().setKey(key).setValue(AnyValue.newBuilder().setStringValue(value)).build(); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRouteCoverageTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRouteCoverageTest.java index aa3c3ecffa..09dd0c501b 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRouteCoverageTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRouteCoverageTest.java @@ -147,7 +147,8 @@ class IamRestRouteCoverageTest { String action = RUN_AS_ANOTHER_OPERATION.getOrDefault(operation.getKey(), authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey())); boolean read = requestResources.path("operations").has(scope + ":" + operation.getKey()); - String expected = handBuilt.contains(scope) || read || IamAuthorizedActions.actsOnNoResourceType(action) + String expected = handBuilt.contains(scope) || read + || IamAuthorizedActions.actsOnNoResourceType(action) ? action : null; tests.add(DynamicTest.dynamicTest(model + " " + operation.getKey(), () -> assertEquals(expected, resolve(route), route.toString()))); diff --git a/tools/aws/regen_rest_routes.py b/tools/aws/regen_rest_routes.py index 28848aaa77..bb88dfbe1f 100644 --- a/tools/aws/regen_rest_routes.py +++ b/tools/aws/regen_rest_routes.py @@ -157,6 +157,7 @@ def build(models: dict[str, dict], provenance: str) -> dict: raise SystemExit(f"error: REST models of {scope} have conflicting access-denied HTTP statuses") denial_statuses[scope] = status routes[name]["accessDeniedStatus"] = status + routes = dict(sorted(routes.items())) shared = shared_routes(routes) if shared: raise SystemExit("error: one route names more than one operation in a scope the rules do not route alone: "