diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index e9e1d6694a..6ec7758280 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -310,13 +310,19 @@ with `InvalidParameterException`. Supported commands: |---|---| | `fields a, b, ...` | Projection. Defaults to `@timestamp, @message`. `display` is an alias | | `filter = 'v'` | Equality. `!=` and `==` are also accepted; `where` is an alias. An unquoted value must be a number and compares by value, so `n = 2` matches `2` and `2.0`. Comparisons can be joined with `or` (any case) and grouped with parentheses, for example `filter (type = 'A' or type = 'B')` | +| `filter ispresent(field)` | Keeps events whose field exists and is not JSON `null` | +| `filter field like /regex/` | Matches with a regular expression; `like 'text'` matches a substring, and `not like` negates either form | +| `stats ... [by field, bin(1h)]` | Supports `count(*)`, `count(field)`, `count_distinct(field)`, and `latest(field)`, with optional aliases and grouping fields or time bins. Place `stats` after any filters and before `sort` or `limit` | | `sort [asc\|desc]` | `order` is an alias | | `dedup ` | Keeps the first row per unique tuple, applied after sorting | | `limit N` | The effective cap is the smallest of this value, the `StartQuery` `limit` parameter, and `FLOCI_SERVICES_CLOUDWATCHLOGS_MAX_EVENTS_PER_QUERY` | Fields may be `@timestamp`, `@message`, `@ingestionTime`, `@ptr`, or a dotted path into -a JSON log message (for example `level` or `params.job_id`). A `@ptr` column is always -included in each result row, appended unless `fields` already names it. +a JSON log message (for example `level` or `params.job_id`). A `@ptr` column is included +in each nonaggregated result row, appended unless `fields` already names it. A `stats` +result contains only its aggregate and grouping columns. For `stats` queries, +`statistics.recordsMatched` counts matching log events, not aggregate result rows. For +nonaggregated queries, it counts rows returned after `dedup` and `limit`. A command or filter operator outside this subset fails the query instead of being dropped: `StartQuery` still returns a query id, and `GetQueryResults` reports `status: Failed` with no @@ -326,16 +332,16 @@ degrade silently, so it is worth knowing how each case behaves: | Input | Result | |---|---| -| An unsupported command (`stats`, `parse`, ...) | The query fails. Logged as `Unsupported command: stats` | -| A `filter` whose operator is not `=`, `!=` or `==`, for example `<`, `<=`, `>`, `>=`, `like /ERROR/` or `=~ /ERROR/` | The query fails. Logged as `Unsupported filter expression: ...` | -| A `filter` using `and`, `not` or `\|\|`, or with text after the value, as in `filter level = 'ERROR' x` | The query fails. AWS evaluates `and` and `not`, ignores the trailing text, and rejects an unparenthesized `\|\|` at `StartQuery` with `MalformedQueryException` (use `or`) | +| An unsupported command (`parse`, ...) | The query fails. Logged as `Unsupported command: parse` | +| A `filter` whose operator is not supported, for example `<`, `<=`, `>`, `>=` or `=~ /ERROR/` | The query fails. Logged as `Unsupported filter expression: ...` | +| A `filter` using `and`, a standalone `not` or `\|\|`, or with text after the value, as in `filter level = 'ERROR' x` | The query fails. AWS evaluates `and` and `not`, ignores the trailing text, and rejects an unparenthesized `\|\|` at `StartQuery` with `MalformedQueryException` (use `or`) | | A blank query, or an empty stage as in a trailing `\|` | The query fails. AWS rejects it at `StartQuery` | -| A `filter` with a backslash escape, a backtick-quoted field name, an expression such as `1+1` in place of the field, or an unquoted value that is not a number, such as `level = ERROR` or `n = 1+1` | The query fails. AWS interprets them | +| A quoted filter value with a backslash escape, a backtick-quoted field name, an expression such as `1+1` in place of the field, or an unquoted value that is not a number, such as `level = ERROR` or `n = 1+1` | The query fails. Backslash escapes within `like /regex/` are supported | | A projected field that does not exist | Rendered as an empty string. No warning | | A `sort` direction other than `asc` / `desc` | Treated as ascending. No warning | -For matching events by a pattern, `FilterLogEvents` is the more predictable option today: it -applies the filter pattern syntax (`?ERROR ?WARN`, `{ $.level = "ERROR" }`, and so on) as AWS does. +For CloudWatch filter pattern syntax (`?ERROR ?WARN`, `{ $.level = "ERROR" }`, and so on), +use `FilterLogEvents`. ### Reading events past the limit diff --git a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsService.java index 06c8e15b45..6401e4d889 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsService.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsService.java @@ -1110,22 +1110,24 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable { private final String failureReason; private boolean cancelled; - QueryRecord(List> rows, long recordsScanned, long completeAtMs) { - this(rows, recordsScanned, completeAtMs, null); + QueryRecord(List> rows, long recordsScanned, + long recordsMatched, long completeAtMs) { + this(rows, recordsScanned, recordsMatched, completeAtMs, null); } - private QueryRecord(List> rows, long recordsScanned, long completeAtMs, + private QueryRecord(List> rows, long recordsScanned, + long recordsMatched, long completeAtMs, String failureReason) { this.rows = rows; this.recordsScanned = recordsScanned; - this.recordsMatched = rows.size(); + this.recordsMatched = recordsMatched; this.completeAtMs = completeAtMs; this.failureReason = failureReason; } /** A query whose string could not be fully evaluated: it never produces rows and ends up {@code Failed}. */ static QueryRecord failed(long recordsScanned, long completeAtMs, String failureReason) { - return new QueryRecord(List.of(), recordsScanned, completeAtMs, failureReason); + return new QueryRecord(List.of(), recordsScanned, 0, completeAtMs, failureReason); } private InsightsQueryStatus status(long nowMs) { @@ -1142,7 +1144,8 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable { * 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. A Failed query exposes neither: it has no rows and no matches to report, + * evaluated count (matched events for stats, returned rows otherwise). A Failed query exposes + * neither: it has no rows and no matches to report, * so both fields are empty and zero respectively. */ synchronized QueryState snapshot(long nowMs) { @@ -1221,9 +1224,10 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable { } int effectiveLimit = (limit != null && limit > 0) ? Math.min(limit, maxEventsPerQuery) : maxEventsPerQuery; - List> rows = parsedQuery.evaluate(gathered, effectiveLimit); + LogsInsightsQuery.Evaluation evaluation = parsedQuery.evaluate(gathered, effectiveLimit); + List> rows = evaluation.rows(); - insightsQueries.put(queryId, new QueryRecord(rows, gathered.size(), completeAtMs)); + insightsQueries.put(queryId, new QueryRecord(rows, gathered.size(), evaluation.recordsMatched(), 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; @@ -1232,7 +1236,7 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable { /** * 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; once the query string is found to contain unsupported syntax + * still reports the evaluated count; once the query string contains unsupported syntax * ({@code Failed}) both the rows and {@code recordsMatched} are empty, since such a query is never * evaluated. 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. diff --git a/src/main/java/io/floci/aws/services/cloudwatch/logs/LogsInsightsQuery.java b/src/main/java/io/floci/aws/services/cloudwatch/logs/LogsInsightsQuery.java index 00aa6f5bfe..15e76569cb 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/logs/LogsInsightsQuery.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/logs/LogsInsightsQuery.java @@ -16,7 +16,10 @@ import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.Set; +import java.util.regex.Matcher; import java.util.regex.Pattern; /** @@ -24,22 +27,24 @@ import java.util.regex.Pattern; * *

Implements the subset of the Logs Insights query language that clients use in practice: *

    - *
  • {@code fields a, b, ...} — projection (defaults to {@code @timestamp, @message})
  • - *
  • {@code filter = 'v'} / {@code filter != 'v'} — equality / inequality
  • + *
  • {@code fields a, b, ...}: projection (defaults to {@code @timestamp, @message})
  • + *
  • {@code filter = 'v'} / {@code filter != 'v'}: equality / inequality
  • + *
  • {@code filter ispresent(field)} and {@code filter field like /regex/}: presence and pattern matching
  • *
  • {@code filter a = 'x' or b = 'y'}: any comparison matches; {@code or} in any case, with parentheses
  • + *
  • {@code stats count(*) by bin(1h)}: aggregation with optional grouping
  • *
  • {@code sort [asc|desc]}
  • - *
  • {@code dedup } — keep the first row per unique tuple (applied after sort)
  • + *
  • {@code dedup }: keep the first row per unique tuple (applied after sort)
  • *
  • {@code limit N}
  • *
* 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}). * *

This is intentionally not a full Insights implementation: unsupported commands - * (e.g. {@code stats}, {@code parse}) and unsupported filter operators (e.g. {@code >=}, - * {@code like}) mark the query as unsupported (see {@link #isUnsupported()}) rather than being + * (e.g. {@code parse}) and unsupported filter operators (e.g. {@code >=}) mark the query as unsupported + * (see {@link #isUnsupported()}) rather than being * silently dropped, so the caller can fail the query instead of returning a result set that does - * not correspond to what was asked. Pipes ({@code |}) inside quoted filter values are respected - * and do not split the query into stages. + * not correspond to what was asked. Pipes ({@code |}) inside quoted filter values or regular + * expressions are respected and do not split the query into stages. */ final class LogsInsightsQuery { @@ -50,6 +55,14 @@ final class LogsInsightsQuery { private static final Pattern NUMBER = Pattern.compile("-?\\d+(\\.\\d+)?"); // Possessive, so a long dotted path is matched in a loop rather than one stack frame per segment. private static final Pattern FIELD = Pattern.compile("[@A-Za-z_]\\w*(?:\\.\\w+)*+"); + private static final Pattern LIKE_FILTER = Pattern.compile( + "(?i)^([@A-Za-z_]\\w*(?:\\.\\w+)*+)\\s+(not\\s+)?like\\s+(.+)$"); + private static final Pattern STATS_AGGREGATE = Pattern.compile( + "(?i)^(count|count_distinct|countDistinct|latest)\\(\\s*(\\*|[@A-Za-z_]\\w*(?:\\.\\w+)*+)?\\s*\\)" + + "(?:\\s+as\\s+([@A-Za-z_]\\w*))?$" + ); + private static final Pattern TIME_BIN = Pattern.compile("(?i)^bin\\(\\s*(\\d+)\\s*(ms|s|m|h)\\s*\\)$"); + private static final Pattern STATS_BY = Pattern.compile("(?i)\\s+by\\s+"); private final List fields = new ArrayList<>(); private final List> filters = new ArrayList<>(); @@ -57,9 +70,25 @@ final class LogsInsightsQuery { private boolean sortDesc; private List dedupFields; private Integer limit; + private StatsSpec stats; + private boolean sortAfterStats; private String unsupportedReason; - private record Filter(String field, boolean negate, String value, boolean numeric) {} + private enum FilterOp { EQUALS, NOT_EQUALS, PRESENT, LIKE, NOT_LIKE } + + // RE2J Pattern is qualified because java.util.regex.Pattern parses query syntax in this class. + private record Filter(String field, FilterOp op, String value, boolean numeric, + com.google.re2j.Pattern regex) {} + + private enum AggregateOp { COUNT, COUNT_DISTINCT, LATEST } + + private record AggregateSpec(String name, AggregateOp op, String field) {} + + private record GroupSpec(String name, String field, long binMillis) {} + + private record StatsSpec(List aggregates, List groups) {} + + record Evaluation(List> rows, long recordsMatched) {} private LogsInsightsQuery() {} @@ -118,9 +147,8 @@ final class LogsInsightsQuery { } /** - * The first index at or after {@code from} (itself outside quoted text) that is outside single- or - * double-quoted text and is not a quote itself, or {@code s.length()}. Escaped quotes are not - * interpreted; an unclosed quote runs to the end. + * The first index at or after {@code from} outside quoted text and slash-delimited regexes, + * or {@code s.length()}. Escaped quotes are not interpreted; an unclosed quote runs to the end. */ private static int unquoted(String s, int from) { int i = from; @@ -128,14 +156,37 @@ final class LogsInsightsQuery { int close = s.indexOf(s.charAt(i), i + 1); i = close < 0 ? s.length() : close + 1; } + while (i < s.length() && s.charAt(i) == '/' && i > 0 && Character.isWhitespace(s.charAt(i - 1))) { + int close = firstUnescapedSlash(s, i + 1); + i = close >= 0 ? close + 1 : s.length(); + } return i; } + /** First unescaped slash at or after {@code from}, or -1 when none exists. */ + private static int firstUnescapedSlash(String s, int from) { + boolean escaped = false; + for (int i = from; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '/' && !escaped) { + return i; + } + escaped = c == '\\' && !escaped; + } + return -1; + } + private void applyStage(String cmd, String args) { switch (cmd) { - case "fields", "display" -> splitCsv(args, fields); + case "fields", "display" -> { + if (stats != null) { + noteUnsupported("Fields after stats are unsupported"); + } else { + splitCsv(args, fields); + } + } case "filter", "where" -> { - List anyOf = args.indexOf('\\') < 0 ? parseDisjunction(args) : null; + List anyOf = stats == null ? parseDisjunction(args) : null; if (anyOf != null) { filters.add(anyOf); } else { @@ -147,11 +198,15 @@ final class LogsInsightsQuery { if (s.length > 0 && !s[0].isEmpty()) { sortField = s[0].trim(); sortDesc = s.length > 1 && s[1].trim().equalsIgnoreCase("desc"); + sortAfterStats = stats != null; } else { noteUnsupported("Sort command is missing its field"); } } case "dedup" -> { + if (stats != null) { + noteUnsupported("Dedup after stats is unsupported"); + } dedupFields = new ArrayList<>(); splitCsv(args, dedupFields); if (dedupFields.isEmpty()) { @@ -165,10 +220,98 @@ final class LogsInsightsQuery { noteUnsupported("Invalid limit argument: " + args); } } + case "stats" -> { + if (stats != null || sortField != null || limit != null || dedupFields != null + || (stats = parseStats(args)) == null) { + noteUnsupported("Unsupported stats expression: " + args); + } + } default -> noteUnsupported("Unsupported command: " + cmd); } } + private static StatsSpec parseStats(String args) { + Matcher byClause = STATS_BY.matcher(args); + int byStart = -1; + int byEnd = -1; + while (byClause.find()) { + byStart = byClause.start(); + byEnd = byClause.end(); + } + String aggregateText = byStart < 0 ? args : args.substring(0, byStart); + String groupText = byStart < 0 ? "" : args.substring(byEnd); + List aggregateTokens = new ArrayList<>(); + splitCsv(aggregateText, aggregateTokens); + if (aggregateTokens.isEmpty()) { + return null; + } + List aggregates = new ArrayList<>(); + Set outputNames = new HashSet<>(); + for (String token : aggregateTokens) { + Matcher match = STATS_AGGREGATE.matcher(token); + if (!match.matches()) { + return null; + } + String function = match.group(1).toLowerCase(Locale.ROOT); + String field = match.group(2); + AggregateOp op = switch (function) { + case "count" -> AggregateOp.COUNT; + case "count_distinct", "countdistinct" -> AggregateOp.COUNT_DISTINCT; + default -> AggregateOp.LATEST; + }; + if (op != AggregateOp.COUNT && (field == null || field.equals("*"))) { + return null; + } + String name = match.group(3) != null ? match.group(3) : token; + if (!outputNames.add(name)) { + return null; + } + aggregates.add(new AggregateSpec(name, op, field)); + } + List groups = new ArrayList<>(); + if (byStart >= 0) { + List groupTokens = new ArrayList<>(); + splitCsv(groupText, groupTokens); + if (groupTokens.isEmpty()) { + return null; + } + for (String token : groupTokens) { + if (!outputNames.add(token)) { + return null; + } + Matcher bin = TIME_BIN.matcher(token); + if (bin.matches()) { + long amount; + try { + amount = Long.parseLong(bin.group(1)); + } catch (NumberFormatException e) { + return null; + } + long unit = switch (bin.group(2).toLowerCase(Locale.ROOT)) { + case "ms" -> 1L; + case "s" -> 1000L; + case "m" -> 60_000L; + default -> 3_600_000L; + }; + long cap = switch (bin.group(2).toLowerCase(Locale.ROOT)) { + case "ms" -> 1000L; + case "s", "m" -> 60L; + default -> 24L; + }; + if (amount <= 0) { + return null; + } + groups.add(new GroupSpec(token, "@timestamp", Math.min(amount, cap) * unit)); + } else if (FIELD.matcher(token).matches()) { + groups.add(new GroupSpec(token, token, 0)); + } else { + return null; + } + } + } + return new StatsSpec(aggregates, groups); + } + /** * Record the first unsupported command or filter expression the query contains. Only the * first is kept: it is enough to fail the whole query, and later stages may reference fields @@ -262,6 +405,34 @@ final class LogsInsightsQuery { } private static Filter parseFilter(String expr) { + String body = expr.trim(); + if (body.regionMatches(true, 0, "ispresent(", 0, 10) && body.endsWith(")")) { + String field = body.substring(10, body.length() - 1).trim(); + return FIELD.matcher(field).matches() ? new Filter(field, FilterOp.PRESENT, null, false, null) : null; + } + Matcher like = LIKE_FILTER.matcher(body); + if (like.matches()) { + String raw = like.group(3).trim(); + boolean negate = like.group(2) != null; + if (raw.length() >= 2 && raw.startsWith("/") && raw.endsWith("/")) { + if (firstUnescapedSlash(raw, 1) != raw.length() - 1) { + return null; + } + try { + return new Filter(like.group(1), negate ? FilterOp.NOT_LIKE : FilterOp.LIKE, + null, false, com.google.re2j.Pattern.compile(raw.substring(1, raw.length() - 1))); + } catch (IllegalArgumentException e) { + return null; + } + } + if (raw.startsWith("'") || raw.startsWith("\"")) { + String value = literal(raw); + return value != null && raw.indexOf('\\') < 0 + ? new Filter(like.group(1), negate ? FilterOp.NOT_LIKE : FilterOp.LIKE, + value, false, null) : null; + } + return null; + } // Take the leftmost operator outside quoted text, checking '!=' / '==' before '=', so an // operator inside a quoted literal (e.g. filter x = 'a==b') is not mistaken for the real one. for (int i = unquoted(expr, 0); i < expr.length(); i = unquoted(expr, i + 1)) { @@ -279,10 +450,11 @@ final class LogsInsightsQuery { String field = expr.substring(0, i).trim(); String raw = expr.substring(i + op.length()).trim(); String value = literal(raw); - if (value == null || !FIELD.matcher(field).matches()) { + if (value == null || raw.indexOf('\\') >= 0 || !FIELD.matcher(field).matches()) { return null; } - return new Filter(field, op.equals("!="), value, NUMBER.matcher(raw).matches()); + return new Filter(field, op.equals("!=") ? FilterOp.NOT_EQUALS : FilterOp.EQUALS, + value, NUMBER.matcher(raw).matches(), null); } } } @@ -304,10 +476,12 @@ final class LogsInsightsQuery { /** * 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. + * @return ordered result rows and the count of matching events for stats queries, or returned + * rows after dedup and limit for nonaggregated queries. Nonaggregated rows map projected + * fields to values and append a synthetic {@code @ptr}; stats rows contain only aggregate + * and grouping fields. */ - List> evaluate(List events, int defaultLimit) { + Evaluation evaluate(List events, int defaultLimit) { List rows = new ArrayList<>(events.size()); for (LogEvent e : events) { rows.add(new Row(e, tryParse(e.getMessage()))); @@ -321,6 +495,10 @@ final class LogsInsightsQuery { } } + if (stats != null) { + return new Evaluation(evaluateStats(matched, defaultLimit), matched.size()); + } + // sort if (sortField != null) { Comparator cmp = comparatorFor(sortField); @@ -366,9 +544,98 @@ final class LogsInsightsQuery { projected.putIfAbsent("@ptr", row.event.getEventId()); out.add(projected); } + return new Evaluation(out, out.size()); + } + + private List> evaluateStats(List matched, int defaultLimit) { + Map, List> grouped = new LinkedHashMap<>(); + for (Row row : matched) { + List key = new ArrayList<>(stats.groups().size()); + for (GroupSpec group : stats.groups()) { + key.add(group.binMillis() > 0 + ? TS_FORMAT.format(Instant.ofEpochMilli( + Math.floorDiv(row.event.getTimestamp(), group.binMillis()) * group.binMillis())) + : resolve(row, group.field())); + } + List accumulators = grouped.computeIfAbsent(key, ignored -> { + List created = new ArrayList<>(stats.aggregates().size()); + for (int i = 0; i < stats.aggregates().size(); i++) { + created.add(new AggregateAccumulator()); + } + return created; + }); + for (int i = 0; i < stats.aggregates().size(); i++) { + AggregateSpec aggregate = stats.aggregates().get(i); + AggregateAccumulator accumulator = accumulators.get(i); + String value = aggregate.field() == null || aggregate.field().equals("*") + ? null : resolve(row, aggregate.field()); + switch (aggregate.op()) { + case COUNT -> { + if (aggregate.field() == null || aggregate.field().equals("*") || value != null) { + accumulator.count++; + } + } + case COUNT_DISTINCT -> { + if (value != null) { + accumulator.distinct.add(value); + } + } + case LATEST -> { + if (value != null && row.event.getTimestamp() >= accumulator.latestTimestamp) { + accumulator.latest = value; + accumulator.latestTimestamp = row.event.getTimestamp(); + } + } + } + } + } + if (grouped.isEmpty() && stats.groups().isEmpty()) { + List empty = new ArrayList<>(); + for (int i = 0; i < stats.aggregates().size(); i++) { + empty.add(new AggregateAccumulator()); + } + grouped.put(List.of(), empty); + } + List> out = new ArrayList<>(grouped.size()); + for (Map.Entry, List> entry : grouped.entrySet()) { + LinkedHashMap result = new LinkedHashMap<>(); + for (int i = 0; i < stats.aggregates().size(); i++) { + AggregateSpec aggregate = stats.aggregates().get(i); + AggregateAccumulator accumulator = entry.getValue().get(i); + result.put(aggregate.name(), switch (aggregate.op()) { + case COUNT -> Long.toString(accumulator.count); + case COUNT_DISTINCT -> Integer.toString(accumulator.distinct.size()); + case LATEST -> accumulator.latest == null ? "" : accumulator.latest; + }); + } + for (int i = 0; i < stats.groups().size(); i++) { + String value = entry.getKey().get(i); + result.put(stats.groups().get(i).name(), value == null ? "" : value); + } + out.add(result); + } + if (sortAfterStats && sortField != null) { + boolean numeric = stats.aggregates().stream().anyMatch(aggregate -> + aggregate.name().equals(sortField) && aggregate.op() != AggregateOp.LATEST); + Comparator> cmp = numeric + ? Comparator.comparing(row -> new BigDecimal(row.get(sortField))) + : Comparator.comparing(row -> row.getOrDefault(sortField, "")); + out.sort(sortDesc ? cmp.reversed() : cmp); + } + int max = limit != null ? Math.min(limit, defaultLimit) : defaultLimit; + if (max >= 0 && out.size() > max) { + return new ArrayList<>(out.subList(0, max)); + } return out; } + private static final class AggregateAccumulator { + long count; + final Set distinct = new HashSet<>(); + String latest; + long latestTimestamp = Long.MIN_VALUE; + } + private boolean passesFilters(Row row) { for (List anyOf : filters) { if (anyOf.stream().noneMatch(f -> matches(row, f))) { @@ -380,8 +647,19 @@ final class LogsInsightsQuery { private boolean matches(Row row, Filter f) { String actual = resolve(row, f.field()); - boolean equal = actual != null && (f.numeric() ? sameNumber(actual, f.value()) : actual.equals(f.value())); - return f.negate() != equal; + return switch (f.op()) { + case PRESENT -> actual != null; + case EQUALS, NOT_EQUALS -> { + boolean equal = actual != null + && (f.numeric() ? sameNumber(actual, f.value()) : actual.equals(f.value())); + yield f.op() == FilterOp.EQUALS ? equal : !equal; + } + case LIKE, NOT_LIKE -> { + boolean found = actual != null && (f.regex() != null + ? f.regex().matcher(actual).find() : actual.contains(f.value())); + yield actual != null && (f.op() == FilterOp.LIKE ? found : !found); + } + }; } /** A bare number compares by value on AWS, so {@code n = 2} matches 2, 2.0 and 02. */ diff --git a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsIntegrationTest.java new file mode 100644 index 0000000000..1888bd1d2c --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsIntegrationTest.java @@ -0,0 +1,62 @@ +package io.floci.aws.services.cloudwatch.logs; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; +import software.amazon.awssdk.services.cloudwatchlogs.model.GetQueryResultsResponse; +import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class CloudWatchLogsInsightsIntegrationTest { + + @Test + void sdkQueriesAggregateAndFilterJsonLogEvents() { + String group = "/floci/insights/" + UUID.randomUUID(); + long first = Instant.now().minus(1, ChronoUnit.HOURS) + .truncatedTo(ChronoUnit.HOURS).plusSeconds(10).toEpochMilli(); + try (CloudWatchLogsClient logs = AwsTestClients.create( + CloudWatchLogsClient.builder(), "test", Region.US_EAST_1)) { + logs.createLogGroup(request -> request.logGroupName(group)); + try { + logs.createLogStream(request -> request.logGroupName(group).logStreamName("stream")); + logs.putLogEvents(request -> request.logGroupName(group).logStreamName("stream") + .logEvents(List.of( + InputLogEvent.builder().timestamp(first).message( + "{\"id\":\"demo\",\"labels\":{\"result\":\"failure\"}}").build(), + InputLogEvent.builder().timestamp(first + 1000).message( + "{\"id\":\"other\"}").build()))); + + GetQueryResultsResponse stats = query(logs, group, first, + "fields @timestamp | stats count(*) as total by bin(1h) | limit 50"); + assertEquals("Complete", stats.statusAsString()); + assertEquals(1, stats.results().size()); + assertEquals("2", stats.results().getFirst().stream() + .filter(field -> field.field().equals("total")).findFirst().orElseThrow().value()); + assertEquals(2.0, stats.statistics().recordsMatched()); + + assertEquals(1, query(logs, group, first, + "fields id | filter ispresent(labels.result) | limit 50").results().size()); + assertEquals(1, query(logs, group, first, + "fields id | filter @message like /demo/ | limit 50").results().size()); + } finally { + logs.deleteLogGroup(request -> request.logGroupName(group)); + } + } + } + + private static GetQueryResultsResponse query(CloudWatchLogsClient logs, String group, long first, String expression) { + String queryId = logs.startQuery(request -> request.logGroupName(group) + .startTime(first / 1000 - 1).endTime(first / 1000 + 3600) + .queryString(expression)).queryId(); + return logs.getQueryResults(request -> request.queryId(queryId)); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java index e1aa9bb1ba..170d20e079 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java @@ -483,6 +483,154 @@ class CloudWatchLogsInsightsQueryTest { assertEquals("", state.rows().get(0).get("params.absent"), "an absent field projects as an empty string"); } + @Test + void queryFiltersOnPresentNestedFields() { + String group = "insights/present"; + createGroupStream(service, group, "s-1"); + putRaw(service, group, "s-1", BASE_MS + 1000, + "{\"labels\":{\"invocation_result\":\"failure\"},\"id\":\"present\"}"); + putRaw(service, group, "s-1", BASE_MS + 2000, "{\"id\":\"absent\"}"); + + CloudWatchLogsService.QueryState state = startQueryFor(group, + "fields id | filter ispresent(labels.invocation_result) | limit 50"); + assertEquals("Complete", state.status()); + assertEquals(List.of("present"), state.rows().stream().map(row -> row.get("id")).toList()); + } + + @Test + void queryFiltersOnLikeRegexAndSubstring() { + String group = "insights/like"; + createGroupStream(service, group, "s-1"); + putRaw(service, group, "s-1", BASE_MS + 1000, "{\"id\":\"match\",\"text\":\"demo failure\"}"); + putRaw(service, group, "s-1", BASE_MS + 2000, "{\"id\":\"other\",\"text\":\"success\"}"); + + for (String expression : List.of("text like /demo/", "text like 'demo'")) { + CloudWatchLogsService.QueryState state = startQueryFor(group, + "fields id | filter " + expression + " | limit 50"); + assertEquals("Complete", state.status(), expression); + assertEquals(List.of("match"), state.rows().stream().map(row -> row.get("id")).toList()); + } + assertEquals(List.of("other"), rowsFor(group, "fields id | filter text not like /demo/") + .stream().map(row -> row.get("id")).toList()); + assertEquals(2, rowsFor(group, "fields id | filter text like /demo|success/").size()); + assertEquals(List.of("match"), rowsFor(group, "fields id | filter @message like /demo/") + .stream().map(row -> row.get("id")).toList()); + assertEquals(List.of("match"), rowsFor(group, "fields id | filter text like /demo\\sfailure/") + .stream().map(row -> row.get("id")).toList()); + } + + @Test + void unsupportedJoinedRegexFiltersFailInsteadOfReturningWrongRows() { + String group = "insights/joined-regex"; + createGroupStream(service, group, "s-1"); + putRaw(service, group, "s-1", BASE_MS + 1000, "{\"id\":\"match\",\"text\":\"demo failure\"}"); + putRaw(service, group, "s-1", BASE_MS + 2000, "{\"id\":\"other\",\"text\":\"success\"}"); + + for (String expression : List.of( + "text like /demo/ and text like /success/", + "text not like /demo/ and text not like /success/")) { + CloudWatchLogsService.QueryState state = startQueryFor(group, "fields id | filter " + expression); + assertEquals("Failed", state.status(), expression); + assertTrue(state.rows().isEmpty(), expression); + assertNotNull(state.failureReason(), expression); + } + assertEquals(2, rowsFor(group, "fields id | filter text like /demo/ or text like /success/").size()); + } + + @Test + void regexWithAnEvenNumberOfBackslashesKeepsTheFollowingStage() { + String group = "insights/regex-backslash"; + createGroupStream(service, group, "s-1"); + putRaw(service, group, "s-1", BASE_MS + 1000, "a\\"); + + CloudWatchLogsService.QueryState state = startQueryFor(group, + "fields @message | filter @message like /a\\\\/ | limit 50"); + assertEquals("Complete", state.status()); + assertEquals(List.of("a\\"), state.rows().stream().map(row -> row.get("@message")).toList()); + } + + @Test + void escapedSlashInRegexStaysInsideTheLiteral() { + String group = "insights/regex-slash"; + createGroupStream(service, group, "s-1"); + putRaw(service, group, "s-1", BASE_MS + 1000, "a/b"); + + assertEquals(List.of("a/b"), rowsFor(group, "fields @message | filter @message like /a\\/b/") + .stream().map(row -> row.get("@message")).toList()); + } + + @Test + void escapedSlashInRegexKeepsDisjunctionAndFollowingStage() { + String group = "insights/regex-slash-stages"; + createGroupStream(service, group, "s-1"); + putRaw(service, group, "s-1", BASE_MS + 1000, "a/b"); + putRaw(service, group, "s-1", BASE_MS + 2000, "c"); + + assertEquals(List.of("a/b", "c"), rowsFor(group, + "fields @message | filter @message like /a\\/b/ or @message like /c/ | sort @message asc") + .stream().map(row -> row.get("@message")).toList()); + } + + @Test + void queryAggregatesCountsAndLatestValuesByHour() { + String group = "insights/stats"; + createGroupStream(service, group, "s-1"); + putRaw(service, group, "s-1", BASE_MS + 1000, "{\"event\":{\"reason\":\"timeout\"}}"); + putRaw(service, group, "s-1", BASE_MS + 2000, "{\"event\":{\"reason\":\"failure\"}}"); + putRaw(service, group, "s-1", BASE_MS + 3601000, "{\"event\":{\"reason\":\"timeout\"}}"); + + CloudWatchLogsService.QueryState state = startQueryFor(group, """ + fields @timestamp, event.reason + | stats count(*) as total, count_distinct(event.reason) as reasons, + latest(event.reason) as last by bin(1h) + | sort bin(1h) asc + | limit 50 + """); + assertEquals("Complete", state.status()); + assertEquals(3, state.recordsMatched(), "aggregation must count matched events, not output groups"); + assertEquals(2, state.rows().size()); + assertEquals("2", state.rows().get(0).get("total")); + assertEquals("2", state.rows().get(0).get("reasons")); + assertEquals("failure", state.rows().get(0).get("last")); + assertEquals("1", state.rows().get(1).get("total")); + assertEquals("timeout", state.rows().get(1).get("last")); + assertEquals(List.of("failure", "timeout"), rowsFor(group, + "stats count(*) as total by event.reason | sort event.reason asc") + .stream().map(row -> row.get("event.reason")).toList()); + assertEquals(2, rowsFor(group, "stats count(*) as total\nby bin(1h)").size()); + assertEquals(2, rowsFor(group, "stats count(*) as total\tby bin(1h)").size()); + } + + @Test + void querySortsAggregateCountsNumerically() { + String group = "insights/stats-count-sort"; + createGroupStream(service, group, "s-1"); + for (int i = 0; i < 12; i++) { + putRaw(service, group, "s-1", BASE_MS + i * 1000, "{\"kind\":\"many\"}"); + } + for (int i = 0; i < 2; i++) { + putRaw(service, group, "s-1", BASE_MS + (i + 12) * 1000, "{\"kind\":\"few\"}"); + } + assertEquals(List.of("few", "many"), rowsFor(group, + "stats count(*) as total by kind | sort total asc") + .stream().map(row -> row.get("kind")).toList()); + } + + @Test + void unsupportedStatsStageOrderFailsRatherThanReturningWrongRows() { + String group = "insights/stats-stage-order"; + createGroupStream(service, group, "s-1"); + putRaw(service, group, "s-1", BASE_MS + 1000, "{\"kind\":\"demo\"}"); + for (String query : List.of( + "stats count(*) as total | filter total = 1", + "stats count(*) as total | fields total", + "stats count(*) as total | dedup total", + "stats count(*) as kind by kind | sort kind", + "dedup kind | stats count(*) as total")) { + assertEquals("Failed", startQueryFor(group, query).status(), query); + } + } + @Test void unsupportedCommandsFailTheQueryInsteadOfBeingIgnored() { String group = "data-sources/connectors"; @@ -491,7 +639,7 @@ class CloudWatchLogsInsightsQueryTest { put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "kept"); put(group, stream, BASE_MS + 2000, "TRACE", "JOB-1", "dropped"); - // 'parse' / 'stats' are unsupported: the query must fail rather than silently apply only the + // 'parse' is unsupported: the query must fail rather than silently apply only the // stages it understands and return a result set that does not correspond to the query asked. String query = """ fields @message @@ -524,7 +672,7 @@ class CloudWatchLogsInsightsQueryTest { // The same holds for '||', 'and', 'not' and leftover text after a value: each fails rather // than degrading silently into a different comparison. for (String expr : List.of("level >= 'INFO'", "level <= 'INFO'", "level =~ /INFO/", ">= 'INFO'", - "level > 'INFO'", "level < 'INFO'", "level like /INFO/", "level not like /INFO/", + "level > 'INFO'", "level < 'INFO'", "level in ['INFO']", "level = 'INFO' || level = 'ERROR'", "level = 'INFO' || level = 'ERROR' | sort @timestamp desc", @@ -534,8 +682,6 @@ class CloudWatchLogsInsightsQueryTest { "level = 'INFO' or", "level = 'INFO' and level = 'ERROR'", "not level = 'INFO'", - "level = 'INFO' or level like /E/", - "level like /a=b/", "level != INFO=oops", "level = INFO=oops", "level = 'INFO\\' or level = 'ERROR'", @@ -568,7 +714,7 @@ class CloudWatchLogsInsightsQueryTest { long startSec = BASE_MS / 1000 - 10; String queryId = service.startQuery( - List.of(group), startSec, startSec + 86400, "filter @message like /ERROR/", null, REGION); + List.of(group), startSec, startSec + 86400, "filter level >= 'ERROR'", null, REGION); assertNotNull(queryId); CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);