Remove most usages of 1-arg Script ctor (elastic/x-pack-elasticsearch#1207)

The one argument ctor for `Script` creates a script with the
default language but most usages of are for testing and either
don't care about the language or are for use with
`MockScriptEngine`. This replaces most usages of the one argument
ctor on `Script` with calls to `ESTestCase#mockScript` to make
it clear that the tests don't need the default scripting language.

Original commit: elastic/x-pack-elasticsearch@c1d05b7357
This commit is contained in:
Nik Everett 2017-04-27 11:35:42 -04:00 committed by GitHub
parent aa7d94ec44
commit 677ea404f7
14 changed files with 80 additions and 73 deletions

View File

@ -6,11 +6,14 @@
package org.elasticsearch.xpack.watcher.transform; package org.elasticsearch.xpack.watcher.transform;
import org.elasticsearch.script.Script; import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest; import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.transform.chain.ChainTransform; import org.elasticsearch.xpack.watcher.transform.chain.ChainTransform;
import org.elasticsearch.xpack.watcher.transform.script.ScriptTransform; import org.elasticsearch.xpack.watcher.transform.script.ScriptTransform;
import org.elasticsearch.xpack.watcher.transform.search.SearchTransform; import org.elasticsearch.xpack.watcher.transform.search.SearchTransform;
import static java.util.Collections.emptyMap;
public final class TransformBuilders { public final class TransformBuilders {
private TransformBuilders() { private TransformBuilders() {
@ -21,7 +24,7 @@ public final class TransformBuilders {
} }
public static ScriptTransform.Builder scriptTransform(String script) { public static ScriptTransform.Builder scriptTransform(String script) {
return scriptTransform(new Script(script)); return scriptTransform(new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, script, emptyMap()));
} }
public static ScriptTransform.Builder scriptTransform(Script script) { public static ScriptTransform.Builder scriptTransform(Script script) {

View File

@ -6,11 +6,11 @@
package org.elasticsearch.xpack.ml.datafeed; package org.elasticsearch.xpack.ml.datafeed;
import com.carrotsearch.randomizedtesting.generators.CodepointSetGenerator; import com.carrotsearch.randomizedtesting.generators.CodepointSetGenerator;
import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
@ -55,7 +55,7 @@ public class DatafeedConfigTests extends AbstractSerializingTestCase<DatafeedCon
int scriptsSize = randomInt(3); int scriptsSize = randomInt(3);
List<SearchSourceBuilder.ScriptField> scriptFields = new ArrayList<>(scriptsSize); List<SearchSourceBuilder.ScriptField> scriptFields = new ArrayList<>(scriptsSize);
for (int scriptIndex = 0; scriptIndex < scriptsSize; scriptIndex++) { for (int scriptIndex = 0; scriptIndex < scriptsSize; scriptIndex++) {
scriptFields.add(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), new Script(randomAlphaOfLength(10)), scriptFields.add(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), mockScript(randomAlphaOfLength(10)),
randomBoolean())); randomBoolean()));
} }
builder.setScriptFields(scriptFields); builder.setScriptFields(scriptFields);
@ -192,7 +192,7 @@ public class DatafeedConfigTests extends AbstractSerializingTestCase<DatafeedCon
datafeed.setIndexes(Arrays.asList("my_index")); datafeed.setIndexes(Arrays.asList("my_index"));
datafeed.setTypes(Arrays.asList("my_type")); datafeed.setTypes(Arrays.asList("my_type"));
datafeed.setScriptFields(Arrays.asList(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), datafeed.setScriptFields(Arrays.asList(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10),
new Script(randomAlphaOfLength(10)), randomBoolean()))); mockScript(randomAlphaOfLength(10)), randomBoolean())));
datafeed.setAggregations(new AggregatorFactories.Builder().addAggregator(AggregationBuilders.avg("foo"))); datafeed.setAggregations(new AggregatorFactories.Builder().addAggregator(AggregationBuilders.avg("foo")));
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> datafeed.build()); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> datafeed.build());

View File

@ -9,7 +9,6 @@ import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder;
@ -53,7 +52,7 @@ public class DatafeedUpdateTests extends AbstractSerializingTestCase<DatafeedUpd
int scriptsSize = randomInt(3); int scriptsSize = randomInt(3);
List<SearchSourceBuilder.ScriptField> scriptFields = new ArrayList<>(scriptsSize); List<SearchSourceBuilder.ScriptField> scriptFields = new ArrayList<>(scriptsSize);
for (int scriptIndex = 0; scriptIndex < scriptsSize; scriptIndex++) { for (int scriptIndex = 0; scriptIndex < scriptsSize; scriptIndex++) {
scriptFields.add(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), new Script(randomAlphaOfLength(10)), scriptFields.add(new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), mockScript(randomAlphaOfLength(10)),
randomBoolean())); randomBoolean()));
} }
builder.setScriptFields(scriptFields); builder.setScriptFields(scriptFields);
@ -126,7 +125,7 @@ public class DatafeedUpdateTests extends AbstractSerializingTestCase<DatafeedUpd
update.setQueryDelay(TimeValue.timeValueSeconds(42)); update.setQueryDelay(TimeValue.timeValueSeconds(42));
update.setFrequency(TimeValue.timeValueSeconds(142)); update.setFrequency(TimeValue.timeValueSeconds(142));
update.setQuery(QueryBuilders.termQuery("a", "b")); update.setQuery(QueryBuilders.termQuery("a", "b"));
update.setScriptFields(Arrays.asList(new SearchSourceBuilder.ScriptField("a", new Script("b"), false))); update.setScriptFields(Arrays.asList(new SearchSourceBuilder.ScriptField("a", mockScript("b"), false)));
update.setScrollSize(8000); update.setScrollSize(8000);
update.setSource(true); update.setSource(true);
update.setChunkingConfig(ChunkingConfig.newManual(TimeValue.timeValueHours(1))); update.setChunkingConfig(ChunkingConfig.newManual(TimeValue.timeValueHours(1)));
@ -141,7 +140,7 @@ public class DatafeedUpdateTests extends AbstractSerializingTestCase<DatafeedUpd
assertThat(updatedDatafeed.getQuery(), equalTo(QueryBuilders.termQuery("a", "b"))); assertThat(updatedDatafeed.getQuery(), equalTo(QueryBuilders.termQuery("a", "b")));
assertThat(updatedDatafeed.hasAggregations(), is(false)); assertThat(updatedDatafeed.hasAggregations(), is(false));
assertThat(updatedDatafeed.getScriptFields(), assertThat(updatedDatafeed.getScriptFields(),
equalTo(Arrays.asList(new SearchSourceBuilder.ScriptField("a", new Script("b"), false)))); equalTo(Arrays.asList(new SearchSourceBuilder.ScriptField("a", mockScript("b"), false))));
assertThat(updatedDatafeed.getScrollSize(), equalTo(8000)); assertThat(updatedDatafeed.getScrollSize(), equalTo(8000));
assertThat(updatedDatafeed.isSource(), is(true)); assertThat(updatedDatafeed.isSource(), is(true));
assertThat(updatedDatafeed.getChunkingConfig(), equalTo(ChunkingConfig.newManual(TimeValue.timeValueHours(1)))); assertThat(updatedDatafeed.getChunkingConfig(), equalTo(ChunkingConfig.newManual(TimeValue.timeValueHours(1))));

View File

@ -12,12 +12,13 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus; import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.script.Script;
import org.junit.Before; import org.junit.Before;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -34,6 +35,7 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static java.util.Collections.emptyMap;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
@ -278,9 +280,9 @@ public class ScrollDataExtractorTests extends ESTestCase {
public void testDomainSplitScriptField() throws IOException { public void testDomainSplitScriptField() throws IOException {
SearchSourceBuilder.ScriptField withoutSplit = new SearchSourceBuilder.ScriptField( SearchSourceBuilder.ScriptField withoutSplit = new SearchSourceBuilder.ScriptField(
"script1", new Script("return 1+1;"), false); "script1", mockScript("return 1+1;"), false);
SearchSourceBuilder.ScriptField withSplit = new SearchSourceBuilder.ScriptField( SearchSourceBuilder.ScriptField withSplit = new SearchSourceBuilder.ScriptField(
"script2", new Script("return domainSplit('foo.com', params);"), false); "script2", new Script(ScriptType.INLINE, "painless", "return domainSplit('foo.com', params);", emptyMap()), false);
List<SearchSourceBuilder.ScriptField> sFields = Arrays.asList(withoutSplit, withSplit); List<SearchSourceBuilder.ScriptField> sFields = Arrays.asList(withoutSplit, withSplit);
ScrollDataExtractorContext context = new ScrollDataExtractorContext(jobId, extractedFields, indexes, ScrollDataExtractorContext context = new ScrollDataExtractorContext(jobId, extractedFields, indexes,
@ -317,7 +319,7 @@ public class ScrollDataExtractorTests extends ESTestCase {
assertThat(searchRequest, containsString("\"stored_fields\":\"_none_\"")); assertThat(searchRequest, containsString("\"stored_fields\":\"_none_\""));
// Check for the scripts // Check for the scripts
assertThat(searchRequest, containsString("{\"script\":{\"inline\":\"return 1 + 1;\",\"lang\":\"painless\"}" assertThat(searchRequest, containsString("{\"script\":{\"inline\":\"return 1 + 1;\",\"lang\":\"mockscript\"}"
.replaceAll("\\s", ""))); .replaceAll("\\s", "")));
assertThat(searchRequest, containsString("List domainSplit(String host, Map params)".replaceAll("\\s", ""))); assertThat(searchRequest, containsString("List domainSplit(String host, Map params)".replaceAll("\\s", "")));
assertThat(searchRequest, containsString("String replaceDots(String input) {".replaceAll("\\s", ""))); assertThat(searchRequest, containsString("String replaceDots(String input) {".replaceAll("\\s", "")));

View File

@ -8,7 +8,6 @@ package org.elasticsearch.xpack.watcher.condition;
import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService; import org.elasticsearch.script.ScriptService;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
@ -53,7 +52,7 @@ public class AlwaysConditionTests extends ESTestCase {
String type = randomFrom(ScriptCondition.TYPE, AlwaysCondition.TYPE, CompareCondition.TYPE, ArrayCompareCondition.TYPE); String type = randomFrom(ScriptCondition.TYPE, AlwaysCondition.TYPE, CompareCondition.TYPE, ArrayCompareCondition.TYPE);
switch (type) { switch (type) {
case ScriptCondition.TYPE: case ScriptCondition.TYPE:
return new ScriptCondition(new Script("_script"), scriptService); return new ScriptCondition(mockScript("_script"), scriptService);
case CompareCondition.TYPE: case CompareCondition.TYPE:
return new CompareCondition("_path", randomFrom(CompareCondition.Op.values()), randomFrom(5, "3"), return new CompareCondition("_path", randomFrom(CompareCondition.Op.values()), randomFrom(5, "3"),
Clock.systemUTC()); Clock.systemUTC());

View File

@ -12,14 +12,13 @@ import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.index.Index; import org.elasticsearch.index.Index;
import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin; import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService; import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.internal.InternalSearchResponse; import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
@ -65,11 +64,6 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa
return scripts; return scripts;
} }
@Override
public String pluginScriptLang() {
return WATCHER_LANG;
}
} }
public void testExecuteWithAggs() throws Exception { public void testExecuteWithAggs() throws Exception {
@ -86,7 +80,7 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa
ScriptService scriptService = internalCluster().getInstance(ScriptService.class); ScriptService scriptService = internalCluster().getInstance(ScriptService.class);
ScriptCondition condition = new ScriptCondition( ScriptCondition condition = new ScriptCondition(
new Script("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5"), mockScript("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5"),
scriptService); scriptService);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
@ -106,7 +100,7 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa
public void testExecuteAccessHits() throws Exception { public void testExecuteAccessHits() throws Exception {
ScriptService scriptService = internalCluster().getInstance(ScriptService.class); ScriptService scriptService = internalCluster().getInstance(ScriptService.class);
ScriptCondition condition = new ScriptCondition( ScriptCondition condition = new ScriptCondition(
new Script("ctx.payload.hits?.hits[0]?._score == 1.0"), scriptService); mockScript("ctx.payload.hits?.hits[0]?._score == 1.0"), scriptService);
SearchHit hit = new SearchHit(0, "1", new Text("type"), null); SearchHit hit = new SearchHit(0, "1", new Text("type"), null);
hit.score(1f); hit.score(1f);
hit.shard(new SearchShardTarget("a", new Index("a", "testUUID"), 0)); hit.shard(new SearchShardTarget("a", new Index("a", "testUUID"), 0));

View File

@ -87,7 +87,7 @@ public class ScriptConditionTests extends ESTestCase {
return total > threshold; return total > threshold;
}); });
ScriptEngineService engine = new MockScriptEngine(AbstractWatcherIntegrationTestCase.WATCHER_LANG, scripts); ScriptEngineService engine = new MockScriptEngine(MockScriptEngine.NAME, scripts);
ScriptEngineRegistry registry = new ScriptEngineRegistry(singleton(engine)); ScriptEngineRegistry registry = new ScriptEngineRegistry(singleton(engine));
ScriptContextRegistry contextRegistry = new ScriptContextRegistry(singleton(new ScriptContext.Plugin("xpack", "watch"))); ScriptContextRegistry contextRegistry = new ScriptContextRegistry(singleton(new ScriptContext.Plugin("xpack", "watch")));
@ -106,15 +106,14 @@ public class ScriptConditionTests extends ESTestCase {
} }
public void testExecute() throws Exception { public void testExecute() throws Exception {
ScriptCondition condition = new ScriptCondition(new Script("ctx.payload.hits.total > 1"), scriptService); ScriptCondition condition = new ScriptCondition(mockScript("ctx.payload.hits.total > 1"), scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
assertFalse(condition.execute(ctx).met()); assertFalse(condition.execute(ctx).met());
} }
public void testExecuteMergedParams() throws Exception { public void testExecuteMergedParams() throws Exception {
Script script = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, Script script = new Script(ScriptType.INLINE, "mockscript", "ctx.payload.hits.total > threshold", singletonMap("threshold", 1));
"ctx.payload.hits.total > threshold", singletonMap("threshold", 1));
ScriptCondition executable = new ScriptCondition(script, scriptService); ScriptCondition executable = new ScriptCondition(script, scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
@ -123,7 +122,7 @@ public class ScriptConditionTests extends ESTestCase {
public void testParserValid() throws Exception { public void testParserValid() throws Exception {
XContentBuilder builder = createConditionContent("ctx.payload.hits.total > 1", null, ScriptType.INLINE); XContentBuilder builder = createConditionContent("ctx.payload.hits.total > 1", "mockscript", ScriptType.INLINE);
XContentParser parser = createParser(builder); XContentParser parser = createParser(builder);
parser.nextToken(); parser.nextToken();
@ -135,7 +134,7 @@ public class ScriptConditionTests extends ESTestCase {
assertFalse(executable.execute(ctx).met()); assertFalse(executable.execute(ctx).met());
builder = createConditionContent("return true", null, ScriptType.INLINE); builder = createConditionContent("return true", "mockscript", ScriptType.INLINE);
parser = createParser(builder); parser = createParser(builder);
parser.nextToken(); parser.nextToken();
executable = ScriptCondition.parse(scriptService, "_watch", parser); executable = ScriptCondition.parse(scriptService, "_watch", parser);
@ -176,7 +175,7 @@ public class ScriptConditionTests extends ESTestCase {
expectedException = GeneralScriptException.class; expectedException = GeneralScriptException.class;
script = "foo = = 1"; script = "foo = = 1";
} }
XContentBuilder builder = createConditionContent(script, "painless", scriptType); XContentBuilder builder = createConditionContent(script, "mockscript", scriptType);
XContentParser parser = createParser(builder); XContentParser parser = createParser(builder);
parser.nextToken(); parser.nextToken();
@ -196,7 +195,7 @@ public class ScriptConditionTests extends ESTestCase {
public void testScriptConditionThrowException() throws Exception { public void testScriptConditionThrowException() throws Exception {
ScriptCondition condition = new ScriptCondition( ScriptCondition condition = new ScriptCondition(
new Script("null.foo"), scriptService); mockScript("null.foo"), scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
ScriptException exception = expectThrows(ScriptException.class, () -> condition.execute(ctx)); ScriptException exception = expectThrows(ScriptException.class, () -> condition.execute(ctx));
@ -204,7 +203,7 @@ public class ScriptConditionTests extends ESTestCase {
} }
public void testScriptConditionReturnObjectThrowsException() throws Exception { public void testScriptConditionReturnObjectThrowsException() throws Exception {
ScriptCondition condition = new ScriptCondition(new Script("return new Object()"), scriptService); ScriptCondition condition = new ScriptCondition(mockScript("return new Object()"), scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
Exception exception = expectThrows(IllegalStateException.class, () -> condition.execute(ctx)); Exception exception = expectThrows(IllegalStateException.class, () -> condition.execute(ctx));
@ -213,7 +212,7 @@ public class ScriptConditionTests extends ESTestCase {
} }
public void testScriptConditionAccessCtx() throws Exception { public void testScriptConditionAccessCtx() throws Exception {
ScriptCondition condition = new ScriptCondition(new Script("ctx.trigger.scheduled_time.getMillis() < new Date().time"), ScriptCondition condition = new ScriptCondition(mockScript("ctx.trigger.scheduled_time.getMillis() < new Date().time"),
scriptService); scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new DateTime(DateTimeZone.UTC), new Payload.XContent(response)); WatchExecutionContext ctx = mockExecutionContext("_name", new DateTime(DateTimeZone.UTC), new Payload.XContent(response));

View File

@ -14,7 +14,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.script.Script;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.common.http.HttpRequestTemplate; import org.elasticsearch.xpack.common.http.HttpRequestTemplate;
import org.elasticsearch.xpack.common.http.auth.basic.BasicAuth; import org.elasticsearch.xpack.common.http.auth.basic.BasicAuth;
@ -153,7 +152,7 @@ public class ChainInputTests extends ESTestCase {
watchBuilder() watchBuilder()
.trigger(schedule(interval("5s"))) .trigger(schedule(interval("5s")))
.input(chainedInputBuilder) .input(chainedInputBuilder)
.condition(new ScriptCondition(new Script("ctx.payload.hits.total == 1"))) .condition(new ScriptCondition(mockScript("ctx.payload.hits.total == 1")))
.addAction("_id", loggingAction("watch [{{ctx.watch_id}}] matched")) .addAction("_id", loggingAction("watch [{{ctx.watch_id}}] matched"))
.toXContent(builder, ToXContent.EMPTY_PARAMS); .toXContent(builder, ToXContent.EMPTY_PARAMS);

View File

@ -13,6 +13,7 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.node.MockNode; import org.elasticsearch.node.MockNode;
import org.elasticsearch.node.Node; import org.elasticsearch.node.Node;
import org.elasticsearch.script.Script; import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.common.http.HttpRequestTemplate; import org.elasticsearch.xpack.common.http.HttpRequestTemplate;
@ -25,7 +26,6 @@ import org.elasticsearch.xpack.watcher.trigger.ScheduleTriggerEngineMock;
import org.elasticsearch.xpack.watcher.trigger.TriggerEngine; import org.elasticsearch.xpack.watcher.trigger.TriggerEngine;
import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleRegistry; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleRegistry;
import javax.security.auth.DestroyFailedException;
import java.io.IOException; import java.io.IOException;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.security.KeyStoreException; import java.security.KeyStoreException;
@ -35,6 +35,9 @@ import java.security.cert.CertificateException;
import java.time.Clock; import java.time.Clock;
import java.util.Arrays; import java.util.Arrays;
import javax.security.auth.DestroyFailedException;
import static java.util.Collections.emptyMap;
import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.indexAction; import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.indexAction;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.httpInput; import static org.elasticsearch.xpack.watcher.input.InputBuilders.httpInput;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.searchInput; import static org.elasticsearch.xpack.watcher.input.InputBuilders.searchInput;
@ -88,7 +91,11 @@ public class WatcherExecutorServiceBenchmark {
PutWatchRequest putAlertRequest = new PutWatchRequest(name, new WatchSourceBuilder() PutWatchRequest putAlertRequest = new PutWatchRequest(name, new WatchSourceBuilder()
.trigger(schedule(interval("5s"))) .trigger(schedule(interval("5s")))
.input(searchInput(templateRequest(new SearchSourceBuilder(), "test"))) .input(searchInput(templateRequest(new SearchSourceBuilder(), "test")))
.condition(new ScriptCondition(new Script("ctx.payload.hits.total > 0")))); .condition(new ScriptCondition(new Script(
ScriptType.INLINE,
Script.DEFAULT_SCRIPT_LANG,
"ctx.payload.hits.total > 0",
emptyMap()))));
putAlertRequest.setId(name); putAlertRequest.setId(name);
watcherClient.putWatch(putAlertRequest).actionGet(); watcherClient.putWatch(putAlertRequest).actionGet();
} }
@ -130,7 +137,7 @@ public class WatcherExecutorServiceBenchmark {
.trigger(schedule(interval("5s"))) .trigger(schedule(interval("5s")))
.input(searchInput(templateRequest(new SearchSourceBuilder(), "test")) .input(searchInput(templateRequest(new SearchSourceBuilder(), "test"))
.extractKeys("hits.total")) .extractKeys("hits.total"))
.condition(new ScriptCondition(new Script("1 == 1"))) .condition(new ScriptCondition(new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, "1 == 1", emptyMap())))
.addAction("_id", indexAction("index", "type"))); .addAction("_id", indexAction("index", "type")));
putAlertRequest.setId(name); putAlertRequest.setId(name);
watcherClient.putWatch(putAlertRequest).actionGet(); watcherClient.putWatch(putAlertRequest).actionGet();
@ -174,7 +181,11 @@ public class WatcherExecutorServiceBenchmark {
PutWatchRequest putAlertRequest = new PutWatchRequest(name, new WatchSourceBuilder() PutWatchRequest putAlertRequest = new PutWatchRequest(name, new WatchSourceBuilder()
.trigger(schedule(interval("5s"))) .trigger(schedule(interval("5s")))
.input(httpInput(HttpRequestTemplate.builder("localhost", 9200))) .input(httpInput(HttpRequestTemplate.builder("localhost", 9200)))
.condition(new ScriptCondition(new Script("ctx.payload.tagline == \"You Know, for Search\"")))); .condition(new ScriptCondition(new Script(
ScriptType.INLINE,
Script.DEFAULT_SCRIPT_LANG,
"ctx.payload.tagline == \"You Know, for Search\"",
emptyMap()))));
putAlertRequest.setId(name); putAlertRequest.setId(name);
watcherClient.putWatch(putAlertRequest).actionGet(); watcherClient.putWatch(putAlertRequest).actionGet();
} }

View File

@ -21,11 +21,13 @@ import org.elasticsearch.monitor.jvm.JvmInfo;
import org.elasticsearch.node.MockNode; import org.elasticsearch.node.MockNode;
import org.elasticsearch.node.Node; import org.elasticsearch.node.Node;
import org.elasticsearch.script.Script; import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.percentiles.Percentiles; import org.elasticsearch.search.aggregations.metrics.percentiles.Percentiles;
import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.threadpool.ThreadPoolStats; import org.elasticsearch.threadpool.ThreadPoolStats;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.watcher.WatcherState; import org.elasticsearch.xpack.watcher.WatcherState;
import org.elasticsearch.xpack.watcher.actions.ActionBuilders; import org.elasticsearch.xpack.watcher.actions.ActionBuilders;
import org.elasticsearch.xpack.watcher.actions.logging.LoggingLevel; import org.elasticsearch.xpack.watcher.actions.logging.LoggingLevel;
@ -34,7 +36,6 @@ import org.elasticsearch.xpack.watcher.client.WatcherClient;
import org.elasticsearch.xpack.watcher.condition.ScriptCondition; import org.elasticsearch.xpack.watcher.condition.ScriptCondition;
import org.elasticsearch.xpack.watcher.history.HistoryStore; import org.elasticsearch.xpack.watcher.history.HistoryStore;
import org.elasticsearch.xpack.watcher.watch.Watch; import org.elasticsearch.xpack.watcher.watch.Watch;
import org.elasticsearch.xpack.XPackPlugin;
import java.io.IOException; import java.io.IOException;
import java.time.Clock; import java.time.Clock;
@ -44,6 +45,7 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import static java.util.Collections.emptyMap;
import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram;
import static org.elasticsearch.search.aggregations.AggregationBuilders.percentiles; import static org.elasticsearch.search.aggregations.AggregationBuilders.percentiles;
import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms;
@ -110,7 +112,11 @@ public class WatcherScheduleEngineBenchmark {
.setSource(new WatchSourceBuilder() .setSource(new WatchSourceBuilder()
.trigger(schedule(interval(interval + "s"))) .trigger(schedule(interval(interval + "s")))
.input(searchInput(templateRequest(new SearchSourceBuilder(), "test"))) .input(searchInput(templateRequest(new SearchSourceBuilder(), "test")))
.condition(new ScriptCondition(new Script("ctx.payload.hits.total > 0"))) .condition(new ScriptCondition(new Script(
ScriptType.INLINE,
Script.DEFAULT_SCRIPT_LANG,
"ctx.payload.hits.total > 0",
emptyMap())))
.addAction("logging", ActionBuilders.loggingAction("test").setLevel(LoggingLevel.TRACE)) .addAction("logging", ActionBuilders.loggingAction("test").setLevel(LoggingLevel.TRACE))
.buildAsBytes(XContentType.JSON), XContentType.JSON .buildAsBytes(XContentType.JSON), XContentType.JSON
).get(); ).get();
@ -182,8 +188,11 @@ public class WatcherScheduleEngineBenchmark {
} }
} }
client.admin().indices().prepareRefresh(HistoryStore.INDEX_PREFIX_WITH_TEMPLATE + "*").get(); client.admin().indices().prepareRefresh(HistoryStore.INDEX_PREFIX_WITH_TEMPLATE + "*").get();
Script script = new Script("doc['trigger_event.schedule.triggered_time'].value - doc['trigger_event.schedule" + Script script = new Script(
".scheduled_time'].value"); ScriptType.INLINE,
Script.DEFAULT_SCRIPT_LANG,
"doc['trigger_event.schedule.triggered_time'].value - doc['trigger_event.schedule.scheduled_time'].value",
emptyMap());
SearchResponse searchResponse = client.prepareSearch(HistoryStore.INDEX_PREFIX_WITH_TEMPLATE + "*") SearchResponse searchResponse = client.prepareSearch(HistoryStore.INDEX_PREFIX_WITH_TEMPLATE + "*")
.setQuery(QueryBuilders.rangeQuery("trigger_event.schedule.scheduled_time").gte(startTime).lte(endTime)) .setQuery(QueryBuilders.rangeQuery("trigger_event.schedule.scheduled_time").gte(startTime).lte(endTime))
.addAggregation(terms("state").field("state")) .addAggregation(terms("state").field("state"))

View File

@ -9,7 +9,6 @@ import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin; import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.xpack.watcher.client.WatcherClient; import org.elasticsearch.xpack.watcher.client.WatcherClient;
import org.elasticsearch.xpack.watcher.condition.ScriptCondition; import org.elasticsearch.xpack.watcher.condition.ScriptCondition;
import org.elasticsearch.xpack.watcher.support.xcontent.ObjectPath; import org.elasticsearch.xpack.watcher.support.xcontent.ObjectPath;
@ -107,11 +106,6 @@ public class ExecutionVarsIntegrationTests extends AbstractWatcherIntegrationTes
return scripts; return scripts;
} }
@Override
public String pluginScriptLang() {
return WATCHER_LANG;
}
} }
public void testVars() throws Exception { public void testVars() throws Exception {
@ -121,15 +115,16 @@ public class ExecutionVarsIntegrationTests extends AbstractWatcherIntegrationTes
.trigger(schedule(cron("0/1 * * * * ?"))) .trigger(schedule(cron("0/1 * * * * ?")))
.input(simpleInput("value", 5)) .input(simpleInput("value", 5))
.condition(new ScriptCondition( .condition(new ScriptCondition(
new Script("ctx.vars.condition_value = ctx.payload.value + 5; return ctx.vars.condition_value > 5;"))) mockScript("ctx.vars.condition_value = ctx.payload.value + 5; return ctx.vars.condition_value > 5;")))
.transform(scriptTransform("ctx.vars.watch_transform_value = ctx.vars.condition_value + 5; return ctx.payload;")) .transform(
scriptTransform(mockScript("ctx.vars.watch_transform_value = ctx.vars.condition_value + 5; return ctx.payload;")))
.addAction( .addAction(
"a1", "a1",
scriptTransform("transform a1"), scriptTransform(mockScript("transform a1")),
loggingAction("_text")) loggingAction("_text"))
.addAction( .addAction(
"a2", "a2",
scriptTransform("transform a2"), scriptTransform(mockScript("transform a2")),
loggingAction("_text"))) loggingAction("_text")))
.get(); .get();
@ -184,15 +179,16 @@ public class ExecutionVarsIntegrationTests extends AbstractWatcherIntegrationTes
.trigger(schedule(cron("0/1 * * * * ? 2020"))) .trigger(schedule(cron("0/1 * * * * ? 2020")))
.input(simpleInput("value", 5)) .input(simpleInput("value", 5))
.condition(new ScriptCondition( .condition(new ScriptCondition(
new Script("ctx.vars.condition_value = ctx.payload.value + 5; return ctx.vars.condition_value > 5;"))) mockScript("ctx.vars.condition_value = ctx.payload.value + 5; return ctx.vars.condition_value > 5;")))
.transform(scriptTransform("ctx.vars.watch_transform_value = ctx.vars.condition_value + 5; return ctx.payload;")) .transform(
scriptTransform(mockScript("ctx.vars.watch_transform_value = ctx.vars.condition_value + 5; return ctx.payload;")))
.addAction( .addAction(
"a1", "a1",
scriptTransform("transform a1"), scriptTransform(mockScript("transform a1")),
loggingAction("_text")) loggingAction("_text"))
.addAction( .addAction(
"a2", "a2",
scriptTransform("transform a2"), scriptTransform(mockScript("transform a2")),
loggingAction("_text"))) loggingAction("_text")))
.get(); .get();

View File

@ -78,7 +78,7 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
// When using the MockScriptPlugin we can map File scripts to inline scripts: // When using the MockScriptPlugin we can map File scripts to inline scripts:
// the name of the file script is used in test method while the source of the file script // the name of the file script is used in test method while the source of the file script
// must match a predefined script from CustomScriptPlugin.pluginScripts() method // must match a predefined script from CustomScriptPlugin.pluginScripts() method
Files.write(scripts.resolve("my-script.painless"), "['key3' : ctx.payload.key1 + ctx.payload.key2]".getBytes("UTF-8")); Files.write(scripts.resolve("my-script.mockscript"), "['key3' : ctx.payload.key1 + ctx.payload.key2]".getBytes("UTF-8"));
} catch (IOException ex) { } catch (IOException ex) {
throw new RuntimeException("Failed to create scripts", ex); throw new RuntimeException("Failed to create scripts", ex);
} }
@ -111,29 +111,24 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
return scripts; return scripts;
} }
@Override
public String pluginScriptLang() {
return WATCHER_LANG;
}
} }
public void testScriptTransform() throws Exception { public void testScriptTransform() throws Exception {
final Script script; final Script script;
if (randomBoolean()) { if (randomBoolean()) {
logger.info("testing script transform with an inline script"); logger.info("testing script transform with an inline script");
script = new Script("['key3' : ctx.payload.key1 + ctx.payload.key2]"); script = mockScript("['key3' : ctx.payload.key1 + ctx.payload.key2]");
} else if (randomBoolean()) { } else if (randomBoolean()) {
logger.info("testing script transform with an indexed script"); logger.info("testing script transform with an indexed script");
assertAcked(client().admin().cluster().preparePutStoredScript() assertAcked(client().admin().cluster().preparePutStoredScript()
.setId("my-script") .setId("my-script")
.setLang("painless") .setLang("mockscript")
.setContent(new BytesArray("{\"script\" : \"['key3' : ctx.payload.key1 + ctx.payload.key2]\"}"), XContentType.JSON) .setContent(new BytesArray("{\"script\" : \"['key3' : ctx.payload.key1 + ctx.payload.key2]\"}"), XContentType.JSON)
.get()); .get());
script = new Script(ScriptType.STORED, "painless", "my-script", Collections.emptyMap()); script = new Script(ScriptType.STORED, "mockscript", "my-script", Collections.emptyMap());
} else { } else {
logger.info("testing script transform with a file script"); logger.info("testing script transform with a file script");
script = new Script(ScriptType.FILE, "painless", "my-script", Collections.emptyMap()); script = new Script(ScriptType.FILE, "mockscript", "my-script", Collections.emptyMap());
} }
// put a watch that has watch level transform: // put a watch that has watch level transform:
@ -227,8 +222,8 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
} }
public void testChainTransform() throws Exception { public void testChainTransform() throws Exception {
Script script1 = new Script("['key3' : ctx.payload.key1 + ctx.payload.key2]"); Script script1 = mockScript("['key3' : ctx.payload.key1 + ctx.payload.key2]");
Script script2 = new Script("['key4' : ctx.payload.key3 + 10]"); Script script2 = mockScript("['key4' : ctx.payload.key3 + 10]");
// put a watch that has watch level transform: // put a watch that has watch level transform:
PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id1") PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id1")

View File

@ -28,6 +28,7 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singleton; import static java.util.Collections.singleton;
import static java.util.Collections.singletonMap; import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
@ -161,7 +162,7 @@ public class ScriptTransformTests extends ESTestCase {
XContentParser parser = createParser(builder); XContentParser parser = createParser(builder);
parser.nextToken(); parser.nextToken();
ExecutableScriptTransform transform = new ScriptTransformFactory(Settings.EMPTY, service).parseExecutable("_id", parser); ExecutableScriptTransform transform = new ScriptTransformFactory(Settings.EMPTY, service).parseExecutable("_id", parser);
assertThat(transform.transform().getScript(), equalTo(new Script("_script"))); assertEquals(new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, "_script", emptyMap()), transform.transform().getScript());
} }
public void testScriptConditionParserBadScript() throws Exception { public void testScriptConditionParserBadScript() throws Exception {

View File

@ -433,7 +433,7 @@ public class WatchTests extends ESTestCase {
DateTimeZone timeZone = randomBoolean() ? DateTimeZone.UTC : null; DateTimeZone timeZone = randomBoolean() ? DateTimeZone.UTC : null;
switch (type) { switch (type) {
case ScriptTransform.TYPE: case ScriptTransform.TYPE:
return new ExecutableScriptTransform(new ScriptTransform(new Script("_script")), logger, scriptService); return new ExecutableScriptTransform(new ScriptTransform(mockScript("_script")), logger, scriptService);
case SearchTransform.TYPE: case SearchTransform.TYPE:
SearchTransform transform = new SearchTransform( SearchTransform transform = new SearchTransform(
templateRequest(searchSource()), timeout, timeZone); templateRequest(searchSource()), timeout, timeZone);
@ -441,14 +441,14 @@ public class WatchTests extends ESTestCase {
default: // chain default: // chain
SearchTransform searchTransform = new SearchTransform( SearchTransform searchTransform = new SearchTransform(
templateRequest(searchSource()), timeout, timeZone); templateRequest(searchSource()), timeout, timeZone);
ScriptTransform scriptTransform = new ScriptTransform(new Script("_script")); ScriptTransform scriptTransform = new ScriptTransform(mockScript("_script"));
ChainTransform chainTransform = new ChainTransform(Arrays.asList(searchTransform, scriptTransform)); ChainTransform chainTransform = new ChainTransform(Arrays.asList(searchTransform, scriptTransform));
return new ExecutableChainTransform(chainTransform, logger, Arrays.<ExecutableTransform>asList( return new ExecutableChainTransform(chainTransform, logger, Arrays.<ExecutableTransform>asList(
new ExecutableSearchTransform(new SearchTransform( new ExecutableSearchTransform(new SearchTransform(
templateRequest(searchSource()), timeout, timeZone), templateRequest(searchSource()), timeout, timeZone),
logger, client, searchTemplateService, null), logger, client, searchTemplateService, null),
new ExecutableScriptTransform(new ScriptTransform(new Script("_script")), new ExecutableScriptTransform(new ScriptTransform(mockScript("_script")),
logger, scriptService))); logger, scriptService)));
} }
} }