mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(cloudwatch): fail Logs Insights queries with unsupported syntax instead of silently dropping it (#3139)
An unsupported filter, command, or invalid argument to a recognized command (e.g. limit abc, a bare sort/dedup) was ignored with only a server log warning, so the query came back Complete with a result set that did not reflect what was asked. It now reports GetQueryResults status Failed instead. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
653c1397a2
commit
121a9292b7
3 files changed
+161
-32
No files matched your search
+55
-17
@@ -731,15 +731,21 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
|
||||
// ──────────────────────────── Logs Insights Queries ────────────────────────────
|
||||
|
||||
/** A query's status and (once Complete) its projected rows — the AWS GetQueryResults shape. */
|
||||
/**
|
||||
* A query's status and (once Complete) its projected rows: the AWS GetQueryResults shape.
|
||||
* {@code failureReason} is {@code null} unless {@code status} is {@code Failed}; it is not
|
||||
* part of the AWS wire response (GetQueryResults carries no such field) but is exposed here
|
||||
* for callers and tests that want to know why an unsupported query failed.
|
||||
*/
|
||||
public record QueryState(String status, List<LinkedHashMap<String, String>> rows,
|
||||
long recordsScanned, long recordsMatched) {}
|
||||
long recordsScanned, long recordsMatched, String failureReason) {}
|
||||
|
||||
/** Lifecycle state of a stored Insights query; {@link #label()} is the AWS wire form. */
|
||||
private enum InsightsQueryStatus {
|
||||
RUNNING("Running"),
|
||||
COMPLETE("Complete"),
|
||||
CANCELLED("Cancelled");
|
||||
CANCELLED("Cancelled"),
|
||||
FAILED("Failed");
|
||||
|
||||
private final String label;
|
||||
|
||||
@@ -755,42 +761,61 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
/**
|
||||
* 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.
|
||||
* execution), then either {@code Complete} or, if the query string contained syntax this engine
|
||||
* cannot evaluate, {@code Failed}, unless cancelled by StopQuery first, after which it is
|
||||
* {@code Cancelled}. State transitions are time-driven and computed on read. For a Complete or
|
||||
* Cancelled query, {@code recordsMatched} is captured at construction so it survives the
|
||||
* Running/Cancelled row masking and the row-drop on cancel; a Failed query never evaluated any
|
||||
* matches, so its {@code recordsMatched} is always zero.
|
||||
*/
|
||||
private static final class QueryRecord {
|
||||
private List<LinkedHashMap<String, String>> rows;
|
||||
private final long recordsScanned;
|
||||
private final long recordsMatched;
|
||||
private final long completeAtMs;
|
||||
private final String failureReason;
|
||||
private boolean cancelled;
|
||||
|
||||
QueryRecord(List<LinkedHashMap<String, String>> rows, long recordsScanned, long completeAtMs) {
|
||||
this(rows, recordsScanned, completeAtMs, null);
|
||||
}
|
||||
|
||||
private QueryRecord(List<LinkedHashMap<String, String>> rows, long recordsScanned, long completeAtMs,
|
||||
String failureReason) {
|
||||
this.rows = rows;
|
||||
this.recordsScanned = recordsScanned;
|
||||
this.recordsMatched = rows.size();
|
||||
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);
|
||||
}
|
||||
|
||||
private InsightsQueryStatus status(long nowMs) {
|
||||
if (cancelled) {
|
||||
return InsightsQueryStatus.CANCELLED;
|
||||
}
|
||||
return nowMs >= completeAtMs ? InsightsQueryStatus.COMPLETE : InsightsQueryStatus.RUNNING;
|
||||
if (nowMs < completeAtMs) {
|
||||
return InsightsQueryStatus.RUNNING;
|
||||
}
|
||||
return failureReason != null ? InsightsQueryStatus.FAILED : InsightsQueryStatus.COMPLETE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* full match count. 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) {
|
||||
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);
|
||||
return new QueryState(status.label(), visible, recordsScanned, recordsMatched, failureReason);
|
||||
}
|
||||
|
||||
/** Cancels the query iff still running, dropping its now-unreachable rows. Returns true if this call stopped it. */
|
||||
@@ -807,7 +832,8 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
/**
|
||||
* 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.
|
||||
* completion delay elapses (default 0 = immediate), emulating AWS's async execution, then either
|
||||
* {@code Complete} or, if the query string could not be fully evaluated, {@code Failed}.
|
||||
* {@code startTimeSeconds}/{@code endTimeSeconds} are epoch <em>seconds</em> (the StartQuery
|
||||
* contract); {@link LogEvent} timestamps are epoch millis, so they are scaled for comparison.
|
||||
*/
|
||||
@@ -844,12 +870,22 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
int effectiveLimit = (limit != null && limit > 0) ? Math.min(limit, maxEventsPerQuery) : maxEventsPerQuery;
|
||||
List<LinkedHashMap<String, String>> rows =
|
||||
LogsInsightsQuery.parse(queryString).evaluate(gathered, effectiveLimit);
|
||||
|
||||
LogsInsightsQuery parsedQuery = LogsInsightsQuery.parse(queryString);
|
||||
String queryId = UUID.randomUUID().toString();
|
||||
long completeAtMs = clock.getAsLong() + queryCompletionDelayMs;
|
||||
|
||||
if (parsedQuery.isUnsupported()) {
|
||||
// A query containing syntax this engine cannot evaluate must not come back as a
|
||||
// "successful" empty or partial result set: fail it, so the caller can tell the
|
||||
// difference between "the filter matched nothing" and "the filter was never applied".
|
||||
insightsQueries.put(queryId, QueryRecord.failed(gathered.size(), completeAtMs, parsedQuery.getUnsupportedReason()));
|
||||
LOG.warnv("Logs Insights query {0} will fail: {1}", queryId, parsedQuery.getUnsupportedReason());
|
||||
return queryId;
|
||||
}
|
||||
|
||||
int effectiveLimit = (limit != null && limit > 0) ? Math.min(limit, maxEventsPerQuery) : maxEventsPerQuery;
|
||||
List<LinkedHashMap<String, String>> rows = parsedQuery.evaluate(gathered, effectiveLimit);
|
||||
|
||||
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());
|
||||
@@ -858,9 +894,11 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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
|
||||
* ({@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.
|
||||
*/
|
||||
public QueryState getQueryResults(String queryId) {
|
||||
QueryRecord rec = insightsQueries.get(queryId);
|
||||
|
||||
+41
-5
@@ -31,8 +31,10 @@ import java.util.Set;
|
||||
*
|
||||
* <p>This is intentionally <em>not</em> a full Insights implementation: unsupported commands
|
||||
* (e.g. {@code stats}, {@code parse}) and unsupported filter operators (e.g. {@code >=},
|
||||
* {@code like}) are ignored with a warning. Pipes ({@code |}) inside quoted filter values are
|
||||
* respected and do not split the query into stages.
|
||||
* {@code like}) 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.
|
||||
*/
|
||||
final class LogsInsightsQuery {
|
||||
|
||||
@@ -47,6 +49,7 @@ final class LogsInsightsQuery {
|
||||
private boolean sortDesc;
|
||||
private List<String> dedupFields;
|
||||
private Integer limit;
|
||||
private String unsupportedReason;
|
||||
|
||||
private record Filter(String field, boolean negate, String value) {}
|
||||
|
||||
@@ -73,6 +76,21 @@ final class LogsInsightsQuery {
|
||||
return q;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the query contains a command or filter expression this engine cannot evaluate.
|
||||
* Such a query must not be executed as if the unsupported stage were absent: the caller
|
||||
* (see {@link #getUnsupportedReason()}) should fail the query rather than return a result
|
||||
* set that silently omits it.
|
||||
*/
|
||||
boolean isUnsupported() {
|
||||
return unsupportedReason != null;
|
||||
}
|
||||
|
||||
/** The first unsupported command or filter expression encountered, or {@code null} if none. */
|
||||
String getUnsupportedReason() {
|
||||
return unsupportedReason;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -109,6 +127,8 @@ final class LogsInsightsQuery {
|
||||
Filter f = parseFilter(args);
|
||||
if (f != null) {
|
||||
filters.add(f);
|
||||
} else {
|
||||
noteUnsupported("Unsupported filter expression: " + args);
|
||||
}
|
||||
}
|
||||
case "sort", "order" -> {
|
||||
@@ -116,20 +136,37 @@ final class LogsInsightsQuery {
|
||||
if (s.length > 0 && !s[0].isEmpty()) {
|
||||
sortField = s[0].trim();
|
||||
sortDesc = s.length > 1 && s[1].trim().equalsIgnoreCase("desc");
|
||||
} else {
|
||||
noteUnsupported("Sort command is missing its field");
|
||||
}
|
||||
}
|
||||
case "dedup" -> {
|
||||
dedupFields = new ArrayList<>();
|
||||
splitCsv(args, dedupFields);
|
||||
if (dedupFields.isEmpty()) {
|
||||
noteUnsupported("Dedup command is missing its field(s): " + args);
|
||||
}
|
||||
}
|
||||
case "limit" -> {
|
||||
try {
|
||||
limit = Integer.parseInt(args.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.warnv("Ignoring invalid Logs Insights limit: {0}", args);
|
||||
noteUnsupported("Invalid limit argument: " + args);
|
||||
}
|
||||
}
|
||||
default -> LOG.warnv("Ignoring unsupported Logs Insights command: {0}", cmd);
|
||||
default -> noteUnsupported("Unsupported command: " + cmd);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* or state the earlier failure never let this engine establish.
|
||||
*/
|
||||
private void noteUnsupported(String reason) {
|
||||
LOG.warnv("Logs Insights query contains unsupported syntax, failing the query: {0}", reason);
|
||||
if (unsupportedReason == null) {
|
||||
unsupportedReason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,7 +208,6 @@ final class LogsInsightsQuery {
|
||||
}
|
||||
}
|
||||
}
|
||||
LOG.warnv("Ignoring unsupported Logs Insights filter: {0}", expr);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user