mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(cloudwatch): add Logs Insights query support (#1448)
* feat(cloudwatch): add Logs Insights query support Implement StartQuery/GetQueryResults/StopQuery for CloudWatch Logs so clients using Logs Insights (e.g. boto3 start_query + get_query_results) work against Floci instead of receiving UnsupportedOperation. LogsInsightsQuery is a minimal engine covering the common subset: fields, filter (= / !=), sort, dedup, limit; it resolves @timestamp/@message and dotted JSON paths (e.g. params.job_id, level). StartQuery times are epoch seconds while event timestamps are millis, scaled accordingly. Queries follow a time-driven lifecycle: results are computed eagerly, but a query reports Running until a configurable completion delay elapses (FLOCI_SERVICES_CLOUDWATCHLOGS_QUERY_COMPLETION_DELAY_MS, default 0 = instant for local dev), then Complete; StopQuery cancels a running query and otherwise returns AWS-faithful errors (InvalidParameterException when already ended, ResourceNotFoundException for an unknown id). Status is computed on read from an injectable clock, with no background threads. GetQueryResults returns ResourceNotFoundException for unknown ids, reports recordsMatched independent of the Running/Cancelled row masking, hands out a defensive copy of result rows, and drops rows once cancelled. Results are cached by queryId with LRU eviction. Covered by unit tests and an AWS SDK v2 compatibility test exercising the full StartQuery/GetQueryResults/StopQuery lifecycle (stable against both instant and delayed completion). * test(cloudwatch): cover Logs Insights search across multiple log groups Verify a single StartQuery spanning several log groups finds the same params.id wherever it was logged (results merged and globally sorted by @timestamp), and that a matching event in an un-queried group is excluded. * test(cloudwatch): cover Logs Insights query-language edge cases Add unit tests for limit (applied after sort), ascending sort on a nested JSON field, the default @timestamp/@message projection, missing-field handling (empty projection plus null-safe inequality filtering), graceful ignoring of unsupported commands (parse/stats), and the recordsScanned vs recordsMatched statistics. * fix(cloudwatch): deterministic Logs Insights ordering for same-ms events and dedup Tie-break the @timestamp/@ingestionTime sort comparators by ingestion sequence then eventId (matching the event store's EVENT_ORDER), and apply the AWS-documented default @timestamp desc sort when a dedup stage has no preceding sort — so the surviving duplicate is the newest, deterministically, rather than depending on storage-scan order. * fix(cloudwatch): validate log groups and harden Logs Insights query parsing StartQuery now de-duplicates the requested log groups (the same group can arrive via multiple selectors) so it is scanned and counted once, and it returns ResourceNotFoundException for a log group that does not exist instead of a successful empty query — matching real AWS. The stage parser splits on pipes only outside quotes, so a filter value containing '|' (e.g. filter x = 'a|b') is no longer broken into fragments. StartQuery still accepts multiple selectors and de-duplicates group names service-side; strict AWS mutual-exclusivity rejection (InvalidParameterException for more than one of logGroupName/logGroupNames/logGroupIdentifiers) is deferred to a handler-side follow-up, since the handler collapses all three selectors into one service argument. * fix(cloudwatch): reject empty StartQuery selectors and parse quoted filter operators StartQuery now rejects a request with no usable log-group selector (InvalidParameterException) instead of returning a successful empty query. parseFilter finds the equality/inequality operator outside quoted values, so a value that itself contains '=' / '==' / '!=' (e.g. filter x = 'a==b') is no longer misparsed. * fix(cloudwatch): reject StartQuery requests with more than one log-group selector AWS requires exactly one of logGroupName, logGroupNames, or logGroupIdentifiers. The handler now rejects a request that provides more than one selector type with InvalidParameterException, instead of silently querying the union. The zero-selector case is already rejected by the service. * fix(cloudwatch): count serialized StartQuery selector fields, not just non-empty ones The mutual-exclusivity guard counted a selector only when its value was non-blank, but the merge path added any present field — so a blank logGroupName alongside a real logGroupNames slipped past the guard. Count serialized fields uniformly (has), so a blank or empty selector field can't bypass the check; a lone empty selector still yields no groups and is rejected by the service. --------- Co-authored-by: Beytullah Gunduz <beytullah-gunduz@users.noreply.github.com>
This commit is contained in:
1 parent
f490bbefad
commit
89fadbad81
7 files changed
+1493
-1
No files matched your search
@@ -871,6 +871,15 @@ public interface EmulatorConfig {
|
||||
|
||||
@WithDefault("10000")
|
||||
int maxEventsPerQuery();
|
||||
|
||||
/**
|
||||
* Artificial Logs Insights query completion delay, in milliseconds. With the default 0,
|
||||
* queries complete immediately (fast local dev). A positive value emulates the real
|
||||
* asynchronous lifecycle — StartQuery → Running → Complete after this delay — which also
|
||||
* makes StopQuery on a still-running query return {@code success=true}.
|
||||
*/
|
||||
@WithDefault("0")
|
||||
long queryCompletionDelayMs();
|
||||
}
|
||||
|
||||
interface CloudWatchMetricsServiceConfig {
|
||||
|
||||
+93
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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;
|
||||
@@ -15,6 +16,7 @@ import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -53,6 +55,9 @@ public class CloudWatchLogsHandler {
|
||||
case "DescribeSubscriptionFilters" -> handleDescribeSubscriptionFilters(request, region);
|
||||
case "DeleteSubscriptionFilter" -> handleDeleteSubscriptionFilter(request, region);
|
||||
case "GetDataProtectionPolicy" -> handleGetDataProtectionPolicy(request, region);
|
||||
case "StartQuery" -> handleStartQuery(request, region);
|
||||
case "GetQueryResults" -> handleGetQueryResults(request, region);
|
||||
case "StopQuery" -> handleStopQuery(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
@@ -196,6 +201,94 @@ public class CloudWatchLogsHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Logs Insights Queries ────────────────────────────
|
||||
|
||||
private Response handleStartQuery(JsonNode request, String region) {
|
||||
// AWS requires exactly one of logGroupName / logGroupNames / logGroupIdentifiers.
|
||||
// The zero-selector case is enforced by the service (it throws when the resolved group
|
||||
// list is empty); here we reject the other invalid shape: more than one selector type.
|
||||
if (presentSelectorCount(request) > 1) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"Exactly one of logGroupName, logGroupNames, or logGroupIdentifiers may be specified.",
|
||||
400);
|
||||
}
|
||||
|
||||
List<String> logGroupNames = new ArrayList<>();
|
||||
request.path("logGroupNames").forEach(n -> logGroupNames.add(extractLogGroupNameFromArn(n.asText())));
|
||||
if (request.has("logGroupName")) {
|
||||
logGroupNames.add(extractLogGroupNameFromArn(request.path("logGroupName").asText()));
|
||||
}
|
||||
request.path("logGroupIdentifiers").forEach(n -> logGroupNames.add(extractLogGroupNameFromArn(n.asText())));
|
||||
|
||||
long startTime = request.path("startTime").asLong();
|
||||
long endTime = request.path("endTime").asLong();
|
||||
String queryString = request.path("queryString").asText("");
|
||||
Integer limit = request.has("limit") ? request.path("limit").asInt() : null;
|
||||
|
||||
String queryId = logsService.startQuery(logGroupNames, startTime, endTime, queryString, limit, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("queryId", queryId);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts how many of the three mutually exclusive StartQuery log-group selector <em>fields</em> the
|
||||
* request carries: {@code logGroupName}, {@code logGroupNames}, {@code logGroupIdentifiers}. A field
|
||||
* counts if it is present at all — even a blank string or empty array — using the same presence rule
|
||||
* ({@code has}) as the merge path below, so a serialized-but-empty selector cannot slip past the
|
||||
* mutual-exclusivity check. A single empty/blank selector yields no groups and is rejected downstream
|
||||
* by the service. (The AWS SDK omits unset list fields, so a well-formed single-selector request
|
||||
* still carries exactly one field.)
|
||||
*/
|
||||
private int presentSelectorCount(JsonNode request) {
|
||||
int count = 0;
|
||||
if (request.has("logGroupName")) {
|
||||
count++;
|
||||
}
|
||||
if (request.has("logGroupNames")) {
|
||||
count++;
|
||||
}
|
||||
if (request.has("logGroupIdentifiers")) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private Response handleGetQueryResults(JsonNode request, String region) {
|
||||
String queryId = request.path("queryId").asText();
|
||||
CloudWatchLogsService.QueryState state = logsService.getQueryResults(queryId);
|
||||
|
||||
ArrayNode results = objectMapper.createArrayNode();
|
||||
for (LinkedHashMap<String, String> row : state.rows()) {
|
||||
ArrayNode rowArray = objectMapper.createArrayNode();
|
||||
row.forEach((field, value) -> {
|
||||
ObjectNode fieldNode = objectMapper.createObjectNode();
|
||||
fieldNode.put("field", field);
|
||||
fieldNode.put("value", value);
|
||||
rowArray.add(fieldNode);
|
||||
});
|
||||
results.add(rowArray);
|
||||
}
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("results", results);
|
||||
response.put("status", state.status());
|
||||
ObjectNode statistics = objectMapper.createObjectNode();
|
||||
statistics.put("recordsMatched", (double) state.recordsMatched());
|
||||
statistics.put("recordsScanned", (double) state.recordsScanned());
|
||||
statistics.put("bytesScanned", 0.0);
|
||||
response.set("statistics", statistics);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleStopQuery(JsonNode request, String region) {
|
||||
String queryId = request.path("queryId").asText();
|
||||
boolean success = logsService.stopQuery(queryId);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("success", success);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handlePutRetentionPolicy(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
int days = request.path("retentionInDays").asInt();
|
||||
|
||||
+197
-1
@@ -15,12 +15,15 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CloudWatchLogsService {
|
||||
@@ -49,6 +52,22 @@ public class CloudWatchLogsService {
|
||||
* the highest sequence already in the store so ordering survives persistence reloads.
|
||||
*/
|
||||
private final AtomicLong ingestionSequence;
|
||||
private final long queryCompletionDelayMs;
|
||||
|
||||
// Wall-clock source of "now" for the query lifecycle, injected so tests can drive it deterministically.
|
||||
// Non-monotonic: a backward NTP step could briefly flip a Complete query back to Running — a rare,
|
||||
// self-healing emulator artifact we accept rather than complicate the injectable clock with nanoTime.
|
||||
private final LongSupplier clock;
|
||||
|
||||
/** Cached Logs Insights queries keyed by queryId, bounded with LRU-style eviction. */
|
||||
private static final int MAX_STORED_QUERIES = 100;
|
||||
private final Map<String, QueryRecord> insightsQueries = Collections.synchronizedMap(
|
||||
new LinkedHashMap<>(16, 0.75f, true) {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(Map.Entry<String, QueryRecord> eldest) {
|
||||
return size() > MAX_STORED_QUERIES;
|
||||
}
|
||||
});
|
||||
|
||||
@Inject
|
||||
public CloudWatchLogsService(StorageFactory storageFactory,
|
||||
@@ -64,7 +83,9 @@ public class CloudWatchLogsService {
|
||||
storageFactory.create("cloudwatchlogs", "cwlogs-subscription-filters.json",
|
||||
new TypeReference<>() {}),
|
||||
config.services().cloudwatchlogs().maxEventsPerQuery(),
|
||||
regionResolver
|
||||
regionResolver,
|
||||
config.services().cloudwatchlogs().queryCompletionDelayMs(),
|
||||
System::currentTimeMillis
|
||||
);
|
||||
}
|
||||
|
||||
@@ -74,6 +95,18 @@ public class CloudWatchLogsService {
|
||||
StorageBackend<String, SubscriptionFilter> subscriptionFilterStore,
|
||||
int maxEventsPerQuery,
|
||||
RegionResolver regionResolver) {
|
||||
this(groupStore, streamStore, eventStore, subscriptionFilterStore,
|
||||
maxEventsPerQuery, regionResolver, 0L, System::currentTimeMillis);
|
||||
}
|
||||
|
||||
CloudWatchLogsService(StorageBackend<String, LogGroup> groupStore,
|
||||
StorageBackend<String, LogStream> streamStore,
|
||||
StorageBackend<String, LogEvent> eventStore,
|
||||
StorageBackend<String, SubscriptionFilter> subscriptionFilterStore,
|
||||
int maxEventsPerQuery,
|
||||
RegionResolver regionResolver,
|
||||
long queryCompletionDelayMs,
|
||||
LongSupplier clock) {
|
||||
this.groupStore = groupStore;
|
||||
this.streamStore = streamStore;
|
||||
this.eventStore = eventStore;
|
||||
@@ -85,6 +118,9 @@ public class CloudWatchLogsService {
|
||||
.max()
|
||||
.orElse(0L);
|
||||
this.ingestionSequence = new AtomicLong(maxSequence);
|
||||
// A negative delay is meaningless; treat it as instant completion.
|
||||
this.queryCompletionDelayMs = Math.max(0, queryCompletionDelayMs);
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Log Groups ────────────────────────────
|
||||
@@ -382,6 +418,166 @@ public class CloudWatchLogsService {
|
||||
return new FilteredLogEventsResult(result, nextToken);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Logs Insights Queries ────────────────────────────
|
||||
|
||||
/** A query's status and (once Complete) its projected rows — the AWS GetQueryResults shape. */
|
||||
public record QueryState(String status, List<LinkedHashMap<String, String>> rows,
|
||||
long recordsScanned, long recordsMatched) {}
|
||||
|
||||
/** Lifecycle state of a stored Insights query; {@link #label()} is the AWS wire form. */
|
||||
private enum InsightsQueryStatus {
|
||||
RUNNING("Running"),
|
||||
COMPLETE("Complete"),
|
||||
CANCELLED("Cancelled");
|
||||
|
||||
private final String label;
|
||||
|
||||
InsightsQueryStatus(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
String label() {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A stored Insights query. Results are computed eagerly at StartQuery, but the query reports
|
||||
* {@code Running} until {@code completeAtMs} (an artificial delay emulating AWS's asynchronous
|
||||
* execution), then {@code Complete} — unless cancelled by StopQuery, after which it is
|
||||
* {@code Cancelled}. State transitions are time-driven and computed on read. {@code recordsMatched}
|
||||
* is captured at construction so it survives the Running/Cancelled row masking and the row-drop on cancel.
|
||||
*/
|
||||
private static final class QueryRecord {
|
||||
private List<LinkedHashMap<String, String>> rows;
|
||||
private final long recordsScanned;
|
||||
private final long recordsMatched;
|
||||
private final long completeAtMs;
|
||||
private boolean cancelled;
|
||||
|
||||
QueryRecord(List<LinkedHashMap<String, String>> rows, long recordsScanned, long completeAtMs) {
|
||||
this.rows = rows;
|
||||
this.recordsScanned = recordsScanned;
|
||||
this.recordsMatched = rows.size();
|
||||
this.completeAtMs = completeAtMs;
|
||||
}
|
||||
|
||||
private InsightsQueryStatus status(long nowMs) {
|
||||
if (cancelled) {
|
||||
return InsightsQueryStatus.CANCELLED;
|
||||
}
|
||||
return nowMs >= completeAtMs ? InsightsQueryStatus.COMPLETE : InsightsQueryStatus.RUNNING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot this query in the AWS GetQueryResults shape. Rows are exposed only once
|
||||
* {@code Complete}, and always as a defensive copy (the cached list is never handed out); while
|
||||
* Running or Cancelled the rows are masked empty, but {@code recordsMatched} still reports the
|
||||
* full match count.
|
||||
*/
|
||||
synchronized QueryState snapshot(long nowMs) {
|
||||
InsightsQueryStatus status = status(nowMs);
|
||||
List<LinkedHashMap<String, String>> visible =
|
||||
status == InsightsQueryStatus.COMPLETE ? List.copyOf(rows) : List.of();
|
||||
return new QueryState(status.label(), visible, recordsScanned, recordsMatched);
|
||||
}
|
||||
|
||||
/** Cancels the query iff still running, dropping its now-unreachable rows. Returns true if this call stopped it. */
|
||||
synchronized boolean stopIfRunning(long nowMs) {
|
||||
if (!cancelled && nowMs < completeAtMs) {
|
||||
cancelled = true;
|
||||
rows = List.of();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a CloudWatch Logs Insights query and cache it under a new queryId. Results are computed
|
||||
* eagerly (the scan is in-memory); the query then reports {@code Running} until the configured
|
||||
* completion delay elapses (default 0 = immediate), emulating AWS's async execution.
|
||||
* {@code startTimeSeconds}/{@code endTimeSeconds} are epoch <em>seconds</em> (the StartQuery
|
||||
* contract); {@link LogEvent} timestamps are epoch millis, so they are scaled for comparison.
|
||||
*/
|
||||
public String startQuery(List<String> logGroupNames, long startTimeSeconds, long endTimeSeconds,
|
||||
String queryString, Integer limit, String region) {
|
||||
long startMs = startTimeSeconds * 1000L;
|
||||
long endMs = endTimeSeconds * 1000L;
|
||||
|
||||
// De-duplicate the requested groups (the same group can arrive via multiple selectors, e.g.
|
||||
// logGroupNames + logGroupIdentifiers) so it is scanned — and counted — once, not twice.
|
||||
List<String> distinctGroups = logGroupNames.stream()
|
||||
.filter(g -> g != null && !g.isBlank())
|
||||
.distinct()
|
||||
.toList();
|
||||
if (distinctGroups.isEmpty()) {
|
||||
// AWS StartQuery requires a log-group selector; an empty or all-blank one is an invalid
|
||||
// request, not a valid query that happens to match nothing.
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"StartQuery must specify at least one log group.", 400);
|
||||
}
|
||||
|
||||
List<LogEvent> gathered = new ArrayList<>();
|
||||
for (String groupName : distinctGroups) {
|
||||
// Real AWS StartQuery returns ResourceNotFoundException for a log group that does not exist,
|
||||
// rather than a successful empty query; mirror that instead of silently scanning nothing.
|
||||
groupStore.get(groupKey(region, groupName)).orElseThrow(() ->
|
||||
new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + groupName, 400));
|
||||
String prefix = region + "::" + groupName + "::";
|
||||
for (LogEvent e : eventStore.scan(k -> k.startsWith(prefix))) {
|
||||
if (e.getTimestamp() >= startMs && e.getTimestamp() <= endMs) {
|
||||
gathered.add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int effectiveLimit = (limit != null && limit > 0) ? Math.min(limit, maxEventsPerQuery) : maxEventsPerQuery;
|
||||
List<LinkedHashMap<String, String>> rows =
|
||||
LogsInsightsQuery.parse(queryString).evaluate(gathered, effectiveLimit);
|
||||
|
||||
String queryId = UUID.randomUUID().toString();
|
||||
long completeAtMs = clock.getAsLong() + queryCompletionDelayMs;
|
||||
insightsQueries.put(queryId, new QueryRecord(rows, gathered.size(), completeAtMs));
|
||||
LOG.infov("Logs Insights query {0}: scanned {1} event(s) across {2} group(s) -> {3} row(s)",
|
||||
queryId, gathered.size(), distinctGroups.size(), rows.size());
|
||||
return queryId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a query's status and, once {@code Complete}, its rows. Mirrors AWS: while {@code Running}
|
||||
* or after a StopQuery ({@code Cancelled}) the result set is empty (though {@code recordsMatched}
|
||||
* still reports the full match count); only a Complete query exposes rows. An unknown queryId is an
|
||||
* error on real AWS — and a query that has fallen out of the bounded LRU cache 404s the same way.
|
||||
*/
|
||||
public QueryState getQueryResults(String queryId) {
|
||||
QueryRecord rec = insightsQueries.get(queryId);
|
||||
if (rec == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The specified query does not exist.", 400);
|
||||
}
|
||||
return rec.snapshot(clock.getAsLong());
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop an in-progress query. Mirrors AWS StopQuery: a running query is cancelled and returns
|
||||
* {@code success=true}; an already-ended query throws {@code InvalidParameterException} ("not
|
||||
* running"); an unknown queryId throws {@code ResourceNotFoundException}.
|
||||
*/
|
||||
public boolean stopQuery(String queryId) {
|
||||
QueryRecord rec = insightsQueries.get(queryId);
|
||||
if (rec == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The specified query does not exist.", 400);
|
||||
}
|
||||
if (rec.stopIfRunning(clock.getAsLong())) {
|
||||
return true;
|
||||
}
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"The query you are trying to stop is not running.", 400);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Subscription Filters ────────────────────────────
|
||||
|
||||
public void putSubscriptionFilter(String logGroupName, String filterName, String filterPattern,
|
||||
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Minimal CloudWatch Logs Insights query engine.
|
||||
*
|
||||
* <p>Implements the subset of the Logs Insights query language that clients use in practice:
|
||||
* <ul>
|
||||
* <li>{@code fields a, b, ...} — projection (defaults to {@code @timestamp, @message})</li>
|
||||
* <li>{@code filter <field> = 'v'} / {@code filter <field> != 'v'} — equality / inequality</li>
|
||||
* <li>{@code sort <field> [asc|desc]}</li>
|
||||
* <li>{@code dedup <field, ...>} — keep the first row per unique tuple (applied after sort)</li>
|
||||
* <li>{@code limit N}</li>
|
||||
* </ul>
|
||||
* Fields may be the synthetic {@code @timestamp} / {@code @message} / {@code @ingestionTime} /
|
||||
* {@code @ptr}, or a dotted path into the JSON log message (e.g. {@code params.job_id}, {@code level}).
|
||||
*
|
||||
* <p>This is intentionally <em>not</em> a full Insights implementation: unsupported commands
|
||||
* (e.g. {@code stats}, {@code parse}) are ignored with a warning. Pipes ({@code |}) inside quoted
|
||||
* filter values are respected and do not split the query into stages.
|
||||
*/
|
||||
final class LogsInsightsQuery {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LogsInsightsQuery.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final DateTimeFormatter TS_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(ZoneOffset.UTC);
|
||||
|
||||
private final List<String> fields = new ArrayList<>();
|
||||
private final List<Filter> filters = new ArrayList<>();
|
||||
private String sortField;
|
||||
private boolean sortDesc;
|
||||
private List<String> dedupFields;
|
||||
private Integer limit;
|
||||
|
||||
private record Filter(String field, boolean negate, String value) {}
|
||||
|
||||
private LogsInsightsQuery() {}
|
||||
|
||||
static LogsInsightsQuery parse(String queryString) {
|
||||
LogsInsightsQuery q = new LogsInsightsQuery();
|
||||
if (queryString != null && !queryString.isBlank()) {
|
||||
for (String rawStage : splitStages(queryString)) {
|
||||
String stage = rawStage.trim();
|
||||
if (stage.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String[] parts = stage.split("\\s+", 2);
|
||||
String cmd = parts[0].toLowerCase();
|
||||
String args = parts.length > 1 ? parts[1].trim() : "";
|
||||
q.applyStage(cmd, args);
|
||||
}
|
||||
}
|
||||
if (q.fields.isEmpty()) {
|
||||
q.fields.add("@timestamp");
|
||||
q.fields.add("@message");
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a query into pipeline stages on {@code |}, ignoring pipes inside single- or double-quoted
|
||||
* values (so {@code filter x = 'a|b'} stays one stage). Escaped quotes are not interpreted.
|
||||
*/
|
||||
private static List<String> splitStages(String query) {
|
||||
List<String> stages = new ArrayList<>();
|
||||
StringBuilder current = new StringBuilder();
|
||||
char quote = 0;
|
||||
for (int i = 0; i < query.length(); i++) {
|
||||
char c = query.charAt(i);
|
||||
if (quote != 0) {
|
||||
if (c == quote) {
|
||||
quote = 0;
|
||||
}
|
||||
current.append(c);
|
||||
} else if (c == '\'' || c == '"') {
|
||||
quote = c;
|
||||
current.append(c);
|
||||
} else if (c == '|') {
|
||||
stages.add(current.toString());
|
||||
current.setLength(0);
|
||||
} else {
|
||||
current.append(c);
|
||||
}
|
||||
}
|
||||
stages.add(current.toString());
|
||||
return stages;
|
||||
}
|
||||
|
||||
private void applyStage(String cmd, String args) {
|
||||
switch (cmd) {
|
||||
case "fields", "display" -> splitCsv(args, fields);
|
||||
case "filter", "where" -> {
|
||||
Filter f = parseFilter(args);
|
||||
if (f != null) {
|
||||
filters.add(f);
|
||||
}
|
||||
}
|
||||
case "sort", "order" -> {
|
||||
String[] s = args.split("\\s+");
|
||||
if (s.length > 0 && !s[0].isEmpty()) {
|
||||
sortField = s[0].trim();
|
||||
sortDesc = s.length > 1 && s[1].trim().equalsIgnoreCase("desc");
|
||||
}
|
||||
}
|
||||
case "dedup" -> {
|
||||
dedupFields = new ArrayList<>();
|
||||
splitCsv(args, dedupFields);
|
||||
}
|
||||
case "limit" -> {
|
||||
try {
|
||||
limit = Integer.parseInt(args.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.warnv("Ignoring invalid Logs Insights limit: {0}", args);
|
||||
}
|
||||
}
|
||||
default -> LOG.warnv("Ignoring unsupported Logs Insights command: {0}", cmd);
|
||||
}
|
||||
}
|
||||
|
||||
private static void splitCsv(String args, List<String> target) {
|
||||
for (String token : args.split(",")) {
|
||||
String t = token.trim();
|
||||
if (!t.isEmpty()) {
|
||||
target.add(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Filter parseFilter(String expr) {
|
||||
// Scan for the operator OUTSIDE any quoted value, taking the leftmost one and checking
|
||||
// '!=' / '==' before '='. This avoids mistaking an operator inside a quoted literal
|
||||
// (e.g. filter x = 'a==b') for the real one.
|
||||
char quote = 0;
|
||||
for (int i = 0; i < expr.length(); i++) {
|
||||
char c = expr.charAt(i);
|
||||
if (quote != 0) {
|
||||
if (c == quote) {
|
||||
quote = 0;
|
||||
}
|
||||
} else if (c == '\'' || c == '"') {
|
||||
quote = c;
|
||||
} else if (i > 0) {
|
||||
String op = expr.startsWith("!=", i) ? "!="
|
||||
: expr.startsWith("==", i) ? "=="
|
||||
: c == '=' ? "="
|
||||
: null;
|
||||
if (op != null) {
|
||||
String field = expr.substring(0, i).trim();
|
||||
String value = unquote(expr.substring(i + op.length()).trim());
|
||||
return new Filter(field, op.equals("!="), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
LOG.warnv("Ignoring unsupported Logs Insights filter: {0}", expr);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String unquote(String s) {
|
||||
if (s.length() >= 2) {
|
||||
char first = s.charAt(0);
|
||||
char last = s.charAt(s.length() - 1);
|
||||
if ((first == '\'' && last == '\'') || (first == '"' && last == '"')) {
|
||||
return s.substring(1, s.length() - 1);
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate the query against the given events.
|
||||
*
|
||||
* @return ordered result rows; each row maps a projected field name to its string value,
|
||||
* in the order declared by {@code fields}, with a synthetic {@code @ptr} appended.
|
||||
*/
|
||||
List<LinkedHashMap<String, String>> evaluate(List<LogEvent> events, int defaultLimit) {
|
||||
List<Row> rows = new ArrayList<>(events.size());
|
||||
for (LogEvent e : events) {
|
||||
rows.add(new Row(e, tryParse(e.getMessage())));
|
||||
}
|
||||
|
||||
// filter (logical AND across all filter stages)
|
||||
List<Row> matched = new ArrayList<>();
|
||||
for (Row row : rows) {
|
||||
if (passesFilters(row)) {
|
||||
matched.add(row);
|
||||
}
|
||||
}
|
||||
|
||||
// sort
|
||||
if (sortField != null) {
|
||||
Comparator<Row> cmp = comparatorFor(sortField);
|
||||
matched.sort(sortDesc ? cmp.reversed() : cmp);
|
||||
} else if (dedupFields != null && !dedupFields.isEmpty()) {
|
||||
// AWS: when dedup runs without an explicit preceding sort, results are ordered by the
|
||||
// default descending @timestamp sort before duplicates are discarded, so the first
|
||||
// (newest) row per tuple is the one kept. Reuse the @timestamp comparator reversed so
|
||||
// the sequence/eventId tie-break stays consistent with an explicit `sort @timestamp desc`.
|
||||
matched.sort(comparatorFor("@timestamp").reversed());
|
||||
}
|
||||
|
||||
// dedup (keep first occurrence per tuple, after sorting)
|
||||
if (dedupFields != null && !dedupFields.isEmpty()) {
|
||||
List<Row> deduped = new ArrayList<>();
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (Row row : matched) {
|
||||
StringBuilder key = new StringBuilder();
|
||||
for (String df : dedupFields) {
|
||||
key.append(resolve(row, df)).append('\0');
|
||||
}
|
||||
if (seen.add(key.toString())) {
|
||||
deduped.add(row);
|
||||
}
|
||||
}
|
||||
matched = deduped;
|
||||
}
|
||||
|
||||
// limit
|
||||
int max = limit != null ? Math.min(limit, defaultLimit) : defaultLimit;
|
||||
if (max >= 0 && matched.size() > max) {
|
||||
matched = matched.subList(0, max);
|
||||
}
|
||||
|
||||
// project
|
||||
List<LinkedHashMap<String, String>> out = new ArrayList<>(matched.size());
|
||||
for (Row row : matched) {
|
||||
LinkedHashMap<String, String> projected = new LinkedHashMap<>();
|
||||
for (String field : fields) {
|
||||
String value = resolve(row, field);
|
||||
projected.put(field, value != null ? value : "");
|
||||
}
|
||||
projected.putIfAbsent("@ptr", row.event.getEventId());
|
||||
out.add(projected);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private boolean passesFilters(Row row) {
|
||||
for (Filter f : filters) {
|
||||
String actual = resolve(row, f.field());
|
||||
boolean equals = actual != null && actual.equals(f.value());
|
||||
boolean fails = f.negate() ? equals : !equals;
|
||||
if (fails) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Comparator<Row> comparatorFor(String field) {
|
||||
if ("@timestamp".equals(field)) {
|
||||
return Comparator.<Row>comparingLong(r -> r.event.getTimestamp())
|
||||
.thenComparingLong(r -> r.event.getSequence())
|
||||
.thenComparing(r -> r.event.getEventId());
|
||||
}
|
||||
if ("@ingestionTime".equals(field)) {
|
||||
// ingestionTime is one wall-clock value per PutLogEvents batch, so whole batches tie on it;
|
||||
// the sequence/eventId tie-break keeps same-batch events in a stable ingestion order.
|
||||
return Comparator.<Row>comparingLong(r -> r.event.getIngestionTime())
|
||||
.thenComparingLong(r -> r.event.getSequence())
|
||||
.thenComparing(r -> r.event.getEventId());
|
||||
}
|
||||
return Comparator.comparing(r -> {
|
||||
String v = resolve(r, field);
|
||||
return v != null ? v : "";
|
||||
});
|
||||
}
|
||||
|
||||
private String resolve(Row row, String field) {
|
||||
switch (field) {
|
||||
case "@timestamp":
|
||||
return TS_FORMAT.format(Instant.ofEpochMilli(row.event.getTimestamp()));
|
||||
case "@ingestionTime":
|
||||
return TS_FORMAT.format(Instant.ofEpochMilli(row.event.getIngestionTime()));
|
||||
case "@message":
|
||||
return row.event.getMessage();
|
||||
case "@ptr":
|
||||
return row.event.getEventId();
|
||||
default:
|
||||
if (row.json == null) {
|
||||
return null;
|
||||
}
|
||||
JsonNode node = row.json;
|
||||
for (String seg : field.split("\\.")) {
|
||||
if (node == null) {
|
||||
return null;
|
||||
}
|
||||
node = node.get(seg);
|
||||
}
|
||||
if (node == null || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
return node.isValueNode() ? node.asText() : node.toString();
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode tryParse(String message) {
|
||||
if (message == null || message.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.readTree(message);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Row {
|
||||
final LogEvent event;
|
||||
final JsonNode json;
|
||||
|
||||
Row(LogEvent event, JsonNode json) {
|
||||
this.event = event;
|
||||
this.json = json;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user