From 43f11cbb3d8a594744260f2214b359d9f5e75ace Mon Sep 17 00:00:00 2001 From: uboness Date: Mon, 2 Mar 2015 22:01:02 +0200 Subject: [PATCH] [fix] added the script params to the condition script execution Now the script's params in the `script` condition are merged with the payload data into a single variable context to the script execution. The payload data is now accessed using the `payload.` prefix. Original commit: elastic/x-pack-elasticsearch@e313a6301ce30358ceb2336c57d8cc4873550c23 --- .../condition/script/ScriptCondition.java | 8 +++++++- .../condition/script/ScriptConditionTests.java | 16 ++++++++++++++-- .../test/integration/AlertMetadataTests.java | 2 +- .../test/integration/AlertStatsTests.java | 2 +- .../test/integration/AlertThrottleTests.java | 4 ++-- .../test/integration/BasicAlertsTests.java | 18 +++++++++--------- .../test/integration/BootStrapTests.java | 2 +- .../test/integration/NoMasterNodeTests.java | 4 ++-- 8 files changed, 37 insertions(+), 19 deletions(-) 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 86e6d6badc6..e9e73e39a7e 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/script/ScriptCondition.java +++ b/src/main/java/org/elasticsearch/alerts/condition/script/ScriptCondition.java @@ -10,7 +10,9 @@ import org.elasticsearch.alerts.ExecutionContext; import org.elasticsearch.alerts.condition.Condition; import org.elasticsearch.alerts.condition.ConditionException; import org.elasticsearch.alerts.support.Script; +import org.elasticsearch.alerts.support.Variables; import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.logging.ESLogger; @@ -51,7 +53,11 @@ public class ScriptCondition extends Condition { @Override public Result execute(ExecutionContext ctx) throws IOException { - ExecutableScript executable = scriptService.executable(script.lang(), script.script(), script.type(), ctx.payload().data()); + ImmutableMap model = ImmutableMap.builder() + .putAll(script.params()) + .put(Variables.PAYLOAD, ctx.payload().data()) + .build(); + ExecutableScript executable = scriptService.executable(script.lang(), script.script(), script.type(), model); Object value = executable.run(); if (value instanceof Boolean) { return (Boolean) value ? Result.MET : Result.UNMET; 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 d5a16ccf0f2..5dda86540d9 100644 --- a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java +++ b/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java @@ -13,6 +13,7 @@ import org.elasticsearch.alerts.Payload; 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.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -57,7 +58,18 @@ public class ScriptConditionTests extends ElasticsearchTestCase { @Test public void testExecute() throws Exception { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); - ScriptCondition condition = new ScriptCondition(logger, scriptService, new Script("hits.total > 1")); + ScriptCondition condition = new ScriptCondition(logger, scriptService, new Script("payload.hits.total > 1")); + SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); + ExecutionContext ctx = mock(ExecutionContext.class); + when(ctx.payload()).thenReturn(new Payload.ActionResponse(response)); + assertFalse(condition.execute(ctx).met()); + } + + @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)); + ScriptCondition condition = new ScriptCondition(logger, scriptService, script); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); ExecutionContext ctx = mock(ExecutionContext.class); when(ctx.payload()).thenReturn(new Payload.ActionResponse(response)); @@ -68,7 +80,7 @@ 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("hits.total > 1", null, null); + XContentBuilder builder = createConditionContent("payload.hits.total > 1", null, null); XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); parser.nextToken(); ScriptCondition condition = conditionParser.parse(parser); 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 d912fc9a66c..d5a494ab2c8 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("hits.total == 1")) + .condition(scriptCondition("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 8002e32f174..e73cc582764 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, "hits.total == 1"); + BytesReference alertSource = createAlertSource("* * * * * ? *", searchRequest, "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 14230cfba95..284ec77bd32 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("hits.total > 0")) + .condition(scriptCondition("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("hits.total > 0")) + .condition(scriptCondition("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 552c146e456..a87e03b42be 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("hits.total == 1"))) + .condition(scriptCondition("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("hits.total == 1"))) + .condition(scriptCondition("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("hits.total == 1"))) + .condition(scriptCondition("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("hits?.hits[0]._score == 1.0"))) + .condition(scriptCondition("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("hits.total == 1"))) + .source(source.condition(scriptCondition("payload.hits.total == 1"))) .get(); assertAlertWithMinimumPerformedActionsCount("1", 0, false); alertClient().preparePutAlert("1") - .source(source.condition(scriptCondition("hits.total == 0"))) + .source(source.condition(scriptCondition("payload.hits.total == 0"))) .get(); assertAlertWithMinimumPerformedActionsCount("1", 1, false); alertClient().preparePutAlert("1") - .source(source.schedule(cron("0/5 * * * * ? 2020")).condition(scriptCondition("hits.total == 0"))) + .source(source.schedule(cron("0/5 * * * * ? 2020")).condition(scriptCondition("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("aggregations.rate.buckets[0]?.doc_count > 5")) + .condition(scriptCondition("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 hits.total >= 3")) + .source(createAlertSource(String.format(Locale.ROOT, "0/%s * * * * ? *", (scheduleTimeInMs / 1000)), request, "return 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 710285c5a3f..9a565394ae4 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, "hits.total == 1"); + BytesReference alertSource = createAlertSource("0 0/5 * * * ? *", searchRequest, "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 2b918b32501..122fd82c295 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, "hits.total == 1"); + BytesReference alertSource = createAlertSource("0/5 * * * * ? *", searchRequest, "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, "hits.total == 1"); + BytesReference alertSource = createAlertSource("0/5 * * * * ? *", searchRequest, "payload.hits.total == 1"); alertClient().preparePutAlert(alertName) .source(alertSource) .get();