mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
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:
1 parent
a3da2a3767
commit
22b0627245
88 files changed
+19188
-101
No files matched your search
@@ -1,9 +1,17 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
/**
|
||||
* Interface for services or components that hold in-memory state
|
||||
* and need to be cleared when the emulator state is reset or nuked.
|
||||
* Services with runtime state cleared by emulator reset/nuke. Storage is wiped before clear(),
|
||||
* allowing clear() to recreate bootstrap data. Background publishers may additionally quiesce
|
||||
* before the wipe and resume afterwards. Hooks must release their locks before returning: the
|
||||
* controller never holds StorageFactory's monitor while invoking them.
|
||||
*/
|
||||
public interface Resettable {
|
||||
/** Stop accepting work and drain active writes before any storage is cleared. */
|
||||
default void beforeReset() {}
|
||||
|
||||
void clear();
|
||||
|
||||
/** Resume after reset, including when a storage/clear operation failed. */
|
||||
default void afterReset() {}
|
||||
}
|
||||
@@ -23,7 +23,9 @@ import jakarta.ws.rs.POST;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -153,17 +155,47 @@ public class EmulatorInfoController {
|
||||
return reset();
|
||||
}
|
||||
|
||||
private void performReset() {
|
||||
private synchronized void performReset() {
|
||||
// Containers first: they are tracked independently of StorageBackend, so this can run
|
||||
// in any order relative to the storage wipe below, but stopping them here means a
|
||||
// client's reset actually reflects a clean slate instead of leaving Batch, CodeBuild,
|
||||
// or SageMaker containers running with no record of them left in the store.
|
||||
ContainerTeardowns.stopAll(containerTeardowns, LOG);
|
||||
// Storage before resettables: services re-create their bootstrap state in clear(), and
|
||||
// a wipe afterwards would remove it again until the next restart.
|
||||
storageFactory.clearAll();
|
||||
for (Resettable r : resettables) {
|
||||
r.clear();
|
||||
// Resolve live instances before taking any storage locks. Serialize resets so one reset
|
||||
// cannot resume a publisher while another is still wiping its storage.
|
||||
List<Resettable> services = new ArrayList<>();
|
||||
for (Resettable service : resettables) {
|
||||
services.add(service);
|
||||
}
|
||||
List<Resettable> prepared = new ArrayList<>();
|
||||
RuntimeException failure = null;
|
||||
try {
|
||||
for (Resettable service : services) {
|
||||
prepared.add(service);
|
||||
service.beforeReset();
|
||||
}
|
||||
// Storage still precedes clear(): services recreate their bootstrap state there.
|
||||
storageFactory.clearAll();
|
||||
for (Resettable service : services) {
|
||||
service.clear();
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
failure = e;
|
||||
} finally {
|
||||
for (Resettable service : prepared.reversed()) {
|
||||
try {
|
||||
service.afterReset();
|
||||
} catch (RuntimeException e) {
|
||||
if (failure == null) {
|
||||
failure = e;
|
||||
} else {
|
||||
failure.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+31
-2
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ReplacementCleanup;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
|
||||
@@ -52,6 +53,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
@@ -221,6 +223,14 @@ public class CloudFormationResourceProvisioner {
|
||||
CloudFormationTemplateEngine engine, String region, String accountId,
|
||||
String stackName, String existingPhysicalId,
|
||||
Map<String, String> existingAttributes) {
|
||||
return provision(logicalId, resourceType, properties, engine, region, accountId, stackName,
|
||||
existingPhysicalId, existingAttributes, event -> {});
|
||||
}
|
||||
|
||||
public StackResource provision(String logicalId, String resourceType, JsonNode properties,
|
||||
CloudFormationTemplateEngine engine, String region, String accountId,
|
||||
String stackName, String existingPhysicalId,
|
||||
Map<String, String> existingAttributes, Consumer<StackEvent> progress) {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId(logicalId);
|
||||
resource.setResourceType(resourceType);
|
||||
@@ -231,7 +241,7 @@ public class CloudFormationResourceProvisioner {
|
||||
CfnResourceProvisioner extracted = resourceRegistry.forType(resourceType).orElse(null);
|
||||
if (extracted != null) {
|
||||
extracted.provision(resource, properties,
|
||||
new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId));
|
||||
new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress));
|
||||
resource.setStatus("CREATE_COMPLETE");
|
||||
return resource;
|
||||
}
|
||||
@@ -1924,6 +1934,21 @@ public class CloudFormationResourceProvisioner {
|
||||
.map(owner -> owner.updateCleanupPhysicalId(resource))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/** Only an opted-in provisioner may identify cleanup owed by an UPDATE_FAILED resource. */
|
||||
boolean hasPendingRollbackCleanup(StackResource resource) {
|
||||
return resourceRegistry.forType(resource.getResourceType())
|
||||
.map(owner -> owner.hasPendingRollbackCleanup(resource))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
/** Only an opted-in provisioner may keep a failed update attempt in place of the previous resource. */
|
||||
boolean retainsFailedUpdateState(StackResource resource) {
|
||||
return resourceRegistry.forType(resource.getResourceType())
|
||||
.map(owner -> owner.retainsFailedUpdateState(resource))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this update replaced the resource's physical entity, so the stack has cleanup
|
||||
* pending.
|
||||
@@ -1944,8 +1969,12 @@ public class CloudFormationResourceProvisioner {
|
||||
* the stack update, delegated to the provisioner that owns the type.
|
||||
*/
|
||||
boolean rollbackUpdate(StackResource resource) {
|
||||
return rollbackUpdate(resource, event -> {});
|
||||
}
|
||||
|
||||
boolean rollbackUpdate(StackResource resource, Consumer<StackEvent> progress) {
|
||||
return resourceRegistry.forType(resource.getResourceType())
|
||||
.map(owner -> owner.rollbackUpdate(resource))
|
||||
.map(owner -> owner.rollbackUpdate(resource, progress))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
|
||||
+15
-5
@@ -1210,7 +1210,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
} else {
|
||||
resource = provisioner.provision(logicalId, type, props.isMissingNode() ? null : props,
|
||||
engine, region, accountId, stack.getStackName(),
|
||||
resource.getPhysicalId(), resource.getAttributes());
|
||||
resource.getPhysicalId(), resource.getAttributes(),
|
||||
event -> addEvent(stack, logicalId, event.getPhysicalResourceId(), type,
|
||||
event.getResourceStatus(), event.getResourceStatusReason()));
|
||||
}
|
||||
resource.setUpdateReplacePolicy(
|
||||
resDef.path("UpdateReplacePolicy").asText(null));
|
||||
@@ -1235,7 +1237,10 @@ public class CloudFormationService implements ResourceProvider {
|
||||
if ("CREATE_FAILED".equals(resource.getStatus())
|
||||
|| "UPDATE_FAILED".equals(resource.getStatus())) {
|
||||
failedResource = resource;
|
||||
if (!isCreate && previousResource != null) {
|
||||
// A provisioner that keeps the failed attempt's identity and tracking for
|
||||
// its own rollback is not restored here; the rollback walker owns it.
|
||||
if (!isCreate && previousResource != null
|
||||
&& !provisioner.retainsFailedUpdateState(resource)) {
|
||||
// Provisioners work on a copy of the stored resource metadata. Keep the
|
||||
// last known-good identity and status when an update attempt fails so a
|
||||
// later retry or stack deletion still manages the original resource.
|
||||
@@ -1657,7 +1662,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
resource.getResourceType(), "UPDATE_FAILED", reason);
|
||||
} else if ("true".equals(resource.getAttributes().remove(
|
||||
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR))
|
||||
|| provisioner.rollbackUpdate(resource)) {
|
||||
|| provisioner.rollbackUpdate(resource,
|
||||
event -> addEvent(stack, resource.getLogicalId(), event.getPhysicalResourceId(),
|
||||
resource.getResourceType(), event.getResourceStatus(), event.getResourceStatusReason()))) {
|
||||
resource.setStatus(previous.getStatus());
|
||||
resource.setStatusReason(previous.getStatusReason());
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
@@ -1932,10 +1939,13 @@ public class CloudFormationService implements ResourceProvider {
|
||||
for (StackResource resource : resources) {
|
||||
// CREATE_COMPLETE/UPDATE_COMPLETE: first delete attempt. DELETE_FAILED: a previous
|
||||
// delete left the resource behind (e.g. the bucket was non-empty); AWS re-attempts
|
||||
// it on retry.
|
||||
// it on retry. Failed updates are included only when their provisioner still
|
||||
// tracks an ownership-aware cleanup obligation.
|
||||
boolean deletable = "CREATE_COMPLETE".equals(resource.getStatus())
|
||||
|| "UPDATE_COMPLETE".equals(resource.getStatus())
|
||||
|| "DELETE_FAILED".equals(resource.getStatus());
|
||||
|| "DELETE_FAILED".equals(resource.getStatus())
|
||||
|| ("UPDATE_FAILED".equals(resource.getStatus())
|
||||
&& provisioner.hasPendingRollbackCleanup(resource));
|
||||
if (resource.getPhysicalId() == null || !deletable) {
|
||||
continue;
|
||||
}
|
||||
|
||||
+22
@@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Provisions and deletes the CloudFormation resource types for a single service, replacing one
|
||||
@@ -45,6 +47,26 @@ public interface CfnResourceProvisioner {
|
||||
return false;
|
||||
}
|
||||
|
||||
default boolean rollbackUpdate(StackResource resource, Consumer<StackEvent> progress) {
|
||||
return rollbackUpdate(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a failed update still needs this provisioner's ownership-aware delete. Opt-in:
|
||||
* a failed resource is not otherwise assumed to own a backing entity.
|
||||
*/
|
||||
default boolean hasPendingRollbackCleanup(StackResource resource) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when this provisioner keeps the failed update attempt's own identity and tracking for
|
||||
* its {@code rollbackUpdate}, so the engine must not restore the previous resource over it.
|
||||
*/
|
||||
default boolean retainsFailedUpdateState(StackResource resource) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The physical id of the entity this update's replacement displaced, or null when this type
|
||||
* owes no replacement cleanup. {@code CloudFormationService} announces it as DELETE_IN_PROGRESS
|
||||
|
||||
+8
@@ -81,6 +81,14 @@ public final class CfnRollback {
|
||||
*/
|
||||
public static final String DASHBOARD_UPDATE_SNAPSHOT_ATTR = "__FlociDashboardUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the complete prior metric filter, identity, name mode and per-address mutation outcomes
|
||||
* and ownership states.
|
||||
* Written before either an in-place put or a delete-then-create replacement; retained across
|
||||
* failed restoration attempts and spent only after rollback or commit succeeds.
|
||||
*/
|
||||
public static final String METRIC_FILTER_UPDATE_SNAPSHOT_ATTR = "__FlociMetricFilterUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the pipe a rename displaced: the name it still lives under, the region that addresses
|
||||
* it, how many times deleting it has been attempted, and when the replacement was created.
|
||||
|
||||
+570
@@ -0,0 +1,570 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
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.services.cloudwatch.logs.model.MetricTransformation;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext.report;
|
||||
|
||||
/**
|
||||
* Metric-filter Ref and physical id are the name alone. Group identity is private metadata.
|
||||
* AWS replaces this type by deleting first, including with UpdateReplacePolicy Retain.
|
||||
* The complete prior definition survives until commit or successful rollback.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LogsMetricFilterCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final String TYPE = "AWS::Logs::MetricFilter";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String GROUP_ATTR = "__FlociMetricFilterLogGroupName";
|
||||
private static final String NAME_MODE_ATTR = "__FlociMetricFilterNameMode";
|
||||
private static final String SNAPSHOT = CfnRollback.METRIC_FILTER_UPDATE_SNAPSHOT_ATTR;
|
||||
private static final String UNCERTAIN_ATTR = "__FlociMetricFilterOwnershipUncertain";
|
||||
private static final String ABSENT_ATTR = "__FlociMetricFilterBackingAbsent";
|
||||
private static final String STATE_ATTR = "__FlociMetricFilterState";
|
||||
private static final String REPLACEMENT_REASON = "Requested update requires the replacement of the existing resource; "
|
||||
+ "deleting existing resource, then creating a new one.";
|
||||
private static final Set<String> UNITS = Set.of("Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes",
|
||||
"Megabytes", "Gigabytes", "Terabytes", "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Percent",
|
||||
"Count", "Bytes/Second", "Kilobytes/Second", "Megabytes/Second", "Gigabytes/Second", "Terabytes/Second",
|
||||
"Bits/Second", "Kilobits/Second", "Megabits/Second", "Gigabits/Second", "Terabits/Second", "Count/Second", "None");
|
||||
private final CloudWatchLogsMetricFilterService metricFilters;
|
||||
|
||||
private enum Ownership { OWNED, UNOWNED, UNKNOWN }
|
||||
private enum Operation { CREATE, UPDATE, DELETE, OBSERVE }
|
||||
|
||||
@Inject
|
||||
public LogsMetricFilterCfnProvisioner(CloudWatchLogsMetricFilterService metricFilters) {
|
||||
this.metricFilters = metricFilters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
JsonNode resolved = pruneNoValue(ctx.engine().resolveNode(markNoValue(props)));
|
||||
MetricFilter definition = definition(resolved);
|
||||
String explicitName = string(resolved, "FilterName", false, 1, 512, "[^:*]+");
|
||||
Identity prior = ctx.isUpdate() ? identity(r, ctx.priorPhysicalId()) : null;
|
||||
String name = explicitName != null ? explicitName
|
||||
: prior != null && !"explicit".equals(r.getAttributes().get(NAME_MODE_ATTR))
|
||||
? prior.name() : ctx.generatePhysicalName(r.getLogicalId(), 512, false);
|
||||
definition.setFilterName(name);
|
||||
Identity target = new Identity(definition.getLogGroupName(), name);
|
||||
ObjectNode snapshot = prior == null ? null : snapshot(r, prior, target, ctx.region());
|
||||
boolean replacement = snapshot != null && snapshot.path("replacement").asBoolean();
|
||||
ObjectNode state = snapshot == null ? state(target, Ownership.UNOWNED) : targetState(snapshot);
|
||||
if (replacement) {
|
||||
report(ctx.progress(), prior.name(), "DELETE_IN_PROGRESS", REPLACEMENT_REASON);
|
||||
try {
|
||||
mutate(r, priorState(snapshot), snapshot, Operation.DELETE, null, ctx.region());
|
||||
} catch (RuntimeException e) {
|
||||
report(ctx.progress(), prior.name(), "DELETE_FAILED", e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
report(ctx.progress(), prior.name(), "DELETE_COMPLETE", null);
|
||||
setIdentity(r, target, explicitName != null);
|
||||
report(ctx.progress(), target.name(), "CREATE_IN_PROGRESS", null);
|
||||
}
|
||||
if (snapshot == null) {
|
||||
r.getAttributes().put(GROUP_ATTR, target.group());
|
||||
r.getAttributes().put(NAME_MODE_ATTR, explicitName != null ? "explicit" : "generated");
|
||||
}
|
||||
try {
|
||||
mutate(r, state, snapshot, prior == null || replacement ? Operation.CREATE : Operation.UPDATE,
|
||||
definition, ctx.region());
|
||||
} catch (RuntimeException e) {
|
||||
if (replacement) {
|
||||
report(ctx.progress(), target.name(), "CREATE_FAILED", e.getMessage());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
setIdentity(r, target, explicitName != null);
|
||||
if (replacement) {
|
||||
report(ctx.progress(), target.name(), "CREATE_COMPLETE", null);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setIdentity(StackResource r, Identity identity, boolean explicit) {
|
||||
r.setPhysicalId(identity.name());
|
||||
r.getAttributes().put(GROUP_ATTR, identity.group());
|
||||
r.getAttributes().put(NAME_MODE_ATTR, explicit ? "explicit" : "generated");
|
||||
}
|
||||
|
||||
private record Identity(String group, String name) {}
|
||||
|
||||
private static Identity identity(StackResource r, String physicalId) {
|
||||
String group = r.getAttributes().get(GROUP_ATTR);
|
||||
if (group == null) {
|
||||
throw new IllegalStateException("Missing metric filter group identity for " + r.getLogicalId());
|
||||
}
|
||||
return new Identity(group, physicalId);
|
||||
}
|
||||
|
||||
private ObjectNode snapshot(StackResource r, Identity prior, Identity target, String region) {
|
||||
if (r.getAttributes().containsKey(SNAPSHOT)) {
|
||||
throw new IllegalStateException("Metric filter update still needs rollback or commit: " + r.getLogicalId());
|
||||
}
|
||||
ObjectNode priorState = currentState(r, prior);
|
||||
resolveUnknown(r, priorState, null, region);
|
||||
ObjectNode snapshot = MAPPER.createObjectNode();
|
||||
snapshot.put("region", region);
|
||||
snapshot.put("replacement", !prior.equals(target));
|
||||
snapshot.set("attributes", MAPPER.valueToTree(r.getAttributes()));
|
||||
if (ownership(priorState) == Ownership.UNOWNED) {
|
||||
snapshot.put("absent", true);
|
||||
} else {
|
||||
metricFilters.findMetricFilter(prior.group(), prior.name(), region).ifPresentOrElse(
|
||||
filter -> snapshot.set("definition", MAPPER.valueToTree(filter)),
|
||||
() -> {
|
||||
snapshot.put("absent", true);
|
||||
priorState.put("ownership", Ownership.UNOWNED.name());
|
||||
});
|
||||
}
|
||||
snapshot.set("prior", priorState);
|
||||
if (!prior.equals(target)) {
|
||||
snapshot.set("target", state(target, Ownership.UNOWNED));
|
||||
}
|
||||
save(r, snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static void save(StackResource r, ObjectNode snapshot) {
|
||||
r.getAttributes().put(SNAPSHOT, snapshot.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(StackResource resource, String region) {
|
||||
String raw = resource.getAttributes().get(SNAPSHOT);
|
||||
if (raw != null) {
|
||||
ObjectNode snapshot = object(raw);
|
||||
if (snapshot.path("replacement").asBoolean()) {
|
||||
mutate(resource, targetState(snapshot), snapshot, Operation.DELETE, null, region);
|
||||
}
|
||||
mutate(resource, priorState(snapshot), snapshot, Operation.DELETE, null, region);
|
||||
} else if (resource.getPhysicalId() != null) {
|
||||
mutate(resource, currentState(resource, identity(resource, resource.getPhysicalId())),
|
||||
null, Operation.DELETE, null, region);
|
||||
}
|
||||
}
|
||||
|
||||
private static ObjectNode state(Identity identity, Ownership ownership) {
|
||||
ObjectNode state = MAPPER.createObjectNode();
|
||||
state.put("group", identity.group());
|
||||
state.put("name", identity.name());
|
||||
state.put("ownership", ownership.name());
|
||||
state.put("operation", Operation.OBSERVE.name());
|
||||
state.put("outcome", ownership == Ownership.UNKNOWN
|
||||
? MutationOutcome.UNKNOWN.name() : MutationOutcome.NOT_APPLIED.name());
|
||||
return state;
|
||||
}
|
||||
|
||||
private ObjectNode currentState(StackResource resource, Identity identity) {
|
||||
String raw = resource.getAttributes().get(STATE_ATTR);
|
||||
if (raw != null) {
|
||||
ObjectNode state = object(raw);
|
||||
if (!identity.equals(address(state))) {
|
||||
throw new IllegalStateException("Metric filter state does not match its physical identity");
|
||||
}
|
||||
return state;
|
||||
}
|
||||
if ("true".equals(resource.getAttributes().get(UNCERTAIN_ATTR))) {
|
||||
return state(identity, Ownership.UNKNOWN);
|
||||
}
|
||||
if ("true".equals(resource.getAttributes().get(ABSENT_ATTR))) {
|
||||
return state(identity, Ownership.UNOWNED);
|
||||
}
|
||||
boolean completed = "CREATE_COMPLETE".equals(resource.getStatus()) || "UPDATE_COMPLETE".equals(resource.getStatus());
|
||||
return state(identity, completed ? Ownership.OWNED : Ownership.UNKNOWN);
|
||||
}
|
||||
|
||||
private static Ownership ownership(ObjectNode state) {
|
||||
return Ownership.valueOf(state.path("ownership").asText());
|
||||
}
|
||||
|
||||
private static Identity address(ObjectNode state) {
|
||||
return new Identity(state.path("group").asText(), state.path("name").asText());
|
||||
}
|
||||
|
||||
private static ObjectNode priorState(ObjectNode snapshot) {
|
||||
return (ObjectNode) snapshot.get("prior");
|
||||
}
|
||||
|
||||
private static ObjectNode targetState(ObjectNode snapshot) {
|
||||
return snapshot.path("replacement").asBoolean() ? (ObjectNode) snapshot.get("target") : priorState(snapshot);
|
||||
}
|
||||
|
||||
private static ObjectNode object(String raw) {
|
||||
try {
|
||||
if (MAPPER.readTree(raw) instanceof ObjectNode object) {
|
||||
return object;
|
||||
}
|
||||
throw new IllegalStateException("Metric filter mutation metadata must be an object");
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Invalid metric filter mutation metadata", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveTracking(StackResource resource, ObjectNode state, ObjectNode snapshot) {
|
||||
if (snapshot == null) {
|
||||
resource.getAttributes().put(STATE_ATTR, state.toString());
|
||||
} else {
|
||||
save(resource, snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
private void resolveUnknown(StackResource resource, ObjectNode state, ObjectNode snapshot, String region) {
|
||||
if (ownership(state) != Ownership.UNKNOWN) {
|
||||
return;
|
||||
}
|
||||
saveTracking(resource, state, snapshot);
|
||||
Identity identity = address(state);
|
||||
if (!metricFilters.confirmMetricFilterAbsent(identity.group(), identity.name(), region, () -> {
|
||||
state.put("ownership", Ownership.UNOWNED.name());
|
||||
state.put("operation", Operation.OBSERVE.name());
|
||||
state.put("outcome", MutationOutcome.NOT_APPLIED.name());
|
||||
saveTracking(resource, state, snapshot);
|
||||
})) {
|
||||
throw new IllegalStateException("Metric filter write outcome is uncertain for "
|
||||
+ identity.group() + "/" + identity.name()
|
||||
+ "; refusing to delete or adopt a filter without confirmed ownership");
|
||||
}
|
||||
}
|
||||
|
||||
private void mutate(StackResource resource, ObjectNode state, ObjectNode snapshot, Operation requested,
|
||||
MetricFilter definition, String region) {
|
||||
resolveUnknown(resource, state, snapshot, region);
|
||||
Ownership before = ownership(state);
|
||||
if (requested == Operation.DELETE && before == Ownership.UNOWNED) {
|
||||
return;
|
||||
}
|
||||
Operation operation = requested == Operation.UPDATE && before == Ownership.UNOWNED ? Operation.CREATE : requested;
|
||||
Identity identity = address(state);
|
||||
boolean firstCreate = snapshot == null && operation == Operation.CREATE && resource.getPhysicalId() == null;
|
||||
state.put("ownership", Ownership.UNKNOWN.name());
|
||||
state.put("operation", operation.name());
|
||||
state.put("outcome", MutationOutcome.UNKNOWN.name());
|
||||
saveTracking(resource, state, snapshot);
|
||||
if (firstCreate) {
|
||||
resource.setPhysicalId(identity.name());
|
||||
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
}
|
||||
Consumer<MutationResult> outcome = result -> {
|
||||
Ownership after;
|
||||
if (result.outcome() == MutationOutcome.UNKNOWN) {
|
||||
after = Ownership.UNKNOWN;
|
||||
} else if (operation == Operation.CREATE) {
|
||||
after = result.outcome() == MutationOutcome.APPLIED ? Ownership.OWNED : Ownership.UNOWNED;
|
||||
} else {
|
||||
after = result.present() == null ? before : result.present() ? Ownership.OWNED : Ownership.UNOWNED;
|
||||
}
|
||||
state.put("ownership", after.name());
|
||||
state.put("outcome", result.outcome().name());
|
||||
saveTracking(resource, state, snapshot);
|
||||
if (snapshot == null) {
|
||||
if (firstCreate && after == Ownership.UNOWNED) {
|
||||
resource.setPhysicalId(null);
|
||||
resource.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
|
||||
}
|
||||
finishState(resource, state);
|
||||
}
|
||||
};
|
||||
switch (operation) {
|
||||
case CREATE -> metricFilters.createMetricFilter(definition, region, outcome);
|
||||
case UPDATE -> metricFilters.updateMetricFilter(definition, region, outcome);
|
||||
case DELETE -> metricFilters.deleteMetricFilter(identity.group(), identity.name(), region, outcome);
|
||||
case OBSERVE -> throw new IllegalStateException("Observation is not a mutation");
|
||||
}
|
||||
}
|
||||
|
||||
private static void finishState(StackResource resource, ObjectNode state) {
|
||||
resource.getAttributes().put(STATE_ATTR, state.toString());
|
||||
resource.getAttributes().remove(UNCERTAIN_ATTR);
|
||||
if (ownership(state) == Ownership.OWNED) {
|
||||
resource.getAttributes().remove(ABSENT_ATTR);
|
||||
} else if (ownership(state) == Ownership.UNOWNED) {
|
||||
resource.getAttributes().put(ABSENT_ATTR, "true");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
String raw = resource.getAttributes().get(SNAPSHOT);
|
||||
if (raw == null) {
|
||||
return;
|
||||
}
|
||||
ObjectNode snapshot = object(raw);
|
||||
if (!canCommit(snapshot)) {
|
||||
throw new IllegalStateException("Cannot commit unconfirmed metric filter mutations");
|
||||
}
|
||||
finishState(resource, targetState(snapshot));
|
||||
resource.getAttributes().remove(SNAPSHOT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
// DeleteStack also invokes this hook, including after a failed rollback.
|
||||
String raw = resource.getAttributes().get(SNAPSHOT);
|
||||
if ("UPDATE_COMPLETE".equals(resource.getStatus()) && raw != null
|
||||
&& canCommit(object(raw))) {
|
||||
clearUpdate(resource);
|
||||
}
|
||||
return UpdateCleanupResult.notApplicable();
|
||||
}
|
||||
|
||||
private static boolean canCommit(ObjectNode snapshot) {
|
||||
return ownership(targetState(snapshot)) == Ownership.OWNED
|
||||
&& (!snapshot.path("replacement").asBoolean() || ownership(priorState(snapshot)) == Ownership.UNOWNED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPendingRollbackCleanup(StackResource resource) {
|
||||
return resource.getAttributes().containsKey(SNAPSHOT)
|
||||
|| resource.getAttributes().containsKey(STATE_ATTR)
|
||||
|| resource.getAttributes().containsKey(UNCERTAIN_ATTR)
|
||||
|| resource.getAttributes().containsKey(GROUP_ATTR)
|
||||
|| resource.getAttributes().containsKey(NAME_MODE_ATTR)
|
||||
|| "true".equals(resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainsFailedUpdateState(StackResource resource) {
|
||||
return resource.getAttributes().containsKey(SNAPSHOT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
return rollbackUpdate(resource, event -> {});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource, Consumer<StackEvent> progress) {
|
||||
String raw = resource.getAttributes().get(SNAPSHOT);
|
||||
if (raw == null) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
ObjectNode snapshot = object(raw);
|
||||
String region = snapshot.path("region").asText();
|
||||
boolean replacement = snapshot.path("replacement").asBoolean();
|
||||
ObjectNode priorState = priorState(snapshot);
|
||||
ObjectNode targetState = targetState(snapshot);
|
||||
Identity prior = address(priorState);
|
||||
Identity target = address(targetState);
|
||||
if (replacement) {
|
||||
report(progress, target.name(), "UPDATE_IN_PROGRESS", "Resource update rolled back");
|
||||
}
|
||||
if (replacement || snapshot.path("absent").asBoolean()) {
|
||||
resolveUnknown(resource, targetState, snapshot, region);
|
||||
boolean announceDelete = replacement && (ownership(targetState) == Ownership.OWNED
|
||||
|| metricFilters.findMetricFilter(target.group(), target.name(), region).isEmpty());
|
||||
if (announceDelete) {
|
||||
report(progress, target.name(), "DELETE_IN_PROGRESS", null);
|
||||
}
|
||||
mutate(resource, targetState, snapshot, Operation.DELETE, null, region);
|
||||
if (announceDelete) {
|
||||
report(progress, target.name(), "DELETE_COMPLETE", null);
|
||||
}
|
||||
}
|
||||
if (!snapshot.path("absent").asBoolean()) {
|
||||
if (replacement) {
|
||||
report(progress, target.name(), "CREATE_IN_PROGRESS", null);
|
||||
}
|
||||
MetricFilter definition = MAPPER.treeToValue(snapshot.get("definition"), MetricFilter.class);
|
||||
mutate(resource, priorState, snapshot, Operation.UPDATE, definition, region);
|
||||
if (replacement) {
|
||||
report(progress, prior.name(), "CREATE_COMPLETE", null);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> attributes = new HashMap<>();
|
||||
snapshot.path("attributes").fields().forEachRemaining(e -> attributes.put(e.getKey(), e.getValue().asText()));
|
||||
resource.setAttributes(attributes);
|
||||
resource.setPhysicalId(prior.name());
|
||||
resource.getAttributes().put(GROUP_ATTR, prior.group());
|
||||
finishState(resource, priorState);
|
||||
return true;
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Invalid metric filter rollback snapshot for " + resource.getLogicalId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve NoValue through intrinsic resolution without confusing it with a valid empty
|
||||
// FilterPattern. The shared engine otherwise renders both as an empty string.
|
||||
private static JsonNode markNoValue(JsonNode node) {
|
||||
if (node == null) {
|
||||
return null;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
if ("AWS::NoValue".equals(node.path("Ref").asText())) {
|
||||
return MissingNode.getInstance();
|
||||
}
|
||||
ObjectNode result = MAPPER.createObjectNode();
|
||||
node.fields().forEachRemaining(e -> result.set(e.getKey(), markNoValue(e.getValue())));
|
||||
return result;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
ArrayNode result = MAPPER.createArrayNode();
|
||||
node.forEach(item -> result.add(markNoValue(item)));
|
||||
return result;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private static JsonNode pruneNoValue(JsonNode node) {
|
||||
if (node != null && node.isObject()) {
|
||||
ObjectNode result = MAPPER.createObjectNode();
|
||||
node.fields().forEachRemaining(e -> {
|
||||
if (!e.getValue().isMissingNode()) {
|
||||
result.set(e.getKey(), pruneNoValue(e.getValue()));
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
if (node != null && node.isArray()) {
|
||||
ArrayNode result = MAPPER.createArrayNode();
|
||||
node.forEach(item -> {
|
||||
if (!item.isMissingNode()) {
|
||||
result.add(pruneNoValue(item));
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private static MetricFilter definition(JsonNode props) {
|
||||
if (props == null || !props.isObject()) {
|
||||
throw invalid("Properties must be an object");
|
||||
}
|
||||
onlyMembers(props, Set.of("LogGroupName", "FilterName", "FilterPattern", "MetricTransformations",
|
||||
"ApplyOnTransformedLogs", "FieldSelectionCriteria", "EmitSystemFieldDimensions"));
|
||||
MetricFilter filter = new MetricFilter();
|
||||
filter.setLogGroupName(string(props, "LogGroupName", true, 1, 512, "[.\\-_/#A-Za-z0-9]+"));
|
||||
filter.setFilterPattern(string(props, "FilterPattern", true, 0, 1024, null));
|
||||
JsonNode transformations = props.get("MetricTransformations");
|
||||
if (transformations == null || !transformations.isArray() || transformations.size() != 1
|
||||
|| !transformations.get(0).isObject()) {
|
||||
throw invalid("MetricTransformations must contain exactly one object");
|
||||
}
|
||||
filter.setMetricTransformations(List.of(transformation(transformations.get(0))));
|
||||
JsonNode transformed = props.get("ApplyOnTransformedLogs");
|
||||
if (transformed != null) {
|
||||
if (!transformed.isBoolean() && (!transformed.isTextual()
|
||||
|| !Set.of("true", "false").contains(transformed.asText()))) {
|
||||
throw invalid("ApplyOnTransformedLogs must be a boolean");
|
||||
}
|
||||
filter.setApplyOnTransformedLogs(Boolean.parseBoolean(transformed.asText()));
|
||||
}
|
||||
filter.setFieldSelectionCriteria(string(props, "FieldSelectionCriteria", false, 0, 2000, null));
|
||||
JsonNode fields = props.get("EmitSystemFieldDimensions");
|
||||
if (fields != null) {
|
||||
if (!fields.isArray()) {
|
||||
throw invalid("EmitSystemFieldDimensions must be an array");
|
||||
}
|
||||
List<String> values = new ArrayList<>();
|
||||
for (JsonNode field : fields) {
|
||||
if (!field.isTextual()) {
|
||||
throw invalid("EmitSystemFieldDimensions entries must be strings");
|
||||
}
|
||||
values.add(field.textValue());
|
||||
}
|
||||
filter.setEmitSystemFieldDimensions(values);
|
||||
}
|
||||
return filter;
|
||||
}
|
||||
|
||||
private static MetricTransformation transformation(JsonNode node) {
|
||||
onlyMembers(node, Set.of("MetricName", "MetricNamespace", "MetricValue", "DefaultValue", "Dimensions", "Unit"));
|
||||
MetricTransformation t = new MetricTransformation();
|
||||
t.setMetricName(string(node, "MetricName", true, 1, 255, "[\\x00-\\x7F&&[^:*$]]+"));
|
||||
t.setMetricNamespace(string(node, "MetricNamespace", true, 1, 256, "[0-9a-zA-Z.\\-_/#]+"));
|
||||
t.setMetricValue(string(node, "MetricValue", true, 1, 100, ".+"));
|
||||
JsonNode defaultValue = node.get("DefaultValue");
|
||||
if (defaultValue != null && !defaultValue.isNull()) {
|
||||
try {
|
||||
if ((!defaultValue.isNumber() && !defaultValue.isTextual())
|
||||
|| !defaultValue.asText().matches("[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?")) {
|
||||
throw invalid("DefaultValue must be a finite number");
|
||||
}
|
||||
double value = Double.parseDouble(defaultValue.asText());
|
||||
if (!Double.isFinite(value)) {
|
||||
throw invalid("DefaultValue must be a finite number");
|
||||
}
|
||||
t.setDefaultValue(value);
|
||||
} catch (NumberFormatException e) {
|
||||
throw invalid("DefaultValue must be a finite number");
|
||||
}
|
||||
}
|
||||
JsonNode dimensions = node.get("Dimensions");
|
||||
if (dimensions != null) {
|
||||
if (!dimensions.isArray() || dimensions.isEmpty() || dimensions.size() > 3) {
|
||||
throw invalid("Dimensions must be an array of one to three Key/Value objects");
|
||||
}
|
||||
Map<String, String> byKey = new LinkedHashMap<>();
|
||||
for (JsonNode dimension : dimensions) {
|
||||
onlyMembers(dimension, Set.of("Key", "Value"));
|
||||
String key = string(dimension, "Key", true, 1, 255, "[\\x00-\\x7F]+");
|
||||
String value = string(dimension, "Value", true, 1, 255, null);
|
||||
if (key.isBlank() || key.startsWith(":") || byKey.putIfAbsent(key, value) != null) {
|
||||
throw invalid("Dimensions need unique ASCII keys, nonblank and not starting with ':'");
|
||||
}
|
||||
}
|
||||
t.setDimensions(byKey);
|
||||
}
|
||||
t.setUnit(string(node, "Unit", false, 1, 64, null));
|
||||
if (t.getUnit() != null && !UNITS.contains(t.getUnit())) {
|
||||
throw invalid("Unit must be a CloudWatch metric unit");
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
private static void onlyMembers(JsonNode node, Set<String> members) {
|
||||
node.fieldNames().forEachRemaining(member -> {
|
||||
if (!members.contains(member)) {
|
||||
throw invalid("Unknown property " + member);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static String string(JsonNode node, String member, boolean required, int min, int max, String pattern) {
|
||||
JsonNode value = node == null ? null : node.get(member);
|
||||
if (value == null && !required) {
|
||||
return null;
|
||||
}
|
||||
if (value == null || !value.isTextual() || value.textValue().length() < min
|
||||
|| value.textValue().length() > max
|
||||
|| pattern != null && !value.textValue().matches(pattern)) {
|
||||
throw invalid(member + " must be a string of length " + min + " to " + max
|
||||
+ (pattern == null ? "" : " matching " + pattern));
|
||||
}
|
||||
return value.textValue();
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("ValidationError", TYPE + " " + message, 400);
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -2,12 +2,14 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* The per-provision context every resource handler drew from: the template engine (for resolving
|
||||
@@ -16,7 +18,22 @@ import java.util.UUID;
|
||||
* so extracted provisioners produce byte-identical physical ids and resolved values.
|
||||
*/
|
||||
public record ProvisionContext(CloudFormationTemplateEngine engine, String region,
|
||||
String accountId, String stackName, String priorPhysicalId) {
|
||||
String accountId, String stackName, String priorPhysicalId,
|
||||
Consumer<StackEvent> progress) {
|
||||
|
||||
public ProvisionContext(CloudFormationTemplateEngine engine, String region,
|
||||
String accountId, String stackName, String priorPhysicalId) {
|
||||
this(engine, region, accountId, stackName, priorPhysicalId, event -> {});
|
||||
}
|
||||
|
||||
/** Intermediate resource events retain the stack pipeline's event IDs and metadata. */
|
||||
public static void report(Consumer<StackEvent> progress, String physicalId, String status, String reason) {
|
||||
StackEvent event = new StackEvent();
|
||||
event.setPhysicalResourceId(physicalId);
|
||||
event.setResourceStatus(status);
|
||||
event.setResourceStatusReason(reason);
|
||||
progress.accept(event);
|
||||
}
|
||||
|
||||
/** A context for a first-time create, with no prior physical id. */
|
||||
public ProvisionContext(CloudFormationTemplateEngine engine, String region,
|
||||
|
||||
+6
-1
@@ -28,14 +28,17 @@ public class CloudWatchLogsHandler {
|
||||
|
||||
private final CloudWatchLogsService logsService;
|
||||
private final CloudWatchLogsCrossAccountService crossAccountService;
|
||||
private final CloudWatchLogsMetricFilterHandler metricFilterHandler;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public CloudWatchLogsHandler(CloudWatchLogsService logsService,
|
||||
CloudWatchLogsCrossAccountService crossAccountService,
|
||||
CloudWatchLogsMetricFilterService metricFilterService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.logsService = logsService;
|
||||
this.crossAccountService = crossAccountService;
|
||||
this.metricFilterHandler = new CloudWatchLogsMetricFilterHandler(metricFilterService, objectMapper);
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@@ -62,6 +65,8 @@ public class CloudWatchLogsHandler {
|
||||
case "PutSubscriptionFilter" -> handlePutSubscriptionFilter(request, region);
|
||||
case "DescribeSubscriptionFilters" -> handleDescribeSubscriptionFilters(request, region);
|
||||
case "DeleteSubscriptionFilter" -> handleDeleteSubscriptionFilter(request, region);
|
||||
case "PutMetricFilter", "DescribeMetricFilters", "DeleteMetricFilter", "TestMetricFilter" ->
|
||||
metricFilterHandler.handle(action, request, region);
|
||||
case "AssociateKmsKey" -> handleAssociateKmsKey(request, region);
|
||||
case "DisassociateKmsKey" -> handleDisassociateKmsKey(request, region);
|
||||
case "PutResourcePolicy" -> handlePutResourcePolicy(request, region);
|
||||
@@ -130,7 +135,7 @@ public class CloudWatchLogsHandler {
|
||||
node.put("kmsKeyId", g.getKmsKeyId());
|
||||
}
|
||||
node.put("storedBytes", 0);
|
||||
node.put("metricFilterCount", 0);
|
||||
node.put("metricFilterCount", metricFilterHandler.metricFilterCount(g.getLogGroupName(), region));
|
||||
groupsArray.add(node);
|
||||
}
|
||||
response.set("logGroups", groupsArray);
|
||||
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
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.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
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 jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The wire shapes of the metric filter operations, reached through {@link CloudWatchLogsHandler}:
|
||||
* request members in the JSON 1.1 form the Logs API takes, responses as the API reference lists
|
||||
* them.
|
||||
*/
|
||||
class CloudWatchLogsMetricFilterHandler {
|
||||
|
||||
private final CloudWatchLogsMetricFilterService metricFilters;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
CloudWatchLogsMetricFilterHandler(CloudWatchLogsMetricFilterService metricFilters, ObjectMapper objectMapper) {
|
||||
this.metricFilters = metricFilters;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
Response handle(String action, JsonNode request, String region) {
|
||||
requireObject(request, "request");
|
||||
return switch (action) {
|
||||
case "PutMetricFilter" -> putMetricFilter(request, region);
|
||||
case "DescribeMetricFilters" -> describeMetricFilters(request, region);
|
||||
case "DeleteMetricFilter" -> deleteMetricFilter(request, region);
|
||||
case "TestMetricFilter" -> testMetricFilter(request);
|
||||
default -> throw new IllegalStateException("not a metric filter action: " + action);
|
||||
};
|
||||
}
|
||||
|
||||
int metricFilterCount(String logGroupName, String region) {
|
||||
return metricFilters.countMetricFilters(logGroupName, region);
|
||||
}
|
||||
|
||||
private Response putMetricFilter(JsonNode request, String region) {
|
||||
MetricFilter definition = new MetricFilter();
|
||||
definition.setLogGroupName(text(request, "logGroupName"));
|
||||
definition.setFilterName(text(request, "filterName"));
|
||||
definition.setFilterPattern(text(request, "filterPattern"));
|
||||
List<MetricTransformation> transformations = new ArrayList<>();
|
||||
JsonNode transformationNodes = request.get("metricTransformations");
|
||||
requireArray(transformationNodes, "metricTransformations");
|
||||
transformationNodes.forEach(node -> transformations.add(transformation(node)));
|
||||
definition.setMetricTransformations(transformations);
|
||||
if (request.has("applyOnTransformedLogs")) {
|
||||
JsonNode flag = request.get("applyOnTransformedLogs");
|
||||
if (!flag.isBoolean()) {
|
||||
throw invalid("applyOnTransformedLogs must be a boolean.");
|
||||
}
|
||||
definition.setApplyOnTransformedLogs(flag.booleanValue());
|
||||
}
|
||||
definition.setFieldSelectionCriteria(text(request, "fieldSelectionCriteria"));
|
||||
if (request.has("emitSystemFieldDimensions")) {
|
||||
List<String> fields = new ArrayList<>();
|
||||
JsonNode fieldNodes = request.get("emitSystemFieldDimensions");
|
||||
requireArray(fieldNodes, "emitSystemFieldDimensions");
|
||||
fieldNodes.forEach(node -> fields.add(string(node, "emitSystemFieldDimensions member")));
|
||||
definition.setEmitSystemFieldDimensions(fields);
|
||||
}
|
||||
metricFilters.putMetricFilter(definition, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private static MetricTransformation transformation(JsonNode node) {
|
||||
requireObject(node, "metricTransformation");
|
||||
MetricTransformation t = new MetricTransformation();
|
||||
t.setMetricName(text(node, "metricName"));
|
||||
t.setMetricNamespace(text(node, "metricNamespace"));
|
||||
t.setMetricValue(text(node, "metricValue"));
|
||||
if (node.has("defaultValue")) {
|
||||
JsonNode defaultValue = node.get("defaultValue");
|
||||
if (defaultValue.isTextual()) {
|
||||
throw new AwsException("SerializationException", "STRING_VALUE cannot be converted to Double", 400);
|
||||
}
|
||||
if (!defaultValue.isNumber()) {
|
||||
throw invalid("defaultValue must be a number.");
|
||||
}
|
||||
double value = defaultValue.asDouble();
|
||||
if (!Double.isFinite(value)) {
|
||||
throw invalid("defaultValue must be finite.");
|
||||
}
|
||||
t.setDefaultValue(value);
|
||||
}
|
||||
if (node.has("dimensions")) {
|
||||
Map<String, String> dimensions = new LinkedHashMap<>();
|
||||
requireObject(node.get("dimensions"), "dimensions");
|
||||
node.get("dimensions").fields().forEachRemaining(entry ->
|
||||
dimensions.put(entry.getKey(), string(entry.getValue(), "dimension value")));
|
||||
t.setDimensions(dimensions);
|
||||
}
|
||||
t.setUnit(text(node, "unit"));
|
||||
return t;
|
||||
}
|
||||
|
||||
private Response describeMetricFilters(JsonNode request, String region) {
|
||||
CloudWatchLogsMetricFilterService.DescribeMetricFiltersResult result = metricFilters.describeMetricFilters(
|
||||
text(request, "logGroupName"), text(request, "filterNamePrefix"), text(request, "metricName"),
|
||||
text(request, "metricNamespace"), text(request, "nextToken"),
|
||||
limit(request), region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode filters = response.putArray("metricFilters");
|
||||
result.metricFilters().forEach(filter -> filters.add(render(filter)));
|
||||
if (result.nextToken() != null) {
|
||||
response.put("nextToken", result.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode render(MetricFilter filter) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("filterName", filter.getFilterName());
|
||||
node.put("filterPattern", filter.getFilterPattern());
|
||||
ArrayNode transformations = node.putArray("metricTransformations");
|
||||
for (MetricTransformation t : filter.getMetricTransformations()) {
|
||||
ObjectNode rendered = transformations.addObject();
|
||||
rendered.put("metricName", t.getMetricName());
|
||||
rendered.put("metricNamespace", t.getMetricNamespace());
|
||||
rendered.put("metricValue", t.getMetricValue());
|
||||
if (t.getDefaultValue() != null) {
|
||||
rendered.put("defaultValue", t.getDefaultValue());
|
||||
}
|
||||
if (t.getDimensions() != null && !t.getDimensions().isEmpty()) {
|
||||
ObjectNode dimensions = rendered.putObject("dimensions");
|
||||
t.getDimensions().forEach(dimensions::put);
|
||||
}
|
||||
if (t.getUnit() != null) {
|
||||
rendered.put("unit", t.getUnit());
|
||||
}
|
||||
}
|
||||
node.put("creationTime", filter.getCreationTime());
|
||||
node.put("logGroupName", filter.getLogGroupName());
|
||||
if (filter.getApplyOnTransformedLogs() != null) {
|
||||
node.put("applyOnTransformedLogs", filter.getApplyOnTransformedLogs());
|
||||
}
|
||||
if (filter.getFieldSelectionCriteria() != null) {
|
||||
node.put("fieldSelectionCriteria", filter.getFieldSelectionCriteria());
|
||||
}
|
||||
if (filter.getEmitSystemFieldDimensions() != null) {
|
||||
ArrayNode fields = node.putArray("emitSystemFieldDimensions");
|
||||
filter.getEmitSystemFieldDimensions().forEach(fields::add);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private Response deleteMetricFilter(JsonNode request, String region) {
|
||||
metricFilters.deleteMetricFilter(text(request, "logGroupName"), text(request, "filterName"), region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response testMetricFilter(JsonNode request) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
JsonNode messageNodes = request.get("logEventMessages");
|
||||
requireArray(messageNodes, "logEventMessages");
|
||||
messageNodes.forEach(node -> messages.add(string(node, "logEventMessages member")));
|
||||
List<CloudWatchLogsMetricFilterService.MetricFilterMatchRecord> matches = metricFilters.testMetricFilter(
|
||||
text(request, "filterPattern"), messages);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode rendered = response.putArray("matches");
|
||||
for (CloudWatchLogsMetricFilterService.MetricFilterMatchRecord match : matches) {
|
||||
ObjectNode node = rendered.addObject();
|
||||
node.put("eventNumber", match.eventNumber());
|
||||
node.put("eventMessage", match.eventMessage());
|
||||
ObjectNode extracted = node.putObject("extractedValues");
|
||||
match.extractedValues().forEach(extracted::put);
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String member) {
|
||||
return node.has(member) ? string(node.get(member), member) : null;
|
||||
}
|
||||
|
||||
private static String string(JsonNode node, String member) {
|
||||
if (!node.isTextual()) {
|
||||
throw invalid(member + " must be a string.");
|
||||
}
|
||||
return node.textValue();
|
||||
}
|
||||
|
||||
private static void requireObject(JsonNode node, String member) {
|
||||
if (node == null || !node.isObject()) {
|
||||
throw invalid(member + " must be an object.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireArray(JsonNode node, String member) {
|
||||
if (node == null || !node.isArray()) {
|
||||
throw invalid(member + " must be an array.");
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer limit(JsonNode request) {
|
||||
if (!request.has("limit")) {
|
||||
return null;
|
||||
}
|
||||
JsonNode node = request.get("limit");
|
||||
if (!node.isIntegralNumber() || !node.canConvertToInt() || node.intValue() < 1 || node.intValue() > 50) {
|
||||
throw invalid("limit must be an integer between 1 and 50.");
|
||||
}
|
||||
return node.intValue();
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidParameterException", message, 400);
|
||||
}
|
||||
}
|
||||
+883
@@ -0,0 +1,883 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
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.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.filter.FilterMatch;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.filter.FilterPattern;
|
||||
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 io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.annotation.Priority;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService.requireFilterPattern;
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.MetricFilterRules.MAX_DIMENSIONS;
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.MetricFilterRules.NUMBER;
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.MetricFilterRules.invalid;
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.MetricFilterRules.number;
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.MetricFilterRules.selects;
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.MetricFilterRules.validateFieldSelectionCriteria;
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.MetricFilterRules.validateSystemFields;
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.MetricFilterRules.withSystemDimensions;
|
||||
|
||||
/**
|
||||
* Metric filters of CloudWatch Logs: the PutMetricFilter, DescribeMetricFilters, DeleteMetricFilter
|
||||
* and TestMetricFilter operations, and the part AWS does at ingestion, publishing a metric value for
|
||||
* every log event a filter matches. The filters live in their own store, keyed by Region, log group
|
||||
* and name. Both filter families share storage coordination with the log service, which tells
|
||||
* this one about ingestion and deleted groups through CDI events.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudWatchLogsMetricFilterService implements Resettable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchLogsMetricFilterService.class);
|
||||
|
||||
/** AWS's cap on metric filters per log group. */
|
||||
public static final int MAX_FILTERS_PER_LOG_GROUP = 100;
|
||||
private static final int MAX_METRIC_VALUE_LENGTH = 100;
|
||||
private static final int MAX_DIMENSION_LENGTH = 255;
|
||||
private static final int MAX_TEST_MESSAGES = 50;
|
||||
private static final int MAX_DESCRIBE_LIMIT = 50;
|
||||
private static final Pattern FILTER_NAME = Pattern.compile("[^:*]{1,512}");
|
||||
private static final Pattern METRIC_NAME = Pattern.compile("[^:*$]{1,255}");
|
||||
private static final Set<String> UNITS = Set.of("Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes",
|
||||
"Megabytes", "Gigabytes", "Terabytes", "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Percent",
|
||||
"Count", "Bytes/Second", "Kilobytes/Second", "Megabytes/Second", "Gigabytes/Second", "Terabytes/Second",
|
||||
"Bits/Second", "Kilobits/Second", "Megabits/Second", "Gigabits/Second", "Terabits/Second", "Count/Second",
|
||||
"None");
|
||||
|
||||
private final StorageBackend<String, MetricFilter> store;
|
||||
private final CloudWatchLogsService logsService;
|
||||
private final CloudWatchMetricsService metricsService;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
/**
|
||||
* Accepted samples wait here for the publisher thread, so PutLogEvents never writes to the Metrics
|
||||
* sink itself. ponytail: one fixed ceiling and one worker; a batch that does not fit is written
|
||||
* inline on the request thread instead of being dropped. Shard the queue if that shows in traces.
|
||||
*/
|
||||
static final int MAX_QUEUED_SAMPLES = 100_000;
|
||||
private final int queueCapacity;
|
||||
private final ArrayDeque<Batch> queued = new ArrayDeque<>();
|
||||
private int queuedSamples;
|
||||
/** Bumped by every reset or clear, so a batch taken before one is never written after it. */
|
||||
private int resetGeneration;
|
||||
private final AtomicBoolean drainScheduled = new AtomicBoolean();
|
||||
/** Failed samples retried by the worker. Process-local best effort, bounded by samples. No durable outbox. */
|
||||
private static final int MAX_PENDING_SAMPLES = 10_000;
|
||||
private final Map<String, Publication> pending = new LinkedHashMap<>();
|
||||
// One detail per owning filter's pending-work outage, then one aggregate warning per 60
|
||||
// failed worker ticks (at least a minute at the production cadence). No exceptions retained.
|
||||
private static final int RETRY_FAILURE_SUMMARY_TICKS = 60;
|
||||
private final Set<Owner> reportedOutages = new HashSet<>();
|
||||
private int failedRetryTicks;
|
||||
// The canonical filter backend is the only monitor, shared with quotas and group deletion.
|
||||
// Never acquire StorageFactory's monitor while holding a separate runtime-state monitor.
|
||||
private ScheduledExecutorService publisher;
|
||||
private boolean enabled = true;
|
||||
private boolean paused;
|
||||
private boolean stopped;
|
||||
|
||||
private record Owner(String account, String region, String group, String filter) {}
|
||||
|
||||
/** One filter's samples for one PutLogEvents request, evaluated at ingestion and immutable after. */
|
||||
private record Batch(Owner owner, List<Publication> publications) {
|
||||
Batch {
|
||||
publications = List.copyOf(publications);
|
||||
}
|
||||
}
|
||||
|
||||
private record Publication(String id, Owner owner, String namespace, String metricName, String unit,
|
||||
List<Dimension> dimensions, double value, long timestamp) {
|
||||
Publication {
|
||||
dimensions = List.copyOf(dimensions);
|
||||
}
|
||||
|
||||
MetricDatum datum() {
|
||||
MetricDatum datum = new MetricDatum();
|
||||
datum.setMetricName(metricName);
|
||||
datum.setUnit(unit);
|
||||
datum.setDimensions(dimensions);
|
||||
datum.setValue(value);
|
||||
datum.setTimestamp(timestamp);
|
||||
return datum;
|
||||
}
|
||||
}
|
||||
|
||||
@Inject
|
||||
public CloudWatchLogsMetricFilterService(CloudWatchLogsService logsService,
|
||||
CloudWatchMetricsService metricsService, RegionResolver regionResolver) {
|
||||
this(logsService, metricsService, regionResolver, MAX_QUEUED_SAMPLES);
|
||||
}
|
||||
|
||||
CloudWatchLogsMetricFilterService(CloudWatchLogsService logsService, CloudWatchMetricsService metricsService,
|
||||
RegionResolver regionResolver, int queueCapacity) {
|
||||
this.store = logsService.metricFilterStore();
|
||||
this.logsService = logsService;
|
||||
this.metricsService = metricsService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.queueCapacity = queueCapacity;
|
||||
}
|
||||
|
||||
/** A page of DescribeMetricFilters. */
|
||||
public record DescribeMetricFiltersResult(List<MetricFilter> metricFilters, String nextToken) {}
|
||||
|
||||
/** One TestMetricFilter match: the event's position in the request, its text and what the pattern extracted. */
|
||||
public record MetricFilterMatchRecord(long eventNumber, String eventMessage, Map<String, String> extractedValues) {}
|
||||
|
||||
/**
|
||||
* Creates the filter, or replaces it when the log group already has one with that name, keeping
|
||||
* the original creation time. The definition is checked the way AWS checks it: the group must
|
||||
* exist, the pattern must parse, the one transformation must name a metric and a value that is
|
||||
* a number or a field the pattern can supply, dimensions are limited to three field references
|
||||
* of a JSON or space-delimited pattern and exclude a default value, and the group holds at
|
||||
* most 100 filters.
|
||||
*/
|
||||
public MetricFilter putMetricFilter(MetricFilter definition, String region) {
|
||||
return putMetricFilter(definition, region, false, null);
|
||||
}
|
||||
|
||||
public enum MutationOutcome { APPLIED, NOT_APPLIED, UNKNOWN }
|
||||
|
||||
/** Internal mutation evidence; presence is null when it could not be inspected. */
|
||||
public record MutationResult(MutationOutcome outcome, Boolean present) {}
|
||||
|
||||
/** Internal CFN create: never adopts an existing filter through the public API's upsert. */
|
||||
public MetricFilter createMetricFilter(MetricFilter definition, String region,
|
||||
Consumer<MutationResult> outcome) {
|
||||
return putMetricFilter(definition, region, true, outcome);
|
||||
}
|
||||
|
||||
/** Internal CFN update of a confirmed-owned identity, including snapshot restoration. */
|
||||
public MetricFilter updateMetricFilter(MetricFilter definition, String region,
|
||||
Consumer<MutationResult> outcome) {
|
||||
return putMetricFilter(definition, region, false, outcome);
|
||||
}
|
||||
|
||||
private MetricFilter putMetricFilter(MetricFilter definition, String region,
|
||||
boolean createOnly, Consumer<MutationResult> outcome) {
|
||||
synchronized (store) {
|
||||
String logGroupName;
|
||||
String filterName;
|
||||
String key;
|
||||
MetricFilter before = null;
|
||||
Boolean present = null;
|
||||
MetricFilter filter;
|
||||
try {
|
||||
logGroupName = requireLogGroup(definition.getLogGroupName(), region);
|
||||
filterName = requireFilterName(definition.getFilterName());
|
||||
key = key(region, logGroupName, filterName);
|
||||
if (createOnly) {
|
||||
before = store.get(key).orElse(null);
|
||||
present = before != null;
|
||||
if (before != null) {
|
||||
throw new AwsException("AlreadyExistsException",
|
||||
"Metric filter " + filterName + " already exists in " + logGroupName, 400);
|
||||
}
|
||||
}
|
||||
FilterPattern pattern = requireFilterPattern(definition.getFilterPattern());
|
||||
MetricTransformation transformation = requireTransformation(definition.getMetricTransformations(), pattern);
|
||||
validateSystemFields(definition.getEmitSystemFieldDimensions(), transformation);
|
||||
validateFieldSelectionCriteria(definition.getFieldSelectionCriteria());
|
||||
if (!createOnly) {
|
||||
before = store.get(key).orElse(null);
|
||||
present = before != null;
|
||||
}
|
||||
if (before == null && countMetricFilters(logGroupName, region) >= MAX_FILTERS_PER_LOG_GROUP) {
|
||||
throw new AwsException("LimitExceededException",
|
||||
"The log group " + logGroupName + " already has the maximum of " + MAX_FILTERS_PER_LOG_GROUP
|
||||
+ " metric filters.", 400);
|
||||
}
|
||||
logsService.validateFilterRegexQuota(logGroupName, filterName, pattern, true, region);
|
||||
|
||||
filter = new MetricFilter();
|
||||
filter.setLogGroupName(logGroupName);
|
||||
filter.setFilterName(filterName);
|
||||
filter.setFilterPattern(definition.getFilterPattern());
|
||||
filter.setMetricTransformations(List.of(copy(transformation)));
|
||||
filter.setCreationTime(before == null ? System.currentTimeMillis() : before.getCreationTime());
|
||||
filter.setApplyOnTransformedLogs(definition.getApplyOnTransformedLogs());
|
||||
filter.setFieldSelectionCriteria(definition.getFieldSelectionCriteria());
|
||||
filter.setEmitSystemFieldDimensions(definition.getEmitSystemFieldDimensions() == null
|
||||
? null : List.copyOf(definition.getEmitSystemFieldDimensions()));
|
||||
} catch (RuntimeException failure) {
|
||||
completeMutation(new MutationResult(MutationOutcome.NOT_APPLIED, present), outcome, null, failure);
|
||||
throw failure;
|
||||
}
|
||||
mutateStore(key, before, filter, outcome, null);
|
||||
LOG.infov("Put metric filter {0} on log group {1}", filterName, logGroupName);
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
|
||||
/** The caller holds the canonical monitor through inspection and metadata recording. */
|
||||
private void mutateStore(String key, MetricFilter before, MetricFilter after,
|
||||
Consumer<MutationResult> outcome, Runnable onAbsent) {
|
||||
RuntimeException failure = null;
|
||||
MutationResult result = new MutationResult(MutationOutcome.APPLIED, after != null);
|
||||
try {
|
||||
if (after == null) {
|
||||
store.delete(key);
|
||||
} else {
|
||||
store.put(key, after);
|
||||
}
|
||||
} catch (RuntimeException storageFailure) {
|
||||
failure = storageFailure;
|
||||
result = new MutationResult(MutationOutcome.UNKNOWN, null);
|
||||
if (outcome != null) {
|
||||
try {
|
||||
MetricFilter current = store.get(key).orElse(null);
|
||||
if (current == after) {
|
||||
result = new MutationResult(MutationOutcome.APPLIED, current != null);
|
||||
} else if (current == before) {
|
||||
result = new MutationResult(MutationOutcome.NOT_APPLIED, current != null);
|
||||
}
|
||||
} catch (RuntimeException inspectionFailure) {
|
||||
if (storageFailure != inspectionFailure) {
|
||||
storageFailure.addSuppressed(inspectionFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
completeMutation(result, outcome, onAbsent, failure);
|
||||
}
|
||||
|
||||
private static void completeMutation(MutationResult result, Consumer<MutationResult> outcome,
|
||||
Runnable onAbsent, RuntimeException failure) {
|
||||
if (outcome != null) {
|
||||
try {
|
||||
outcome.accept(result);
|
||||
} catch (RuntimeException recordingFailure) {
|
||||
if (failure == null) {
|
||||
failure = recordingFailure;
|
||||
} else if (failure != recordingFailure) {
|
||||
failure.addSuppressed(recordingFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (onAbsent != null && Boolean.FALSE.equals(result.present())) {
|
||||
try {
|
||||
onAbsent.run();
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
if (failure == null) {
|
||||
failure = cleanupFailure;
|
||||
} else if (failure != cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private String requireLogGroup(String logGroupName, String region) {
|
||||
if (logGroupName == null || logGroupName.isBlank()) {
|
||||
throw invalid("logGroupName is required.");
|
||||
}
|
||||
if (!logsService.logGroupExists(logGroupName, region)) {
|
||||
throw new AwsException("ResourceNotFoundException", "The specified log group does not exist.", 400);
|
||||
}
|
||||
return logGroupName;
|
||||
}
|
||||
|
||||
private static String requireFilterName(String filterName) {
|
||||
if (filterName == null || filterName.isBlank()) {
|
||||
throw invalid("filterName is required.");
|
||||
}
|
||||
if (!FILTER_NAME.matcher(filterName).matches()) {
|
||||
throw invalid("filterName must be 1 to 512 characters and must not contain ':' or '*'.");
|
||||
}
|
||||
return filterName;
|
||||
}
|
||||
|
||||
private static MetricTransformation requireTransformation(List<MetricTransformation> transformations,
|
||||
FilterPattern pattern) {
|
||||
if (transformations == null || transformations.size() != 1 || transformations.getFirst() == null) {
|
||||
throw invalid("metricTransformations must contain exactly one transformation.");
|
||||
}
|
||||
MetricTransformation t = transformations.getFirst();
|
||||
if (t.getMetricName() == null || !METRIC_NAME.matcher(t.getMetricName()).matches()) {
|
||||
throw invalid("metricName is required, must be at most 255 characters and must not contain ':', '*' or '$'.");
|
||||
}
|
||||
if (t.getMetricNamespace() == null || !METRIC_NAME.matcher(t.getMetricNamespace()).matches()) {
|
||||
throw invalid("metricNamespace is required, must be at most 255 characters and must not contain ':', '*' or '$'.");
|
||||
}
|
||||
String value = t.getMetricValue();
|
||||
if (value == null || value.isBlank() || value.length() > MAX_METRIC_VALUE_LENGTH) {
|
||||
throw invalid("metricValue is required and must be at most " + MAX_METRIC_VALUE_LENGTH + " characters.");
|
||||
}
|
||||
if (NUMBER.matcher(value).matches() ? number(value) == null : !pattern.declaresSingleValueField(value)) {
|
||||
throw invalid("Invalid metric transformation: metric value " + value + " must be a valid number");
|
||||
}
|
||||
if (t.getDefaultValue() != null && !Double.isFinite(t.getDefaultValue())) {
|
||||
throw invalid("defaultValue must be a finite number.");
|
||||
}
|
||||
Map<String, String> dimensions = t.getDimensions();
|
||||
if (dimensions != null && !dimensions.isEmpty()) {
|
||||
if (dimensions.size() > MAX_DIMENSIONS) {
|
||||
throw invalid("A metric filter can include at most " + MAX_DIMENSIONS + " dimensions.");
|
||||
}
|
||||
if (pattern.kind() != FilterPattern.Kind.JSON && pattern.kind() != FilterPattern.Kind.SPACE_DELIMITED) {
|
||||
throw invalid("Dimensions are only available for JSON and space-delimited filter patterns.");
|
||||
}
|
||||
if (t.getDefaultValue() != null) {
|
||||
throw invalid("A metric filter with dimensions cannot have a default value.");
|
||||
}
|
||||
for (Map.Entry<String, String> dimension : dimensions.entrySet()) {
|
||||
String name = dimension.getKey();
|
||||
String reference = dimension.getValue();
|
||||
if (name == null || name.isBlank() || name.length() > MAX_DIMENSION_LENGTH || name.startsWith(":")) {
|
||||
throw invalid("Dimension names must be 1 to 255 characters and must not start with ':'.");
|
||||
}
|
||||
if (reference == null || reference.length() > MAX_DIMENSION_LENGTH || !pattern.declaresField(reference)) {
|
||||
throw invalid("Dimension " + name + " must refer to a field of the filter pattern such as $.field or"
|
||||
+ " $field, got '" + reference + "'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (t.getUnit() != null && !UNITS.contains(t.getUnit())) {
|
||||
throw invalid("unit must be one of the CloudWatch standard units, got '" + t.getUnit() + "'.");
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
private static MetricTransformation copy(MetricTransformation t) {
|
||||
MetricTransformation copy = new MetricTransformation();
|
||||
copy.setMetricName(t.getMetricName());
|
||||
copy.setMetricNamespace(t.getMetricNamespace());
|
||||
copy.setMetricValue(t.getMetricValue());
|
||||
copy.setDefaultValue(t.getDefaultValue());
|
||||
copy.setDimensions(t.getDimensions() == null ? new LinkedHashMap<>() : new LinkedHashMap<>(t.getDimensions()));
|
||||
copy.setUnit(t.getUnit());
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists filters, sorted by name as AWS does, for one log group or for the whole Region. As on
|
||||
* AWS, {@code filterNamePrefix} applies only together with {@code logGroupName}, and
|
||||
* {@code metricName} and {@code metricNamespace} must be given together or not at all.
|
||||
*/
|
||||
public DescribeMetricFiltersResult describeMetricFilters(String logGroupName, String filterNamePrefix,
|
||||
String metricName, String metricNamespace,
|
||||
String nextToken, Integer limit, String region) {
|
||||
int pageSize = limit == null ? MAX_DESCRIBE_LIMIT : limit;
|
||||
if (pageSize < 1 || pageSize > MAX_DESCRIBE_LIMIT) {
|
||||
throw invalid("limit must be between 1 and " + MAX_DESCRIBE_LIMIT + ".");
|
||||
}
|
||||
if ((metricName == null) != (metricNamespace == null)) {
|
||||
throw invalid("Describe Metric Filters request must contain both MetricName and MetricNamespace");
|
||||
}
|
||||
boolean byGroup = logGroupName != null && !logGroupName.isBlank();
|
||||
if (byGroup) {
|
||||
requireLogGroup(logGroupName, region);
|
||||
}
|
||||
String prefix = byGroup ? groupPrefix(region, logGroupName) : region + "::";
|
||||
List<MetricFilter> all = store.scan(key -> key.startsWith(prefix));
|
||||
List<MetricFilter> filtered = all.stream()
|
||||
.filter(f -> !byGroup || filterNamePrefix == null || filterNamePrefix.isBlank()
|
||||
|| f.getFilterName().startsWith(filterNamePrefix))
|
||||
.filter(f -> metricNamespace == null || transformationMatches(f, metricName, metricNamespace))
|
||||
.sorted(Comparator.comparing(MetricFilter::getFilterName).thenComparing(MetricFilter::getLogGroupName))
|
||||
.toList();
|
||||
|
||||
int offset = 0;
|
||||
if (nextToken != null && !nextToken.isBlank()) {
|
||||
try {
|
||||
offset = Integer.parseInt(nextToken);
|
||||
} catch (NumberFormatException e) {
|
||||
throw invalid("The specified nextToken is invalid.");
|
||||
}
|
||||
if (offset < 0 || offset > filtered.size()) {
|
||||
throw invalid("The specified nextToken is invalid.");
|
||||
}
|
||||
}
|
||||
int end = Math.min(offset + pageSize, filtered.size());
|
||||
String token = end < filtered.size() ? String.valueOf(end) : null;
|
||||
return new DescribeMetricFiltersResult(filtered.subList(offset, end), token);
|
||||
}
|
||||
|
||||
private static boolean transformationMatches(MetricFilter filter, String metricName, String metricNamespace) {
|
||||
return filter.getMetricTransformations().stream().anyMatch(t ->
|
||||
metricNamespace.equals(t.getMetricNamespace()) && metricName.equals(t.getMetricName()));
|
||||
}
|
||||
|
||||
public void deleteMetricFilter(String logGroupName, String filterName, String region) {
|
||||
synchronized (store) {
|
||||
requireLogGroup(logGroupName, region);
|
||||
if (filterName == null || filterName.isBlank()) {
|
||||
throw invalid("filterName is required.");
|
||||
}
|
||||
String key = key(region, logGroupName, filterName);
|
||||
if (store.get(key).isEmpty()) {
|
||||
throw new AwsException("ResourceNotFoundException", "The specified metric filter does not exist.", 400);
|
||||
}
|
||||
store.delete(key);
|
||||
cancelPublications(logGroupName, filterName, region);
|
||||
LOG.infov("Deleted metric filter {0} on log group {1}", filterName, logGroupName);
|
||||
}
|
||||
}
|
||||
|
||||
/** Internal CFN delete with evidence recorded before another creator can acquire the monitor. */
|
||||
public void deleteMetricFilter(String logGroupName, String filterName, String region,
|
||||
Consumer<MutationResult> outcome) {
|
||||
synchronized (store) {
|
||||
String key = key(region, logGroupName, filterName);
|
||||
MetricFilter before;
|
||||
try {
|
||||
before = store.get(key).orElse(null);
|
||||
} catch (RuntimeException failure) {
|
||||
completeMutation(new MutationResult(MutationOutcome.NOT_APPLIED, null), outcome, null, failure);
|
||||
throw failure;
|
||||
}
|
||||
Runnable cancel = () -> cancelPublications(logGroupName, filterName, region);
|
||||
if (before == null) {
|
||||
completeMutation(new MutationResult(MutationOutcome.NOT_APPLIED, false), outcome, cancel, null);
|
||||
return;
|
||||
}
|
||||
mutateStore(key, before, null, outcome, cancel);
|
||||
LOG.infov("Deleted metric filter {0} on log group {1}", filterName, logGroupName);
|
||||
}
|
||||
}
|
||||
|
||||
/** Confirms absence and records relinquished ownership atomically, without touching a surviving row. */
|
||||
public boolean confirmMetricFilterAbsent(String logGroupName, String filterName, String region, Runnable onAbsent) {
|
||||
synchronized (store) {
|
||||
if (store.get(key(region, logGroupName, filterName)).isPresent()) {
|
||||
return false;
|
||||
}
|
||||
completeMutation(new MutationResult(MutationOutcome.NOT_APPLIED, false), ignored -> onAbsent.run(),
|
||||
() -> cancelPublications(logGroupName, filterName, region), null);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelPublications(String logGroupName, String filterName, String region) {
|
||||
Owner owner = new Owner(regionResolver.getAccountId(), region, logGroupName, filterName);
|
||||
pending.values().removeIf(p -> p.owner().equals(owner));
|
||||
forgetCompletedOutages();
|
||||
}
|
||||
|
||||
public Optional<MetricFilter> findMetricFilter(String logGroupName, String filterName, String region) {
|
||||
return store.get(key(region, logGroupName, filterName));
|
||||
}
|
||||
|
||||
public int countMetricFilters(String logGroupName, String region) {
|
||||
return filtersOf(logGroupName, region).size();
|
||||
}
|
||||
|
||||
/** Runs a pattern over sample messages, the TestMetricFilter operation; event numbers start at one. */
|
||||
public List<MetricFilterMatchRecord> testMetricFilter(String filterPattern, List<String> messages) {
|
||||
FilterPattern pattern = requireFilterPattern(filterPattern);
|
||||
if (messages == null || messages.isEmpty() || messages.size() > MAX_TEST_MESSAGES) {
|
||||
throw invalid("logEventMessages must contain between 1 and " + MAX_TEST_MESSAGES + " messages.");
|
||||
}
|
||||
List<MetricFilterMatchRecord> matches = new ArrayList<>();
|
||||
for (int i = 0; i < messages.size(); i++) {
|
||||
String message = messages.get(i);
|
||||
if (message == null || message.isEmpty()) {
|
||||
throw invalid("logEventMessages must not contain an empty message.");
|
||||
}
|
||||
FilterMatch match = pattern.match(message);
|
||||
if (match.matched()) {
|
||||
matches.add(new MetricFilterMatchRecord(i + 1L, message, match.extractedValues()));
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
/** Logs cascades first; retain idempotent cleanup for standalone observer callers as well. */
|
||||
void onLogGroupDeleted(@Observes LogGroupDeleted event) {
|
||||
synchronized (store) {
|
||||
String account = regionResolver.getAccountId();
|
||||
String prefix = groupPrefix(event.region(), event.logGroupName());
|
||||
store.keys().stream().filter(key -> key.startsWith(prefix)).toList().forEach(store::delete);
|
||||
pending.values().removeIf(p -> p.owner().account().equals(account)
|
||||
&& p.owner().region().equals(event.region()) && p.owner().group().equals(event.logGroupName()));
|
||||
forgetCompletedOutages();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates the group's filters as they are at ingestion and queues each event's contribution,
|
||||
* independent of other events or later traffic. The Metrics writes happen on the publisher thread.
|
||||
*/
|
||||
void onLogEventsIngested(@Observes LogEventsIngested event) {
|
||||
synchronized (store) {
|
||||
if (!enabled || paused || stopped) {
|
||||
return;
|
||||
}
|
||||
String account = event.accountId() == null || event.accountId().isBlank()
|
||||
? regionResolver.getAccountId() : event.accountId();
|
||||
try {
|
||||
for (MetricFilter filter : filtersOf(event.logGroupName(), event.region(), account)) {
|
||||
try {
|
||||
if (selects(filter, account, event.region())) {
|
||||
enqueue(evaluate(filter, event, account));
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.errorv(e, "Cannot evaluate metric filter: account={0}, region={1}, group={2}, filter={3}",
|
||||
account, event.region(), event.logGroupName(), filter.getFilterName());
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// Stored Logs remain successful even if the definition store cannot be read.
|
||||
LOG.errorv(e, "Cannot load metric filters; publication not queued: account={0}, region={1}, group={2}",
|
||||
account, event.region(), event.logGroupName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Batch evaluate(MetricFilter filter, LogEventsIngested event, String account) {
|
||||
FilterPattern pattern = FilterPattern.parse(filter.getFilterPattern());
|
||||
MetricTransformation t = filter.getMetricTransformations().getFirst();
|
||||
Double literal = number(t.getMetricValue());
|
||||
Owner owner = new Owner(account, event.region(), event.logGroupName(), filter.getFilterName());
|
||||
List<Publication> publications = new ArrayList<>();
|
||||
for (LogEvent logEvent : event.events()) {
|
||||
FilterMatch match = pattern.match(logEvent.getMessage());
|
||||
Double value = t.getDefaultValue();
|
||||
List<Dimension> dimensions = new ArrayList<>();
|
||||
if (match.matched()) {
|
||||
// Preserve raw text: only missing/null falls back. A present nonnumeric value skips.
|
||||
String raw = match.value(t.getMetricValue());
|
||||
value = literal != null ? literal : raw == null ? t.getDefaultValue() : number(raw);
|
||||
if (t.getDimensions() != null) {
|
||||
for (Map.Entry<String, String> dimension : t.getDimensions().entrySet()) {
|
||||
String extracted = match.value(dimension.getValue());
|
||||
if (extracted == null) {
|
||||
dimensions.clear();
|
||||
break;
|
||||
}
|
||||
dimensions.add(new Dimension(dimension.getKey(), extracted));
|
||||
}
|
||||
}
|
||||
// Policy for unmeasured combinations: matching fallback and incomplete ordinary
|
||||
// dimensions retain system dimensions. Pattern-nonmatch defaults are dimensionless.
|
||||
withSystemDimensions(filter, account, event.region(), dimensions);
|
||||
}
|
||||
if (value != null) {
|
||||
publications.add(new Publication(UUID.randomUUID().toString(), owner, t.getMetricNamespace(),
|
||||
t.getMetricName(), t.getUnit() == null ? "None" : t.getUnit(), dimensions,
|
||||
value, logEvent.getTimestamp() / 1000));
|
||||
}
|
||||
}
|
||||
return new Batch(owner, publications);
|
||||
}
|
||||
|
||||
/** Under the monitor. A batch the queue cannot hold is written here, on the request thread. */
|
||||
private void enqueue(Batch batch) {
|
||||
int size = batch.publications().size();
|
||||
if (size == 0) {
|
||||
return;
|
||||
}
|
||||
if (queuedSamples + size > queueCapacity) {
|
||||
write(batch);
|
||||
return;
|
||||
}
|
||||
queued.addLast(batch);
|
||||
queuedSamples += size;
|
||||
scheduleDrain();
|
||||
}
|
||||
|
||||
private void scheduleDrain() {
|
||||
if (publisher == null || !drainScheduled.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
publisher.execute(() -> {
|
||||
drainScheduled.set(false);
|
||||
try {
|
||||
publishQueued();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.errorv(e, "Metric publication drain failed; queued work retained");
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException e) {
|
||||
// Racing stop(), whose synchronous drain picks the batch up.
|
||||
drainScheduled.set(false);
|
||||
LOG.debugv("Metric publisher already stopping; {0} queued samples drain on shutdown", queuedSamples);
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes every queued batch. The worker's entry point, also used by tests and the shutdown drain. */
|
||||
void publishQueued() {
|
||||
while (true) {
|
||||
Batch batch;
|
||||
int generation;
|
||||
synchronized (store) {
|
||||
if (paused) {
|
||||
return;
|
||||
}
|
||||
batch = queued.pollFirst();
|
||||
if (batch == null) {
|
||||
return;
|
||||
}
|
||||
queuedSamples -= batch.publications().size();
|
||||
generation = resetGeneration;
|
||||
}
|
||||
write(batch, generation);
|
||||
}
|
||||
}
|
||||
|
||||
/** Under the monitor, for a batch the queue cannot hold. */
|
||||
private void write(Batch batch) {
|
||||
write(batch, resetGeneration);
|
||||
}
|
||||
|
||||
/**
|
||||
* One monitor acquisition per sample, so a PutMetricFilter or a reset waits for at most one
|
||||
* write. A reset seen mid-batch, paused or already completed, discards the rest: the samples
|
||||
* belong to the state that was wiped.
|
||||
*/
|
||||
private void write(Batch batch, int generation) {
|
||||
int failed = 0;
|
||||
int dropped = 0;
|
||||
RuntimeException firstFailure = null;
|
||||
for (Publication publication : batch.publications()) {
|
||||
synchronized (store) {
|
||||
if (paused || generation != resetGeneration) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
write(publication);
|
||||
} catch (RuntimeException e) {
|
||||
failed++;
|
||||
if (firstFailure == null) {
|
||||
firstFailure = e;
|
||||
}
|
||||
if (pending.size() < MAX_PENDING_SAMPLES) {
|
||||
pending.put(publication.id(), publication);
|
||||
} else {
|
||||
dropped++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Owner owner = batch.owner();
|
||||
if (failed > dropped) {
|
||||
// Only retained work owns suppression state. Dropped-only work gets the ERROR below.
|
||||
synchronized (store) {
|
||||
logPublicationFailureOnce(owner, firstFailure);
|
||||
}
|
||||
}
|
||||
if (dropped > 0) {
|
||||
LOG.errorv("Metric publication retry queue overflow: account={0}, region={1}, group={2}, filter={3}, dropped={4}, capacity={5}",
|
||||
owner.account(), owner.region(), owner.group(), owner.filter(), dropped, MAX_PENDING_SAMPLES);
|
||||
}
|
||||
}
|
||||
|
||||
private void write(Publication publication) {
|
||||
metricsService.publishMetricForAccount(publication.owner().account(), publication.namespace(),
|
||||
publication.datum(), publication.owner().region(), publication.id());
|
||||
}
|
||||
|
||||
/** The production worker's entry point, also used by deterministic fault/race tests. */
|
||||
void retryPending() {
|
||||
try {
|
||||
synchronized (store) {
|
||||
if (!enabled || paused || stopped) {
|
||||
return;
|
||||
}
|
||||
for (Publication publication : List.copyOf(pending.values())) {
|
||||
try {
|
||||
write(publication);
|
||||
pending.remove(publication.id());
|
||||
} catch (RuntimeException e) {
|
||||
// Retain this exact snapshot/ID. Other filters still get their attempt.
|
||||
logPublicationFailureOnce(publication.owner(), e);
|
||||
}
|
||||
}
|
||||
forgetCompletedOutages();
|
||||
if (!pending.isEmpty() && ++failedRetryTicks >= RETRY_FAILURE_SUMMARY_TICKS) {
|
||||
LOG.warnv("Metric publication retries still failing: filters={0}, failedSamples={1}",
|
||||
reportedOutages.size(), pending.size());
|
||||
failedRetryTicks = 0;
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// Scheduled executors suppress every future tick if any invocation escapes.
|
||||
LOG.errorv(e, "Metric publication retry tick failed; pending work retained");
|
||||
}
|
||||
}
|
||||
|
||||
private void logPublicationFailureOnce(Owner owner, RuntimeException failure) {
|
||||
if (reportedOutages.add(owner)) {
|
||||
LOG.warnv(failure, "Metric publication failed: account={0}, region={1}, group={2}, filter={3}, pending={4}",
|
||||
owner.account(), owner.region(), owner.group(), owner.filter(), pending.size());
|
||||
}
|
||||
}
|
||||
|
||||
/** Called under the canonical monitor after drain/cancellation. State is bounded by pending owners. */
|
||||
private void forgetCompletedOutages() {
|
||||
Set<Owner> activeOwners = new HashSet<>();
|
||||
for (Publication publication : pending.values()) {
|
||||
activeOwners.add(publication.owner());
|
||||
}
|
||||
reportedOutages.retainAll(activeOwners);
|
||||
if (pending.isEmpty()) {
|
||||
failedRetryTicks = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void onStart(@Observes StartupEvent event, EmulatorConfig config) {
|
||||
start(config.services().cloudwatchlogs().enabled(), config.services().cloudwatchmetrics().enabled());
|
||||
}
|
||||
|
||||
void start(boolean logsEnabled, boolean metricsEnabled) {
|
||||
synchronized (store) {
|
||||
if (publisher != null || stopped) {
|
||||
return;
|
||||
}
|
||||
enabled = logsEnabled && metricsEnabled;
|
||||
if (!enabled) {
|
||||
discardQueued();
|
||||
return;
|
||||
}
|
||||
publisher = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "logs-metric-publisher"));
|
||||
publisher.scheduleWithFixedDelay(this::retryPending, 1, 1, TimeUnit.SECONDS);
|
||||
if (!queued.isEmpty()) {
|
||||
scheduleDrain();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stop before EmulatorLifecycle's default-priority storage flush/shutdown observer.
|
||||
void onStop(@Observes @Priority(1000) ShutdownEvent event) {
|
||||
stop();
|
||||
}
|
||||
|
||||
/** Accepted samples are written before storage shuts down; failed retries are abandoned. */
|
||||
@PreDestroy
|
||||
void stop() {
|
||||
ScheduledExecutorService worker;
|
||||
synchronized (store) {
|
||||
stopped = true;
|
||||
worker = publisher;
|
||||
}
|
||||
publishQueued();
|
||||
if (worker != null) {
|
||||
worker.shutdownNow();
|
||||
try {
|
||||
if (!worker.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
LOG.errorv("Metric publisher did not terminate within 5 seconds");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv(e, "Interrupted while stopping the metric publisher");
|
||||
}
|
||||
}
|
||||
// After the worker is gone, so a write failing during the drain cannot repopulate the map.
|
||||
synchronized (store) {
|
||||
pending.clear();
|
||||
forgetCompletedOutages();
|
||||
}
|
||||
}
|
||||
|
||||
int queuedSamples() {
|
||||
synchronized (store) {
|
||||
return queuedSamples;
|
||||
}
|
||||
}
|
||||
|
||||
int pendingSamples() {
|
||||
synchronized (store) {
|
||||
return pending.size();
|
||||
}
|
||||
}
|
||||
|
||||
boolean publisherRunning() {
|
||||
synchronized (store) {
|
||||
return publisher != null && !publisher.isShutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeReset() {
|
||||
synchronized (store) {
|
||||
// Acquiring the canonical monitor drains the active write. Release it before the
|
||||
// controller enters StorageFactory.clearAll(), avoiding factory/backend inversion.
|
||||
paused = true;
|
||||
discardQueued();
|
||||
pending.clear();
|
||||
forgetCompletedOutages();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterReset() {
|
||||
synchronized (store) {
|
||||
paused = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
synchronized (store) {
|
||||
discardQueued();
|
||||
pending.clear();
|
||||
forgetCompletedOutages();
|
||||
}
|
||||
}
|
||||
|
||||
private void discardQueued() {
|
||||
queued.clear();
|
||||
queuedSamples = 0;
|
||||
resetGeneration++;
|
||||
}
|
||||
|
||||
private List<MetricFilter> filtersOf(String logGroupName, String region) {
|
||||
return filtersOf(logGroupName, region, null);
|
||||
}
|
||||
|
||||
/** The group's filters in {@code accountId}'s partition, or in the caller's own when it is null. */
|
||||
private List<MetricFilter> filtersOf(String logGroupName, String region, String accountId) {
|
||||
String prefix = groupPrefix(region, logGroupName);
|
||||
if (accountId != null && store instanceof AccountAwareStorageBackend<?> rawAware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<MetricFilter> aware = (AccountAwareStorageBackend<MetricFilter>) rawAware;
|
||||
return aware.scanForAccount(accountId, key -> key.startsWith(prefix));
|
||||
}
|
||||
return store.scan(key -> key.startsWith(prefix));
|
||||
}
|
||||
|
||||
private static String groupPrefix(String region, String logGroupName) {
|
||||
return region + "::" + logGroupName + "::";
|
||||
}
|
||||
|
||||
private static String key(String region, String logGroupName, String filterName) {
|
||||
return groupPrefix(region, logGroupName) + filterName;
|
||||
}
|
||||
|
||||
}
|
||||
+191
-71
@@ -7,13 +7,17 @@ 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.filter.FilterPattern;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.filter.FilterPatternException;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.ResourcePolicy;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.SubscriptionFilter;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Event;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -37,10 +41,14 @@ import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
|
||||
import static io.github.hectorvent.floci.services.cloudwatch.logs.MetricFilterRules.invalid;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CloudWatchLogsService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchLogsService.class);
|
||||
private static final int MAX_REGEX_FILTERS_PER_LOG_GROUP = 5;
|
||||
private static final int MAX_FILTER_PATTERN_LENGTH = 1024;
|
||||
|
||||
/**
|
||||
* Orders events by timestamp, then by ingestion sequence so that events sharing the same
|
||||
@@ -57,8 +65,15 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
private final StorageBackend<String, LogStream> streamStore;
|
||||
private final StorageBackend<String, LogEvent> eventStore;
|
||||
private final StorageBackend<String, SubscriptionFilter> subscriptionFilterStore;
|
||||
private final StorageBackend<String, MetricFilter> metricFilterStore;
|
||||
private final StorageBackend<String, ResourcePolicy> resourcePolicyStore;
|
||||
private final RegionResolver regionResolver;
|
||||
/**
|
||||
* What ingestion and group deletion tell the rest of the emulator, so features AWS drives from
|
||||
* them (metric filters) stay out of this class. Null when built by the test constructors.
|
||||
*/
|
||||
private final Event<LogEventsIngested> logEventsIngested;
|
||||
private final Event<LogGroupDeleted> logGroupDeleted;
|
||||
private final int maxEventsPerQuery;
|
||||
/** Ceiling on stored events across every group in an account; the oldest are evicted first once exceeded. */
|
||||
private final int maxStoredEvents;
|
||||
@@ -94,7 +109,9 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
@Inject
|
||||
public CloudWatchLogsService(StorageFactory storageFactory,
|
||||
EmulatorConfig config,
|
||||
RegionResolver regionResolver) {
|
||||
RegionResolver regionResolver,
|
||||
Event<LogEventsIngested> logEventsIngested,
|
||||
Event<LogGroupDeleted> logGroupDeleted) {
|
||||
this(
|
||||
storageFactory.create("cloudwatchlogs", "cwlogs-groups.json",
|
||||
new TypeReference<>() {}),
|
||||
@@ -104,13 +121,17 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
new TypeReference<>() {}),
|
||||
storageFactory.create("cloudwatchlogs", "cwlogs-subscription-filters.json",
|
||||
new TypeReference<>() {}),
|
||||
storageFactory.create("cloudwatchlogs", "cwlogs-metric-filters.json",
|
||||
new TypeReference<>() {}),
|
||||
storageFactory.create("cloudwatchlogs", "cwlogs-resource-policies.json",
|
||||
new TypeReference<>() {}),
|
||||
config.services().cloudwatchlogs().maxEventsPerQuery(),
|
||||
config.services().cloudwatchlogs().maxStoredEvents(),
|
||||
regionResolver,
|
||||
config.services().cloudwatchlogs().queryCompletionDelayMs(),
|
||||
System::currentTimeMillis
|
||||
System::currentTimeMillis,
|
||||
logEventsIngested,
|
||||
logGroupDeleted
|
||||
);
|
||||
}
|
||||
|
||||
@@ -118,9 +139,10 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
StorageBackend<String, LogStream> streamStore,
|
||||
StorageBackend<String, LogEvent> eventStore,
|
||||
StorageBackend<String, SubscriptionFilter> subscriptionFilterStore,
|
||||
StorageBackend<String, MetricFilter> metricFilterStore,
|
||||
int maxEventsPerQuery,
|
||||
RegionResolver regionResolver) {
|
||||
this(groupStore, streamStore, eventStore, subscriptionFilterStore, new InMemoryStorage<>(),
|
||||
this(groupStore, streamStore, eventStore, subscriptionFilterStore, metricFilterStore, new InMemoryStorage<>(),
|
||||
maxEventsPerQuery, Integer.MAX_VALUE, regionResolver, 0L, System::currentTimeMillis);
|
||||
}
|
||||
|
||||
@@ -128,10 +150,11 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
StorageBackend<String, LogStream> streamStore,
|
||||
StorageBackend<String, LogEvent> eventStore,
|
||||
StorageBackend<String, SubscriptionFilter> subscriptionFilterStore,
|
||||
StorageBackend<String, MetricFilter> metricFilterStore,
|
||||
int maxEventsPerQuery,
|
||||
int maxStoredEvents,
|
||||
RegionResolver regionResolver) {
|
||||
this(groupStore, streamStore, eventStore, subscriptionFilterStore, new InMemoryStorage<>(),
|
||||
this(groupStore, streamStore, eventStore, subscriptionFilterStore, metricFilterStore, new InMemoryStorage<>(),
|
||||
maxEventsPerQuery, maxStoredEvents, regionResolver, 0L, System::currentTimeMillis);
|
||||
}
|
||||
|
||||
@@ -139,11 +162,12 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
StorageBackend<String, LogStream> streamStore,
|
||||
StorageBackend<String, LogEvent> eventStore,
|
||||
StorageBackend<String, SubscriptionFilter> subscriptionFilterStore,
|
||||
StorageBackend<String, MetricFilter> metricFilterStore,
|
||||
int maxEventsPerQuery,
|
||||
RegionResolver regionResolver,
|
||||
long queryCompletionDelayMs,
|
||||
LongSupplier clock) {
|
||||
this(groupStore, streamStore, eventStore, subscriptionFilterStore, new InMemoryStorage<>(),
|
||||
this(groupStore, streamStore, eventStore, subscriptionFilterStore, metricFilterStore, new InMemoryStorage<>(),
|
||||
maxEventsPerQuery, Integer.MAX_VALUE, regionResolver, queryCompletionDelayMs, clock);
|
||||
}
|
||||
|
||||
@@ -151,16 +175,35 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
StorageBackend<String, LogStream> streamStore,
|
||||
StorageBackend<String, LogEvent> eventStore,
|
||||
StorageBackend<String, SubscriptionFilter> subscriptionFilterStore,
|
||||
StorageBackend<String, MetricFilter> metricFilterStore,
|
||||
StorageBackend<String, ResourcePolicy> resourcePolicyStore,
|
||||
int maxEventsPerQuery,
|
||||
int maxStoredEvents,
|
||||
RegionResolver regionResolver,
|
||||
long queryCompletionDelayMs,
|
||||
LongSupplier clock) {
|
||||
this(groupStore, streamStore, eventStore, subscriptionFilterStore, metricFilterStore, resourcePolicyStore,
|
||||
maxEventsPerQuery, maxStoredEvents, regionResolver, queryCompletionDelayMs, clock, null, null);
|
||||
}
|
||||
|
||||
CloudWatchLogsService(StorageBackend<String, LogGroup> groupStore,
|
||||
StorageBackend<String, LogStream> streamStore,
|
||||
StorageBackend<String, LogEvent> eventStore,
|
||||
StorageBackend<String, SubscriptionFilter> subscriptionFilterStore,
|
||||
StorageBackend<String, MetricFilter> metricFilterStore,
|
||||
StorageBackend<String, ResourcePolicy> resourcePolicyStore,
|
||||
int maxEventsPerQuery,
|
||||
int maxStoredEvents,
|
||||
RegionResolver regionResolver,
|
||||
long queryCompletionDelayMs,
|
||||
LongSupplier clock,
|
||||
Event<LogEventsIngested> logEventsIngested,
|
||||
Event<LogGroupDeleted> logGroupDeleted) {
|
||||
this.groupStore = groupStore;
|
||||
this.streamStore = streamStore;
|
||||
this.eventStore = eventStore;
|
||||
this.subscriptionFilterStore = subscriptionFilterStore;
|
||||
this.metricFilterStore = metricFilterStore;
|
||||
this.resourcePolicyStore = resourcePolicyStore;
|
||||
this.maxEventsPerQuery = maxEventsPerQuery;
|
||||
this.maxStoredEvents = maxStoredEvents;
|
||||
@@ -173,6 +216,8 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
// A negative delay is meaningless; treat it as instant completion.
|
||||
this.queryCompletionDelayMs = Math.max(0, queryCompletionDelayMs);
|
||||
this.clock = clock;
|
||||
this.logEventsIngested = logEventsIngested;
|
||||
this.logGroupDeleted = logGroupDeleted;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Log Groups ────────────────────────────
|
||||
@@ -206,55 +251,67 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
public void createLogGroupForAccount(
|
||||
String accountId, String name, Integer retentionInDays,
|
||||
Map<String, String> tags, boolean deletionProtectionEnabled, String kmsKeyId, String region) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "logGroupName is required.", 400);
|
||||
synchronized (metricFilterStore) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "logGroupName is required.", 400);
|
||||
}
|
||||
String key = groupKey(region, name);
|
||||
if (getForAccount(groupStore, accountId, key).isPresent()) {
|
||||
throw new AwsException("ResourceAlreadyExistsException",
|
||||
"The specified log group already exists: " + name, 400);
|
||||
}
|
||||
LogGroup group = new LogGroup();
|
||||
group.setLogGroupName(name);
|
||||
group.setCreatedTime(System.currentTimeMillis());
|
||||
group.setRetentionInDays(retentionInDays);
|
||||
group.setDeletionProtectionEnabled(deletionProtectionEnabled);
|
||||
if (kmsKeyId != null && !kmsKeyId.isBlank()) {
|
||||
group.setKmsKeyId(kmsKeyId);
|
||||
}
|
||||
if (tags != null) {
|
||||
group.setTags(new HashMap<>(tags));
|
||||
}
|
||||
putForAccount(groupStore, accountId, key, group);
|
||||
LOG.infov("Created log group: {0} in region {1}", name, region);
|
||||
}
|
||||
String key = groupKey(region, name);
|
||||
if (getForAccount(groupStore, accountId, key).isPresent()) {
|
||||
throw new AwsException("ResourceAlreadyExistsException",
|
||||
"The specified log group already exists: " + name, 400);
|
||||
}
|
||||
LogGroup group = new LogGroup();
|
||||
group.setLogGroupName(name);
|
||||
group.setCreatedTime(System.currentTimeMillis());
|
||||
group.setRetentionInDays(retentionInDays);
|
||||
group.setDeletionProtectionEnabled(deletionProtectionEnabled);
|
||||
if (kmsKeyId != null && !kmsKeyId.isBlank()) {
|
||||
group.setKmsKeyId(kmsKeyId);
|
||||
}
|
||||
if (tags != null) {
|
||||
group.setTags(new HashMap<>(tags));
|
||||
}
|
||||
putForAccount(groupStore, accountId, key, group);
|
||||
LOG.infov("Created log group: {0} in region {1}", name, region);
|
||||
}
|
||||
|
||||
public void deleteLogGroup(String name, String region) {
|
||||
String key = groupKey(region, name);
|
||||
LogGroup group = groupStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + name, 400));
|
||||
if (group.isDeletionProtectionEnabled()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"The specified log group has deletion protection enabled. "
|
||||
+ "Disable deletion protection before deleting the log group.",
|
||||
400);
|
||||
}
|
||||
synchronized (metricFilterStore) {
|
||||
String key = groupKey(region, name);
|
||||
LogGroup group = groupStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + name, 400));
|
||||
if (group.isDeletionProtectionEnabled()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"The specified log group has deletion protection enabled. "
|
||||
+ "Disable deletion protection before deleting the log group.",
|
||||
400);
|
||||
}
|
||||
|
||||
// Cascade: delete all streams and events for this group
|
||||
String streamPrefix = streamKeyPrefix(region, name);
|
||||
List<String> streamKeys = streamStore.keys().stream()
|
||||
.filter(k -> k.startsWith(streamPrefix))
|
||||
.toList();
|
||||
for (String sk : streamKeys) {
|
||||
LogStream stream = streamStore.get(sk).orElse(null);
|
||||
if (stream != null) {
|
||||
deleteEventsForStream(region, name, stream.getLogStreamName());
|
||||
streamStore.delete(sk);
|
||||
// Cascade: delete all streams, events and filters before removing the group.
|
||||
String streamPrefix = streamKeyPrefix(region, name);
|
||||
List<String> streamKeys = streamStore.keys().stream()
|
||||
.filter(k -> k.startsWith(streamPrefix))
|
||||
.toList();
|
||||
for (String sk : streamKeys) {
|
||||
LogStream stream = streamStore.get(sk).orElse(null);
|
||||
if (stream != null) {
|
||||
deleteEventsForStream(region, name, stream.getLogStreamName());
|
||||
streamStore.delete(sk);
|
||||
}
|
||||
}
|
||||
metricFilterStore.keys().stream().filter(k -> k.startsWith(streamPrefix))
|
||||
.toList().forEach(metricFilterStore::delete);
|
||||
String subscriptionPrefix = subscriptionFilterKeyPrefix(region, name);
|
||||
subscriptionFilterStore.keys().stream().filter(k -> k.startsWith(subscriptionPrefix))
|
||||
.toList().forEach(subscriptionFilterStore::delete);
|
||||
groupStore.delete(key);
|
||||
LOG.infov("Deleted log group: {0}", name);
|
||||
if (logGroupDeleted != null) {
|
||||
logGroupDeleted.fire(new LogGroupDeleted(region, name));
|
||||
}
|
||||
}
|
||||
groupStore.delete(key);
|
||||
LOG.infov("Deleted log group: {0}", name);
|
||||
}
|
||||
|
||||
public boolean logGroupExists(String name, String region) {
|
||||
@@ -556,6 +613,7 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
long totalBytes = 0;
|
||||
Long minTs = null;
|
||||
Long maxTs = null;
|
||||
List<LogEvent> stored = new ArrayList<>(events.size());
|
||||
|
||||
for (Map<String, Object> evt : events) {
|
||||
long ts = toLong(evt.get("timestamp"), now);
|
||||
@@ -570,6 +628,7 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
|
||||
String eventKey = eventKey(region, groupName, streamName, ts, logEvent.getEventId());
|
||||
putForAccount(eventStore, accountId, eventKey, logEvent);
|
||||
stored.add(logEvent);
|
||||
|
||||
totalBytes += msg.getBytes().length + 26; // approx overhead
|
||||
if (minTs == null || ts < minTs) { minTs = ts; }
|
||||
@@ -594,6 +653,9 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
stream.setUploadSequenceToken(nextToken);
|
||||
putForAccount(streamStore, accountId, streamKey, stream);
|
||||
|
||||
if (logEventsIngested != null && !stored.isEmpty()) {
|
||||
logEventsIngested.fire(new LogEventsIngested(accountId, region, groupName, streamName, List.copyOf(stored)));
|
||||
}
|
||||
return nextToken;
|
||||
}
|
||||
|
||||
@@ -1021,24 +1083,80 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
|
||||
// ──────────────────────────── Subscription Filters ────────────────────────────
|
||||
|
||||
/**
|
||||
* The canonical factory-backed metric store is also the shared monitor for both filter
|
||||
* families' check-and-write operations and group creation/deletion. Direct constructors must
|
||||
* supply this same store rather than silently creating a second quota pool.
|
||||
*/
|
||||
StorageBackend<String, MetricFilter> metricFilterStore() {
|
||||
return metricFilterStore;
|
||||
}
|
||||
|
||||
static FilterPattern requireFilterPattern(String filterPattern) {
|
||||
if (filterPattern == null) {
|
||||
throw invalid("filterPattern is required.");
|
||||
}
|
||||
if (filterPattern.length() > MAX_FILTER_PATTERN_LENGTH) {
|
||||
throw invalid("filterPattern must be at most " + MAX_FILTER_PATTERN_LENGTH + " characters.");
|
||||
}
|
||||
try {
|
||||
return FilterPattern.parse(filterPattern);
|
||||
} catch (FilterPatternException e) {
|
||||
throw invalid(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Called with the metric store monitor held through the caller's subsequent write. */
|
||||
void validateFilterRegexQuota(String logGroupName, String filterName, FilterPattern pattern,
|
||||
boolean metricFilter, String region) {
|
||||
if (pattern.regexCount() == 0) {
|
||||
return;
|
||||
}
|
||||
int used = 1;
|
||||
String metricPrefix = region + "::" + logGroupName + "::";
|
||||
for (MetricFilter other : metricFilterStore.scan(k -> k.startsWith(metricPrefix))) {
|
||||
if ((!metricFilter || !filterName.equals(other.getFilterName()))
|
||||
&& requireFilterPattern(other.getFilterPattern()).regexCount() > 0) {
|
||||
used++;
|
||||
}
|
||||
}
|
||||
String subscriptionPrefix = subscriptionFilterKeyPrefix(region, logGroupName);
|
||||
for (SubscriptionFilter other : subscriptionFilterStore.scan(k -> k.startsWith(subscriptionPrefix))) {
|
||||
if ((metricFilter || !filterName.equals(other.getFilterName()))
|
||||
&& requireFilterPattern(other.getFilterPattern()).regexCount() > 0) {
|
||||
used++;
|
||||
}
|
||||
}
|
||||
if (used > MAX_REGEX_FILTERS_PER_LOG_GROUP) {
|
||||
throw new AwsException("LimitExceededException",
|
||||
"The log group " + logGroupName + " already has the maximum of "
|
||||
+ MAX_REGEX_FILTERS_PER_LOG_GROUP + " filters containing regular expressions.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public void putSubscriptionFilter(String logGroupName, String filterName, String filterPattern,
|
||||
String destinationArn, String distribution, String region) {
|
||||
String groupKey = groupKey(region, logGroupName);
|
||||
groupStore.get(groupKey)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + logGroupName, 400));
|
||||
synchronized (metricFilterStore) {
|
||||
String groupKey = groupKey(region, logGroupName);
|
||||
groupStore.get(groupKey)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + logGroupName, 400));
|
||||
String normalizedPattern = filterPattern != null ? filterPattern : "";
|
||||
FilterPattern pattern = requireFilterPattern(normalizedPattern);
|
||||
validateFilterRegexQuota(logGroupName, filterName, pattern, false, region);
|
||||
|
||||
SubscriptionFilter filter = new SubscriptionFilter();
|
||||
filter.setFilterName(filterName);
|
||||
filter.setLogGroupName(logGroupName);
|
||||
filter.setFilterPattern(filterPattern != null ? filterPattern : "");
|
||||
filter.setDestinationArn(destinationArn);
|
||||
filter.setDistribution(distribution != null ? distribution : "ByLogStream");
|
||||
filter.setCreationTime(System.currentTimeMillis());
|
||||
SubscriptionFilter filter = new SubscriptionFilter();
|
||||
filter.setFilterName(filterName);
|
||||
filter.setLogGroupName(logGroupName);
|
||||
filter.setFilterPattern(normalizedPattern);
|
||||
filter.setDestinationArn(destinationArn);
|
||||
filter.setDistribution(distribution != null ? distribution : "ByLogStream");
|
||||
filter.setCreationTime(System.currentTimeMillis());
|
||||
|
||||
String filterKey = subscriptionFilterKey(region, logGroupName, filterName);
|
||||
subscriptionFilterStore.put(filterKey, filter);
|
||||
LOG.infov("Created subscription filter: {0} on log group: {1}", filterName, logGroupName);
|
||||
String filterKey = subscriptionFilterKey(region, logGroupName, filterName);
|
||||
subscriptionFilterStore.put(filterKey, filter);
|
||||
LOG.infov("Created subscription filter: {0} on log group: {1}", filterName, logGroupName);
|
||||
}
|
||||
}
|
||||
|
||||
public record DescribeSubscriptionFiltersResult(List<SubscriptionFilter> subscriptionFilters, String nextToken) {}
|
||||
@@ -1076,17 +1194,19 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public void deleteSubscriptionFilter(String logGroupName, String filterName, String region) {
|
||||
String groupKey = groupKey(region, logGroupName);
|
||||
groupStore.get(groupKey)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + logGroupName, 400));
|
||||
synchronized (metricFilterStore) {
|
||||
String groupKey = groupKey(region, logGroupName);
|
||||
groupStore.get(groupKey)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + logGroupName, 400));
|
||||
|
||||
String filterKey = subscriptionFilterKey(region, logGroupName, filterName);
|
||||
subscriptionFilterStore.get(filterKey)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified subscription filter does not exist: " + filterName, 400));
|
||||
subscriptionFilterStore.delete(filterKey);
|
||||
LOG.infov("Deleted subscription filter: {0} on log group: {1}", filterName, logGroupName);
|
||||
String filterKey = subscriptionFilterKey(region, logGroupName, filterName);
|
||||
subscriptionFilterStore.get(filterKey)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified subscription filter does not exist: " + filterName, 400));
|
||||
subscriptionFilterStore.delete(filterKey);
|
||||
LOG.infov("Deleted subscription filter: {0} on log group: {1}", filterName, logGroupName);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Resource Policies ────────────────────────────
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Fired by {@link CloudWatchLogsService} once a PutLogEvents batch is stored, with the events as
|
||||
* stored, so the features AWS drives from ingestion (metric filters today) run without the log
|
||||
* service knowing about them. {@code accountId} is the account the batch was written for when the
|
||||
* writer named one, as a container streaming logs outside any request does, and null when the
|
||||
* batch belongs to the caller's own account.
|
||||
*/
|
||||
public record LogEventsIngested(String accountId, String region, String logGroupName, String logStreamName,
|
||||
List<LogEvent> events) {}
|
||||
@@ -0,0 +1,4 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
/** Fired by {@link CloudWatchLogsService} once a log group is deleted, so what hangs off the group goes with it. */
|
||||
public record LogGroupDeleted(String region, String logGroupName) {}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.filter.FilterPatternException;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.filter.SystemFieldSelection;
|
||||
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.model.Dimension;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The rules PutMetricFilter applies to the three options that describe a filter rather than its
|
||||
* pattern: {@code emitSystemFieldDimensions}, {@code fieldSelectionCriteria} and the dimensions
|
||||
* they share a limit with, plus what those options do at ingestion. They live beside
|
||||
* {@link CloudWatchLogsMetricFilterService} so the service keeps to storing filters and publishing
|
||||
* their metrics.
|
||||
*
|
||||
* <p>{@code applyOnTransformedLogs} has no rule here on purpose. It selects the transformed view of
|
||||
* a log group that has a log transformer, Floci has no transformers, and the Logs API documents no
|
||||
* error for setting it without one, so it is stored and returned unchanged.
|
||||
*/
|
||||
final class MetricFilterRules {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(MetricFilterRules.class);
|
||||
|
||||
/** A metric value or default value written as a number, rather than a field of the pattern. */
|
||||
static final Pattern NUMBER = Pattern.compile("[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?");
|
||||
|
||||
private MetricFilterRules() {
|
||||
}
|
||||
|
||||
/** AWS's cap on dimensions per metric filter. */
|
||||
public static final int MAX_DIMENSIONS = 3;
|
||||
|
||||
private static final int MAX_FIELD_SELECTION_CRITERIA_LENGTH = 2000;
|
||||
|
||||
private static final String ACCOUNT_FIELD = "@aws.account";
|
||||
private static final String REGION_FIELD = "@aws.region";
|
||||
private static final Set<String> SYSTEM_FIELDS = Set.of(ACCOUNT_FIELD, REGION_FIELD);
|
||||
|
||||
static void validateSystemFields(List<String> systemFields, MetricTransformation t) {
|
||||
if (systemFields == null) {
|
||||
return;
|
||||
}
|
||||
for (String field : systemFields) {
|
||||
if (field == null || !SYSTEM_FIELDS.contains(field)) {
|
||||
throw invalid("emitSystemFieldDimensions must contain only @aws.account and @aws.region, got '"
|
||||
+ field + "'.");
|
||||
}
|
||||
}
|
||||
int dimensions = t.getDimensions() == null ? 0 : t.getDimensions().size();
|
||||
if (dimensions + systemFields.size() > MAX_DIMENSIONS) {
|
||||
throw invalid("System field dimensions count toward the limit of " + MAX_DIMENSIONS
|
||||
+ " dimensions per metric filter.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A criterion selects which events the filter processes from the batch's system fields, so it
|
||||
* has to parse before it is stored; AWS caps it at 2000 characters.
|
||||
*/
|
||||
static void validateFieldSelectionCriteria(String criteria) {
|
||||
if (criteria == null || criteria.isBlank()) {
|
||||
return;
|
||||
}
|
||||
if (criteria.length() > MAX_FIELD_SELECTION_CRITERIA_LENGTH) {
|
||||
throw invalid("fieldSelectionCriteria must be at most " + MAX_FIELD_SELECTION_CRITERIA_LENGTH
|
||||
+ " characters.");
|
||||
}
|
||||
try {
|
||||
SystemFieldSelection.parse(criteria);
|
||||
} catch (FilterPatternException e) {
|
||||
throw invalid("fieldSelectionCriteria is not valid: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a batch is one this filter processes. A filter with no selection criteria processes
|
||||
* every batch. Corrupted stored criteria are logged and skipped, never treated as selecting
|
||||
* every account and Region.
|
||||
*/
|
||||
static boolean selects(MetricFilter filter, String account, String region) {
|
||||
String criteria = filter.getFieldSelectionCriteria();
|
||||
if (criteria == null || criteria.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
return SystemFieldSelection.parse(criteria).test(account, region);
|
||||
} catch (FilterPatternException unparsable) {
|
||||
LOG.warnv("Skipping metric filter {0} on log group {1} in account {2}, Region {3}: "
|
||||
+ "fieldSelectionCriteria no longer parses: {4}",
|
||||
filter.getFilterName(), filter.getLogGroupName(), account, region, unparsable.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the system fields the filter emits as dimensions to the ones its transformation
|
||||
* names. AWS counts both against the same limit of three, which {@code validateSystemFields}
|
||||
* enforces when the filter is stored.
|
||||
*/
|
||||
static List<Dimension> withSystemDimensions(MetricFilter filter, String account, String region,
|
||||
List<Dimension> dimensions) {
|
||||
List<String> fields = filter.getEmitSystemFieldDimensions();
|
||||
if (fields == null) {
|
||||
return dimensions;
|
||||
}
|
||||
for (String field : fields) {
|
||||
if (ACCOUNT_FIELD.equals(field)) {
|
||||
dimensions.add(new Dimension(field, account));
|
||||
} else if (REGION_FIELD.equals(field)) {
|
||||
dimensions.add(new Dimension(field, region));
|
||||
}
|
||||
}
|
||||
return dimensions;
|
||||
}
|
||||
|
||||
static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidParameterException", message, 400);
|
||||
}
|
||||
|
||||
static Double number(String text) {
|
||||
if (text == null || !NUMBER.matcher(text).matches()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
double value = Double.parseDouble(text);
|
||||
return Double.isFinite(value) ? value : null;
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
/**
|
||||
* The regular expression subset CloudWatch Logs accepts between percent signs: letters, digits, a
|
||||
* short list of symbols, the operators {@code ^ $ ? [ ] { } | \ * + .} and the escapes {@code \d \D
|
||||
* \s \S \w \W \xhh}. Parentheses, other symbols and characters outside ASCII are rejected, as AWS
|
||||
* rejects them. What passes is Java regex syntax with the same meaning, so it compiles as is.
|
||||
*/
|
||||
final class AwsRegex {
|
||||
|
||||
private static final String SYMBOLS = ":_#=@/;,- ";
|
||||
private static final String OPERATORS = "^$?[]{}|\\*+.";
|
||||
private static final String ESCAPES = "dDsSwW";
|
||||
|
||||
private final Pattern pattern;
|
||||
|
||||
private AwsRegex(Pattern pattern) {
|
||||
this.pattern = pattern;
|
||||
}
|
||||
|
||||
static AwsRegex compile(String body) {
|
||||
if (body.isEmpty()) {
|
||||
throw new FilterPatternException("Invalid filter pattern: empty regular expression");
|
||||
}
|
||||
boolean characterClass = false;
|
||||
boolean quantifier = false;
|
||||
for (int i = 0; i < body.length(); i++) {
|
||||
char c = body.charAt(i);
|
||||
if (c == '\\') {
|
||||
i = checkEscape(body, i);
|
||||
quantifier = false;
|
||||
continue;
|
||||
}
|
||||
if (c > 127) {
|
||||
throw new FilterPatternException("Invalid filter pattern: regular expressions support ASCII only, found '" + c + "'");
|
||||
}
|
||||
boolean allowed = Character.isLetterOrDigit(c) || SYMBOLS.indexOf(c) >= 0 || OPERATORS.indexOf(c) >= 0;
|
||||
if (!allowed) {
|
||||
throw new FilterPatternException("Invalid filter pattern: '" + c + "' is not supported in a regular expression");
|
||||
}
|
||||
if (c == '[') {
|
||||
characterClass = true;
|
||||
} else if (c == ']') {
|
||||
characterClass = false;
|
||||
}
|
||||
if (!characterClass && c == '+' && quantifier) {
|
||||
throw new FilterPatternException("Invalid filter pattern: possessive quantifiers are not supported");
|
||||
}
|
||||
quantifier = !characterClass && (c == '*' || c == '+' || c == '?' || c == '}');
|
||||
}
|
||||
try {
|
||||
return new AwsRegex(Pattern.compile(body));
|
||||
} catch (PatternSyntaxException e) {
|
||||
throw new FilterPatternException("Invalid filter pattern: bad regular expression '" + body + "': "
|
||||
+ e.getDescription());
|
||||
}
|
||||
}
|
||||
|
||||
/** Validates the escape starting at {@code index} and returns the index of its last character. */
|
||||
private static int checkEscape(String body, int index) {
|
||||
if (index + 1 >= body.length()) {
|
||||
throw new FilterPatternException("Invalid filter pattern: regular expression ends with a backslash");
|
||||
}
|
||||
char escaped = body.charAt(index + 1);
|
||||
if (escaped == 'x') {
|
||||
if (index + 3 < body.length() && isHex(body.charAt(index + 2)) && isHex(body.charAt(index + 3))) {
|
||||
return index + 3;
|
||||
}
|
||||
throw new FilterPatternException("Invalid filter pattern: \\x needs two hexadecimal digits");
|
||||
}
|
||||
if (Character.isLetterOrDigit(escaped)) {
|
||||
if (ESCAPES.indexOf(escaped) < 0) {
|
||||
throw new FilterPatternException("Invalid filter pattern: '\\" + escaped + "' is not a supported escape");
|
||||
}
|
||||
return index + 1;
|
||||
}
|
||||
// A backslash gives an operator its literal meaning; it does not admit characters AWS
|
||||
// rejects, so an escaped parenthesis or exclamation mark is still rejected.
|
||||
if (OPERATORS.indexOf(escaped) < 0 && SYMBOLS.indexOf(escaped) < 0) {
|
||||
throw new FilterPatternException("Invalid filter pattern: '" + escaped
|
||||
+ "' is not supported in a regular expression, escaped or not");
|
||||
}
|
||||
return index + 1;
|
||||
}
|
||||
|
||||
private static boolean isHex(char c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||
}
|
||||
|
||||
boolean find(String text) {
|
||||
return pattern.matcher(text).find();
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* A boolean expression over one log event, shared by the JSON and space-delimited syntaxes: atoms
|
||||
* joined with {@code &&} and {@code ||}, grouped with parentheses, {@code &&} binding tighter.
|
||||
* System-field selection opts into keyword operators without changing either log grammar.
|
||||
* {@code C} is what an atom is evaluated against, a parsed JSON document or the event's fields.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
interface Condition<C> {
|
||||
|
||||
boolean test(C context);
|
||||
|
||||
static <C> Condition<C> and(List<Condition<C>> operands) {
|
||||
return context -> operands.stream().allMatch(operand -> operand.test(context));
|
||||
}
|
||||
|
||||
static <C> Condition<C> or(List<Condition<C>> operands) {
|
||||
return context -> operands.stream().anyMatch(operand -> operand.test(context));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses {@code or := and ('||' and)*; and := unary ('&&' unary)*; unary := '(' or ')' | atom}
|
||||
* at the cursor, reading atoms through {@code atom}.
|
||||
*/
|
||||
static <C> Condition<C> parse(PatternCursor cursor, Function<PatternCursor, Condition<C>> atom) {
|
||||
return parse(cursor, atom, false);
|
||||
}
|
||||
|
||||
static <C> Condition<C> parse(PatternCursor cursor, Function<PatternCursor, Condition<C>> atom,
|
||||
boolean keywordOperators) {
|
||||
List<Condition<C>> alternatives = new ArrayList<>();
|
||||
do {
|
||||
alternatives.add(parseAnd(cursor, atom, keywordOperators));
|
||||
cursor.skipWhitespace();
|
||||
} while (cursor.consume("||") || keywordOperators && cursor.consumeKeyword("OR"));
|
||||
return alternatives.size() == 1 ? alternatives.getFirst() : or(alternatives);
|
||||
}
|
||||
|
||||
private static <C> Condition<C> parseAnd(PatternCursor cursor, Function<PatternCursor, Condition<C>> atom,
|
||||
boolean keywordOperators) {
|
||||
List<Condition<C>> operands = new ArrayList<>();
|
||||
do {
|
||||
operands.add(parseUnary(cursor, atom, keywordOperators));
|
||||
cursor.skipWhitespace();
|
||||
} while (cursor.consume("&&") || keywordOperators && cursor.consumeKeyword("AND"));
|
||||
return operands.size() == 1 ? operands.getFirst() : and(operands);
|
||||
}
|
||||
|
||||
private static <C> Condition<C> parseUnary(PatternCursor cursor, Function<PatternCursor, Condition<C>> atom,
|
||||
boolean keywordOperators) {
|
||||
cursor.skipWhitespace();
|
||||
if (cursor.consume("(")) {
|
||||
Condition<C> inner = parse(cursor, atom, keywordOperators);
|
||||
cursor.expect(')');
|
||||
return inner;
|
||||
}
|
||||
return atom.apply(cursor);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* The outcome of matching one log event message against a {@link FilterPattern}: whether it
|
||||
* matched, the values the pattern extracted (what {@code TestMetricFilter} reports), and a way to
|
||||
* read any field of the event by reference, which is how a metric filter finds its metric value
|
||||
* ({@code $.latency}, {@code $bytes}) and its dimensions.
|
||||
*/
|
||||
public final class FilterMatch {
|
||||
|
||||
public static final FilterMatch NONE = new FilterMatch(false, Map.of(), reference -> null);
|
||||
|
||||
private final boolean matched;
|
||||
private final Map<String, String> extractedValues;
|
||||
private final Function<String, String> values;
|
||||
|
||||
FilterMatch(boolean matched, Map<String, String> extractedValues, Function<String, String> values) {
|
||||
this.matched = matched;
|
||||
this.extractedValues = Collections.unmodifiableMap(extractedValues);
|
||||
this.values = values;
|
||||
}
|
||||
|
||||
static FilterMatch of(Map<String, String> extractedValues, Function<String, String> values) {
|
||||
return new FilterMatch(true, extractedValues, values);
|
||||
}
|
||||
|
||||
public boolean matched() {
|
||||
return matched;
|
||||
}
|
||||
|
||||
/** The named values the pattern pulled out of the event, in pattern order; empty for term patterns. */
|
||||
public Map<String, String> extractedValues() {
|
||||
return extractedValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* The text of the event field a reference names ({@code $.path} for a JSON event, {@code $name}
|
||||
* or {@code $3} for a space-delimited one), or null when the event has no such scalar field.
|
||||
*/
|
||||
public String value(String reference) {
|
||||
return reference == null ? null : values.apply(reference);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A CloudWatch Logs filter pattern, parsed once and matched against many log event messages. The
|
||||
* four syntaxes AWS documents are told apart by the first character: {@code {} is a JSON pattern,
|
||||
* {@code [} a space-delimited one, a blank pattern matches everything, and anything else is a list
|
||||
* of terms.
|
||||
*
|
||||
* <p>Instances are immutable and safe to share between threads.
|
||||
*/
|
||||
public abstract class FilterPattern {
|
||||
|
||||
public enum Kind { MATCH_ALL, TERMS, JSON, SPACE_DELIMITED }
|
||||
|
||||
/** AWS's quota on regular expressions in one pattern. */
|
||||
static final int MAX_REGEXES = 2;
|
||||
|
||||
private static final FilterPattern MATCH_ALL = new FilterPattern() {
|
||||
@Override
|
||||
public Kind kind() {
|
||||
return Kind.MATCH_ALL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FilterMatch match(String message) {
|
||||
return FilterMatch.of(Map.of(), reference -> null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean declaresField(String reference) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** Parses a pattern, throwing {@link FilterPatternException} when it does not follow the syntax. */
|
||||
public static FilterPattern parse(String pattern) {
|
||||
String text = pattern == null ? "" : pattern.strip();
|
||||
FilterPattern parsed;
|
||||
if (text.isEmpty()) {
|
||||
return MATCH_ALL;
|
||||
} else if (text.startsWith("{")) {
|
||||
parsed = JsonPattern.of(text);
|
||||
} else if (text.startsWith("[")) {
|
||||
parsed = SpaceDelimitedPattern.of(text);
|
||||
} else {
|
||||
parsed = TermPattern.of(text);
|
||||
}
|
||||
if (parsed.regexCount() > MAX_REGEXES) {
|
||||
throw new FilterPatternException("Invalid filter pattern: at most " + MAX_REGEXES
|
||||
+ " regular expressions are allowed in a filter pattern");
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
public abstract Kind kind();
|
||||
|
||||
/** Matches one message; never throws, an event the pattern cannot read simply does not match. */
|
||||
public abstract FilterMatch match(String message);
|
||||
|
||||
/**
|
||||
* Whether a field reference can be read off this pattern's matches: any
|
||||
* {@code $.path} for a JSON pattern, a declared {@code $name} or a position {@code $3} for a
|
||||
* space-delimited one, nothing for the others.
|
||||
*/
|
||||
public abstract boolean declaresField(String reference);
|
||||
|
||||
/** Whether a reference addresses one field rather than a wildcard selection. */
|
||||
public boolean declaresSingleValueField(String reference) {
|
||||
return declaresField(reference);
|
||||
}
|
||||
|
||||
/** How many {@code %regex%} the pattern holds, for the per-pattern and per-log-group quotas. */
|
||||
public int regexCount() {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
/** A filter pattern that does not follow the CloudWatch Logs syntax; the message says where. */
|
||||
public class FilterPatternException extends IllegalArgumentException {
|
||||
|
||||
public FilterPatternException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A pattern in curly braces over a JSON log event: conditions on property selectors, each a
|
||||
* comparison with a literal, {@code IS NULL}, {@code IS TRUE}, {@code IS FALSE} or
|
||||
* {@code NOT EXISTS}, joined with {@code &&} and {@code ||}. A comparison holds when any node the
|
||||
* selector points at is a scalar that satisfies it; an object, an array or a missing property
|
||||
* satisfies no scalar comparison. Wildcard inequality excludes a match if any selected value
|
||||
* equals the literal.
|
||||
*/
|
||||
final class JsonPattern extends FilterPattern {
|
||||
|
||||
private static final ObjectReader JSON = new ObjectMapper()
|
||||
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
|
||||
.readerFor(JsonNode.class);
|
||||
|
||||
/** AWS's quota on wildcard selectors in one filter pattern. */
|
||||
private static final int MAX_WILDCARDS = 3;
|
||||
|
||||
private final Condition<JsonNode> condition;
|
||||
private final int regexes;
|
||||
|
||||
private JsonPattern(Condition<JsonNode> condition, int regexes) {
|
||||
this.condition = condition;
|
||||
this.regexes = regexes;
|
||||
}
|
||||
|
||||
static JsonPattern of(String text) {
|
||||
PatternCursor cursor = new PatternCursor(text);
|
||||
cursor.expect('{');
|
||||
int[] regexes = {0};
|
||||
int[] wildcards = {0};
|
||||
Condition<JsonNode> condition = Condition.parse(cursor, c -> atom(c, regexes, wildcards));
|
||||
if (wildcards[0] > MAX_WILDCARDS) {
|
||||
throw new FilterPatternException("Invalid filter pattern: at most " + MAX_WILDCARDS
|
||||
+ " wildcard selectors are allowed in a filter pattern");
|
||||
}
|
||||
cursor.expect('}');
|
||||
cursor.expectEnd();
|
||||
return new JsonPattern(condition, regexes[0]);
|
||||
}
|
||||
|
||||
private static Condition<JsonNode> atom(PatternCursor cursor, int[] regexes, int[] wildcards) {
|
||||
JsonSelector selector = JsonSelector.read(cursor);
|
||||
wildcards[0] += selector.wildcards();
|
||||
cursor.skipWhitespace();
|
||||
if (Character.isLetter(cursor.peek())) {
|
||||
String keyword = cursor.identifier().toUpperCase();
|
||||
if (keyword.equals("IS")) {
|
||||
String state = cursor.identifier().toUpperCase();
|
||||
return switch (state) {
|
||||
case "NULL" -> root -> selector.resolve(root).stream()
|
||||
.anyMatch(node -> isNull(node, selector.wildcards() == 0));
|
||||
case "TRUE" -> root -> selector.resolve(root).stream()
|
||||
.anyMatch(node -> node.isBoolean() && node.booleanValue());
|
||||
case "FALSE" -> root -> selector.resolve(root).stream()
|
||||
.anyMatch(node -> node.isBoolean() && !node.booleanValue());
|
||||
default -> throw cursor.error("IS must be followed by NULL, TRUE or FALSE");
|
||||
};
|
||||
}
|
||||
if (keyword.equals("NOT")) {
|
||||
if (!cursor.identifier().equalsIgnoreCase("EXISTS")) {
|
||||
throw cursor.error("NOT must be followed by EXISTS");
|
||||
}
|
||||
return root -> selector.resolve(root).isEmpty();
|
||||
}
|
||||
throw cursor.error("expected a comparison operator, IS or NOT EXISTS");
|
||||
}
|
||||
Literal.Operator op = Literal.Operator.read(cursor);
|
||||
Literal literal = Literal.read(cursor, "&|)}");
|
||||
literal.validateOperator(op);
|
||||
if (literal.isRegex()) {
|
||||
regexes[0]++;
|
||||
}
|
||||
if (op == Literal.Operator.NE && selector.wildcards() > 0) {
|
||||
return root -> selector.wildcardParentExists(root) && selector.resolve(root).stream()
|
||||
.noneMatch(node -> literal.test(Literal.Operator.EQ, node));
|
||||
}
|
||||
return root -> selector.resolve(root).stream().anyMatch(node -> literal.test(op, node));
|
||||
}
|
||||
|
||||
private static boolean isNull(JsonNode node, boolean includeArrayElements) {
|
||||
if (node.isNull()) {
|
||||
return true;
|
||||
}
|
||||
if (includeArrayElements && node.isArray()) {
|
||||
for (JsonNode element : node) {
|
||||
if (element.isNull()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Kind kind() {
|
||||
return Kind.JSON;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FilterMatch match(String message) {
|
||||
JsonNode root;
|
||||
try {
|
||||
root = message == null ? null : JSON.readValue(message);
|
||||
} catch (JsonProcessingException e) {
|
||||
return FilterMatch.NONE;
|
||||
}
|
||||
if (root == null || !root.isObject() || !condition.test(root)) {
|
||||
return FilterMatch.NONE;
|
||||
}
|
||||
return FilterMatch.of(Map.of(), reference -> {
|
||||
JsonSelector selector = JsonSelector.parse(reference);
|
||||
return selector == null ? null : selector.firstScalar(root);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean declaresField(String reference) {
|
||||
return JsonSelector.parse(reference) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean declaresSingleValueField(String reference) {
|
||||
JsonSelector selector = JsonSelector.parse(reference);
|
||||
return selector != null && selector.wildcards() == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int regexCount() {
|
||||
return regexes;
|
||||
}
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A property selector of a JSON pattern: {@code $} followed by {@code .name}, {@code [index]},
|
||||
* the wildcard {@code .*} or {@code [*]} for every field or element, and {@code ['name.with.dots']}
|
||||
* for a property a dot could not name. Resolving it against a document yields the nodes it points
|
||||
* at, several when a wildcard is used.
|
||||
*/
|
||||
final class JsonSelector {
|
||||
|
||||
private static final String SELECTOR_END = " \t\r\n=!<>)}&|,";
|
||||
|
||||
/** AWS's quota on wildcards in one property selector. */
|
||||
private static final int MAX_WILDCARDS = 1;
|
||||
|
||||
private sealed interface Segment permits Name, Index, Wildcard {}
|
||||
|
||||
private record Name(String name) implements Segment {}
|
||||
|
||||
private record Index(int index) implements Segment {}
|
||||
|
||||
private record Wildcard() implements Segment {}
|
||||
|
||||
private final String text;
|
||||
private final List<Segment> segments;
|
||||
private final int wildcards;
|
||||
|
||||
private JsonSelector(String text, List<Segment> segments) {
|
||||
this.text = text;
|
||||
this.segments = segments;
|
||||
this.wildcards = (int) segments.stream().filter(Wildcard.class::isInstance).count();
|
||||
}
|
||||
|
||||
/** Reads the selector at the cursor, which must start with {@code $}. */
|
||||
static JsonSelector read(PatternCursor cursor) {
|
||||
cursor.skipWhitespace();
|
||||
if (cursor.peek() != '$') {
|
||||
throw cursor.error("expected a property selector starting with '$'");
|
||||
}
|
||||
StringBuilder text = new StringBuilder("$");
|
||||
cursor.next();
|
||||
if (cursor.peek() != '.') {
|
||||
throw cursor.error("expected '.' after '$'");
|
||||
}
|
||||
List<Segment> segments = new ArrayList<>();
|
||||
while (!cursor.atEnd() && SELECTOR_END.indexOf(cursor.peek()) < 0) {
|
||||
char c = cursor.next();
|
||||
text.append(c);
|
||||
if (c == '.') {
|
||||
if (cursor.peek() == '[') {
|
||||
continue;
|
||||
}
|
||||
segments.add(readName(cursor, text));
|
||||
} else if (c == '[') {
|
||||
segments.add(readBracket(cursor, text));
|
||||
} else {
|
||||
throw cursor.error("unexpected '" + c + "' in a property selector");
|
||||
}
|
||||
}
|
||||
JsonSelector selector = new JsonSelector(text.toString(), List.copyOf(segments));
|
||||
if (segments.isEmpty()) {
|
||||
throw cursor.error("expected a property name");
|
||||
}
|
||||
if (selector.wildcards() > MAX_WILDCARDS) {
|
||||
throw cursor.error("at most " + MAX_WILDCARDS + " wildcard is allowed in a property selector");
|
||||
}
|
||||
return selector;
|
||||
}
|
||||
|
||||
/** Parses a whole reference such as {@code $.latency}, or returns null when it is not a selector. */
|
||||
static JsonSelector parse(String reference) {
|
||||
if (reference == null || !reference.startsWith("$.")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
PatternCursor cursor = new PatternCursor(reference);
|
||||
JsonSelector selector = read(cursor);
|
||||
return cursor.atEnd() ? selector : null;
|
||||
} catch (FilterPatternException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Segment readName(PatternCursor cursor, StringBuilder text) {
|
||||
if (cursor.peek() == '*') {
|
||||
text.append(cursor.next());
|
||||
return new Wildcard();
|
||||
}
|
||||
StringBuilder name = new StringBuilder();
|
||||
while (!cursor.atEnd() && (Character.isLetterOrDigit(cursor.peek()) || cursor.peek() == '_'
|
||||
|| cursor.peek() == '-')) {
|
||||
name.append(cursor.next());
|
||||
}
|
||||
if (name.isEmpty()) {
|
||||
throw cursor.error("expected a property name after '.'");
|
||||
}
|
||||
text.append(name);
|
||||
return new Name(name.toString());
|
||||
}
|
||||
|
||||
private static Segment readBracket(PatternCursor cursor, StringBuilder text) {
|
||||
Segment segment;
|
||||
if (cursor.peek() == '\'') {
|
||||
char quote = cursor.next();
|
||||
StringBuilder name = new StringBuilder();
|
||||
while (!cursor.atEnd() && cursor.peek() != quote) {
|
||||
name.append(cursor.next());
|
||||
}
|
||||
if (cursor.atEnd()) {
|
||||
throw cursor.error("unterminated quoted property name");
|
||||
}
|
||||
cursor.next();
|
||||
text.append(quote).append(name).append(quote);
|
||||
segment = new Name(name.toString());
|
||||
} else if (cursor.peek() == '*') {
|
||||
text.append(cursor.next());
|
||||
segment = new Wildcard();
|
||||
} else {
|
||||
StringBuilder digits = new StringBuilder();
|
||||
while (!cursor.atEnd() && Character.isDigit(cursor.peek())) {
|
||||
digits.append(cursor.next());
|
||||
}
|
||||
if (digits.isEmpty()) {
|
||||
throw cursor.error("expected an array index, '*' or a quoted property name inside '[ ]'");
|
||||
}
|
||||
text.append(digits);
|
||||
try {
|
||||
segment = new Index(Integer.parseInt(digits.toString()));
|
||||
} catch (NumberFormatException e) {
|
||||
throw cursor.error("array index " + digits + " is too large");
|
||||
}
|
||||
}
|
||||
if (cursor.peek() != ']') {
|
||||
throw cursor.error("expected ']'");
|
||||
}
|
||||
text.append(cursor.next());
|
||||
return segment;
|
||||
}
|
||||
|
||||
String text() {
|
||||
return text;
|
||||
}
|
||||
|
||||
/** How many {@code .*} or {@code [*]} the selector holds, for the quota. */
|
||||
int wildcards() {
|
||||
return wildcards;
|
||||
}
|
||||
|
||||
/** The nodes the selector points at in {@code root}; empty when the path is absent. */
|
||||
List<JsonNode> resolve(JsonNode root) {
|
||||
List<JsonNode> current = List.of(root);
|
||||
for (Segment segment : segments) {
|
||||
List<JsonNode> next = new ArrayList<>();
|
||||
for (JsonNode node : current) {
|
||||
step(node, segment, next);
|
||||
}
|
||||
if (next.isEmpty()) {
|
||||
return next;
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
boolean wildcardParentExists(JsonNode root) {
|
||||
List<JsonNode> current = List.of(root);
|
||||
for (Segment segment : segments) {
|
||||
if (segment instanceof Wildcard) {
|
||||
return !current.isEmpty();
|
||||
}
|
||||
List<JsonNode> next = new ArrayList<>();
|
||||
for (JsonNode node : current) {
|
||||
step(node, segment, next);
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void step(JsonNode node, Segment segment, List<JsonNode> into) {
|
||||
switch (segment) {
|
||||
case Name name -> {
|
||||
JsonNode child = node.isObject() ? node.get(name.name()) : null;
|
||||
if (child != null) {
|
||||
into.add(child);
|
||||
}
|
||||
}
|
||||
case Index index -> {
|
||||
if (node.isArray() && index.index() < node.size()) {
|
||||
into.add(node.get(index.index()));
|
||||
}
|
||||
}
|
||||
case Wildcard wildcard -> {
|
||||
if (node.isObject() || node.isArray()) {
|
||||
node.forEach(into::add);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The text of the first scalar node the selector points at, or null. */
|
||||
String firstScalar(JsonNode root) {
|
||||
for (JsonNode node : resolve(root)) {
|
||||
if (node.isValueNode() && !node.isNull()) {
|
||||
return node.asText();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The right-hand side of a JSON or space-delimited condition, and how it compares with a value from
|
||||
* a log event. A quoted or bare word compares as text, a word with an asterisk as a wildcard, a
|
||||
* number by value, and a {@code %regex%} by search. JSON strings compare with the literal's text,
|
||||
* never by numeric coercion. Space-delimited numeric fields compare by value. Ordering requires
|
||||
* a numeric literal and, for JSON events, a numeric node.
|
||||
*/
|
||||
final class Literal {
|
||||
|
||||
enum Operator {
|
||||
EQ("="), NE("!="), LT("<"), LE("<="), GT(">"), GE(">=");
|
||||
|
||||
private final String token;
|
||||
|
||||
Operator(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
/** Reads the longest operator at the cursor, or throws. */
|
||||
static Operator read(PatternCursor cursor) {
|
||||
cursor.skipWhitespace();
|
||||
for (Operator op : new Operator[] {NE, LE, GE, EQ, LT, GT}) {
|
||||
if (cursor.consume(op.token)) {
|
||||
if (op == EQ && cursor.peek() == '=') {
|
||||
throw cursor.error("'==' is not an operator, use '='");
|
||||
}
|
||||
return op;
|
||||
}
|
||||
}
|
||||
throw cursor.error("expected a comparison operator");
|
||||
}
|
||||
}
|
||||
|
||||
private static final Pattern NUMBER = Pattern.compile("[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?");
|
||||
|
||||
private final String text;
|
||||
private final BigDecimal number;
|
||||
private final Pattern glob;
|
||||
private final AwsRegex regex;
|
||||
|
||||
private Literal(String text, BigDecimal number, Pattern glob, AwsRegex regex) {
|
||||
this.text = text;
|
||||
this.number = number;
|
||||
this.glob = glob;
|
||||
this.regex = regex;
|
||||
}
|
||||
|
||||
/** A quoted value: text, or a wildcard when it holds an asterisk. */
|
||||
static Literal quoted(String text) {
|
||||
return new Literal(text, null, globOf(text), null);
|
||||
}
|
||||
|
||||
/** A bare value: a number, a wildcard, or a word. */
|
||||
static Literal bare(String text) {
|
||||
if (NUMBER.matcher(text).matches()) {
|
||||
try {
|
||||
int exponent = Math.max(text.indexOf('e'), text.indexOf('E'));
|
||||
if (exponent >= 0) {
|
||||
Integer.parseInt(text.substring(exponent + 1));
|
||||
}
|
||||
return new Literal(text, new BigDecimal(text), null, null);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new FilterPatternException("Invalid filter pattern: numeric literal is out of range");
|
||||
}
|
||||
}
|
||||
if (text.equals("null") || !text.matches("[\\p{L}\\p{N}_.*-]+")) {
|
||||
throw new FilterPatternException("Invalid filter pattern: invalid unquoted value '" + text + "'");
|
||||
}
|
||||
return new Literal(text, null, globOf(text), null);
|
||||
}
|
||||
|
||||
static Literal regex(AwsRegex regex) {
|
||||
return new Literal(null, null, null, regex);
|
||||
}
|
||||
|
||||
/** Reads a quoted string, a {@code %regex%} or a bare value from the cursor. */
|
||||
static Literal read(PatternCursor cursor, String bareDelimiters) {
|
||||
cursor.skipWhitespace();
|
||||
if (cursor.peek() == '"') {
|
||||
return quoted(cursor.quoted());
|
||||
}
|
||||
if (cursor.peek() == '%') {
|
||||
return regex(cursor.regex());
|
||||
}
|
||||
return bare(cursor.bareValue(bareDelimiters));
|
||||
}
|
||||
|
||||
private static Pattern globOf(String text) {
|
||||
if (text.indexOf('*') < 0) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder regex = new StringBuilder();
|
||||
for (String piece : text.split("\\*", -1)) {
|
||||
if (!regex.isEmpty()) {
|
||||
regex.append(".*");
|
||||
}
|
||||
regex.append(Pattern.quote(piece));
|
||||
}
|
||||
return Pattern.compile(regex.toString(), Pattern.DOTALL);
|
||||
}
|
||||
|
||||
boolean isRegex() {
|
||||
return regex != null;
|
||||
}
|
||||
|
||||
void validateOperator(Operator op) {
|
||||
if (op != Operator.EQ && op != Operator.NE && number == null) {
|
||||
throw new FilterPatternException("Invalid filter pattern: ordering requires a numeric literal");
|
||||
}
|
||||
}
|
||||
|
||||
boolean test(Operator op, JsonNode node) {
|
||||
if (!node.isTextual() && !node.isNumber()) {
|
||||
return false;
|
||||
}
|
||||
if (number != null) {
|
||||
if (node.isTextual()) {
|
||||
return switch (op) {
|
||||
case EQ -> text.equals(node.textValue());
|
||||
case NE -> !text.equals(node.textValue());
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
if (!Double.isFinite(node.doubleValue())) {
|
||||
return false;
|
||||
}
|
||||
return compare(op, node.decimalValue().compareTo(number));
|
||||
}
|
||||
return test(op, node.asText());
|
||||
}
|
||||
|
||||
/** Whether the value from the event satisfies {@code op} against this literal. */
|
||||
boolean test(Operator op, String value) {
|
||||
return switch (op) {
|
||||
case EQ -> equalTo(value);
|
||||
case NE -> !equalTo(value);
|
||||
case LT, LE, GT, GE -> orders(op, value);
|
||||
};
|
||||
}
|
||||
|
||||
private boolean equalTo(String value) {
|
||||
if (regex != null) {
|
||||
return regex.find(value);
|
||||
}
|
||||
if (number != null) {
|
||||
BigDecimal actual = parse(value);
|
||||
return actual != null && actual.compareTo(number) == 0;
|
||||
}
|
||||
if (glob != null) {
|
||||
return glob.matcher(value).matches();
|
||||
}
|
||||
return text.equals(value);
|
||||
}
|
||||
|
||||
private boolean orders(Operator op, String value) {
|
||||
BigDecimal actual = number == null ? null : parse(value);
|
||||
if (actual == null) {
|
||||
return false;
|
||||
}
|
||||
return compare(op, actual.compareTo(number));
|
||||
}
|
||||
|
||||
private static boolean compare(Operator op, int comparison) {
|
||||
return switch (op) {
|
||||
case EQ -> comparison == 0;
|
||||
case NE -> comparison != 0;
|
||||
case LT -> comparison < 0;
|
||||
case LE -> comparison <= 0;
|
||||
case GT -> comparison > 0;
|
||||
case GE -> comparison >= 0;
|
||||
};
|
||||
}
|
||||
|
||||
private static BigDecimal parse(String value) {
|
||||
if (!NUMBER.matcher(value).matches()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new BigDecimal(value);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
/** A position in the pattern text for the recursive descent parsers, with the small reads they share. */
|
||||
final class PatternCursor {
|
||||
|
||||
private final String text;
|
||||
private int position;
|
||||
|
||||
PatternCursor(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
boolean atEnd() {
|
||||
return position >= text.length();
|
||||
}
|
||||
|
||||
char peek() {
|
||||
return atEnd() ? '\0' : text.charAt(position);
|
||||
}
|
||||
|
||||
boolean lookingAt(String token) {
|
||||
return text.startsWith(token, position);
|
||||
}
|
||||
|
||||
char next() {
|
||||
if (atEnd()) {
|
||||
throw error("unexpected end of pattern");
|
||||
}
|
||||
return text.charAt(position++);
|
||||
}
|
||||
|
||||
void skipWhitespace() {
|
||||
while (!atEnd() && Character.isWhitespace(peek())) {
|
||||
position++;
|
||||
}
|
||||
}
|
||||
|
||||
void expect(char c) {
|
||||
skipWhitespace();
|
||||
if (peek() != c) {
|
||||
throw error("expected '" + c + "'");
|
||||
}
|
||||
position++;
|
||||
}
|
||||
|
||||
/** Consumes {@code token} if it is next, reporting whether it was. */
|
||||
boolean consume(String token) {
|
||||
if (lookingAt(token)) {
|
||||
position += token.length();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean consumeKeyword(String keyword) {
|
||||
int end = position + keyword.length();
|
||||
if (!lookingAt(keyword) || end < text.length()
|
||||
&& (Character.isLetterOrDigit(text.charAt(end)) || text.charAt(end) == '_')) {
|
||||
return false;
|
||||
}
|
||||
position = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Reads a double-quoted string whose opening quote is next; {@code \"} and {@code \\} are escapes. */
|
||||
String quoted() {
|
||||
expect('"');
|
||||
StringBuilder value = new StringBuilder();
|
||||
while (true) {
|
||||
if (atEnd()) {
|
||||
throw error("unterminated quoted string");
|
||||
}
|
||||
char c = next();
|
||||
if (c == '"') {
|
||||
return value.toString();
|
||||
}
|
||||
if (c == '\\' && !atEnd() && (peek() == '"' || peek() == '\\')) {
|
||||
c = next();
|
||||
}
|
||||
value.append(c);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a {@code %regex%} whose opening percent sign is next, returning the compiled regex. */
|
||||
AwsRegex regex() {
|
||||
expect('%');
|
||||
int start = position;
|
||||
while (!atEnd() && peek() != '%') {
|
||||
position++;
|
||||
}
|
||||
if (atEnd()) {
|
||||
throw error("unterminated regular expression, expected a closing '%'");
|
||||
}
|
||||
String body = text.substring(start, position);
|
||||
position++;
|
||||
return AwsRegex.compile(body);
|
||||
}
|
||||
|
||||
/** Reads an identifier: a letter or underscore followed by letters, digits and underscores. */
|
||||
String identifier() {
|
||||
skipWhitespace();
|
||||
int start = position;
|
||||
if (atEnd() || !(Character.isLetter(peek()) || peek() == '_')) {
|
||||
throw error("expected a field name");
|
||||
}
|
||||
while (!atEnd() && (Character.isLetterOrDigit(peek()) || peek() == '_')) {
|
||||
position++;
|
||||
}
|
||||
return text.substring(start, position);
|
||||
}
|
||||
|
||||
/** Reads a bare value up to whitespace or one of the delimiters the enclosing syntax uses. */
|
||||
String bareValue(String delimiters) {
|
||||
int start = position;
|
||||
while (!atEnd() && !Character.isWhitespace(peek()) && delimiters.indexOf(peek()) < 0) {
|
||||
position++;
|
||||
}
|
||||
if (start == position) {
|
||||
throw error("expected a value");
|
||||
}
|
||||
return text.substring(start, position);
|
||||
}
|
||||
|
||||
void expectEnd() {
|
||||
skipWhitespace();
|
||||
if (!atEnd()) {
|
||||
throw error("unexpected '" + text.substring(position) + "'");
|
||||
}
|
||||
}
|
||||
|
||||
FilterPatternException error(String what) {
|
||||
return new FilterPatternException("Invalid filter pattern at position " + position + ": " + what);
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* A pattern in square brackets over a space-delimited log event, one entry per field: a name, a
|
||||
* name with conditions ({@code status_code = 4*}, {@code w1=ERROR || w1=WARNING}), an empty entry
|
||||
* for a field without a name, or one {@code ...} standing for any number of fields. Text between
|
||||
* double quotes or square brackets is one field. Without an ellipsis the last entry takes the rest
|
||||
* of the line, which is why the reference asks for a blank indicator after the last term.
|
||||
*
|
||||
* <p>A match extracts every field: named ones as {@code $name}, the rest by position as
|
||||
* {@code $1}, {@code $2} and so on, the shape {@code TestMetricFilter} reports.
|
||||
*/
|
||||
final class SpaceDelimitedPattern extends FilterPattern {
|
||||
|
||||
/** The bound fields of one event, by name and by position. */
|
||||
record Fields(List<String> values, Map<String, String> byName) {}
|
||||
|
||||
private record Entry(String name, Condition<Fields> condition) {}
|
||||
|
||||
private final List<Entry> before;
|
||||
private final List<Entry> after;
|
||||
private final boolean ellipsis;
|
||||
private final Set<String> names;
|
||||
private final int regexes;
|
||||
|
||||
private SpaceDelimitedPattern(List<Entry> before, List<Entry> after, boolean ellipsis, Set<String> names,
|
||||
int regexes) {
|
||||
this.before = before;
|
||||
this.after = after;
|
||||
this.ellipsis = ellipsis;
|
||||
this.names = names;
|
||||
this.regexes = regexes;
|
||||
}
|
||||
|
||||
static SpaceDelimitedPattern of(String text) {
|
||||
PatternCursor cursor = new PatternCursor(text);
|
||||
cursor.expect('[');
|
||||
List<Entry> before = new ArrayList<>();
|
||||
List<Entry> after = new ArrayList<>();
|
||||
boolean ellipsis = false;
|
||||
Set<String> declared = new HashSet<>();
|
||||
Set<String> referenced = new HashSet<>();
|
||||
int[] regexes = {0};
|
||||
cursor.skipWhitespace();
|
||||
if (cursor.peek() != ']') {
|
||||
while (true) {
|
||||
cursor.skipWhitespace();
|
||||
if (cursor.lookingAt("...")) {
|
||||
cursor.consume("...");
|
||||
if (ellipsis) {
|
||||
throw cursor.error("only one '...' is allowed");
|
||||
}
|
||||
ellipsis = true;
|
||||
} else if (cursor.peek() == ',' || cursor.peek() == ']') {
|
||||
(ellipsis ? after : before).add(new Entry(null, null));
|
||||
} else {
|
||||
Entry entry = readEntry(cursor, referenced, regexes);
|
||||
if (!declared.add(entry.name())) {
|
||||
throw cursor.error("field '" + entry.name() + "' is declared twice");
|
||||
}
|
||||
(ellipsis ? after : before).add(entry);
|
||||
}
|
||||
cursor.skipWhitespace();
|
||||
if (cursor.consume("]")) {
|
||||
break;
|
||||
}
|
||||
cursor.expect(',');
|
||||
}
|
||||
} else {
|
||||
cursor.next();
|
||||
ellipsis = true;
|
||||
}
|
||||
cursor.expectEnd();
|
||||
referenced.removeAll(declared);
|
||||
if (!referenced.isEmpty()) {
|
||||
throw cursor.error("condition refers to an undeclared field " + referenced.iterator().next());
|
||||
}
|
||||
if (!ellipsis && before.isEmpty()) {
|
||||
ellipsis = true;
|
||||
}
|
||||
return new SpaceDelimitedPattern(List.copyOf(before), List.copyOf(after), ellipsis, Set.copyOf(declared),
|
||||
regexes[0]);
|
||||
}
|
||||
|
||||
/** Reads one entry; the first field name in it is the field the entry declares. */
|
||||
private static Entry readEntry(PatternCursor cursor, Set<String> referenced, int[] regexes) {
|
||||
String[] declared = {null};
|
||||
Condition<Fields> condition = Condition.parse(cursor, c -> {
|
||||
String name = c.identifier();
|
||||
if (declared[0] == null) {
|
||||
declared[0] = name;
|
||||
} else if (!declared[0].equals(name)) {
|
||||
throw c.error("a field condition cannot reference another field");
|
||||
}
|
||||
referenced.add(name);
|
||||
c.skipWhitespace();
|
||||
if ("=!<>".indexOf(c.peek()) < 0) {
|
||||
return fields -> true;
|
||||
}
|
||||
Literal.Operator op = Literal.Operator.read(c);
|
||||
Literal literal = Literal.read(c, ",]&|)");
|
||||
literal.validateOperator(op);
|
||||
if (literal.isRegex()) {
|
||||
regexes[0]++;
|
||||
}
|
||||
return fields -> {
|
||||
String value = fields.byName().get(name);
|
||||
return value != null && literal.test(op, value);
|
||||
};
|
||||
});
|
||||
return new Entry(declared[0], condition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Kind kind() {
|
||||
return Kind.SPACE_DELIMITED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FilterMatch match(String message) {
|
||||
List<String> values = split(message == null ? "" : message, ellipsis ? -1 : before.size());
|
||||
int fixed = before.size() + after.size();
|
||||
if (values.size() < fixed || (!ellipsis && values.size() != fixed)) {
|
||||
return FilterMatch.NONE;
|
||||
}
|
||||
Map<String, String> byName = new HashMap<>();
|
||||
Map<String, String> extracted = new LinkedHashMap<>();
|
||||
for (int position = 0; position < values.size(); position++) {
|
||||
Entry entry = null;
|
||||
if (position < before.size()) {
|
||||
entry = before.get(position);
|
||||
} else if (position >= values.size() - after.size()) {
|
||||
entry = after.get(position - (values.size() - after.size()));
|
||||
}
|
||||
String value = values.get(position);
|
||||
if (entry != null && entry.name() != null) {
|
||||
byName.put(entry.name(), value);
|
||||
extracted.put("$" + entry.name(), value);
|
||||
} else {
|
||||
extracted.put("$" + (position + 1), value);
|
||||
}
|
||||
}
|
||||
Fields fields = new Fields(values, byName);
|
||||
for (List<Entry> entries : List.of(before, after)) {
|
||||
for (Entry entry : entries) {
|
||||
if (entry.condition() != null && !entry.condition().test(fields)) {
|
||||
return FilterMatch.NONE;
|
||||
}
|
||||
}
|
||||
}
|
||||
return FilterMatch.of(extracted, reference -> value(fields, reference));
|
||||
}
|
||||
|
||||
private static String value(Fields fields, String reference) {
|
||||
if (reference == null || reference.length() < 2 || reference.charAt(0) != '$') {
|
||||
return null;
|
||||
}
|
||||
String key = reference.substring(1);
|
||||
Integer position = position(key);
|
||||
if (position != null) {
|
||||
return position >= 1 && position <= fields.values().size() ? fields.values().get(position - 1) : null;
|
||||
}
|
||||
return fields.byName().get(key);
|
||||
}
|
||||
|
||||
private static Integer position(String key) {
|
||||
if (key.isEmpty() || !key.chars().allMatch(Character::isDigit)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(key);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a message into fields on whitespace, keeping text between double quotes or square
|
||||
* brackets together without the delimiters. With {@code limit} above zero, the field at that
|
||||
* position takes the rest of the line as written.
|
||||
*/
|
||||
static List<String> split(String message, int limit) {
|
||||
List<String> fields = new ArrayList<>();
|
||||
int i = 0;
|
||||
int length = message.length();
|
||||
while (i < length) {
|
||||
while (i < length && Character.isWhitespace(message.charAt(i))) {
|
||||
i++;
|
||||
}
|
||||
if (i >= length) {
|
||||
break;
|
||||
}
|
||||
char c = message.charAt(i);
|
||||
char closing = c == '"' ? '"' : c == '[' ? ']' : '\0';
|
||||
int end = closing == '\0' ? -1 : message.indexOf(closing, i + 1);
|
||||
boolean quoted = end >= 0;
|
||||
if (quoted) {
|
||||
end++;
|
||||
} else {
|
||||
end = i;
|
||||
while (end < length && !Character.isWhitespace(message.charAt(end))) {
|
||||
end++;
|
||||
}
|
||||
}
|
||||
if (limit > 0 && fields.size() == limit - 1 && !message.substring(end).isBlank()) {
|
||||
fields.add(message.substring(i));
|
||||
break;
|
||||
}
|
||||
fields.add(quoted ? message.substring(i + 1, end - 1) : message.substring(i, end));
|
||||
i = end;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean declaresField(String reference) {
|
||||
if (reference == null || reference.length() < 2 || reference.charAt(0) != '$') {
|
||||
return false;
|
||||
}
|
||||
String key = reference.substring(1);
|
||||
Integer position = position(key);
|
||||
return position != null ? position >= 1 : names.contains(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int regexCount() {
|
||||
return regexes;
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A metric filter's {@code fieldSelectionCriteria}: which log events the filter processes, decided
|
||||
* from the system fields {@code @aws.account} and {@code @aws.region} rather than from the event's
|
||||
* own text. The Logs API documents the operators {@code =}, {@code !=}, {@code IN}, {@code NOT IN},
|
||||
* {@code AND} and {@code OR}, as in {@code @aws.region = "us-east-1"} or
|
||||
* {@code @aws.account IN ["123456789012", "987654321098"]}.
|
||||
*
|
||||
* <p>Both fields describe the batch rather than the individual event, so one evaluation decides a
|
||||
* whole ingested batch. {@code &&} and {@code ||} are accepted beside {@code AND} and {@code OR},
|
||||
* and parentheses group, because the criteria share their shape with the filter-pattern syntax.
|
||||
*
|
||||
* <p>Instances are immutable and safe to share between threads.
|
||||
*/
|
||||
public final class SystemFieldSelection {
|
||||
|
||||
private static final String ACCOUNT = "@aws.account";
|
||||
private static final String REGION = "@aws.region";
|
||||
|
||||
/** The system fields of one ingested batch. */
|
||||
private record Fields(String account, String region) {}
|
||||
|
||||
private final Condition<Fields> condition;
|
||||
|
||||
private SystemFieldSelection(Condition<Fields> condition) {
|
||||
this.condition = condition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a criterion, throwing {@link FilterPatternException} when it does not follow the
|
||||
* syntax. A blank criterion selects everything, as an absent one does.
|
||||
*/
|
||||
public static SystemFieldSelection parse(String expression) {
|
||||
String text = expression == null ? "" : expression.strip();
|
||||
if (text.isEmpty()) {
|
||||
return new SystemFieldSelection(fields -> true);
|
||||
}
|
||||
PatternCursor cursor = new PatternCursor(text);
|
||||
Condition<Fields> condition = Condition.parse(cursor, SystemFieldSelection::atom, true);
|
||||
cursor.expectEnd();
|
||||
return new SystemFieldSelection(condition);
|
||||
}
|
||||
|
||||
/** Whether a batch written for {@code account} in {@code region} is one this filter processes. */
|
||||
public boolean test(String account, String region) {
|
||||
return condition.test(new Fields(account, region));
|
||||
}
|
||||
|
||||
private static Condition<Fields> atom(PatternCursor cursor) {
|
||||
String field = field(cursor);
|
||||
cursor.skipWhitespace();
|
||||
if (cursor.consume("!=")) {
|
||||
String value = value(cursor);
|
||||
return fields -> !value.equals(valueOf(field, fields));
|
||||
}
|
||||
if (cursor.consume("=")) {
|
||||
if (cursor.peek() == '=') {
|
||||
throw cursor.error("'==' is not an operator, use '='");
|
||||
}
|
||||
String value = value(cursor);
|
||||
return fields -> value.equals(valueOf(field, fields));
|
||||
}
|
||||
boolean negated = cursor.consumeKeyword("NOT") || cursor.consumeKeyword("not");
|
||||
cursor.skipWhitespace();
|
||||
if (!cursor.consumeKeyword("IN") && !cursor.consumeKeyword("in")) {
|
||||
throw cursor.error("expected '=', '!=', IN or NOT IN after " + field);
|
||||
}
|
||||
List<String> values = list(cursor);
|
||||
return fields -> values.contains(valueOf(field, fields)) != negated;
|
||||
}
|
||||
|
||||
private static String field(PatternCursor cursor) {
|
||||
cursor.skipWhitespace();
|
||||
if (cursor.consume(ACCOUNT)) {
|
||||
return ACCOUNT;
|
||||
}
|
||||
if (cursor.consume(REGION)) {
|
||||
return REGION;
|
||||
}
|
||||
throw cursor.error("expected " + ACCOUNT + " or " + REGION);
|
||||
}
|
||||
|
||||
private static String value(PatternCursor cursor) {
|
||||
cursor.skipWhitespace();
|
||||
return cursor.peek() == '"' ? cursor.quoted() : cursor.bareValue(",]()=!<>|&");
|
||||
}
|
||||
|
||||
private static List<String> list(PatternCursor cursor) {
|
||||
cursor.expect('[');
|
||||
List<String> values = new ArrayList<>();
|
||||
do {
|
||||
values.add(value(cursor));
|
||||
cursor.skipWhitespace();
|
||||
} while (cursor.consume(","));
|
||||
cursor.expect(']');
|
||||
return List.copyOf(values);
|
||||
}
|
||||
|
||||
private static String valueOf(String field, Fields fields) {
|
||||
return ACCOUNT.equals(field) ? fields.account() : fields.region();
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.filter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Terms matched against an unstructured message: every plain term must be present (a
|
||||
* case-sensitive substring, as the API reference's examples show), no {@code -term} may be, and
|
||||
* {@code ?term}s make the pattern match when any of them is present, though only when no other
|
||||
* kind of term is given, since AWS ignores them otherwise. A quoted phrase is one term.
|
||||
* An unstructured {@code %regex%} must stand alone and is searched for.
|
||||
*/
|
||||
final class TermPattern extends FilterPattern {
|
||||
|
||||
private enum Mode { INCLUDE, EXCLUDE, OPTIONAL }
|
||||
|
||||
private record Term(Mode mode, String text, AwsRegex regex) {
|
||||
boolean occursIn(String message) {
|
||||
return regex != null ? regex.find(message) : message.contains(text);
|
||||
}
|
||||
}
|
||||
|
||||
private final List<Term> includes = new ArrayList<>();
|
||||
private final List<Term> excludes = new ArrayList<>();
|
||||
private final List<Term> optionals = new ArrayList<>();
|
||||
private int regexes;
|
||||
|
||||
static TermPattern of(String text) {
|
||||
TermPattern pattern = new TermPattern();
|
||||
PatternCursor cursor = new PatternCursor(text);
|
||||
if (cursor.peek() == '%') {
|
||||
pattern.add(new Term(Mode.INCLUDE, null, cursor.regex()));
|
||||
cursor.expectEnd();
|
||||
return pattern;
|
||||
}
|
||||
while (true) {
|
||||
cursor.skipWhitespace();
|
||||
if (cursor.atEnd()) {
|
||||
return pattern;
|
||||
}
|
||||
pattern.add(readTerm(cursor));
|
||||
if (!cursor.atEnd() && !Character.isWhitespace(cursor.peek())
|
||||
&& cursor.peek() != '-' && cursor.peek() != '?') {
|
||||
throw cursor.error("terms must be separated");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Term readTerm(PatternCursor cursor) {
|
||||
Mode mode = Mode.INCLUDE;
|
||||
if (cursor.peek() == '-' && !cursor.lookingAt("- ")) {
|
||||
cursor.next();
|
||||
mode = Mode.EXCLUDE;
|
||||
} else if (cursor.peek() == '?' && !cursor.lookingAt("? ")) {
|
||||
cursor.next();
|
||||
mode = Mode.OPTIONAL;
|
||||
}
|
||||
if (cursor.peek() == '"') {
|
||||
String value = cursor.quoted();
|
||||
if (value.isEmpty()) {
|
||||
throw cursor.error("empty quoted term");
|
||||
}
|
||||
return new Term(mode, value, null);
|
||||
}
|
||||
if (cursor.peek() == '%') {
|
||||
throw cursor.error("a regex must be the entire unstructured pattern");
|
||||
}
|
||||
String value = cursor.bareValue("-?");
|
||||
if (!value.matches("[\\p{L}\\p{N}_.]+")) {
|
||||
throw cursor.error("invalid unquoted term '" + value + "'");
|
||||
}
|
||||
return new Term(mode, value, null);
|
||||
}
|
||||
|
||||
private void add(Term term) {
|
||||
if (term.regex() != null) {
|
||||
regexes++;
|
||||
}
|
||||
switch (term.mode()) {
|
||||
case INCLUDE -> includes.add(term);
|
||||
case EXCLUDE -> excludes.add(term);
|
||||
case OPTIONAL -> optionals.add(term);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Kind kind() {
|
||||
return Kind.TERMS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FilterMatch match(String message) {
|
||||
String text = message == null ? "" : message;
|
||||
boolean matched;
|
||||
if (includes.isEmpty() && excludes.isEmpty()) {
|
||||
matched = optionals.stream().anyMatch(term -> term.occursIn(text));
|
||||
} else {
|
||||
matched = includes.stream().allMatch(term -> term.occursIn(text))
|
||||
&& excludes.stream().noneMatch(term -> term.occursIn(text));
|
||||
}
|
||||
return matched ? FilterMatch.of(Map.of(), reference -> null) : FilterMatch.NONE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean declaresField(String reference) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int regexCount() {
|
||||
return regexes;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** A metric filter on a log group, the AWS MetricFilter shape. */
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class MetricFilter {
|
||||
|
||||
private String filterName;
|
||||
private String logGroupName;
|
||||
private String filterPattern;
|
||||
private List<MetricTransformation> metricTransformations = new ArrayList<>();
|
||||
private long creationTime;
|
||||
private Boolean applyOnTransformedLogs;
|
||||
private String fieldSelectionCriteria;
|
||||
private List<String> emitSystemFieldDimensions;
|
||||
|
||||
public MetricFilter() {}
|
||||
|
||||
public String getFilterName() { return filterName; }
|
||||
public void setFilterName(String filterName) { this.filterName = filterName; }
|
||||
|
||||
public String getLogGroupName() { return logGroupName; }
|
||||
public void setLogGroupName(String logGroupName) { this.logGroupName = logGroupName; }
|
||||
|
||||
public String getFilterPattern() { return filterPattern; }
|
||||
public void setFilterPattern(String filterPattern) { this.filterPattern = filterPattern; }
|
||||
|
||||
public List<MetricTransformation> getMetricTransformations() { return metricTransformations; }
|
||||
public void setMetricTransformations(List<MetricTransformation> metricTransformations) {
|
||||
this.metricTransformations = metricTransformations != null ? metricTransformations : new ArrayList<>();
|
||||
}
|
||||
|
||||
public long getCreationTime() { return creationTime; }
|
||||
public void setCreationTime(long creationTime) { this.creationTime = creationTime; }
|
||||
|
||||
public Boolean getApplyOnTransformedLogs() { return applyOnTransformedLogs; }
|
||||
public void setApplyOnTransformedLogs(Boolean applyOnTransformedLogs) {
|
||||
this.applyOnTransformedLogs = applyOnTransformedLogs;
|
||||
}
|
||||
|
||||
public String getFieldSelectionCriteria() { return fieldSelectionCriteria; }
|
||||
public void setFieldSelectionCriteria(String fieldSelectionCriteria) {
|
||||
this.fieldSelectionCriteria = fieldSelectionCriteria;
|
||||
}
|
||||
|
||||
public List<String> getEmitSystemFieldDimensions() { return emitSystemFieldDimensions; }
|
||||
public void setEmitSystemFieldDimensions(List<String> emitSystemFieldDimensions) {
|
||||
this.emitSystemFieldDimensions = emitSystemFieldDimensions;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** How a metric filter turns a matching log event into a metric value, the AWS MetricTransformation shape. */
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class MetricTransformation {
|
||||
|
||||
private String metricName;
|
||||
private String metricNamespace;
|
||||
private String metricValue;
|
||||
private Double defaultValue;
|
||||
private Map<String, String> dimensions = new LinkedHashMap<>();
|
||||
private String unit;
|
||||
|
||||
public MetricTransformation() {}
|
||||
|
||||
public String getMetricName() { return metricName; }
|
||||
public void setMetricName(String metricName) { this.metricName = metricName; }
|
||||
|
||||
public String getMetricNamespace() { return metricNamespace; }
|
||||
public void setMetricNamespace(String metricNamespace) { this.metricNamespace = metricNamespace; }
|
||||
|
||||
public String getMetricValue() { return metricValue; }
|
||||
public void setMetricValue(String metricValue) { this.metricValue = metricValue; }
|
||||
|
||||
public Double getDefaultValue() { return defaultValue; }
|
||||
public void setDefaultValue(Double defaultValue) { this.defaultValue = defaultValue; }
|
||||
|
||||
public Map<String, String> getDimensions() { return dimensions; }
|
||||
public void setDimensions(Map<String, String> dimensions) {
|
||||
this.dimensions = dimensions != null ? dimensions : new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String unit) { this.unit = unit; }
|
||||
}
|
||||
+2
-2
@@ -153,7 +153,7 @@ public class CloudWatchMetricsQueryHandler {
|
||||
xml.elem("Unit", dp.unit()).end("member");
|
||||
}
|
||||
xml.end("Datapoints");
|
||||
return Response.ok(AwsQueryResponse.envelope("GetMetricStatistics", null, xml.build())).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("GetMetricStatistics", AwsNamespaces.CW, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleGetMetricData(MultivaluedMap<String, String> params, String region) {
|
||||
@@ -188,7 +188,7 @@ public class CloudWatchMetricsQueryHandler {
|
||||
xml.end("member");
|
||||
}
|
||||
xml.end("MetricDataResults");
|
||||
return Response.ok(AwsQueryResponse.envelope("GetMetricData", null, xml.build())).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("GetMetricData", AwsNamespaces.CW, xml.build())).build();
|
||||
}
|
||||
|
||||
private List<CloudWatchMetricsService.MetricDataQuery> parseMetricDataQueries(
|
||||
|
||||
+50
-5
@@ -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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
@@ -48,6 +49,15 @@ public class CloudWatchMetricsService {
|
||||
}
|
||||
|
||||
public void putMetricData(String namespace, List<MetricDatum> datums, String region) {
|
||||
putMetricDataForAccount(null, namespace, datums, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the datums in {@code accountId}'s partition rather than the caller's, for writers that
|
||||
* run outside a request, such as a metric filter publishing for a log batch a container
|
||||
* streamed on another account's behalf. A null account is the caller's own.
|
||||
*/
|
||||
public void putMetricDataForAccount(String accountId, String namespace, List<MetricDatum> datums, String region) {
|
||||
long nowSeconds = Instant.now().getEpochSecond();
|
||||
for (MetricDatum datum : datums) {
|
||||
datum.setNamespace(namespace);
|
||||
@@ -62,15 +72,50 @@ public class CloudWatchMetricsService {
|
||||
datum.setMaximum(datum.getValue());
|
||||
}
|
||||
|
||||
String dimKey = buildDimKey(datum.getDimensions());
|
||||
String key = region + "::" + namespace + "::" + datum.getMetricName()
|
||||
+ "::" + dimKey + "::"
|
||||
+ String.format("%013d", datum.getTimestamp()) + "::" + UUID.randomUUID();
|
||||
metricStore.put(key, datum);
|
||||
storeDatum(accountId, namespace, datum, region, UUID.randomUUID().toString());
|
||||
}
|
||||
LOG.debugv("PutMetricData: {0} datums for namespace {1}", datums.size(), namespace);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal scalar publication, not an AWS PutMetricData operation. The publisher supplies a
|
||||
* canonical account, an explicit event timestamp (including epoch zero), and a stable ID for
|
||||
* this one contribution. Retrying a partially/ambiguously committed write replaces the same
|
||||
* key instead of appending another sample. Distinct contributions must have distinct IDs.
|
||||
* The caller's snapshot is never mutated or retained by the store.
|
||||
*/
|
||||
public void publishMetricForAccount(String accountId, String namespace, MetricDatum datum,
|
||||
String region, String publicationId) {
|
||||
if (accountId == null || accountId.isBlank() || publicationId == null || publicationId.isBlank()) {
|
||||
throw new IllegalArgumentException("Internal publication requires an explicit account and publication ID");
|
||||
}
|
||||
MetricDatum sample = new MetricDatum();
|
||||
sample.setNamespace(namespace);
|
||||
sample.setMetricName(datum.getMetricName());
|
||||
sample.setUnit(datum.getUnit());
|
||||
sample.setDimensions(List.copyOf(datum.getDimensions()));
|
||||
sample.setTimestamp(datum.getTimestamp());
|
||||
sample.setValue(datum.getValue());
|
||||
sample.setSampleCount(1);
|
||||
sample.setSum(datum.getValue());
|
||||
sample.setMinimum(datum.getValue());
|
||||
sample.setMaximum(datum.getValue());
|
||||
storeDatum(accountId, namespace, sample, region, "publication-" + publicationId);
|
||||
}
|
||||
|
||||
private void storeDatum(String accountId, String namespace, MetricDatum datum, String region, String id) {
|
||||
String key = region + "::" + namespace + "::" + datum.getMetricName()
|
||||
+ "::" + buildDimKey(datum.getDimensions()) + "::"
|
||||
+ String.format("%013d", datum.getTimestamp()) + "::" + id;
|
||||
if (accountId != null && metricStore instanceof AccountAwareStorageBackend<?> rawAware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<MetricDatum> aware = (AccountAwareStorageBackend<MetricDatum>) rawAware;
|
||||
aware.putForAccount(accountId, key, datum);
|
||||
} else {
|
||||
metricStore.put(key, datum);
|
||||
}
|
||||
}
|
||||
|
||||
public record MetricIdentity(String namespace, String metricName, List<Dimension> dimensions) {}
|
||||
|
||||
public List<MetricIdentity> listMetrics(String namespace, String metricName,
|
||||
|
||||
Reference in new issue
Block a user