mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudwatch): exclude EndTime from metric queries (#8824)
This commit is contained in:
1 parent
90b6d46317
commit
4c0181cd20
7 files changed
+175
-6
No files matched your search
@@ -432,6 +432,10 @@ aws logs put-retention-policy \
|
||||
|
||||
**Protocol:** Query (XML), JSON 1.0, and OTLP/HTTP.
|
||||
|
||||
`GetMetricStatistics` and `GetMetricData` exclude samples exactly at `EndTime`, so
|
||||
adjacent query windows do not count their shared boundary twice. A whole-second sample
|
||||
before a fractional-second `EndTime` remains included.
|
||||
|
||||
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
|
||||
|
||||
@@ -119,7 +119,7 @@ public class AlarmEvaluator {
|
||||
long lastCompleteBucket = nowBucket - period;
|
||||
long oldestBucket = lastCompleteBucket - (long) period * (range - 1);
|
||||
Instant start = Instant.ofEpochSecond(oldestBucket);
|
||||
Instant end = Instant.ofEpochSecond(lastCompleteBucket + period - 1);
|
||||
Instant end = Instant.ofEpochSecond(lastCompleteBucket + period);
|
||||
|
||||
List<CloudWatchMetricsService.Datapoint> retrieved = metricsService.getMetricStatistics(
|
||||
alarm.getNamespace(), alarm.getMetricName(), alarm.getDimensions(),
|
||||
|
||||
+3
-1
@@ -322,7 +322,9 @@ public class CloudWatchMetricsService {
|
||||
if (parts.length < 6) return false;
|
||||
try {
|
||||
long ts = Long.parseLong(parts[parts.length - 2]);
|
||||
return ts >= startEpoch && ts <= endEpoch;
|
||||
boolean beforeEnd = endTime == null || ts < endEpoch
|
||||
|| (ts == endEpoch && endTime.getNano() > 0);
|
||||
return ts >= startEpoch && beforeEnd;
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.cloudwatch.metrics;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -78,6 +79,37 @@ class AlarmEvaluatorTest {
|
||||
any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void includesFinalSecondOfCompletedPeriodButExcludesCurrentPeriod() {
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setEvaluationPeriods(1);
|
||||
when(handlers.iterator()).thenAnswer(invocation -> List.<AlarmActionHandler>of().iterator());
|
||||
doAnswer(invocation -> {
|
||||
Instant end = invocation.getArgument(4);
|
||||
int period = invocation.getArgument(5);
|
||||
long boundary = ((end.getEpochSecond() + period - 1) / period) * period;
|
||||
MetricDatum completed = new MetricDatum();
|
||||
completed.setMetricName(alarm.getMetricName());
|
||||
completed.setTimestamp(boundary - 1);
|
||||
completed.setValue(90.0);
|
||||
MetricDatum current = new MetricDatum();
|
||||
current.setMetricName(alarm.getMetricName());
|
||||
current.setTimestamp(boundary);
|
||||
current.setValue(0.0);
|
||||
metricsService.putMetricData(alarm.getNamespace(), List.of(completed, current), REGION);
|
||||
Object result = invocation.callRealMethod();
|
||||
assertEquals(List.of(new CloudWatchMetricsService.Datapoint(
|
||||
Instant.ofEpochSecond(boundary - period), 1, 90.0, 90.0, 90.0, 90.0, "None")), result);
|
||||
return result;
|
||||
}).when(metricsService).getMetricStatistics(
|
||||
any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString());
|
||||
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService).setAlarmState(
|
||||
eq(alarm.getAlarmName()), eq("ALARM"), anyString(), any(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void transitionsToAlarmAndDispatchesWhenThresholdBreachedForAllPeriods() {
|
||||
stubMetrics(datapoints(80, 85, 90));
|
||||
@@ -179,7 +211,7 @@ class AlarmEvaluatorTest {
|
||||
List<CloudWatchMetricsService.Datapoint> points = new ArrayList<>();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
points.add(new CloudWatchMetricsService.Datapoint(
|
||||
end.minusSeconds(60L * i), 1, 80, 80, 80, 80, "Percent"));
|
||||
end.minusSeconds(60L * (i + 1)), 1, 80, 80, 80, 80, "Percent"));
|
||||
}
|
||||
return points;
|
||||
}).when(metricsService).getMetricStatistics(
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.Statistic;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudWatchMetricEndTimeIntegrationTest {
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@Test
|
||||
void sdkHourlyWindowsDoNotDoubleCountTheSharedBoundary() {
|
||||
String namespace = "EndBoundary/" + UUID.randomUUID();
|
||||
Instant start = Instant.now().truncatedTo(ChronoUnit.HOURS).minus(2, ChronoUnit.HOURS);
|
||||
Instant middle = start.plus(1, ChronoUnit.HOURS);
|
||||
Instant end = middle.plus(1, ChronoUnit.HOURS);
|
||||
try (CloudWatchClient client = AwsTestClients.create(CloudWatchClient.builder(), "test", Region.US_EAST_1)) {
|
||||
client.putMetricData(request -> request.namespace(namespace).metricData(
|
||||
MetricDatum.builder().metricName("Counter").timestamp(start).value(3.0).build(),
|
||||
MetricDatum.builder().metricName("Counter").timestamp(middle).value(7.0).build(),
|
||||
MetricDatum.builder().metricName("Counter").timestamp(end).value(11.0).build()));
|
||||
assertEquals(List.of(3.0), client.getMetricStatistics(request -> request.namespace(namespace)
|
||||
.metricName("Counter").startTime(start).endTime(middle).period(3600).statistics(Statistic.SUM))
|
||||
.datapoints().stream().map(point -> point.sum()).toList());
|
||||
assertEquals(List.of(7.0), client.getMetricStatistics(request -> request.namespace(namespace)
|
||||
.metricName("Counter").startTime(middle).endTime(end).period(3600).statistics(Statistic.SUM))
|
||||
.datapoints().stream().map(point -> point.sum()).toList());
|
||||
assertEquals(List.of(3.0), client.getMetricData(request -> request.startTime(start).endTime(middle)
|
||||
.metricDataQueries(query -> query.id("m").returnData(true).metricStat(stat -> stat
|
||||
.metric(metric -> metric.namespace(namespace).metricName("Counter"))
|
||||
.period(3600).stat("Sum")))).metricDataResults().getFirst().values());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryAndJsonExcludeTheSharedBoundary() throws JsonProcessingException {
|
||||
String namespace = "EndBoundary/" + UUID.randomUUID();
|
||||
Instant start = Instant.now().truncatedTo(ChronoUnit.HOURS).minus(2, ChronoUnit.HOURS);
|
||||
Instant end = start.plus(1, ChronoUnit.HOURS);
|
||||
String scope = "AWS4-HMAC-SHA256 Credential=test/20261118/us-east-1/monitoring/aws4_request";
|
||||
try (CloudWatchClient client = AwsTestClients.create(CloudWatchClient.builder(), "test", Region.US_EAST_1)) {
|
||||
client.putMetricData(request -> request.namespace(namespace).metricData(
|
||||
MetricDatum.builder().metricName("Counter").timestamp(start).value(3.0).build(),
|
||||
MetricDatum.builder().metricName("Counter").timestamp(end).value(7.0).build()));
|
||||
}
|
||||
CloudWatchTestRequests.call(endpoint, scope, false, "GetMetricStatistics", Map.of(
|
||||
"Namespace", namespace, "MetricName", "Counter", "StartTime", start.toString(),
|
||||
"EndTime", end.toString(), "Period", 3600, "Statistics", List.of("Sum")))
|
||||
.then().statusCode(200)
|
||||
.body("GetMetricStatisticsResponse.GetMetricStatisticsResult.Datapoints.member.size()", equalTo(1))
|
||||
.body("GetMetricStatisticsResponse.GetMetricStatisticsResult.Datapoints.member.Sum", equalTo("3.0"));
|
||||
CloudWatchTestRequests.call(endpoint, scope, true, "GetMetricStatistics", Map.of(
|
||||
"Namespace", namespace, "MetricName", "Counter", "StartTime", start.getEpochSecond(),
|
||||
"EndTime", end.getEpochSecond(), "Period", 3600, "Statistics", List.of("Sum")))
|
||||
.then().statusCode(200).body("Datapoints.size()", equalTo(1))
|
||||
.body("Datapoints[0].Sum", equalTo(3.0f));
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class CloudWatchMetricEndTimeTest {
|
||||
private final CloudWatchMetricsService service = new CloudWatchMetricsService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", "123456789012"));
|
||||
|
||||
private void seed() {
|
||||
service.putMetricData("Boundary", List.of(
|
||||
MetricDatum.of("Counter", "Count", 3, List.of(), 120),
|
||||
MetricDatum.of("Counter", "Count", 7, List.of(), 180),
|
||||
MetricDatum.of("Counter", "Count", 11, List.of(), 240)), "us-east-1");
|
||||
}
|
||||
|
||||
private List<CloudWatchMetricsService.Datapoint> read(long start, Instant end) {
|
||||
return service.getMetricStatistics("Boundary", "Counter", List.of(), Instant.ofEpochSecond(start),
|
||||
end, 60, List.of("Sum"), "Count", "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void adjacentWindowsIncludeTheirStartAndExcludeTheirEnd() {
|
||||
seed();
|
||||
List<CloudWatchMetricsService.Datapoint> first = read(120, Instant.ofEpochSecond(180));
|
||||
List<CloudWatchMetricsService.Datapoint> second = read(180, Instant.ofEpochSecond(240));
|
||||
assertEquals(List.of(3.0), first.stream().map(CloudWatchMetricsService.Datapoint::sum).toList());
|
||||
assertEquals(List.of(7.0), second.stream().map(CloudWatchMetricsService.Datapoint::sum).toList());
|
||||
assertEquals(Instant.ofEpochSecond(120), first.getFirst().timestamp());
|
||||
assertEquals(Instant.ofEpochSecond(180), second.getFirst().timestamp());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {1, 500_000_000})
|
||||
void fractionalExclusiveEndStillIncludesAnEarlierWholeSecond(int nanos) {
|
||||
seed();
|
||||
Instant end = Instant.ofEpochSecond(180, nanos);
|
||||
assertEquals(List.of(7.0), read(180, end).stream()
|
||||
.map(CloudWatchMetricsService.Datapoint::sum).toList());
|
||||
CloudWatchMetricsService.MetricStat metric = new CloudWatchMetricsService.MetricStat(
|
||||
"Boundary", "Counter", List.of(), 60, "Sum", "Count");
|
||||
List<CloudWatchMetricsService.MetricDataResult> results = service.getMetricData(
|
||||
List.of(new CloudWatchMetricsService.MetricDataQuery("m", metric, null, null, true)),
|
||||
Instant.ofEpochSecond(180), end, "us-east-1");
|
||||
assertEquals(List.of(7.0), results.getFirst().values());
|
||||
}
|
||||
}
|
||||
@@ -270,7 +270,7 @@ class SqsMetricsPublisherTest {
|
||||
|
||||
Instant ended = Instant.parse("2026-10-22T12:00:00Z");
|
||||
List<Datapoint> points = cloudWatch.getMetricStatistics("AWS/SQS", "NumberOfMessagesSent",
|
||||
List.of(new Dimension("QueueName", "stamped")), ended, ended, 60, List.of("Sum"), null, REGION);
|
||||
List.of(new Dimension("QueueName", "stamped")), ended, ended.plusSeconds(60), 1, List.of("Sum"), null, REGION);
|
||||
assertEquals(1, points.size());
|
||||
assertEquals(ended, points.getFirst().timestamp());
|
||||
}
|
||||
@@ -296,7 +296,7 @@ class SqsMetricsPublisherTest {
|
||||
}
|
||||
|
||||
private List<Datapoint> points(String namespace, List<Dimension> dimensions, Instant at) {
|
||||
return cloudWatch.getMetricStatistics(namespace, "NumberOfMessagesSent", dimensions, at, at, 60,
|
||||
return cloudWatch.getMetricStatistics(namespace, "NumberOfMessagesSent", dimensions, at, at.plusSeconds(60), 60,
|
||||
List.of("Sum"), null, REGION);
|
||||
}
|
||||
|
||||
@@ -332,7 +332,7 @@ class SqsMetricsPublisherTest {
|
||||
private Datapoint datapoint(String queueName, String metricName, Instant tick) {
|
||||
Instant minute = tick.minusSeconds(30).truncatedTo(ChronoUnit.MINUTES);
|
||||
List<Datapoint> points = cloudWatch.getMetricStatistics("AWS/SQS", metricName,
|
||||
List.of(new Dimension("QueueName", queueName)), minute, minute, 60, List.of("Sum"), null, REGION);
|
||||
List.of(new Dimension("QueueName", queueName)), minute, minute.plusSeconds(60), 60, List.of("Sum"), null, REGION);
|
||||
assertTrue(points.size() <= 1, metricName + " has " + points.size() + " datapoints");
|
||||
return points.isEmpty() ? null : points.getFirst();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user