Merge pull request elastic/elasticsearch#2845 from rjernst/remove_script_proxy

Remove script service proxy

Original commit: elastic/x-pack-elasticsearch@c4a1dfda1a
This commit is contained in:
Ryan Ernst 2016-07-18 13:41:41 -07:00 committed by GitHub
commit 2de185ac72
35 changed files with 254 additions and 319 deletions

View File

@ -14,7 +14,7 @@ import org.elasticsearch.xpack.watcher.condition.script.ScriptCondition;
import org.elasticsearch.xpack.watcher.execution.ManualExecutionContext;
import org.elasticsearch.xpack.watcher.execution.ManualExecutionTests.ExecutionRunner;
import org.elasticsearch.xpack.watcher.history.WatchRecord;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.transport.actions.delete.DeleteWatchResponse;
import org.elasticsearch.xpack.watcher.transport.actions.get.GetWatchRequest;
@ -65,7 +65,7 @@ public class GroovyManualExecutionIT extends AbstractWatcherIntegrationTestCase
WatchSourceBuilder watchBuilder = watchBuilder()
.trigger(schedule(cron("0 0 0 1 * ? 2099")))
.input(simpleInput("foo", "bar"))
.condition(new ScriptCondition((new Script.Builder.Inline("sleep 100; return true")).build()))
.condition(new ScriptCondition((new WatcherScript.Builder.Inline("sleep 100; return true")).build()))
.addAction("log", loggingAction("foobar"));
Watch watch = watchParser().parse("_id", false, watchBuilder.buildAsBytes(XContentType.JSON));
@ -80,7 +80,7 @@ public class GroovyManualExecutionIT extends AbstractWatcherIntegrationTestCase
WatchSourceBuilder watchBuilder = watchBuilder()
.trigger(schedule(cron("0 0 0 1 * ? 2099")))
.input(simpleInput("foo", "bar"))
.condition(new ScriptCondition((new Script.Builder.Inline("sleep 10000; return true")).build()))
.condition(new ScriptCondition((new WatcherScript.Builder.Inline("sleep 10000; return true")).build()))
.defaultThrottlePeriod(new TimeValue(1, TimeUnit.HOURS))
.addAction("log", loggingAction("foobar"));

View File

@ -8,6 +8,7 @@ package org.elasticsearch.messy.tests;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.groovy.GroovyPlugin;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
@ -16,8 +17,7 @@ import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.watcher.condition.script.ExecutableScriptCondition;
import org.elasticsearch.xpack.watcher.condition.script.ScriptCondition;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.watch.Payload;
import org.junit.AfterClass;
@ -28,7 +28,7 @@ import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.messy.tests.MessyTestUtils.getScriptServiceProxy;
import static org.elasticsearch.messy.tests.MessyTestUtils.createScriptService;
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.mockExecutionContext;
public class GroovyScriptConditionIT extends AbstractWatcherIntegrationTestCase {
@ -46,7 +46,7 @@ public class GroovyScriptConditionIT extends AbstractWatcherIntegrationTestCase
}
private static ThreadPool THREAD_POOL;
private ScriptServiceProxy scriptService;
private ScriptService scriptService;
@BeforeClass
public static void startThreadPool() {
@ -55,7 +55,7 @@ public class GroovyScriptConditionIT extends AbstractWatcherIntegrationTestCase
@Before
public void init() throws Exception {
scriptService = getScriptServiceProxy(THREAD_POOL);
scriptService = createScriptService(THREAD_POOL);
}
@AfterClass
@ -83,7 +83,7 @@ public class GroovyScriptConditionIT extends AbstractWatcherIntegrationTestCase
SearchResponse unmetResponse = builder.get();
ExecutableScriptCondition condition =
new ExecutableScriptCondition(new ScriptCondition(Script.inline(
new ExecutableScriptCondition(new ScriptCondition(WatcherScript.inline(
String.join(
" ",
"if (ctx.payload.hits.total < 1) return false;",

View File

@ -6,9 +6,6 @@
package org.elasticsearch.messy.tests;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
@ -19,9 +16,8 @@ import org.elasticsearch.script.ScriptSettings;
import org.elasticsearch.script.groovy.GroovyScriptEngineService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.junit.Ignore;
import org.mockito.Mockito;
import java.util.Arrays;
import java.util.Collections;
@ -29,7 +25,7 @@ import java.util.Collections;
@Ignore // not a test.
@SuppressForbidden(reason = "gradle is broken and tries to run me as a test")
public final class MessyTestUtils {
public static ScriptServiceProxy getScriptServiceProxy(ThreadPool tp) throws Exception {
public static ScriptService createScriptService(ThreadPool tp) throws Exception {
Settings settings = Settings.builder()
.put("script.inline", "true")
.put("script.indexed", "true")
@ -37,10 +33,10 @@ public final class MessyTestUtils {
.build();
GroovyScriptEngineService groovyScriptEngineService = new GroovyScriptEngineService(settings);
ScriptEngineRegistry scriptEngineRegistry = new ScriptEngineRegistry(Collections.singleton(groovyScriptEngineService));
ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(Arrays.asList(ScriptServiceProxy.INSTANCE));
ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(Arrays.asList(WatcherScript.CTX_PLUGIN));
ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, scriptContextRegistry);
return ScriptServiceProxy.of(new ScriptService(settings, new Environment(settings),
new ResourceWatcherService(settings, tp), scriptEngineRegistry, scriptContextRegistry, scriptSettings));
return new ScriptService(settings, new Environment(settings), new ResourceWatcherService(settings, tp),
scriptEngineRegistry, scriptContextRegistry, scriptSettings);
}
}

View File

@ -10,6 +10,7 @@ import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.Index;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.groovy.GroovyPlugin;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.aggregations.AggregationBuilders;
@ -20,11 +21,10 @@ import org.elasticsearch.search.internal.InternalSearchHits;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.condition.script.ExecutableScriptCondition;
import org.elasticsearch.xpack.watcher.condition.script.ScriptCondition;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.watch.Payload;
import org.junit.After;
@ -40,7 +40,7 @@ import static org.mockito.Mockito.when;
*/
public class ScriptConditionSearchIT extends AbstractWatcherIntegrationTestCase {
private ThreadPool tp = null;
private ScriptServiceProxy scriptService;
private ScriptService scriptService;
@Override
protected List<Class<? extends Plugin>> pluginTypes() {
@ -52,7 +52,7 @@ public class ScriptConditionSearchIT extends AbstractWatcherIntegrationTestCase
@Before
public void init() throws Exception {
tp = new TestThreadPool(ThreadPool.Names.SAME);
scriptService = MessyTestUtils.getScriptServiceProxy(tp);
scriptService = MessyTestUtils.createScriptService(tp);
}
@After
@ -73,7 +73,7 @@ public class ScriptConditionSearchIT extends AbstractWatcherIntegrationTestCase
.get();
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(Script.inline("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5").build()),
new ScriptCondition(WatcherScript.inline("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5").build()),
logger, scriptService);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
@ -92,7 +92,7 @@ public class ScriptConditionSearchIT extends AbstractWatcherIntegrationTestCase
public void testExecuteAccessHits() throws Exception {
ExecutableScriptCondition condition = new ExecutableScriptCondition(new ScriptCondition(
Script.inline("ctx.payload.hits?.hits[0]?._score == 1.0").build()), logger, scriptService);
WatcherScript.inline("ctx.payload.hits?.hits[0]?._score == 1.0").build()), logger, scriptService);
InternalSearchHit hit = new InternalSearchHit(0, "1", new Text("type"), null);
hit.score(1f);
hit.shard(new SearchShardTarget("a", new Index("a", "testUUID"), 0));

View File

@ -15,17 +15,17 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.GeneralScriptException;
import org.elasticsearch.script.ScriptException;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.condition.script.ExecutableScriptCondition;
import org.elasticsearch.xpack.watcher.condition.script.ScriptCondition;
import org.elasticsearch.xpack.watcher.condition.script.ScriptConditionFactory;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.watch.Payload;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
@ -36,7 +36,7 @@ import java.io.IOException;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.messy.tests.MessyTestUtils.getScriptServiceProxy;
import static org.elasticsearch.messy.tests.MessyTestUtils.createScriptService;
import static org.elasticsearch.xpack.watcher.support.Exceptions.illegalArgument;
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.mockExecutionContext;
import static org.hamcrest.Matchers.containsString;
@ -57,18 +57,18 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testExecute() throws Exception {
ScriptServiceProxy scriptService = getScriptServiceProxy(tp);
ScriptService scriptService = createScriptService(tp);
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(Script.inline("ctx.payload.hits.total > 1").build()), logger, scriptService);
new ScriptCondition(WatcherScript.inline("ctx.payload.hits.total > 1").build()), logger, scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
assertFalse(condition.execute(ctx).met());
}
public void testExecuteMergedParams() throws Exception {
ScriptServiceProxy scriptService = getScriptServiceProxy(tp);
Script script = Script.inline("ctx.payload.hits.total > threshold")
.lang(Script.DEFAULT_LANG).params(singletonMap("threshold", 1)).build();
ScriptService scriptService = createScriptService(tp);
WatcherScript script = WatcherScript.inline("ctx.payload.hits.total > threshold")
.lang(WatcherScript.DEFAULT_LANG).params(singletonMap("threshold", 1)).build();
ExecutableScriptCondition executable = new ExecutableScriptCondition(new ScriptCondition(script), logger, scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
@ -76,7 +76,7 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testParserValid() throws Exception {
ScriptConditionFactory factory = new ScriptConditionFactory(Settings.builder().build(), getScriptServiceProxy(tp));
ScriptConditionFactory factory = new ScriptConditionFactory(Settings.builder().build(), createScriptService(tp));
XContentBuilder builder = createConditionContent("ctx.payload.hits.total > 1", null, ScriptType.INLINE);
@ -103,7 +103,7 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testParserInvalid() throws Exception {
ScriptConditionFactory factory = new ScriptConditionFactory(Settings.builder().build(), getScriptServiceProxy(tp));
ScriptConditionFactory factory = new ScriptConditionFactory(Settings.builder().build(), createScriptService(tp));
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject().endObject();
XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes());
@ -118,7 +118,7 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testScriptConditionParserBadScript() throws Exception {
ScriptConditionFactory conditionParser = new ScriptConditionFactory(Settings.builder().build(), getScriptServiceProxy(tp));
ScriptConditionFactory conditionParser = new ScriptConditionFactory(Settings.builder().build(), createScriptService(tp));
ScriptType scriptType = randomFrom(ScriptType.values());
String script;
switch (scriptType) {
@ -139,7 +139,7 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testScriptConditionParser_badLang() throws Exception {
ScriptConditionFactory conditionParser = new ScriptConditionFactory(Settings.builder().build(), getScriptServiceProxy(tp));
ScriptConditionFactory conditionParser = new ScriptConditionFactory(Settings.builder().build(), createScriptService(tp));
ScriptType scriptType = ScriptType.INLINE;
String script = "return true";
XContentBuilder builder = createConditionContent(script, "not_a_valid_lang", scriptType);
@ -152,9 +152,9 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testScriptConditionThrowException() throws Exception {
ScriptServiceProxy scriptService = getScriptServiceProxy(tp);
ScriptService scriptService = createScriptService(tp);
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(Script.inline("null.foo").build()), logger, scriptService);
new ScriptCondition(WatcherScript.inline("null.foo").build()), logger, scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
ScriptException exception = expectThrows(ScriptException.class, () -> condition.execute(ctx));
@ -162,9 +162,9 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testScriptConditionReturnObjectThrowsException() throws Exception {
ScriptServiceProxy scriptService = getScriptServiceProxy(tp);
ScriptService scriptService = createScriptService(tp);
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(Script.inline("return new Object()").build()), logger, scriptService);
new ScriptCondition(WatcherScript.inline("return new Object()").build()), logger, scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
Exception exception = expectThrows(GeneralScriptException.class, () -> condition.execute(ctx));
@ -173,9 +173,9 @@ public class ScriptConditionTests extends ESTestCase {
}
public void testScriptConditionAccessCtx() throws Exception {
ScriptServiceProxy scriptService = getScriptServiceProxy(tp);
ScriptService scriptService = createScriptService(tp);
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(Script.inline("ctx.trigger.scheduled_time.getMillis() < new Date().time ").build()),
new ScriptCondition(WatcherScript.inline("ctx.trigger.scheduled_time.getMillis() < new Date().time ").build()),
logger, scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new DateTime(DateTimeZone.UTC), new Payload.XContent(response));

View File

@ -13,7 +13,7 @@ import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.groovy.GroovyPlugin;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.test.WatcherTestUtils;
import org.elasticsearch.xpack.watcher.transport.actions.put.PutWatchResponse;
@ -72,10 +72,10 @@ public class TransformIT extends AbstractWatcherIntegrationTestCase {
}
public void testScriptTransform() throws Exception {
final Script script;
final WatcherScript script;
if (randomBoolean()) {
logger.info("testing script transform with an inline script");
script = Script.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build();
script = WatcherScript.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build();
} else if (randomBoolean()) {
logger.info("testing script transform with an indexed script");
client().admin().cluster().preparePutStoredScript()
@ -83,10 +83,10 @@ public class TransformIT extends AbstractWatcherIntegrationTestCase {
.setScriptLang("groovy")
.setSource(new BytesArray("{\"script\" : \"return [key3 : ctx.payload.key1 + ctx.payload.key2]\"}"))
.get();
script = Script.indexed("_id").lang("groovy").build();
script = WatcherScript.indexed("_id").lang("groovy").build();
} else {
logger.info("testing script transform with a file script");
script = Script.file("my-script").lang("groovy").build();
script = WatcherScript.file("my-script").lang("groovy").build();
}
// put a watch that has watch level transform:
@ -182,8 +182,8 @@ public class TransformIT extends AbstractWatcherIntegrationTestCase {
}
public void testChainTransform() throws Exception {
final Script script1 = Script.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build();
final Script script2 = Script.inline("return [key4 : ctx.payload.key3 + 10]").lang("groovy").build();
final WatcherScript script1 = WatcherScript.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build();
final WatcherScript script2 = WatcherScript.inline("return [key4 : ctx.payload.key3 + 10]").lang("groovy").build();
// put a watch that has watch level transform:
PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id1")
.setSource(watchBuilder()

View File

@ -28,7 +28,6 @@ import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.Suggesters;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.common.text.TextTemplate;
import org.elasticsearch.xpack.watcher.actions.ActionWrapper;
import org.elasticsearch.xpack.watcher.actions.ExecutableActions;
@ -41,7 +40,7 @@ import org.elasticsearch.xpack.watcher.input.search.SearchInput;
import org.elasticsearch.xpack.watcher.input.search.SearchInputFactory;
import org.elasticsearch.xpack.watcher.input.simple.ExecutableSimpleInput;
import org.elasticsearch.xpack.watcher.input.simple.SimpleInput;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.init.proxy.WatcherClientProxy;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService;
@ -190,7 +189,7 @@ public class SearchInputIT extends ESIntegTestCase {
Map<String, Object> params = new HashMap<>();
params.put("seconds_param", "30s");
Script template = Script.inline(TEMPLATE_QUERY).lang("mustache").params(params).build();
WatcherScript template = WatcherScript.inline(TEMPLATE_QUERY).lang("mustache").params(params).build();
SearchRequest request = client().prepareSearch()
.setSearchType(ExecutableSearchInput.DEFAULT_SEARCH_TYPE)
@ -224,7 +223,7 @@ public class SearchInputIT extends ESIntegTestCase {
Map<String, Object> params = new HashMap<>();
params.put("seconds_param", "30s");
Script template = Script.indexed("test-template").lang("mustache").params(params).build();
WatcherScript template = WatcherScript.indexed("test-template").lang("mustache").params(params).build();
jsonBuilder().value(TextTemplate.indexed("test-template").params(params).build()).bytes();
SearchRequest request = client().prepareSearch().setSearchType(ExecutableSearchInput.DEFAULT_SEARCH_TYPE)
@ -252,7 +251,7 @@ public class SearchInputIT extends ESIntegTestCase {
Map<String, Object> params = new HashMap<>();
params.put("seconds_param", "30s");
Script template = Script.file("test_disk_template").lang("mustache").params(params).build();
WatcherScript template = WatcherScript.file("test_disk_template").lang("mustache").params(params).build();
SearchRequest request = client().prepareSearch().setSearchType(ExecutableSearchInput.DEFAULT_SEARCH_TYPE)
.setIndices("test-search-index").request();
@ -347,7 +346,8 @@ public class SearchInputIT extends ESIntegTestCase {
timeValueSeconds(5));
}
private SearchInput.Result executeSearchInput(SearchRequest request, Script template, WatchExecutionContext ctx) throws IOException {
private SearchInput.Result executeSearchInput(SearchRequest request, WatcherScript template,
WatchExecutionContext ctx) throws IOException {
createIndex("test-search-index");
ensureGreen("test-search-index");
SearchInput.Builder siBuilder = SearchInput.builder(new WatcherSearchTemplateRequest(request, template));
@ -362,15 +362,15 @@ public class SearchInputIT extends ESIntegTestCase {
protected WatcherSearchTemplateService watcherSearchTemplateService() {
String master = internalCluster().getMasterName();
return new WatcherSearchTemplateService(internalCluster().clusterService(master).getSettings(),
ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class, master)),
internalCluster().getInstance(ScriptService.class, master),
internalCluster().getInstance(IndicesQueriesRegistry.class, master),
internalCluster().getInstance(AggregatorParsers.class, master),
internalCluster().getInstance(Suggesters.class, master)
);
}
protected ScriptServiceProxy scriptService() {
return ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class));
protected ScriptService scriptService() {
return internalCluster().getInstance(ScriptService.class);
}
private XContentSource toXContentSource(SearchInput.Result result) throws IOException {
@ -387,7 +387,7 @@ public class SearchInputIT extends ESIntegTestCase {
@Override
public ScriptContext.Plugin getCustomScriptContexts() {
return ScriptServiceProxy.INSTANCE;
return WatcherScript.CTX_PLUGIN;
}
}
}

View File

@ -32,7 +32,6 @@ import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.Suggesters;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.common.text.TextTemplate;
import org.elasticsearch.xpack.watcher.actions.ExecutableActions;
import org.elasticsearch.xpack.watcher.condition.always.ExecutableAlwaysCondition;
@ -40,7 +39,7 @@ import org.elasticsearch.xpack.watcher.execution.TriggeredExecutionContext;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.input.simple.ExecutableSimpleInput;
import org.elasticsearch.xpack.watcher.input.simple.SimpleInput;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.init.proxy.WatcherClientProxy;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService;
@ -348,7 +347,7 @@ public class SearchTransformIT extends ESIntegTestCase {
}
if (templateName != null) {
assertThat(executable.transform().getRequest().getTemplate(),
equalTo(Script.file("template1").build()));
equalTo(WatcherScript.file("template1").build()));
}
SearchSourceBuilder source = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
assertThat(executable.transform().getRequest().getRequest().source(), equalTo(source));
@ -381,7 +380,7 @@ public class SearchTransformIT extends ESIntegTestCase {
Map<String, Object> params = new HashMap<>();
params.put("seconds_param", "30s");
Script template = Script.inline(templateQuery).lang("mustache").params(params).build();
WatcherScript template = WatcherScript.inline(templateQuery).lang("mustache").params(params).build();
SearchRequest request = client().prepareSearch().setSearchType(ExecutableSearchTransform.DEFAULT_SEARCH_TYPE)
.setIndices("test-search-index").request();
@ -415,7 +414,7 @@ public class SearchTransformIT extends ESIntegTestCase {
Map<String, Object> params = new HashMap<>();
params.put("seconds_param", "30s");
Script template = Script.indexed("test-script").lang("mustache").params(params).build();
WatcherScript template = WatcherScript.indexed("test-script").lang("mustache").params(params).build();
SearchRequest request = client()
.prepareSearch()
@ -441,7 +440,7 @@ public class SearchTransformIT extends ESIntegTestCase {
Map<String, Object> params = new HashMap<>();
params.put("seconds_param", "30s");
Script template = Script.file("test_disk_template").lang("mustache").params(params).build();
WatcherScript template = WatcherScript.file("test_disk_template").lang("mustache").params(params).build();
SearchRequest request = client().prepareSearch().setSearchType(ExecutableSearchTransform.DEFAULT_SEARCH_TYPE)
.setIndices("test-search-index").request();
@ -504,7 +503,7 @@ public class SearchTransformIT extends ESIntegTestCase {
timeValueSeconds(5));
}
private SearchTransform.Result executeSearchTransform(SearchRequest request, Script template, WatchExecutionContext ctx)
private SearchTransform.Result executeSearchTransform(SearchRequest request, WatcherScript template, WatchExecutionContext ctx)
throws IOException {
createIndex("test-search-index");
ensureGreen("test-search-index");
@ -519,15 +518,15 @@ public class SearchTransformIT extends ESIntegTestCase {
protected WatcherSearchTemplateService watcherSearchTemplateService() {
String master = internalCluster().getMasterName();
return new WatcherSearchTemplateService(internalCluster().clusterService(master).getSettings(),
ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class, master)),
internalCluster().getInstance(ScriptService.class, master),
internalCluster().getInstance(IndicesQueriesRegistry.class, master),
internalCluster().getInstance(AggregatorParsers.class, master),
internalCluster().getInstance(Suggesters.class, master)
);
}
protected ScriptServiceProxy scriptService() {
return ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class));
protected ScriptService scriptService() {
return internalCluster().getInstance(ScriptService.class);
}
private static Map<String, Object> doc(String date, String value) {
@ -551,7 +550,7 @@ public class SearchTransformIT extends ESIntegTestCase {
@Override
public ScriptContext.Plugin getCustomScriptContexts() {
return ScriptServiceProxy.INSTANCE;
return WatcherScript.CTX_PLUGIN;
}
}
}

View File

@ -6,37 +6,31 @@
package org.elasticsearch.smoketest;
import com.fasterxml.jackson.core.io.JsonStringEncoder;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.env.Environment;
import org.elasticsearch.script.ScriptContextRegistry;
import org.elasticsearch.script.ScriptEngineRegistry;
import org.elasticsearch.script.ScriptEngineService;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptSettings;
import org.elasticsearch.script.mustache.MustacheScriptEngineService;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.common.text.DefaultTextTemplateEngine;
import org.elasticsearch.xpack.common.text.TextTemplate;
import org.elasticsearch.xpack.common.text.TextTemplateEngine;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.junit.Before;
import org.mockito.Mockito;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
@ -50,7 +44,7 @@ public class WatcherTemplateTests extends ESTestCase {
Settings setting = Settings.builder().put(ScriptService.SCRIPT_AUTO_RELOAD_ENABLED_SETTING, true).build();
Environment environment = Mockito.mock(Environment.class);
ResourceWatcherService resourceWatcherService = Mockito.mock(ResourceWatcherService.class);
ScriptContextRegistry registry = new ScriptContextRegistry(Collections.singletonList(ScriptServiceProxy.INSTANCE));
ScriptContextRegistry registry = new ScriptContextRegistry(Collections.singletonList(WatcherScript.CTX_PLUGIN));
ScriptEngineRegistry scriptEngineRegistry = new ScriptEngineRegistry(
Collections.singleton(new MustacheScriptEngineService(setting))
@ -58,7 +52,7 @@ public class WatcherTemplateTests extends ESTestCase {
ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, registry);
ScriptService scriptService = new ScriptService(setting, environment, resourceWatcherService, scriptEngineRegistry,
registry, scriptSettings);
engine = new DefaultTextTemplateEngine(Settings.EMPTY, ScriptServiceProxy.of(scriptService));
engine = new DefaultTextTemplateEngine(Settings.EMPTY, scriptService);
}
public void testEscaping() throws Exception {

View File

@ -36,7 +36,6 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexModule;
import org.elasticsearch.license.plugin.Licensing;
import org.elasticsearch.license.plugin.core.LicensesService;
import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.ScriptPlugin;
@ -49,7 +48,6 @@ import org.elasticsearch.xpack.action.TransportXPackInfoAction;
import org.elasticsearch.xpack.action.TransportXPackUsageAction;
import org.elasticsearch.xpack.action.XPackInfoAction;
import org.elasticsearch.xpack.action.XPackUsageAction;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.common.http.HttpClient;
import org.elasticsearch.xpack.common.http.HttpRequestTemplate;
import org.elasticsearch.xpack.common.http.auth.HttpAuthFactory;
@ -75,6 +73,7 @@ import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken;
import org.elasticsearch.xpack.support.clock.Clock;
import org.elasticsearch.xpack.support.clock.SystemClock;
import org.elasticsearch.xpack.watcher.Watcher;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
public class XPackPlugin extends Plugin implements ScriptPlugin, ActionPlugin {
@ -231,7 +230,7 @@ public class XPackPlugin extends Plugin implements ScriptPlugin, ActionPlugin {
@Override
public ScriptContext.Plugin getCustomScriptContexts() {
return ScriptServiceProxy.INSTANCE;
return WatcherScript.CTX_PLUGIN;
}
@Override

View File

@ -1,68 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.common;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.security.SecurityContext;
import org.elasticsearch.xpack.security.user.XPackUser;
import org.elasticsearch.xpack.watcher.support.Script;
import java.util.Map;
import static java.util.Collections.emptyMap;
/**
* Wraps {@link ScriptService} but ensure that all scripts are run or compiled as {@link XPackUser}.
*/
public class ScriptServiceProxy {
private final ScriptService service;
private final SecurityContext securityContext;
@Inject
public ScriptServiceProxy(ScriptService service, SecurityContext securityContext) {
this.service = service;
this.securityContext = securityContext;
}
public CompiledScript compile(Script script) {
return compile(new org.elasticsearch.script.Script(script.script(), script.type(), script.lang(), script.params()), emptyMap());
}
public CompiledScript compile(org.elasticsearch.script.Script script, Map<String, String> compileParams) {
return securityContext.executeAs(XPackUser.INSTANCE, () ->
service.compile(script, WatcherScriptContext.CTX, compileParams));
}
public ExecutableScript executable(CompiledScript compiledScript, Map<String, Object> vars) {
return securityContext.executeAs(XPackUser.INSTANCE, () ->
service.executable(compiledScript, vars));
}
public static final ScriptContext.Plugin INSTANCE = new ScriptContext.Plugin("xpack", "watch");
private static class WatcherScriptContext implements ScriptContext {
public static final ScriptContext CTX = new WatcherScriptContext();
@Override
public String getKey() {
return INSTANCE.getKey();
}
}
/**
* Factory helper method for testing.
*/
public static ScriptServiceProxy of(ScriptService service) {
return new ScriptServiceProxy(service, SecurityContext.Insecure.INSTANCE);
}
}

View File

@ -13,7 +13,8 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import java.util.Collections;
import java.util.HashMap;
@ -21,10 +22,10 @@ import java.util.Map;
public class DefaultTextTemplateEngine extends AbstractComponent implements TextTemplateEngine {
private final ScriptServiceProxy service;
private final ScriptService service;
@Inject
public DefaultTextTemplateEngine(Settings settings, ScriptServiceProxy service) {
public DefaultTextTemplateEngine(Settings settings, ScriptService service) {
super(settings);
this.service = service;
}
@ -39,7 +40,7 @@ public class DefaultTextTemplateEngine extends AbstractComponent implements Text
Map<String, String> compileParams = compileParams(contentType);
template = trimContentType(template);
CompiledScript compiledScript = service.compile(convert(template, model), compileParams);
CompiledScript compiledScript = service.compile(convert(template, model), WatcherScript.CTX, compileParams);
ExecutableScript executable = service.executable(compiledScript, model);
Object result = executable.run();
if (result instanceof BytesReference) {

View File

@ -6,7 +6,6 @@
package org.elasticsearch.xpack.common.text;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
/**
*
@ -15,7 +14,6 @@ public class TextTemplateModule extends AbstractModule {
@Override
protected void configure() {
bind(ScriptServiceProxy.class).asEagerSingleton();
bind(DefaultTextTemplateEngine.class).asEagerSingleton();
bind(TextTemplateEngine.class).to(DefaultTextTemplateEngine.class);
}

View File

@ -14,10 +14,11 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.script.Script;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.junit.Before;
import java.util.Collections;
@ -37,16 +38,16 @@ import static org.mockito.Mockito.when;
public class TextTemplateTests extends ESTestCase {
private ScriptServiceProxy proxy;
private ScriptService service;
private TextTemplateEngine engine;
private ExecutableScript script;
private final String lang = "mustache";
@Before
public void init() throws Exception {
proxy = mock(ScriptServiceProxy.class);
service = mock(ScriptService.class);
script = mock(ExecutableScript.class);
engine = new DefaultTextTemplateEngine(Settings.EMPTY, proxy);
engine = new DefaultTextTemplateEngine(Settings.EMPTY, service);
}
public void testRender() throws Exception {
@ -59,9 +60,9 @@ public class TextTemplateTests extends ESTestCase {
ScriptType type = randomFrom(ScriptType.values());
CompiledScript compiledScript = mock(CompiledScript.class);
when(proxy.compile(new Script(templateText, type, lang, merged), Collections.singletonMap("content_type", "text/plain")))
.thenReturn(compiledScript);
when(proxy.executable(compiledScript, model)).thenReturn(script);
when(service.compile(new Script(templateText, type, lang, merged), WatcherScript.CTX,
Collections.singletonMap("content_type", "text/plain"))).thenReturn(compiledScript);
when(service.executable(compiledScript, model)).thenReturn(script);
when(script.run()).thenReturn("rendered_text");
TextTemplate template = templateBuilder(type, templateText).params(params).build();
@ -75,10 +76,9 @@ public class TextTemplateTests extends ESTestCase {
ScriptType scriptType = randomFrom(ScriptType.values());
CompiledScript compiledScript = mock(CompiledScript.class);
when(proxy.compile(new Script(templateText, scriptType, lang, model),
Collections.singletonMap("content_type", "text/plain")))
.thenReturn(compiledScript);
when(proxy.executable(compiledScript, model)).thenReturn(script);
when(service.compile(new Script(templateText, scriptType, lang, model), WatcherScript.CTX,
Collections.singletonMap("content_type", "text/plain"))).thenReturn(compiledScript);
when(service.executable(compiledScript, model)).thenReturn(script);
when(script.run()).thenReturn("rendered_text");
TextTemplate template = templateBuilder(scriptType, templateText).params(params).build();
@ -90,10 +90,9 @@ public class TextTemplateTests extends ESTestCase {
Map<String, Object> model = singletonMap("key", "model_val");
CompiledScript compiledScript = mock(CompiledScript.class);
when(proxy.compile(new Script(templateText, ScriptType.INLINE, lang, model),
Collections.singletonMap("content_type", "text/plain")))
.thenReturn(compiledScript);
when(proxy.executable(compiledScript, model)).thenReturn(script);
when(service.compile(new Script(templateText, ScriptType.INLINE, lang, model), WatcherScript.CTX,
Collections.singletonMap("content_type", "text/plain"))).thenReturn(compiledScript);
when(service.executable(compiledScript, model)).thenReturn(script);
when(script.run()).thenReturn("rendered_text");
TextTemplate template = new TextTemplate(templateText);

View File

@ -10,7 +10,7 @@ import org.elasticsearch.xpack.watcher.condition.compare.CompareCondition;
import org.elasticsearch.xpack.watcher.condition.compare.array.ArrayCompareCondition;
import org.elasticsearch.xpack.watcher.condition.never.NeverCondition;
import org.elasticsearch.xpack.watcher.condition.script.ScriptCondition;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
/**
*
@ -29,14 +29,14 @@ public final class ConditionBuilders {
}
public static ScriptCondition.Builder scriptCondition(String script) {
return scriptCondition(Script.inline(script));
return scriptCondition(WatcherScript.inline(script));
}
public static ScriptCondition.Builder scriptCondition(Script.Builder script) {
public static ScriptCondition.Builder scriptCondition(WatcherScript.Builder script) {
return scriptCondition(script.build());
}
public static ScriptCondition.Builder scriptCondition(Script script) {
public static ScriptCondition.Builder scriptCondition(WatcherScript script) {
return ScriptCondition.builder(script);
}

View File

@ -8,11 +8,14 @@ package org.elasticsearch.xpack.watcher.condition.script;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.watcher.condition.ExecutableCondition;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.Variables;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import java.util.Collections;
import java.util.Map;
import static org.elasticsearch.xpack.watcher.support.Exceptions.invalidScript;
@ -22,14 +25,16 @@ import static org.elasticsearch.xpack.watcher.support.Exceptions.invalidScript;
*/
public class ExecutableScriptCondition extends ExecutableCondition<ScriptCondition, ScriptCondition.Result> {
private final ScriptServiceProxy scriptService;
private final ScriptService scriptService;
private final CompiledScript compiledScript;
public ExecutableScriptCondition(ScriptCondition condition, ESLogger logger, ScriptServiceProxy scriptService) {
public ExecutableScriptCondition(ScriptCondition condition, ESLogger logger, ScriptService scriptService) {
super(condition, logger);
this.scriptService = scriptService;
try {
compiledScript = scriptService.compile(condition.script);
Script script = new Script(condition.script.script(), condition.script.type(),
condition.script.lang(), condition.script.params());
compiledScript = scriptService.compile(script, WatcherScript.CTX, Collections.emptyMap());
} catch (Exception e) {
throw invalidScript("failed to compile script [{}] with lang [{}] of type [{}]", e, condition.script.script(),
condition.script.lang(), condition.script.type(), e);

View File

@ -9,7 +9,7 @@ import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.watcher.condition.Condition;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import java.io.IOException;
@ -20,9 +20,9 @@ public class ScriptCondition implements Condition {
public static final String TYPE = "script";
final Script script;
final WatcherScript script;
public ScriptCondition(Script script) {
public ScriptCondition(WatcherScript script) {
this.script = script;
}
@ -31,7 +31,7 @@ public class ScriptCondition implements Condition {
return TYPE;
}
public Script getScript() {
public WatcherScript getScript() {
return script;
}
@ -57,7 +57,7 @@ public class ScriptCondition implements Condition {
public static ScriptCondition parse(String watchId, XContentParser parser) throws IOException {
try {
Script script = Script.parse(parser);
WatcherScript script = WatcherScript.parse(parser);
return new ScriptCondition(script);
} catch (ElasticsearchParseException pe) {
throw new ElasticsearchParseException("could not parse [{}] condition for watch [{}]. failed to parse script", pe, TYPE,
@ -65,7 +65,7 @@ public class ScriptCondition implements Condition {
}
}
public static Builder builder(Script script) {
public static Builder builder(WatcherScript script) {
return new Builder(script);
}
@ -86,9 +86,9 @@ public class ScriptCondition implements Condition {
public static class Builder implements Condition.Builder<ScriptCondition> {
private final Script script;
private final WatcherScript script;
private Builder(Script script) {
private Builder(WatcherScript script) {
this.script = script;
}

View File

@ -9,8 +9,8 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.watcher.condition.ConditionFactory;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import java.io.IOException;
@ -19,10 +19,10 @@ import java.io.IOException;
*/
public class ScriptConditionFactory extends ConditionFactory<ScriptCondition, ScriptCondition.Result, ExecutableScriptCondition> {
private final ScriptServiceProxy scriptService;
private final ScriptService scriptService;
@Inject
public ScriptConditionFactory(Settings settings, ScriptServiceProxy service) {
public ScriptConditionFactory(Settings settings, ScriptService service) {
super(Loggers.getLogger(ExecutableScriptCondition.class, settings));
scriptService = service;
}

View File

@ -13,9 +13,9 @@ import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.aggregations.AggregatorParsers;
import org.elasticsearch.search.suggest.Suggesters;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.security.InternalClient;
import org.elasticsearch.xpack.watcher.input.InputFactory;
import org.elasticsearch.xpack.watcher.input.simple.ExecutableSimpleInput;
@ -39,12 +39,12 @@ public class SearchInputFactory extends InputFactory<SearchInput, SearchInput.Re
@Inject
public SearchInputFactory(Settings settings, InternalClient client, IndicesQueriesRegistry queryRegistry,
AggregatorParsers aggParsers, Suggesters suggesters, ScriptServiceProxy scriptService) {
AggregatorParsers aggParsers, Suggesters suggesters, ScriptService scriptService) {
this(settings, new WatcherClientProxy(settings, client), queryRegistry, aggParsers, suggesters, scriptService);
}
public SearchInputFactory(Settings settings, WatcherClientProxy client, IndicesQueriesRegistry queryRegistry,
AggregatorParsers aggParsers, Suggesters suggesters, ScriptServiceProxy scriptService) {
AggregatorParsers aggParsers, Suggesters suggesters, ScriptService scriptService) {
super(Loggers.getLogger(ExecutableSimpleInput.class, settings));
this.parseFieldMatcher = new ParseFieldMatcher(settings);
this.client = client;

View File

@ -12,6 +12,8 @@ import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.script.ScriptSettings;
@ -22,20 +24,22 @@ import java.util.Map;
/**
*
*/
public class Script implements ToXContent {
public class WatcherScript implements ToXContent {
public static final String DEFAULT_LANG = ScriptSettings.DEFAULT_LANG;
public static final ScriptContext.Plugin CTX_PLUGIN = new ScriptContext.Plugin("xpack", "watch");
public static final ScriptContext CTX = new WatcherScriptContext();
private final String script;
@Nullable private final ScriptType type;
@Nullable private final String lang;
@Nullable private final Map<String, Object> params;
Script(String script) {
WatcherScript(String script) {
this(script, null, null, null);
}
Script(String script, @Nullable ScriptType type, @Nullable String lang, @Nullable Map<String, Object> params) {
WatcherScript(String script, @Nullable ScriptType type, @Nullable String lang, @Nullable Map<String, Object> params) {
this.script = script;
this.type = type;
this.lang = lang;
@ -58,12 +62,16 @@ public class Script implements ToXContent {
return params != null ? params : Collections.emptyMap();
}
public Script toScript() {
return new Script(script(), type(), lang(), params());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Script script1 = (Script) o;
WatcherScript script1 = (WatcherScript) o;
if (!script.equals(script1.script)) return false;
if (type != script1.type) return false;
@ -106,10 +114,10 @@ public class Script implements ToXContent {
return builder.endObject();
}
public static Script parse(XContentParser parser) throws IOException {
public static WatcherScript parse(XContentParser parser) throws IOException {
XContentParser.Token token = parser.currentToken();
if (token == XContentParser.Token.VALUE_STRING) {
return new Script(parser.text());
return new WatcherScript(parser.text());
}
if (token != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException("expected a string value or an object, but found [{}] instead", token);
@ -170,7 +178,7 @@ public class Script implements ToXContent {
Field.INLINE.getPreferredName(), Field.FILE.getPreferredName(), Field.ID.getPreferredName());
}
assert type != null : "if script is not null, type should definitely not be null";
return new Script(script, type, lang, params);
return new WatcherScript(script, type, lang, params);
}
public static Builder.Inline inline(String script) {
@ -211,7 +219,7 @@ public class Script implements ToXContent {
return (B) this;
}
public abstract Script build();
public abstract WatcherScript build();
public static class Inline extends Builder<Inline> {
@ -220,8 +228,8 @@ public class Script implements ToXContent {
}
@Override
public Script build() {
return new Script(script, type, lang, params);
public WatcherScript build() {
return new WatcherScript(script, type, lang, params);
}
}
@ -232,8 +240,8 @@ public class Script implements ToXContent {
}
@Override
public Script build() {
return new Script(script, type, lang, params);
public WatcherScript build() {
return new WatcherScript(script, type, lang, params);
}
}
@ -244,8 +252,8 @@ public class Script implements ToXContent {
}
@Override
public Script build() {
return new Script(script, type, lang, params);
public WatcherScript build() {
return new WatcherScript(script, type, lang, params);
}
}
@ -256,8 +264,8 @@ public class Script implements ToXContent {
}
@Override
public Script build() {
return new Script(script, type, lang, params);
public WatcherScript build() {
return new WatcherScript(script, type, lang, params);
}
}
}
@ -271,4 +279,10 @@ public class Script implements ToXContent {
}
private static class WatcherScriptContext implements ScriptContext {
@Override
public String getKey() {
return CTX_PLUGIN.getKey();
}
}
}

View File

@ -20,7 +20,7 @@ import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.search.aggregations.AggregatorParsers;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.Suggesters;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.SearchRequestEquivalence;
import java.io.IOException;
@ -36,9 +36,9 @@ import java.util.Objects;
public class WatcherSearchTemplateRequest implements ToXContent {
private final SearchRequest request;
@Nullable private final Script template;
@Nullable private final WatcherScript template;
public WatcherSearchTemplateRequest(SearchRequest searchRequest, @Nullable Script template) {
public WatcherSearchTemplateRequest(SearchRequest searchRequest, @Nullable WatcherScript template) {
this.request = Objects.requireNonNull(searchRequest);
this.template = template;
}
@ -51,7 +51,7 @@ public class WatcherSearchTemplateRequest implements ToXContent {
return request;
}
public Script getTemplate() {
public WatcherScript getTemplate() {
return template;
}
@ -105,7 +105,7 @@ public class WatcherSearchTemplateRequest implements ToXContent {
throws IOException {
IndicesOptions indicesOptions = DEFAULT_INDICES_OPTIONS;
SearchRequest searchRequest = new SearchRequest();
Script template = null;
WatcherScript template = null;
XContentParser.Token token;
String currentFieldName = null;
@ -190,7 +190,7 @@ public class WatcherSearchTemplateRequest implements ToXContent {
indicesOptions = IndicesOptions.fromOptions(ignoreUnavailable, allowNoIndices, expandOpen, expandClosed,
DEFAULT_INDICES_OPTIONS);
} else if (ParseFieldMatcher.STRICT.match(currentFieldName, TEMPLATE_FIELD)) {
template = Script.parse(parser);
template = WatcherScript.parse(parser);
} else {
throw new ElasticsearchParseException("could not read search request. unexpected object field [" +
currentFieldName + "]");

View File

@ -17,17 +17,18 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.aggregations.AggregatorParsers;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.Suggesters;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.Variables;
import org.elasticsearch.xpack.watcher.watch.Payload;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
@ -39,17 +40,17 @@ public class WatcherSearchTemplateService extends AbstractComponent {
private static final String DEFAULT_LANG = "mustache";
private final ScriptServiceProxy scriptService;
private final ScriptService scriptService;
private final ParseFieldMatcher parseFieldMatcher;
private final IndicesQueriesRegistry queryRegistry;
private final AggregatorParsers aggsParsers;
private final Suggesters suggesters;
@Inject
public WatcherSearchTemplateService(Settings settings, ScriptServiceProxy scriptServiceProxy,
public WatcherSearchTemplateService(Settings settings, ScriptService scriptService,
IndicesQueriesRegistry queryRegistry, AggregatorParsers aggregatorParsers, Suggesters suggesters) {
super(settings);
this.scriptService = scriptServiceProxy;
this.scriptService = scriptService;
this.queryRegistry = queryRegistry;
this.aggsParsers = aggregatorParsers;
this.suggesters = suggesters;
@ -65,7 +66,7 @@ public class WatcherSearchTemplateService extends AbstractComponent {
.indices(prototype.getRequest().indices())
.types(prototype.getRequest().types());
Script template = null;
WatcherScript template = null;
// Due the inconsistency with templates in ES 1.x, we maintain our own template format.
// This template format we use now, will become the template structure in ES 2.0
@ -76,26 +77,26 @@ public class WatcherSearchTemplateService extends AbstractComponent {
if (prototype.getRequest().source() != null) {
try (XContentBuilder builder = jsonBuilder()) {
prototype.getRequest().source().toXContent(builder, ToXContent.EMPTY_PARAMS);
template = Script.inline(builder.string()).lang(DEFAULT_LANG).params(watcherContextParams).build();
template = WatcherScript.inline(builder.string()).lang(DEFAULT_LANG).params(watcherContextParams).build();
}
} else if (prototype.getTemplate() != null) {
// Here we convert watcher template into a ES core templates. Due to the different format we use, we
// convert to the template format used in ES core
Script templatePrototype = prototype.getTemplate();
WatcherScript templatePrototype = prototype.getTemplate();
if (templatePrototype.params() != null) {
watcherContextParams.putAll(templatePrototype.params());
}
Script.Builder builder;
WatcherScript.Builder builder;
if (templatePrototype.type() == ScriptService.ScriptType.INLINE) {
builder = Script.inline(templatePrototype.script());
builder = WatcherScript.inline(templatePrototype.script());
} else if (templatePrototype.type() == ScriptService.ScriptType.FILE) {
builder = Script.file(templatePrototype.script());
builder = WatcherScript.file(templatePrototype.script());
} else if (templatePrototype.type() == ScriptService.ScriptType.STORED) {
builder = Script.indexed(templatePrototype.script());
builder = WatcherScript.indexed(templatePrototype.script());
} else {
builder = Script.defaultType(templatePrototype.script());
builder = WatcherScript.defaultType(templatePrototype.script());
}
template = builder.lang(templatePrototype.lang()).params(watcherContextParams).build();
}
@ -105,16 +106,16 @@ public class WatcherSearchTemplateService extends AbstractComponent {
}
/**
* Converts a {@link Script} to a {@link org.elasticsearch.search.builder.SearchSourceBuilder}
* Converts a {@link WatcherScript} to a {@link org.elasticsearch.search.builder.SearchSourceBuilder}
*/
private SearchSourceBuilder convert(Script template) throws IOException {
private SearchSourceBuilder convert(WatcherScript template) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
if (template == null) {
// falling back to an empty body
return sourceBuilder;
}
BytesReference source = (BytesReference) scriptService.executable(scriptService.compile(template), template.params()).run();
CompiledScript compiledScript = scriptService.compile(template.toScript(), WatcherScript.CTX, Collections.emptyMap());
BytesReference source = (BytesReference) scriptService.executable(compiledScript, template.params()).run();
if (source != null && source.length() > 0) {
try (XContentParser parser = XContentFactory.xContent(source).createParser(source)) {
sourceBuilder.parseXContent(new QueryParseContext(queryRegistry, parser, parseFieldMatcher), aggsParsers, suggesters);

View File

@ -6,7 +6,7 @@
package org.elasticsearch.xpack.watcher.transform;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.transform.chain.ChainTransform;
import org.elasticsearch.xpack.watcher.transform.script.ScriptTransform;
@ -29,14 +29,14 @@ public final class TransformBuilders {
}
public static ScriptTransform.Builder scriptTransform(String script) {
return scriptTransform(Script.inline(script));
return scriptTransform(WatcherScript.inline(script));
}
public static ScriptTransform.Builder scriptTransform(Script.Builder script) {
public static ScriptTransform.Builder scriptTransform(WatcherScript.Builder script) {
return scriptTransform(script.build());
}
public static ScriptTransform.Builder scriptTransform(Script script) {
public static ScriptTransform.Builder scriptTransform(WatcherScript script) {
return ScriptTransform.builder(script);
}

View File

@ -8,13 +8,14 @@ package org.elasticsearch.xpack.watcher.transform.script;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.transform.ExecutableTransform;
import org.elasticsearch.xpack.watcher.watch.Payload;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@ -26,15 +27,15 @@ import static org.elasticsearch.xpack.watcher.support.Variables.createCtxModel;
*/
public class ExecutableScriptTransform extends ExecutableTransform<ScriptTransform, ScriptTransform.Result> {
private final ScriptServiceProxy scriptService;
private final ScriptService scriptService;
private final CompiledScript compiledScript;
public ExecutableScriptTransform(ScriptTransform transform, ESLogger logger, ScriptServiceProxy scriptService) {
public ExecutableScriptTransform(ScriptTransform transform, ESLogger logger, ScriptService scriptService) {
super(transform, logger);
this.scriptService = scriptService;
Script script = transform.getScript();
WatcherScript script = transform.getScript();
try {
compiledScript = scriptService.compile(script);
compiledScript = scriptService.compile(script.toScript(), WatcherScript.CTX, Collections.emptyMap());
} catch (Exception e) {
throw invalidScript("failed to compile script [{}] with lang [{}] of type [{}]", e, script.script(), script.lang(),
script.type(), e);
@ -53,7 +54,7 @@ public class ExecutableScriptTransform extends ExecutableTransform<ScriptTransfo
ScriptTransform.Result doExecute(WatchExecutionContext ctx, Payload payload) throws IOException {
Script script = transform.getScript();
WatcherScript script = transform.getScript();
Map<String, Object> model = new HashMap<>();
model.putAll(script.params());
model.putAll(createCtxModel(ctx, payload));

View File

@ -8,7 +8,7 @@ package org.elasticsearch.xpack.watcher.transform.script;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.transform.Transform;
import org.elasticsearch.xpack.watcher.watch.Payload;
@ -21,9 +21,9 @@ public class ScriptTransform implements Transform {
public static final String TYPE = "script";
private final Script script;
private final WatcherScript script;
public ScriptTransform(Script script) {
public ScriptTransform(WatcherScript script) {
this.script = script;
}
@ -32,7 +32,7 @@ public class ScriptTransform implements Transform {
return TYPE;
}
public Script getScript() {
public WatcherScript getScript() {
return script;
}
@ -58,7 +58,7 @@ public class ScriptTransform implements Transform {
public static ScriptTransform parse(String watchId, XContentParser parser) throws IOException {
try {
Script script = Script.parse(parser);
WatcherScript script = WatcherScript.parse(parser);
return new ScriptTransform(script);
} catch (ElasticsearchParseException pe) {
throw new ElasticsearchParseException("could not parse [{}] transform for watch [{}]. failed to parse script", pe, TYPE,
@ -66,7 +66,7 @@ public class ScriptTransform implements Transform {
}
}
public static Builder builder(Script script) {
public static Builder builder(WatcherScript script) {
return new Builder(script);
}
@ -88,9 +88,9 @@ public class ScriptTransform implements Transform {
public static class Builder implements Transform.Builder<ScriptTransform> {
private final Script script;
private final WatcherScript script;
public Builder(Script script) {
public Builder(WatcherScript script) {
this.script = script;
}

View File

@ -9,7 +9,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.watcher.transform.TransformFactory;
import java.io.IOException;
@ -19,10 +19,10 @@ import java.io.IOException;
*/
public class ScriptTransformFactory extends TransformFactory<ScriptTransform, ScriptTransform.Result, ExecutableScriptTransform> {
private final ScriptServiceProxy scriptService;
private final ScriptService scriptService;
@Inject
public ScriptTransformFactory(Settings settings, ScriptServiceProxy scriptService) {
public ScriptTransformFactory(Settings settings, ScriptService scriptService) {
super(Loggers.getLogger(ExecutableScriptTransform.class, settings));
this.scriptService = scriptService;
}

View File

@ -15,10 +15,10 @@ import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.aggregations.AggregatorParsers;
import org.elasticsearch.search.suggest.Suggesters;
import org.elasticsearch.xpack.security.InternalClient;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.support.init.proxy.WatcherClientProxy;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService;
import org.elasticsearch.xpack.watcher.transform.TransformFactory;
@ -38,11 +38,11 @@ public class SearchTransformFactory extends TransformFactory<SearchTransform, Se
@Inject
public SearchTransformFactory(Settings settings, InternalClient client, IndicesQueriesRegistry queryRegistry,
AggregatorParsers aggParsers, Suggesters suggesters, ScriptServiceProxy scriptService) {
AggregatorParsers aggParsers, Suggesters suggesters, ScriptService scriptService) {
this(settings, new WatcherClientProxy(settings, client), queryRegistry, aggParsers, suggesters, scriptService);
}
public SearchTransformFactory(Settings settings, WatcherClientProxy client, IndicesQueriesRegistry queryRegistry,
AggregatorParsers aggParsers, Suggesters suggesters, ScriptServiceProxy scriptService) {
AggregatorParsers aggParsers, Suggesters suggesters, ScriptService scriptService) {
super(Loggers.getLogger(ExecutableSearchTransform.class, settings));
this.client = client;
this.parseFieldMatcher = new ParseFieldMatcher(settings);

View File

@ -10,6 +10,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.search.lookup.SearchLookup;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import java.io.IOException;
import java.util.Collections;
@ -68,8 +69,8 @@ public class SleepScriptEngine implements ScriptEngineService {
public void close() throws IOException {
}
public static org.elasticsearch.xpack.watcher.support.Script sleepScript(long millis) {
return new org.elasticsearch.xpack.watcher.support.Script.Builder.Inline("")
public static WatcherScript sleepScript(long millis) {
return new WatcherScript.Builder.Inline("")
.lang("sleep")
.params(Collections.singletonMap("millis", millis)).build();
}

View File

@ -98,7 +98,7 @@ public class WatcherUtilsTests extends ESTestCase {
public void testSerializeSearchRequest() throws Exception {
String[] randomIndices = generateRandomStringArray(5, 5, false);
SearchRequest expectedRequest = new SearchRequest(randomIndices);
Script expectedTemplate = null;
WatcherScript expectedTemplate = null;
if (randomBoolean()) {
String[] randomTypes = generateRandomStringArray(2, 5, false);
@ -121,7 +121,8 @@ public class WatcherUtilsTests extends ESTestCase {
}
}
String text = randomAsciiOfLengthBetween(1, 5);
expectedTemplate = randomFrom(Script.inline(text), Script.file(text), Script.indexed(text)).params(params).build();
expectedTemplate = randomFrom(WatcherScript.inline(text), WatcherScript.file(text),
WatcherScript.indexed(text)).params(params).build();
}
WatcherSearchTemplateRequest request = new WatcherSearchTemplateRequest(expectedRequest, expectedTemplate);
@ -199,7 +200,7 @@ public class WatcherUtilsTests extends ESTestCase {
source = searchSourceBuilder.buildAsBytes(XContentType.JSON);
builder.rawField("body", source);
}
Script template = null;
WatcherScript template = null;
if (randomBoolean()) {
Map<String, Object> params = new HashMap<>();
if (randomBoolean()) {
@ -209,7 +210,8 @@ public class WatcherUtilsTests extends ESTestCase {
}
}
String text = randomAsciiOfLengthBetween(1, 5);
template = randomFrom(Script.inline(text), Script.file(text), Script.indexed(text)) .params(params).build();
template = randomFrom(WatcherScript.inline(text), WatcherScript.file(text), WatcherScript.indexed(text))
.params(params).build();
builder.field("template", template);
}
builder.endObject();

View File

@ -22,6 +22,7 @@ import org.elasticsearch.common.util.Callback;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.monitoring.Monitoring;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockMustacheScriptEngine;
@ -51,7 +52,6 @@ import org.elasticsearch.xpack.watcher.WatcherLicensee;
import org.elasticsearch.xpack.watcher.support.WatcherIndexTemplateRegistry;
import org.elasticsearch.xpack.support.clock.ClockMock;
import org.elasticsearch.xpack.common.http.HttpClient;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.support.xcontent.XContentSource;
import org.elasticsearch.xpack.watcher.trigger.ScheduleTriggerEngineMock;
import org.elasticsearch.xpack.watcher.trigger.TriggerService;
@ -356,8 +356,8 @@ public abstract class AbstractWatcherIntegrationTestCase extends ESIntegTestCase
return randomBoolean() ? new XPackClient(client).watcher() : new WatcherClient(client);
}
protected ScriptServiceProxy scriptService() {
return internalCluster().getInstance(ScriptServiceProxy.class);
protected ScriptService scriptService() {
return internalCluster().getInstance(ScriptService.class);
}
protected HttpClient watcherHttpClient() {

View File

@ -8,11 +8,7 @@ package org.elasticsearch.xpack.watcher.test;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
@ -20,7 +16,6 @@ import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.env.Environment;
import org.elasticsearch.script.ScriptContextRegistry;
@ -31,7 +26,6 @@ import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.common.http.HttpClient;
import org.elasticsearch.xpack.common.http.HttpMethod;
import org.elasticsearch.xpack.common.http.HttpRequestTemplate;
@ -56,6 +50,7 @@ import org.elasticsearch.xpack.watcher.execution.Wid;
import org.elasticsearch.xpack.watcher.input.search.ExecutableSearchInput;
import org.elasticsearch.xpack.watcher.input.simple.ExecutableSimpleInput;
import org.elasticsearch.xpack.watcher.input.simple.SimpleInput;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.init.proxy.WatcherClientProxy;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService;
@ -71,11 +66,9 @@ import org.elasticsearch.xpack.watcher.watch.Watch;
import org.elasticsearch.xpack.watcher.watch.WatchStatus;
import org.hamcrest.Matcher;
import org.joda.time.DateTime;
import org.mockito.Mockito;
import javax.mail.internet.AddressException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@ -245,19 +238,19 @@ public final class WatcherTestUtils {
new WatchStatus(now, statuses));
}
public static ScriptServiceProxy getScriptServiceProxy(ThreadPool tp) throws Exception {
public static ScriptService createScriptService(ThreadPool tp) throws Exception {
Settings settings = Settings.builder()
.put("script.inline", "true")
.put("script.indexed", "true")
.put("path.home", createTempDir())
.build();
ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(Collections.singletonList(ScriptServiceProxy.INSTANCE));
ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(Collections.singletonList(WatcherScript.CTX_PLUGIN));
ScriptEngineRegistry scriptEngineRegistry =
new ScriptEngineRegistry(Collections.emptyList());
ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, scriptContextRegistry);
return ScriptServiceProxy.of(new ScriptService(settings, new Environment(settings),
new ResourceWatcherService(settings, tp), scriptEngineRegistry, scriptContextRegistry, scriptSettings));
return new ScriptService(settings, new Environment(settings), new ResourceWatcherService(settings, tp),
scriptEngineRegistry, scriptContextRegistry, scriptSettings);
}
public static SearchType getRandomSupportedSearchType() {

View File

@ -15,7 +15,7 @@ import org.elasticsearch.xpack.support.clock.SystemClock;
import org.elasticsearch.xpack.watcher.client.WatchSourceBuilder;
import org.elasticsearch.xpack.watcher.client.WatcherClient;
import org.elasticsearch.xpack.watcher.condition.compare.CompareCondition;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.support.xcontent.XContentSource;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
@ -259,7 +259,7 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase {
.setSource(jsonBuilder().startObject().field("template").value(searchSourceBuilder).endObject().bytes())
.get());
Script template = Script.indexed("my-template").lang("mustache").build();
WatcherScript template = WatcherScript.indexed("my-template").lang("mustache").build();
SearchRequest searchRequest = newInputSearchRequest("events");
testConditionSearch(searchRequest, template);
}
@ -368,7 +368,7 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase {
}
}
private void testConditionSearch(SearchRequest request, Script template) throws Exception {
private void testConditionSearch(SearchRequest request, WatcherScript template) throws Exception {
// reset, so we don't miss event docs when we filter over the _timestamp field.
timeWarp().clock().setTime(SystemClock.INSTANCE.nowUTC());

View File

@ -12,7 +12,7 @@ import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.test.WatcherTestUtils;
import org.elasticsearch.xpack.watcher.transport.actions.put.PutWatchResponse;
@ -63,10 +63,10 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
}
public void testScriptTransform() throws Exception {
final Script script;
final WatcherScript script;
if (randomBoolean()) {
logger.info("testing script transform with an inline script");
script = Script.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build();
script = WatcherScript.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build();
} else if (randomBoolean()) {
logger.info("testing script transform with an indexed script");
client().admin().cluster().preparePutStoredScript()
@ -74,10 +74,10 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
.setScriptLang("groovy")
.setSource(new BytesArray("{\"script\" : \"return [key3 : ctx.payload.key1 + ctx.payload.key2]\"}"))
.get();
script = Script.indexed("_id").lang("groovy").build();
script = WatcherScript.indexed("_id").lang("groovy").build();
} else {
logger.info("testing script transform with a file script");
script = Script.file("my-script").lang("groovy").build();
script = WatcherScript.file("my-script").lang("groovy").build();
}
// put a watch that has watch level transform:
@ -173,8 +173,8 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
}
public void testChainTransform() throws Exception {
final Script script1 = Script.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build();
final Script script2 = Script.inline("return [key4 : ctx.payload.key3 + 10]").lang("groovy").build();
final WatcherScript script1 = WatcherScript.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build();
final WatcherScript script2 = WatcherScript.inline("return [key4 : ctx.payload.key3 + 10]").lang("groovy").build();
// put a watch that has watch level transform:
PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id1")
.setSource(watchBuilder()

View File

@ -13,14 +13,14 @@ import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.GeneralScriptException;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.Variables;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.transform.Transform;
import org.elasticsearch.xpack.watcher.watch.Payload;
import org.junit.After;
@ -35,7 +35,7 @@ import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.xpack.watcher.support.Exceptions.illegalArgument;
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.EMPTY_PAYLOAD;
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.getScriptServiceProxy;
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.createScriptService;
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.mockExecutionContext;
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.simplePayload;
import static org.hamcrest.Matchers.containsString;
@ -63,12 +63,12 @@ public class ScriptTransformTests extends ESTestCase {
}
public void testExecute_MapValue() throws Exception {
ScriptServiceProxy service = mock(ScriptServiceProxy.class);
ScriptService service = mock(ScriptService.class);
ScriptType type = randomFrom(ScriptType.values());
Map<String, Object> params = Collections.emptyMap();
Script script = scriptBuilder(type, "_script").lang("_lang").params(params).build();
WatcherScript script = scriptBuilder(type, "_script").lang("_lang").params(params).build();
CompiledScript compiledScript = mock(CompiledScript.class);
when(service.compile(script)).thenReturn(compiledScript);
when(service.compile(script.toScript(), WatcherScript.CTX, Collections.emptyMap())).thenReturn(compiledScript);
ExecutableScriptTransform transform = new ExecutableScriptTransform(new ScriptTransform(script), logger, service);
WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD);
@ -91,12 +91,12 @@ public class ScriptTransformTests extends ESTestCase {
}
public void testExecuteMapValueFailure() throws Exception {
ScriptServiceProxy service = mock(ScriptServiceProxy.class);
ScriptService service = mock(ScriptService.class);
ScriptType type = randomFrom(ScriptType.values());
Map<String, Object> params = Collections.emptyMap();
Script script = scriptBuilder(type, "_script").lang("_lang").params(params).build();
WatcherScript script = scriptBuilder(type, "_script").lang("_lang").params(params).build();
CompiledScript compiledScript = mock(CompiledScript.class);
when(service.compile(script)).thenReturn(compiledScript);
when(service.compile(script.toScript(), WatcherScript.CTX, Collections.emptyMap())).thenReturn(compiledScript);
ExecutableScriptTransform transform = new ExecutableScriptTransform(new ScriptTransform(script), logger, service);
WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD);
@ -117,13 +117,12 @@ public class ScriptTransformTests extends ESTestCase {
}
public void testExecuteNonMapValue() throws Exception {
ScriptServiceProxy service = mock(ScriptServiceProxy.class);
ScriptService service = mock(ScriptService.class);
ScriptType type = randomFrom(ScriptType.values());
Map<String, Object> params = Collections.emptyMap();
Script script = scriptBuilder(type, "_script").lang("_lang").params(params).build();
WatcherScript script = scriptBuilder(type, "_script").lang("_lang").params(params).build();
CompiledScript compiledScript = mock(CompiledScript.class);
when(service.compile(script)).thenReturn(compiledScript);
when(service.compile(script.toScript(), WatcherScript.CTX, Collections.emptyMap())).thenReturn(compiledScript);
ExecutableScriptTransform transform = new ExecutableScriptTransform(new ScriptTransform(script), logger, service);
WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD);
@ -145,7 +144,7 @@ public class ScriptTransformTests extends ESTestCase {
}
public void testParser() throws Exception {
ScriptServiceProxy service = mock(ScriptServiceProxy.class);
ScriptService service = mock(ScriptService.class);
ScriptType type = randomFrom(ScriptType.values());
XContentBuilder builder = jsonBuilder().startObject();
builder.field(scriptTypeField(type), "_script");
@ -156,22 +155,22 @@ public class ScriptTransformTests extends ESTestCase {
XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes());
parser.nextToken();
ExecutableScriptTransform transform = new ScriptTransformFactory(Settings.EMPTY, service).parseExecutable("_id", parser);
Script script = scriptBuilder(type, "_script").lang("_lang").params(singletonMap("key", "value")).build();
WatcherScript script = scriptBuilder(type, "_script").lang("_lang").params(singletonMap("key", "value")).build();
assertThat(transform.transform().getScript(), equalTo(script));
}
public void testParserString() throws Exception {
ScriptServiceProxy service = mock(ScriptServiceProxy.class);
ScriptService service = mock(ScriptService.class);
XContentBuilder builder = jsonBuilder().value("_script");
XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes());
parser.nextToken();
ExecutableScriptTransform transform = new ScriptTransformFactory(Settings.EMPTY, service).parseExecutable("_id", parser);
assertThat(transform.transform().getScript(), equalTo(Script.defaultType("_script").build()));
assertThat(transform.transform().getScript(), equalTo(WatcherScript.defaultType("_script").build()));
}
public void testScriptConditionParserBadScript() throws Exception {
ScriptTransformFactory transformFactory = new ScriptTransformFactory(Settings.builder().build(), getScriptServiceProxy(tp));
ScriptTransformFactory transformFactory = new ScriptTransformFactory(Settings.builder().build(), createScriptService(tp));
ScriptType scriptType = randomFrom(ScriptType.values());
String script;
switch (scriptType) {
@ -203,7 +202,7 @@ public class ScriptTransformTests extends ESTestCase {
}
public void testScriptConditionParserBadLang() throws Exception {
ScriptTransformFactory transformFactory = new ScriptTransformFactory(Settings.builder().build(), getScriptServiceProxy(tp));
ScriptTransformFactory transformFactory = new ScriptTransformFactory(Settings.builder().build(), createScriptService(tp));
ScriptType scriptType = randomFrom(ScriptType.values());
String script = "return true";
XContentBuilder builder = jsonBuilder().startObject()
@ -224,11 +223,11 @@ public class ScriptTransformTests extends ESTestCase {
}
}
static Script.Builder scriptBuilder(ScriptType type, String script) {
static WatcherScript.Builder scriptBuilder(ScriptType type, String script) {
switch (type) {
case INLINE: return Script.inline(script);
case FILE: return Script.file(script);
case STORED: return Script.indexed(script);
case INLINE: return WatcherScript.inline(script);
case FILE: return WatcherScript.file(script);
case STORED: return WatcherScript.indexed(script);
default:
throw illegalArgument("unsupported script type [{}]", type);
}

View File

@ -16,8 +16,8 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryParser;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.common.http.HttpClient;
import org.elasticsearch.xpack.common.http.HttpMethod;
import org.elasticsearch.xpack.common.http.HttpRequestTemplate;
@ -78,7 +78,7 @@ import org.elasticsearch.xpack.watcher.input.search.SearchInputFactory;
import org.elasticsearch.xpack.watcher.input.simple.ExecutableSimpleInput;
import org.elasticsearch.xpack.watcher.input.simple.SimpleInput;
import org.elasticsearch.xpack.watcher.input.simple.SimpleInputFactory;
import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.init.proxy.WatcherClientProxy;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService;
@ -141,7 +141,7 @@ import static org.joda.time.DateTimeZone.UTC;
import static org.mockito.Mockito.mock;
public class WatchTests extends ESTestCase {
private ScriptServiceProxy scriptService;
private ScriptService scriptService;
private WatcherClientProxy client;
private HttpClient httpClient;
private EmailService emailService;
@ -155,7 +155,7 @@ public class WatchTests extends ESTestCase {
@Before
public void init() throws Exception {
scriptService = mock(ScriptServiceProxy.class);
scriptService = mock(ScriptService.class);
client = mock(WatcherClientProxy.class);
httpClient = mock(HttpClient.class);
emailService = mock(EmailService.class);
@ -363,7 +363,7 @@ public class WatchTests extends ESTestCase {
String type = randomFrom(ScriptCondition.TYPE, AlwaysCondition.TYPE, CompareCondition.TYPE, ArrayCompareCondition.TYPE);
switch (type) {
case ScriptCondition.TYPE:
return new ExecutableScriptCondition(new ScriptCondition(Script.inline("_script").build()), logger, scriptService);
return new ExecutableScriptCondition(new ScriptCondition(WatcherScript.inline("_script").build()), logger, scriptService);
case CompareCondition.TYPE:
return new ExecutableCompareCondition(new CompareCondition("_path", randomFrom(Op.values()), randomFrom(5, "3")), logger,
SystemClock.INSTANCE);
@ -400,7 +400,7 @@ public class WatchTests extends ESTestCase {
DateTimeZone timeZone = randomBoolean() ? DateTimeZone.UTC : null;
switch (type) {
case ScriptTransform.TYPE:
return new ExecutableScriptTransform(new ScriptTransform(Script.inline("_script").build()), logger, scriptService);
return new ExecutableScriptTransform(new ScriptTransform(WatcherScript.inline("_script").build()), logger, scriptService);
case SearchTransform.TYPE:
SearchTransform transform = new SearchTransform(
new WatcherSearchTemplateRequest(matchAllRequest(DEFAULT_INDICES_OPTIONS), null), timeout, timeZone);
@ -408,14 +408,15 @@ public class WatchTests extends ESTestCase {
default: // chain
SearchTransform searchTransform = new SearchTransform(
new WatcherSearchTemplateRequest(matchAllRequest(DEFAULT_INDICES_OPTIONS), null), timeout, timeZone);
ScriptTransform scriptTransform = new ScriptTransform(Script.inline("_script").build());
ScriptTransform scriptTransform = new ScriptTransform(WatcherScript.inline("_script").build());
ChainTransform chainTransform = new ChainTransform(Arrays.asList(searchTransform, scriptTransform));
return new ExecutableChainTransform(chainTransform, logger, Arrays.<ExecutableTransform>asList(
new ExecutableSearchTransform(new SearchTransform(
new WatcherSearchTemplateRequest(matchAllRequest(DEFAULT_INDICES_OPTIONS), null), timeout, timeZone),
logger, client, searchTemplateService, null),
new ExecutableScriptTransform(new ScriptTransform(Script.inline("_script").build()), logger, scriptService)));
new ExecutableScriptTransform(new ScriptTransform(WatcherScript.inline("_script").build()),
logger, scriptService)));
}
}