diff --git a/src/main/java/org/elasticsearch/alerts/actions/Action.java b/src/main/java/org/elasticsearch/alerts/actions/Action.java index b3f79537f27..388f42c3fa1 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/Action.java +++ b/src/main/java/org/elasticsearch/alerts/actions/Action.java @@ -8,7 +8,6 @@ package org.elasticsearch.alerts.actions; import org.elasticsearch.alerts.ExecutionContext; import org.elasticsearch.alerts.Payload; import org.elasticsearch.common.ParseField; -import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -20,9 +19,6 @@ import java.io.IOException; */ public abstract class Action implements ToXContent { - public static final String ALERT_NAME_VARIABLE = "alert_name"; - public static final String PAYLOAD_VARIABLE = "payload"; - protected final ESLogger logger; protected Action(ESLogger logger) { @@ -39,12 +35,6 @@ public abstract class Action implements ToXContent { */ public abstract R execute(ExecutionContext context, Payload payload) throws IOException; - protected static ImmutableMap templateModel(ExecutionContext ctx, Payload payload) { - return ImmutableMap.builder() - .put(ALERT_NAME_VARIABLE, ctx.alert().name()) - .put(PAYLOAD_VARIABLE, payload.data()) - .build(); - } /** * Parses xcontent to a concrete action of the same type. */ diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/EmailAction.java b/src/main/java/org/elasticsearch/alerts/actions/email/EmailAction.java index 6b4edb4be0a..2650fc51cba 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/EmailAction.java +++ b/src/main/java/org/elasticsearch/alerts/actions/email/EmailAction.java @@ -10,9 +10,9 @@ import org.elasticsearch.alerts.Payload; import org.elasticsearch.alerts.actions.Action; import org.elasticsearch.alerts.actions.ActionSettingsException; import org.elasticsearch.alerts.actions.email.service.*; +import org.elasticsearch.alerts.support.Variables; import org.elasticsearch.alerts.support.template.Template; import org.elasticsearch.common.ParseField; -import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.logging.ESLogger; @@ -22,6 +22,7 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; +import java.util.Map; import java.util.Objects; /** @@ -63,7 +64,7 @@ public class EmailAction extends Action { @Override public Result execute(ExecutionContext ctx, Payload payload) throws IOException { - ImmutableMap model = templateModel(ctx, payload); + Map model = Variables.createCtxModel(ctx, payload); Email.Builder email = Email.builder() .id(ctx.id()) diff --git a/src/main/java/org/elasticsearch/alerts/actions/webhook/WebhookAction.java b/src/main/java/org/elasticsearch/alerts/actions/webhook/WebhookAction.java index 1dc7c5c0366..9c0382c981a 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/webhook/WebhookAction.java +++ b/src/main/java/org/elasticsearch/alerts/actions/webhook/WebhookAction.java @@ -12,11 +12,11 @@ import org.elasticsearch.alerts.actions.Action; import org.elasticsearch.alerts.actions.ActionException; import org.elasticsearch.alerts.actions.ActionSettingsException; import org.elasticsearch.alerts.support.Script; +import org.elasticsearch.alerts.support.Variables; import org.elasticsearch.alerts.support.template.Template; import org.elasticsearch.alerts.support.template.XContentTemplate; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; -import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.logging.ESLogger; @@ -27,6 +27,7 @@ import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; import java.util.Locale; +import java.util.Map; /** */ @@ -55,10 +56,7 @@ public class WebhookAction extends Action { @Override public Result execute(ExecutionContext ctx, Payload payload) throws IOException { - ImmutableMap model = ImmutableMap.builder() - .put(ALERT_NAME_VARIABLE, ctx.alert().name()) - .put(PAYLOAD_VARIABLE, payload.data()) - .build(); + Map model = Variables.createCtxModel(ctx, payload); String urlText = url.render(model); String bodyText = body != null ? body.render(model) : XContentTemplate.YAML.render(model); try { diff --git a/src/main/java/org/elasticsearch/alerts/condition/script/ScriptCondition.java b/src/main/java/org/elasticsearch/alerts/condition/script/ScriptCondition.java index e9e73e39a7e..f0f960d818b 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/script/ScriptCondition.java +++ b/src/main/java/org/elasticsearch/alerts/condition/script/ScriptCondition.java @@ -55,7 +55,7 @@ public class ScriptCondition extends Condition { public Result execute(ExecutionContext ctx) throws IOException { ImmutableMap model = ImmutableMap.builder() .putAll(script.params()) - .put(Variables.PAYLOAD, ctx.payload().data()) + .putAll(Variables.createCtxModel(ctx, ctx.payload())) .build(); ExecutableScript executable = scriptService.executable(script.lang(), script.script(), script.type(), model); Object value = executable.run(); diff --git a/src/main/java/org/elasticsearch/alerts/support/Variables.java b/src/main/java/org/elasticsearch/alerts/support/Variables.java index 2576808a878..a6a75e6fba0 100644 --- a/src/main/java/org/elasticsearch/alerts/support/Variables.java +++ b/src/main/java/org/elasticsearch/alerts/support/Variables.java @@ -5,13 +5,37 @@ */ package org.elasticsearch.alerts.support; +import org.elasticsearch.alerts.ExecutionContext; +import org.elasticsearch.alerts.Payload; +import org.elasticsearch.common.joda.time.DateTime; + +import java.util.HashMap; +import java.util.Map; + /** * */ public final class Variables { - public static final String PAYLOAD = "payload"; + public static final String CTX = "ctx"; + public static final String ALERT_NAME = "alert_name"; public static final String FIRE_TIME = "fire_time"; public static final String SCHEDULED_FIRE_TIME = "scheduled_fire_time"; + public static final String PAYLOAD = "payload"; + + public static Map createCtxModel(ExecutionContext ctx, Payload payload) { + return createCtxModel(ctx.alert().name(), ctx.fireTime(), ctx.scheduledTime(), payload); + } + + public static Map createCtxModel(String alertName, DateTime fireTime, DateTime scheduledTime, Payload payload) { + Map vars = new HashMap<>(); + vars.put(ALERT_NAME, alertName); + vars.put(FIRE_TIME, fireTime); + vars.put(SCHEDULED_FIRE_TIME, scheduledTime); + vars.put(PAYLOAD, payload.data()); + Map model = new HashMap<>(); + model.put(CTX, vars); + return model; + } } diff --git a/src/main/java/org/elasticsearch/alerts/transform/ScriptTransform.java b/src/main/java/org/elasticsearch/alerts/transform/ScriptTransform.java index 0e12edde561..66c62659361 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/ScriptTransform.java +++ b/src/main/java/org/elasticsearch/alerts/transform/ScriptTransform.java @@ -19,6 +19,8 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; +import static org.elasticsearch.alerts.support.Variables.createCtxModel; + /** * */ @@ -47,7 +49,7 @@ public class ScriptTransform extends Transform { public Result apply(ExecutionContext ctx, Payload payload) throws IOException { Map model = new HashMap<>(); model.putAll(script.params()); - model.putAll(createModel(ctx, payload)); + model.putAll(createCtxModel(ctx, payload)); ExecutableScript executable = scriptService.executable(script.lang(), script.script(), script.type(), model); Object value = executable.run(); if (!(value instanceof Map)) { diff --git a/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java b/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java index 2fc37290c19..6200c908d75 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java +++ b/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java @@ -35,6 +35,7 @@ import java.util.HashMap; import java.util.Map; import static org.elasticsearch.alerts.support.AlertsDateUtils.formatDate; +import static org.elasticsearch.alerts.support.Variables.createCtxModel; /** * @@ -81,11 +82,11 @@ public class SearchTransform extends Transform { .indices(requestPrototype.indices()); if (Strings.hasLength(requestPrototype.source())) { String requestSource = XContentHelper.convertToJson(requestPrototype.source(), false); - ExecutableScript script = scriptService.executable("mustache", requestSource, ScriptService.ScriptType.INLINE, createModel(ctx, payload)); + ExecutableScript script = scriptService.executable("mustache", requestSource, ScriptService.ScriptType.INLINE, createCtxModel(ctx, payload)); request.source((BytesReference) script.unwrap(script.run()), false); } else if (requestPrototype.templateName() != null) { MapBuilder templateParams = MapBuilder.newMapBuilder(requestPrototype.templateParams()) - .putAll(flatten(createModel(ctx, payload))); + .putAll(flatten(createCtxModel(ctx, payload))); request.templateParams(templateParams.map()); request.templateName(requestPrototype.templateName()); request.templateType(requestPrototype.templateType()); diff --git a/src/main/java/org/elasticsearch/alerts/transform/Transform.java b/src/main/java/org/elasticsearch/alerts/transform/Transform.java index a84e7db2d7f..30b201bc5b9 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/Transform.java +++ b/src/main/java/org/elasticsearch/alerts/transform/Transform.java @@ -7,14 +7,11 @@ package org.elasticsearch.alerts.transform; import org.elasticsearch.alerts.ExecutionContext; import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.support.Variables; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; /** * @@ -42,14 +39,6 @@ public abstract class Transform implements ToXContent { public abstract Result apply(ExecutionContext ctx, Payload payload) throws IOException; - protected static Map createModel(ExecutionContext ctx, Payload payload) { - Map model = new HashMap<>(); - model.put(Variables.SCHEDULED_FIRE_TIME, ctx.scheduledTime()); - model.put(Variables.FIRE_TIME, ctx.fireTime()); - model.put(Variables.PAYLOAD, payload.data()); - return model; - } - public static class Result { private final String type; diff --git a/src/test/java/org/elasticsearch/alerts/actions/email/EmailActionTests.java b/src/test/java/org/elasticsearch/alerts/actions/email/EmailActionTests.java index f37dc3913de..ee64989e06a 100644 --- a/src/test/java/org/elasticsearch/alerts/actions/email/EmailActionTests.java +++ b/src/test/java/org/elasticsearch/alerts/actions/email/EmailActionTests.java @@ -17,6 +17,7 @@ import org.elasticsearch.alerts.support.template.Template; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.joda.time.DateTime; +import org.elasticsearch.common.joda.time.DateTimeZone; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -75,16 +76,23 @@ public class EmailActionTests extends ElasticsearchTestCase { } }; + DateTime now = new DateTime(DateTimeZone.UTC); + String ctxId = randomAsciiOfLength(5); ExecutionContext ctx = mock(ExecutionContext.class); when(ctx.id()).thenReturn(ctxId); Alert alert = mock(Alert.class); when(alert.name()).thenReturn("alert1"); when(ctx.alert()).thenReturn(alert); + when(ctx.fireTime()).thenReturn(now); + when(ctx.scheduledTime()).thenReturn(now); Map expectedModel = ImmutableMap.builder() - .put("alert_name", "alert1") - .put("payload", data) + .put("ctx", ImmutableMap.builder() + .put("alert_name", "alert1") + .put("payload", data) + .put("fire_time", now) + .put("scheduled_fire_time", now).build()) .build(); when(subject.render(expectedModel)).thenReturn("_subject"); diff --git a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java b/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java index 5dda86540d9..5fcbde45b7e 100644 --- a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java +++ b/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java @@ -7,6 +7,7 @@ package org.elasticsearch.alerts.condition.script; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.ShardSearchFailure; +import org.elasticsearch.alerts.Alert; import org.elasticsearch.alerts.AlertsSettingsException; import org.elasticsearch.alerts.ExecutionContext; import org.elasticsearch.alerts.Payload; @@ -14,6 +15,7 @@ import org.elasticsearch.alerts.condition.ConditionException; import org.elasticsearch.alerts.support.Script; import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.collect.ImmutableMap; +import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -58,9 +60,14 @@ public class ScriptConditionTests extends ElasticsearchTestCase { @Test public void testExecute() throws Exception { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); - ScriptCondition condition = new ScriptCondition(logger, scriptService, new Script("payload.hits.total > 1")); + ScriptCondition condition = new ScriptCondition(logger, scriptService, new Script("ctx.payload.hits.total > 1")); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); ExecutionContext ctx = mock(ExecutionContext.class); + Alert alert = mock(Alert.class); + when(alert.name()).thenReturn("_name"); + when(ctx.alert()).thenReturn(alert); + when(ctx.scheduledTime()).thenReturn(new DateTime()); + when(ctx.fireTime()).thenReturn(new DateTime()); when(ctx.payload()).thenReturn(new Payload.ActionResponse(response)); assertFalse(condition.execute(ctx).met()); } @@ -68,10 +75,15 @@ public class ScriptConditionTests extends ElasticsearchTestCase { @Test public void testExecute_MergedParams() throws Exception { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); - Script script = new Script("payload.hits.total > threshold", ScriptService.ScriptType.INLINE, ScriptService.DEFAULT_LANG, ImmutableMap.of("threshold", 1)); + Script script = new Script("ctx.payload.hits.total > threshold", ScriptService.ScriptType.INLINE, ScriptService.DEFAULT_LANG, ImmutableMap.of("threshold", 1)); ScriptCondition condition = new ScriptCondition(logger, scriptService, script); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); ExecutionContext ctx = mock(ExecutionContext.class); + Alert alert = mock(Alert.class); + when(alert.name()).thenReturn("_name"); + when(ctx.alert()).thenReturn(alert); + when(ctx.scheduledTime()).thenReturn(new DateTime()); + when(ctx.fireTime()).thenReturn(new DateTime()); when(ctx.payload()).thenReturn(new Payload.ActionResponse(response)); assertFalse(condition.execute(ctx).met()); } @@ -80,13 +92,18 @@ public class ScriptConditionTests extends ElasticsearchTestCase { public void testParser_Valid() throws Exception { ScriptCondition.Parser conditionParser = new ScriptCondition.Parser(ImmutableSettings.settingsBuilder().build(), getScriptServiceProxy(tp)); - XContentBuilder builder = createConditionContent("payload.hits.total > 1", null, null); + XContentBuilder builder = createConditionContent("ctx.payload.hits.total > 1", null, null); XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); parser.nextToken(); ScriptCondition condition = conditionParser.parse(parser); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); ExecutionContext ctx = mock(ExecutionContext.class); + Alert alert = mock(Alert.class); + when(alert.name()).thenReturn("_name"); + when(ctx.alert()).thenReturn(alert); + when(ctx.scheduledTime()).thenReturn(new DateTime()); + when(ctx.fireTime()).thenReturn(new DateTime()); when(ctx.payload()).thenReturn(new Payload.ActionResponse(response)); assertFalse(condition.execute(ctx).met()); @@ -98,6 +115,9 @@ public class ScriptConditionTests extends ElasticsearchTestCase { condition = conditionParser.parse(parser); reset(ctx); + when(ctx.alert()).thenReturn(alert); + when(ctx.scheduledTime()).thenReturn(new DateTime()); + when(ctx.fireTime()).thenReturn(new DateTime()); when(ctx.payload()).thenReturn(new Payload.ActionResponse(response)); assertTrue(condition.execute(ctx).met()); diff --git a/src/test/java/org/elasticsearch/alerts/input/search/SearchInputTests.java b/src/test/java/org/elasticsearch/alerts/input/search/SearchInputTests.java index d665f7d44c9..56d3084403a 100644 --- a/src/test/java/org/elasticsearch/alerts/input/search/SearchInputTests.java +++ b/src/test/java/org/elasticsearch/alerts/input/search/SearchInputTests.java @@ -116,8 +116,7 @@ public class SearchInputTests extends ElasticsearchIntegrationTest { data.put("baz", new ArrayList() ); SearchSourceBuilder searchSourceBuilder = searchSource().query( - filteredQuery(matchQuery("event_type", "a"), rangeFilter("_timestamp").from("{{" + Variables.SCHEDULED_FIRE_TIME + "}}||-30s").to("{{" + Variables.SCHEDULED_FIRE_TIME + "}}")) - ); + filteredQuery(matchQuery("event_type", "a"), rangeFilter("_timestamp").from("{{" + Variables.SCHEDULED_FIRE_TIME + "}}||-30s").to("{{" + Variables.SCHEDULED_FIRE_TIME + "}}"))); SearchRequest request = client() .prepareSearch() .setSearchType(SearchInput.DEFAULT_SEARCH_TYPE) diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/AlertMetadataTests.java b/src/test/java/org/elasticsearch/alerts/test/integration/AlertMetadataTests.java index d5a494ab2c8..e8e1e9e62ea 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/AlertMetadataTests.java +++ b/src/test/java/org/elasticsearch/alerts/test/integration/AlertMetadataTests.java @@ -45,7 +45,7 @@ public class AlertMetadataTests extends AbstractAlertsIntegrationTests { .source(alertSourceBuilder() .schedule(cron("0/5 * * * * ? *")) .input(searchInput(AlertsTestUtils.newInputSearchRequest("my-index").source(searchSource().query(matchAllQuery())))) - .condition(scriptCondition("payload.hits.total == 1")) + .condition(scriptCondition("ctx.payload.hits.total == 1")) .metadata(metadata)) .get(); // Wait for a no action entry to be added. (the condition search request will not match, because there are no docs in my-index) diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/AlertStatsTests.java b/src/test/java/org/elasticsearch/alerts/test/integration/AlertStatsTests.java index e73cc582764..45a6bd6cad2 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/AlertStatsTests.java +++ b/src/test/java/org/elasticsearch/alerts/test/integration/AlertStatsTests.java @@ -57,7 +57,7 @@ public class AlertStatsTests extends AbstractAlertsIntegrationTests { assertThat(response.getAlertManagerStarted(), equalTo(AlertsService.State.STARTED)); SearchRequest searchRequest = AlertsTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); - BytesReference alertSource = createAlertSource("* * * * * ? *", searchRequest, "payload.hits.total == 1"); + BytesReference alertSource = createAlertSource("* * * * * ? *", searchRequest, "ctx.payload.hits.total == 1"); alertClient().preparePutAlert("testAlert") .source(alertSource) .get(); diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/AlertThrottleTests.java b/src/test/java/org/elasticsearch/alerts/test/integration/AlertThrottleTests.java index 284ec77bd32..71018dec7af 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/AlertThrottleTests.java +++ b/src/test/java/org/elasticsearch/alerts/test/integration/AlertThrottleTests.java @@ -58,7 +58,7 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { .source(alertSourceBuilder() .schedule(cron("0/5 * * * * ? *")) .input(searchInput(matchAllRequest().indices("test-index"))) - .condition(scriptCondition("payload.hits.total > 0")) + .condition(scriptCondition("ctx.payload.hits.total > 0")) .transform(searchTransform(matchAllRequest().indices("test-index"))) .addAction(ActionBuilders.indexAction("action-index", "action-type")) .throttlePeriod(TimeValue.timeValueMillis(0))) @@ -129,7 +129,7 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { .source(alertSourceBuilder() .schedule(cron("0/5 * * * * ? *")) .input(searchInput(matchAllRequest().indices("test-index"))) - .condition(scriptCondition("payload.hits.total > 0")) + .condition(scriptCondition("ctx.payload.hits.total > 0")) .transform(searchTransform(matchAllRequest().indices("test-index"))) .addAction(ActionBuilders.indexAction("action-index", "action-type")) .throttlePeriod(TimeValue.timeValueSeconds(10))) diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/BasicAlertsTests.java b/src/test/java/org/elasticsearch/alerts/test/integration/BasicAlertsTests.java index a87e03b42be..07e64df6982 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/BasicAlertsTests.java +++ b/src/test/java/org/elasticsearch/alerts/test/integration/BasicAlertsTests.java @@ -64,7 +64,7 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { .source(alertSourceBuilder() .schedule(interval(5, IntervalSchedule.Interval.Unit.SECONDS)) .input(searchInput(searchRequest)) - .condition(scriptCondition("payload.hits.total == 1"))) + .condition(scriptCondition("ctx.payload.hits.total == 1"))) .get(); assertAlertWithMinimumPerformedActionsCount("my-first-alert", 1); @@ -81,7 +81,7 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { .source(alertSourceBuilder() .schedule(interval(5, IntervalSchedule.Interval.Unit.SECONDS)) .input(searchInput(searchRequest)) - .condition(scriptCondition("payload.hits.total == 1"))) + .condition(scriptCondition("ctx.payload.hits.total == 1"))) .get(); // The alert's condition won't meet because there is no data that matches with the query @@ -101,7 +101,7 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { .source(alertSourceBuilder() .schedule(interval(5, IntervalSchedule.Interval.Unit.SECONDS)) .input(searchInput(searchRequest)) - .condition(scriptCondition("payload.hits.total == 1"))) + .condition(scriptCondition("ctx.payload.hits.total == 1"))) .get(); assertThat(indexResponse.indexResponse().isCreated(), is(true)); @@ -175,7 +175,7 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { .source(alertSourceBuilder() .schedule(interval(5, IntervalSchedule.Interval.Unit.SECONDS)) .input(searchInput(searchRequest)) - .condition(scriptCondition("payload.hits?.hits[0]._score == 1.0"))) + .condition(scriptCondition("ctx.payload.hits?.hits[0]._score == 1.0"))) .get(); assertThat(indexResponse.indexResponse().isCreated(), is(true)); assertAlertWithMinimumPerformedActionsCount("my-first-alert", 1); @@ -193,17 +193,17 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { alertClient().preparePutAlert("1") - .source(source.condition(scriptCondition("payload.hits.total == 1"))) + .source(source.condition(scriptCondition("ctx.payload.hits.total == 1"))) .get(); assertAlertWithMinimumPerformedActionsCount("1", 0, false); alertClient().preparePutAlert("1") - .source(source.condition(scriptCondition("payload.hits.total == 0"))) + .source(source.condition(scriptCondition("ctx.payload.hits.total == 0"))) .get(); assertAlertWithMinimumPerformedActionsCount("1", 1, false); alertClient().preparePutAlert("1") - .source(source.schedule(cron("0/5 * * * * ? 2020")).condition(scriptCondition("payload.hits.total == 0"))) + .source(source.schedule(cron("0/5 * * * * ? 2020")).condition(scriptCondition("ctx.payload.hits.total == 0"))) .get(); Thread.sleep(5000); @@ -250,7 +250,7 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { .source(alertSourceBuilder() .schedule(cron("* 0/1 * * * ? *")) .input(searchInput(searchRequest)) - .condition(scriptCondition("payload.aggregations.rate.buckets[0]?.doc_count > 5")) + .condition(scriptCondition("ctx.payload.aggregations.rate.buckets[0]?.doc_count > 5")) .addAction(indexAction("my-index", "trail"))) .get(); @@ -299,7 +299,7 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { alertClient().prepareDeleteAlert(alertName).get(); alertClient().preparePutAlert(alertName) - .source(createAlertSource(String.format(Locale.ROOT, "0/%s * * * * ? *", (scheduleTimeInMs / 1000)), request, "return payload.hits.total >= 3")) + .source(createAlertSource(String.format(Locale.ROOT, "0/%s * * * * ? *", (scheduleTimeInMs / 1000)), request, "return ctx.payload.hits.total >= 3")) .get(); long time1 = System.currentTimeMillis(); diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/BootStrapTests.java b/src/test/java/org/elasticsearch/alerts/test/integration/BootStrapTests.java index 9a565394ae4..93625fa08dc 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/BootStrapTests.java +++ b/src/test/java/org/elasticsearch/alerts/test/integration/BootStrapTests.java @@ -55,7 +55,7 @@ public class BootStrapTests extends AbstractAlertsIntegrationTests { ensureAlertingStarted(); SearchRequest searchRequest = AlertsTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); - BytesReference alertSource = createAlertSource("0 0/5 * * * ? *", searchRequest, "payload.hits.total == 1"); + BytesReference alertSource = createAlertSource("0 0/5 * * * ? *", searchRequest, "ctx.payload.hits.total == 1"); client().prepareIndex(AlertsStore.ALERT_INDEX, AlertsStore.ALERT_TYPE, "my-first-alert") .setSource(alertSource) .setConsistencyLevel(WriteConsistencyLevel.ALL) diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/NoMasterNodeTests.java b/src/test/java/org/elasticsearch/alerts/test/integration/NoMasterNodeTests.java index 122fd82c295..583a3936fda 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/NoMasterNodeTests.java +++ b/src/test/java/org/elasticsearch/alerts/test/integration/NoMasterNodeTests.java @@ -66,7 +66,7 @@ public class NoMasterNodeTests extends AbstractAlertsIntegrationTests { // Have a sample document in the index, the alert is going to evaluate client().prepareIndex("my-index", "my-type").setSource("field", "value").get(); SearchRequest searchRequest = AlertsTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); - BytesReference alertSource = createAlertSource("0/5 * * * * ? *", searchRequest, "payload.hits.total == 1"); + BytesReference alertSource = createAlertSource("0/5 * * * * ? *", searchRequest, "ctx.payload.hits.total == 1"); alertClient().preparePutAlert("my-first-alert") .source(alertSource) .get(); @@ -114,7 +114,7 @@ public class NoMasterNodeTests extends AbstractAlertsIntegrationTests { for (int i = 1; i <= numberOfAlerts; i++) { String alertName = "alert" + i; SearchRequest searchRequest = AlertsTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); - BytesReference alertSource = createAlertSource("0/5 * * * * ? *", searchRequest, "payload.hits.total == 1"); + BytesReference alertSource = createAlertSource("0/5 * * * * ? *", searchRequest, "ctx.payload.hits.total == 1"); alertClient().preparePutAlert(alertName) .source(alertSource) .get(); diff --git a/src/test/java/org/elasticsearch/alerts/transform/ScriptTransformTests.java b/src/test/java/org/elasticsearch/alerts/transform/ScriptTransformTests.java index cf66e734d1b..6a8a455ba0c 100644 --- a/src/test/java/org/elasticsearch/alerts/transform/ScriptTransformTests.java +++ b/src/test/java/org/elasticsearch/alerts/transform/ScriptTransformTests.java @@ -5,6 +5,7 @@ */ package org.elasticsearch.alerts.transform; +import org.elasticsearch.alerts.Alert; import org.elasticsearch.alerts.ExecutionContext; import org.elasticsearch.alerts.Payload; import org.elasticsearch.alerts.support.Script; @@ -45,14 +46,13 @@ public class ScriptTransformTests extends ElasticsearchTestCase { ExecutionContext ctx = mock(ExecutionContext.class); when(ctx.scheduledTime()).thenReturn(now); when(ctx.fireTime()).thenReturn(now); + Alert alert = mock(Alert.class); + when(alert.name()).thenReturn("_name"); + when(ctx.alert()).thenReturn(alert); Payload payload = new Payload.Simple(ImmutableMap.builder().put("key", "value").build()); - Map model = ImmutableMap.builder() - .put(Variables.PAYLOAD, payload.data()) - .put(Variables.FIRE_TIME, now) - .put(Variables.SCHEDULED_FIRE_TIME, now) - .build(); + Map model = Variables.createCtxModel(ctx, payload); Map transformed = ImmutableMap.builder() .put("key", "value") diff --git a/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java b/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java index 769e87e6987..6ef11a16614 100644 --- a/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java +++ b/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java @@ -8,6 +8,7 @@ package org.elasticsearch.alerts.transform; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; +import org.elasticsearch.alerts.Alert; import org.elasticsearch.alerts.ExecutionContext; import org.elasticsearch.alerts.Payload; import org.elasticsearch.alerts.support.Variables; @@ -63,6 +64,10 @@ public class SearchTransformTests extends AbstractAlertsSingleNodeTests { DateTime now = new DateTime(); when(ctx.scheduledTime()).thenReturn(now); when(ctx.fireTime()).thenReturn(now); + Alert alert = mock(Alert.class); + when(alert.name()).thenReturn("_name"); + when(ctx.alert()).thenReturn(alert); + Payload payload = new Payload.Simple(new HashMap()); @@ -115,15 +120,18 @@ public class SearchTransformTests extends AbstractAlertsSingleNodeTests { refresh(); SearchRequest request = Requests.searchRequest("idx").source(searchSource().query(filteredQuery(matchAllQuery(), boolFilter() - .must(rangeFilter("date").gt("{{" + Variables.SCHEDULED_FIRE_TIME + "}}")) - .must(rangeFilter("date").lt("{{" + Variables.FIRE_TIME + "}}")) - .must(termFilter("value", "{{" + Variables.PAYLOAD + ".value}}"))))); + .must(rangeFilter("date").gt("{{" + Variables.CTX + "." + Variables.SCHEDULED_FIRE_TIME + "}}")) + .must(rangeFilter("date").lt("{{" + Variables.CTX + "." + Variables.FIRE_TIME + "}}")) + .must(termFilter("value", "{{" + Variables.CTX + "." + Variables.PAYLOAD + ".value}}"))))); SearchTransform transform = new SearchTransform(logger, scriptService(), ClientProxy.of(client()), request); ExecutionContext ctx = mock(ExecutionContext.class); when(ctx.scheduledTime()).thenReturn(parseDate("2015-01-01T00:00:00")); when(ctx.fireTime()).thenReturn(parseDate("2015-01-04T00:00:00")); + Alert alert = mock(Alert.class); + when(alert.name()).thenReturn("_name"); + when(ctx.alert()).thenReturn(alert); Payload payload = new Payload.Simple(ImmutableMap.builder() .put("value", "val_3")