watcher: remove WatchScript class

Original commit: elastic/x-pack-elasticsearch@fb2f9a28f1
This commit is contained in:
Martijn van Groningen 2016-08-17 16:31:01 +02:00
parent 8ae939fec7
commit f10fbeeb70
39 changed files with 279 additions and 586 deletions

View File

@ -10,6 +10,7 @@ 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.ScriptContext;
import org.elasticsearch.script.ScriptContextRegistry;
import org.elasticsearch.script.ScriptEngineRegistry;
import org.elasticsearch.script.ScriptService;
@ -17,9 +18,9 @@ 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.XPackPlugin;
import org.elasticsearch.xpack.common.text.TextTemplateEngine;
import org.elasticsearch.xpack.common.text.TextTemplate;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.junit.Before;
import org.mockito.Mockito;
@ -43,7 +44,7 @@ public class WatcherTemplateIT 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(WatcherScript.CTX_PLUGIN));
ScriptContextRegistry registry = new ScriptContextRegistry(Collections.singletonList(new ScriptContext.Plugin("xpack", "watch")));
ScriptEngineRegistry scriptEngineRegistry = new ScriptEngineRegistry(
Collections.singleton(new MustacheScriptEngineService(setting))

View File

@ -100,16 +100,6 @@ processResources {
from licenseKeyPath
}
processTestResources {
from(sourceSets.test.resources.srcDirs) {
exclude '**/*.key'
exclude '**/*.jks'
exclude '**/*.p12'
inputs.properties(expansions)
MavenFilteringHack.filter(it, expansions)
}
}
forbiddenPatterns {
exclude '**/*.key'
exclude '**/*.p12'

View File

@ -49,6 +49,7 @@ import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.rest.RestHandler;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptSettings;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.threadpool.ExecutorBuilder;
import org.elasticsearch.threadpool.ThreadPool;
@ -93,7 +94,6 @@ 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.WatcherFeatureSet;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
public class XPackPlugin extends Plugin implements ScriptPlugin, ActionPlugin, IngestPlugin {
@ -279,7 +279,7 @@ public class XPackPlugin extends Plugin implements ScriptPlugin, ActionPlugin, I
@Override
public ScriptContext.Plugin getCustomScriptContexts() {
return WatcherScript.CTX_PLUGIN;
return watcher.getCustomScriptContexts();
}
@Override

View File

@ -7,14 +7,13 @@ package org.elasticsearch.xpack.common.text;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.Watcher;
import java.util.Collections;
import java.util.HashMap;
@ -29,6 +28,7 @@ public class TextTemplateEngine extends AbstractComponent {
this.service = service;
}
// TODO: move over to use o.e.script.Script instead
public String render(TextTemplate template, Map<String, Object> model) {
if (template == null) {
return null;
@ -38,7 +38,8 @@ public class TextTemplateEngine extends AbstractComponent {
Map<String, String> compileParams = compileParams(contentType);
template = trimContentType(template);
CompiledScript compiledScript = service.compile(convert(template, model), WatcherScript.CTX, compileParams);
CompiledScript compiledScript = service.compile(convert(template, model), Watcher.SCRIPT_CONTEXT,
compileParams);
ExecutableScript executable = service.executable(compiledScript, model);
Object result = executable.run();
if (result instanceof BytesReference) {

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.xpack.common.text;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.Settings;
@ -18,7 +17,7 @@ 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.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.Watcher;
import org.junit.Before;
import java.util.Collections;
@ -60,7 +59,7 @@ public class TextTemplateTests extends ESTestCase {
ScriptType type = randomFrom(ScriptType.values());
CompiledScript compiledScript = mock(CompiledScript.class);
when(service.compile(new Script(templateText, type, lang, merged), WatcherScript.CTX,
when(service.compile(new Script(templateText, type, lang, merged), Watcher.SCRIPT_CONTEXT,
Collections.singletonMap("content_type", "text/plain"))).thenReturn(compiledScript);
when(service.executable(compiledScript, model)).thenReturn(script);
when(script.run()).thenReturn("rendered_text");
@ -76,7 +75,7 @@ public class TextTemplateTests extends ESTestCase {
ScriptType scriptType = randomFrom(ScriptType.values());
CompiledScript compiledScript = mock(CompiledScript.class);
when(service.compile(new Script(templateText, scriptType, lang, model), WatcherScript.CTX,
when(service.compile(new Script(templateText, scriptType, lang, model), Watcher.SCRIPT_CONTEXT,
Collections.singletonMap("content_type", "text/plain"))).thenReturn(compiledScript);
when(service.executable(compiledScript, model)).thenReturn(script);
when(script.run()).thenReturn("rendered_text");
@ -90,7 +89,7 @@ public class TextTemplateTests extends ESTestCase {
Map<String, Object> model = singletonMap("key", "model_val");
CompiledScript compiledScript = mock(CompiledScript.class);
when(service.compile(new Script(templateText, ScriptType.INLINE, lang, model), WatcherScript.CTX,
when(service.compile(new Script(templateText, ScriptType.INLINE, lang, model), Watcher.SCRIPT_CONTEXT,
Collections.singletonMap("content_type", "text/plain"))).thenReturn(compiledScript);
when(service.executable(compiledScript, model)).thenReturn(script);
when(script.run()).thenReturn("rendered_text");

View File

@ -21,7 +21,9 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.rest.RestHandler;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.threadpool.ExecutorBuilder;
import org.elasticsearch.threadpool.FixedExecutorBuilder;
import org.elasticsearch.xpack.XPackPlugin;
@ -80,7 +82,7 @@ import java.util.function.Function;
import static java.util.Collections.emptyList;
public class Watcher implements ActionPlugin {
public class Watcher implements ActionPlugin, ScriptPlugin {
public static final Setting<String> INDEX_WATCHER_VERSION_SETTING =
new Setting<>("index.xpack.watcher.plugin.version", "", Function.identity(), Setting.Property.IndexScope);
@ -91,6 +93,9 @@ public class Watcher implements ActionPlugin {
public static final Setting<TimeValue> MAX_STOP_TIMEOUT_SETTING =
Setting.timeSetting("xpack.watcher.stop.timeout", TimeValue.timeValueSeconds(30), Setting.Property.NodeScope);
private static final ScriptContext.Plugin SCRIPT_PLUGIN = new ScriptContext.Plugin("xpack", "watch");
public static final ScriptContext SCRIPT_CONTEXT = SCRIPT_PLUGIN::getKey;
private static final ESLogger logger = Loggers.getLogger(XPackPlugin.class);
static {
@ -203,6 +208,11 @@ public class Watcher implements ActionPlugin {
RestHijackOperationAction.class);
}
@Override
public ScriptContext.Plugin getCustomScriptContexts() {
return SCRIPT_PLUGIN;
}
static void validAutoCreateIndex(Settings settings) {
String value = settings.get("action.auto_create_index");
if (value == null) {

View File

@ -5,16 +5,13 @@
*/
package org.elasticsearch.xpack.watcher.condition;
import org.elasticsearch.script.Script;
import org.elasticsearch.xpack.watcher.condition.always.AlwaysCondition;
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.WatcherScript;
/**
*
*/
public final class ConditionBuilders {
private ConditionBuilders() {
@ -29,14 +26,10 @@ public final class ConditionBuilders {
}
public static ScriptCondition.Builder scriptCondition(String script) {
return scriptCondition(WatcherScript.inline(script));
return scriptCondition(new Script(script));
}
public static ScriptCondition.Builder scriptCondition(WatcherScript.Builder script) {
return scriptCondition(script.build());
}
public static ScriptCondition.Builder scriptCondition(WatcherScript script) {
public static ScriptCondition.Builder scriptCondition(Script script) {
return ScriptCondition.builder(script);
}

View File

@ -10,10 +10,10 @@ import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.watcher.Watcher;
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;
@ -32,12 +32,11 @@ public class ExecutableScriptCondition extends ExecutableCondition<ScriptConditi
super(condition, logger);
this.scriptService = scriptService;
try {
Script script = new Script(condition.script.script(), condition.script.type(),
condition.script.lang(), condition.script.params());
compiledScript = scriptService.compile(script, WatcherScript.CTX, Collections.emptyMap());
Script script = new Script(condition.script.getScript(), condition.script.getType(),
condition.script.getLang(), condition.script.getParams());
compiledScript = scriptService.compile(script, Watcher.SCRIPT_CONTEXT, 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);
throw invalidScript("failed to compile script [{}]", e, condition.script, e);
}
}
@ -48,8 +47,8 @@ public class ExecutableScriptCondition extends ExecutableCondition<ScriptConditi
public ScriptCondition.Result doExecute(WatchExecutionContext ctx) {
Map<String, Object> parameters = Variables.createCtxModel(ctx, ctx.payload());
if (condition.script.params() != null && !condition.script.params().isEmpty()) {
parameters.putAll(condition.script.params());
if (condition.script.getParams() != null && !condition.script.getParams().isEmpty()) {
parameters.putAll(condition.script.getParams());
}
ExecutableScript executable = scriptService.executable(compiledScript, parameters);
Object value = executable.run();
@ -57,6 +56,6 @@ public class ExecutableScriptCondition extends ExecutableCondition<ScriptConditi
return (Boolean) value ? ScriptCondition.Result.MET : ScriptCondition.Result.UNMET;
}
throw invalidScript("condition [{}] must return a boolean value (true|false) but instead returned [{}]", type(), ctx.watch().id(),
condition.script.script(), value);
condition.script, value);
}
}

View File

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

View File

@ -14,10 +14,10 @@ import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.input.ExecutableInput;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.XContentFilterKeysUtils;
import org.elasticsearch.xpack.watcher.support.init.proxy.WatcherClientProxy;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
@ -51,7 +51,7 @@ public class ExecutableSearchInput extends ExecutableInput<SearchInput, SearchIn
public SearchInput.Result execute(WatchExecutionContext ctx, Payload payload) {
WatcherSearchTemplateRequest request = null;
try {
WatcherScript template = input.getRequest().getOrCreateTemplate();
Script template = input.getRequest().getOrCreateTemplate();
BytesReference renderedTemplate = searchTemplateService.renderTemplate(template, ctx, payload);
// We need to make a copy, so that we don't modify the original instance that we keep around in a watch:
request = new WatcherSearchTemplateRequest(input.getRequest(), renderedTemplate);

View File

@ -12,9 +12,6 @@ import java.io.IOException;
import static org.elasticsearch.common.logging.LoggerMessageFormat.format;
/**
*
*/
public class Exceptions {
private Exceptions() {

View File

@ -1,290 +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.watcher.support;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
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;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
// TODO: remove this class as it is exactly the same as org.elasticsearch.script.Script
// and we should be able to remove it without breaking bwc in the .watch index
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;
WatcherScript(String script) {
this(script, null, null, null);
}
WatcherScript(String script, @Nullable ScriptType type, @Nullable String lang, @Nullable Map<String, Object> params) {
this.script = script;
this.type = type;
this.lang = lang;
this.params = params;
}
public String script() {
return script;
}
public ScriptType type() {
return type != null ? type : ScriptType.INLINE;
}
public String lang() {
return lang != null ? lang : DEFAULT_LANG;
}
public Map<String, Object> params() {
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;
WatcherScript script1 = (WatcherScript) o;
if (!script.equals(script1.script)) return false;
if (type != script1.type) return false;
if (lang != null ? !lang.equals(script1.lang) : script1.lang != null) return false;
return !(params != null ? !params.equals(script1.params) : script1.params != null);
}
@Override
public int hashCode() {
int result = script.hashCode();
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (lang != null ? lang.hashCode() : 0);
result = 31 * result + (params != null ? params.hashCode() : 0);
return result;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (type == null) {
return builder.value(script);
}
builder.startObject();
switch (type) {
case INLINE:
builder.field(Field.INLINE.getPreferredName(), script);
break;
case FILE:
builder.field(Field.FILE.getPreferredName(), script);
break;
default:
assert type == ScriptType.STORED : "script type [" + type + "] is not supported";
builder.field(Field.ID.getPreferredName(), script);
}
if (lang != null) {
builder.field(Field.LANG.getPreferredName(), lang);
}
if (this.params != null) {
builder.field(Field.PARAMS.getPreferredName(), this.params);
}
return builder.endObject();
}
public static WatcherScript parse(XContentParser parser) throws IOException {
return parse(parser, null);
}
public static WatcherScript parse(XContentParser parser, @Nullable String lang) throws IOException {
XContentParser.Token token = parser.currentToken();
if (token == XContentParser.Token.VALUE_STRING) {
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);
}
String script = null;
ScriptType type = null;
Map<String, Object> params = null;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (ParseFieldMatcher.STRICT.match(currentFieldName, Field.INLINE)) {
type = ScriptType.INLINE;
if (token == XContentParser.Token.VALUE_STRING) {
script = parser.text();
} else {
throw new ElasticsearchParseException("expected a string value for field [{}], but found [{}]", currentFieldName,
token);
}
} else if (ParseFieldMatcher.STRICT.match(currentFieldName, Field.FILE)) {
type = ScriptType.FILE;
if (token == XContentParser.Token.VALUE_STRING) {
script = parser.text();
} else {
throw new ElasticsearchParseException("expected a string value for field [{}], but found [{}]", currentFieldName,
token);
}
} else if (ParseFieldMatcher.STRICT.match(currentFieldName, Field.ID)) {
type = ScriptType.STORED;
if (token == XContentParser.Token.VALUE_STRING) {
script = parser.text();
} else {
throw new ElasticsearchParseException("expected a string value for field [{}], but found [{}]", currentFieldName,
token);
}
} else if (ParseFieldMatcher.STRICT.match(currentFieldName, Field.LANG)) {
if (token == XContentParser.Token.VALUE_STRING) {
lang = parser.text();
} else {
throw new ElasticsearchParseException("expected a string value for field [{}], but found [{}]", currentFieldName,
token);
}
} else if (ParseFieldMatcher.STRICT.match(currentFieldName, Field.PARAMS)) {
if (token == XContentParser.Token.START_OBJECT) {
params = parser.map();
} else {
throw new ElasticsearchParseException("expected an object for field [{}], but found [{}]", currentFieldName, token);
}
} else {
throw new ElasticsearchParseException("unexpected field [{}]", currentFieldName);
}
}
if (script == null) {
throw new ElasticsearchParseException("expected one of [{}], [{}] or [{}] fields, but found none",
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 WatcherScript(script, type, lang, params);
}
public static Builder.Inline inline(String script) {
return new Builder.Inline(script);
}
public static Builder.File file(String file) {
return new Builder.File(file);
}
public static Builder.Indexed indexed(String id) {
return new Builder.Indexed(id);
}
public static Builder.DefaultType defaultType(String text) {
return new Builder.DefaultType(text);
}
public abstract static class Builder<B extends Builder> {
protected final ScriptType type;
protected final String script;
protected String lang;
protected Map<String, Object> params;
protected Builder(String script, ScriptType type) {
this.script = script;
this.type = type;
}
public B lang(String lang) {
this.lang = lang;
return (B) this;
}
public B params(Map<String, Object> params) {
this.params = params;
return (B) this;
}
public abstract WatcherScript build();
public static class Inline extends Builder<Inline> {
public Inline(String script) {
super(script, ScriptType.INLINE);
}
@Override
public WatcherScript build() {
return new WatcherScript(script, type, lang, params);
}
}
public static class File extends Builder<File> {
public File(String file) {
super(file, ScriptType.FILE);
}
@Override
public WatcherScript build() {
return new WatcherScript(script, type, lang, params);
}
}
public static class Indexed extends Builder<Indexed> {
public Indexed(String id) {
super(id, ScriptType.STORED);
}
@Override
public WatcherScript build() {
return new WatcherScript(script, type, lang, params);
}
}
public static class DefaultType extends Builder<DefaultType> {
public DefaultType(String text) {
super(text, null);
}
@Override
public WatcherScript build() {
return new WatcherScript(script, type, lang, params);
}
}
}
interface Field {
ParseField INLINE = new ParseField("inline");
ParseField FILE = new ParseField("file");
ParseField ID = new ParseField("id");
ParseField LANG = new ParseField("lang");
ParseField PARAMS = new ParseField("params");
}
private static class WatcherScriptContext implements ScriptContext {
@Override
public String getKey() {
return CTX_PLUGIN.getKey();
}
}
}

View File

@ -16,7 +16,8 @@ import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import java.io.IOException;
import java.util.ArrayList;
@ -37,7 +38,7 @@ public class WatcherSearchTemplateRequest implements ToXContent {
private final String[] types;
private final SearchType searchType;
private final IndicesOptions indicesOptions;
private final WatcherScript template;
private final Script template;
private final BytesReference searchSource;
@ -49,12 +50,12 @@ public class WatcherSearchTemplateRequest implements ToXContent {
this.indicesOptions = indicesOptions;
// Here we convert a watch search request body into an inline search template,
// this way if any Watcher related context variables are used, they will get resolved.
this.template = WatcherScript.inline(searchSource.utf8ToString()).lang(DEFAULT_LANG).build();
this.template = new Script(searchSource.utf8ToString(), ScriptService.ScriptType.INLINE, DEFAULT_LANG, null);
this.searchSource = null;
}
public WatcherSearchTemplateRequest(String[] indices, String[] types, SearchType searchType, IndicesOptions indicesOptions,
WatcherScript template) {
Script template) {
this.indices = indices;
this.types = types;
this.searchType = searchType;
@ -73,7 +74,7 @@ public class WatcherSearchTemplateRequest implements ToXContent {
}
private WatcherSearchTemplateRequest(String[] indices, String[] types, SearchType searchType, IndicesOptions indicesOptions,
BytesReference searchSource, WatcherScript template) {
BytesReference searchSource, Script template) {
this.indices = indices;
this.types = types;
this.searchType = searchType;
@ -83,7 +84,7 @@ public class WatcherSearchTemplateRequest implements ToXContent {
}
@Nullable
public WatcherScript getTemplate() {
public Script getTemplate() {
return template;
}
@ -108,11 +109,11 @@ public class WatcherSearchTemplateRequest implements ToXContent {
return searchSource;
}
public WatcherScript getOrCreateTemplate() {
public Script getOrCreateTemplate() {
if (template != null) {
return template;
} else {
return WatcherScript.inline(searchSource.utf8ToString()).lang(DEFAULT_LANG).build();
return new Script(searchSource.utf8ToString(), ScriptService.ScriptType.INLINE, DEFAULT_LANG, null);
}
}
@ -164,7 +165,7 @@ public class WatcherSearchTemplateRequest implements ToXContent {
List<String> types = new ArrayList<>();
IndicesOptions indicesOptions = DEFAULT_INDICES_OPTIONS;
BytesReference searchSource = null;
WatcherScript template = null;
Script template = null;
XContentParser.Token token;
String currentFieldName = null;
@ -247,7 +248,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 = WatcherScript.parse(parser, DEFAULT_LANG);
template = Script.parse(parser, ParseFieldMatcher.STRICT, DEFAULT_LANG);
} else {
throw new ElasticsearchParseException("could not read search request. unexpected object field [" +
currentFieldName + "]");

View File

@ -15,12 +15,13 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xpack.watcher.Watcher;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.Variables;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.watch.Payload;
import java.io.IOException;
@ -44,7 +45,7 @@ public class WatcherSearchTemplateService extends AbstractComponent {
this.parseFieldMatcher = new ParseFieldMatcher(settings);
}
public BytesReference renderTemplate(WatcherScript templatePrototype,
public BytesReference renderTemplate(Script source,
WatchExecutionContext ctx,
Payload payload) throws IOException {
// Due the inconsistency with templates in ES 1.x, we maintain our own template format.
@ -52,22 +53,13 @@ public class WatcherSearchTemplateService extends AbstractComponent {
Map<String, Object> watcherContextParams = Variables.createCtxModel(ctx, payload);
// 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
if (templatePrototype.params() != null) {
watcherContextParams.putAll(templatePrototype.params());
if (source.getParams() != null) {
watcherContextParams.putAll(source.getParams());
}
WatcherScript.Builder builder;
if (templatePrototype.type() == ScriptService.ScriptType.INLINE) {
builder = WatcherScript.inline(templatePrototype.script());
} else if (templatePrototype.type() == ScriptService.ScriptType.FILE) {
builder = WatcherScript.file(templatePrototype.script());
} else if (templatePrototype.type() == ScriptService.ScriptType.STORED) {
builder = WatcherScript.indexed(templatePrototype.script());
} else {
builder = WatcherScript.defaultType(templatePrototype.script());
}
WatcherScript template = builder.lang(templatePrototype.lang()).params(watcherContextParams).build();
CompiledScript compiledScript = scriptService.compile(template.toScript(), WatcherScript.CTX, Collections.emptyMap());
return (BytesReference) scriptService.executable(compiledScript, template.params()).run();
Script template = new Script(source.getScript(), source.getType(), source.getLang(), watcherContextParams,
source.getContentType());
CompiledScript compiledScript = scriptService.compile(template, Watcher.SCRIPT_CONTEXT, Collections.emptyMap());
return (BytesReference) scriptService.executable(compiledScript, template.getParams()).run();
}
public SearchRequest toSearchRequest(WatcherSearchTemplateRequest request) throws IOException {

View File

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

View File

@ -8,9 +8,10 @@ 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.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.watcher.Watcher;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.transform.ExecutableTransform;
import org.elasticsearch.xpack.watcher.watch.Payload;
@ -22,9 +23,6 @@ import java.util.Map;
import static org.elasticsearch.xpack.watcher.support.Exceptions.invalidScript;
import static org.elasticsearch.xpack.watcher.support.Variables.createCtxModel;
/**
*
*/
public class ExecutableScriptTransform extends ExecutableTransform<ScriptTransform, ScriptTransform.Result> {
private final ScriptService scriptService;
@ -33,12 +31,11 @@ public class ExecutableScriptTransform extends ExecutableTransform<ScriptTransfo
public ExecutableScriptTransform(ScriptTransform transform, ESLogger logger, ScriptService scriptService) {
super(transform, logger);
this.scriptService = scriptService;
WatcherScript script = transform.getScript();
Script script = transform.getScript();
try {
compiledScript = scriptService.compile(script.toScript(), WatcherScript.CTX, Collections.emptyMap());
compiledScript = scriptService.compile(script, Watcher.SCRIPT_CONTEXT, Collections.emptyMap());
} catch (Exception e) {
throw invalidScript("failed to compile script [{}] with lang [{}] of type [{}]", e, script.script(), script.lang(),
script.type(), e);
throw invalidScript("failed to compile script [{}]", e, script, e);
}
}
@ -54,9 +51,11 @@ public class ExecutableScriptTransform extends ExecutableTransform<ScriptTransfo
ScriptTransform.Result doExecute(WatchExecutionContext ctx, Payload payload) throws IOException {
WatcherScript script = transform.getScript();
Script script = transform.getScript();
Map<String, Object> model = new HashMap<>();
model.putAll(script.params());
if (script.getParams() != null) {
model.putAll(script.getParams());
}
model.putAll(createCtxModel(ctx, payload));
ExecutableScript executable = scriptService.executable(compiledScript, model);
Object value = executable.run();

View File

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

View File

@ -11,8 +11,8 @@ import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.script.Script;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
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;
@ -39,7 +39,7 @@ public class ExecutableSearchTransform extends ExecutableTransform<SearchTransfo
public SearchTransform.Result execute(WatchExecutionContext ctx, Payload payload) {
WatcherSearchTemplateRequest request = null;
try {
WatcherScript template = transform.getRequest().getOrCreateTemplate();
Script template = transform.getRequest().getOrCreateTemplate();
BytesReference renderedTemplate = searchTemplateService.renderTemplate(template, ctx, payload);
// We need to make a copy, so that we don't modify the original instance that we keep around in a watch:
request = new WatcherSearchTemplateRequest(transform.getRequest(), renderedTemplate);

View File

@ -17,9 +17,6 @@ import java.util.Objects;
import static org.elasticsearch.xpack.watcher.support.WatcherUtils.responseToData;
/**
*
*/
public interface Payload extends ToXContent {
Simple EMPTY = new Simple(Collections.<String, Object>emptyMap());

View File

@ -10,7 +10,6 @@ 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;
@ -69,10 +68,8 @@ public class SleepScriptEngine implements ScriptEngineService {
public void close() throws IOException {
}
public static WatcherScript sleepScript(long millis) {
return new WatcherScript.Builder.Inline("")
.lang("sleep")
.params(Collections.singletonMap("millis", millis)).build();
public static Script sleepScript(long millis) {
return new Script("", ScriptService.ScriptType.INLINE, "sleep", Collections.singletonMap("millis", millis));
}
@Override

View File

@ -12,6 +12,7 @@ import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.index.Index;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchShardTarget;
@ -21,8 +22,8 @@ import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.InternalSearchHits;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.watch.Payload;
@ -68,7 +69,7 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa
@Override
public String pluginScriptLang() {
return WatcherScript.DEFAULT_LANG;
return WATCHER_LANG;
}
}
@ -86,7 +87,7 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa
ScriptService scriptService = internalCluster().getInstance(ScriptService.class);
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(WatcherScript.inline("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5").build()),
new ScriptCondition(new Script("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5")),
logger, scriptService);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
@ -106,7 +107,7 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa
public void testExecuteAccessHits() throws Exception {
ScriptService scriptService = internalCluster().getInstance(ScriptService.class);
ExecutableScriptCondition condition = new ExecutableScriptCondition(new ScriptCondition(
WatcherScript.inline("ctx.payload.hits?.hits[0]?._score == 1.0").build()), logger, scriptService);
new Script("ctx.payload.hits?.hits[0]?._score == 1.0")), 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

@ -17,6 +17,8 @@ import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.env.Environment;
import org.elasticsearch.script.GeneralScriptException;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptContextRegistry;
import org.elasticsearch.script.ScriptEngineRegistry;
import org.elasticsearch.script.ScriptEngineService;
@ -26,8 +28,9 @@ import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.script.ScriptSettings;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.watch.Payload;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
@ -66,7 +69,7 @@ public class ScriptConditionTests extends ESTestCase {
scripts.put("null.foo", s -> {
throw new ScriptException("Error evaluating null.foo", new IllegalArgumentException(), emptyList(),
"null.foo", WatcherScript.DEFAULT_LANG);
"null.foo", AbstractWatcherIntegrationTestCase.WATCHER_LANG);
});
scripts.put("ctx.payload.hits.total > 1", vars -> {
@ -80,10 +83,10 @@ public class ScriptConditionTests extends ESTestCase {
return total > threshold;
});
ScriptEngineService engine = new MockScriptEngine(WatcherScript.DEFAULT_LANG, scripts);
ScriptEngineService engine = new MockScriptEngine(AbstractWatcherIntegrationTestCase.WATCHER_LANG, scripts);
ScriptEngineRegistry registry = new ScriptEngineRegistry(singleton(engine));
ScriptContextRegistry contextRegistry = new ScriptContextRegistry(singleton(WatcherScript.CTX_PLUGIN));
ScriptContextRegistry contextRegistry = new ScriptContextRegistry(singleton(new ScriptContext.Plugin("xpack", "watch")));
ScriptSettings scriptSettings = new ScriptSettings(registry, contextRegistry);
Settings settings = Settings.builder()
@ -96,15 +99,14 @@ public class ScriptConditionTests extends ESTestCase {
public void testExecute() throws Exception {
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(WatcherScript.inline("ctx.payload.hits.total > 1").build()), logger, scriptService);
new ScriptCondition(new Script("ctx.payload.hits.total > 1")), 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 {
WatcherScript script = WatcherScript.inline("ctx.payload.hits.total > threshold")
.lang(WatcherScript.DEFAULT_LANG).params(singletonMap("threshold", 1)).build();
Script script = new Script("ctx.payload.hits.total > threshold", ScriptType.INLINE, null, singletonMap("threshold", 1));
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));
@ -188,7 +190,7 @@ public class ScriptConditionTests extends ESTestCase {
public void testScriptConditionThrowException() throws Exception {
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(WatcherScript.inline("null.foo").build()), logger, scriptService);
new ScriptCondition(new Script("null.foo")), 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));
@ -197,7 +199,7 @@ public class ScriptConditionTests extends ESTestCase {
public void testScriptConditionReturnObjectThrowsException() throws Exception {
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(WatcherScript.inline("return new Object()").build()), logger, scriptService);
new ScriptCondition(new Script("return new Object()")), 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));
@ -207,7 +209,7 @@ public class ScriptConditionTests extends ESTestCase {
public void testScriptConditionAccessCtx() throws Exception {
ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(WatcherScript.inline("ctx.trigger.scheduled_time.getMillis() < new Date().time").build()),
new ScriptCondition(new Script("ctx.trigger.scheduled_time.getMillis() < new Date().time")),
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

@ -12,6 +12,9 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.support.clock.SystemClock;
import org.elasticsearch.xpack.watcher.WatcherService;
import org.elasticsearch.xpack.watcher.actions.ActionStatus;
@ -22,7 +25,6 @@ import org.elasticsearch.xpack.watcher.condition.script.ScriptCondition;
import org.elasticsearch.xpack.watcher.history.HistoryStore;
import org.elasticsearch.xpack.watcher.history.WatchRecord;
import org.elasticsearch.xpack.watcher.input.simple.SimpleInput;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.xcontent.ObjectPath;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.transport.actions.delete.DeleteWatchResponse;
@ -70,7 +72,6 @@ import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase {
@Override
@ -110,7 +111,7 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase {
@Override
public String pluginScriptLang() {
return WatcherScript.DEFAULT_LANG;
return WATCHER_LANG;
}
}
@ -349,7 +350,7 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase {
}
public void testWatchExecutionDuration() throws Exception {
WatcherScript script = new WatcherScript.Builder.Inline("sleep").params(singletonMap("millis", 100L)).build();
Script script = new Script("sleep", ScriptService.ScriptType.INLINE, null, singletonMap("millis", 100L));
WatchSourceBuilder watchBuilder = watchBuilder()
.trigger(schedule(cron("0 0 0 1 * ? 2099")))
.input(simpleInput("foo", "bar"))
@ -365,7 +366,7 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase {
}
public void testForceDeletionOfLongRunningWatch() throws Exception {
WatcherScript script = new WatcherScript.Builder.Inline("sleep").params(singletonMap("millis", 10000L)).build();
Script script = new Script("sleep", ScriptService.ScriptType.INLINE, null, singletonMap("millis", 10000L));
WatchSourceBuilder watchBuilder = watchBuilder()
.trigger(schedule(cron("0 0 0 1 * ? 2099")))
.input(simpleInput("foo", "bar"))

View File

@ -10,6 +10,8 @@ import com.google.common.collect.Lists;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xpack.watcher.client.WatchSourceBuilder;
@ -17,7 +19,6 @@ import org.elasticsearch.xpack.watcher.condition.Condition;
import org.elasticsearch.xpack.watcher.condition.compare.CompareCondition;
import org.elasticsearch.xpack.watcher.execution.ExecutionState;
import org.elasticsearch.xpack.watcher.input.Input;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.transport.actions.put.PutWatchResponse;
@ -265,11 +266,8 @@ public class HistoryActionConditionTests extends AbstractWatcherIntegrationTestC
* @return Never {@code null}
*/
private static Condition.Builder mockScriptCondition(String inlineScript) {
WatcherScript.Builder builder = new WatcherScript.Builder.Inline(inlineScript);
builder.lang(MockScriptPlugin.NAME);
return scriptCondition(builder);
Script script = new Script(inlineScript, ScriptService.ScriptType.INLINE, MockScriptPlugin.NAME, null, null);
return scriptCondition(script);
}
}

View File

@ -8,8 +8,8 @@ package org.elasticsearch.xpack.watcher.history;
import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.watcher.execution.ExecutionState;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.transport.actions.put.PutWatchResponse;
@ -59,7 +59,7 @@ public class HistoryTemplateTransformMappingsTests extends AbstractWatcherIntegr
@Override
public String pluginScriptLang() {
return WatcherScript.DEFAULT_LANG;
return WATCHER_LANG;
}
}

View File

@ -1,75 +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.watcher.support;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
public class WatcherScriptTests extends ESTestCase {
public void testParseScript() throws IOException {
final Map<String, Object> params =
randomFrom(Collections.<String, Object>emptyMap(), Collections.singletonMap("foo", (Object)"bar"), null);
WatcherScript script = new WatcherScript(randomAsciiOfLengthBetween(1, 5),
randomFrom(ScriptType.values()),
randomFrom("custom", "mustache", null),
params);
try (XContentParser parser = createParser(script)) {
assertThat(WatcherScript.parse(parser), equalTo(script));
}
}
public void testParseScriptWithCustomLang() throws IOException {
final String lang = randomFrom("custom", "painful");
final WatcherScript script = new WatcherScript("my-script", randomFrom(ScriptType.values()), lang, null);
try (XContentParser parser = createParser(script)) {
WatcherScript result = WatcherScript.parse(parser, WatcherScript.DEFAULT_LANG);
assertThat(result.script(), equalTo(script.script()));
assertThat(result.type(), equalTo(script.type()));
assertThat(result.lang(), equalTo(lang));
assertThat(result.params(), equalTo(script.params()));
}
}
public void testParseScriptWithDefaultLang() throws IOException {
final WatcherScript script = new WatcherScript("my-script", randomFrom(ScriptType.values()), null, null);
try (XContentParser parser = createParser(script)) {
WatcherScript result = WatcherScript.parse(parser, WatcherScript.DEFAULT_LANG);
assertThat(result.script(), equalTo(script.script()));
assertThat(result.type(), equalTo(script.type()));
assertThat(result.lang(), equalTo(WatcherScript.DEFAULT_LANG));
assertThat(result.params(), equalTo(script.params()));
}
}
private static XContentParser createParser(WatcherScript watcherScript) throws IOException {
final XContent xContent = randomFrom(XContentType.values()).xContent();
XContentBuilder builder = XContentBuilder.builder(xContent);
watcherScript.toXContent(builder, ToXContent.EMPTY_PARAMS);
XContentParser parser = XContentHelper.createParser(builder.bytes());
assertNull(parser.currentToken());
parser.nextToken();
return parser;
}
}

View File

@ -16,6 +16,8 @@ import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.support.clock.SystemClock;
@ -94,7 +96,7 @@ public class WatcherUtilsTests extends ESTestCase {
SearchType expectedSearchType = getRandomSupportedSearchType();
BytesReference expectedSource = null;
WatcherScript expectedTemplate = null;
Script expectedTemplate = null;
WatcherSearchTemplateRequest request;
if (randomBoolean()) {
Map<String, Object> params = new HashMap<>();
@ -105,10 +107,8 @@ public class WatcherUtilsTests extends ESTestCase {
}
}
String text = randomAsciiOfLengthBetween(1, 5);
expectedTemplate = randomFrom(WatcherScript.inline(text), WatcherScript.file(text), WatcherScript.indexed(text))
.lang(randomBoolean() ? null : "mustache")
.params(params)
.build();
ScriptService.ScriptType scriptType = randomFrom(ScriptService.ScriptType.values());
expectedTemplate = new Script(text, scriptType, randomBoolean() ? null : "mustache", params);
request = new WatcherSearchTemplateRequest(expectedIndices, expectedTypes, expectedSearchType,
expectedIndicesOptions, expectedTemplate);
} else {
@ -132,14 +132,14 @@ public class WatcherUtilsTests extends ESTestCase {
assertThat(result.getSearchType(), equalTo(expectedSearchType));
assertNotNull(result.getTemplate());
assertThat(result.getTemplate().lang(), equalTo("mustache"));
assertThat(result.getTemplate().getLang(), equalTo("mustache"));
if (expectedSource == null) {
assertThat(result.getTemplate().script(), equalTo(expectedTemplate.script()));
assertThat(result.getTemplate().type(), equalTo(expectedTemplate.type()));
assertThat(result.getTemplate().params(), equalTo(expectedTemplate.params()));
assertThat(result.getTemplate().getScript(), equalTo(expectedTemplate.getScript()));
assertThat(result.getTemplate().getType(), equalTo(expectedTemplate.getType()));
assertThat(result.getTemplate().getParams(), equalTo(expectedTemplate.getParams()));
} else {
assertThat(result.getTemplate().script(), equalTo(expectedSource.utf8ToString()));
assertThat(result.getTemplate().type(), equalTo(ScriptType.INLINE));
assertThat(result.getTemplate().getScript(), equalTo(expectedSource.utf8ToString()));
assertThat(result.getTemplate().getType(), equalTo(ScriptType.INLINE));
}
}
@ -195,7 +195,7 @@ public class WatcherUtilsTests extends ESTestCase {
source = searchSourceBuilder.buildAsBytes(XContentType.JSON);
builder.rawField("body", source);
}
WatcherScript template = null;
Script template = null;
if (randomBoolean()) {
Map<String, Object> params = new HashMap<>();
if (randomBoolean()) {
@ -205,10 +205,8 @@ public class WatcherUtilsTests extends ESTestCase {
}
}
String text = randomAsciiOfLengthBetween(1, 5);
template = randomFrom(WatcherScript.inline(text), WatcherScript.file(text), WatcherScript.indexed(text))
.lang(randomBoolean() ? null : "mustache")
.params(params)
.build();
ScriptService.ScriptType scriptType = randomFrom(ScriptService.ScriptType.values());
template = new Script(text, scriptType, randomBoolean() ? null : "mustache", params);
builder.field("template", template);
}
builder.endObject();
@ -229,10 +227,10 @@ public class WatcherUtilsTests extends ESTestCase {
if (template == null) {
assertThat(result.getTemplate(), nullValue());
} else {
assertThat(result.getTemplate().script(), equalTo(template.script()));
assertThat(result.getTemplate().type(), equalTo(template.type()));
assertThat(result.getTemplate().params(), equalTo(template.params()));
assertThat(result.getTemplate().lang(), equalTo("mustache"));
assertThat(result.getTemplate().getScript(), equalTo(template.getScript()));
assertThat(result.getTemplate().getType(), equalTo(template.getType()));
assertThat(result.getTemplate().getParams(), equalTo(template.getParams()));
assertThat(result.getTemplate().getLang(), equalTo("mustache"));
}
}

View File

@ -35,9 +35,9 @@ public class WatcherSearchTemplateRequestTests extends ESTestCase {
WatcherSearchTemplateRequest result = WatcherSearchTemplateRequest.fromXContent(parser, randomFrom(SearchType.values()));
assertNotNull(result.getTemplate());
assertThat(result.getTemplate().script(), equalTo(expectedScript));
assertThat(result.getTemplate().lang(), equalTo(expectedLang));
assertThat(result.getTemplate().params(), equalTo(expectedParams));
assertThat(result.getTemplate().getScript(), equalTo(expectedScript));
assertThat(result.getTemplate().getLang(), equalTo(expectedLang));
assertThat(result.getTemplate().getParams(), equalTo(expectedParams));
} catch (IOException e) {
fail("Failed to parse watch search request: " + e.getMessage());
}

View File

@ -24,6 +24,7 @@ import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.script.ScriptSettings;
import org.elasticsearch.xpack.XPackSettings;
import org.elasticsearch.xpack.monitoring.Monitoring;
import org.elasticsearch.plugins.Plugin;
@ -107,6 +108,8 @@ import static org.hamcrest.core.IsNot.not;
@ClusterScope(scope = SUITE, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false, maxNumDataNodes = 3)
public abstract class AbstractWatcherIntegrationTestCase extends ESIntegTestCase {
public static final String WATCHER_LANG = ScriptSettings.DEFAULT_LANG;
private static final boolean timeWarpEnabled = SystemPropertyUtil.getBoolean("tests.timewarp", true);
private TimeWarp timeWarp;

View File

@ -18,6 +18,7 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.env.Environment;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptContextRegistry;
import org.elasticsearch.script.ScriptEngineRegistry;
import org.elasticsearch.script.ScriptService;
@ -26,6 +27,7 @@ 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.XPackPlugin;
import org.elasticsearch.xpack.common.http.HttpClient;
import org.elasticsearch.xpack.common.http.HttpMethod;
import org.elasticsearch.xpack.common.http.HttpRequestTemplate;
@ -49,7 +51,6 @@ import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.execution.Wid;
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;
@ -247,7 +248,8 @@ public final class WatcherTestUtils {
.put("script.indexed", "true")
.put("path.home", createTempDir())
.build();
ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(Collections.singletonList(WatcherScript.CTX_PLUGIN));
ScriptContextRegistry scriptContextRegistry =
new ScriptContextRegistry(Collections.singletonList(new ScriptContext.Plugin("xpack", "watch")));
ScriptEngineRegistry scriptEngineRegistry =
new ScriptEngineRegistry(Collections.emptyList());

View File

@ -10,12 +10,13 @@ import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.builder.SearchSourceBuilder;
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.WatcherScript;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.support.xcontent.XContentSource;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
@ -256,7 +257,7 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase {
.setSource(jsonBuilder().startObject().field("template").value(searchSourceBuilder).endObject().bytes())
.get());
WatcherScript template = WatcherScript.indexed("my-template").lang("mustache").build();
Script template = new Script("my-template", ScriptService.ScriptType.STORED, "mustache", null);
WatcherSearchTemplateRequest searchRequest = new WatcherSearchTemplateRequest(new String[]{"events"}, new String[0],
SearchType.DEFAULT, WatcherSearchTemplateRequest.DEFAULT_INDICES_OPTIONS, template);
testConditionSearch(searchRequest);

View File

@ -9,8 +9,8 @@ import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.watcher.client.WatcherClient;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.xcontent.ObjectPath;
import org.elasticsearch.xpack.watcher.support.xcontent.XContentSource;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
@ -110,7 +110,7 @@ public class ExecutionVarsIntegrationTests extends AbstractWatcherIntegrationTes
@Override
public String pluginScriptLang() {
return WatcherScript.DEFAULT_LANG;
return WATCHER_LANG;
}
}

View File

@ -19,11 +19,10 @@ import org.elasticsearch.script.MockMustacheScriptEngine;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.search.aggregations.AggregatorParsers;
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.XPackPlugin;
import org.elasticsearch.xpack.watcher.actions.ExecutableActions;
import org.elasticsearch.xpack.watcher.condition.always.ExecutableAlwaysCondition;
import org.elasticsearch.xpack.watcher.execution.TriggeredExecutionContext;
@ -34,7 +33,6 @@ 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.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;
@ -178,7 +176,7 @@ public class SearchInputTests extends ESIntegTestCase {
@Override
public ScriptContext.Plugin getCustomScriptContexts() {
return WatcherScript.CTX_PLUGIN;
return new ScriptContext.Plugin("xpack", "watch");
}
}
}

View File

@ -19,12 +19,14 @@ import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.script.MockMustacheScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.common.text.TextTemplate;
import org.elasticsearch.xpack.watcher.actions.ExecutableActions;
import org.elasticsearch.xpack.watcher.condition.always.ExecutableAlwaysCondition;
@ -32,7 +34,6 @@ 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.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;
@ -230,7 +231,7 @@ public class SearchTransformTests extends ESIntegTestCase {
}
if (templateName != null) {
assertThat(executable.transform().getRequest().getTemplate(),
equalTo(WatcherScript.file("template1").lang("mustache").build()));
equalTo(new Script("template1", ScriptService.ScriptType.FILE, "mustache", null)));
}
assertThat(executable.transform().getRequest().getSearchSource().utf8ToString(), equalTo("{\"query\":{\"match_all\":{}}}"));
assertThat(executable.transform().getTimeout(), equalTo(readTimeout));
@ -301,7 +302,7 @@ public class SearchTransformTests extends ESIntegTestCase {
@Override
public ScriptContext.Plugin getCustomScriptContexts() {
return WatcherScript.CTX_PLUGIN;
return new ScriptContext.Plugin("xpack", "watch");
}
}
}

View File

@ -0,0 +1,95 @@
/*
* 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.watcher.test.integration;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
import org.elasticsearch.Version;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.xpack.watcher.support.xcontent.ObjectPath;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.transport.actions.get.GetWatchResponse;
import org.elasticsearch.xpack.watcher.watch.WatchStore;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0)
@LuceneTestCase.SuppressFileSystems("ExtrasFS")
public class WatcherBackwardsCompatibilityTests extends AbstractWatcherIntegrationTestCase {
private static final String INDEX_NAME = WatchStore.INDEX;
private static final String TYPE_NAME = WatchStore.DOC_TYPE;
@Override
protected boolean enableSecurity() {
return false;
}
@Override
protected boolean timeWarped() {
return false;
}
public void testWatchLoadedSuccessfullyAfterUpgrade() throws Exception {
// setup node
Path dataDir = createTempDir();
Path clusterDir = Files.createDirectory(dataDir.resolve(cluster().getClusterName()));
try (InputStream stream = WatcherBackwardsCompatibilityTests.class.
getResourceAsStream("/bwc_indices/bwc_index_2_3_5.zip")) {
TestUtil.unzip(stream, clusterDir);
}
Settings.Builder nodeSettings = Settings.builder()
.put(super.nodeSettings(0))
.put(Environment.PATH_DATA_SETTING.getKey(), dataDir);
internalCluster().startNode(nodeSettings.build());
ensureYellow();
// verify cluster state:
assertBusy(() -> {
ClusterState state = client().admin().cluster().prepareState().get().getState();
assertThat(state.metaData().indices().size(), equalTo(1)); // only the .watches index
// (the watch has a very high interval (99 weeks))
assertThat(state.metaData().indices().get(INDEX_NAME), notNullValue());
assertThat(state.metaData().indices().get(INDEX_NAME).getCreationVersion(), equalTo(Version.V_2_3_5));
assertThat(state.metaData().indices().get(INDEX_NAME).getUpgradedVersion(), equalTo(Version.CURRENT));
assertThat(state.metaData().indices().get(INDEX_NAME).getMappings().size(), equalTo(1));
assertThat(state.metaData().indices().get(INDEX_NAME).getMappings().get(TYPE_NAME), notNullValue());
});
// verify existing watcher documents:
SearchResponse searchResponse = client().prepareSearch(INDEX_NAME)
.setTypes(TYPE_NAME)
.get();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
assertThat(searchResponse.getHits().getAt(0).id(), equalTo("log_error_watch"));
// Verify that we can get the watch, which means the watch stored in ES 2.3.5 cluster has been successfully
// loaded with the current version of ES:
ensureWatcherStarted();
assertThat(watcherClient().prepareWatcherStats().get().getWatchesCount(), equalTo(1L));
GetWatchResponse getWatchResponse = watcherClient().prepareGetWatch("log_error_watch").get();
assertThat(getWatchResponse.isFound(), is(true));
Map<String, Object> watchSourceAsMap = getWatchResponse.getSource().getAsMap();
assertThat(ObjectPath.eval("trigger.schedule.interval", watchSourceAsMap), equalTo("99w"));
assertThat(ObjectPath.eval("input.search.request.body.query.bool.filter.1.range.date.lte", watchSourceAsMap),
equalTo("{{ctx.trigger.scheduled_time}}"));
assertThat(ObjectPath.eval("actions.log_error.logging.text", watchSourceAsMap),
equalTo("Found {{ctx.payload.hits.total}} errors in the logs"));
}
}

View File

@ -13,7 +13,9 @@ import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.env.Environment;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.transport.actions.put.PutWatchResponse;
@ -104,15 +106,15 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
@Override
public String pluginScriptLang() {
return WatcherScript.DEFAULT_LANG;
return WATCHER_LANG;
}
}
public void testScriptTransform() throws Exception {
final WatcherScript script;
final Script script;
if (randomBoolean()) {
logger.info("testing script transform with an inline script");
script = WatcherScript.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build();
script = new Script("return [key3 : ctx.payload.key1 + ctx.payload.key2]");
} else if (randomBoolean()) {
logger.info("testing script transform with an indexed script");
assertAcked(client().admin().cluster().preparePutStoredScript()
@ -120,10 +122,10 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
.setScriptLang("groovy")
.setSource(new BytesArray("{\"script\" : \"return [key3 : ctx.payload.key1 + ctx.payload.key2]\"}"))
.get());
script = WatcherScript.indexed("my-script").lang("groovy").build();
script = new Script("my-script", ScriptService.ScriptType.STORED, "groovy", null);
} else {
logger.info("testing script transform with a file script");
script = WatcherScript.file("my-script").lang("groovy").build();
script = new Script("my-script", ScriptService.ScriptType.FILE, "groovy", null);
}
// put a watch that has watch level transform:
@ -217,8 +219,8 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
}
public void testChainTransform() throws Exception {
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();
Script script1 = new Script("return [key3 : ctx.payload.key1 + ctx.payload.key2]");
Script script2 = new Script("return [key4 : ctx.payload.key3 + 10]");
// put a watch that has watch level transform:
PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id1")
.setSource(watchBuilder()

View File

@ -13,13 +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.Script;
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.Watcher;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.WatcherScript;
import org.elasticsearch.xpack.watcher.support.Variables;
import org.elasticsearch.xpack.watcher.transform.Transform;
import org.elasticsearch.xpack.watcher.watch.Payload;
@ -46,9 +47,6 @@ import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
*
*/
public class ScriptTransformTests extends ESTestCase {
ThreadPool tp = null;
@ -66,9 +64,9 @@ public class ScriptTransformTests extends ESTestCase {
ScriptService service = mock(ScriptService.class);
ScriptType type = randomFrom(ScriptType.values());
Map<String, Object> params = Collections.emptyMap();
WatcherScript script = scriptBuilder(type, "_script").lang("_lang").params(params).build();
Script script = new Script("_script", type, "_lang", params);
CompiledScript compiledScript = mock(CompiledScript.class);
when(service.compile(script.toScript(), WatcherScript.CTX, Collections.emptyMap())).thenReturn(compiledScript);
when(service.compile(script, Watcher.SCRIPT_CONTEXT, Collections.emptyMap())).thenReturn(compiledScript);
ExecutableScriptTransform transform = new ExecutableScriptTransform(new ScriptTransform(script), logger, service);
WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD);
@ -94,9 +92,9 @@ public class ScriptTransformTests extends ESTestCase {
ScriptService service = mock(ScriptService.class);
ScriptType type = randomFrom(ScriptType.values());
Map<String, Object> params = Collections.emptyMap();
WatcherScript script = scriptBuilder(type, "_script").lang("_lang").params(params).build();
Script script = new Script("_script", type, "_lang", params);
CompiledScript compiledScript = mock(CompiledScript.class);
when(service.compile(script.toScript(), WatcherScript.CTX, Collections.emptyMap())).thenReturn(compiledScript);
when(service.compile(script, Watcher.SCRIPT_CONTEXT, Collections.emptyMap())).thenReturn(compiledScript);
ExecutableScriptTransform transform = new ExecutableScriptTransform(new ScriptTransform(script), logger, service);
WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD);
@ -120,9 +118,9 @@ public class ScriptTransformTests extends ESTestCase {
ScriptService service = mock(ScriptService.class);
ScriptType type = randomFrom(ScriptType.values());
Map<String, Object> params = Collections.emptyMap();
WatcherScript script = scriptBuilder(type, "_script").lang("_lang").params(params).build();
Script script = new Script("_script", type, "_lang", params);
CompiledScript compiledScript = mock(CompiledScript.class);
when(service.compile(script.toScript(), WatcherScript.CTX, Collections.emptyMap())).thenReturn(compiledScript);
when(service.compile(script, Watcher.SCRIPT_CONTEXT, Collections.emptyMap())).thenReturn(compiledScript);
ExecutableScriptTransform transform = new ExecutableScriptTransform(new ScriptTransform(script), logger, service);
WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD);
@ -155,7 +153,7 @@ public class ScriptTransformTests extends ESTestCase {
XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes());
parser.nextToken();
ExecutableScriptTransform transform = new ScriptTransformFactory(Settings.EMPTY, service).parseExecutable("_id", parser);
WatcherScript script = scriptBuilder(type, "_script").lang("_lang").params(singletonMap("key", "value")).build();
Script script = new Script("_script", type, "_lang", singletonMap("key", "value"));
assertThat(transform.transform().getScript(), equalTo(script));
}
@ -166,7 +164,7 @@ public class ScriptTransformTests extends ESTestCase {
XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes());
parser.nextToken();
ExecutableScriptTransform transform = new ScriptTransformFactory(Settings.EMPTY, service).parseExecutable("_id", parser);
assertThat(transform.transform().getScript(), equalTo(WatcherScript.defaultType("_script").build()));
assertThat(transform.transform().getScript(), equalTo(new Script("_script")));
}
public void testScriptConditionParserBadScript() throws Exception {
@ -223,16 +221,6 @@ public class ScriptTransformTests extends ESTestCase {
}
}
static WatcherScript.Builder scriptBuilder(ScriptType type, String script) {
switch (type) {
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);
}
}
static String scriptTypeField(ScriptType type) {
switch (type) {
case INLINE: return "inline";

View File

@ -17,6 +17,7 @@ import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryParser;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.test.ESTestCase;
@ -79,7 +80,6 @@ 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.WatcherScript;
import org.elasticsearch.xpack.watcher.support.init.proxy.WatcherClientProxy;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService;
import org.elasticsearch.xpack.watcher.test.WatcherTestUtils;
@ -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(WatcherScript.inline("_script").build()), logger, scriptService);
return new ExecutableScriptCondition(new ScriptCondition(new Script("_script")), logger, scriptService);
case CompareCondition.TYPE:
return new ExecutableCompareCondition(new CompareCondition("_path", randomFrom(Op.values()), randomFrom(5, "3")), logger,
SystemClock.INSTANCE);
@ -391,7 +391,7 @@ public class WatchTests extends ESTestCase {
DateTimeZone timeZone = randomBoolean() ? DateTimeZone.UTC : null;
switch (type) {
case ScriptTransform.TYPE:
return new ExecutableScriptTransform(new ScriptTransform(WatcherScript.inline("_script").build()), logger, scriptService);
return new ExecutableScriptTransform(new ScriptTransform(new Script("_script")), logger, scriptService);
case SearchTransform.TYPE:
SearchTransform transform = new SearchTransform(
templateRequest(searchSource()), timeout, timeZone);
@ -399,14 +399,14 @@ public class WatchTests extends ESTestCase {
default: // chain
SearchTransform searchTransform = new SearchTransform(
templateRequest(searchSource()), timeout, timeZone);
ScriptTransform scriptTransform = new ScriptTransform(WatcherScript.inline("_script").build());
ScriptTransform scriptTransform = new ScriptTransform(new Script("_script"));
ChainTransform chainTransform = new ChainTransform(Arrays.asList(searchTransform, scriptTransform));
return new ExecutableChainTransform(chainTransform, logger, Arrays.<ExecutableTransform>asList(
new ExecutableSearchTransform(new SearchTransform(
templateRequest(searchSource()), timeout, timeZone),
logger, client, searchTemplateService, null),
new ExecutableScriptTransform(new ScriptTransform(WatcherScript.inline("_script").build()),
new ExecutableScriptTransform(new ScriptTransform(new Script("_script")),
logger, scriptService)));
}
}