test(compat): assert recorded metric filter publishing through the SDK modules (#3809)

* feat(logs): add metric filters with per-event metric publication

Implements PutMetricFilter, DescribeMetricFilters, DeleteMetricFilter and
TestMetricFilter on the CloudWatch Logs JSON 1.1 handler, backed by a filter
pattern engine for term, space-delimited and JSON patterns. The grammar is
checked against 148 TestMetricFilter cases recorded from AWS, kept as
fixtures under src/test/resources/cloudwatchlogs and recaptured with the
opt-in script under tools/aws-capture/cloudwatchlogs.

Validation follows the observed AWS wire behavior: the five regex-bearing
filters per log group quota is shared with subscription filters through one
canonical backend monitor, a filter pattern may hold at most two regular
expressions, defaultValue must be a JSON number, DescribeMetricFilters
requires metricName and metricNamespace together in both directions, and
TestMetricFilter reports one-based event numbers with an empty public
extractedValues map for JSON patterns.

Ingested events publish samples into CloudWatch Metrics per event at the
event timestamp: matching events contribute the extracted or literal value,
non-matching events contribute defaultValue, dimensions are all-or-none, and
system dimensions only attach to matching events. Failed publications are
retried from a bounded queue of 10,000 samples with stable publication ids.

Resettable gains beforeReset and afterReset default hooks so the metric
filter publisher can pause and drain before a state reset wipes storage and
resume afterwards. EmulatorInfoController.performReset is serialized and
calls the hooks around the existing container teardown and storage wipe,
running afterReset in a finally block so a failed wipe cannot leave a
publisher paused. The GetMetricStatistics and GetMetricData Query responses
now carry the CloudWatch namespace so both read paths return the same
samples.

* feat(cloudformation): provision AWS::Logs::MetricFilter

Adds LogsMetricFilterCfnProvisioner for creates, in-place updates, name
changes and deletes. Ref and PhysicalResourceId are the filter name alone,
as observed on AWS; the log group is kept as private resource metadata.
A replacement deletes the old filter before creating the new one, matching
the DELETE then CREATE event order AWS emits, and a failed replacement
recreates the previous definition on rollback.

Every mutation records an APPLIED, NOT_APPLIED or UNKNOWN outcome under the
service lock so a failed or ambiguous call can never authorize deleting or
overwriting a filter the stack does not own. Ownership that cannot be proven
is resolved conservatively before the next mutation.

The engine gains three small provisioner hooks that this type needs and
others may reuse:

- ProvisionContext carries a progress consumer so a provisioner can emit
  the intermediate DELETE_IN_PROGRESS and DELETE_COMPLETE events of a
  delete-first replacement while provision is still running.
- rollbackUpdate(resource, progress) lets a provisioner restore its own
  previous state during UPDATE_ROLLBACK and report the steps as events.
- hasPendingRollbackCleanup and retainsFailedUpdateState let a provisioner
  tell the engine that an UPDATE_FAILED resource still holds its own
  rollback snapshot, so the engine neither restores the previous resource
  over it nor refuses a later DeleteStack. Both default to false; only this
  provisioner overrides them.

The type is listed in supported-resource-types.tsv, the generated resource
table and CfnProvisionerFixture, with unit, integration, storage reload and
SDK coverage.

* docs(logs): document metric filters and the AWS verification record

Describes the metric filter operations, publication semantics and
CloudFormation support in docs/services/cloudwatch.md and adds
cloudwatch-metric-filters-verification.md, the record of what was observed
on AWS in eu-west-1, with which tools, and where each recorded fixture came
from. Registers the handler and the verification page with the docs tooling
and teaches the service inventory test to count facet pages.

* feat(logs): publish metric filter samples off the PutLogEvents thread

PutLogEvents evaluated each filter and wrote one CloudWatch Metrics sample
per filter and event on the request thread while holding the filter-store
monitor, up to a million writes for a maximal request, so ingestion latency
depended on the Metrics sink and every PutMetricFilter waited behind the
whole batch.

The request thread now only evaluates the group's filters as they are at
ingestion and hands the resulting immutable samples, with their stable
publication ids, to a bounded queue of 100,000 samples. The existing single
worker drains it and writes one sample per monitor acquisition, so a
PutMetricFilter or a reset waits for at most one write. A batch that does
not fit the queue is written inline on the request thread rather than
dropped. Failed writes still land in the 10,000 sample retry map with the
same ids and cadence as before.

Reset pauses the worker, discards queued and failed samples and bumps a
generation counter so a batch taken before the reset is never written into
the wiped store. Shutdown drains the queue before storage shuts down and
clears the retry map only after the worker has terminated. Samples ingested
while Metrics is disabled are discarded at startup.

Integration and SDK tests poll for the sample, as they would against AWS.

* test(compat): assert recorded metric filter publishing through the SDK modules

Extends the Java compatibility module with the publishing scenarios recorded
from AWS: mixed defaults and quiet traffic, extraction and ordinary dimension
series, system dimensions on matches only, and a Sum alarm driven by quiet
defaults. Each series is read through the SDK's CloudWatch JSON protocol and
again as a signed legacy Query request, so GetMetricStatistics and
GetMetricData agree on every sample, timestamp, unit and dimension set.

Expected values come from module-local copies of the root fixture
metric-filter-publishing-aws.json. MetricFilterFixturePackagingTest checks
the Java copy loads from the classpath and the root
CloudWatchLogsMetricFilterFixturePackagingTest fails when either SDK module
copy drifts from the root file.

The Python module gains tests/metric_filter_replay.py, an opt-in replay of
the same scenarios against a Floci endpoint or, with explicit profile,
region and write acknowledgement, against AWS. Its logic is covered offline
by tests/test_metric_filter_replay.py with the network blocked. Both module
Dockerfiles are unchanged: the Java image already runs the whole suite and
the Python image already copies tests/.

* test(compat): assert every recorded statistic and poll for published samples

The SDK publishing assertions compared only Sum and SampleCount although the
AWS fixture also records Minimum and Maximum for the default-value scenarios.
Both the SDK JSON reads and the signed legacy Query reads now assert every
statistic the fixture carries, on GetMetricStatistics and GetMetricData.

Publication now happens shortly after PutLogEvents returns, so present series
are polled and absent series are asserted only after a later positive control
of the same filter is visible, which the publisher's ordering guarantees. The
read window ends at second 59 so a sample stamped on the following minute is
never in scope.

The live replay's Region check names the commercial partition explicitly.
botocore already defaults get_available_regions to partition_name="aws", so
GovCloud and China Regions were rejected before; the offline test now pins it.

* test(compat): keep the metric filter SDK test on the Java 17 API of the compat image

List.getLast() is Java 21; the sdk-test-java image compiles with Temurin 17.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-17 13:53:35 -04:00
1 parent a3da2a3767
commit 22b0627245
88 files changed
+19188 -101

No files matched your search

@@ -17,8 +17,11 @@ import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -84,4 +87,37 @@ class EmulatorInfoControllerTest {
verify(sageMakerTeardown).stopManagedContainers();
verify(storageFactory).clearAll();
}
@Test
@DisplayName("Should call beforeReset on every service before the wipe and afterReset after every clear")
void reset_bracketsTheWipeWithBeforeAndAfterHooks() {
Resettable second = mock(Resettable.class);
when(containerTeardowns.iterator()).thenReturn(List.<ContainerTeardown>of().iterator());
when(resettables.iterator()).thenReturn(List.of(resettable, second).iterator());
controller.reset();
InOrder order = inOrder(storageFactory, resettable, second);
order.verify(resettable).beforeReset();
order.verify(second).beforeReset();
order.verify(storageFactory).clearAll();
order.verify(resettable).clear();
order.verify(second).clear();
order.verify(second).afterReset();
order.verify(resettable).afterReset();
}
@Test
@DisplayName("Should still call afterReset when the storage wipe fails, then rethrow")
void reset_runsAfterResetWhenTheWipeFails() {
doThrow(new IllegalStateException("wipe failed")).when(storageFactory).clearAll();
when(containerTeardowns.iterator()).thenReturn(List.<ContainerTeardown>of().iterator());
when(resettables.iterator()).thenReturn(List.of(resettable).iterator());
assertThrows(IllegalStateException.class, controller::reset);
verify(resettable).beforeReset();
verify(resettable).afterReset();
verify(resettable, never()).clear();
}
}
@@ -67,6 +67,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEve
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEventSourceMappingCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaVersionAliasCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsMetricFilterCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.PipesCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.RdsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftClusterCfnProvisioner;
@@ -82,6 +83,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudForm
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsMetricFilterService;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cognito.CognitoService;
@@ -182,6 +184,7 @@ final class CfnProvisionerFixture {
// dispatcher. They exist only so inferredProvisioners() can wire their provisioner.
private FlowLogService flowLogService;
private CloudWatchDashboardsService cloudWatchDashboardsService;
private CloudWatchLogsMetricFilterService logsMetricFilterService;
private IotDomainConfigurationService iotDomainConfigurationService;
private IotService iotService;
private LambdaMicrovmsService lambdaMicrovmsService;
@@ -267,6 +270,9 @@ final class CfnProvisionerFixture {
if (logsService != null) {
discovered.add(new LogsCfnProvisioner(logsService));
}
if (logsMetricFilterService != null) {
discovered.add(new LogsMetricFilterCfnProvisioner(logsMetricFilterService));
}
if (kinesisService != null) {
discovered.add(new KinesisCfnProvisioner(kinesisService));
}
@@ -571,6 +577,11 @@ final class CfnProvisionerFixture {
return this;
}
public Builder logsMetricFilters(CloudWatchLogsMetricFilterService v) {
this.logsMetricFilterService = v;
return this;
}
public Builder iotDomainConfiguration(IotDomainConfigurationService v) {
this.iotDomainConfigurationService = v;
return this;
@@ -0,0 +1,758 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsMetricFilterService;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsMetricFilterService.MutationOutcome;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsMetricFilterService.MutationResult;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import jakarta.inject.Inject;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doCallRealMethod;
/**
* Provisions an {@code AWS::Logs::MetricFilter} through a CloudFormation stack and reads it back
* through the Logs API. Ref and physical id are filter names. A name change deletes before create;
* a failed update restores the complete backing definition;
* and the stack delete removes the filter.
*/
@QuarkusTest
class CloudFormationLogsMetricFilterIntegrationTest {
@InjectSpy
CloudWatchLogsMetricFilterService metricFilterService;
@Inject
CloudFormationService cloudFormationService;
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260908/us-east-1/cloudformation/aws4_request";
private static final String LOGS_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String LOGS_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260908/us-east-1/logs/aws4_request";
private static final Map<String, Set<String>> PRIOR_EVENTS = new ConcurrentHashMap<>();
private static final String TEMPLATE = """
{
"Parameters": {
"FilterName": {"Type": "String"},
"Pattern": {"Type": "String", "Default": "ERROR"}
},
"Resources": {
"Filter": {
"Type": "AWS::Logs::MetricFilter",
"Properties": {
"LogGroupName": "%s",
"FilterName": {"Ref": "FilterName"},
"FilterPattern": {"Ref": "Pattern"},
"MetricTransformations": [{
"MetricName": "ErrorCount",
"MetricNamespace": "Stack/%s",
"MetricValue": "1",
"DefaultValue": 0,
"Unit": "Count"
}]
}
}%s
},
"Outputs": {
"FilterRef": {"Value": {"Ref": "Filter"}}
}
}
""";
private static final String UNNAMED_TEMPLATE = """
{
"Resources": {
"Filter": {
"Type": "AWS::Logs::MetricFilter",
"Properties": {
"LogGroupName": "%s",
"FilterPattern": "{ $.latency = * }",
"MetricTransformations": [{
"MetricName": "Latency",
"MetricNamespace": "Stack/%s",
"MetricValue": "$.latency",
"Dimensions": [{"Key": "Route", "Value": "$.route"}]
}]
}
}
},
"Outputs": {
"FilterRef": {"Value": {"Ref": "Filter"}}
}
}
""";
/** The log group in a stack of its own, so the filter stacks hold nothing else. */
private static final String GROUP_TEMPLATE = """
{
"Resources": {
"LogGroup": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "%s"}
}
}
}
""";
/** A resource that fails after the filter, so the update rolls back. */
private static final String FAILING_RESOURCE = """
,
"BadSecret": {
"Type": "AWS::SecretsManager::Secret",
"DependsOn": "Filter",
"Properties": {
"Name": "metric-filter-rollback-%s",
"SecretString": "explicit",
"GenerateSecretString": {"PasswordLength": 32}
}
}""";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void filterFollowsTheTemplateThroughCreateUpdateReplacementAndDelete() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-metric-filter-" + suffix;
String groupStack = "cfn-metric-filter-group-" + suffix;
String group = "/cfn/metric-filter/" + suffix;
createGroupStack(groupStack, group);
String template = TEMPLATE.formatted(group, suffix, "");
cloudFormation(stack, "CreateStack", template, Map.of("FilterName", "errors"));
assertEquals("errors", outputValue(describeStacks(stack, "CREATE_COMPLETE"), "FilterRef"));
describeFilters(group).then()
.statusCode(200)
.body("metricFilters", hasSize(1))
.body("metricFilters[0].filterName", equalTo("errors"))
.body("metricFilters[0].filterPattern", equalTo("ERROR"))
.body("metricFilters[0].metricTransformations[0].metricName", equalTo("ErrorCount"))
.body("metricFilters[0].metricTransformations[0].metricNamespace", equalTo("Stack/" + suffix))
.body("metricFilters[0].metricTransformations[0].metricValue", equalTo("1"))
.body("metricFilters[0].metricTransformations[0].defaultValue", equalTo(0.0f))
.body("metricFilters[0].metricTransformations[0].unit", equalTo("Count"));
cloudFormation(stack, "UpdateStack", template, Map.of("FilterName", "errors", "Pattern", "FATAL"));
assertEquals("errors", outputValue(describeStacks(stack, "UPDATE_COMPLETE"), "FilterRef"),
"a pattern change keeps the same filter");
describeFilters(group).then()
.statusCode(200)
.body("metricFilters", hasSize(1))
.body("metricFilters[0].filterPattern", equalTo("FATAL"));
cloudFormation(stack, "UpdateStack", template, Map.of("FilterName", "fatal", "Pattern", "FATAL"));
assertEquals("fatal", outputValue(describeStacks(stack, "UPDATE_COMPLETE"), "FilterRef"),
"a name change is a replacement");
describeFilters(group).then()
.statusCode(200)
.body("metricFilters", hasSize(1))
.body("metricFilters[0].filterName", equalTo("fatal"));
assertResourceSequence(stack, List.of("errors:UPDATE_IN_PROGRESS", "errors:DELETE_IN_PROGRESS",
"errors:DELETE_COMPLETE", "fatal:CREATE_IN_PROGRESS", "fatal:CREATE_COMPLETE", "fatal:UPDATE_COMPLETE"));
assertTrue(describeEvents(stack).contains(
"Requested update requires the replacement of the existing resource; deleting existing resource, then creating a new one."));
cloudFormation(stack, "DeleteStack", null, Map.of());
awaitStackDeleted(stack);
describeFilters(group).then()
.statusCode(200)
.body("metricFilters", hasSize(0));
cloudFormation(groupStack, "DeleteStack", null, Map.of());
awaitStackDeleted(groupStack);
}
@Test
void anUnnamedFilterGetsAGeneratedNameAndItsDimensionsReachTheService() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-metric-filter-unnamed-" + suffix;
String groupStack = "cfn-metric-filter-unnamed-group-" + suffix;
String group = "/cfn/metric-filter/unnamed/" + suffix;
createGroupStack(groupStack, group);
String template = UNNAMED_TEMPLATE.formatted(group, suffix);
cloudFormation(stack, "CreateStack", template, Map.of());
String ref = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "FilterRef");
assertTrue(ref.startsWith(stack + "-Filter-"), ref);
describeFilters(group).then()
.statusCode(200)
.body("metricFilters", hasSize(1))
.body("metricFilters[0].metricTransformations[0].metricValue", equalTo("$.latency"))
.body("metricFilters[0].metricTransformations[0].dimensions.Route", equalTo("$.route"));
cloudFormation(stack, "UpdateStack", template.replace("$.latency = *", "$.latency > 10"), Map.of());
assertEquals(ref, outputValue(describeStacks(stack, "UPDATE_COMPLETE"), "FilterRef"),
"an unnamed filter keeps its generated name");
describeFilters(group).then().body("metricFilters[0].filterPattern", equalTo("{ $.latency > 10 }"));
cloudFormation(stack, "DeleteStack", null, Map.of());
awaitStackDeleted(stack);
cloudFormation(groupStack, "DeleteStack", null, Map.of());
awaitStackDeleted(groupStack);
}
@Test
void aFailedUpdateRestoresThePatternAnInPlaceUpdateChanged() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-metric-filter-rb-" + suffix;
String groupStack = "cfn-metric-filter-rb-group-" + suffix;
String group = "/cfn/metric-filter/rb/" + suffix;
createGroupStack(groupStack, group);
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(group, suffix, ""), Map.of("FilterName", "errors"));
describeStacks(stack, "CREATE_COMPLETE");
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(group, suffix, FAILING_RESOURCE.formatted(suffix)),
Map.of("FilterName", "errors", "Pattern", "FATAL"));
assertEquals("errors", outputValue(describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"), "FilterRef"));
describeFilters(group).then()
.statusCode(200)
.body("metricFilters", hasSize(1))
.body("metricFilters[0].filterPattern", equalTo("ERROR"));
assertMutationPrecedesBadSecret(stack, "errors");
assertPublishedValue(group, "Stack/" + suffix, "ERROR", 1);
cloudFormation(stack, "DeleteStack", null, Map.of());
awaitStackDeleted(stack);
cloudFormation(groupStack, "DeleteStack", null, Map.of());
awaitStackDeleted(groupStack);
}
@Test
void aFailedUpdateRollsAReplacementBack() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-metric-filter-rb2-" + suffix;
String groupStack = "cfn-metric-filter-rb2-group-" + suffix;
String group = "/cfn/metric-filter/rb2/" + suffix;
createGroupStack(groupStack, group);
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(group, suffix, ""), Map.of("FilterName", "errors"));
describeStacks(stack, "CREATE_COMPLETE");
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(group, suffix, FAILING_RESOURCE.formatted(suffix)),
Map.of("FilterName", "fatal"));
assertEquals("errors", outputValue(describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"), "FilterRef"));
describeFilters(group).then()
.statusCode(200)
.body("metricFilters", hasSize(1))
.body("metricFilters[0].filterName", equalTo("errors"));
assertMutationPrecedesBadSecret(stack, "fatal");
assertPublishedValue(group, "Stack/" + suffix, "ERROR", 1);
assertResourceSequence(stack, List.of("errors:UPDATE_IN_PROGRESS", "errors:DELETE_IN_PROGRESS",
"errors:DELETE_COMPLETE", "fatal:CREATE_IN_PROGRESS", "fatal:CREATE_COMPLETE", "fatal:UPDATE_COMPLETE",
"fatal:UPDATE_IN_PROGRESS", "fatal:DELETE_IN_PROGRESS", "fatal:DELETE_COMPLETE",
"fatal:CREATE_IN_PROGRESS", "errors:CREATE_COMPLETE", "errors:UPDATE_COMPLETE"));
cloudFormation(stack, "DeleteStack", null, Map.of());
awaitStackDeleted(stack);
cloudFormation(groupStack, "DeleteStack", null, Map.of());
awaitStackDeleted(groupStack);
}
@Test
void invalidReplacementDeletesThenRecreatesPriorDefinitionWithNameOnlyRefAndEvents() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-metric-filter-invalid-replace-" + suffix;
String groupStack = stack + "-group";
String group = "/cfn/invalid-replace/" + suffix;
createGroupStack(groupStack, group);
String original = TEMPLATE.formatted(group, suffix, "").replace("\"MetricValue\": \"1\"", "\"MetricValue\": \"2\"");
cloudFormation(stack, "CreateStack", original, Map.of("FilterName", "old", "Pattern", "WARN"));
describeStacks(stack, "CREATE_COMPLETE");
Map<String, Object> before = describeFilters(group).jsonPath().getMap("metricFilters[0]");
cloudFormation(stack, "UpdateStack", original.replace("\"MetricValue\": \"2\"", "\"MetricValue\": \"9\""),
Map.of("FilterName", "new", "Pattern", "{"));
assertEquals("old", outputValue(describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"), "FilterRef"));
Map<String, Object> after = describeFilters(group).jsonPath().getMap("metricFilters[0]");
assertNotNull(after, "rollback must restore the deleted backing filter, not just its Ref");
assertTrue(((Number) after.get("creationTime")).longValue() > ((Number) before.get("creationTime")).longValue());
after.remove("creationTime");
before.remove("creationTime");
assertEquals(before, after);
assertResourceSequence(stack, List.of("old:UPDATE_IN_PROGRESS", "old:DELETE_IN_PROGRESS", "old:DELETE_COMPLETE",
"new:CREATE_IN_PROGRESS", "new:CREATE_FAILED", "new:UPDATE_FAILED", "new:UPDATE_IN_PROGRESS",
"new:DELETE_IN_PROGRESS", "new:DELETE_COMPLETE", "new:CREATE_IN_PROGRESS",
"old:CREATE_COMPLETE", "old:UPDATE_COMPLETE"));
assertPublishedValue(group, "Stack/" + suffix, "WARN", 2);
String template = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "GetTemplate").formParam("StackName", stack).post("/").asString();
assertTrue(template.contains("MetricValue"), template);
assertTrue(template.contains("&quot;2&quot;") || template.contains("\"2\""), template);
cloudFormation(stack, "DeleteStack", null, Map.of());
awaitStackDeleted(stack);
cloudFormation(groupStack, "DeleteStack", null, Map.of());
awaitStackDeleted(groupStack);
}
@Test
void resolvedArrayIntrinsicsAndNoValueUseCfnShapes() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-metric-filter-intrinsics-" + suffix;
String groupStack = stack + "-group";
String group = "/cfn/intrinsics/" + suffix;
createGroupStack(groupStack, group);
String template = """
{"Parameters":{"Enabled":{"Type":"String","Default":"false"}},
"Conditions":{"UseDimensions":{"Fn::Equals":[{"Ref":"Enabled"},"true"]}},
"Resources":{"Filter":{"Type":"AWS::Logs::MetricFilter","Properties":{
"LogGroupName":"%s", "FilterName":{"Ref":"AWS::NoValue"}, "FilterPattern":"",
"ApplyOnTransformedLogs":{"Ref":"Enabled"},
"MetricTransformations":{"Fn::If":["UseDimensions",[],[
{"MetricName":"ErrorCount","MetricNamespace":"Stack/%s","MetricValue":"1",
"Dimensions":{"Fn::If":["UseDimensions",[],{"Ref":"AWS::NoValue"}]}}]]},
"EmitSystemFieldDimensions":{"Fn::Split":[",","@aws.account,@aws.region"]}}}},
"Outputs":{"FilterRef":{"Value":{"Ref":"Filter"}}}}
""".formatted(group, suffix);
cloudFormation(stack, "CreateStack", template, Map.of());
String ref = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "FilterRef");
assertTrue(ref.startsWith(stack + "-Filter-"), ref);
describeFilters(group).then().body("metricFilters[0].applyOnTransformedLogs", equalTo(false))
.body("metricFilters[0].emitSystemFieldDimensions", hasSize(2));
cloudFormation(stack, "DeleteStack", null, Map.of());
awaitStackDeleted(stack);
cloudFormation(groupStack, "DeleteStack", null, Map.of());
awaitStackDeleted(groupStack);
}
@ParameterizedTest
@ValueSource(strings = {"confirmedRestore", "uncertainRestore", "uncertainReplacement", "confirmedAddedDelete"})
void deleteStackPreservesFailedRollbackOwnershipUntilResourceAwareCleanup(String fault) throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-metric-filter-delete-failed-" + suffix;
String group = "/cfn/external-delete-failed/" + suffix;
boolean uncertain = fault.startsWith("uncertain");
boolean added = "confirmedAddedDelete".equals(fault);
String faultName = added ? "added" : "uncertainReplacement".equals(fault) ? "new" : "old";
given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.CreateLogGroup")
.body(Map.of("logGroupName", group)).post("/").then().statusCode(200);
try {
given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.PutMetricFilter")
.body(Map.of("logGroupName", group, "filterName", "unrelated", "filterPattern", "UNRELATED",
"metricTransformations", List.of(Map.of("metricName", "Unrelated",
"metricNamespace", "Other/" + suffix, "metricValue", "7"))))
.post("/").then().statusCode(200);
Map<String, Object> unrelated = backingFilter(group, "unrelated");
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(group, suffix, ""),
Map.of("FilterName", "old", "Pattern", "WARN"));
describeStacks(stack, "CREATE_COMPLETE");
doAnswer(invocation -> {
MetricFilter definition = invocation.getArgument(0);
if (added || !group.equals(definition.getLogGroupName()) || !faultName.equals(definition.getFilterName())) {
return invocation.callRealMethod();
}
assertTrue(metricFilterService.findMetricFilter(group, faultName, "us-east-1").isEmpty());
if (uncertain) {
// Persist the real definition but withhold the ownership acknowledgement,
// simulating a write followed by an unavailable ownership inspection.
metricFilterService.putMetricFilter(definition, "us-east-1");
Consumer<MutationResult> outcome = invocation.getArgument(2);
outcome.accept(new MutationResult(MutationOutcome.UNKNOWN, null));
} else {
invocation.callRealMethod();
}
throw new AwsException("ServiceUnavailableException", "injected " + fault + " after write", 500);
}).when(metricFilterService).createMetricFilter(any(), anyString(), any());
String additions = FAILING_RESOURCE.formatted(suffix);
if (added) {
doAnswer(invocation -> {
Consumer<MutationResult> outcome = invocation.getArgument(3);
outcome.accept(new MutationResult(MutationOutcome.NOT_APPLIED, true));
throw new AwsException("ServiceUnavailableException", "injected added-filter rollback deletion", 500);
}).doCallRealMethod().when(metricFilterService)
.deleteMetricFilter(eq(group), eq("added"), eq("us-east-1"), any());
additions = """
,"AddedFilter":{"Type":"AWS::Logs::MetricFilter","Properties":{
"LogGroupName":"%s","FilterName":"added","FilterPattern":"WARN",
"MetricTransformations":[{"MetricName":"Added","MetricNamespace":"Stack/%s","MetricValue":"1"}]}}
""".formatted(group, suffix)
+ additions.replace("\"DependsOn\": \"Filter\"", "\"DependsOn\": \"AddedFilter\"");
}
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(group, suffix, additions),
Map.of("FilterName", added ? "old" : "new", "Pattern", "FATAL"));
describeStacks(stack, "UPDATE_ROLLBACK_FAILED");
StackResource failed = cloudFormationService.describeStacks(stack, "us-east-1")
.getFirst().getResources().get(added ? "AddedFilter" : "Filter");
assertEquals("UPDATE_FAILED", failed.getStatus());
String snapshot = failed.getAttributes().get(CfnRollback.METRIC_FILTER_UPDATE_SNAPSHOT_ATTR);
if (added) {
assertNull(snapshot, "new resources carry create ownership, not an update snapshot");
assertEquals("true", failed.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
} else {
assertNotNull(snapshot);
String address = "uncertainReplacement".equals(fault) ? "target" : "prior";
assertEquals(uncertain ? "UNKNOWN" : "OWNED",
new ObjectMapper().readTree(snapshot).path(address).path("ownership").asText(), snapshot);
}
assertNotNull(backingFilter(group, faultName), "the failed write really created a backing filter");
if (uncertain) {
for (int attempt = 0; attempt < 2; attempt++) {
assertThrows(ExecutionException.class, () -> cloudFormationService
.deleteStack(stack, "us-east-1", "000000000000").get(10, TimeUnit.SECONDS));
describeStacks(stack, "DELETE_FAILED");
StackResource retained = cloudFormationService.describeStacks(stack, "us-east-1")
.getFirst().getResources().get("Filter");
assertEquals("DELETE_FAILED", retained.getStatus());
assertEquals(snapshot, retained.getAttributes().get(CfnRollback.METRIC_FILTER_UPDATE_SNAPSHOT_ATTR));
assertNotNull(backingFilter(group, faultName));
assertEquals(unrelated, backingFilter(group, "unrelated"));
}
metricFilterService.deleteMetricFilter(group, faultName, "us-east-1");
}
assertDoesNotThrow(() -> cloudFormationService.deleteStack(stack, "us-east-1", "000000000000")
.get(10, TimeUnit.SECONDS));
assertTrue(metricFilterService.findMetricFilter(group, "old", "us-east-1").isEmpty(),
"DeleteStack must clean the owned restoration before reporting completion");
assertTrue(metricFilterService.findMetricFilter(group, "new", "us-east-1").isEmpty());
assertTrue(metricFilterService.findMetricFilter(group, "added", "us-east-1").isEmpty(),
"a failed rollback delete of a newly owned resource must also be retried");
assertEquals(unrelated, backingFilter(group, "unrelated"));
given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.DescribeLogGroups")
.body(Map.of("logGroupNamePrefix", group)).post("/").then().statusCode(200)
.body("logGroups[0].logGroupName", equalTo(group));
assertThrows(AwsException.class, () -> cloudFormationService.describeStacks(stack, "us-east-1"));
} finally {
doCallRealMethod().when(metricFilterService).createMetricFilter(any(), anyString(), any());
doCallRealMethod().when(metricFilterService).deleteMetricFilter(anyString(), anyString(), anyString(), any());
for (String name : List.of("old", "new", "added")) {
if (metricFilterService.findMetricFilter(group, name, "us-east-1").isPresent()) {
metricFilterService.deleteMetricFilter(group, name, "us-east-1");
}
}
cloudFormationService.deleteStack(stack, "us-east-1", "000000000000").get(10, TimeUnit.SECONDS);
given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.DeleteLogGroup")
.body(Map.of("logGroupName", group)).post("/").then().statusCode(200);
}
}
private static Map<String, Object> backingFilter(String group, String name) {
List<Map<String, Object>> filters = describeFilters(group).jsonPath().getList("metricFilters");
return filters.stream().filter(filter -> name.equals(filter.get("filterName"))).findFirst().orElse(null);
}
@ParameterizedTest
@CsvSource({"forward,false", "forward,true", "stack,false", "stack,true"})
void appliedAndUnknownDeletesDoNotClaimAConcurrentOwnersFilter(String phase, boolean unknown) throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-delete-outcome-" + suffix;
String group = "/cfn/external-delete-outcome/" + suffix;
ObjectMapper mapper = new ObjectMapper();
given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.CreateLogGroup")
.body(Map.of("logGroupName", group)).post("/").then().statusCode(200);
try {
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(group, suffix, ""),
Map.of("FilterName", "old", "Pattern", "WARN"));
describeStacks(stack, "CREATE_COMPLETE");
MetricFilter original = metricFilterService.findMetricFilter(group, "old", "us-east-1").orElseThrow();
MetricFilter stable = mapper.convertValue(original, MetricFilter.class);
stable.setFilterName("unrelated");
metricFilterService.putMetricFilter(stable, "us-east-1");
Map<String, Object> unrelated = backingFilter(group, "unrelated");
AtomicReference<MetricFilter> otherOwner = new AtomicReference<>();
AtomicBoolean armed = new AtomicBoolean(true);
doAnswer(invocation -> {
String requestedGroup = invocation.getArgument(0);
String requestedName = invocation.getArgument(1);
if (!group.equals(requestedGroup) || !"old".equals(requestedName) || !armed.compareAndSet(true, false)) {
return invocation.callRealMethod();
}
if (unknown) {
metricFilterService.deleteMetricFilter(group, "old", "us-east-1");
Consumer<MutationResult> outcome = invocation.getArgument(3);
outcome.accept(new MutationResult(MutationOutcome.UNKNOWN, null));
} else {
invocation.callRealMethod();
}
MetricFilter b = mapper.convertValue(original, MetricFilter.class);
b.setFilterPattern("UNRELATED");
b.getMetricTransformations().getFirst().setMetricValue("7");
otherOwner.set(metricFilterService.putMetricFilter(b, "us-east-1"));
throw new AwsException("ServiceUnavailableException", "injected failure after delete", 500);
}).when(metricFilterService).deleteMetricFilter(anyString(), anyString(), anyString(), any());
if ("forward".equals(phase)) {
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(group, suffix, ""),
Map.of("FilterName", "new", "Pattern", "FATAL"));
describeStacks(stack, "UPDATE_ROLLBACK_FAILED");
} else {
assertThrows(ExecutionException.class, () -> cloudFormationService
.deleteStack(stack, "us-east-1", "000000000000").get(10, TimeUnit.SECONDS));
describeStacks(stack, "DELETE_FAILED");
}
assertNotNull(otherOwner.get(), "B must be created after the actual delete and before A handles its failure");
assertEquals(mapper.valueToTree(otherOwner.get()),
mapper.valueToTree(mapper.convertValue(backingFilter(group, "old"), MetricFilter.class)));
StackResource resource = cloudFormationService.describeStacks(stack, "us-east-1")
.getFirst().getResources().get("Filter");
String metadataKey = "forward".equals(phase) ? CfnRollback.METRIC_FILTER_UPDATE_SNAPSHOT_ATTR
: "__FlociMetricFilterState";
String metadata = resource.getAttributes().get(metadataKey);
assertNotNull(metadata);
JsonNode state = mapper.readTree(metadata);
if ("forward".equals(phase)) {
state = state.path("prior");
}
assertEquals(unknown ? "UNKNOWN" : "UNOWNED", state.path("ownership").asText());
if (unknown) {
for (int attempt = 0; attempt < 2; attempt++) {
assertThrows(ExecutionException.class, () -> cloudFormationService
.deleteStack(stack, "us-east-1", "000000000000").get(10, TimeUnit.SECONDS));
describeStacks(stack, "DELETE_FAILED");
assertEquals(metadata, cloudFormationService.describeStacks(stack, "us-east-1").getFirst()
.getResources().get("Filter").getAttributes().get(metadataKey));
assertEquals(mapper.valueToTree(otherOwner.get()),
mapper.valueToTree(mapper.convertValue(backingFilter(group, "old"), MetricFilter.class)));
}
metricFilterService.deleteMetricFilter(group, "old", "us-east-1");
}
assertDoesNotThrow(() -> cloudFormationService.deleteStack(stack, "us-east-1", "000000000000")
.get(10, TimeUnit.SECONDS));
if (!unknown) {
assertEquals(mapper.valueToTree(otherOwner.get()),
mapper.valueToTree(mapper.convertValue(backingFilter(group, "old"), MetricFilter.class)));
}
assertEquals(unrelated, backingFilter(group, "unrelated"));
given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.DescribeLogGroups")
.body(Map.of("logGroupNamePrefix", group)).post("/").then().statusCode(200)
.body("logGroups[0].logGroupName", equalTo(group));
} finally {
doCallRealMethod().when(metricFilterService).deleteMetricFilter(anyString(), anyString(), anyString(), any());
for (String name : List.of("old", "new")) {
if (metricFilterService.findMetricFilter(group, name, "us-east-1").isPresent()) {
metricFilterService.deleteMetricFilter(group, name, "us-east-1");
}
}
cloudFormationService.deleteStack(stack, "us-east-1", "000000000000").get(10, TimeUnit.SECONDS);
given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.DeleteLogGroup")
.body(Map.of("logGroupName", group)).post("/").then().statusCode(200);
}
}
private static List<Map<String, String>> newEvents(String stack) {
List<Map<String, String>> events = new ArrayList<>(XmlParser.extractGroups(describeEvents(stack), "member"));
Collections.reverse(events);
return events.stream().filter(e -> !PRIOR_EVENTS.getOrDefault(stack, Set.of()).contains(e.get("EventId"))).toList();
}
private static void assertResourceSequence(String stack, List<String> expected) {
List<Map<String, String>> events = newEvents(stack);
assertEquals(events.size(), events.stream().map(e -> e.get("EventId")).distinct().count());
assertEquals(expected, events.stream().filter(e -> "Filter".equals(e.get("LogicalResourceId")))
.map(e -> e.get("PhysicalResourceId") + ":" + e.get("ResourceStatus")).toList());
}
private static void assertMutationPrecedesBadSecret(String stack, String physicalId) {
List<Map<String, String>> events = newEvents(stack);
int mutation = -1;
int failure = -1;
for (int i = 0; i < events.size(); i++) {
Map<String, String> e = events.get(i);
if ("Filter".equals(e.get("LogicalResourceId")) && physicalId.equals(e.get("PhysicalResourceId"))
&& "UPDATE_COMPLETE".equals(e.get("ResourceStatus")) && mutation == -1) {
mutation = i;
}
if ("BadSecret".equals(e.get("LogicalResourceId")) && "UPDATE_FAILED".equals(e.get("ResourceStatus"))) {
failure = i;
}
}
assertTrue(mutation >= 0 && failure > mutation, events.toString());
}
private static void assertPublishedValue(String group, String namespace, String message, int value) {
long timestamp = System.currentTimeMillis();
String stream = "verify-" + timestamp;
given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.CreateLogStream")
.body(Map.of("logGroupName", group, "logStreamName", stream)).post("/").then().statusCode(200);
given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.PutLogEvents")
.body(Map.of("logGroupName", group, "logStreamName", stream,
"logEvents", List.of(Map.of("timestamp", timestamp, "message", message))))
.post("/").then().statusCode(200);
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> given().contentType("application/x-amz-json-1.0")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260908/us-east-1/monitoring/aws4_request")
.header("X-Amz-Target", "GraniteServiceVersion20100801.GetMetricStatistics")
.body(Map.of("Namespace", namespace, "MetricName", "ErrorCount", "Period", 60,
"StartTime", (timestamp - 60_000) / 1000.0, "EndTime", (timestamp + 60_000) / 1000.0,
"Statistics", List.of("Sum", "SampleCount")))
.post("/").then().statusCode(200)
.body("Datapoints", hasSize(1)).body("Datapoints[0].Sum", equalTo((float) value))
.body("Datapoints[0].SampleCount", equalTo(1.0f)));
}
@Test
void anInvalidPatternFailsTheResource() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-metric-filter-bad-" + suffix;
String groupStack = "cfn-metric-filter-bad-group-" + suffix;
String group = "/cfn/metric-filter/bad/" + suffix;
createGroupStack(groupStack, group);
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(group, suffix, ""),
Map.of("FilterName", "bad", "Pattern", "{ $.a = }"));
String events = awaitStackStatus(stack, "ROLLBACK_COMPLETE");
assertTrue(events.contains("Invalid filter pattern"), "the status reason carries the parse error: " + events);
cloudFormation(stack, "DeleteStack", null, Map.of());
awaitStackDeleted(stack);
cloudFormation(groupStack, "DeleteStack", null, Map.of());
awaitStackDeleted(groupStack);
}
private static void createGroupStack(String stack, String group) {
cloudFormation(stack, "CreateStack", GROUP_TEMPLATE.formatted(group), Map.of());
describeStacks(stack, "CREATE_COMPLETE");
}
private static Response describeFilters(String group) {
return given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328.DescribeMetricFilters")
.body("{\"logGroupName\":\"" + group + "\"}").post("/");
}
private static void cloudFormation(String stack, String action, String templateBody,
Map<String, String> parameters) {
if ("UpdateStack".equals(action)) {
PRIOR_EVENTS.put(stack, XmlParser.extractGroups(describeEvents(stack), "member").stream()
.map(e -> e.get("EventId")).collect(Collectors.toSet()));
}
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
if (templateBody != null) {
request.formParam("TemplateBody", templateBody);
}
int index = 1;
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
index++;
}
request.when().post("/").then().statusCode(200);
}
private static String describeStacks(String stack, String expectedStatus) {
String body = "";
for (int i = 0; i < 100; i++) {
body = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stack).post("/").asString();
if (body.contains("<StackStatus>" + expectedStatus + "</StackStatus>")
&& newEvents(stack).stream().anyMatch(e -> stack.equals(e.get("LogicalResourceId"))
&& expectedStatus.equals(e.get("ResourceStatus")))) {
return body;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError(e);
}
}
return fail("Expected new " + expectedStatus + " for " + stack + ": " + body + "\n" + describeEvents(stack));
}
private static String describeEvents(String stack) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200).extract().asString();
}
private static String awaitStackStatus(String stack, String expectedStatus) throws InterruptedException {
for (int i = 0; i < 100; i++) {
String body = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().extract().asString();
if (body.contains("<StackStatus>" + expectedStatus + "</StackStatus>")) {
return describeEvents(stack);
}
Thread.sleep(50);
}
return fail("stack " + stack + " did not reach " + expectedStatus + " within the timeout");
}
private static void awaitStackDeleted(String stack) throws InterruptedException {
for (int i = 0; i < 100; i++) {
String body = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().extract().asString();
if (body.contains("does not exist")) {
return;
}
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
fail("stack delete failed: " + body);
}
Thread.sleep(50);
}
fail("stack " + stack + " was not deleted within the timeout");
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
}
@@ -0,0 +1,380 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricTransformation;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.SubscriptionFilter;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class CloudWatchLogsFilterQuotaTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String GROUP = "/quota";
private static final String TWO_REGEXES = "{ $.a = %ERROR% || $.a = %WARN% }";
@ParameterizedTest
@CsvSource({"false,true", "false,false", "true,true", "true,false"})
void fiveRegexBearingFiltersCanEachHoldTwoExpressions(boolean factoryConstructor, boolean metric) {
Fixture fixture = new Fixture(factoryConstructor);
for (int i = 0; i < 5; i++) {
fixture.put(metric, "f" + i, TWO_REGEXES);
}
rejected(() -> fixture.put(metric, "sixth", "%INFO%"), "LimitExceededException");
fixture.put(metric, "f0", TWO_REGEXES);
fixture.put(metric, "plain", "INFO");
assertEquals(6, metric ? fixture.metricStore.keys().size() : fixture.subscriptions.keys().size());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void bothConstructorPathsShareThePoolAcrossFilterFamilies(boolean factoryConstructor) {
Fixture fixture = new Fixture(factoryConstructor);
for (int i = 0; i < 4; i++) {
fixture.put(true, "m" + i, "%ERROR%");
}
fixture.put(false, "s0", "%ERROR%");
rejected(() -> fixture.put(false, "s1", "%WARN%"), "LimitExceededException");
rejected(() -> fixture.put(true, "m4", "%WARN%"), "LimitExceededException");
}
@Test
void replacementsAreFamilySpecificAndRejectedUpdatesLeaveTheStoredDefinitionUnchanged() {
Fixture fixture = new Fixture(false);
for (int i = 0; i < 3; i++) {
fixture.put(true, "m" + i, "%ERROR%");
}
fixture.put(true, "shared", "%ERROR%");
fixture.put(false, "shared", "%ERROR%");
fixture.put(true, "shared", TWO_REGEXES);
fixture.put(false, "shared", TWO_REGEXES);
fixture.put(true, "plain", "ORIGINAL");
fixture.put(false, "plain", "ORIGINAL");
MetricFilter metric = fixture.metricStore.get(metricKey("plain")).orElseThrow();
SubscriptionFilter subscription = fixture.subscriptions.get(subscriptionKey("plain")).orElseThrow();
rejected(() -> fixture.put(true, "plain", "%ERROR%"), "LimitExceededException");
rejected(() -> fixture.put(false, "plain", "%ERROR%"), "LimitExceededException");
assertSame(metric, fixture.metricStore.get(metricKey("plain")).orElseThrow());
assertSame(subscription, fixture.subscriptions.get(subscriptionKey("plain")).orElseThrow());
assertEquals("ORIGINAL", metric.getFilterPattern());
assertEquals("ORIGINAL", subscription.getFilterPattern());
fixture.put(true, "shared", "PLAIN");
fixture.put(false, "plain", "%ERROR%");
rejected(() -> fixture.put(true, "plain", "%ERROR%"), "LimitExceededException");
fixture.put(false, "shared", "PLAIN");
fixture.put(true, "plain", "%ERROR%");
fixture.metrics.deleteMetricFilter(GROUP, "plain", REGION);
fixture.put(false, "new-subscription", "%ERROR%");
fixture.logs.deleteSubscriptionFilter(GROUP, "plain", REGION);
fixture.put(true, "new-metric", "%ERROR%");
rejected(() -> fixture.put(true, "sixth", "%ERROR%"), "LimitExceededException");
}
@ParameterizedTest
@ValueSource(strings = {"%ERROR% %WARN%", "{ $.a = }",
"{ $.a = %ERROR% || $.a = %WARN% || $.a = %INFO% }"})
void subscriptionPatternsUseTheSameGrammarAndPerPatternQuota(String pattern) {
Fixture fixture = new Fixture(false);
fixture.put(false, "original", "ORIGINAL");
rejected(() -> fixture.put(false, "original", pattern), "InvalidParameterException");
assertEquals("ORIGINAL", fixture.subscriptions.get(subscriptionKey("original")).orElseThrow().getFilterPattern());
}
@Test
void regexFiltersBeyondTheFirstSubscriptionPageStillCount() {
Fixture fixture = new Fixture(false);
for (int i = 0; i < 51; i++) {
fixture.put(false, "a" + i, "PLAIN");
}
for (int i = 0; i < 5; i++) {
fixture.put(false, "z" + i, "%ERROR%");
}
rejected(() -> fixture.put(true, "sixth", "%ERROR%"), "LimitExceededException");
}
@ParameterizedTest
@CsvSource({"true,true", "true,false", "false,true", "false,false"})
void storageFailuresCannotSilentlyFreeQuota(boolean metricStorageFails, boolean metricWriter) {
Fixture fixture = new Fixture(false);
IllegalStateException failure = new IllegalStateException("quota storage unavailable");
if (metricStorageFails) {
doThrow(failure).when(fixture.metricStore).scan(any());
} else {
doThrow(failure).when(fixture.subscriptions).scan(any());
}
assertSame(failure, assertThrows(IllegalStateException.class,
() -> fixture.put(metricWriter, "candidate", "%ERROR%")));
assertTrue(fixture.metricStore.keys().isEmpty());
assertTrue(fixture.subscriptions.keys().isEmpty());
}
@ParameterizedTest
@CsvSource({"true,true", "true,false", "false,true", "false,false"})
void invalidStoredPatternsCannotSilentlyFreeQuota(boolean invalidMetric, boolean metricWriter) {
Fixture fixture = new Fixture(false);
if (invalidMetric) {
fixture.metricStore.put(metricKey("corrupt"), definition("corrupt", "{ $.a = }"));
} else {
SubscriptionFilter corrupt = new SubscriptionFilter();
corrupt.setLogGroupName(GROUP);
corrupt.setFilterName("corrupt");
corrupt.setFilterPattern("{ $.a = }");
fixture.subscriptions.put(subscriptionKey("corrupt"), corrupt);
}
rejected(() -> fixture.put(metricWriter, "candidate", "%ERROR%"), "InvalidParameterException");
assertTrue(fixture.metricStore.get(metricKey("candidate")).isEmpty());
assertTrue(fixture.subscriptions.get(subscriptionKey("candidate")).isEmpty());
}
@Test
void quotaAndGroupDeletionAreIsolatedByAccountRegionAndGroup() {
RequestContext context = new RequestContext();
context.setAccountId(ACCOUNT);
@SuppressWarnings("unchecked")
Instance<RequestContext> contexts = mock(Instance.class);
when(contexts.get()).thenReturn(context);
Fixture fixture = new Fixture(contexts);
for (int i = 0; i < 5; i++) {
fixture.put(i % 2 == 0, "f" + i, "%ERROR%");
}
fixture.logs.createLogGroup(GROUP, null, null, "eu-west-1");
fixture.logs.putSubscriptionFilter(GROUP, "other-region", TWO_REGEXES, "destination", null, "eu-west-1");
fixture.logs.createLogGroup("/other-group", null, null, REGION);
fixture.logs.putSubscriptionFilter("/other-group", "other-group", TWO_REGEXES, "destination", null, REGION);
context.setAccountId("111111111111");
fixture.logs.createLogGroup(GROUP, null, null, REGION);
for (int i = 0; i < 5; i++) {
fixture.put(i % 2 == 0, "f" + i, "%ERROR%");
}
rejected(() -> fixture.put(false, "sixth", "%ERROR%"), "LimitExceededException");
fixture.logs.deleteLogGroup(GROUP, REGION);
context.setAccountId(ACCOUNT);
rejected(() -> fixture.put(true, "sixth", "%ERROR%"), "LimitExceededException");
assertEquals(3, fixture.metrics.countMetricFilters(GROUP, REGION));
assertEquals(2, fixture.logs.describeSubscriptionFilters(GROUP, null, null, 50, REGION)
.subscriptionFilters().size());
assertEquals(1, fixture.logs.describeSubscriptionFilters(GROUP, null, null, 50, "eu-west-1")
.subscriptionFilters().size());
assertEquals(1, fixture.logs.describeSubscriptionFilters("/other-group", null, null, 50, REGION)
.subscriptionFilters().size());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void deletingAGroupCascadesBothFamiliesWithoutRequiringAnEventObserver(boolean factoryConstructor) {
Fixture fixture = new Fixture(factoryConstructor);
fixture.put(true, "metric", "%ERROR%");
fixture.put(false, "subscription", "%ERROR%");
fixture.logs.deleteLogGroup(GROUP, REGION);
assertTrue(fixture.metricStore.keys().isEmpty());
assertTrue(fixture.subscriptions.keys().isEmpty());
rejected(() -> fixture.put(true, "orphan", "%ERROR%"), "ResourceNotFoundException");
rejected(() -> fixture.put(false, "orphan", "%ERROR%"), "ResourceNotFoundException");
fixture.logs.createLogGroup(GROUP, null, null, REGION);
for (int i = 0; i < 5; i++) {
fixture.put(i % 2 == 0, "new" + i, "%ERROR%");
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void crossFamilyWritersCannotBothClaimTheLastSlot(boolean metricFirst) throws Exception {
Fixture fixture = new Fixture(false);
for (int i = 0; i < 4; i++) {
fixture.put(true, "existing" + i, "%ERROR%");
}
CountDownLatch inWrite = new CountDownLatch(1);
CountDownLatch finishWrite = new CountDownLatch(1);
if (metricFirst) {
gateWrite(fixture.metricStore, inWrite, finishWrite);
} else {
gateWrite(fixture.subscriptions, inWrite, finishWrite);
}
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> first = pool.submit(() -> fixture.put(metricFirst, "first", "%ERROR%"));
assertTrue(inWrite.await(5, TimeUnit.SECONDS));
CyclicBarrier start = new CyclicBarrier(2);
Future<?> second = pool.submit(() -> {
start.await(5, TimeUnit.SECONDS);
rejected(() -> fixture.put(!metricFirst, "second", "%ERROR%"), "LimitExceededException");
return null;
});
start.await(5, TimeUnit.SECONDS);
assertThrows(TimeoutException.class, () -> second.get(200, TimeUnit.MILLISECONDS),
"the second writer must wait until the first check-and-write completes");
finishWrite.countDown();
first.get(5, TimeUnit.SECONDS);
second.get(5, TimeUnit.SECONDS);
assertEquals(metricFirst ? 5 : 4, fixture.metricStore.keys().size());
assertEquals(metricFirst ? 0 : 1, fixture.subscriptions.keys().size());
} finally {
finishWrite.countDown();
pool.shutdownNow();
assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void groupDeletionCannotLeaveAConcurrentFilterWriteOrphaned(boolean metricWriter) throws Exception {
Fixture fixture = new Fixture(false);
CountDownLatch inWrite = new CountDownLatch(1);
CountDownLatch finishWrite = new CountDownLatch(1);
if (metricWriter) {
gateWrite(fixture.metricStore, inWrite, finishWrite);
} else {
gateWrite(fixture.subscriptions, inWrite, finishWrite);
}
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> writer = pool.submit(() -> fixture.put(metricWriter, "racing", "%ERROR%"));
assertTrue(inWrite.await(5, TimeUnit.SECONDS));
CyclicBarrier start = new CyclicBarrier(2);
Future<?> deletion = pool.submit(() -> {
start.await(5, TimeUnit.SECONDS);
fixture.logs.deleteLogGroup(GROUP, REGION);
return null;
});
start.await(5, TimeUnit.SECONDS);
assertThrows(TimeoutException.class, () -> deletion.get(200, TimeUnit.MILLISECONDS),
"the cascade must wait for an in-flight filter write");
finishWrite.countDown();
writer.get(5, TimeUnit.SECONDS);
deletion.get(5, TimeUnit.SECONDS);
assertFalse(fixture.logs.logGroupExists(GROUP, REGION));
assertTrue(fixture.metricStore.keys().isEmpty());
assertTrue(fixture.subscriptions.keys().isEmpty());
} finally {
finishWrite.countDown();
pool.shutdownNow();
assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
private static <T> void gateWrite(StorageBackend<String, T> store, CountDownLatch entered,
CountDownLatch release) {
doAnswer(invocation -> {
entered.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return invocation.callRealMethod();
}).when(store).put(anyString(), any());
}
private static void rejected(Runnable operation, String code) {
assertEquals(code, assertThrows(AwsException.class, operation::run).getErrorCode());
}
private static String metricKey(String name) {
return REGION + "::" + GROUP + "::" + name;
}
private static String subscriptionKey(String name) {
return REGION + "::" + GROUP + "::filter::" + name;
}
private static MetricFilter definition(String name, String pattern) {
MetricTransformation transformation = new MetricTransformation();
transformation.setMetricName("Errors");
transformation.setMetricNamespace("Quota");
transformation.setMetricValue("1");
MetricFilter filter = new MetricFilter();
filter.setLogGroupName(GROUP);
filter.setFilterName(name);
filter.setFilterPattern(pattern);
filter.setMetricTransformations(List.of(transformation));
return filter;
}
private static final class Fixture {
private final StorageBackend<String, MetricFilter> metricStore;
private final StorageBackend<String, SubscriptionFilter> subscriptions;
private final CloudWatchLogsService logs;
private final CloudWatchLogsMetricFilterService metrics;
private Fixture(boolean factoryConstructor) {
this(factoryConstructor, null);
}
private Fixture(Instance<RequestContext> contexts) {
this(false, contexts);
}
private Fixture(boolean factoryConstructor, Instance<RequestContext> contexts) {
RegionResolver resolver = new RegionResolver(REGION, ACCOUNT);
CloudWatchMetricsService publisher = mock(CloudWatchMetricsService.class);
if (factoryConstructor) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
when(config.storage().persistentPath()).thenReturn("target/quota-test-storage");
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode("cloudwatchlogs")).thenReturn("memory");
StorageFactory factory = new StorageFactory(config, access);
metricStore = factory.create("cloudwatchlogs", "cwlogs-metric-filters.json",
new TypeReference<Map<String, MetricFilter>>() {});
subscriptions = factory.create("cloudwatchlogs", "cwlogs-subscription-filters.json",
new TypeReference<Map<String, SubscriptionFilter>>() {});
logs = new CloudWatchLogsService(factory, config, resolver, null, null);
metrics = new CloudWatchLogsMetricFilterService(logs, publisher, resolver);
} else {
metricStore = spy(new AccountAwareStorageBackend<MetricFilter>(new InMemoryStorage<>(), contexts, ACCOUNT));
subscriptions = spy(new AccountAwareStorageBackend<SubscriptionFilter>(new InMemoryStorage<>(), contexts, ACCOUNT));
logs = new CloudWatchLogsService(
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), contexts, ACCOUNT),
new InMemoryStorage<>(), new InMemoryStorage<>(), subscriptions, metricStore, 10_000, resolver);
metrics = new CloudWatchLogsMetricFilterService(logs, publisher, resolver);
}
logs.createLogGroup(GROUP, null, null, REGION);
}
private void put(boolean metric, String name, String pattern) {
if (metric) {
metrics.putMetricFilter(definition(name, pattern), REGION);
} else {
logs.putSubscriptionFilter(GROUP, name, pattern, "destination", null, REGION);
}
}
}
}
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -15,6 +16,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.mockito.Mockito.mock;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -50,6 +52,7 @@ class CloudWatchLogsHandlerTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
10_000,
new RegionResolver(REGION, ACCOUNT)
);
@@ -58,6 +61,8 @@ class CloudWatchLogsHandlerTest {
new CloudWatchLogsCrossAccountService(
new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT), MAPPER),
new CloudWatchLogsMetricFilterService(service,
mock(CloudWatchMetricsService.class), new RegionResolver(REGION, ACCOUNT)),
MAPPER);
service.createLogGroup(GROUP, null, null, REGION);
@@ -6,9 +6,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -35,6 +37,7 @@ class CloudWatchLogsInputConstraintTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
10_000,
new RegionResolver(REGION, ACCOUNT)
);
@@ -43,6 +46,8 @@ class CloudWatchLogsInputConstraintTest {
new CloudWatchLogsCrossAccountService(
new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT), MAPPER),
new CloudWatchLogsMetricFilterService(service,
mock(CloudWatchMetricsService.class), new RegionResolver(REGION, ACCOUNT)),
MAPPER);
service.createLogGroup(GROUP, null, null, REGION);
service.createLogStream(GROUP, "s1", REGION);
@@ -46,6 +46,7 @@ class CloudWatchLogsInsightsQueryTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
10000,
new RegionResolver(REGION, "000000000000"));
}
@@ -674,7 +675,7 @@ class CloudWatchLogsInsightsQueryTest {
private CloudWatchLogsService newAsyncService(AtomicLong clockMs, long delayMs, String group, String stream) {
CloudWatchLogsService svc = new CloudWatchLogsService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
10000, new RegionResolver(REGION, "000000000000"), delayMs, clockMs::get);
new InMemoryStorage<>(), 10000, new RegionResolver(REGION, "000000000000"), delayMs, clockMs::get);
createGroupStream(svc, group, stream);
putRaw(svc, group, stream, BASE_MS + 2000, jobLog("INFO", "x", "JOB-1"));
return svc;
@@ -0,0 +1,27 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
class CloudWatchLogsMetricFilterFixturePackagingTest {
@ParameterizedTest
@ValueSource(strings = {
"compatibility-tests/sdk-test-java/src/test/resources/cloudwatchlogs/metric-filter-publishing-aws.json",
"compatibility-tests/sdk-test-python/tests/fixtures/metric-filter-publishing-aws.json"
})
void sdkModuleFixtureIsAnExactCopyOfTheCanonicalAwsOracle(String modulePath) throws Exception {
Path copy = Path.of(modulePath);
assertTrue(Files.isRegularFile(copy), "SDK module must package its own fixture: " + modulePath);
try (InputStream canonical = getClass().getResourceAsStream("/cloudwatchlogs/metric-filter-publishing-aws.json")) {
assertNotNull(canonical);
assertArrayEquals(canonical.readAllBytes(), Files.readAllBytes(copy),
"Copy canonical bytes; never regenerate expected values from emulator output");
}
}
}
@@ -0,0 +1,185 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
* The metric filter operations through the Logs handler: request members in the JSON 1.1 form the
* API takes, responses in the shape the API reference lists, and the real filter count on
* DescribeLogGroups.
*/
class CloudWatchLogsMetricFilterHandlerTest {
private static final String REGION = "us-east-1";
private static final String GROUP = "/app/api";
private static final ObjectMapper MAPPER = new ObjectMapper();
private CloudWatchLogsHandler handler;
@BeforeEach
void setUp() {
CloudWatchLogsService service = new CloudWatchLogsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
10_000, new RegionResolver(REGION, "000000000000"));
handler = new CloudWatchLogsHandler(service,
new CloudWatchLogsCrossAccountService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"), MAPPER),
new CloudWatchLogsMetricFilterService(service,
mock(CloudWatchMetricsService.class), new RegionResolver(REGION, "000000000000")),
MAPPER);
service.createLogGroup(GROUP, null, null, REGION);
}
private JsonNode call(String action, String json) {
try {
Response response = handler.handle(action, MAPPER.readTree(json), REGION);
assertEquals(200, response.getStatus());
return MAPPER.valueToTree(response.getEntity());
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
private static final String PUT = """
{"logGroupName": "/app/api", "filterName": "errors", "filterPattern": "[..., status_code, size]",
"metricTransformations": [{"metricName": "Volume", "metricNamespace": "Web", "metricValue": "$size",
"dimensions": {"Status": "$status_code"}, "unit": "Bytes"}],
"applyOnTransformedLogs": false, "emitSystemFieldDimensions": ["@aws.region"]}
""";
@Test
void putThenDescribeRoundTripsTheApiShape() {
JsonNode putResponse = call("PutMetricFilter", PUT);
assertTrue(putResponse.isObject() && putResponse.isEmpty(), "PutMetricFilter answers an empty object");
JsonNode described = call("DescribeMetricFilters", "{\"logGroupName\": \"/app/api\"}");
assertEquals(1, described.path("metricFilters").size());
JsonNode filter = described.path("metricFilters").get(0);
assertEquals("errors", filter.path("filterName").asText());
assertEquals("/app/api", filter.path("logGroupName").asText());
assertEquals("[..., status_code, size]", filter.path("filterPattern").asText());
assertTrue(filter.path("creationTime").asLong() > 0);
assertFalse(filter.path("applyOnTransformedLogs").asBoolean());
assertEquals("@aws.region", filter.path("emitSystemFieldDimensions").get(0).asText());
JsonNode t = filter.path("metricTransformations").get(0);
assertEquals("Volume", t.path("metricName").asText());
assertEquals("Web", t.path("metricNamespace").asText());
assertEquals("$size", t.path("metricValue").asText());
assertEquals("$status_code", t.path("dimensions").path("Status").asText());
assertEquals("Bytes", t.path("unit").asText());
assertFalse(t.has("defaultValue"), "an unset default value is left out");
assertFalse(described.has("nextToken"));
}
@Test
void defaultValueIsANumberOnTheWire() {
call("PutMetricFilter", """
{"logGroupName": "/app/api", "filterName": "errors", "filterPattern": "ERROR",
"metricTransformations": [{"metricName": "Errors", "metricNamespace": "App", "metricValue": "1",
"defaultValue": 0}]}
""");
JsonNode t = call("DescribeMetricFilters", "{\"logGroupName\": \"/app/api\"}")
.path("metricFilters").get(0).path("metricTransformations").get(0);
assertTrue(t.path("defaultValue").isNumber());
assertEquals(0.0, t.path("defaultValue").asDouble());
AwsException e = assertThrows(AwsException.class, () -> call("PutMetricFilter", """
{"logGroupName": "/app/api", "filterName": "bad", "filterPattern": "ERROR",
"metricTransformations": [{"metricName": "Errors", "metricNamespace": "App", "metricValue": "1",
"defaultValue": "zero"}]}
"""));
assertEquals("SerializationException", e.getErrorCode());
}
@Test
void describeHonoursLimitAndNextToken() {
for (int i = 0; i < 3; i++) {
call("PutMetricFilter", PUT.replace("\"errors\"", "\"f" + i + "\""));
}
JsonNode first = call("DescribeMetricFilters", "{\"logGroupName\": \"/app/api\", \"limit\": 2}");
assertEquals(2, first.path("metricFilters").size());
String token = first.path("nextToken").asText();
JsonNode second = call("DescribeMetricFilters",
"{\"logGroupName\": \"/app/api\", \"limit\": 2, \"nextToken\": \"" + token + "\"}");
assertEquals(1, second.path("metricFilters").size());
assertFalse(second.has("nextToken"));
}
@Test
void describeRequiresMetricNameAndNamespaceTogether() {
String message = "Describe Metric Filters request must contain both MetricName and MetricNamespace";
AwsException namespaceOnly = assertThrows(AwsException.class,
() -> call("DescribeMetricFilters", "{\"metricNamespace\": \"Web\"}"));
assertEquals("InvalidParameterException", namespaceOnly.getErrorCode());
assertEquals(message, namespaceOnly.getMessage());
AwsException nameOnly = assertThrows(AwsException.class,
() -> call("DescribeMetricFilters", "{\"metricName\": \"Volume\"}"));
assertEquals("InvalidParameterException", nameOnly.getErrorCode());
assertEquals(message, nameOnly.getMessage());
assertEquals(0, call("DescribeMetricFilters", "{\"metricName\": \"Volume\", \"metricNamespace\": \"Web\"}")
.path("metricFilters").size());
}
@Test
void describeLogGroupsCountsTheFilters() {
assertEquals(0, call("DescribeLogGroups", "{}").path("logGroups").get(0).path("metricFilterCount").asInt());
call("PutMetricFilter", PUT);
call("PutMetricFilter", PUT.replace("\"errors\"", "\"more\""));
assertEquals(2, call("DescribeLogGroups", "{}").path("logGroups").get(0).path("metricFilterCount").asInt());
}
@Test
void deleteRemovesTheFilter() {
call("PutMetricFilter", PUT);
JsonNode response = call("DeleteMetricFilter", "{\"logGroupName\": \"/app/api\", \"filterName\": \"errors\"}");
assertTrue(response.isObject() && response.isEmpty());
assertEquals(0, call("DescribeMetricFilters", "{\"logGroupName\": \"/app/api\"}").path("metricFilters").size());
AwsException e = assertThrows(AwsException.class, () -> call("DeleteMetricFilter",
"{\"logGroupName\": \"/app/api\", \"filterName\": \"errors\"}"));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void testMetricFilterAnswersTheReferenceShape() {
JsonNode response = call("TestMetricFilter", """
{"filterPattern": "[..., status_code=200, size]",
"logEventMessages": [
"127.0.0.1 - frank [10/Oct/2000:13:25:15 -0700] \\"GET /apache_pb.gif HTTP/1.0\\" 200 1534",
"127.0.0.1 - frank [10/Oct/2000:13:35:22 -0700] \\"GET /apache_pb.gif HTTP/1.0\\" 500 5324"]}
""");
assertEquals(1, response.path("matches").size());
JsonNode match = response.path("matches").get(0);
assertEquals(1, match.path("eventNumber").asLong());
assertTrue(match.path("eventMessage").asText().endsWith("200 1534"));
assertEquals("1534", match.path("extractedValues").path("$size").asText());
assertEquals("200", match.path("extractedValues").path("$status_code").asText());
assertEquals("127.0.0.1", match.path("extractedValues").path("$1").asText());
JsonNode terms = call("TestMetricFilter",
"{\"filterPattern\": \"\\\"[ERROR]\\\"\", \"logEventMessages\": [\"[INFO] up\", \"[ERROR] down\"]}");
assertEquals(2, terms.path("matches").get(0).path("eventNumber").asLong());
assertTrue(terms.path("matches").get(0).path("extractedValues").isObject());
assertTrue(terms.path("matches").get(0).path("extractedValues").isEmpty());
}
}
@@ -0,0 +1,234 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Metric filters over the wire: PutMetricFilter, DescribeMetricFilters, TestMetricFilter and
* DeleteMetricFilter as the Logs API takes them, the metric a filter publishes when PutLogEvents
* stores matching events, read back through CloudWatch GetMetricStatistics, and the filters going
* with their log group.
*/
@QuarkusTest
class CloudWatchLogsMetricFilterIntegrationTest {
private static final String LOGS_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String LOGS_AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260908/us-east-1/logs/aws4_request";
private static final String CW_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String CW_AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260908/us-east-1/monitoring/aws4_request";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static Response logs(String action, String body) {
return given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH)
.header("X-Amz-Target", "Logs_20140328." + action).body(body).post("/");
}
private static Response cloudWatch(String action, String body) {
return given().contentType(CW_CONTENT_TYPE).header("Authorization", CW_AUTH)
.header("X-Amz-Target", "GraniteServiceVersion20100801." + action).body(body).post("/");
}
private static void createGroupAndStream(String group, String stream) {
logs("CreateLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200);
logs("CreateLogStream", "{\"logGroupName\":\"" + group + "\",\"logStreamName\":\"" + stream + "\"}")
.then().statusCode(200);
}
private static void putLogEvents(String group, String stream, long timestamp, List<String> messages) {
StringBuilder events = new StringBuilder();
for (int i = 0; i < messages.size(); i++) {
events.append(i > 0 ? "," : "").append("{\"timestamp\":").append(timestamp + i)
.append(",\"message\":").append(quote(messages.get(i))).append("}");
}
logs("PutLogEvents", "{\"logGroupName\":\"" + group + "\",\"logStreamName\":\"" + stream
+ "\",\"logEvents\":[" + events + "]}").then().statusCode(200);
}
private static String quote(String text) {
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
private static Response statistics(String namespace, String metric, String dimensionName, String dimensionValue,
Instant from, Instant to) {
String dimensions = dimensionName == null ? ""
: ",\"Dimensions\":[{\"Name\":\"" + dimensionName + "\",\"Value\":\"" + dimensionValue + "\"}]";
return cloudWatch("GetMetricStatistics", "{\"Namespace\":\"" + namespace + "\",\"MetricName\":\"" + metric
+ "\",\"Period\":60,\"StartTime\":" + from.getEpochSecond() + ",\"EndTime\":" + to.getEpochSecond()
+ ",\"Statistics\":[\"Sum\",\"SampleCount\"]" + dimensions + "}");
}
private static double sum(Response statistics) {
List<Float> sums = statistics.then().statusCode(200).extract().jsonPath().getList("Datapoints.Sum", Float.class);
return sums.stream().mapToDouble(Float::doubleValue).sum();
}
@Test
void aFilterPublishesTheFieldValueWithDimensionsForMatchingEvents() {
String group = "/it/metric-filter/access-" + System.nanoTime();
createGroupAndStream(group, "web");
logs("PutMetricFilter", """
{"logGroupName":"%s","filterName":"volume","filterPattern":"[..., status_code, size]",
"metricTransformations":[{"metricName":"Volume","metricNamespace":"%s","metricValue":"$size",
"dimensions":{"Status":"$status_code"},"unit":"Bytes"}]}
""".formatted(group, group)).then().statusCode(200);
long now = System.currentTimeMillis();
putLogEvents(group, "web", now, List.of(
"127.0.0.1 - frank [10/Oct/2000:13:25:15 -0700] \"GET /index.html HTTP/1.0\" 200 1534",
"127.0.0.1 - frank [10/Oct/2000:13:35:22 -0700] \"GET /index.html HTTP/1.0\" 500 5324",
"127.0.0.1 - frank [10/Oct/2000:13:50:35 -0700] \"GET /index.html HTTP/1.0\" 200 4355",
"not an access log line"));
Instant from = Instant.ofEpochMilli(now).minusSeconds(120);
Instant to = Instant.ofEpochMilli(now).plusSeconds(120);
// The 4355 sample is the batch's last write, so its sum arriving means the 500 sample is stored too.
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertEquals(1534 + 4355, sum(statistics(group, "Volume", "Status", "200", from, to)), 0.001));
assertEquals(5324, sum(statistics(group, "Volume", "Status", "500", from, to)), 0.001);
assertEquals(0, sum(statistics(group, "Volume", "Status", "404", from, to)), 0.001);
}
@Test
void nonmatchDefaultsPublishPerEventWithoutSyntheticClosingEvents() {
String group = "/it/metric-filter/quiet-" + System.nanoTime();
createGroupAndStream(group, "app");
logs("PutMetricFilter", """
{"logGroupName":"%s","filterName":"quiet","filterPattern":"ERROR",
"metricTransformations":[{"metricName":"ErrorCount","metricNamespace":"%s","metricValue":"3",
"defaultValue":7}]}
""".formatted(group, group)).then().statusCode(200);
// Newly ingested historical events belong to their event minute, even before filter creation.
long time = (System.currentTimeMillis() / 60_000 - 10) * 60_000;
putLogEvents(group, "app", time, List.of("INFO one", "INFO two", "INFO three"));
Instant from = Instant.ofEpochMilli(time);
Instant to = from.plusSeconds(59);
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertEquals(21, sum(statistics(group, "ErrorCount", null, null, from, to)), 0.001));
for (int read = 0; read < 2; read++) {
Response result = statistics(group, "ErrorCount", null, null, from, to);
assertEquals(21, sum(result), 0.001);
result.then().body("Datapoints", hasSize(1)).body("Datapoints[0].SampleCount", equalTo(3.0f));
}
statistics(group, "ErrorCount", null, null, to.plusSeconds(1), to.plusSeconds(60)).then()
.statusCode(200).body("Datapoints", hasSize(0));
logs("DeleteLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200);
}
@Test
void putDescribeTestAndDeleteFollowTheApi() {
String group = "/it/metric-filter/api-" + System.nanoTime();
createGroupAndStream(group, "s");
logs("PutMetricFilter", """
{"logGroupName":"%s","filterName":"latency","filterPattern":"{ $.latency = * }",
"metricTransformations":[{"metricName":"Latency","metricNamespace":"App","metricValue":"$.latency",
"unit":"Milliseconds"}]}
""".formatted(group)).then().statusCode(200);
logs("DescribeMetricFilters", "{\"logGroupName\":\"" + group + "\"}").then()
.statusCode(200)
.body("metricFilters", hasSize(1))
.body("metricFilters[0].filterName", equalTo("latency"))
.body("metricFilters[0].logGroupName", equalTo(group))
.body("metricFilters[0].filterPattern", equalTo("{ $.latency = * }"))
.body("metricFilters[0].metricTransformations[0].metricName", equalTo("Latency"))
.body("metricFilters[0].metricTransformations[0].metricNamespace", equalTo("App"))
.body("metricFilters[0].metricTransformations[0].metricValue", equalTo("$.latency"))
.body("metricFilters[0].metricTransformations[0].unit", equalTo("Milliseconds"))
.body("nextToken", nullValue());
logs("DescribeMetricFilters", "{\"metricName\":\"Latency\",\"metricNamespace\":\"App\"}").then()
.statusCode(200)
.body("metricFilters.logGroupName", org.hamcrest.Matchers.hasItem(group));
logs("DescribeLogGroups", "{\"logGroupNamePrefix\":\"" + group + "\"}").then()
.statusCode(200)
.body("logGroups[0].metricFilterCount", equalTo(1));
logs("TestMetricFilter", """
{"filterPattern":"{ $.latency = * }","logEventMessages":["{\\"latency\\": 50}","plain text"]}
""").then()
.statusCode(200)
.body("matches", hasSize(1))
.body("matches[0].eventNumber", equalTo(1))
.body("matches[0].eventMessage", equalTo("{\"latency\": 50}"))
.body("matches[0].extractedValues", equalTo(Map.of()));
logs("PutMetricFilter", """
{"logGroupName":"%s","filterName":"broken","filterPattern":"{ $.a = }",
"metricTransformations":[{"metricName":"A","metricNamespace":"App","metricValue":"1"}]}
""".formatted(group)).then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"));
logs("PutMetricFilter", """
{"logGroupName":"/it/metric-filter/missing","filterName":"x","filterPattern":"ERROR",
"metricTransformations":[{"metricName":"A","metricNamespace":"App","metricValue":"1"}]}
""").then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
logs("DeleteMetricFilter", "{\"logGroupName\":\"" + group + "\",\"filterName\":\"latency\"}").then()
.statusCode(200);
logs("DeleteMetricFilter", "{\"logGroupName\":\"" + group + "\",\"filterName\":\"latency\"}").then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
logs("DescribeMetricFilters", "{\"logGroupName\":\"" + group + "\"}").then()
.statusCode(200)
.body("metricFilters", hasSize(0));
}
@Test
void deletingTheLogGroupDeletesItsFilters() {
String group = "/it/metric-filter/cascade-" + System.nanoTime();
createGroupAndStream(group, "s");
logs("PutMetricFilter", """
{"logGroupName":"%s","filterName":"errors","filterPattern":"ERROR",
"metricTransformations":[{"metricName":"Errors","metricNamespace":"Cascade","metricValue":"1"}]}
""".formatted(group)).then().statusCode(200);
logs("DeleteLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200);
logs("DescribeMetricFilters", "{\"metricName\":\"Errors\",\"metricNamespace\":\"Cascade\"}").then()
.statusCode(200)
.body("metricFilters.logGroupName", not(hasItem(group)));
logs("DescribeMetricFilters", "{\"logGroupName\":\"" + group + "\"}").then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void describeRequiresMetricNameAndNamespaceTogether() {
String message = "Describe Metric Filters request must contain both MetricName and MetricNamespace";
logs("DescribeMetricFilters", "{\"metricNamespace\":\"ProbeNs\"}").then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"))
.body("message", equalTo(message));
logs("DescribeMetricFilters", "{\"metricName\":\"ProbeMetric\"}").then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"))
.body("message", equalTo(message));
logs("DescribeMetricFilters", "{\"metricName\":\"ProbeMetric\",\"metricNamespace\":\"ProbeNs\"}").then()
.statusCode(200)
.body("metricFilters", hasSize(0));
}
}
@@ -0,0 +1,189 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsMetricFilterRetryTest.FaultStore;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsMetricFilterRetryTest.await;
import static io.github.hectorvent.floci.services.cloudwatch.logs.PublicationTestSupport.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* PutLogEvents evaluates the group's filters on the request thread and hands the resulting immutable
* samples to a bounded queue. The single publisher thread writes them; the request never waits on the
* Metrics sink. A full queue degrades to an inline write instead of dropping accepted samples.
*/
class CloudWatchLogsMetricFilterPublisherTest {
private final FaultStore sink = new FaultStore();
private final PublicationTestSupport f = new PublicationTestSupport(sink);
@AfterEach
void stop() { f.service.stop(); }
@Test
void ingestionQueuesSamplesAndWritesNothingUntilTheQueueIsDrained() {
f.put("queued", "ERROR", "3", 7.0);
f.enqueue(TIME, "ERROR", "INFO", "ERROR");
assertEquals(3, f.service.queuedSamples());
assertTrue(sink.attempts.isEmpty(), "the ingestion thread must not write to the Metrics sink");
f.stats("queued", TIME, 0, 0);
f.service.publishQueued();
assertEquals(0, f.service.queuedSamples());
f.stats("queued", TIME, 13, 3);
}
@Test
void theStartedWorkerDrainsTheQueueWithoutFurtherIngestionOrReads() throws Exception {
f.put("worker", "ERROR", "3", 7.0);
CountDownLatch written = new CountDownLatch(2);
sink.after = (key, datum) -> written.countDown();
f.service.start(true, true);
f.enqueue(TIME, "ERROR", "INFO");
assertTrue(written.await(5, TimeUnit.SECONDS), "the worker must publish queued samples on its own");
f.stats("worker", TIME, 10, 2);
assertEquals(0, f.service.queuedSamples());
}
@Test
void samplesQueuedBeforeStartAreDrainedWhenTheWorkerStarts() throws Exception {
f.put("early", "ERROR", "3", 7.0);
f.enqueue(TIME, "INFO");
CountDownLatch written = new CountDownLatch(1);
sink.after = (key, datum) -> written.countDown();
f.service.start(true, true);
assertTrue(written.await(5, TimeUnit.SECONDS));
f.stats("early", TIME, 7, 1);
}
@Test
void aFullQueueWritesTheBatchInlineInsteadOfDroppingIt() {
PublicationTestSupport bounded = new PublicationTestSupport(sink, 4);
try {
bounded.put("bounded", "ERROR", "3", 7.0);
bounded.enqueue(TIME, "INFO", "INFO", "INFO");
assertEquals(3, bounded.service.queuedSamples());
bounded.enqueue(TIME, "ERROR", "ERROR");
assertEquals(3, bounded.service.queuedSamples(), "the batch that does not fit is written at once");
bounded.stats("bounded", TIME, 6, 2);
bounded.service.publishQueued();
bounded.stats("bounded", TIME, 27, 5);
} finally {
bounded.service.stop();
}
}
@Test
void failedFirstAttemptsMoveToTheRetryQueueWithTheirIds() {
f.put("failing", "ERROR", "3", 7.0);
sink.fail = true;
f.enqueue(TIME, "ERROR", "INFO");
f.service.publishQueued();
assertEquals(0, f.service.queuedSamples());
assertEquals(2, f.service.pendingSamples());
sink.fail = false;
f.service.retryPending();
assertEquals(0, f.service.pendingSamples());
f.stats("failing", TIME, 10, 2);
assertEquals(2, sink.keys().size(), "retries replace the same publication keys");
}
@Test
void resetDiscardsQueuedSamplesAndResumesTheSameInstance() {
f.put("reset", "ERROR", "3", 7.0);
f.enqueue(TIME, "INFO", "INFO");
f.service.beforeReset();
assertEquals(0, f.service.queuedSamples());
f.service.publishQueued();
f.service.afterReset();
f.service.publishQueued();
f.stats("reset", TIME, 0, 0);
f.ingest(TIME, "INFO");
f.stats("reset", TIME, 7, 1);
}
@Test
void resetWaitsForTheActiveWriteAndNothingIsWrittenAfterItReturns() throws Exception {
f.put("midway", "ERROR", "3", 7.0);
f.enqueue(TIME, "INFO", "INFO", "INFO");
CountDownLatch inWrite = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
sink.before = (key, datum) -> { inWrite.countDown(); await(release); };
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> drain = pool.submit(f.service::publishQueued);
assertTrue(inWrite.await(5, TimeUnit.SECONDS));
Future<?> reset = pool.submit(f.service::beforeReset);
assertThrows(TimeoutException.class, () -> reset.get(100, TimeUnit.MILLISECONDS),
"reset must wait for the write holding the monitor");
sink.before = (key, datum) -> {};
release.countDown();
reset.get(5, TimeUnit.SECONDS);
int writtenWhenResetReturned = sink.attempts.size();
drain.get(5, TimeUnit.SECONDS);
assertEquals(writtenWhenResetReturned, sink.attempts.size(), "no write may follow a completed beforeReset");
assertEquals(0, f.service.queuedSamples());
f.service.afterReset();
f.service.publishQueued();
assertEquals(writtenWhenResetReturned, sink.attempts.size());
} finally {
release.countDown();
pool.shutdownNow();
assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
@Test
void aResetBetweenTwoSamplesOfABatchDiscardsTheRest() {
f.put("between", "ERROR", "3", 7.0);
f.enqueue(TIME, "INFO", "INFO", "INFO");
// The monitor is reentrant, so a reset issued from inside the first write lands exactly
// between two samples of the batch, which unfair scheduling cannot guarantee from another thread.
sink.after = (key, datum) -> {
f.service.beforeReset();
f.service.afterReset();
};
f.service.publishQueued();
assertEquals(1, sink.attempts.size(), "the samples after the reset belong to the wiped state");
assertEquals(0, f.service.queuedSamples());
sink.after = (key, datum) -> {};
f.ingest(TIME, "INFO");
f.stats("between", TIME, 14, 2);
}
@Test
void stopDrainsQueuedSamplesBeforeTheWorkerShutsDown() {
f.put("stopping", "ERROR", "3", 7.0);
f.enqueue(TIME, "ERROR", "INFO");
f.service.stop();
assertEquals(0, f.service.queuedSamples());
f.stats("stopping", TIME, 10, 2);
}
@Test
void deletingTheFilterDoesNotCancelSamplesAlreadyAccepted() {
f.put("deleted", "ERROR", "3", 7.0);
f.enqueue(TIME, "ERROR");
f.service.deleteMetricFilter(GROUP, "deleted", REGION);
f.service.publishQueued();
f.stats("deleted", TIME, 3, 1);
}
@Test
void eventsIngestedWhileDisabledAreNeverQueued() {
f.service.start(true, false);
f.put("disabled", "ERROR", "3", 7.0);
f.enqueue(TIME, "ERROR");
assertEquals(0, f.service.queuedSamples());
f.service.publishQueued();
f.stats("disabled", TIME, 0, 0);
assertEquals(List.of(), sink.attempts);
}
}
@@ -0,0 +1,225 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.services.cloudwatch.logs.PublicationTestSupport.*;
import static org.junit.jupiter.api.Assertions.*;
/** AWS observations are input data, never regenerated from emulator output. */
class CloudWatchLogsMetricFilterPublishingTest {
private static final ObjectMapper JSON = new ObjectMapper();
private PublicationTestSupport f;
@BeforeEach
void setUp() { f = new PublicationTestSupport(); }
private static JsonNode evidence(String section) throws IOException {
return JSON.readTree(CloudWatchLogsMetricFilterPublishingTest.class.getResourceAsStream(
"/cloudwatchlogs/metric-filter-publishing-aws.json")).get(section);
}
@Test
void recordedMixedAndSeparateBatchesContributePerEvent() throws IOException {
JsonNode data = evidence("metricDefaults");
int i = 0;
for (JsonNode scenario : data.get("cases")) {
String name = "case" + i;
f.put(name, data.get("filterPattern").asText(), data.get("metricValue").asText(),
data.get("defaultValue").asDouble());
for (JsonNode batch : scenario.get("batches")) {
List<String> messages = new ArrayList<>();
batch.forEach(message -> messages.add(message.asText()));
f.ingest(TIME + i * 60_000L, messages.toArray(String[]::new));
}
JsonNode expected = scenario.get("expected");
f.stats(name, TIME + i * 60_000L, expected.get("Sum").asDouble(), expected.get("SampleCount").asDouble());
assertEquals(expected.get("Minimum").asDouble(), f.points(name, List.of(), TIME + i * 60_000L, REGION)
.getFirst().minimum());
assertEquals(expected.get("Maximum").asDouble(), f.points(name, List.of(), TIME + i * 60_000L, REGION)
.getFirst().maximum());
i++;
}
}
@Test
void threeQuietNonmatchesPublishImmediatelyWithoutClosingTraffic() {
f.put("quiet", "ERROR", "3", 7.0);
f.ingest(TIME, "INFO", "INFO", "INFO");
f.stats("quiet", TIME, 21, 3);
f.stats("quiet", TIME, 21, 3);
f.stats("quiet", TIME + 60_000, 0, 0);
}
@Test
void noEventsProduceNoPointsEvenWithANonzeroDefault() {
f.put("empty", "ERROR", "3", 7.0);
f.ingest(TIME);
assertTrue(f.metrics.listMetrics(null, null, null, REGION).isEmpty());
}
@Test
void lateMatchAppendsWithoutRetractingAlreadyPublishedDefault() {
f.put("late", "ERROR", "3", 11.0);
f.ingest(TIME, "INFO");
f.stats("late", TIME, 11, 1);
f.ingest(TIME + 1_000, "ERROR");
f.stats("late", TIME, 14, 2);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void recordedExtractionDistinguishesMissingNullAndRawNonnumeric(boolean fallback) throws IOException {
JsonNode data = evidence("extraction");
f.put("extraction", data.get("filterPattern").asText(), data.get("metricValue").asText(),
fallback ? data.get("defaultValue").asDouble() : null);
int i = 0;
for (JsonNode scenario : data.get("cases")) {
long time = TIME + i++ * 60_000L;
f.ingest(time, scenario.get("message").toString());
JsonNode expected = scenario.get("expected");
boolean numeric = scenario.get("message").path("value").isNumber();
boolean present = expected.has("Sum") && (fallback || numeric);
f.stats("extraction", time, present ? expected.get("Sum").asDouble() : 0, present ? 1 : 0);
}
f.ingest(TIME + i * 60_000L, "INFO");
f.stats("extraction", TIME + i * 60_000L, fallback ? 7 : 0, fallback ? 1 : 0);
}
@Test
void ordinaryDimensionsAreAllOrNoneAsRecorded() throws IOException {
JsonNode data = evidence("ordinaryDimensions");
MetricFilter filter = definition("dimensions", data.get("filterPattern").asText(), "1", null);
filter.getMetricTransformations().getFirst().setDimensions(Map.of("A", "$.a", "B", "$.b"));
f.service.putMetricFilter(filter, REGION);
for (JsonNode message : data.get("messages")) { f.ingest(TIME, message.toString()); }
for (JsonNode series : data.get("expectedSeries")) {
List<Dimension> dims = new ArrayList<>();
series.get("dimensions").properties().forEach(entry -> dims.add(new Dimension(entry.getKey(), entry.getValue().asText())));
f.stats("dimensions", dims, TIME, series.get("Sum").asDouble(), series.get("SampleCount").asDouble());
}
f.stats("dimensions", List.of(new Dimension("A", "alpha")), TIME, 0, 0);
f.stats("dimensions", List.of(new Dimension("B", "beta")), TIME, 0, 0);
}
@Test
void recordedSystemDimensionsApplyToMatchesButNotPatternNonmatchDefaults() throws IOException {
JsonNode data = evidence("systemDimensions");
int i = 0;
for (JsonNode scenario : data.get("cases")) {
String name = "system" + i++;
MetricFilter filter = definition(name, "ERROR", "3", 7.0);
List<String> fields = new ArrayList<>();
scenario.get("emitSystemFieldDimensions").forEach(field -> fields.add(field.asText()));
filter.setEmitSystemFieldDimensions(fields);
f.service.putMetricFilter(filter, REGION);
f.ingest(TIME, "ERROR", "INFO");
for (JsonNode series : scenario.get("expectedSeries")) {
List<Dimension> dims = new ArrayList<>();
series.get("dimensions").properties().forEach(entry -> dims.add(new Dimension(entry.getKey(),
entry.getValue().asText().replace("<CALLER_ACCOUNT>", ACCOUNT))));
f.stats(name, dims, TIME, series.get("Sum").asDouble(), series.get("SampleCount").asDouble());
}
f.service.deleteMetricFilter(GROUP, name, REGION);
}
}
@Test
void inferredPolicyRetainsSystemDimensionsOnMatchingExtractionFallback() {
MetricFilter filter = definition("fallback", "{ $.probe = \"value\" || $.value = * }", "$.value", 7.0);
filter.setEmitSystemFieldDimensions(List.of("@aws.account"));
f.service.putMetricFilter(filter, REGION);
f.ingest(TIME, "{\"probe\":\"value\"}", "{\"probe\":\"value\",\"value\":null}");
f.stats("fallback", List.of(new Dimension("@aws.account", ACCOUNT)), TIME, 14, 2);
f.stats("fallback", TIME, 0, 0);
}
@Test
void inferredPolicyDropsIncompleteOrdinarySetButRetainsSystemDimensions() {
MetricFilter filter = definition("incomplete", "{ $.a = * || $.b = * }", "1", null);
filter.getMetricTransformations().getFirst().setDimensions(Map.of("A", "$.a", "B", "$.b"));
filter.setEmitSystemFieldDimensions(List.of("@aws.region"));
f.service.putMetricFilter(filter, REGION);
f.ingest(TIME, "{\"a\":\"alpha\"}");
f.stats("incomplete", List.of(new Dimension("@aws.region", REGION)), TIME, 1, 1);
f.stats("incomplete", List.of(new Dimension("A", "alpha"), new Dimension("@aws.region", REGION)), TIME, 0, 0);
}
@Test
void timestampsComeFromEventsIncludingBeforeCreationAndFutureNotIngestionTime() {
f.put("time", "ERROR", "3", 7.0);
long future = (System.currentTimeMillis() / 60_000 + 10) * 60_000;
f.ingest(TIME, "ERROR", "INFO");
f.ingest(future, "ERROR", "INFO");
f.stats("time", TIME, 10, 2);
f.stats("time", future, 10, 2);
assertEquals("Count", f.points("time", List.of(), TIME, REGION).getFirst().unit());
}
@Test
void spaceDelimitedFieldsStillFeedValuesAndDimensions() {
MetricFilter filter = definition("space", "[..., status_code, size]", "$size", null);
filter.getMetricTransformations().getFirst().setDimensions(Map.of("Status", "$status_code", "Method", "$1"));
f.service.putMetricFilter(filter, REGION);
f.ingest(TIME, "GET /index.html 200 1534");
f.stats("space", List.of(new Dimension("Status", "200"), new Dimension("Method", "GET")), TIME, 1534, 1);
}
@Test
void selectionRunsBeforeBothMatchesAndDefaults() {
MetricFilter filter = definition("selection", "ERROR", "3", 7.0);
filter.setFieldSelectionCriteria("@aws.account = \"" + OTHER_ACCOUNT + "\" AND @aws.region = \"" + REGION + "\"");
f.service.putMetricFilter(filter, REGION);
f.ingest(TIME, "ERROR", "INFO");
f.stats("selection", TIME, 0, 0);
f.account.set(OTHER_ACCOUNT);
f.group(GROUP, REGION);
f.service.putMetricFilter(filter, REGION);
f.account.set(ACCOUNT);
f.ingest(OTHER_ACCOUNT, GROUP, REGION, TIME, List.of("ERROR", "INFO"));
f.stats("selection", TIME, 0, 0);
f.account.set(OTHER_ACCOUNT);
f.stats("selection", TIME, 10, 2);
}
@Test
void selectionRegionExcludesBothDefaultAndMatchBeforePublication() {
MetricFilter filter = definition("region", "ERROR", "3", 7.0);
filter.setFieldSelectionCriteria("@aws.region = \"us-east-1\"");
f.service.putMetricFilter(filter, REGION);
f.ingest(TIME, "ERROR", "INFO");
f.stats("region", TIME, 0, 0);
filter.setFieldSelectionCriteria("@aws.region = \"" + REGION + "\"");
f.service.putMetricFilter(filter, REGION);
f.ingest(TIME, "ERROR", "INFO");
f.stats("region", TIME, 10, 2);
}
@Test
void otherGroupsRegionsAndAccountsDoNotUseTheCallersFilters() {
f.put("isolation", "ERROR", "3", 7.0);
f.group("/other", REGION);
f.group(GROUP, "us-east-1");
f.ingest(null, "/other", REGION, TIME, List.of("ERROR", "INFO"));
f.ingest(null, GROUP, "us-east-1", TIME, List.of("ERROR", "INFO"));
f.account.set(OTHER_ACCOUNT);
f.group(GROUP, REGION);
f.ingest(TIME, "ERROR", "INFO");
f.stats("isolation", TIME, 0, 0);
f.account.set(ACCOUNT);
f.stats("isolation", TIME, 0, 0);
f.ingest(TIME, "ERROR");
f.stats("isolation", TIME, 3, 1);
}
}
@@ -0,0 +1,144 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricTransformation;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
class CloudWatchLogsMetricFilterReferenceTest {
private static final String REGION = "eu-west-1";
private static final String GROUP = "/synthetic/reference-validation";
private static final String SCALAR_PATTERN = "{ $.probe = \"yes\" }";
private static final String WILDCARD_PATTERN = "{ $.values[*] = * }";
private static final ObjectMapper MAPPER = new ObjectMapper();
private CloudWatchLogsMetricFilterService service;
private CloudWatchMetricsService metrics;
@BeforeEach
void setUp() {
RegionResolver resolver = new RegionResolver(REGION, "000000000000");
CloudWatchLogsService logs = new CloudWatchLogsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), 10_000, resolver);
logs.createLogGroup(GROUP, null, null, REGION);
metrics = mock(CloudWatchMetricsService.class);
service = new CloudWatchLogsMetricFilterService(logs, metrics, resolver);
}
static Stream<Arguments> verifiedLiveAwsCases() throws Exception {
try (InputStream input = CloudWatchLogsMetricFilterReferenceTest.class.getResourceAsStream(
"/cloudwatchlogs/metric-filter-reference-validation-aws.json")) {
JsonNode fixture = MAPPER.readTree(input);
assertEquals("Verified on Live AWS", fixture.path("provenance").path("verification").textValue());
List<Arguments> cases = new ArrayList<>();
for (JsonNode example : fixture.path("cases")) {
cases.add(Arguments.of(example.path("id").textValue(), example));
}
return cases.stream();
}
}
@ParameterizedTest(name = "{0}")
@MethodSource("verifiedLiveAwsCases")
void putMatchesVerifiedLiveAwsReferenceValidation(String id, JsonNode example) {
MetricFilter definition = definition(example.path("filterPattern").textValue(),
example.path("metricValue").textValue());
MetricTransformation transformation = definition.getMetricTransformations().getFirst();
if (example.has("defaultValue")) {
transformation.setDefaultValue(example.path("defaultValue").doubleValue());
}
if (example.has("dimensions")) {
transformation.setDimensions(MAPPER.convertValue(example.path("dimensions"), new TypeReference<>() {}));
}
JsonNode expected = example.path("expected");
if (expected.path("accepted").booleanValue()) {
service.putMetricFilter(definition, REGION);
MetricFilter stored = service.findMetricFilter(GROUP, "reference", REGION).orElseThrow();
assertEquals(definition.getFilterPattern(), stored.getFilterPattern(), id);
MetricTransformation saved = stored.getMetricTransformations().getFirst();
assertEquals(transformation.getMetricValue(), saved.getMetricValue(), id);
assertEquals(transformation.getDefaultValue(), saved.getDefaultValue(), id);
assertEquals(transformation.getDimensions(), saved.getDimensions(), id);
} else {
AwsException error = assertThrows(AwsException.class, () -> service.putMetricFilter(definition, REGION));
assertEquals(expected.path("errorCode").textValue(), error.getErrorCode(), id);
assertEquals(expected.path("message").textValue(), error.getMessage(), id);
assertEquals(400, error.getHttpStatus());
assertTrue(service.findMetricFilter(GROUP, "reference", REGION).isEmpty());
}
verifyNoInteractions(metrics);
}
@ParameterizedTest
@ValueSource(strings = {"$.values[*]", "$.values.*", "$.values[*].amount"})
void wildcardMetricReferencesCannotReplaceThePriorDefinition(String reference) {
service.putMetricFilter(definition(SCALAR_PATTERN, "$.value"), REGION);
AwsException error = assertThrows(AwsException.class,
() -> service.putMetricFilter(definition(WILDCARD_PATTERN, reference), REGION));
assertEquals("InvalidParameterException", error.getErrorCode());
MetricFilter retained = service.findMetricFilter(GROUP, "reference", REGION).orElseThrow();
assertEquals(SCALAR_PATTERN, retained.getFilterPattern());
assertEquals("$.value", retained.getMetricTransformations().getFirst().getMetricValue());
verifyNoInteractions(metrics);
}
@ParameterizedTest
@ValueSource(strings = {"$.['*']", "$.['foo*bar']", "$.['values[*]']", "$.values[0]"})
void singlePropertyReferencesRemainValidIncludingLiteralAsterisks(String reference) {
MetricFilter stored = service.putMetricFilter(definition(SCALAR_PATTERN, reference), REGION);
assertEquals(reference, stored.getMetricTransformations().getFirst().getMetricValue());
}
@Test
void wildcardFilterPatternsRemainValidWithANumericMetricValue() {
MetricFilter stored = service.putMetricFilter(definition(WILDCARD_PATTERN, "1"), REGION);
assertEquals(WILDCARD_PATTERN, stored.getFilterPattern());
}
@Test
void unmeasuredDimensionWildcardValidationRemainsUnchanged() {
MetricFilter definition = definition(SCALAR_PATTERN, "1");
definition.getMetricTransformations().getFirst().setDimensions(Map.of("A", "$.values[*]"));
MetricFilter stored = service.putMetricFilter(definition, REGION);
assertEquals(Map.of("A", "$.values[*]"), stored.getMetricTransformations().getFirst().getDimensions());
}
private static MetricFilter definition(String pattern, String value) {
MetricTransformation transformation = new MetricTransformation();
transformation.setMetricName("Value");
transformation.setMetricNamespace("Synthetic");
transformation.setMetricValue(value);
MetricFilter filter = new MetricFilter();
filter.setFilterName("reference");
filter.setLogGroupName(GROUP);
filter.setFilterPattern(pattern);
filter.setMetricTransformations(List.of(transformation));
return filter;
}
}
@@ -0,0 +1,120 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.lifecycle.EmulatorInfoController;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsMetricFilterRetryTest.await;
import static io.github.hectorvent.floci.services.cloudwatch.logs.PublicationTestSupport.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class CloudWatchLogsMetricFilterResetTest {
private final CloudWatchLogsMetricFilterRetryTest.FaultStore sink = new CloudWatchLogsMetricFilterRetryTest.FaultStore();
private final PublicationTestSupport f = new PublicationTestSupport(sink);
@AfterEach
void stop() { f.service.stop(); }
@ParameterizedTest
@ValueSource(booleans = {false, true})
void actualResetControllerDrainsPublicationBeforeStorageWipe(boolean afterWrite) throws Exception {
f.put("reset", "ERROR", "3", 7.0);
sink.fail = true;
f.ingest(TIME, "INFO");
CountDownLatch inWrite = new CountDownLatch(1);
CountDownLatch releaseWrite = new CountDownLatch(1);
if (afterWrite) { sink.after = (key, datum) -> { inWrite.countDown(); await(releaseWrite); }; }
else { sink.before = (key, datum) -> { inWrite.countDown(); await(releaseWrite); }; }
sink.fail = false;
CountDownLatch resetReachedService = new CountDownLatch(1);
Resettable resettable = new Resettable() {
@Override public void beforeReset() { resetReachedService.countDown(); f.service.beforeReset(); }
@Override public void clear() { resetReachedService.countDown(); f.service.clear(); }
@Override public void afterReset() { f.service.afterReset(); }
};
EmulatorInfoController controller = controller(resettable);
doAnswer(call -> { f.metricStore.clear(); f.filters.clear(); return null; }).when(f.factory).clearAll();
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> retry = pool.submit(f.service::retryPending);
assertTrue(inWrite.await(5, TimeUnit.SECONDS));
Future<?> reset = pool.submit(controller::reset);
assertTrue(resetReachedService.await(5, TimeUnit.SECONDS));
assertFalse(reset.isDone(), "reset must drain the active store write");
releaseWrite.countDown();
retry.get(5, TimeUnit.SECONDS);
reset.get(5, TimeUnit.SECONDS);
f.service.retryPending();
assertEquals(0, f.service.pendingSamples());
f.stats("reset", TIME, 0, 0);
assertTrue(f.filters.keys().isEmpty());
sink.before = (key, datum) -> {};
sink.after = (key, datum) -> {};
f.put("reset", "ERROR", "3", 11.0);
f.ingest(TIME, "INFO");
f.stats("reset", TIME, 11, 1);
} finally {
releaseWrite.countDown(); pool.shutdownNow(); assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
@Test
void resetPausesConcurrentIngestionDuringWipeAndResumesSameInstance() throws Exception {
f.put("reset", "ERROR", "3", 7.0);
CountDownLatch wiping = new CountDownLatch(1);
CountDownLatch finishWipe = new CountDownLatch(1);
doAnswer(call -> { wiping.countDown(); await(finishWipe); f.metricStore.clear(); f.filters.clear(); return null; })
.when(f.factory).clearAll();
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Future<?> reset = pool.submit(controller(f.service)::reset);
assertTrue(wiping.await(5, TimeUnit.SECONDS));
int attempts = sink.attempts.size();
f.ingest(TIME, "INFO");
assertEquals(attempts, sink.attempts.size(), "publication cannot enter the metric sink during reset");
finishWipe.countDown();
reset.get(5, TimeUnit.SECONDS);
f.put("reset", "ERROR", "3", 11.0);
f.ingest(TIME, "INFO");
f.stats("reset", TIME, 11, 1);
} finally {
finishWipe.countDown(); pool.shutdownNow(); assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
@Test
void failedStorageResetStillResumesAndCancelsOldQueue() {
f.put("reset", "ERROR", "3", 7.0);
sink.fail = true;
f.ingest(TIME, "INFO");
doThrow(new IllegalStateException("wipe failed")).when(f.factory).clearAll();
assertThrows(IllegalStateException.class, () -> controller(f.service).reset());
assertEquals(0, f.service.pendingSamples());
sink.fail = false;
f.service.retryPending();
f.ingest(TIME, "INFO");
f.stats("reset", TIME, 7, 1);
}
@SuppressWarnings("unchecked")
private EmulatorInfoController controller(Resettable resettable) {
Instance<Resettable> resettables = mock(Instance.class);
when(resettables.iterator()).thenAnswer(call -> List.of(resettable).iterator());
Instance<ContainerTeardown> teardowns = mock(Instance.class);
when(teardowns.iterator()).thenAnswer(call -> List.<ContainerTeardown>of().iterator());
return new EmulatorInfoController(null, null, f.factory, resettables, teardowns, null, null);
}
}
@@ -0,0 +1,115 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@QuarkusTest
@TestProfile(CloudWatchLogsMetricFilterRetryIntegrationTest.ResetIsolationProfile.class)
class CloudWatchLogsMetricFilterRetryIntegrationTest {
/** HTTP reset wipes every service; do not share this application with other test classes. */
public static class ResetIsolationProfile implements QuarkusTestProfile {}
@InjectSpy CloudWatchMetricsService metrics;
@Inject CloudWatchLogsMetricFilterService publications;
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260916/eu-west-1/logs/aws4_request";
private static final long TIME = 1_700_000_040_000L;
@BeforeAll
static void contentTypes() { RestAssuredJsonUtils.configureAwsContentTypes(); }
@AfterEach
void removeFault() { reset(metrics); }
@Test
void managedWorkerSurvivesFailedRetryAndPublishesWithoutFurtherIngestion() throws Exception {
String group = "/it/publication/automatic-" + System.nanoTime();
create(group);
AtomicInteger attempts = new AtomicInteger();
CountDownLatch published = new CountDownLatch(1);
doAnswer(call -> {
if (attempts.incrementAndGet() <= 2) { throw new IllegalStateException("temporary metric sink failure"); }
Object result = call.callRealMethod();
published.countDown();
return result;
}).when(metrics).publishMetricForAccount(anyString(), eq(group), any(), eq("eu-west-1"), anyString());
ingest(group);
assertTrue(published.await(10, TimeUnit.SECONDS), "no reads, ingestion or manual retry drive the worker");
assertTrue(attempts.get() >= 3, "a failed retry must not suppress future scheduled ticks");
statistics(group).then().statusCode(200).body("Datapoints", hasSize(1))
.body("Datapoints[0].Sum", equalTo(7.0f)).body("Datapoints[0].SampleCount", equalTo(1.0f));
publications.retryPending();
statistics(group).then().body("Datapoints[0].SampleCount", equalTo(1.0f));
logs("DeleteLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200);
}
@Test
void httpResetCancelsQueuedWorkOnTheLiveCdiInstance() {
String group = "/it/publication/reset-" + System.nanoTime();
create(group);
doThrow(new IllegalStateException("outage through reset")).when(metrics)
.publishMetricForAccount(anyString(), eq(group), any(), eq("eu-west-1"), anyString());
ingest(group);
await().atMost(Duration.ofSeconds(10)).until(() -> publications.pendingSamples() > 0);
given().post("/_floci/state/reset").then().statusCode(200).body("status", equalTo("OK"));
assertEquals(0, publications.pendingSamples());
reset(metrics);
publications.retryPending();
statistics(group).then().statusCode(200).body("Datapoints", hasSize(0));
create(group);
ingest(group);
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> statistics(group).then().statusCode(200)
.body("Datapoints[0].Sum", equalTo(7.0f)).body("Datapoints[0].SampleCount", equalTo(1.0f)));
logs("DeleteLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200);
}
private static void create(String group) {
logs("CreateLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200);
logs("CreateLogStream", "{\"logGroupName\":\"" + group + "\",\"logStreamName\":\"s\"}").then().statusCode(200);
logs("PutMetricFilter", """
{"logGroupName":"%s","filterName":"retry","filterPattern":"ERROR",
"metricTransformations":[{"metricName":"Value","metricNamespace":"%s","metricValue":"3","defaultValue":7}]}
""".formatted(group, group)).then().statusCode(200);
}
private static void ingest(String group) {
logs("PutLogEvents", """
{"logGroupName":"%s","logStreamName":"s","logEvents":[{"timestamp":%d,"message":"INFO"}]}
""".formatted(group, TIME)).then().statusCode(200);
logs("GetLogEvents", "{\"logGroupName\":\"" + group + "\",\"logStreamName\":\"s\"}")
.then().statusCode(200).body("events", hasSize(1));
}
private static Response logs(String action, String body) {
return given().contentType("application/x-amz-json-1.1").header("Authorization", AUTH)
.header("X-Amz-Target", "Logs_20140328." + action).body(body).post("/");
}
private static Response statistics(String namespace) {
return given().contentType("application/x-amz-json-1.0").header("Authorization", AUTH.replace("/logs/", "/monitoring/"))
.header("X-Amz-Target", "GraniteServiceVersion20100801.GetMetricStatistics").body("""
{"Namespace":"%s","MetricName":"Value","Period":60,"StartTime":%d,"EndTime":%d,
"Statistics":["Sum","SampleCount"]}
""".formatted(namespace, TIME / 1000, TIME / 1000 + 59)).post("/");
}
}
@@ -0,0 +1,493 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static io.github.hectorvent.floci.services.cloudwatch.logs.PublicationTestSupport.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class CloudWatchLogsMetricFilterRetryTest {
private final FaultStore sink = new FaultStore();
private final PublicationTestSupport f = new PublicationTestSupport(sink);
@AfterEach
void stop() { f.service.stop(); }
@ParameterizedTest
@ValueSource(booleans = {false, true})
void realPartialWritesRetryWithoutDuplicatesAndIngestionStillSucceeds(boolean after) {
f.put("broken", "ERROR", "3", 7.0);
AtomicBoolean armed = new AtomicBoolean(true);
BiConsumer<String, MetricDatum> fault = (key, datum) -> {
if (datum.getValue() == 7 && armed.compareAndSet(true, false)) { throw new IllegalStateException("sink failure"); }
};
if (after) { sink.after = fault; } else { sink.before = fault; }
f.ingest(TIME, "ERROR", "INFO", "ERROR");
assertEquals(1, f.service.pendingSamples());
f.service.retryPending();
f.service.retryPending();
f.stats("broken", TIME, 13, 3);
assertEquals(0, f.service.pendingSamples());
assertEquals(3, sink.keys().size());
assertTrue(sink.attempts.size() > sink.attempts.stream().distinct().count());
f.ingest(TIME, "ERROR", "INFO", "ERROR");
f.stats("broken", TIME, 26, 6); // new identical accepted logs are legitimate contributions
}
@Test
void confirmingAnIndeterminateDeleteCancelsOnlyTheAbsentOwnersPendingSamples() {
f.put("gone", "ERROR", "3", null);
sink.fail = true;
f.ingest(TIME, "ERROR");
f.account.set(OTHER_ACCOUNT);
f.group(GROUP, REGION);
f.put("gone", "ERROR", "9", null);
f.ingest(TIME, "ERROR");
assertEquals(2, f.service.pendingSamples());
f.account.set(ACCOUNT);
synchronized (f.filters) {
f.filters.keys().forEach(f.filters::delete);
}
assertTrue(f.service.confirmMetricFilterAbsent(GROUP, "gone", REGION,
() -> assertTrue(Thread.holdsLock(f.filters))));
assertEquals(1, f.service.pendingSamples(), "confirmed absence must finish deletion's publication cleanup");
sink.fail = false;
f.service.retryPending();
f.stats("gone", TIME, 0, 0);
f.account.set(OTHER_ACCOUNT);
f.stats("gone", TIME, 9, 1);
}
@Test
void failedWorkRetainsCanonicalAccountAndImmutableTransformationAcrossUpdate() {
MetricFilter old = definition("filter", "{ $.value = * }", "$.value", null);
old.getMetricTransformations().getFirst().setDimensions(Map.of("A", "$.a"));
f.service.putMetricFilter(old, REGION);
sink.fail = true;
f.ingest(TIME, "{\"value\":3,\"a\":\"alpha\"}");
MetricFilter replacement = definition("filter", "ERROR", "99", 17.0);
replacement.getMetricTransformations().getFirst().setMetricNamespace("New");
replacement.getMetricTransformations().getFirst().setMetricName("NewName");
replacement.getMetricTransformations().getFirst().setUnit("Bytes");
f.service.putMetricFilter(replacement, REGION);
clearInvocations(f.resolver);
f.account.set(OTHER_ACCOUNT); // no request context survives on the worker
sink.fail = false;
f.service.retryPending();
verify(f.resolver, never()).getAccountId();
f.stats("filter", List.of(new Dimension("A", "alpha")), TIME, 0, 0);
f.account.set(ACCOUNT);
f.stats("filter", List.of(new Dimension("A", "alpha")), TIME, 3, 1);
assertEquals("Count", f.points("filter", List.of(new Dimension("A", "alpha")), TIME, REGION).getFirst().unit());
assertTrue(f.metrics.listMetrics("New", null, null, REGION).isEmpty());
f.ingest(TIME, "ERROR");
assertEquals(1, f.metrics.listMetrics("New", "NewName", null, REGION).size());
}
@Test
void accountIsResolvedOnceForImmediateAndRetainedPublication() {
f.put("account", "ERROR", "3", 7.0);
clearInvocations(f.resolver);
sink.fail = true;
f.ingest(TIME, "ERROR", "INFO");
verify(f.resolver, times(1)).getAccountId();
f.account.set(OTHER_ACCOUNT);
sink.fail = false;
f.service.retryPending();
verify(f.resolver, times(1)).getAccountId();
f.stats("account", TIME, 0, 0);
f.account.set(ACCOUNT);
f.stats("account", TIME, 10, 2);
}
@Test
void failingFilterDoesNotStopOtherFiltersOrSuccessfulLogsIngestion() {
f.put("broken", "ERROR", "3", null);
f.put("healthy", "ERROR", "5", null);
sink.before = (key, datum) -> {
if (datum.getNamespace().equals("broken")) { throw new IllegalStateException("one namespace unavailable"); }
};
f.ingest(TIME, "ERROR");
f.stats("healthy", TIME, 5, 1);
assertEquals(1, f.service.pendingSamples());
sink.before = (key, datum) -> {};
f.service.retryPending();
f.stats("broken", TIME, 3, 1);
}
@Test
void sampleBoundReportsOverflowAtErrorPreservesQueuedIdsAndReleasesCapacity() {
f.put("bound", "ERROR", "3", 7.0);
sink.fail = true;
List<LogRecord> records = new CopyOnWriteArrayList<>();
Logger logger = Logger.getLogger(CloudWatchLogsMetricFilterService.class.getName());
Handler handler = new Handler() {
@Override public void publish(LogRecord record) { records.add(record); }
@Override public void flush() {}
@Override public void close() {}
};
logger.addHandler(handler);
try {
f.ingest(null, GROUP, REGION, TIME, Collections.nCopies(10_003, "INFO"));
assertEquals(10_000, f.service.pendingSamples(), "bound counts samples, not batches");
assertTrue(records.stream().anyMatch(r -> r.getLevel().intValue() >= Level.SEVERE.intValue()
&& formatted(r).contains(ACCOUNT) && formatted(r).contains(GROUP)
&& formatted(r).contains("region=" + REGION) && formatted(r).contains("filter=bound")
&& formatted(r).contains("dropped=3")), "overflow must be ERROR with ownership and dropped count");
List<String> queuedKeys = List.copyOf(sink.attempts.subList(0, 10_000));
sink.fail = false;
f.service.retryPending();
f.stats("bound", TIME, 70_000, 10_000);
assertEquals(0, f.service.pendingSamples());
assertEquals(Set.copyOf(queuedKeys), sink.keys());
sink.fail = true;
f.ingest(TIME, "INFO");
assertEquals(1, f.service.pendingSamples());
f.service.deleteMetricFilter(GROUP, "bound", REGION);
assertEquals(0, f.service.pendingSamples());
f.put("bound", "ERROR", "3", 7.0);
f.ingest(TIME, "INFO");
assertEquals(1, f.service.pendingSamples());
} finally { logger.removeHandler(handler); }
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void deleteCancelsOnlyItsAccountRegionGroupAndFilter(boolean group) {
f.put("same", "ERROR", "3", null);
f.put("sibling", "ERROR", "5", null);
sink.fail = true;
f.ingest(TIME, "ERROR");
f.group(GROUP, "us-east-1");
f.service.putMetricFilter(definition("same", "ERROR", "3", null), "us-east-1");
f.ingest(null, GROUP, "us-east-1", TIME, List.of("ERROR"));
f.group("/other", REGION);
MetricFilter other = definition("same", "ERROR", "3", null);
other.setLogGroupName("/other");
f.service.putMetricFilter(other, REGION);
f.ingest(null, "/other", REGION, TIME, List.of("ERROR"));
f.account.set(OTHER_ACCOUNT);
f.group(GROUP, REGION);
f.put("same", "ERROR", "3", null);
f.ingest(TIME, "ERROR");
f.account.set(ACCOUNT);
if (group) { f.logs.deleteLogGroup(GROUP, REGION); }
else { f.service.deleteMetricFilter(GROUP, "same", REGION); }
assertEquals(group ? 3 : 4, f.service.pendingSamples());
sink.fail = false;
f.service.retryPending();
f.stats("same", TIME, 3, 1); // other group only
f.stats("sibling", TIME, group ? 0 : 5, group ? 0 : 1);
assertEquals(3, f.points("same", List.of(), TIME, "us-east-1").getFirst().sum());
f.account.set(OTHER_ACCOUNT);
f.stats("same", TIME, 3, 1);
}
@Test
void clearOnTheSameInstanceReleasesQueuedWork() {
f.put("reset", "ERROR", "3", 7.0);
sink.fail = true;
f.ingest(TIME, "INFO");
assertEquals(1, f.service.pendingSamples());
f.service.clear();
assertEquals(0, f.service.pendingSamples());
sink.fail = false;
f.service.retryPending();
f.stats("reset", TIME, 0, 0);
f.ingest(TIME, "INFO");
f.stats("reset", TIME, 7, 1);
}
@ParameterizedTest
@ValueSource(strings = {"filter", "group", "update", "clear", "stop"})
void mutationRacingRetryWaitsForTheActiveWriteAndNeverReinterpretsIt(String mutation) throws Exception {
f.put("race", "ERROR", "3", 7.0);
sink.fail = true;
f.ingest(TIME, "INFO");
sink.fail = false;
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
sink.before = (key, datum) -> { entered.countDown(); await(release); };
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> retry = pool.submit(f.service::retryPending);
assertTrue(entered.await(5, TimeUnit.SECONDS));
CountDownLatch started = new CountDownLatch(1);
Future<?> change = pool.submit(() -> {
started.countDown();
switch (mutation) {
case "filter" -> f.service.deleteMetricFilter(GROUP, "race", REGION);
case "group" -> f.logs.deleteLogGroup(GROUP, REGION);
case "clear" -> f.service.clear();
case "stop" -> f.service.stop();
case "update" -> {
MetricFilter next = definition("race", "ERROR", "99", 17.0);
next.getMetricTransformations().getFirst().setMetricNamespace("new");
f.service.putMetricFilter(next, REGION);
}
default -> fail(mutation);
}
});
assertTrue(started.await(5, TimeUnit.SECONDS));
assertThrows(TimeoutException.class, () -> change.get(100, TimeUnit.MILLISECONDS));
release.countDown();
retry.get(5, TimeUnit.SECONDS);
change.get(5, TimeUnit.SECONDS);
sink.before = (key, datum) -> {};
assertEquals(0, f.service.pendingSamples());
f.service.retryPending();
f.stats("race", TIME, 7, 1);
if (mutation.equals("stop")) {
f.ingest(TIME, "INFO");
f.stats("race", TIME, 7, 1);
return;
}
if (mutation.equals("group")) { f.group(GROUP, REGION); }
if (!mutation.equals("update")) { f.put("race", "ERROR", "3", 11.0); }
f.ingest(TIME, "INFO");
f.stats("race", TIME, mutation.equals("update") ? 7 : 18, mutation.equals("update") ? 1 : 2);
if (mutation.equals("update")) { f.stats("new", TIME, 17, 1); }
} finally {
release.countDown(); pool.shutdownNow(); assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
@Test
void simultaneousStreamsAndConcurrentRetryTicksKeepEveryAcceptedContribution() throws Exception {
f.put("streams", "ERROR", "3", 7.0);
f.logs.createLogStream(GROUP, "other", REGION);
sink.fail = true;
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
Future<?> first = pool.submit(() -> { await(start); f.ingest(TIME, "ERROR", "INFO"); });
Future<?> second = pool.submit(() -> {
await(start);
f.logs.putLogEvents(GROUP, "other", List.of(Map.of("timestamp", TIME, "message", "INFO")), REGION);
});
start.countDown();
first.get(5, TimeUnit.SECONDS);
second.get(5, TimeUnit.SECONDS);
f.service.publishQueued();
assertEquals(3, f.service.pendingSamples());
sink.fail = false;
Future<?> retryOne = pool.submit(f.service::retryPending);
Future<?> retryTwo = pool.submit(f.service::retryPending);
retryOne.get(5, TimeUnit.SECONDS);
retryTwo.get(5, TimeUnit.SECONDS);
f.stats("streams", TIME, 17, 3);
assertEquals(0, f.service.pendingSamples());
} finally {
start.countDown(); pool.shutdownNow(); assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void eitherDisabledServicePreventsPublicationAndWorkerStartup(boolean logsDisabled) {
f.service.start(!logsDisabled, logsDisabled);
f.put("disabled", "ERROR", "3", 7.0);
f.ingest(TIME, "ERROR");
assertFalse(f.service.publisherRunning());
f.stats("disabled", TIME, 0, 0);
assertEquals(0, f.service.pendingSamples());
}
@Test
void enabledWorkerStartsOnceAndStopIsIdempotentAndCancelsPending() {
f.service.start(true, true);
f.service.start(true, true);
assertTrue(f.service.publisherRunning());
f.put("stop", "ERROR", "3", 7.0);
sink.fail = true;
f.ingest(TIME, "INFO");
f.service.stop();
f.service.stop();
assertFalse(f.service.publisherRunning());
assertEquals(0, f.service.pendingSamples());
sink.fail = false;
f.service.retryPending();
f.ingest(TIME, "INFO");
f.stats("stop", TIME, 0, 0);
}
@ParameterizedTest
@ValueSource(ints = {1, 100})
void loggingOneHundredFailedTicksKeepOneDetailPerOutageAndBoundedSummaries(int filters) {
for (int i = 0; i < filters; i++) { f.put("outage-" + i, "ERROR", "3", 7.0); }
sink.fail = true;
try (FailureLogs logs = new FailureLogs()) {
f.ingest(TIME, "INFO");
for (int tick = 0; tick < 100; tick++) { f.service.retryPending(); }
assertEquals(101 * filters, sink.attempts.size(), "diagnostic throttling must not throttle retries");
assertEquals(filters, f.service.pendingSamples());
assertEquals(filters, logs.details(), "one stack per owning filter outage, not per tick or sample");
assertEquals(1, logs.summaries(), "one aggregate stack-free warning after 60 failed ticks, even for 100 filters");
LogRecord summary = logs.warnings.stream().filter(record -> record.getThrown() == null).findFirst().orElseThrow();
assertTrue(formatted(summary).contains("failedSamples=" + filters));
assertTrue(formatted(summary).contains("filters=" + filters));
}
}
@Test
void loggingNewFailedIngestionDoesNotRepeatAnOutstandingOutagesStack() {
f.put("outage", "ERROR", "3", 7.0);
sink.fail = true;
try (FailureLogs logs = new FailureLogs()) {
for (int batch = 0; batch < 100; batch++) { f.ingest(TIME, "INFO"); }
assertEquals(100, f.service.pendingSamples());
assertEquals(100, sink.attempts.size());
assertEquals(1, logs.details());
assertEquals(0, logs.summaries(), "new batches must not bypass retry summary throttling");
}
}
@Test
void loggingRecoveryThenNewOutageGetsFreshDetailAndSummaryWindow() {
f.put("outage", "ERROR", "3", 7.0);
sink.fail = true;
try (FailureLogs logs = new FailureLogs()) {
f.ingest(TIME, "INFO");
for (int tick = 0; tick < 100; tick++) { f.service.retryPending(); }
sink.fail = false;
f.service.retryPending();
assertEquals(0, f.service.pendingSamples());
f.stats("outage", TIME, 7, 1);
sink.fail = true;
f.ingest(TIME, "INFO");
assertEquals(2, logs.details(), "recovery must allow fresh detail for the next outage");
for (int tick = 0; tick < 59; tick++) { f.service.retryPending(); }
assertEquals(1, logs.summaries(), "recovery must restart the summary window");
f.service.retryPending();
assertEquals(2, logs.summaries());
assertEquals(2, logs.details());
assertEquals(163, sink.attempts.size());
}
}
@ParameterizedTest
@ValueSource(strings = {"filter", "group", "clear", "reset"})
void loggingLastCancellationOrResetReleasesSuppressionAndRestartsSummaryWindow(String operation) {
f.put("outage", "ERROR", "3", 7.0);
sink.fail = true;
try (FailureLogs logs = new FailureLogs()) {
f.ingest(TIME, "INFO");
for (int tick = 0; tick < 59; tick++) { f.service.retryPending(); }
switch (operation) {
case "filter" -> f.service.deleteMetricFilter(GROUP, "outage", REGION);
case "group" -> f.logs.deleteLogGroup(GROUP, REGION);
case "clear" -> f.service.clear();
case "reset" -> {
f.service.beforeReset();
f.service.clear();
f.service.afterReset();
}
default -> fail(operation);
}
assertEquals(0, f.service.pendingSamples());
if (operation.equals("group")) { f.group(GROUP, REGION); }
f.put("outage", "ERROR", "3", 7.0);
f.ingest(TIME, "INFO");
f.service.retryPending();
assertEquals(2, logs.details());
assertEquals(0, logs.summaries(), "cancelling the final pending owner must restart the summary window");
for (int tick = 0; tick < 59; tick++) { f.service.retryPending(); }
assertEquals(1, logs.summaries());
assertEquals(2, logs.details());
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void loggingScopedCancellationDoesNotRearmAnUnrelatedPendingOutage(boolean group) {
f.put("outage", "ERROR", "3", 7.0);
f.group("/other", REGION);
MetricFilter sibling = definition("sibling", "ERROR", "3", 7.0);
sibling.setLogGroupName("/other");
f.service.putMetricFilter(sibling, REGION);
sink.fail = true;
try (FailureLogs logs = new FailureLogs()) {
f.ingest(TIME, "INFO");
f.ingest(null, "/other", REGION, TIME, List.of("INFO"));
for (int tick = 0; tick < 10; tick++) { f.service.retryPending(); }
if (group) {
f.logs.deleteLogGroup(GROUP, REGION);
f.group(GROUP, REGION);
} else {
f.service.deleteMetricFilter(GROUP, "outage", REGION);
}
assertEquals(1, f.service.pendingSamples());
f.put("outage", "ERROR", "3", 7.0);
f.ingest(TIME, "INFO");
f.ingest(null, "/other", REGION, TIME, List.of("INFO"));
for (int tick = 0; tick < 100; tick++) { f.service.retryPending(); }
assertEquals(3, f.service.pendingSamples());
assertEquals(3, logs.details(), "only the cancelled owner gets new detail; its sibling stays suppressed");
assertEquals(1, logs.summaries());
}
}
private static class FailureLogs extends Handler implements AutoCloseable {
private final Logger logger = Logger.getLogger(CloudWatchLogsMetricFilterService.class.getName());
private final List<LogRecord> warnings = new CopyOnWriteArrayList<>();
FailureLogs() { logger.addHandler(this); }
@Override public void publish(LogRecord record) {
if (record.getLevel().intValue() == Level.WARNING.intValue()) { warnings.add(record); }
}
long details() { return warnings.stream().filter(record -> record.getThrown() != null).count(); }
long summaries() { return warnings.stream().filter(record -> record.getThrown() == null).count(); }
@Override public void flush() {}
@Override public void close() { logger.removeHandler(this); }
}
static void await(CountDownLatch latch) {
try { assertTrue(latch.await(5, TimeUnit.SECONDS)); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); }
}
private static String formatted(LogRecord r) {
return MessageFormat.format(r.getMessage(), r.getParameters() == null ? new Object[0] : r.getParameters());
}
static class FaultStore extends InMemoryStorage<String, MetricDatum> {
volatile boolean fail;
volatile BiConsumer<String, MetricDatum> before = (key, value) -> {};
volatile BiConsumer<String, MetricDatum> after = (key, value) -> {};
final List<String> attempts = Collections.synchronizedList(new ArrayList<>());
@Override public void put(String key, MetricDatum value) {
attempts.add(key);
if (fail) { throw new IllegalStateException("storage offline"); }
before.accept(key, value);
super.put(key, value);
after.accept(key, value);
}
}
}
@@ -0,0 +1,520 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricTransformation;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* The metric filter operations against the rules the Logs API documents. What a filter publishes
* for a stored batch is in {@link CloudWatchLogsMetricFilterPublishingTest}.
*/
class CloudWatchLogsMetricFilterServiceTest {
private static final String REGION = "us-east-1";
private static final String GROUP = "/app/api";
private static final String OTHER_GROUP = "/app/worker";
private CloudWatchLogsMetricFilterService service;
private CloudWatchMetricsService metrics;
@BeforeEach
void setUp() {
RegionResolver resolver = new RegionResolver(REGION, "000000000000");
CloudWatchLogsService logs = new CloudWatchLogsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), 10_000, resolver);
logs.createLogGroup(GROUP, null, null, REGION);
logs.createLogGroup(OTHER_GROUP, null, null, REGION);
metrics = mock(CloudWatchMetricsService.class);
service = new CloudWatchLogsMetricFilterService(logs, metrics, resolver);
}
private static MetricTransformation transformation(String name, String namespace, String value) {
MetricTransformation t = new MetricTransformation();
t.setMetricName(name);
t.setMetricNamespace(namespace);
t.setMetricValue(value);
return t;
}
private static MetricFilter filter(String group, String name, String pattern, MetricTransformation transformation) {
MetricFilter filter = new MetricFilter();
filter.setLogGroupName(group);
filter.setFilterName(name);
filter.setFilterPattern(pattern);
filter.setMetricTransformations(transformation == null ? List.of() : List.of(transformation));
return filter;
}
private static MetricFilter errorCounter(String group, String name) {
return filter(group, name, "ERROR", transformation("ErrorCount", "App", "1"));
}
private static AwsException rejected(Runnable call, String code) {
AwsException e = assertThrows(AwsException.class, call::run);
assertEquals(code, e.getErrorCode(), e.getMessage());
return e;
}
// ──────────────────────────── PutMetricFilter ────────────────────────────
@Test
void putStoresTheFilterAndDescribeReturnsIt() {
MetricTransformation t = transformation("ErrorCount", "App", "1");
t.setDefaultValue(0.0);
t.setUnit("Count");
MetricFilter definition = filter(GROUP, "errors", "ERROR", t);
definition.setApplyOnTransformedLogs(false);
definition.setFieldSelectionCriteria("@aws.region = \"us-east-1\"");
definition.setEmitSystemFieldDimensions(List.of("@aws.account"));
MetricFilter stored = service.putMetricFilter(definition, REGION);
List<MetricFilter> described = service.describeMetricFilters(GROUP, null, null, null, null, null, REGION)
.metricFilters();
assertEquals(1, described.size());
MetricFilter f = described.getFirst();
assertEquals("errors", f.getFilterName());
assertEquals(GROUP, f.getLogGroupName());
assertEquals("ERROR", f.getFilterPattern());
assertEquals("ErrorCount", f.getMetricTransformations().getFirst().getMetricName());
assertEquals("App", f.getMetricTransformations().getFirst().getMetricNamespace());
assertEquals("1", f.getMetricTransformations().getFirst().getMetricValue());
assertEquals(0.0, f.getMetricTransformations().getFirst().getDefaultValue());
assertEquals("Count", f.getMetricTransformations().getFirst().getUnit());
assertEquals(Boolean.FALSE, f.getApplyOnTransformedLogs());
assertEquals("@aws.region = \"us-east-1\"", f.getFieldSelectionCriteria());
assertEquals(List.of("@aws.account"), f.getEmitSystemFieldDimensions());
assertTrue(f.getCreationTime() > 0);
assertEquals(stored.getCreationTime(), f.getCreationTime());
assertEquals(1, service.countMetricFilters(GROUP, REGION));
assertEquals(0, service.countMetricFilters(OTHER_GROUP, REGION));
}
@Test
void putReplacesAFilterOfTheSameNameAndKeepsItsCreationTime() throws InterruptedException {
long created = service.putMetricFilter(errorCounter(GROUP, "errors"), REGION).getCreationTime();
Thread.sleep(2);
service.putMetricFilter(filter(GROUP, "errors", "FATAL", transformation("FatalCount", "App", "2")), REGION);
List<MetricFilter> described = service.describeMetricFilters(GROUP, null, null, null, null, null, REGION)
.metricFilters();
assertEquals(1, described.size());
assertEquals("FATAL", described.getFirst().getFilterPattern());
assertEquals("FatalCount", described.getFirst().getMetricTransformations().getFirst().getMetricName());
assertEquals(created, described.getFirst().getCreationTime(), "the creation time is the first put's");
}
@Test
void putNeedsAnExistingLogGroup() {
rejected(() -> service.putMetricFilter(errorCounter("/missing", "errors"), REGION), "ResourceNotFoundException");
rejected(() -> service.putMetricFilter(errorCounter(GROUP, "errors"), "eu-west-1"), "ResourceNotFoundException");
rejected(() -> service.putMetricFilter(errorCounter(null, "errors"), REGION), "InvalidParameterException");
}
@Test
void filterNameFollowsTheApiPattern() {
rejected(() -> service.putMetricFilter(errorCounter(GROUP, null), REGION), "InvalidParameterException");
rejected(() -> service.putMetricFilter(errorCounter(GROUP, "a:b"), REGION), "InvalidParameterException");
rejected(() -> service.putMetricFilter(errorCounter(GROUP, "a*"), REGION), "InvalidParameterException");
rejected(() -> service.putMetricFilter(errorCounter(GROUP, "n".repeat(513)), REGION), "InvalidParameterException");
service.putMetricFilter(errorCounter(GROUP, "spaces and | pipes are fine"), REGION);
}
@Test
void filterPatternMustParse() {
AwsException e = rejected(() -> service.putMetricFilter(
filter(GROUP, "bad", "{ $.a = }", transformation("M", "N", "1")), REGION), "InvalidParameterException");
assertTrue(e.getMessage().startsWith("Invalid filter pattern"), e.getMessage());
rejected(() -> service.putMetricFilter(filter(GROUP, "none", null, transformation("M", "N", "1")), REGION),
"InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "long", "x".repeat(1025), transformation("M", "N", "1")),
REGION), "InvalidParameterException");
service.putMetricFilter(filter(GROUP, "everything", "", transformation("All", "App", "1")), REGION);
}
@Test
void exactlyOneTransformationIsRequired() {
rejected(() -> service.putMetricFilter(filter(GROUP, "none", "ERROR", null), REGION), "InvalidParameterException");
MetricFilter two = filter(GROUP, "two", "ERROR", transformation("A", "N", "1"));
two.setMetricTransformations(List.of(transformation("A", "N", "1"), transformation("B", "N", "1")));
rejected(() -> service.putMetricFilter(two, REGION), "InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "noname", "ERROR", transformation(null, "N", "1")), REGION),
"InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "badname", "ERROR", transformation("a:b", "N", "1")), REGION),
"InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "nons", "ERROR", transformation("A", null, "1")), REGION),
"InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "badns", "ERROR", transformation("A", "n$s", "1")), REGION),
"InvalidParameterException");
}
@Test
void metricValueIsANumberOrAFieldThePatternCanSupply() {
service.putMetricFilter(filter(GROUP, "literal", "ERROR", transformation("A", "N", "1")), REGION);
service.putMetricFilter(filter(GROUP, "decimal", "ERROR", transformation("A", "N", "0.5")), REGION);
service.putMetricFilter(filter(GROUP, "json", "{ $.latency = * }", transformation("A", "N", "$.latency")), REGION);
service.putMetricFilter(filter(GROUP, "delimited", "[..., size]", transformation("A", "N", "$size")), REGION);
service.putMetricFilter(filter(GROUP, "position", "[..., size]", transformation("A", "N", "$3")), REGION);
rejected(() -> service.putMetricFilter(filter(GROUP, "x", "ERROR", transformation("A", "N", null)), REGION),
"InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "x", "ERROR", transformation("A", "N", "abc")), REGION),
"InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "x", "ERROR", transformation("A", "N", "$.latency")), REGION),
"InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "x", "[..., size]", transformation("A", "N", "$bytes")), REGION),
"InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "x", "[..., size]", transformation("A", "N", "$.size")), REGION),
"InvalidParameterException");
rejected(() -> service.putMetricFilter(filter(GROUP, "x", "ERROR", transformation("A", "N", "1".repeat(101))), REGION),
"InvalidParameterException");
}
@ParameterizedTest
@ValueSource(strings = {"1e309", "-1e309", "1e9999999999"})
void numericLiteralMustBeFinite(String value) {
service.putMetricFilter(errorCounter(GROUP, "existing"), REGION);
rejected(() -> service.putMetricFilter(
filter(GROUP, "existing", "WARN", transformation("A", "N", value)), REGION),
"InvalidParameterException");
assertEquals("ERROR", service.findMetricFilter(GROUP, "existing", REGION).orElseThrow().getFilterPattern());
}
@ParameterizedTest
@ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY})
void directServiceDefaultValueMustBeFinite(double value) {
MetricTransformation t = transformation("A", "N", "1");
t.setDefaultValue(value);
rejected(() -> service.putMetricFilter(filter(GROUP, "bad-default", "ERROR", t), REGION),
"InvalidParameterException");
assertTrue(service.findMetricFilter(GROUP, "bad-default", REGION).isEmpty());
}
@Test
void ingestionDoesNotPublishANonFiniteStoredLiteral() {
MetricFilter stored = service.putMetricFilter(errorCounter(GROUP, "legacy"), REGION);
stored.getMetricTransformations().getFirst().setMetricValue("1e309");
LogEvent event = new LogEvent();
event.setMessage("ERROR");
event.setTimestamp(1_700_000_000_000L);
service.onLogEventsIngested(new LogEventsIngested(null, REGION, GROUP, "s", List.of(event)));
assertEquals(0, service.queuedSamples());
service.publishQueued();
verifyNoInteractions(metrics);
}
@Test
void dimensionsFollowTheReferenceRules() {
MetricTransformation ok = transformation("A", "N", "1");
ok.setDimensions(Map.of("eventType", "$.eventType", "ip", "$.sourceIPAddress"));
service.putMetricFilter(filter(GROUP, "ok", "{ $.eventType = \"*\" }", ok), REGION);
MetricTransformation four = transformation("A", "N", "1");
four.setDimensions(Map.of("a", "$.a", "b", "$.b", "c", "$.c", "d", "$.d"));
rejected(() -> service.putMetricFilter(filter(GROUP, "four", "{ $.a = 1 }", four), REGION), "InvalidParameterException");
MetricTransformation onTerms = transformation("A", "N", "1");
onTerms.setDimensions(Map.of("a", "$.a"));
rejected(() -> service.putMetricFilter(filter(GROUP, "terms", "ERROR", onTerms), REGION), "InvalidParameterException");
MetricTransformation withDefault = transformation("A", "N", "1");
withDefault.setDimensions(Map.of("a", "$.a"));
withDefault.setDefaultValue(0.0);
rejected(() -> service.putMetricFilter(filter(GROUP, "default", "{ $.a = 1 }", withDefault), REGION),
"InvalidParameterException");
MetricTransformation badReference = transformation("A", "N", "1");
badReference.setDimensions(Map.of("a", "$bytes"));
rejected(() -> service.putMetricFilter(filter(GROUP, "ref", "[..., size]", badReference), REGION),
"InvalidParameterException");
MetricTransformation badName = transformation("A", "N", "1");
badName.setDimensions(Map.of(":a", "$.a"));
rejected(() -> service.putMetricFilter(filter(GROUP, "name", "{ $.a = 1 }", badName), REGION),
"InvalidParameterException");
}
@Test
void unitMustBeAStandardUnit() {
MetricTransformation t = transformation("A", "N", "1");
t.setUnit("Furlongs");
rejected(() -> service.putMetricFilter(filter(GROUP, "unit", "ERROR", t), REGION), "InvalidParameterException");
t.setUnit("Bytes/Second");
service.putMetricFilter(filter(GROUP, "unit", "ERROR", t), REGION);
}
@Test
void systemFieldDimensionsAreTheTwoDocumentedOnesAndCountTowardTheLimit() {
MetricFilter bad = errorCounter(GROUP, "sys");
bad.setEmitSystemFieldDimensions(List.of("@aws.host"));
rejected(() -> service.putMetricFilter(bad, REGION), "InvalidParameterException");
MetricTransformation two = transformation("A", "N", "1");
two.setDimensions(Map.of("a", "$.a", "b", "$.b"));
MetricFilter crowded = filter(GROUP, "sys", "{ $.a = 1 }", two);
crowded.setEmitSystemFieldDimensions(List.of("@aws.account", "@aws.region"));
rejected(() -> service.putMetricFilter(crowded, REGION), "InvalidParameterException");
crowded.setEmitSystemFieldDimensions(List.of("@aws.region"));
service.putMetricFilter(crowded, REGION);
}
@Test
void aLogGroupHoldsAtMostOneHundredFilters() {
for (int i = 0; i < 100; i++) {
service.putMetricFilter(errorCounter(GROUP, "f" + i), REGION);
}
rejected(() -> service.putMetricFilter(errorCounter(GROUP, "f100"), REGION), "LimitExceededException");
service.putMetricFilter(errorCounter(GROUP, "f0"), REGION);
service.putMetricFilter(errorCounter(OTHER_GROUP, "f100"), REGION);
assertEquals(100, service.countMetricFilters(GROUP, REGION));
}
/** Two creates racing for the last slot must not both get it. */
@Test
void theLimitHoldsUnderConcurrentPuts() throws Exception {
for (int i = 0; i < 99; i++) {
service.putMetricFilter(errorCounter(GROUP, "f" + i), REGION);
}
int threads = 8;
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
AtomicInteger refused = new AtomicInteger();
ExecutorService pool = Executors.newFixedThreadPool(threads);
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < threads; i++) {
String name = "race" + i;
futures.add(pool.submit(() -> {
start.await();
try {
service.putMetricFilter(errorCounter(GROUP, name), REGION);
accepted.incrementAndGet();
} catch (AwsException e) {
assertEquals("LimitExceededException", e.getErrorCode());
refused.incrementAndGet();
}
return null;
}));
}
start.countDown();
for (Future<?> future : futures) {
future.get();
}
pool.shutdown();
assertEquals(1, accepted.get());
assertEquals(threads - 1, refused.get());
assertEquals(100, service.countMetricFilters(GROUP, REGION));
}
// ──────────────────────────── DescribeMetricFilters ────────────────────────────
@Test
void describeSortsByNameAndFiltersByPrefixMetricAndNamespace() {
service.putMetricFilter(filter(GROUP, "beta", "B", transformation("Bees", "App", "1")), REGION);
service.putMetricFilter(filter(GROUP, "alpha", "A", transformation("Ants", "App", "1")), REGION);
service.putMetricFilter(filter(GROUP, "other", "O", transformation("Owls", "Zoo", "1")), REGION);
service.putMetricFilter(filter(OTHER_GROUP, "alpha", "A", transformation("Ants", "App", "1")), REGION);
assertEquals(List.of("alpha", "beta", "other"), names(service.describeMetricFilters(GROUP, null, null, null,
null, null, REGION).metricFilters()));
assertEquals(List.of("alpha"), names(service.describeMetricFilters(GROUP, "al", null, null, null, null, REGION)
.metricFilters()));
assertEquals(List.of("alpha", "alpha"), names(service.describeMetricFilters(null, null, "Ants", "App",
null, null, REGION).metricFilters()), "a metric search spans the Region's groups");
assertEquals(List.of("beta"), names(service.describeMetricFilters(null, null, "Bees", "App", null, null, REGION)
.metricFilters()));
assertEquals(List.of("alpha", "alpha", "beta", "other"), names(service.describeMetricFilters(null, null, null,
null, null, null, REGION).metricFilters()));
assertEquals(List.of(), names(service.describeMetricFilters(null, null, null, null, null, null, "eu-west-1")
.metricFilters()));
assertEquals(List.of("alpha", "alpha", "beta", "other"), names(service.describeMetricFilters(null, "al", null,
null, null, null, REGION).metricFilters()), "a prefix without a group is ignored, as on AWS");
}
@Test
void describeRejectsWhatTheApiRejects() {
rejected(() -> service.describeMetricFilters("/missing", null, null, null, null, null, REGION),
"ResourceNotFoundException");
rejected(() -> service.describeMetricFilters(GROUP, null, null, null, null, 0, REGION), "InvalidParameterException");
rejected(() -> service.describeMetricFilters(GROUP, null, null, null, null, 51, REGION), "InvalidParameterException");
rejected(() -> service.describeMetricFilters(GROUP, null, null, null, "garbage", null, REGION),
"InvalidParameterException");
rejected(() -> service.describeMetricFilters(GROUP, null, null, null, "99", null, REGION),
"InvalidParameterException");
}
@Test
void describeRequiresMetricNameAndNamespaceTogether() {
service.putMetricFilter(filter(GROUP, "beta", "B", transformation("Bees", "App", "1")), REGION);
String message = "Describe Metric Filters request must contain both MetricName and MetricNamespace";
AwsException nameOnly = rejected(() -> service.describeMetricFilters(null, null, "Bees", null, null, null, REGION),
"InvalidParameterException");
assertEquals(message, nameOnly.getMessage());
AwsException namespaceOnly = rejected(() -> service.describeMetricFilters(null, null, null, "App", null, null,
REGION), "InvalidParameterException");
assertEquals(message, namespaceOnly.getMessage());
assertEquals(List.of(), names(service.describeMetricFilters(null, null, "Ants", "App", null, null, REGION)
.metricFilters()), "both supplied with no match is an empty page, not an error");
}
@Test
void describePaginates() {
for (int i = 0; i < 5; i++) {
service.putMetricFilter(errorCounter(GROUP, "f" + i), REGION);
}
CloudWatchLogsMetricFilterService.DescribeMetricFiltersResult first =
service.describeMetricFilters(GROUP, null, null, null, null, 2, REGION);
assertEquals(List.of("f0", "f1"), names(first.metricFilters()));
assertNotNull(first.nextToken());
CloudWatchLogsMetricFilterService.DescribeMetricFiltersResult second =
service.describeMetricFilters(GROUP, null, null, null, first.nextToken(), 2, REGION);
assertEquals(List.of("f2", "f3"), names(second.metricFilters()));
CloudWatchLogsMetricFilterService.DescribeMetricFiltersResult last =
service.describeMetricFilters(GROUP, null, null, null, second.nextToken(), 2, REGION);
assertEquals(List.of("f4"), names(last.metricFilters()));
assertNull(last.nextToken());
}
private static List<String> names(List<MetricFilter> filters) {
return filters.stream().map(MetricFilter::getFilterName).toList();
}
// ──────────────────────────── DeleteMetricFilter ────────────────────────────
@Test
void deleteRemovesTheFilterAndRejectsWhatIsNotThere() {
service.putMetricFilter(errorCounter(GROUP, "errors"), REGION);
service.deleteMetricFilter(GROUP, "errors", REGION);
assertEquals(0, service.countMetricFilters(GROUP, REGION));
rejected(() -> service.deleteMetricFilter(GROUP, "errors", REGION), "ResourceNotFoundException");
rejected(() -> service.deleteMetricFilter("/missing", "errors", REGION), "ResourceNotFoundException");
rejected(() -> service.deleteMetricFilter(GROUP, null, REGION), "InvalidParameterException");
}
@Test
void deletingTheLogGroupTakesItsFiltersAlong() {
service.putMetricFilter(errorCounter(GROUP, "errors"), REGION);
service.putMetricFilter(errorCounter(OTHER_GROUP, "errors"), REGION);
service.onLogGroupDeleted(new LogGroupDeleted(REGION, GROUP));
assertEquals(0, service.countMetricFilters(GROUP, REGION));
assertEquals(1, service.countMetricFilters(OTHER_GROUP, REGION));
}
// ──────────────────────────── TestMetricFilter ────────────────────────────
@Test
void testMetricFilterReportsMatchesWithOneBasedNumbersAndExtractedValues() {
List<CloudWatchLogsMetricFilterService.MetricFilterMatchRecord> matches = service.testMetricFilter(
"[..., status_code=200, size]", List.of(
"127.0.0.1 - frank [10/Oct/2000:13:25:15 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 1534",
"127.0.0.1 - frank [10/Oct/2000:13:35:22 -0700] \"GET /apache_pb.gif HTTP/1.0\" 500 5324",
"127.0.0.1 - frank [10/Oct/2000:13:50:35 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 4355"));
assertEquals(2, matches.size());
assertEquals(1, matches.get(0).eventNumber());
assertEquals(3, matches.get(1).eventNumber());
assertEquals("1534", matches.get(0).extractedValues().get("$size"));
assertEquals("200", matches.get(0).extractedValues().get("$status_code"));
assertEquals("frank", matches.get(0).extractedValues().get("$3"));
assertTrue(matches.get(0).eventMessage().endsWith("200 1534"));
List<CloudWatchLogsMetricFilterService.MetricFilterMatchRecord> terms = service.testMetricFilter(
"\"[ERROR]\"", List.of("[INFO] up", "[ERROR] down"));
assertEquals(1, terms.size());
assertEquals(2, terms.getFirst().eventNumber());
assertEquals(Map.of(), terms.getFirst().extractedValues());
}
@Test
void testMetricFilterDoesNotExposeJsonExtractions() {
List<CloudWatchLogsMetricFilterService.MetricFilterMatchRecord> matches = service.testMetricFilter(
"{ $.latency = * }", List.of("plain text", "{\"latency\":50}"));
assertEquals(1, matches.size());
assertEquals(2, matches.getFirst().eventNumber());
assertEquals(Map.of(), matches.getFirst().extractedValues());
}
@Test
void testMetricFilterRejectsWhatTheApiRejects() {
rejected(() -> service.testMetricFilter("{ $.a = }", List.of("x")), "InvalidParameterException");
rejected(() -> service.testMetricFilter(null, List.of("x")), "InvalidParameterException");
rejected(() -> service.testMetricFilter("ERROR", List.of()), "InvalidParameterException");
rejected(() -> service.testMetricFilter("ERROR", List.of("")), "InvalidParameterException");
List<String> tooMany = new ArrayList<>();
for (int i = 0; i < 51; i++) {
tooMany.add("m");
}
rejected(() -> service.testMetricFilter("ERROR", tooMany), "InvalidParameterException");
}
/**
* AWS allows five regex-bearing filters per log group, each holding up to two expressions.
* Replacing a filter reuses its slot, a pattern
* without a regular expression never counts, and the quota is per log group.
*/
@Test
void theRegexQuotaOfALogGroup() {
for (int i = 0; i < 5; i++) {
service.putMetricFilter(filter(GROUP, "r" + i, "{ $.a = %ERROR% || $.a = %WARN% }",
transformation("E", "App", "1")), REGION);
}
rejected(() -> service.putMetricFilter(filter(GROUP, "r5", "%INFO%", transformation("E", "App", "1")), REGION),
"LimitExceededException");
service.putMetricFilter(filter(GROUP, "r2", "%NOTICE%", transformation("E", "App", "1")), REGION);
service.putMetricFilter(filter(GROUP, "plain", "ERROR", transformation("E", "App", "1")), REGION);
service.putMetricFilter(filter(OTHER_GROUP, "r3", "%INFO%", transformation("E", "App", "1")), REGION);
}
/** The criterion has to parse and to fit the 2000 characters the API allows. */
@Test
void aFieldSelectionCriterionIsCheckedBeforeItIsStored() {
MetricFilter selected = errorCounter(GROUP, "selected");
selected.setFieldSelectionCriteria("@aws.region = \"us-east-1\" && @aws.account IN [\"000000000000\"]");
assertNotNull(service.putMetricFilter(selected, REGION).getFieldSelectionCriteria());
MetricFilter unknownField = errorCounter(GROUP, "unknown");
unknownField.setFieldSelectionCriteria("@aws.zone = \"us-east-1\"");
rejected(() -> service.putMetricFilter(unknownField, REGION), "InvalidParameterException");
MetricFilter tooLong = errorCounter(GROUP, "long");
tooLong.setFieldSelectionCriteria("@aws.region = \"" + "x".repeat(2000) + "\"");
rejected(() -> service.putMetricFilter(tooLong, REGION), "InvalidParameterException");
}
}
@@ -0,0 +1,227 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsMetricFilterCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import jakarta.enterprise.event.Event;
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.Instant;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.services.cloudwatch.logs.PublicationTestSupport.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/** Graceful factory shutdown/reload, not a durability claim for the process-local retry queue. */
class CloudWatchLogsMetricFilterStorageReloadTest {
@TempDir Path directory;
@ParameterizedTest
@ValueSource(strings = {"memory", "persistent", "hybrid", "wal"})
void definitionsQuotasDeletionIsolationAndPublishedSamplesSurviveAccordingToMode(String mode) {
long created;
try (Services first = open(mode, ACCOUNT)) {
first.group(GROUP, REGION);
first.group(GROUP, "us-east-1");
MetricFilter definition = definition("kept", "{ $.kind = %ERROR% }", "$.value", 7.0);
definition.setApplyOnTransformedLogs(true);
definition.setFieldSelectionCriteria("@aws.region = \"" + REGION + "\"");
definition.setEmitSystemFieldDimensions(List.of("@aws.region"));
created = first.filters.putMetricFilter(definition, REGION).getCreationTime();
for (int i = 0; i < 3; i++) {
first.filters.putMetricFilter(definition("regex" + i, "%WARN%", "1", null), REGION);
}
first.logs.putSubscriptionFilter(GROUP, "subscription", "%INFO%", "arn:aws:lambda:" + REGION
+ ":" + ACCOUNT + ":function:target", null, REGION);
first.filters.putMetricFilter(definition("deleted", "ERROR", "3", 7.0), REGION);
first.filters.deleteMetricFilter(GROUP, "deleted", REGION);
MetricFilter dimensioned = definition("dimensioned", "{ $.kind = * }", "$.value", null);
dimensioned.getMetricTransformations().getFirst().setDimensions(Map.of("Kind", "$.kind"));
first.filters.putMetricFilter(dimensioned, REGION);
first.filters.putMetricFilter(definition("regional", "ERROR", "1", null), "us-east-1");
first.logs.putLogEvents(GROUP, "s", List.of(Map.of("timestamp", TIME, "message", "INFO")), REGION);
assertEquals(5, first.filters.countMetricFilters(GROUP, REGION));
assertEquals(1, first.logs.describeLogGroups(GROUP, REGION).size());
first.factory.flushAll();
}
// Different accounts use the very same factory path, with no concurrent writers.
try (Services other = open(mode, OTHER_ACCOUNT)) {
assertTrue(other.logs.describeLogGroups(GROUP, REGION).isEmpty());
other.group(GROUP, REGION);
other.filters.putMetricFilter(definition("other", "ERROR", "9", null), REGION);
}
try (Services second = open(mode, ACCOUNT)) {
if (mode.equals("memory")) {
assertTrue(second.logs.describeLogGroups(null, REGION).isEmpty());
assertTrue(second.metrics.listMetrics(null, null, null, REGION).isEmpty());
return;
}
List<MetricFilter> loaded = second.filters.describeMetricFilters(
GROUP, null, null, null, null, 50, REGION).metricFilters();
assertEquals(5, loaded.size());
assertFalse(loaded.stream().anyMatch(f -> List.of("deleted", "other", "regional").contains(f.getFilterName())));
MetricFilter kept = loaded.stream().filter(f -> f.getFilterName().equals("kept")).findFirst().orElseThrow();
assertEquals(created, kept.getCreationTime());
assertEquals("{ $.kind = %ERROR% }", kept.getFilterPattern());
assertEquals(true, kept.getApplyOnTransformedLogs());
assertEquals("@aws.region = \"" + REGION + "\"", kept.getFieldSelectionCriteria());
assertEquals(List.of("@aws.region"), kept.getEmitSystemFieldDimensions());
assertEquals("$.value", kept.getMetricTransformations().getFirst().getMetricValue());
assertEquals("Value", kept.getMetricTransformations().getFirst().getMetricName());
assertEquals("kept", kept.getMetricTransformations().getFirst().getMetricNamespace());
assertEquals(7.0, kept.getMetricTransformations().getFirst().getDefaultValue());
assertEquals("Count", kept.getMetricTransformations().getFirst().getUnit());
assertEquals(Map.of("Kind", "$.kind"), loaded.stream().filter(f -> f.getFilterName().equals("dimensioned"))
.findFirst().orElseThrow().getMetricTransformations().getFirst().getDimensions());
assertEquals(5, second.filters.countMetricFilters(GROUP, REGION));
assertEquals(1, second.filters.countMetricFilters(GROUP, "us-east-1"));
AwsException quota = assertThrows(AwsException.class, () ->
second.filters.putMetricFilter(definition("over", "%FATAL%", "1", null), REGION));
assertEquals("LimitExceededException", quota.getErrorCode());
second.logs.deleteSubscriptionFilter(GROUP, "subscription", REGION);
second.filters.putMetricFilter(definition("over", "%FATAL%", "1", null), REGION);
assertEquals(6, second.filters.countMetricFilters(GROUP, REGION));
List<CloudWatchMetricsService.Datapoint> samples = second.metrics.getMetricStatistics("kept", "Value",
List.of(), Instant.ofEpochMilli(TIME), Instant.ofEpochMilli(TIME).plusSeconds(60),
60, List.of("Sum", "SampleCount"), null, REGION);
assertEquals(1, samples.size());
assertEquals(7, samples.getFirst().sum());
assertEquals(1, samples.getFirst().sampleCount());
assertEquals(Instant.ofEpochMilli(TIME), samples.getFirst().timestamp());
assertTrue(second.metrics.listMetrics(null, null, null, "us-east-1").isEmpty());
second.logs.deleteLogGroup(GROUP, REGION);
}
try (Services third = open(mode, ACCOUNT)) {
assertTrue(third.logs.describeLogGroups(GROUP, REGION).isEmpty());
third.group(GROUP, REGION);
assertEquals(0, third.filters.countMetricFilters(GROUP, REGION), "group deletion cannot resurrect filters");
}
try (Services other = open(mode, OTHER_ACCOUNT)) {
assertEquals(1, other.filters.countMetricFilters(GROUP, REGION));
assertTrue(other.metrics.listMetrics(null, null, null, REGION).isEmpty());
}
}
@ParameterizedTest
@ValueSource(strings = {"persistent", "hybrid", "wal"})
void reloadedMetricFilterCountStillEnforcesTheHundredDefinitionLimit(String mode) {
try (Services first = open(mode, ACCOUNT)) {
first.group(GROUP, REGION);
for (int i = 0; i < 100; i++) {
first.filters.putMetricFilter(definition("filter" + i, "ERROR", "1", null), REGION);
}
}
try (Services second = open(mode, ACCOUNT)) {
assertEquals(100, second.filters.countMetricFilters(GROUP, REGION));
AwsException quota = assertThrows(AwsException.class, () ->
second.filters.putMetricFilter(definition("overflow", "ERROR", "1", null), REGION));
assertEquals("LimitExceededException", quota.getErrorCode());
second.filters.putMetricFilter(definition("filter0", "WARN", "2", null), REGION);
assertEquals(100, second.filters.countMetricFilters(GROUP, REGION));
second.filters.deleteMetricFilter(GROUP, "filter1", REGION);
second.filters.putMetricFilter(definition("replacement", "ERROR", "1", null), REGION);
assertEquals(100, second.filters.countMetricFilters(GROUP, REGION));
}
try (Services third = open(mode, ACCOUNT)) {
assertEquals(100, third.filters.countMetricFilters(GROUP, REGION));
assertTrue(third.filters.describeMetricFilters(GROUP, "filter1", null, null, null, 50, REGION)
.metricFilters().stream().noneMatch(f -> f.getFilterName().equals("filter1")));
}
}
@ParameterizedTest
@ValueSource(strings = {"persistent", "hybrid", "wal"})
void actualCfnOwnershipMetadataRoundTripsAndStillDeletesOnlyItsNamedFilter(String mode) throws Exception {
Map<String, String> attributes;
try (Services first = open(mode, ACCOUNT)) {
first.group(GROUP, REGION);
StackResource resource = new StackResource();
resource.setLogicalId("Filter");
resource.setResourceType("AWS::Logs::MetricFilter");
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolveNode(any())).thenAnswer(call -> call.getArgument(0));
new LogsMetricFilterCfnProvisioner(first.filters).provision(resource, new ObjectMapper().readTree("""
{"LogGroupName":"/publication","FilterName":"owned","FilterPattern":"ERROR",
"MetricTransformations":[{"MetricNamespace":"CfnReload","MetricName":"Count","MetricValue":"1"}]}
"""), new ProvisionContext(engine, REGION, ACCOUNT, "reload"));
assertEquals("owned", resource.getPhysicalId());
attributes = Map.copyOf(resource.getAttributes());
assertTrue(attributes.get("__FlociMetricFilterState").contains("\"ownership\":\"OWNED\""));
first.resources().put("filter", resource);
}
try (Services second = open(mode, ACCOUNT)) {
StackResource loaded = second.resources().get("filter").orElseThrow();
assertEquals(attributes, loaded.getAttributes());
assertEquals("owned", loaded.getPhysicalId());
second.filters.putMetricFilter(definition("unrelated", "ERROR", "1", null), REGION);
new LogsMetricFilterCfnProvisioner(second.filters).delete(loaded, REGION);
assertEquals(List.of("unrelated"), second.filters.describeMetricFilters(
GROUP, null, null, null, null, 50, REGION).metricFilters().stream().map(MetricFilter::getFilterName).toList());
}
}
private Services open(String mode, String account) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(account);
when(config.storage().persistentPath()).thenReturn(directory.toString());
when(config.storage().wal().compactionIntervalMs()).thenReturn(3_600_000L);
when(config.services().cloudwatchlogs().maxEventsPerQuery()).thenReturn(10_000);
when(config.services().cloudwatchlogs().maxStoredEvents()).thenReturn(10_000);
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode(anyString())).thenReturn(mode);
when(access.storageFlushInterval(anyString())).thenReturn(3_600_000L);
return new Services(new StorageFactory(config, access), config, account);
}
private static class Services implements AutoCloseable {
final StorageFactory factory;
final CloudWatchLogsService logs;
final CloudWatchMetricsService metrics;
final CloudWatchLogsMetricFilterService filters;
@SuppressWarnings("unchecked")
Services(StorageFactory factory, EmulatorConfig config, String account) {
this.factory = factory;
RegionResolver resolver = new RegionResolver(REGION, account);
Event<LogEventsIngested> ingested = mock(Event.class);
Event<LogGroupDeleted> deleted = mock(Event.class);
logs = new CloudWatchLogsService(factory, config, resolver, ingested, deleted);
metrics = new CloudWatchMetricsService(factory, resolver);
filters = new CloudWatchLogsMetricFilterService(logs, metrics, resolver);
doAnswer(call -> { filters.onLogEventsIngested(call.getArgument(0)); return null; }).when(ingested).fire(any());
doAnswer(call -> { filters.onLogGroupDeleted(call.getArgument(0)); return null; }).when(deleted).fire(any());
}
void group(String group, String region) {
logs.createLogGroup(group, null, null, region);
logs.createLogStream(group, "s", region);
}
AccountAwareStorageBackend<StackResource> resources() {
return factory.create("cloudformation", "reload-resources.json", new TypeReference<>() {});
}
/** Production order: the publisher drains and stops before storage shuts down. */
@Override public void close() {
filters.stop();
factory.shutdownAll();
}
}
}
@@ -0,0 +1,170 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class CloudWatchLogsMetricFilterWireTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String PUT = """
{"logGroupName":"/synthetic","filterName":"synthetic","filterPattern":"",
"metricTransformations":[{"metricName":"Count","metricNamespace":"Synthetic","metricValue":"1"}]}
""";
private static final String DELETE = """
{"logGroupName":"/synthetic","filterName":"synthetic"}
""";
private static final String TEST = """
{"filterPattern":"","logEventMessages":["synthetic"]}
""";
private CloudWatchLogsMetricFilterService service;
private CloudWatchLogsMetricFilterHandler handler;
@BeforeEach
void setUp() {
service = mock(CloudWatchLogsMetricFilterService.class);
when(service.describeMetricFilters(any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new CloudWatchLogsMetricFilterService.DescribeMetricFiltersResult(List.of(), null));
when(service.testMetricFilter(any(), any())).thenReturn(List.of());
clearInvocations(service);
handler = new CloudWatchLogsMetricFilterHandler(service, MAPPER);
}
static Stream<Arguments> invalidRequests() throws Exception {
List<Arguments> cases = new ArrayList<>();
for (String action : List.of("PutMetricFilter", "DescribeMetricFilters", "DeleteMetricFilter", "TestMetricFilter")) {
for (String root : List.of("null", "[]", "\"text\"", "true", "1")) {
cases.add(Arguments.of(action, MAPPER.readTree(root)));
}
}
strings(cases, "PutMetricFilter", PUT,
List.of("logGroupName", "filterName", "filterPattern", "fieldSelectionCriteria"));
strings(cases, "DeleteMetricFilter", DELETE, List.of("logGroupName", "filterName"));
strings(cases, "DescribeMetricFilters", "{}",
List.of("logGroupName", "filterNamePrefix", "metricName", "metricNamespace", "nextToken"));
strings(cases, "TestMetricFilter", TEST, List.of("filterPattern"));
for (String member : List.of("metricName", "metricNamespace", "metricValue", "unit")) {
for (String value : List.of("null", "true", "1", "[]", "{}")) {
ObjectNode request = (ObjectNode) MAPPER.readTree(PUT);
((ObjectNode) request.path("metricTransformations").get(0)).set(member, MAPPER.readTree(value));
cases.add(Arguments.of("PutMetricFilter", request));
}
}
replace(cases, "PutMetricFilter", PUT, "applyOnTransformedLogs", "null", "\"true\"", "1", "[]", "{}");
replace(cases, "PutMetricFilter", PUT, "metricTransformations",
"null", "{}", "\"text\"", "1", "true", "[null]", "[[]]", "[1]", "[\"text\"]");
replace(cases, "PutMetricFilter", PUT, "emitSystemFieldDimensions",
"null", "{}", "\"@aws.region\"", "1", "true", "[null]", "[[]]", "[1]");
replace(cases, "TestMetricFilter", TEST, "logEventMessages",
"null", "{}", "\"text\"", "1", "true", "[null]", "[{}]", "[1]", "[true]", "[[]]");
replace(cases, "DescribeMetricFilters", "{}", "limit",
"null", "\"1\"", "true", "[]", "{}", "1.5", "1.0", "2147483649", "4294967297", "0", "51");
for (String value : List.of("null", "[]", "\"text\"", "1", "true", "{\"Name\":null}", "{\"Name\":1}",
"{\"Name\":true}", "{\"Name\":[]}", "{\"Name\":{}}")) {
ObjectNode request = (ObjectNode) MAPPER.readTree(PUT);
((ObjectNode) request.path("metricTransformations").get(0)).set("dimensions", MAPPER.readTree(value));
cases.add(Arguments.of("PutMetricFilter", request));
}
for (String value : List.of("null", "[]", "{}", "true", "1e309")) {
ObjectNode request = (ObjectNode) MAPPER.readTree(PUT);
((ObjectNode) request.path("metricTransformations").get(0)).set("defaultValue", MAPPER.readTree(value));
cases.add(Arguments.of("PutMetricFilter", request));
}
return cases.stream();
}
private static void strings(List<Arguments> cases, String action, String request, List<String> members)
throws Exception {
for (String member : members) {
replace(cases, action, request, member, "null", "true", "1", "[]", "{}");
}
}
private static void replace(List<Arguments> cases, String action, String json, String member, String... values)
throws Exception {
for (String value : values) {
ObjectNode request = (ObjectNode) MAPPER.readTree(json);
request.set(member, MAPPER.readTree(value));
cases.add(Arguments.of(action, request));
}
}
@ParameterizedTest
@MethodSource("invalidRequests")
void rejectsIncorrectNodeTypesBeforeCallingTheService(String action, JsonNode request) {
AwsException error = assertThrows(AwsException.class, () -> handler.handle(action, request, "eu-west-1"),
() -> action + " " + request);
assertEquals("InvalidParameterException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
verifyNoInteractions(service);
}
@Test
void numericStringDefaultReportsTheSerializationErrorVerifiedOnLiveAws() throws Exception {
try (InputStream input = getClass().getResourceAsStream(
"/cloudwatchlogs/metric-filter-default-value-wire-aws.json")) {
JsonNode observation = MAPPER.readTree(input);
ObjectNode request = (ObjectNode) MAPPER.readTree(PUT);
((ObjectNode) request.path("metricTransformations").get(0))
.set("defaultValue", observation.get("requestValue"));
AwsException error = assertThrows(AwsException.class,
() -> handler.handle("PutMetricFilter", request, "eu-west-1"));
assertEquals("Verified on Live AWS", observation.path("provenance").path("verification").textValue());
assertEquals(observation.path("response").path("status").intValue(), error.getHttpStatus());
assertEquals(observation.path("response").path("body").path("__type").textValue(), error.getErrorCode());
assertEquals(observation.path("response").path("body").path("Message").textValue(), error.getMessage());
verifyNoInteractions(service);
}
}
@Test
void otherStringsFollowTheSameNodeTypeRuleWithoutClaimingSeparateAwsObservations() throws Exception {
for (String value : List.of("NaN", "zero")) {
ObjectNode request = (ObjectNode) MAPPER.readTree(PUT);
((ObjectNode) request.path("metricTransformations").get(0)).put("defaultValue", value);
AwsException error = assertThrows(AwsException.class,
() -> handler.handle("PutMetricFilter", request, "eu-west-1"));
assertEquals("SerializationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
verifyNoInteractions(service);
}
@Test
void validShapesKeepObjectNodeResponsesAndNumericDefaults() throws Exception {
for (String action : List.of("PutMetricFilter", "DescribeMetricFilters", "DeleteMetricFilter", "TestMetricFilter")) {
String json = switch (action) {
case "PutMetricFilter" -> PUT.replace("\"metricValue\":\"1\"", "\"metricValue\":\"1\",\"defaultValue\":0");
case "DeleteMetricFilter" -> DELETE;
case "TestMetricFilter" -> TEST;
default -> "{\"limit\":50}";
};
Response response = handler.handle(action, MAPPER.readTree(json), "eu-west-1");
assertEquals(200, response.getStatus());
assertInstanceOf(ObjectNode.class, response.getEntity());
}
}
}
@@ -32,6 +32,7 @@ class CloudWatchLogsServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
10000,
new RegionResolver("us-east-1", "000000000000")
);
@@ -80,6 +81,7 @@ class CloudWatchLogsServiceTest {
new AccountAwareStorageBackend<>(rawStreams, null, "000000000000"),
new AccountAwareStorageBackend<>(rawEvents, null, "000000000000"),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "000000000000"),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "000000000000"),
10_000, new RegionResolver(REGION, "000000000000"));
String accountA = "111111111111";
String accountB = "222222222222";
@@ -120,6 +122,7 @@ class CloudWatchLogsServiceTest {
new AccountAwareStorageBackend<>(rawStreams, null, accountB),
new AccountAwareStorageBackend<>(rawEvents, null, accountB),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, accountB),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, accountB),
10_000, new RegionResolver(REGION, accountB));
long now = System.currentTimeMillis();
long twoDaysAgo = now - 2 * 86_400_000L;
@@ -154,6 +157,7 @@ class CloudWatchLogsServiceTest {
new AccountAwareStorageBackend<>(rawStreams, null, accountB),
new AccountAwareStorageBackend<>(rawEvents, null, accountB),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, accountB),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, accountB),
10_000, 2, new RegionResolver(REGION, accountB));
accountService.createLogGroupForAccount(accountA, "/app/logs", null, null, REGION);
@@ -244,6 +248,7 @@ class CloudWatchLogsServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
10000,
maxStoredEvents,
new RegionResolver("us-east-1", "000000000000")
@@ -820,6 +825,7 @@ class CloudWatchLogsServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
2,
new RegionResolver("us-east-1", "000000000000")
);
@@ -904,6 +910,7 @@ class CloudWatchLogsServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
Integer.MAX_VALUE,
new RegionResolver("us-east-1", "000000000000")
);
@@ -1199,6 +1206,7 @@ class CloudWatchLogsServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
0,
new RegionResolver("us-east-1", "000000000000")
);
@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricTransformation;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MetricFilterRulesTest {
@ParameterizedTest
@ValueSource(strings = {"1e309", "-1e309", "NaN", "Infinity", " 1", "1x"})
void numbersThatCannotBePublishedAreNotValues(String text) {
assertNull(MetricFilterRules.number(text));
}
@Test
void finiteNumbersRetainExistingGrammar() {
assertEquals(1000.0, MetricFilterRules.number("1e3"));
assertEquals(-0.5, MetricFilterRules.number("-.5"));
assertEquals(Double.MAX_VALUE, MetricFilterRules.number("1.7976931348623157e308"));
assertEquals(0.0, MetricFilterRules.number("1e-999"));
}
@Test
void corruptedStoredCriteriaSkipRatherThanPublishAcrossAccounts() {
MetricFilter filter = new MetricFilter();
filter.setFilterName("synthetic");
filter.setLogGroupName("/synthetic");
filter.setFieldSelectionCriteria("@aws.account === \"111111111111\"");
assertFalse(MetricFilterRules.selects(filter, "222222222222", "eu-west-1"));
filter.setFieldSelectionCriteria(null);
assertTrue(MetricFilterRules.selects(filter, "222222222222", "eu-west-1"));
}
@Test
void nullSystemDimensionsAreDomainErrorsRatherThanNullPointerExceptions() {
AwsException error = assertThrows(AwsException.class, () -> MetricFilterRules.validateSystemFields(
Arrays.asList("@aws.account", null), new MetricTransformation()));
assertEquals("InvalidParameterException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
MetricFilterRules.validateSystemFields(List.of("@aws.account", "@aws.region"), new MetricTransformation());
}
}
@@ -0,0 +1,137 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricTransformation;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import jakarta.enterprise.event.Event;
import jakarta.enterprise.inject.Instance;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/** Real Logs ingestion and Metrics aggregation, with only CDI wiring supplied by the fixture. */
class PublicationTestSupport {
static final String ACCOUNT = "111111111111";
static final String OTHER_ACCOUNT = "222222222222";
static final String REGION = "eu-west-1";
static final String GROUP = "/publication";
static final long TIME = 1_700_000_040_000L;
final AtomicReference<String> account = new AtomicReference<>(ACCOUNT);
final RegionResolver resolver = mock(RegionResolver.class);
final StorageFactory factory = mock(StorageFactory.class);
final AccountAwareStorageBackend<MetricDatum> metricStore;
final AccountAwareStorageBackend<MetricFilter> filters;
final CloudWatchMetricsService metrics;
final CloudWatchLogsService logs;
final CloudWatchLogsMetricFilterService service;
PublicationTestSupport() {
this(new InMemoryStorage<>());
}
PublicationTestSupport(StorageBackend<String, MetricDatum> sink) {
this(sink, CloudWatchLogsMetricFilterService.MAX_QUEUED_SAMPLES);
}
@SuppressWarnings("unchecked")
PublicationTestSupport(StorageBackend<String, MetricDatum> sink, int queueCapacity) {
Instance<RequestContext> contexts = mock(Instance.class);
RequestContext context = mock(RequestContext.class);
when(contexts.get()).thenReturn(context);
when(context.getAccountId()).thenAnswer(call -> account.get());
when(resolver.getAccountId()).thenAnswer(call -> account.get());
metricStore = new AccountAwareStorageBackend<>(sink, contexts, ACCOUNT);
filters = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), contexts, ACCOUNT);
doReturn(metricStore).when(factory).create(eq("cloudwatchmetrics"), eq("cwmetrics.json"), any());
doReturn(AccountAwareStorageBackend.inMemory(ACCOUNT)).when(factory)
.create(eq("cloudwatchmetrics"), eq("cwalarms.json"), any());
metrics = new CloudWatchMetricsService(factory, resolver);
Event<LogEventsIngested> ingested = mock(Event.class);
Event<LogGroupDeleted> deleted = mock(Event.class);
logs = new CloudWatchLogsService(new AccountAwareStorageBackend<>(new InMemoryStorage<>(), contexts, ACCOUNT),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), contexts, ACCOUNT),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), contexts, ACCOUNT),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), contexts, ACCOUNT), filters,
new InMemoryStorage<>(), 10_000, Integer.MAX_VALUE, resolver, 0L, System::currentTimeMillis,
ingested, deleted);
service = new CloudWatchLogsMetricFilterService(logs, metrics, resolver, queueCapacity);
doAnswer(call -> { service.onLogEventsIngested(call.getArgument(0)); return null; }).when(ingested).fire(any());
doAnswer(call -> { service.onLogGroupDeleted(call.getArgument(0)); return null; }).when(deleted).fire(any());
group(GROUP, REGION);
}
void group(String group, String region) {
logs.createLogGroup(group, null, null, region);
logs.createLogStream(group, "s", region);
}
static MetricFilter definition(String name, String pattern, String value, Double fallback) {
MetricTransformation t = new MetricTransformation();
t.setMetricName("Value");
t.setMetricNamespace(name);
t.setMetricValue(value);
t.setDefaultValue(fallback);
t.setUnit("Count");
MetricFilter f = new MetricFilter();
f.setFilterName(name);
f.setLogGroupName(GROUP);
f.setFilterPattern(pattern);
f.setMetricTransformations(List.of(t));
return f;
}
void put(String name, String pattern, String value, Double fallback) {
service.putMetricFilter(definition(name, pattern, value, fallback), REGION);
}
void ingest(long time, String... messages) {
ingest(null, GROUP, REGION, time, List.of(messages));
}
/** Ingests and drains the publication queue on this thread, as the worker would. */
void ingest(String owner, String group, String region, long time, List<String> messages) {
enqueue(owner, group, region, time, messages);
service.publishQueued();
}
/** Ingests without draining: the samples stay queued until publishQueued, start or stop. */
void enqueue(long time, String... messages) {
enqueue(null, GROUP, REGION, time, List.of(messages));
}
void enqueue(String owner, String group, String region, long time, List<String> messages) {
List<Map<String, Object>> events = messages.stream()
.map(message -> Map.<String, Object>of("timestamp", time, "message", message)).toList();
assertNotNull(logs.putLogEventsForAccount(owner, group, "s", events, region));
}
List<CloudWatchMetricsService.Datapoint> points(String namespace, List<Dimension> dims, long time, String region) {
return metrics.getMetricStatistics(namespace, "Value", dims, Instant.ofEpochMilli(time),
Instant.ofEpochMilli(time).plusSeconds(59), 60, List.of("Sum", "SampleCount"), null, region);
}
void stats(String namespace, long time, double sum, double count) {
stats(namespace, List.of(), time, sum, count);
}
void stats(String namespace, List<Dimension> dims, long time, double sum, double count) {
List<CloudWatchMetricsService.Datapoint> points = points(namespace, dims, time, REGION);
assertEquals(count == 0 ? 0 : 1, points.size());
assertEquals(sum, points.stream().mapToDouble(CloudWatchMetricsService.Datapoint::sum).sum());
assertEquals(count, points.stream().mapToDouble(CloudWatchMetricsService.Datapoint::sampleCount).sum());
}
}
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class FilterPatternAwsCorpusTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@TestFactory
List<DynamicTest> observedAwsPatterns() throws Exception {
List<DynamicTest> tests = new ArrayList<>();
for (String fixture : List.of("filter-pattern-aws.json", "filter-pattern-aws-edges.json",
"filter-pattern-aws-boundaries.json")) {
try (InputStream input = getClass().getResourceAsStream("/cloudwatchlogs/" + fixture)) {
JsonNode corpus = MAPPER.readTree(input);
for (JsonNode example : corpus.path("cases")) {
addCase(tests, example);
}
}
}
return tests;
}
private static void addCase(List<DynamicTest> tests, JsonNode example) {
String id = example.path("id").textValue();
String pattern = example.path("request").path("filterPattern").textValue();
if (example.has("error")) {
tests.add(DynamicTest.dynamicTest(id, () ->
assertThrows(FilterPatternException.class, () -> FilterPattern.parse(pattern), pattern)));
return;
}
JsonNode messages = example.path("request").path("logEventMessages");
for (int index = 0; index < messages.size(); index++) {
String message = messages.get(index).textValue();
int eventNumber = index + 1;
JsonNode expected = null;
for (JsonNode match : example.path("response").path("matches")) {
if (match.path("eventNumber").intValue() == eventNumber) {
expected = match;
break;
}
}
JsonNode expectedMatch = expected;
tests.add(DynamicTest.dynamicTest(id + "/" + eventNumber, () -> {
FilterMatch actual = FilterPattern.parse(pattern).match(message);
assertEquals(expectedMatch != null, actual.matched(), pattern + " on " + message);
if (expectedMatch != null) {
Map<String, String> extracted = MAPPER.convertValue(expectedMatch.path("extractedValues"),
new TypeReference<>() {});
assertEquals(extracted, actual.extractedValues(), pattern + " on " + message);
}
}));
}
}
}
@@ -0,0 +1,503 @@
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The filter pattern syntax CloudWatch Logs documents for metric filters, subscription filters and
* FilterLogEvents: plain terms, {@code %regex%}, JSON selectors and space-delimited fields. The
* examples are the ones on the AWS reference pages, with the matches those pages state.
*/
class FilterPatternTest {
private static boolean matches(String pattern, String message) {
return FilterPattern.parse(pattern).match(message).matched();
}
private static FilterMatch match(String pattern, String message) {
return FilterPattern.parse(pattern).match(message);
}
@Nested
class Terms {
@Test
void aSingleTermMatchesMessagesContainingIt() {
assertTrue(matches("ERROR", "[ERROR 400] BAD REQUEST"));
assertTrue(matches("ERROR", "[ERROR 419] MISSING ARGUMENTS"));
assertFalse(matches("ERROR", "[INFO 200] OK"));
}
@Test
void termsAreCaseSensitiveSubstrings() {
assertFalse(matches("ERROR", "an error happened"));
assertTrue(matches("Exception", "[ERROR] Unhanded exception: InvalidQueryException"),
"the API reference matches Exception inside InvalidQueryException");
}
@Test
void severalTermsMustAllBePresent() {
assertTrue(matches("ERROR ARGUMENTS", "[ERROR 419] MISSING ARGUMENTS"));
assertTrue(matches("ERROR ARGUMENTS", "[ERROR 420] INVALID ARGUMENTS"));
assertFalse(matches("ERROR ARGUMENTS", "[ERROR 400] BAD REQUEST"));
assertFalse(matches("ERROR ARGUMENTS", "[ERROR 401] UNAUTHORIZED REQUEST"));
}
@Test
void questionMarkTermsMatchWhenAnyIsPresent() {
for (String message : List.of("[ERROR 400] BAD REQUEST", "[ERROR 401] UNAUTHORIZED REQUEST",
"[ERROR 419] MISSING ARGUMENTS", "[ERROR 420] INVALID ARGUMENTS")) {
assertTrue(matches("?ERROR ?ARGUMENTS", message), message);
}
assertFalse(matches("?ERROR ?ARGUMENTS", "[INFO 200] OK"));
}
/** The reference: combined with other terms, the question mark terms are ignored. */
@Test
void questionMarkTermsAreIgnoredNextToOtherTerms() {
assertTrue(matches("?ERROR ?ARGUMENTS REQUEST", "[INFO] REQUEST FAILED"));
assertTrue(matches("?ERROR ?ARGUMENTS REQUEST", "[WARN] UNAUTHORIZED REQUEST"));
assertTrue(matches("?ERROR ?ARGUMENTS REQUEST", "[ERROR] 400 BAD REQUEST"));
assertFalse(matches("?ERROR ?ARGUMENTS REQUEST", "[ERROR] MISSING ARGUMENTS"));
}
@Test
void quotedPhrasesMatchExactly() {
assertTrue(matches("\"INTERNAL SERVER ERROR\"", "[ERROR 500] INTERNAL SERVER ERROR"));
assertFalse(matches("\"INTERNAL SERVER ERROR\"", "[ERROR 500] INTERNAL ERROR ON SERVER"));
assertTrue(matches("\"[ERROR]\"", "02 May 2014 00:34:16,142 [ERROR] Unhanded exception"));
assertFalse(matches("\"[ERROR]\"", "02 May 2014 00:34:12,525 [INFO] Starting the application"));
}
@Test
void aQuotedPhraseAndATermCombine() {
assertTrue(matches("\"[ERROR]\" Exception",
"02 May 2014 00:34:16,142 [ERROR] Unhanded exception: InvalidQueryException"));
assertFalse(matches("\"[ERROR]\" Exception", "02 May 2014 00:34:16,224 [ERROR] Terminating the application"));
}
@Test
void minusExcludesATerm() {
assertTrue(matches("ERROR -ARGUMENTS", "[ERROR 400] BAD REQUEST"));
assertTrue(matches("ERROR -ARGUMENTS", "[ERROR 401] UNAUTHORIZED REQUEST"));
assertFalse(matches("ERROR -ARGUMENTS", "[ERROR 419] MISSING ARGUMENTS"));
assertFalse(matches("ERROR -ARGUMENTS", "[ERROR 420] INVALID ARGUMENTS"));
}
@Test
void aQuotedSpaceMatchesEverythingWithASpaceAndAnEmptyPatternMatchesEverything() {
assertTrue(matches("\" \"", "two words"));
assertTrue(matches("", "anything at all"));
assertTrue(matches(" ", "anything at all"));
assertTrue(matches("", ""));
}
@Test
void aTermMatchHasNoExtractedValues() {
FilterMatch m = match("ERROR", "[ERROR 400] BAD REQUEST");
assertTrue(m.matched());
assertEquals(Map.of(), m.extractedValues());
assertNull(m.value("$.anything"));
}
@Test
void aNullMessageMatchesNothingButTheEmptyPattern() {
assertFalse(matches("ERROR", null));
assertFalse(matches("%ERR%", null));
assertTrue(matches("-ERROR", null), "an exclusion alone matches what lacks the term");
assertTrue(matches("", null));
assertFalse(matches("{ $.a = 1 }", null));
assertFalse(matches("[a, b]", null));
}
@Test
void anUnterminatedQuoteIsRejected() {
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("\"INTERNAL SERVER"));
}
}
@Nested
class Regex {
@Test
void aStandaloneRegexMatchesAnywhereInTheMessage() {
assertTrue(matches("%AUTHORIZED%", "[ERROR 401] UNAUTHORIZED REQUEST"));
assertTrue(matches("%AUTHORIZED%", "[SUCCESS 200] AUTHORIZED REQUEST"));
assertFalse(matches("%AUTHORIZED%", "[SUCCESS 200] OK"));
}
@Test
void theDocumentedOperatorsBehaveAsDocumented() {
assertTrue(matches("%^[hc]at%", "hat trick"));
assertFalse(matches("%^[hc]at%", "a hat"));
assertTrue(matches("%[hc]at$%", "the cat"));
assertTrue(matches("%colou?r%", "color"));
assertTrue(matches("%colou?r%", "colour"));
assertTrue(matches("%a{3,5}%", "aaaa"));
assertFalse(matches("%^a{3,5}$%", "aa"));
assertTrue(matches("%gra|ey%", "grey"));
assertTrue(matches("%^starting|^initializing|^shutting down%", "shutting down now"));
assertFalse(matches("%^starting|^initializing|^shutting down%", "skipping initializing ..."));
assertTrue(matches("%\\[.\\]%", "value [7] here"));
assertTrue(matches("%ab*c%", "ac"));
assertTrue(matches("%ab+c%", "abbc"));
assertFalse(matches("%ab+c%", "ac"));
assertTrue(matches("%.at%", "4at"));
assertTrue(matches("%\\d%", "port 80"));
assertTrue(matches("%\\D%", "port 80"));
assertTrue(matches("%\\s%", "a b"));
assertTrue(matches("%\\w%", "_"));
assertTrue(matches("%\\x3A%", "key:value"), "\\xhh matches the ASCII character");
assertTrue(matches("%10\\.10\\.0\\.1%", "from 10.10.0.1"));
assertFalse(matches("%10\\.10\\.0\\.1%", "from 10010,051"));
}
@Test
void unsupportedCharactersAreRejected() {
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("%something!%"));
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("%(ab)+%"),
"parentheses are not supported");
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("%café%"),
"multi-byte characters are not supported");
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("%\\p%"),
"only the documented escapes are supported");
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("%\\(ab\\)+%"),
"escaping does not admit parentheses");
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("%\\!%"));
assertTrue(matches("%a\\-b%", "a-b"), "an escaped symbol from the allowed list is fine");
assertTrue(matches("%\\\\%", "back\\slash"), "an escaped backslash is a backslash");
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("%%"));
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("%abc"));
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("%a{3,%"));
}
@Test
void aPatternMayHoldAtMostTwoRegexes() {
FilterPattern.parse("[a=%x%, b=%y%, c]");
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("[a=%x%, b=%y%, c=%z%]"));
}
}
@Nested
class Json {
private static final String EVENT = """
{
"eventType": "UpdateTrail",
"sourceIPAddress": "111.111.111.111",
"arrayKey": ["value", "another value"],
"objectList": [{"name": "a", "id": 1}, {"name": "b", "id": 2}],
"SomeObject": null,
"cluster.name": "c"
}
""";
private static final String COMPOUND = """
{
"user": {"id": 1, "email": "John.Stiles@example.com"},
"users": [{"id": 2, "email": "John.Doe@example.com"}, {"id": 3, "email": "Jane.Doe@example.com"}],
"actions": ["GET", "PUT", "DELETE"],
"coordinates": [[0, 1, 2], [4, 5, 6], [7, 8, 9]]
}
""";
/**
* AWS allows one wildcard in a property selector and three wildcard selectors in a whole
* pattern, the quotas the syntax page states beside its JSON examples.
*/
@Test
void theWildcardQuotas() {
assertTrue(matches("{ $.* = %111\\.111\\.111\\.1[0-9]{1,2}% }", EVENT),
"the reference example uses one wildcard in the selector");
assertTrue(matches("{ $.objectList[*].name = \"a\" }", EVENT));
assertEquals(FilterPattern.Kind.JSON, FilterPattern.parse(
"{ $.users[*].id = 2 || $.actions[*] = \"GET\" || $.coordinates[*][0] = 4 }").kind(),
"three wildcard selectors are within the quota");
assertThrows(FilterPatternException.class, () -> FilterPattern.parse("{ $.*[*] = \"a\" }"),
"two wildcards in one property selector are more than AWS allows");
assertThrows(FilterPatternException.class, () -> FilterPattern.parse(
"{ $.users[*].id = 2 || $.actions[*] = \"GET\" || $.coordinates[*][0] = 4"
+ " || $.objectList[*].id = 1 }"),
"four wildcard selectors are more than AWS allows in one pattern");
}
@Test
void theReferenceStringExamples() {
assertTrue(matches("{ $.eventType = \"UpdateTrail\" }", EVENT));
assertTrue(matches("{ $.sourceIPAddress != 123.123.* }", EVENT));
assertFalse(matches("{ $.sourceIPAddress != 111.111.* }", EVENT));
assertTrue(matches("{ $.arrayKey[0] = \"value\" }", EVENT));
assertFalse(matches("{ $.arrayKey[1] = \"value\" }", EVENT));
assertTrue(matches("{ $.eventType = %Trail% }", EVENT));
assertTrue(matches("{ $.arrayKey[*] = %val.{2}% }", EVENT));
assertTrue(matches("{ $.* = %111\\.111\\.111\\.1[0-9]{1,2}% }", EVENT));
assertTrue(matches("{ $.['cluster.name'] = \"c\" }", EVENT));
assertTrue(matches("{ $.SomeObject IS NULL }", EVENT));
assertFalse(matches("{ $.eventType IS NULL }", EVENT));
assertTrue(matches("{ $.SomeOtherObject NOT EXISTS }", EVENT));
assertFalse(matches("{ $.eventType NOT EXISTS }", EVENT));
assertTrue(matches("{ $.objectList[1].name = \"b\" }", EVENT));
assertTrue(matches("{ $.objectList[*].id = 2 }", EVENT));
}
@Test
void theReferenceNumericExamples() {
assertTrue(matches("{ $.bandwidth > 75 }", "{\"bandwidth\": 80}"));
assertFalse(matches("{ $.bandwidth > 75 }", "{\"bandwidth\": 75}"));
assertTrue(matches("{ $.latency < 50 }", "{\"latency\": 49.5}"));
assertTrue(matches("{ $.refreshRate >= 60 }", "{\"refreshRate\": 60}"));
assertTrue(matches("{ $.responseTime <= 5 }", "{\"responseTime\": 5}"));
assertTrue(matches("{ $.errorCode = 400}", "{\"errorCode\": 400}"));
assertTrue(matches("{ $.errorCode != 500 }", "{\"errorCode\": 400}"));
assertFalse(matches("{ $.errorCode != 500 }", "{\"errorCode\": 500}"));
assertTrue(matches("{ $.number[0] = 1e+3 }", "{\"number\": [1000]}"));
assertTrue(matches("{ $.number[0] != 1e-3 }", "{\"number\": [1000]}"));
assertTrue(matches("{ $.errorCode = 4* }", "{\"errorCode\": 404}"), "the asterisk also matches numbers");
}
@Test
void theReferenceCompoundExamples() {
assertTrue(matches("{ ($.user.id = 1) && ($.users[0].email = \"John.Doe@example.com\") }", COMPOUND));
assertTrue(matches("{ $.user.email = \"John.Stiles@example.com\" || $.coordinates[0][1] = \"nonmatch\""
+ " && $.actions[2] = \"nonmatch\" }", COMPOUND));
assertFalse(matches("{ ($.user.email = \"John.Stiles@example.com\" || $.coordinates[0][1] = \"nonmatch\")"
+ " && $.actions[2] = \"nonmatch\" }", COMPOUND));
assertFalse(matches("{ ($.user.id = 2 && $.users[0].email = \"nonmatch\") || $.actions[2] = \"GET\" }",
COMPOUND));
assertTrue(matches("{ $.coordinates[1][2] = 6 }", COMPOUND));
}
@Test
void aMessageThatIsNotJsonDoesNotMatch() {
assertFalse(matches("{ $.eventType = \"UpdateTrail\" }", "eventType=UpdateTrail"));
assertFalse(matches("{ $.eventType = \"UpdateTrail\" }", "2024-01-01 INFO {\"eventType\": \"UpdateTrail\"}"));
assertFalse(matches("{ $.eventType NOT EXISTS }", "not json"), "an unparseable message matches nothing");
assertFalse(matches("{ $.eventType = \"UpdateTrail\" }", ""));
}
@Test
void aSelectorPointingAtAnObjectOrArrayDoesNotMatch() {
assertFalse(matches("{ $.arrayKey = \"value\" }", EVENT));
assertFalse(matches("{ $.objectList[0] != \"x\" }", EVENT));
assertFalse(matches("{ $.missing != \"x\" }", EVENT), "a missing field satisfies no comparison");
}
@Test
void bareWordsQuotedStringsAndBooleans() {
assertTrue(matches("{ $.eventType = UpdateTrail }", EVENT), "alphanumeric strings may be unquoted");
assertTrue(matches("{ $.flag IS TRUE }", "{\"flag\": true}"));
assertTrue(matches("{ $.flag IS FALSE }", "{\"flag\": false}"));
assertFalse(matches("{ $.flag IS TRUE }", "{\"flag\": \"true\"}"), "IS TRUE wants a boolean");
assertFalse(matches("{ $.flag = true }", "{\"flag\": true}"),
"AWS comparisons exclude booleans; IS TRUE tests boolean values");
assertTrue(matches("{ $.flag = true }", "{\"flag\": \"true\"}"));
assertTrue(matches("{ $.eventType = \"*\" }", EVENT), "a wildcard string matches any value");
assertFalse(matches("{ $.SomeObject = \"*\" }", EVENT), "but not null");
assertTrue(matches("{ $.count = \"3\" }", "{\"count\": 3}"), "a number compares by its text too");
assertTrue(matches("{ $.count = 3 }", "{\"count\": \"3\"}"), "and a numeric string by its value");
assertFalse(matches("{ $.count > 2 }", "{\"count\": \"many\"}"));
}
@Test
void jsonMatchesExposeValuesInternallyButNotInTheTestMetricFilterExtractionMap() {
FilterMatch m = match("{ $.eventType = \"UpdateTrail\" && $.objectList[1].id = 2 }", EVENT);
assertTrue(m.matched());
assertEquals(Map.of(), m.extractedValues(), "observed AWS JSON TestMetricFilter response");
assertEquals("UpdateTrail", m.value("$.eventType"));
assertEquals("111.111.111.111", m.value("$.sourceIPAddress"), "any field can be read off a match");
assertEquals("c", m.value("$.['cluster.name']"));
assertNull(m.value("$.missing"));
assertNull(m.value("$.objectList"), "objects and arrays have no value");
assertNull(m.value("$server"), "a space-delimited reference means nothing here");
}
@Test
void malformedPatternsAreRejected() {
for (String bad : List.of("{ $.a = }", "{ $.a }", "{ $.a = 1", "{ $.a = 1 } trailing", "{ a = 1 }",
"{ $.a == 1 }", "{ $.a = 1 && }", "{ ($.a = 1 }", "{ $.a IS MAYBE }", "{ $.a EXISTS }",
"{ $.a[x] = 1 }", "{ $.a = \"unterminated }", "{ $.x[99999999999999999999] = 1 }")) {
assertThrows(FilterPatternException.class, () -> FilterPattern.parse(bad), bad);
}
}
}
@Nested
class SpaceDelimited {
private static final String APACHE =
"127.0.0.1 Prod frank [10/Oct/2000:13:25:15 -0700] \"GET /index.html HTTP/1.0\" 404 1534";
private static final String ACCESS_200 =
"127.0.0.1 - frank [10/Oct/2000:13:25:15 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 1534";
@Test
void quotedAndBracketedRunsAreSingleFields() {
FilterMatch m = match("[ip, user, username, timestamp, request, status_code, bytes]", APACHE);
assertTrue(m.matched());
assertEquals("127.0.0.1", m.value("$ip"));
assertEquals("Prod", m.value("$user"));
assertEquals("10/Oct/2000:13:25:15 -0700", m.value("$timestamp"));
assertEquals("GET /index.html HTTP/1.0", m.value("$request"));
assertEquals("404", m.value("$status_code"));
assertEquals("1534", m.value("$bytes"));
assertEquals("1534", m.value("$7"), "positions can always be read");
}
/**
* The reference says {@code [w1=ERROR, w2]} matches lines of any length and that a blank
* indicator must follow the last term, which holds when the last field takes the rest of
* the line. An ellipsis stands for any number of fields, before, between or after the named ones.
*/
@Test
void fieldCountRules() {
FilterMatch rest = match("[ip, user, rest]", APACHE);
assertTrue(rest.matched());
assertEquals("frank [10/Oct/2000:13:25:15 -0700] \"GET /index.html HTTP/1.0\" 404 1534", rest.value("$rest"));
assertFalse(matches("[w1=ERROR]", "ERROR 09/25/2014 12:00:02 Failed"), "without a blank indicator w1 is the whole line");
assertFalse(matches("[a, b, c, d, e, f, g, h]", APACHE), "eight fields need eight words");
assertFalse(matches("[w1=ERROR, w2]", "ERROR"), "a blank indicator still needs a word");
assertTrue(matches("[..., bytes]", APACHE));
assertTrue(matches("[ip, ..., bytes]", APACHE));
assertTrue(matches("[ip, user, ...]", APACHE));
assertFalse(matches("[a, b, c, d, e, f, g, h, ...]", APACHE), "eight named fields need eight fields");
assertTrue(matches("[]", APACHE), "an empty field list matches any event");
assertTrue(matches("[]", ""), "even an empty one");
assertFalse(matches("[a]", ""));
}
@Test
void theReferenceConditions() {
assertTrue(matches("[ip=%127\\.0\\.0\\.[1-9]%, user, username, timestamp, request =*.html*,"
+ " status_code = 4*, bytes]", APACHE));
assertTrue(matches("[..., request =*.html*, status_code = 4*, bytes]", APACHE));
assertTrue(matches("[ip, user, username, timestamp, request =*.html*, status_code = 404"
+ " || status_code = 410, bytes]", APACHE));
assertTrue(matches("[ip, server, username, timestamp, request, status_code, bytes > 1000]", APACHE));
assertFalse(matches("[ip, server, username, timestamp, request, status_code, bytes > 2000]", APACHE));
assertTrue(matches("[..., status_code=200, size]", ACCESS_200));
assertFalse(matches("[..., status_code=200, size]", APACHE));
}
@Test
void theReferencePatternMatchingExamples() {
assertTrue(matches("[w1=ERROR, w2]", "ERROR 09/25/2014 12:00:02 Failed to process request"));
assertFalse(matches("[w1=ERROR, w2]", "INFO 09/25/2014 12:00:00 GET /service/resource/67 1200"));
assertTrue(matches("[w1=ERROR || w1=WARNING, w2]", "WARNING 09/25/2014 12:00:02 Invalid user request"));
assertTrue(matches("[w1!=ERROR && w1!=WARNING, w2]", "INFO 09/25/2014 12:00:00 GET /service/resource/67 1200"));
assertFalse(matches("[w1!=ERROR && w1!=WARNING, w2]", "ERROR 09/25/2014 12:00:02 Failed to process request"));
assertTrue(matches("[logLevel, date, time, method, url=%/service/resource/[0-9]+$%, response_time]",
"INFO 09/25/2014 12:00:00 GET /service/resource/67 1200"));
assertFalse(matches("[logLevel, date, time, method, url=%/service/resource/[0-9]+$%, response_time]",
"INFO 09/25/2014 12:00:01 POST /service/resource/67/part/111 1310"));
assertTrue(matches("[logLevel, date, time, method, url=%/service/resource/[0-9]+/part/[0-9]+$%, response_time]",
"INFO 09/25/2014 12:00:01 POST /service/resource/67/part/111 1310"));
assertTrue(matches("[w1=ERROR || w1=%WARN%, w2]", "WARNING 09/25/2014 12:00:02 Invalid user request"));
}
/** The extracted values of the TestMetricFilter reference examples, verbatim. */
@Test
void extractedValuesNameFieldsAndNumberTheRest() {
FilterMatch all = match("[ip, identity, user_id, timestamp, request, status_code, size]", ACCESS_200);
assertEquals(Map.of("$ip", "127.0.0.1", "$identity", "-", "$user_id", "frank",
"$timestamp", "10/Oct/2000:13:25:15 -0700", "$request", "GET /apache_pb.gif HTTP/1.0",
"$status_code", "200", "$size", "1534"), all.extractedValues());
FilterMatch ellipsis = match("[..., size]", ACCESS_200);
assertEquals(Map.of("$1", "127.0.0.1", "$2", "-", "$3", "frank", "$4", "10/Oct/2000:13:25:15 -0700",
"$5", "GET /apache_pb.gif HTTP/1.0", "$6", "200", "$size", "1534"), ellipsis.extractedValues());
FilterMatch none = match("[]", ACCESS_200);
assertEquals("1534", none.extractedValues().get("$7"));
assertEquals(7, none.extractedValues().size());
FilterMatch mixed = match("[..., status_code=200, size]", ACCESS_200);
assertEquals("200", mixed.extractedValues().get("$status_code"));
assertEquals("1534", mixed.extractedValues().get("$size"));
assertEquals("frank", mixed.extractedValues().get("$3"));
FilterMatch trailingComma = match("[..., request=*.html*, status_code=4*,]", APACHE);
assertTrue(trailingComma.matched());
assertEquals("1534", trailingComma.extractedValues().get("$7"), "an empty entry is an unnamed field");
assertEquals("404", trailingComma.extractedValues().get("$status_code"));
}
@Test
void valuesOfNamedAndNumberedFieldsCanBeReadOffAMatch() {
FilterMatch m = match("[..., status_code, bytes]", APACHE);
assertEquals("1534", m.value("$bytes"));
assertEquals("Prod", m.value("$2"));
assertNull(m.value("$missing"));
assertNull(m.value("$9"));
assertNull(m.value("$.bytes"), "a JSON reference means nothing here");
}
@Test
void quotedValuesAndNumbersCompare() {
assertTrue(matches("[..., request=\"GET /index.html HTTP/1.0\", status_code, bytes]", APACHE));
assertTrue(matches("[..., status_code >= 400 && status_code < 500, bytes]", APACHE));
assertTrue(matches("[..., status_code, bytes = 1534]", APACHE));
assertFalse(matches("[..., status_code, bytes < 100]", APACHE));
assertFalse(matches("[..., status_code, bytes > 100]", "a b c d e f text"), "a word is not a number");
}
@Test
void malformedPatternsAreRejected() {
for (String bad : List.of("[a, ..., b, ..., c]", "[a, a]", "[a = ]", "[a, b", "[a, b] trailing",
"[a = 1 ||]", "[1a]", "[a, b=x || c=y]")) {
assertThrows(FilterPatternException.class, () -> FilterPattern.parse(bad), bad);
}
}
}
@Nested
class References {
@ParameterizedTest
@ValueSource(strings = {"$ip", "$1", "$7"})
void aDelimitedPatternDeclaresItsNamesAndAnyPosition(String reference) {
assertTrue(FilterPattern.parse("[ip, ..., bytes]").declaresField(reference));
}
@Test
void aDelimitedPatternDoesNotDeclareOtherNames() {
FilterPattern pattern = FilterPattern.parse("[ip, ..., bytes]");
assertFalse(pattern.declaresField("$size"));
assertFalse(pattern.declaresField("$.ip"));
assertFalse(pattern.declaresField("ip"));
}
@Test
void aJsonPatternDeclaresAnySelector() {
FilterPattern pattern = FilterPattern.parse("{ $.a = 1 }");
assertTrue(pattern.declaresField("$.latency"));
assertTrue(pattern.declaresField("$.['a.b'][0]"));
assertFalse(pattern.declaresField("$latency"));
assertFalse(pattern.declaresField("$.a["));
}
@Test
void termPatternsDeclareNothing() {
assertFalse(FilterPattern.parse("ERROR").declaresField("$.a"));
assertFalse(FilterPattern.parse("").declaresField("$1"));
}
@Test
void kindsAreReported() {
assertEquals(FilterPattern.Kind.MATCH_ALL, FilterPattern.parse(" ").kind());
assertEquals(FilterPattern.Kind.TERMS, FilterPattern.parse("ERROR").kind());
assertEquals(FilterPattern.Kind.TERMS, FilterPattern.parse("%ERR%").kind());
assertEquals(FilterPattern.Kind.JSON, FilterPattern.parse("{ $.a = 1 }").kind());
assertEquals(FilterPattern.Kind.SPACE_DELIMITED, FilterPattern.parse("[a, b]").kind());
}
}
}
@@ -0,0 +1,94 @@
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SystemFieldSelectionTest {
private static final String ACCOUNT = "@aws.account = \"111111111111\"";
private static final String REGION = "@aws.region = \"eu-west-1\"";
@Test
void keywordOperatorsFollowTheirTruthTables() {
for (String account : List.of("111111111111", "222222222222")) {
for (String region : List.of("eu-west-1", "us-east-1")) {
boolean a = account.equals("111111111111");
boolean b = region.equals("eu-west-1");
for (String and : List.of("AND", "&&")) {
assertEquals(a && b, SystemFieldSelection.parse(ACCOUNT + " " + and + " " + REGION)
.test(account, region));
}
for (String or : List.of("OR", "||")) {
assertEquals(a || b, SystemFieldSelection.parse(ACCOUNT + " " + or + " " + REGION)
.test(account, region));
}
}
}
}
@Test
void andBindsMoreTightlyThanOrAndParenthesesOverridePrecedence() {
for (String account : List.of("111111111111", "222222222222")) {
for (String region : List.of("eu-west-1", "us-east-1", "ap-south-1")) {
boolean a = account.equals("111111111111");
boolean b = region.equals("eu-west-1");
boolean c = !region.equals("us-east-1");
String third = "@aws.region != \"us-east-1\"";
assertEquals(a || b && c, SystemFieldSelection.parse(ACCOUNT + " OR " + REGION + " AND " + third)
.test(account, region));
assertEquals((a || b) && c, SystemFieldSelection.parse("(" + ACCOUNT + " OR " + REGION + ") AND " + third)
.test(account, region));
}
}
}
@Test
void membershipComposesWithoutRewritingKeywordsInsideValues() {
assertTrue(SystemFieldSelection.parse(
"@aws.account IN [\"111111111111\", \"222222222222\"] AND "
+ "(@aws.region NOT IN [\"us-east-1\"] OR @aws.region = \"AND OR\")")
.test("111111111111", "AND OR"));
}
@ParameterizedTest
@ValueSource(strings = {
"AND", "OR", "&", "|", "&&&", "|||", "AND AND", "OR OR", "XOR", "ANDROID", "ORDER"
})
void malformedOperatorsAreRejected(String operator) {
assertThrows(FilterPatternException.class, () -> SystemFieldSelection.parse(ACCOUNT + " " + operator));
if (!operator.equals("AND") && !operator.equals("OR")) {
assertThrows(FilterPatternException.class,
() -> SystemFieldSelection.parse(ACCOUNT + " " + operator + " " + REGION));
}
}
@ParameterizedTest
@ValueSource(strings = {
"@aws.account == \"111111111111\"",
"@aws.account = =",
"@aws.account = ||",
"@aws.account != &&",
"@aws.account NOTIN [\"111111111111\"]",
"@aws.account IN [\"111111111111\",]",
"@aws.account IN []",
"@aws.account = \"111111111111\" AND ()",
"(@aws.account = \"111111111111\""
})
void malformedComparisonsAreRejected(String expression) {
assertThrows(FilterPatternException.class, () -> SystemFieldSelection.parse(expression));
}
@ParameterizedTest
@ValueSource(strings = {"AND", "OR"})
void keywordsDoNotBecomeJsonLogPatternOperators(String operator) {
assertThrows(FilterPatternException.class,
() -> FilterPattern.parse("{ $.a = 1 " + operator + " $.b = 2 }"));
}
}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CloudWatchMetricFilterQueryNamespaceTest {
@ParameterizedTest
@ValueSource(strings = {"GetMetricStatistics", "GetMetricData"})
void metricFilterReadApisUseTheCloudWatchQueryNamespace(String action) throws Exception {
CloudWatchMetricsService metrics = new CloudWatchMetricsService(new InMemoryStorage<>(),
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metrics, null, null);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("Namespace", "MetricFilters");
params.putSingle("MetricName", "Count");
params.putSingle("Period", "60");
params.putSingle("StartTime", "2026-09-16T00:00:00Z");
params.putSingle("EndTime", "2026-09-16T00:01:00Z");
try (Response response = handler.handle(action, params, "us-east-1")) {
assertEquals(200, response.getStatus());
assertEquals(AwsNamespaces.CW, XmlParser.parseDocument((String) response.getEntity())
.getDocumentElement().getNamespaceURI());
}
}
}
@@ -0,0 +1,102 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.HybridStorage;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.WalStorage;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.*;
/** Injects failures around real backend writes, not mock invocation counts. */
class CloudWatchMetricPublicationStorageFaultTest {
private static final String ACCOUNT = "111111111111";
private static final String REGION = "eu-west-1";
private static final TypeReference<Map<String, MetricDatum>> TYPE = new TypeReference<>() {};
@TempDir Path directory;
@ParameterizedTest
@CsvSource({"memory,false", "memory,true", "persistent,false", "persistent,true",
"hybrid,false", "hybrid,true", "wal,false", "wal,true"})
void beforeAndAfterPartialCommitRemainSingleSamplesInEveryBackend(String mode, boolean after) {
StorageBackend<String, MetricDatum> actual = backend(mode);
AtomicBoolean armed = new AtomicBoolean(true);
AccountAwareStorageBackend<MetricDatum> faulting = new AccountAwareStorageBackend<>(actual, null, ACCOUNT) {
@Override
public void putForAccount(String account, String key, MetricDatum value) {
boolean fail = value.getValue() == 7 && armed.compareAndSet(true, false);
if (fail && !after) { throw new IllegalStateException("before actual backend write"); }
super.putForAccount(account, key, value);
if (fail) { throw new IllegalStateException("after actual backend write"); }
}
};
try {
actual.load();
CloudWatchMetricsService metrics = metrics(faulting);
assertThrows(IllegalStateException.class, () -> batch(metrics));
assertEquals(after ? 2 : 1, actual.keys().size(), "the fault surrounds the second actual write");
batch(metrics);
batch(metrics);
statistics(metrics);
assertEquals(3, actual.keys().size());
actual.flush();
} finally { close(actual); }
if (!mode.equals("memory")) {
StorageBackend<String, MetricDatum> reloaded = backend(mode);
try {
reloaded.load();
statistics(metrics(new AccountAwareStorageBackend<>(reloaded, null, ACCOUNT)));
assertEquals(3, reloaded.keys().size());
} finally { close(reloaded); }
}
}
private StorageBackend<String, MetricDatum> backend(String mode) {
return switch (mode) {
case "memory" -> new InMemoryStorage<>();
case "persistent" -> new PersistentStorage<>(directory.resolve("metrics.json"), TYPE);
case "hybrid" -> new HybridStorage<>(directory.resolve("metrics.json"), TYPE, 3_600_000);
case "wal" -> new WalStorage<>(directory.resolve("metrics-snapshot.json"), directory.resolve("metrics.wal"), TYPE, 3_600_000);
default -> throw new IllegalArgumentException(mode);
};
}
private static void close(StorageBackend<String, MetricDatum> backend) {
if (backend instanceof HybridStorage<?, ?> hybrid) { hybrid.shutdown(); }
if (backend instanceof WalStorage<?, ?> wal) { wal.shutdown(); }
}
private static CloudWatchMetricsService metrics(AccountAwareStorageBackend<MetricDatum> store) {
return new CloudWatchMetricsService(store, new InMemoryStorage<>(), new RegionResolver(REGION, ACCOUNT));
}
private static void batch(CloudWatchMetricsService metrics) {
double[] values = {3, 7, 3};
for (int i = 0; i < values.length; i++) {
MetricDatum datum = new MetricDatum();
datum.setMetricName("Value"); datum.setValue(values[i]); datum.setTimestamp(120); datum.setUnit("Count");
metrics.publishMetricForAccount(ACCOUNT, "App", datum, REGION, "stable-" + i);
}
}
private static void statistics(CloudWatchMetricsService metrics) {
List<CloudWatchMetricsService.Datapoint> points = metrics.getMetricStatistics("App", "Value", List.of(),
Instant.ofEpochSecond(120), Instant.ofEpochSecond(179), 60, List.of("Sum", "SampleCount"), null, REGION);
assertEquals(1, points.size());
assertEquals(13, points.getFirst().sum());
assertEquals(3, points.getFirst().sampleCount());
}
}
@@ -0,0 +1,93 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.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.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.*;
class CloudWatchMetricPublicationTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void partialStorageFailureBeforeOrAfterWriteIsIdempotentWithStableIds(boolean after) {
AtomicBoolean armed = new AtomicBoolean(true);
List<String> secondKeys = new ArrayList<>();
InMemoryStorage<String, MetricDatum> store = new InMemoryStorage<>() {
@Override
public void put(String key, MetricDatum value) {
if (value.getValue() == 7) { secondKeys.add(key); }
boolean fail = value.getValue() == 7 && armed.compareAndSet(true, false);
if (fail && !after) { throw new IllegalStateException("before store.put"); }
super.put(key, value);
if (fail) { throw new IllegalStateException("after store.put"); }
}
};
CloudWatchMetricsService service = service(store);
assertThrows(IllegalStateException.class, () -> publishBatch(service));
publishBatch(service);
publishBatch(service);
List<CloudWatchMetricsService.Datapoint> points = service.getMetricStatistics("App", "Value", List.of(),
Instant.ofEpochSecond(120), Instant.ofEpochSecond(179), 60, List.of("Sum", "SampleCount"), null, "eu-west-1");
assertEquals(1, points.size());
assertEquals(13, points.getFirst().sum());
assertEquals(3, points.getFirst().sampleCount());
assertEquals(1, secondKeys.stream().distinct().count(), "ambiguous writes must reuse the exact storage key");
}
private static void publishBatch(CloudWatchMetricsService service) {
double[] values = {3, 7, 3};
for (int i = 0; i < values.length; i++) {
service.publishMetricForAccount("111111111111", "App", datum(values[i], 120), "eu-west-1", "batch-" + i);
}
}
@Test
void ordinaryPutMetricDataStillAppendsIdenticalInputsAndSuppliesMissingTime() {
CloudWatchMetricsService service = service(new InMemoryStorage<>());
service.putMetricDataForAccount("111111111111", "App", List.of(datum(7, 120)), "eu-west-1");
service.putMetricDataForAccount("111111111111", "App", List.of(datum(7, 120)), "eu-west-1");
List<CloudWatchMetricsService.Datapoint> points = service.getMetricStatistics("App", "Value", List.of(),
Instant.ofEpochSecond(120), Instant.ofEpochSecond(179), 60, List.of("Sum"), null, "eu-west-1");
assertEquals(14, points.getFirst().sum());
assertEquals(2, points.getFirst().sampleCount());
MetricDatum missingTime = datum(1, 0);
service.putMetricData("App", List.of(missingTime), "eu-west-1");
assertTrue(missingTime.getTimestamp() > 0);
}
@Test
void internalPublicationPreservesExplicitEpochZeroAndDoesNotMutateCallerDatum() {
CloudWatchMetricsService service = service(new InMemoryStorage<>());
MetricDatum input = datum(7, 0);
input.setDimensions(new ArrayList<>(List.of(new Dimension("A", "a"))));
service.publishMetricForAccount("111111111111", "App", input, "eu-west-1", "epoch");
assertEquals(0, input.getTimestamp());
assertNull(input.getNamespace());
input.getDimensions().clear();
List<CloudWatchMetricsService.Datapoint> points = service.getMetricStatistics("App", "Value",
List.of(new Dimension("A", "a")), Instant.EPOCH, Instant.ofEpochSecond(59), 60, List.of("Sum"), null, "eu-west-1");
assertEquals(1, points.size());
assertEquals(7, points.getFirst().sum());
}
private static MetricDatum datum(double value, long timestamp) {
MetricDatum d = new MetricDatum();
d.setMetricName("Value"); d.setValue(value); d.setTimestamp(timestamp); d.setUnit("Count");
return d;
}
private static CloudWatchMetricsService service(InMemoryStorage<String, MetricDatum> store) {
return new CloudWatchMetricsService(new AccountAwareStorageBackend<>(store, null, "111111111111"),
new InMemoryStorage<>(), new RegionResolver("eu-west-1", "111111111111"));
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudwatch.metrics;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
@@ -253,4 +254,20 @@ class CloudWatchMetricsServiceTest {
assertEquals("", CloudWatchMetricsService.buildDimKey(List.of()));
assertEquals("", CloudWatchMetricsService.buildDimKey(null));
}
/** A writer outside any request can store datums in the account it acts for, not the default one. */
@Test
void putMetricDataForAccountStoresInThatAccountsPartition() {
AccountAwareStorageBackend<MetricDatum> store = AccountAwareStorageBackend.inMemory("000000000000");
CloudWatchMetricsService accountAware = new CloudWatchMetricsService(store, new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"));
accountAware.putMetricDataForAccount("111111111111", NAMESPACE, List.of(datum("Requests", 1)), REGION);
accountAware.putMetricData(NAMESPACE, List.of(datum("Requests", 2)), REGION);
assertEquals(1, store.scanForAccount("111111111111", k -> true).size());
assertEquals(1.0, store.scanForAccount("111111111111", k -> true).getFirst().getValue());
assertEquals(1, store.scan(k -> true).size(), "the default partition holds only the ambient put");
assertEquals(2.0, store.scan(k -> true).getFirst().getValue());
}
}