Scripting: Move context definitions to instance type classes (#24883)

This is a simple refactoring to move the context definitions into the
type that they use. While we have multiple context names for the same
class at the moment, this will eventually become one ScriptContext per
instance type, so the pattern of a static member on the interface called
CONTEXT can be used. This commit also moves the consolidated list of
contexts provided by core ES into ScriptModule.
This commit is contained in:
Ryan Ernst 2017-05-25 12:18:45 -07:00 committed by GitHub
parent 59c052e76f
commit 8aaea51a0a
41 changed files with 118 additions and 106 deletions

View File

@ -300,7 +300,7 @@ public class UpdateHelper extends AbstractComponent {
private Map<String, Object> executeScript(Script script, Map<String, Object> ctx) {
try {
if (scriptService != null) {
ExecutableScript.Compiled compiledScript = scriptService.compile(script, ScriptContext.UPDATE);
ExecutableScript.Compiled compiledScript = scriptService.compile(script, ExecutableScript.UPDATE_CONTEXT);
ExecutableScript executableScript = compiledScript.newInstance(script.getParams());
executableScript.setNextVar(ContextFields.CTX, ctx);
executableScript.run();

View File

@ -75,7 +75,7 @@ public abstract class InnerHitContextBuilder {
if (innerHitBuilder.getScriptFields() != null) {
for (SearchSourceBuilder.ScriptField field : innerHitBuilder.getScriptFields()) {
SearchScript searchScript = innerHitsContext.getQueryShardContext().getSearchScript(field.script(),
ScriptContext.SEARCH);
SearchScript.CONTEXT);
innerHitsContext.scriptFields().add(new org.elasticsearch.search.fetch.subphase.ScriptFieldsContext.ScriptField(
field.fieldName(), searchScript, field.ignoreFailure()));
}

View File

@ -24,6 +24,7 @@ import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptService;
@ -103,7 +104,7 @@ public class QueryRewriteContext {
}
public String getTemplateBytes(Script template) {
CompiledTemplate compiledTemplate = scriptService.compileTemplate(template, ScriptContext.EXECUTABLE);
CompiledTemplate compiledTemplate = scriptService.compileTemplate(template, ExecutableScript.CONTEXT);
return compiledTemplate.run(template.getParams());
}
}

View File

@ -131,7 +131,7 @@ public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder>
@Override
protected Query doToQuery(QueryShardContext context) throws IOException {
return new ScriptQuery(script, context.getSearchScript(script, ScriptContext.SEARCH));
return new ScriptQuery(script, context.getSearchScript(script, SearchScript.CONTEXT));
}
static class ScriptQuery extends Query {

View File

@ -94,7 +94,7 @@ public class ScriptScoreFunctionBuilder extends ScoreFunctionBuilder<ScriptScore
@Override
protected ScoreFunction doToFunction(QueryShardContext context) {
try {
SearchScript searchScript = context.getSearchScript(script, ScriptContext.SEARCH);
SearchScript searchScript = context.getSearchScript(script, SearchScript.CONTEXT);
return new ScriptScoreFunction(script, searchScript);
} catch (Exception e) {
throw new QueryShardException(context, "script_score: the script could not be loaded", e);

View File

@ -24,6 +24,7 @@ import java.util.Map;
import org.apache.logging.log4j.util.Supplier;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptService;
@ -44,7 +45,7 @@ public class InternalTemplateService implements TemplateService {
int mustacheEnd = template.indexOf("}}");
if (mustacheStart != -1 && mustacheEnd != -1 && mustacheStart < mustacheEnd) {
Script script = new Script(ScriptType.INLINE, "mustache", template, Collections.emptyMap());
CompiledTemplate compiledTemplate = scriptService.compileTemplate(script, ScriptContext.INGEST);
CompiledTemplate compiledTemplate = scriptService.compileTemplate(script, ExecutableScript.INGEST_CONTEXT);
return new Template() {
@Override
public String execute(Map<String, Object> model) {

View File

@ -44,4 +44,11 @@ public interface ExecutableScript {
interface Compiled {
ExecutableScript newInstance(Map<String, Object> params);
}
ScriptContext<Compiled> CONTEXT = new ScriptContext<>("executable", Compiled.class);
// TODO: remove these once each has its own script interface
ScriptContext<Compiled> AGGS_CONTEXT = new ScriptContext<>("aggs_executable", Compiled.class);
ScriptContext<Compiled> UPDATE_CONTEXT = new ScriptContext<>("update", Compiled.class);
ScriptContext<Compiled> INGEST_CONTEXT = new ScriptContext<>("ingest", Compiled.class);
}

View File

@ -45,32 +45,6 @@ import java.util.Map;
*/
public final class ScriptContext<CompiledType> {
public static final ScriptContext<SearchScript.Compiled> AGGS =
new ScriptContext<>("aggs", SearchScript.Compiled.class);
public static final ScriptContext<SearchScript.Compiled> SEARCH =
new ScriptContext<>("search", SearchScript.Compiled.class);
// TODO: remove this once each agg calling scripts has its own context
public static final ScriptContext<ExecutableScript.Compiled> AGGS_EXECUTABLE =
new ScriptContext<>("aggs_executable", ExecutableScript.Compiled.class);
public static final ScriptContext<ExecutableScript.Compiled> UPDATE =
new ScriptContext<>("update", ExecutableScript.Compiled.class);
public static final ScriptContext<ExecutableScript.Compiled> INGEST =
new ScriptContext<>("ingest", ExecutableScript.Compiled.class);
public static final ScriptContext<ExecutableScript.Compiled> EXECUTABLE =
new ScriptContext<>("executable", ExecutableScript.Compiled.class);
public static final Map<String, ScriptContext<?>> BUILTINS;
static {
Map<String, ScriptContext<?>> builtins = new HashMap<>();
builtins.put(AGGS.name, AGGS);
builtins.put(SEARCH.name, SEARCH);
builtins.put(AGGS_EXECUTABLE.name, AGGS_EXECUTABLE);
builtins.put(UPDATE.name, UPDATE);
builtins.put(INGEST.name, INGEST);
builtins.put(EXECUTABLE.name, EXECUTABLE);
BUILTINS = Collections.unmodifiableMap(builtins);
}
/** A unique identifier for this context. */
public final String name;

View File

@ -19,10 +19,14 @@
package org.elasticsearch.script;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
@ -32,11 +36,24 @@ import org.elasticsearch.plugins.ScriptPlugin;
* Manages building {@link ScriptService}.
*/
public class ScriptModule {
public static final Map<String, ScriptContext<?>> CORE_CONTEXTS;
static {
CORE_CONTEXTS = Stream.of(
SearchScript.CONTEXT,
SearchScript.AGGS_CONTEXT,
ExecutableScript.CONTEXT,
ExecutableScript.AGGS_CONTEXT,
ExecutableScript.UPDATE_CONTEXT,
ExecutableScript.INGEST_CONTEXT
).collect(Collectors.toMap(c -> c.name, Function.identity()));
}
private final ScriptService scriptService;
public ScriptModule(Settings settings, List<ScriptPlugin> scriptPlugins) {
Map<String, ScriptEngine> engines = new HashMap<>();
Map<String, ScriptContext<?>> contexts = new HashMap<>(ScriptContext.BUILTINS);
Map<String, ScriptContext<?>> contexts = new HashMap<>(CORE_CONTEXTS);
for (ScriptPlugin plugin : scriptPlugins) {
for (ScriptContext context : plugin.getContexts()) {
ScriptContext oldContext = contexts.put(context.name, context);

View File

@ -264,7 +264,7 @@ public class ScriptService extends AbstractComponent implements Closeable, Clust
// TODO: fix this through some API or something, that's wrong
// special exception to prevent expressions from compiling as update or mapping scripts
boolean expression = "expression".equals(script.getLang());
boolean notSupported = context.name.equals(ScriptContext.UPDATE.name);
boolean notSupported = context.name.equals(ExecutableScript.UPDATE_CONTEXT.name);
if (expression && notSupported) {
throw new UnsupportedOperationException("scripts of type [" + script.getType() + "]," +
" operation [" + context.name + "] and lang [" + lang + "] are not supported");
@ -433,7 +433,7 @@ public class ScriptService extends AbstractComponent implements Closeable, Clust
"cannot put [" + ScriptType.STORED + "] script, no script contexts are enabled");
} else {
// TODO: executable context here is just a placeholder, replace with optional context name passed into PUT stored script req
Object compiled = scriptEngine.compile(request.id(), source.getCode(), ScriptContext.EXECUTABLE, Collections.emptyMap());
Object compiled = scriptEngine.compile(request.id(), source.getCode(), ExecutableScript.CONTEXT, Collections.emptyMap());
if (compiled == null) {
throw new IllegalArgumentException("failed to parse/compile stored script [" + request.id() + "]" +

View File

@ -41,4 +41,8 @@ public interface SearchScript {
interface Compiled {
SearchScript newInstance(Map<String, Object> params, SearchLookup lookup);
}
ScriptContext<Compiled> CONTEXT = new ScriptContext<>("search", Compiled.class);
// TODO: remove aggs context when it has its own interface
ScriptContext<SearchScript.Compiled> AGGS_CONTEXT = new ScriptContext<>("aggs", Compiled.class);
}

View File

@ -685,7 +685,7 @@ public class SearchService extends AbstractLifecycleComponent implements IndexEv
}
if (source.scriptFields() != null) {
for (org.elasticsearch.search.builder.SearchSourceBuilder.ScriptField field : source.scriptFields()) {
SearchScript.Compiled compiled = scriptService.compile(field.script(), ScriptContext.SEARCH);
SearchScript.Compiled compiled = scriptService.compile(field.script(), SearchScript.CONTEXT);
SearchScript searchScript = compiled.newInstance(field.script().getParams(), context.lookup());
context.scriptFields().add(new ScriptField(field.fieldName(), searchScript, field.ignoreFailure()));
}

View File

@ -92,14 +92,14 @@ public class ScriptHeuristic extends SignificanceHeuristic {
@Override
public SignificanceHeuristic rewrite(InternalAggregation.ReduceContext context) {
ExecutableScript.Compiled compiled = context.scriptService().compile(script, ScriptContext.AGGS_EXECUTABLE);
ExecutableScript.Compiled compiled = context.scriptService().compile(script, ExecutableScript.AGGS_CONTEXT);
return new ExecutableScriptHeuristic(script, compiled.newInstance(script.getParams()));
}
@Override
public SignificanceHeuristic rewrite(SearchContext context) {
return new ExecutableScriptHeuristic(script,
context.getQueryShardContext().getExecutableScript(script, ScriptContext.AGGS_EXECUTABLE));
context.getQueryShardContext().getExecutableScript(script, ExecutableScript.AGGS_CONTEXT));
}

View File

@ -96,7 +96,7 @@ public class InternalScriptedMetric extends InternalAggregation implements Scrip
vars.putAll(firstAggregation.reduceScript.getParams());
}
ExecutableScript.Compiled compiled = reduceContext.scriptService().compile(
firstAggregation.reduceScript, ScriptContext.AGGS_EXECUTABLE);
firstAggregation.reduceScript, ExecutableScript.AGGS_CONTEXT);
ExecutableScript script = compiled.newInstance(vars);
aggregation = Collections.singletonList(script.run());
} else if (reduceContext.isFinalReduce()) {

View File

@ -186,14 +186,15 @@ public class ScriptedMetricAggregationBuilder extends AbstractAggregationBuilder
QueryShardContext queryShardContext = context.getQueryShardContext();
Function<Map<String, Object>, ExecutableScript> executableInitScript;
if (initScript != null) {
executableInitScript = queryShardContext.getLazyExecutableScript(initScript, ScriptContext.AGGS_EXECUTABLE);
executableInitScript = queryShardContext.getLazyExecutableScript(initScript, ExecutableScript.AGGS_CONTEXT);
} else {
executableInitScript = (p) -> null;
}
Function<Map<String, Object>, SearchScript> searchMapScript = queryShardContext.getLazySearchScript(mapScript, ScriptContext.AGGS);
Function<Map<String, Object>, SearchScript> searchMapScript =
queryShardContext.getLazySearchScript(mapScript, SearchScript.AGGS_CONTEXT);
Function<Map<String, Object>, ExecutableScript> executableCombineScript;
if (combineScript != null) {
executableCombineScript = queryShardContext.getLazyExecutableScript(combineScript, ScriptContext.AGGS_EXECUTABLE);
executableCombineScript = queryShardContext.getLazyExecutableScript(combineScript, ExecutableScript.AGGS_CONTEXT);
} else {
executableCombineScript = (p) -> null;
}

View File

@ -534,7 +534,7 @@ public class TopHitsAggregationBuilder extends AbstractAggregationBuilder<TopHit
if (scriptFields != null) {
for (ScriptField field : scriptFields) {
SearchScript searchScript = context.getQueryShardContext().getSearchScript(field.script(),
ScriptContext.SEARCH);
SearchScript.CONTEXT);
fields.add(new org.elasticsearch.search.fetch.subphase.ScriptFieldsContext.ScriptField(
field.fieldName(), searchScript, field.ignoreFailure()));
}

View File

@ -90,7 +90,7 @@ public class BucketScriptPipelineAggregator extends PipelineAggregator {
(InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket>) aggregation;
List<? extends InternalMultiBucketAggregation.InternalBucket> buckets = originalAgg.getBuckets();
ExecutableScript.Compiled compiledScript = reduceContext.scriptService().compile(script, ScriptContext.AGGS_EXECUTABLE);
ExecutableScript.Compiled compiledScript = reduceContext.scriptService().compile(script, ExecutableScript.AGGS_CONTEXT);
List<InternalMultiBucketAggregation.InternalBucket> newBuckets = new ArrayList<>();
for (InternalMultiBucketAggregation.InternalBucket bucket : buckets) {
Map<String, Object> vars = new HashMap<>();

View File

@ -83,7 +83,7 @@ public class BucketSelectorPipelineAggregator extends PipelineAggregator {
(InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket>) aggregation;
List<? extends InternalMultiBucketAggregation.InternalBucket> buckets = originalAgg.getBuckets();
ExecutableScript.Compiled compiledScript = reduceContext.scriptService().compile(script, ScriptContext.AGGS_EXECUTABLE);
ExecutableScript.Compiled compiledScript = reduceContext.scriptService().compile(script, ExecutableScript.AGGS_CONTEXT);
List<InternalMultiBucketAggregation.InternalBucket> newBuckets = new ArrayList<>();
for (InternalMultiBucketAggregation.InternalBucket bucket : buckets) {
Map<String, Object> vars = new HashMap<>();

View File

@ -120,7 +120,7 @@ public class ValuesSourceConfig<VS extends ValuesSource> {
if (script == null) {
return null;
} else {
return context.getSearchScript(script, ScriptContext.AGGS);
return context.getSearchScript(script, SearchScript.AGGS_CONTEXT);
}
}

View File

@ -242,7 +242,7 @@ public class ScriptSortBuilder extends SortBuilder<ScriptSortBuilder> {
@Override
public SortFieldAndFormat build(QueryShardContext context) throws IOException {
final SearchScript searchScript = context.getSearchScript(script, ScriptContext.SEARCH);
final SearchScript searchScript = context.getSearchScript(script, SearchScript.CONTEXT);
MultiValueMode valueMode = null;
if (sortMode != null) {

View File

@ -631,7 +631,7 @@ public class PhraseSuggestionBuilder extends SuggestionBuilder<PhraseSuggestionB
if (this.collateQuery != null) {
Function<Map<String, Object>, ExecutableScript> compiledScript = context.getLazyExecutableScript(this.collateQuery,
ScriptContext.EXECUTABLE);
ExecutableScript.CONTEXT);
suggestionContext.setCollateQueryScript(compiledScript);
if (this.collateParams != null) {
suggestionContext.setCollateScriptParams(this.collateParams);

View File

@ -42,8 +42,8 @@ import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.test.ESTestCase;
@ -136,7 +136,7 @@ public class UpdateRequestTests extends ESTestCase {
scripts.put("return", vars -> null);
final MockScriptEngine engine = new MockScriptEngine("mock", scripts);
Map<String, ScriptEngine> engines = Collections.singletonMap(engine.getType(), engine);
ScriptService scriptService = new ScriptService(baseSettings, engines, ScriptContext.BUILTINS);
ScriptService scriptService = new ScriptService(baseSettings, engines, ScriptModule.CORE_CONTEXTS);
final Settings settings = settings(Version.CURRENT).build();
updateHelper = new UpdateHelper(settings, scriptService);

View File

@ -70,7 +70,7 @@ public class ScriptServiceTests extends ESTestCase {
scripts.put("script", p -> null);
scriptEngine = new MockScriptEngine(Script.DEFAULT_SCRIPT_LANG, scripts);
//prevent duplicates using map
contexts = new HashMap<>(ScriptContext.BUILTINS);
contexts = new HashMap<>(ScriptModule.CORE_CONTEXTS);
engines = new HashMap<>();
engines.put(scriptEngine.getType(), scriptEngine);
engines.put("test", new MockScriptEngine("test", scripts));
@ -124,25 +124,25 @@ public class ScriptServiceTests extends ESTestCase {
public void testInlineScriptCompiledOnceCache() throws IOException {
buildScriptService(Settings.EMPTY);
Script script = new Script(ScriptType.INLINE, "test", "1+1", Collections.emptyMap());
SearchScript.Compiled compiledScript1 = scriptService.compile(script, ScriptContext.SEARCH);
SearchScript.Compiled compiledScript2 = scriptService.compile(script, ScriptContext.SEARCH);
SearchScript.Compiled compiledScript1 = scriptService.compile(script, SearchScript.CONTEXT);
SearchScript.Compiled compiledScript2 = scriptService.compile(script, SearchScript.CONTEXT);
assertThat(compiledScript1, sameInstance(compiledScript2));
}
public void testAllowAllScriptTypeSettings() throws IOException {
buildScriptService(Settings.EMPTY);
assertCompileAccepted("painless", "script", ScriptType.INLINE, ScriptContext.SEARCH);
assertCompileAccepted("painless", "script", ScriptType.STORED, ScriptContext.SEARCH);
assertCompileAccepted("painless", "script", ScriptType.INLINE, SearchScript.CONTEXT);
assertCompileAccepted("painless", "script", ScriptType.STORED, SearchScript.CONTEXT);
}
public void testAllowAllScriptContextSettings() throws IOException {
buildScriptService(Settings.EMPTY);
assertCompileAccepted("painless", "script", ScriptType.INLINE, ScriptContext.SEARCH);
assertCompileAccepted("painless", "script", ScriptType.INLINE, ScriptContext.AGGS);
assertCompileAccepted("painless", "script", ScriptType.INLINE, ScriptContext.UPDATE);
assertCompileAccepted("painless", "script", ScriptType.INLINE, ScriptContext.INGEST);
assertCompileAccepted("painless", "script", ScriptType.INLINE, SearchScript.CONTEXT);
assertCompileAccepted("painless", "script", ScriptType.INLINE, SearchScript.AGGS_CONTEXT);
assertCompileAccepted("painless", "script", ScriptType.INLINE, ExecutableScript.UPDATE_CONTEXT);
assertCompileAccepted("painless", "script", ScriptType.INLINE, ExecutableScript.INGEST_CONTEXT);
}
public void testAllowSomeScriptTypeSettings() throws IOException {
@ -150,8 +150,8 @@ public class ScriptServiceTests extends ESTestCase {
builder.put("script.allowed_types", "inline");
buildScriptService(builder.build());
assertCompileAccepted("painless", "script", ScriptType.INLINE, ScriptContext.SEARCH);
assertCompileRejected("painless", "script", ScriptType.STORED, ScriptContext.SEARCH);
assertCompileAccepted("painless", "script", ScriptType.INLINE, SearchScript.CONTEXT);
assertCompileRejected("painless", "script", ScriptType.STORED, SearchScript.CONTEXT);
}
public void testAllowSomeScriptContextSettings() throws IOException {
@ -159,9 +159,9 @@ public class ScriptServiceTests extends ESTestCase {
builder.put("script.allowed_contexts", "search, aggs");
buildScriptService(builder.build());
assertCompileAccepted("painless", "script", ScriptType.INLINE, ScriptContext.SEARCH);
assertCompileAccepted("painless", "script", ScriptType.INLINE, ScriptContext.AGGS);
assertCompileRejected("painless", "script", ScriptType.INLINE, ScriptContext.UPDATE);
assertCompileAccepted("painless", "script", ScriptType.INLINE, SearchScript.CONTEXT);
assertCompileAccepted("painless", "script", ScriptType.INLINE, SearchScript.AGGS_CONTEXT);
assertCompileRejected("painless", "script", ScriptType.INLINE, ExecutableScript.UPDATE_CONTEXT);
}
public void testAllowNoScriptTypeSettings() throws IOException {
@ -169,8 +169,8 @@ public class ScriptServiceTests extends ESTestCase {
builder.put("script.allowed_types", "none");
buildScriptService(builder.build());
assertCompileRejected("painless", "script", ScriptType.INLINE, ScriptContext.SEARCH);
assertCompileRejected("painless", "script", ScriptType.STORED, ScriptContext.SEARCH);
assertCompileRejected("painless", "script", ScriptType.INLINE, SearchScript.CONTEXT);
assertCompileRejected("painless", "script", ScriptType.STORED, SearchScript.CONTEXT);
}
public void testAllowNoScriptContextSettings() throws IOException {
@ -178,18 +178,18 @@ public class ScriptServiceTests extends ESTestCase {
builder.put("script.allowed_contexts", "none");
buildScriptService(builder.build());
assertCompileRejected("painless", "script", ScriptType.INLINE, ScriptContext.SEARCH);
assertCompileRejected("painless", "script", ScriptType.INLINE, ScriptContext.AGGS);
assertCompileRejected("painless", "script", ScriptType.INLINE, SearchScript.CONTEXT);
assertCompileRejected("painless", "script", ScriptType.INLINE, SearchScript.AGGS_CONTEXT);
}
public void testCompileNonRegisteredContext() throws IOException {
contexts.remove(ScriptContext.INGEST.name);
contexts.remove(ExecutableScript.INGEST_CONTEXT.name);
buildScriptService(Settings.EMPTY);
String type = scriptEngine.getType();
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () ->
scriptService.compile(new Script(randomFrom(ScriptType.values()), type, "test", Collections.emptyMap()), ScriptContext.INGEST));
assertThat(e.getMessage(), containsString("script context [" + ScriptContext.INGEST.name + "] not supported"));
scriptService.compile(new Script(randomFrom(ScriptType.values()), type, "test", Collections.emptyMap()), ExecutableScript.INGEST_CONTEXT));
assertThat(e.getMessage(), containsString("script context [" + ExecutableScript.INGEST_CONTEXT.name + "] not supported"));
}
public void testCompileCountedInCompilationStats() throws IOException {

View File

@ -25,6 +25,8 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.ParsedAggregation;
@ -113,7 +115,8 @@ public class InternalScriptedMetricTests extends InternalAggregationTestCase<Int
@SuppressWarnings("unchecked")
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME,
Collections.singletonMap(REDUCE_SCRIPT_NAME, script -> ((List<Object>) script.get("_aggs")).size()));
return new ScriptService(Settings.EMPTY, Collections.singletonMap(scriptEngine.getType(), scriptEngine), ScriptContext.BUILTINS);
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS);
}
@Override

View File

@ -35,6 +35,7 @@ import org.elasticsearch.script.ScoreAccessor;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
@ -197,7 +198,7 @@ public class ScriptedMetricAggregatorTests extends AggregatorTestCase {
CircuitBreakerService circuitBreakerService) {
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, SCRIPTS);
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
ScriptService scriptService = new ScriptService(Settings.EMPTY, engines, ScriptContext.BUILTINS);
ScriptService scriptService = new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS);
return new QueryShardContext(0, mapperService.getIndexSettings(), null, null, mapperService, null, scriptService,
xContentRegistry(), null, null, System::currentTimeMillis);
}

View File

@ -80,7 +80,7 @@ public class ExplainableScriptIT extends ESIntegTestCase {
@Override
public <T> T compile(String scriptName, String scriptSource, ScriptContext<T> context, Map<String, String> params) {
assert scriptSource.equals("explainable_script");
assert context == ScriptContext.SEARCH;
assert context == SearchScript.CONTEXT;
SearchScript.Compiled compiled = (p, lookup) -> new SearchScript() {
@Override
public LeafSearchScript getLeafSearchScript(LeafReaderContext context) throws IOException {

View File

@ -53,6 +53,7 @@ import org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.SearchModule;
@ -87,7 +88,7 @@ public abstract class AbstractSortTestCase<T extends SortBuilder<T>> extends EST
.build();
Map<String, Function<Map<String, Object>, Object>> scripts = Collections.singletonMap("dummy", p -> null);
ScriptEngine engine = new MockScriptEngine(MockScriptEngine.NAME, scripts);
scriptService = new ScriptService(baseSettings, Collections.singletonMap(engine.getType(), engine), ScriptContext.BUILTINS);
scriptService = new ScriptService(baseSettings, Collections.singletonMap(engine.getType(), engine), ScriptModule.CORE_CONTEXTS);
SearchModule searchModule = new SearchModule(Settings.EMPTY, false, emptyList());
namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables());

View File

@ -69,7 +69,7 @@ public final class ScriptProcessor extends AbstractProcessor {
*/
@Override
public void execute(IngestDocument document) {
ExecutableScript.Compiled compiledScript = scriptService.compile(script, ScriptContext.INGEST);
ExecutableScript.Compiled compiledScript = scriptService.compile(script, ExecutableScript.INGEST_CONTEXT);
ExecutableScript executableScript = compiledScript.newInstance(script.getParams());
executableScript.setNextVar("ctx", document.getSourceAndMetadata());
executableScript.run();
@ -133,7 +133,7 @@ public final class ScriptProcessor extends AbstractProcessor {
// verify script is able to be compiled before successfully creating processor.
try {
scriptService.compile(script, ScriptContext.INGEST);
scriptService.compile(script, ExecutableScript.INGEST_CONTEXT);
} catch (ScriptException e) {
throw newConfigurationException(TYPE, processorTag, scriptPropertyUsed, e);
}

View File

@ -48,7 +48,7 @@ public class ScriptProcessorTests extends ESTestCase {
Script script = mockScript("_script");
ExecutableScript.Compiled compiledScript = mock(ExecutableScript.Compiled.class);
ExecutableScript executableScript = mock(ExecutableScript.class);
when(scriptService.compile(script, ScriptContext.INGEST)).thenReturn(compiledScript);
when(scriptService.compile(script, ExecutableScript.INGEST_CONTEXT)).thenReturn(compiledScript);
when(compiledScript.newInstance(any())).thenReturn(executableScript);
Map<String, Object> document = new HashMap<>();

View File

@ -43,7 +43,7 @@ public class ExpressionTests extends ESSingleNodeTestCase {
}
private SearchScript compile(String expression) {
SearchScript.Compiled compiled = service.compile(null, expression, ScriptContext.SEARCH, Collections.emptyMap());
SearchScript.Compiled compiled = service.compile(null, expression, SearchScript.CONTEXT, Collections.emptyMap());
return compiled.newInstance(Collections.emptyMap(), lookup);
}

View File

@ -34,6 +34,7 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.builder.SearchSourceBuilder;
@ -44,7 +45,7 @@ import org.elasticsearch.transport.TransportService;
import java.io.IOException;
import java.util.Collections;
import static org.elasticsearch.script.ScriptContext.EXECUTABLE;
import static org.elasticsearch.script.ExecutableScript.CONTEXT;
public class TransportSearchTemplateAction extends HandledTransportAction<SearchTemplateRequest, SearchTemplateResponse> {
@ -100,7 +101,7 @@ public class TransportSearchTemplateAction extends HandledTransportAction<Search
NamedXContentRegistry xContentRegistry) throws IOException {
Script script = new Script(searchTemplateRequest.getScriptType(), TEMPLATE_LANG, searchTemplateRequest.getScript(),
searchTemplateRequest.getScriptParams() == null ? Collections.emptyMap() : searchTemplateRequest.getScriptParams());
CompiledTemplate compiledScript = scriptService.compileTemplate(script, EXECUTABLE);
CompiledTemplate compiledScript = scriptService.compileTemplate(script, ExecutableScript.CONTEXT);
String source = compiledScript.run(script.getParams());
response.setSource(new BytesArray(source));

View File

@ -62,7 +62,7 @@ public class CustomMustacheFactoryTests extends ESTestCase {
final ScriptEngine engine = new MustacheScriptEngine();
final Map<String, String> params = randomBoolean() ? singletonMap(Script.CONTENT_TYPE_OPTION, JSON_MIME_TYPE) : emptyMap();
ExecutableScript.Compiled compiled = engine.compile(null, "{\"field\": \"{{value}}\"}", ScriptContext.EXECUTABLE, params);
ExecutableScript.Compiled compiled = engine.compile(null, "{\"field\": \"{{value}}\"}", ExecutableScript.CONTEXT, params);
ExecutableScript executable = compiled.newInstance(singletonMap("value", "a \"value\""));
assertThat(executable.run(), equalTo("{\"field\": \"a \\\"value\\\"\"}"));
@ -72,7 +72,7 @@ public class CustomMustacheFactoryTests extends ESTestCase {
final ScriptEngine engine = new MustacheScriptEngine();
final Map<String, String> params = singletonMap(Script.CONTENT_TYPE_OPTION, PLAIN_TEXT_MIME_TYPE);
ExecutableScript.Compiled compiled = engine.compile(null, "{\"field\": \"{{value}}\"}", ScriptContext.EXECUTABLE, params);
ExecutableScript.Compiled compiled = engine.compile(null, "{\"field\": \"{{value}}\"}", ExecutableScript.CONTEXT, params);
ExecutableScript executable = compiled.newInstance(singletonMap("value", "a \"value\""));
assertThat(executable.run(), equalTo("{\"field\": \"a \"value\"\"}"));
@ -82,7 +82,7 @@ public class CustomMustacheFactoryTests extends ESTestCase {
final ScriptEngine engine = new MustacheScriptEngine();
final Map<String, String> params = singletonMap(Script.CONTENT_TYPE_OPTION, X_WWW_FORM_URLENCODED_MIME_TYPE);
ExecutableScript.Compiled compiled = engine.compile(null, "{\"field\": \"{{value}}\"}", ScriptContext.EXECUTABLE, params);
ExecutableScript.Compiled compiled = engine.compile(null, "{\"field\": \"{{value}}\"}", ExecutableScript.CONTEXT, params);
ExecutableScript executable = compiled.newInstance(singletonMap("value", "tilde~ AND date:[2016 FROM*]"));
assertThat(executable.run(), equalTo("{\"field\": \"tilde%7E+AND+date%3A%5B2016+FROM*%5D\"}"));

View File

@ -56,7 +56,7 @@ public class MustacheScriptEngineTests extends ESTestCase {
+ "\"negative\": {\"term\": {\"body\": {\"value\": \"solr\"}" + "}}, \"negative_boost\": {{boost_val}} } }}";
Map<String, Object> vars = new HashMap<>();
vars.put("boost_val", "0.3");
String o = (String) qe.compile(null, template, ScriptContext.EXECUTABLE, compileParams).newInstance(vars).run();
String o = (String) qe.compile(null, template, ExecutableScript.CONTEXT, compileParams).newInstance(vars).run();
assertEquals("GET _search {\"query\": {\"boosting\": {\"positive\": {\"match\": {\"body\": \"gift\"}},"
+ "\"negative\": {\"term\": {\"body\": {\"value\": \"solr\"}}}, \"negative_boost\": 0.3 } }}",
o);
@ -67,7 +67,7 @@ public class MustacheScriptEngineTests extends ESTestCase {
Map<String, Object> vars = new HashMap<>();
vars.put("boost_val", "0.3");
vars.put("body_val", "\"quick brown\"");
String o = (String) qe.compile(null, template, ScriptContext.EXECUTABLE, compileParams).newInstance(vars).run();
String o = (String) qe.compile(null, template, ExecutableScript.CONTEXT, compileParams).newInstance(vars).run();
assertEquals("GET _search {\"query\": {\"boosting\": {\"positive\": {\"match\": {\"body\": \"gift\"}},"
+ "\"negative\": {\"term\": {\"body\": {\"value\": \"\\\"quick brown\\\"\"}}}, \"negative_boost\": 0.3 } }}",
o);
@ -82,7 +82,7 @@ public class MustacheScriptEngineTests extends ESTestCase {
+ "}";
XContentParser parser = createParser(JsonXContent.jsonXContent, templateString);
Script script = Script.parse(parser);
ExecutableScript.Compiled compiled = qe.compile(null, script.getIdOrCode(), ScriptContext.EXECUTABLE, Collections.emptyMap());
ExecutableScript.Compiled compiled = qe.compile(null, script.getIdOrCode(), ExecutableScript.CONTEXT, Collections.emptyMap());
ExecutableScript executableScript = compiled.newInstance(script.getParams());
assertThat(executableScript.run(), equalTo("{\"match_all\":{}}"));
}
@ -97,7 +97,7 @@ public class MustacheScriptEngineTests extends ESTestCase {
+ "}";
XContentParser parser = createParser(JsonXContent.jsonXContent, templateString);
Script script = Script.parse(parser);
ExecutableScript.Compiled compiled = qe.compile(null, script.getIdOrCode(), ScriptContext.EXECUTABLE, Collections.emptyMap());
ExecutableScript.Compiled compiled = qe.compile(null, script.getIdOrCode(), ExecutableScript.CONTEXT, Collections.emptyMap());
ExecutableScript executableScript = compiled.newInstance(script.getParams());
assertThat(executableScript.run(), equalTo("{ \"match_all\":{} }"));
}

View File

@ -62,7 +62,7 @@ public class MustacheTests extends ESTestCase {
+ "}}, \"negative_boost\": {{boost_val}} } }}";
Map<String, Object> params = Collections.singletonMap("boost_val", "0.2");
ExecutableScript.Compiled compiled = engine.compile(null, template, ScriptContext.EXECUTABLE, Collections.emptyMap());
ExecutableScript.Compiled compiled = engine.compile(null, template, ExecutableScript.CONTEXT, Collections.emptyMap());
ExecutableScript result = compiled.newInstance(params);
assertEquals(
"Mustache templating broken",
@ -74,7 +74,7 @@ public class MustacheTests extends ESTestCase {
public void testArrayAccess() throws Exception {
String template = "{{data.0}} {{data.1}}";
ExecutableScript.Compiled compiled = engine.compile(null, template, ScriptContext.EXECUTABLE, Collections.emptyMap());
ExecutableScript.Compiled compiled = engine.compile(null, template, ExecutableScript.CONTEXT, Collections.emptyMap());
Map<String, Object> vars = new HashMap<>();
Object data = randomFrom(
new String[] { "foo", "bar" },
@ -94,7 +94,7 @@ public class MustacheTests extends ESTestCase {
public void testArrayInArrayAccess() throws Exception {
String template = "{{data.0.0}} {{data.0.1}}";
ExecutableScript.Compiled compiled = engine.compile(null, template, ScriptContext.EXECUTABLE, Collections.emptyMap());
ExecutableScript.Compiled compiled = engine.compile(null, template, ExecutableScript.CONTEXT, Collections.emptyMap());
Map<String, Object> vars = new HashMap<>();
Object data = randomFrom(
new String[][] { new String[] { "foo", "bar" }},
@ -107,7 +107,7 @@ public class MustacheTests extends ESTestCase {
public void testMapInArrayAccess() throws Exception {
String template = "{{data.0.key}} {{data.1.key}}";
ExecutableScript.Compiled compiled= engine.compile(null, template, ScriptContext.EXECUTABLE, Collections.emptyMap());
ExecutableScript.Compiled compiled= engine.compile(null, template, ExecutableScript.CONTEXT, Collections.emptyMap());
Map<String, Object> vars = new HashMap<>();
Object data = randomFrom(
new Object[] { singletonMap("key", "foo"), singletonMap("key", "bar") },
@ -131,7 +131,7 @@ public class MustacheTests extends ESTestCase {
List<String> randomList = Arrays.asList(generateRandomStringArray(10, 20, false));
String template = "{{data.array.size}} {{data.list.size}}";
ExecutableScript.Compiled compiled = engine.compile(null, template, ScriptContext.EXECUTABLE, Collections.emptyMap());
ExecutableScript.Compiled compiled = engine.compile(null, template, ExecutableScript.CONTEXT, Collections.emptyMap());
Map<String, Object> data = new HashMap<>();
data.put("array", randomArrayValues);
data.put("list", randomList);
@ -379,6 +379,6 @@ public class MustacheTests extends ESTestCase {
private ExecutableScript.Compiled compile(String script) {
assertThat("cannot compile null or empty script", script, not(isEmptyOrNullString()));
return engine.compile(null, script, ScriptContext.EXECUTABLE, Collections.emptyMap());
return engine.compile(null, script, ExecutableScript.CONTEXT, Collections.emptyMap());
}
}

View File

@ -40,19 +40,19 @@ public class NeedsScoreTests extends ESSingleNodeTestCase {
PainlessScriptEngine service = new PainlessScriptEngine(Settings.EMPTY);
SearchLookup lookup = new SearchLookup(index.mapperService(), index.fieldData(), null);
SearchScript.Compiled compiled = service.compile(null, "1.2", ScriptContext.SEARCH, Collections.emptyMap());
SearchScript.Compiled compiled = service.compile(null, "1.2", SearchScript.CONTEXT, Collections.emptyMap());
SearchScript ss = compiled.newInstance(Collections.emptyMap(), lookup);
assertFalse(ss.needsScores());
compiled = service.compile(null, "doc['d'].value", ScriptContext.SEARCH, Collections.emptyMap());
compiled = service.compile(null, "doc['d'].value", SearchScript.CONTEXT, Collections.emptyMap());
ss = compiled.newInstance(Collections.emptyMap(), lookup);
assertFalse(ss.needsScores());
compiled = service.compile(null, "1/_score", ScriptContext.SEARCH, Collections.emptyMap());
compiled = service.compile(null, "1/_score", SearchScript.CONTEXT, Collections.emptyMap());
ss = compiled.newInstance(Collections.emptyMap(), lookup);
assertTrue(ss.needsScores());
compiled = service.compile(null, "doc['d'].value * _score", ScriptContext.SEARCH, Collections.emptyMap());
compiled = service.compile(null, "doc['d'].value * _score", SearchScript.CONTEXT, Collections.emptyMap());
ss = compiled.newInstance(Collections.emptyMap(), lookup);
assertTrue(ss.needsScores());
}

View File

@ -81,7 +81,7 @@ public class ScriptEngineTests extends ScriptTestCase {
vars.put("ctx", ctx);
ExecutableScript.Compiled compiledScript =
scriptEngine.compile(null, "return ctx.value;", ScriptContext.EXECUTABLE, Collections.emptyMap());
scriptEngine.compile(null, "return ctx.value;", ExecutableScript.CONTEXT, Collections.emptyMap());
ExecutableScript script = compiledScript.newInstance(vars);
ctx.put("value", 1);
@ -96,7 +96,7 @@ public class ScriptEngineTests extends ScriptTestCase {
public void testChangingVarsCrossExecution2() {
Map<String, Object> vars = new HashMap<>();
ExecutableScript.Compiled compiledScript =
scriptEngine.compile(null, "return params['value'];", ScriptContext.EXECUTABLE, Collections.emptyMap());
scriptEngine.compile(null, "return params['value'];", ExecutableScript.CONTEXT, Collections.emptyMap());
ExecutableScript script = compiledScript.newInstance(vars);
script.setNextVar("value", 1);

View File

@ -86,7 +86,7 @@ public abstract class ScriptTestCase extends ESTestCase {
definition, null);
}
// test actual script execution
ExecutableScript.Compiled compiled = scriptEngine.compile(null, script, ScriptContext.EXECUTABLE, compileParams);
ExecutableScript.Compiled compiled = scriptEngine.compile(null, script, ExecutableScript.CONTEXT, compileParams);
ExecutableScript executableScript = compiled.newInstance(vars);
if (scorer != null) {
((ScorerAware)executableScript).setScorer(scorer);

View File

@ -772,7 +772,7 @@ public abstract class AbstractAsyncBulkByScrollAction<Request extends AbstractBu
return request;
}
if (executable == null) {
ExecutableScript.Compiled compiled = scriptService.compile(script, ScriptContext.UPDATE);
ExecutableScript.Compiled compiled = scriptService.compile(script, ExecutableScript.UPDATE_CONTEXT);
executable = compiled.newInstance(params);
}
if (context == null) {

View File

@ -57,8 +57,8 @@ public abstract class AbstractAsyncBulkByScrollActionScriptTestCase<
ScrollableHitSource.Hit doc = new ScrollableHitSource.BasicHit("test", "type", "id", 0);
ExecutableScript executableScript = new SimpleExecutableScript(scriptBody);
ExecutableScript.Compiled compiled = params -> executableScript;
when(scriptService.compile(any(), eq(ScriptContext.EXECUTABLE))).thenReturn(compiled);
when(scriptService.compile(any(), eq(ScriptContext.UPDATE))).thenReturn(compiled);
when(scriptService.compile(any(), eq(ExecutableScript.CONTEXT))).thenReturn(compiled);
when(scriptService.compile(any(), eq(ExecutableScript.UPDATE_CONTEXT))).thenReturn(compiled);
AbstractAsyncBulkByScrollAction<Request> action = action(scriptService, request().setScript(mockScript("")));
RequestWrapper<?> result = action.buildScriptApplier().apply(AbstractAsyncBulkByScrollAction.wrap(index), doc);
return (result != null) ? (T) result.self() : null;

View File

@ -59,7 +59,7 @@ public class ExpertScriptPlugin extends Plugin implements ScriptPlugin {
@Override
public <T> T compile(String scriptName, String scriptSource, ScriptContext<T> context, Map<String, String> params) {
if (context.equals(ScriptContext.SEARCH) == false) {
if (context.equals(SearchScript.CONTEXT) == false) {
throw new IllegalArgumentException(getType() + " scripts cannot be used for context [" + context.name + "]");
}
// we use the script "source" as the script identifier

View File

@ -22,6 +22,7 @@ package org.elasticsearch.ingest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.mustache.MustacheScriptEngine;
import org.elasticsearch.test.ESTestCase;
@ -38,7 +39,7 @@ public abstract class AbstractScriptTestCase extends ESTestCase {
public void init() throws Exception {
MustacheScriptEngine engine = new MustacheScriptEngine();
Map<String, ScriptEngine> engines = Collections.singletonMap(engine.getType(), engine);
ScriptService scriptService = new ScriptService(Settings.EMPTY, engines, ScriptContext.BUILTINS);
ScriptService scriptService = new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS);
templateService = new InternalTemplateService(scriptService);
}