Skip to content

Commit 68f74cf

Browse files
authored
EQL: Fix custom scripting for functions (#53935) (#54114)
Improve separation of scripting between EQL and SQL by delegating common methods to QL. The context detection is determined based on the package to avoid having repetitive class hierarchies. The Painless whitelists have been improved so that the declaring class is used instead of the inherited one. Relates #53688 (cherry picked from commit 6d46033) EQL: Add Substring function with Python semantics (#53688) Does not reuse substring from SQL due to the difference in semantics and the accepted arguments. Currently it is missing full integration tests as, due to the usage of scripting, requires an actual integration test against a proper cluster (and likely its own QA project). (cherry picked from commit f58680b)
1 parent b21b7fb commit 68f74cf

File tree

40 files changed

+869
-214
lines changed

40 files changed

+869
-214
lines changed

x-pack/plugin/eql/qa/common/src/main/resources/test_queries_unsupported.toml

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -881,34 +881,6 @@ file where opcode=0 and indexOf(file_name, 'explorer.', 0) == 0'''
881881
expected_event_ids = [88, 92]
882882
description = "check substring ranges"
883883

884-
[[queries]]
885-
query = '''
886-
file where serial_event_id=88 and substring(file_name, 0, 4) == 'expl'
887-
'''
888-
expected_event_ids = [88]
889-
description = "check substring ranges"
890-
891-
[[queries]]
892-
query = '''
893-
file where serial_event_id=88 and substring(file_name, 1, 3) == 'xp'
894-
'''
895-
expected_event_ids = [88]
896-
description = "chaeck substring ranges"
897-
898-
[[queries]]
899-
query = '''
900-
file where serial_event_id=88 and substring(file_name, -4) == '.exe'
901-
'''
902-
expected_event_ids = [88]
903-
description = "check substring ranges"
904-
905-
[[queries]]
906-
query = '''
907-
file where serial_event_id=88 and substring(file_name, -4, -1) == '.ex'
908-
'''
909-
expected_event_ids = [88]
910-
description = "check substring ranges"
911-
912884
[[queries]]
913885
query = '''
914886
process where add(serial_event_id, 0) == 1 and add(0, 1) == serial_event_id'''

x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/analysis/Analyzer.java

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010
import org.elasticsearch.xpack.ql.expression.Attribute;
1111
import org.elasticsearch.xpack.ql.expression.NamedExpression;
1212
import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute;
13+
import org.elasticsearch.xpack.ql.expression.function.Function;
14+
import org.elasticsearch.xpack.ql.expression.function.FunctionDefinition;
1315
import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry;
16+
import org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction;
1417
import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan;
15-
import org.elasticsearch.xpack.ql.rule.Rule;
1618
import org.elasticsearch.xpack.ql.rule.RuleExecutor;
1719

1820
import java.util.ArrayList;
@@ -35,7 +37,8 @@ public Analyzer(FunctionRegistry functionRegistry, Verifier verifier) {
3537
@Override
3638
protected Iterable<RuleExecutor<LogicalPlan>.Batch> batches() {
3739
Batch resolution = new Batch("Resolution",
38-
new ResolveRefs());
40+
new ResolveRefs(),
41+
new ResolveFunctions());
3942

4043
return asList(resolution);
4144
}
@@ -52,7 +55,7 @@ private LogicalPlan verify(LogicalPlan plan) {
5255
return plan;
5356
}
5457

55-
private static class ResolveRefs extends AnalyzeRule<LogicalPlan> {
58+
private static class ResolveRefs extends AnalyzerRule<LogicalPlan> {
5659

5760
@Override
5861
protected LogicalPlan rule(LogicalPlan plan) {
@@ -87,20 +90,34 @@ protected LogicalPlan rule(LogicalPlan plan) {
8790
}
8891
}
8992

90-
abstract static class AnalyzeRule<SubPlan extends LogicalPlan> extends Rule<SubPlan, LogicalPlan> {
93+
private class ResolveFunctions extends AnalyzerRule<LogicalPlan> {
9194

92-
// transformUp (post-order) - that is first children and then the node
93-
// but with a twist; only if the tree is not resolved or analyzed
9495
@Override
95-
public final LogicalPlan apply(LogicalPlan plan) {
96-
return plan.transformUp(t -> t.analyzed() || skipResolved() && t.resolved() ? t : rule(t), typeToken());
97-
}
96+
protected LogicalPlan rule(LogicalPlan plan) {
97+
return plan.transformExpressionsUp(e -> {
98+
if (e instanceof UnresolvedFunction) {
99+
UnresolvedFunction uf = (UnresolvedFunction) e;
98100

99-
@Override
100-
protected abstract LogicalPlan rule(SubPlan plan);
101+
if (uf.analyzed()) {
102+
return uf;
103+
}
104+
105+
String name = uf.name();
101106

102-
protected boolean skipResolved() {
103-
return true;
107+
if (uf.childrenResolved() == false) {
108+
return uf;
109+
}
110+
111+
String functionName = functionRegistry.resolveAlias(name);
112+
if (functionRegistry.functionExists(functionName) == false) {
113+
return uf.missing(functionName, functionRegistry.listFunctions());
114+
}
115+
FunctionDefinition def = functionRegistry.resolveFunction(functionName);
116+
Function f = uf.buildResolved(null, def);
117+
return f;
118+
}
119+
return e;
120+
});
104121
}
105122
}
106123
}

x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/execution/PlanExecutor.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import org.elasticsearch.xpack.eql.analysis.Analyzer;
1313
import org.elasticsearch.xpack.eql.analysis.PreAnalyzer;
1414
import org.elasticsearch.xpack.eql.analysis.Verifier;
15+
import org.elasticsearch.xpack.eql.expression.function.EqlFunctionRegistry;
1516
import org.elasticsearch.xpack.eql.optimizer.Optimizer;
1617
import org.elasticsearch.xpack.eql.parser.ParserParams;
1718
import org.elasticsearch.xpack.eql.planner.Planner;
@@ -44,7 +45,7 @@ public PlanExecutor(Client client, IndexResolver indexResolver, NamedWriteableRe
4445
this.writableRegistry = writeableRegistry;
4546

4647
this.indexResolver = indexResolver;
47-
this.functionRegistry = null;
48+
this.functionRegistry = new EqlFunctionRegistry();
4849

4950
this.metrics = new Metrics();
5051

x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/expression/function/EqlFunctionRegistry.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,30 @@
66

77
package org.elasticsearch.xpack.eql.expression.function;
88

9+
import org.elasticsearch.xpack.eql.expression.function.scalar.string.Substring;
10+
import org.elasticsearch.xpack.ql.expression.function.FunctionDefinition;
911
import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry;
1012

13+
import java.util.Locale;
14+
1115
public class EqlFunctionRegistry extends FunctionRegistry {
1216

1317
public EqlFunctionRegistry() {
18+
super(functions());
19+
}
20+
21+
private static FunctionDefinition[][] functions() {
22+
return new FunctionDefinition[][] {
23+
// Scalar functions
24+
// String
25+
new FunctionDefinition[] {
26+
def(Substring.class, Substring::new, "substring"),
27+
},
28+
};
29+
}
30+
31+
@Override
32+
protected String normalize(String name) {
33+
return name.toLowerCase(Locale.ROOT);
1434
}
1535
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
package org.elasticsearch.xpack.eql.expression.function.scalar.string;
8+
9+
import org.elasticsearch.common.Strings;
10+
11+
import static org.elasticsearch.common.Strings.hasLength;
12+
13+
final class StringUtils {
14+
15+
private StringUtils() {}
16+
17+
/**
18+
* Returns a substring using the Python slice semantics, meaning
19+
* start and end can be negative
20+
*/
21+
static String substringSlice(String string, int start, int end) {
22+
if (hasLength(string) == false) {
23+
return string;
24+
}
25+
26+
int length = string.length();
27+
28+
// handle first negative values
29+
if (start < 0) {
30+
start += length;
31+
}
32+
if (start < 0) {
33+
start = 0;
34+
}
35+
if (end < 0) {
36+
end += length;
37+
}
38+
if (end < 0) {
39+
end = 0;
40+
} else if (end > length) {
41+
end = length;
42+
}
43+
44+
if (start >= end) {
45+
return org.elasticsearch.xpack.ql.util.StringUtils.EMPTY;
46+
}
47+
48+
return Strings.substring(string, start, end);
49+
}
50+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
package org.elasticsearch.xpack.eql.expression.function.scalar.string;
8+
9+
import org.elasticsearch.xpack.ql.expression.Expression;
10+
import org.elasticsearch.xpack.ql.expression.Expressions;
11+
import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal;
12+
import org.elasticsearch.xpack.ql.expression.FieldAttribute;
13+
import org.elasticsearch.xpack.ql.expression.Literal;
14+
import org.elasticsearch.xpack.ql.expression.function.OptionalArgument;
15+
import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction;
16+
import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe;
17+
import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate;
18+
import org.elasticsearch.xpack.ql.expression.gen.script.Scripts;
19+
import org.elasticsearch.xpack.ql.tree.NodeInfo;
20+
import org.elasticsearch.xpack.ql.tree.Source;
21+
import org.elasticsearch.xpack.ql.type.DataType;
22+
import org.elasticsearch.xpack.ql.type.DataTypes;
23+
24+
import java.util.Arrays;
25+
import java.util.List;
26+
import java.util.Locale;
27+
28+
import static java.lang.String.format;
29+
import static org.elasticsearch.xpack.eql.expression.function.scalar.string.SubstringFunctionProcessor.doProcess;
30+
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isInteger;
31+
import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact;
32+
import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder;
33+
34+
/**
35+
* EQL specific substring function - similar to the one in Python.
36+
* Note this is different than the one in SQL.
37+
*/
38+
public class Substring extends ScalarFunction implements OptionalArgument {
39+
40+
private final Expression source, start, end;
41+
42+
public Substring(Source source, Expression src, Expression start, Expression end) {
43+
super(source, Arrays.asList(src, start, end != null ? end : new Literal(source, null, DataTypes.NULL)));
44+
this.source = src;
45+
this.start = start;
46+
this.end = arguments().get(2);
47+
}
48+
49+
@Override
50+
protected TypeResolution resolveType() {
51+
if (!childrenResolved()) {
52+
return new TypeResolution("Unresolved children");
53+
}
54+
55+
TypeResolution sourceResolution = isStringAndExact(source, sourceText(), ParamOrdinal.FIRST);
56+
if (sourceResolution.unresolved()) {
57+
return sourceResolution;
58+
}
59+
60+
TypeResolution startResolution = isInteger(start, sourceText(), ParamOrdinal.SECOND);
61+
if (startResolution.unresolved()) {
62+
return startResolution;
63+
}
64+
65+
return isInteger(end, sourceText(), ParamOrdinal.THIRD);
66+
}
67+
68+
@Override
69+
protected Pipe makePipe() {
70+
return new SubstringFunctionPipe(source(), this, Expressions.pipe(source), Expressions.pipe(start), Expressions.pipe(end));
71+
}
72+
73+
@Override
74+
public boolean foldable() {
75+
return source.foldable() && start.foldable() && end.foldable();
76+
}
77+
78+
@Override
79+
public Object fold() {
80+
return doProcess(source.fold(), start.fold(), end.fold());
81+
}
82+
83+
@Override
84+
protected NodeInfo<? extends Expression> info() {
85+
return NodeInfo.create(this, Substring::new, source, start, end);
86+
}
87+
88+
@Override
89+
public ScriptTemplate asScript() {
90+
ScriptTemplate sourceScript = asScript(source);
91+
ScriptTemplate startScript = asScript(start);
92+
ScriptTemplate endScript = asScript(end);
93+
94+
return asScriptFrom(sourceScript, startScript, endScript);
95+
}
96+
97+
protected ScriptTemplate asScriptFrom(ScriptTemplate sourceScript, ScriptTemplate startScript, ScriptTemplate endScript) {
98+
return new ScriptTemplate(format(Locale.ROOT, formatTemplate("{eql}.%s(%s,%s,%s)"),
99+
"substring",
100+
sourceScript.template(),
101+
startScript.template(),
102+
endScript.template()),
103+
paramsBuilder()
104+
.script(sourceScript.params())
105+
.script(startScript.params())
106+
.script(endScript.params())
107+
.build(), dataType());
108+
}
109+
110+
@Override
111+
public ScriptTemplate scriptWithField(FieldAttribute field) {
112+
return new ScriptTemplate(processScript(Scripts.DOC_VALUE),
113+
paramsBuilder().variable(field.exactAttribute().name()).build(),
114+
dataType());
115+
}
116+
117+
@Override
118+
public DataType dataType() {
119+
return DataTypes.KEYWORD;
120+
}
121+
122+
@Override
123+
public Expression replaceChildren(List<Expression> newChildren) {
124+
if (newChildren.size() != 3) {
125+
throw new IllegalArgumentException("expected [3] children but received [" + newChildren.size() + "]");
126+
}
127+
128+
return new Substring(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2));
129+
}
130+
}

0 commit comments

Comments
 (0)