diff --git a/elasticsearch/qa/messy-test-watcher-with-groovy/src/test/java/org/elasticsearch/messy/tests/IndexActionIT.java b/elasticsearch/qa/messy-test-watcher-with-groovy/src/test/java/org/elasticsearch/messy/tests/IndexActionIT.java deleted file mode 100644 index 74b9aeab263..00000000000 --- a/elasticsearch/qa/messy-test-watcher-with-groovy/src/test/java/org/elasticsearch/messy/tests/IndexActionIT.java +++ /dev/null @@ -1,215 +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.messy.tests; - -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.plugins.Plugin; -import org.elasticsearch.script.groovy.GroovyPlugin; -import org.elasticsearch.search.SearchHit; -import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; -import org.elasticsearch.search.sort.SortOrder; -import org.elasticsearch.xpack.watcher.history.HistoryStore; -import org.elasticsearch.xpack.watcher.support.WatcherDateTimeUtils; -import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; -import org.elasticsearch.xpack.watcher.transport.actions.execute.ExecuteWatchResponse; -import org.elasticsearch.xpack.watcher.transport.actions.put.PutWatchResponse; -import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; - -import java.util.List; - -import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.QueryBuilders.matchQuery; -import static org.elasticsearch.search.aggregations.AggregationBuilders.dateHistogram; -import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; -import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.indexAction; -import static org.elasticsearch.xpack.watcher.client.WatchSourceBuilders.watchBuilder; -import static org.elasticsearch.xpack.watcher.input.InputBuilders.searchInput; -import static org.elasticsearch.xpack.watcher.input.InputBuilders.simpleInput; -import static org.elasticsearch.xpack.watcher.transform.TransformBuilders.scriptTransform; -import static org.elasticsearch.xpack.watcher.trigger.TriggerBuilders.schedule; -import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.cron; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.is; - -/** - * - */ -public class IndexActionIT extends AbstractWatcherIntegrationTestCase { - - @Override - protected List> pluginTypes() { - List> types = super.pluginTypes(); - types.add(GroovyPlugin.class); - return types; - } - - public void testSimple() throws Exception { - PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() - .trigger(schedule(cron("0/1 * * * * ? 2020"))) - .input(simpleInput("foo", "bar")) - .addAction("index-buckets", indexAction("idx", "type").setExecutionTimeField("@timestamp"))) - .get(); - - assertThat(putWatchResponse.isCreated(), is(true)); - - DateTime now = timeWarped() ? timeWarp().clock().now(DateTimeZone.UTC) : DateTime.now(DateTimeZone.UTC); - - ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .get(); - - assertThat(executeWatchResponse.getRecordSource().getValue("state"), is((Object) "executed")); - - flush("idx"); - refresh(); - - SearchResponse searchResponse = client().prepareSearch("idx").setTypes("type").get(); - assertThat(searchResponse.getHits().totalHits(), is(1L)); - SearchHit hit = searchResponse.getHits().getAt(0); - if (timeWarped()) { - assertThat(hit.getSource(), hasEntry("@timestamp", (Object) WatcherDateTimeUtils.formatDate(now))); - } else { - assertThat(hit.getSource(), hasKey("@timestamp")); - DateTime timestamp = WatcherDateTimeUtils.parseDate((String) hit.getSource().get("@timestamp")); - assertThat(timestamp.isEqual(now) || timestamp.isAfter(now), is(true)); - } - assertThat(hit.getSource(), hasEntry("foo", (Object) "bar")); - } - - public void testSimpleWithDocField() throws Exception { - PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() - .trigger(schedule(cron("0/1 * * * * ? 2020"))) - .input(simpleInput("foo", "bar")) - .addAction("index-buckets", - scriptTransform("return [ '_doc' : ctx.payload ]"), - indexAction("idx", "type").setExecutionTimeField("@timestamp"))) - - .get(); - - assertThat(putWatchResponse.isCreated(), is(true)); - - DateTime now = timeWarped() ? timeWarp().clock().now(DateTimeZone.UTC) : DateTime.now(DateTimeZone.UTC); - - ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .get(); - - assertThat(executeWatchResponse.getRecordSource().getValue("state"), is((Object) "executed")); - - flush("idx"); - refresh(); - - SearchResponse searchResponse = client().prepareSearch("idx").setTypes("type").get(); - assertThat(searchResponse.getHits().totalHits(), is(1L)); - SearchHit hit = searchResponse.getHits().getAt(0); - if (timeWarped()) { - assertThat(hit.getSource(), hasEntry("@timestamp", (Object) WatcherDateTimeUtils.formatDate(now))); - } else { - assertThat(hit.getSource(), hasKey("@timestamp")); - DateTime timestamp = WatcherDateTimeUtils.parseDate((String) hit.getSource().get("@timestamp")); - assertThat(timestamp.isEqual(now) || timestamp.isAfter(now), is(true)); - } - assertThat(hit.getSource(), hasEntry("foo", (Object) "bar")); - } - - public void testSimpleWithDocFieldWrongFieldType() throws Exception { - PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() - .trigger(schedule(cron("0/1 * * * * ? 2020"))) - .input(simpleInput("foo", "bar")) - .addAction("index-buckets", - scriptTransform("return [ '_doc' : 1 ]"), - indexAction("idx", "type").setExecutionTimeField("@timestamp"))) - .get(); - - assertThat(putWatchResponse.isCreated(), is(true)); - - DateTime now = timeWarped() ? timeWarp().clock().now(DateTimeZone.UTC) : DateTime.now(DateTimeZone.UTC); - - ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .setRecordExecution(true) - .get(); - - assertThat(executeWatchResponse.getRecordSource().getValue("state"), is((Object) "executed")); - - flush(); - refresh(); - - assertThat(client().admin().indices().prepareExists("idx").get().isExists(), is(false)); - - assertThat(docCount(HistoryStore.INDEX_PREFIX_WITH_TEMPLATE + "*", HistoryStore.DOC_TYPE, searchSource() - .query(matchQuery("result.actions.status", "failure"))), is(1L)); - - } - - public void testIndexAggsBucketsAsDocuments() throws Exception { - DateTime now = timeWarped() ? timeWarp().clock().now(DateTimeZone.UTC) : DateTime.now(DateTimeZone.UTC); - long bucketCount = randomIntBetween(2, 5); - for (int i = 0; i < bucketCount; i++) { - index("idx", "type", jsonBuilder().startObject() - .field("timestamp", now.minusDays(i)) - .endObject()); - } - - flush("idx"); - refresh(); - - PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() - .trigger(schedule(cron("0/1 * * * * ? 2020"))) - .input(searchInput(new SearchRequest("idx") - .types("type") - .searchType(SearchType.QUERY_THEN_FETCH) - .source(searchSource() - .aggregation(dateHistogram("trend") - .field("timestamp") - .dateHistogramInterval(DateHistogramInterval.DAY))))) - .addAction("index-buckets", - - // this transform takes the bucket list and assigns it to `_doc` - // this means each bucket will be indexed as a separate doc, - // so we expect to have the same number of documents as the number - // of buckets. - scriptTransform("return [ '_doc' : ctx.payload.aggregations.trend.buckets]"), - - indexAction("idx", "bucket").setExecutionTimeField("@timestamp"))) - - .get(); - - assertThat(putWatchResponse.isCreated(), is(true)); - - ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .get(); - - assertThat(executeWatchResponse.getRecordSource().getValue("state"), is((Object) "executed")); - - flush("idx"); - refresh(); - - SearchResponse searchResponse = client().prepareSearch("idx").setTypes("bucket") - .addSort("key", SortOrder.DESC) - .get(); - assertThat(searchResponse.getHits().getTotalHits(), is(bucketCount)); - DateTime key = now.withMillisOfDay(0); - int i = 0; - for (SearchHit hit : searchResponse.getHits()) { - if (timeWarped()) { - assertThat(hit.getSource(), hasEntry("@timestamp", (Object) WatcherDateTimeUtils.formatDate(now))); - } else { - assertThat(hit.getSource(), hasKey("@timestamp")); - DateTime timestamp = WatcherDateTimeUtils.parseDate((String) hit.getSource().get("@timestamp")); - assertThat(timestamp.isEqual(now) || timestamp.isAfter(now), is(true)); - } - assertThat(hit.getSource(), hasEntry("key", (Object) key.getMillis())); - key = key.minusDays(1); - } - } -} diff --git a/elasticsearch/qa/smoke-test-watcher-with-groovy/src/test/resources/rest-api-spec/test/watcher_groovy/40_index_action.yaml b/elasticsearch/qa/smoke-test-watcher-with-groovy/src/test/resources/rest-api-spec/test/watcher_groovy/40_index_action.yaml new file mode 100644 index 00000000000..1c90ab603b6 --- /dev/null +++ b/elasticsearch/qa/smoke-test-watcher-with-groovy/src/test/resources/rest-api-spec/test/watcher_groovy/40_index_action.yaml @@ -0,0 +1,238 @@ +--- +"Test simple input to index action": + - do: + xpack.watcher.put_watch: + id: my_watch + body: > + { + "trigger" : { "schedule" : { "cron" : "0/1 * * * * ? 2020" } }, + "input" : { "simple" : { "foo": "bar" } }, + "actions" : { + "index_action" : { + "index" : { + "index" : "idx", + "doc_type" : "type", + "execution_time_field" : "@timestamp" + } + } + } + } + + - match: { _id: "my_watch" } + + + - do: + xpack.watcher.execute_watch: + id: "my_watch" + body: > + { + "trigger_data" : { + "triggered_time" : "2016-07-07T09:00:00Z", + "scheduled_time" : "2016-07-07T09:00:00Z" + } + } + + - match: { "watch_record.state": "executed" } + + - do: + indices.refresh: {} + + - do: + search: + index: idx + type: type + + - match: { hits.total: 1 } + - match: { hits.hits.0._source.foo: bar } + - gte: { hits.hits.0._source.@timestamp: '2016-07-08' } + +--- +"Test simple input with document field": + + - do: + xpack.watcher.put_watch: + id: my_watch + body: > + { + "trigger" : { "schedule" : { "cron" : "0/1 * * * * ? 2020" } }, + "input" : { "simple" : { "foo": "bar" } }, + "actions" : { + "index_action" : { + "transform" : { "script" : { "inline": "return [ '_doc' : ctx.payload ]" } }, + "index" : { + "index" : "idx", + "doc_type" : "type", + "execution_time_field" : "@timestamp" + } + } + } + } + + - match: { _id: "my_watch" } + + + - do: + xpack.watcher.execute_watch: + id: "my_watch" + body: > + { + "trigger_data" : { + "triggered_time" : "2016-07-07T09:00:00Z", + "scheduled_time" : "2016-07-07T09:00:00Z" + } + } + + - match: { "watch_record.state": "executed" } + + - do: + indices.refresh: {} + + - do: + search: + index: idx + type: type + + - match: { hits.total: 1 } + - match: { hits.hits.0._source.foo: bar } + - gte: { hits.hits.0._source.@timestamp: '2016-07-08"' } + + +--- +"Test simple input with wrong document results in error": + + - do: + xpack.watcher.put_watch: + id: my_watch + body: > + { + "trigger" : { "schedule" : { "cron" : "0/1 * * * * ? 2020" } }, + "input" : { "simple" : { "foo": "bar" } }, + "actions" : { + "index_action" : { + "transform" : { "script" : { "inline": "return [ '_doc' : 1 ]" } }, + "index" : { + "index" : "idx", + "doc_type" : "type", + "execution_time_field" : "@timestamp" + } + } + } + } + + - match: { _id: "my_watch" } + + + - do: + xpack.watcher.execute_watch: + id: "my_watch" + body: > + { + "record_execution" : true, + "trigger_data" : { + "triggered_time" : "2016-07-07T09:00:00Z", + "scheduled_time" : "2016-07-07T09:00:00Z" + } + } + + - match: { "watch_record.state": "executed" } + + - do: + indices.refresh: {} + + - do: + indices.exists: + index: idx + + - is_false: '' + + - do: + search: + index: .watcher-history-* + type: watch_record + body: > + { + "query" : { + "match" : { + "result.actions.status": "failure" + } + } + } + + - match: { hits.total: 1 } + +--- +"Test search input to index action with aggs": + + - do: + bulk: + refresh: true + body: + - '{"index": {"_index": "idx", "_type": "type", "_id": "1"}}' + - '{"@timestamp": "2016-07-07" }' + - '{"index": {"_index": "idx", "_type": "type", "_id": "2"}}' + - '{"@timestamp": "2016-07-08" }' + - '{"index": {"_index": "idx", "_type": "type", "_id": "3"}}' + - '{"@timestamp": "2016-07-09" }' + + - do: + xpack.watcher.put_watch: + id: my_watch + body: > + { + "trigger" : { "schedule" : { "cron" : "0/1 * * * * ? 2020" } }, + "input" : { + "search" : { + "request": { + "indices" : [ "idx" ], + "types" : [ "type" ], + "body" : { + "aggs" : { + "trend" : { + "date_histogram" : { + "field" : "@timestamp", + "interval" : "day" + } + } + } + } + } + } + }, + "actions" : { + "index_action" : { + "transform" : { "script" : { "inline": "return [ '_doc' : ctx.payload.aggregations.trend.buckets]" } }, + "index" : { + "index" : "idx", + "doc_type" : "bucket", + "execution_time_field" : "@timestamp" + } + } + } + } + + - match: { _id: "my_watch" } + + + - do: + xpack.watcher.execute_watch: + id: "my_watch" + body: > + { + "trigger_data" : { + "triggered_time" : "2016-07-07T09:00:00Z", + "scheduled_time" : "2016-07-07T09:00:00Z" + } + } + + - match: { "watch_record.state": "executed" } + + - do: + indices.refresh: {} + + - do: + search: + index: idx + type: bucket + + - match: { hits.total: 3 } + diff --git a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/Licensing.java b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/Licensing.java index 7629a129b26..8fcc604d28f 100644 --- a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/Licensing.java +++ b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/Licensing.java @@ -20,7 +20,7 @@ import org.elasticsearch.license.plugin.action.get.TransportGetLicenseAction; import org.elasticsearch.license.plugin.action.put.PutLicenseAction; import org.elasticsearch.license.plugin.action.put.TransportPutLicenseAction; import org.elasticsearch.license.plugin.core.LicensesMetaData; -import org.elasticsearch.license.plugin.core.LicensesService; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.license.plugin.rest.RestDeleteLicenseAction; import org.elasticsearch.license.plugin.rest.RestGetLicenseAction; import org.elasticsearch.license.plugin.rest.RestPutLicenseAction; @@ -92,11 +92,11 @@ public class Licensing implements ActionPlugin { WatcherLicensee watcherLicensee = new WatcherLicensee(settings); MonitoringLicensee monitoringLicensee = new MonitoringLicensee(settings); GraphLicensee graphLicensee = new GraphLicensee(settings); - LicensesService licensesService = new LicensesService(settings, clusterService, clock, + LicenseService licenseService = new LicenseService(settings, clusterService, clock, environment, resourceWatcherService, Arrays.asList(securityLicensee, watcherLicensee, monitoringLicensee, graphLicensee)); - return Arrays.asList(licensesService, securityLicenseState, securityLicensee, watcherLicensee, monitoringLicensee, graphLicensee); + return Arrays.asList(licenseService, securityLicenseState, securityLicensee, watcherLicensee, monitoringLicensee, graphLicensee); } public List> getSettings() { diff --git a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/delete/TransportDeleteLicenseAction.java b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/delete/TransportDeleteLicenseAction.java index f36a6b3f5e4..c9c6123aac1 100644 --- a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/delete/TransportDeleteLicenseAction.java +++ b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/delete/TransportDeleteLicenseAction.java @@ -17,21 +17,21 @@ import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.license.plugin.core.LicensesService; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; public class TransportDeleteLicenseAction extends TransportMasterNodeAction { - private final LicensesService licensesService; + private final LicenseService licenseService; @Inject public TransportDeleteLicenseAction(Settings settings, TransportService transportService, ClusterService clusterService, - LicensesService licensesService, ThreadPool threadPool, ActionFilters actionFilters, + LicenseService licenseService, ThreadPool threadPool, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { super(settings, DeleteLicenseAction.NAME, transportService, clusterService, threadPool, actionFilters, indexNameExpressionResolver, DeleteLicenseRequest::new); - this.licensesService = licensesService; + this.licenseService = licenseService; } @Override @@ -52,7 +52,7 @@ public class TransportDeleteLicenseAction extends TransportMasterNodeAction listener) throws ElasticsearchException { - licensesService.removeLicense(request, new ActionListener() { + licenseService.removeLicense(request, new ActionListener() { @Override public void onResponse(ClusterStateUpdateResponse clusterStateUpdateResponse) { listener.onResponse(new DeleteLicenseResponse(clusterStateUpdateResponse.isAcknowledged())); diff --git a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/get/TransportGetLicenseAction.java b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/get/TransportGetLicenseAction.java index dabb92ea841..98bd9b6fb72 100644 --- a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/get/TransportGetLicenseAction.java +++ b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/get/TransportGetLicenseAction.java @@ -16,21 +16,21 @@ import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.license.plugin.core.LicensesService; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; public class TransportGetLicenseAction extends TransportMasterNodeReadAction { - private final LicensesService licensesService; + private final LicenseService licenseService; @Inject public TransportGetLicenseAction(Settings settings, TransportService transportService, ClusterService clusterService, - LicensesService licensesService, ThreadPool threadPool, ActionFilters actionFilters, + LicenseService licenseService, ThreadPool threadPool, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { super(settings, GetLicenseAction.NAME, transportService, clusterService, threadPool, actionFilters, indexNameExpressionResolver, GetLicenseRequest::new); - this.licensesService = licensesService; + this.licenseService = licenseService; } @Override @@ -51,6 +51,6 @@ public class TransportGetLicenseAction extends TransportMasterNodeReadAction listener) throws ElasticsearchException { - listener.onResponse(new GetLicenseResponse(licensesService.getLicense())); + listener.onResponse(new GetLicenseResponse(licenseService.getLicense())); } } diff --git a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/put/TransportPutLicenseAction.java b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/put/TransportPutLicenseAction.java index d527be2cf0c..bd7931be486 100644 --- a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/put/TransportPutLicenseAction.java +++ b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/action/put/TransportPutLicenseAction.java @@ -16,21 +16,21 @@ import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.license.plugin.core.LicensesService; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; public class TransportPutLicenseAction extends TransportMasterNodeAction { - private final LicensesService licensesService; + private final LicenseService licenseService; @Inject public TransportPutLicenseAction(Settings settings, TransportService transportService, ClusterService clusterService, - LicensesService licensesService, ThreadPool threadPool, ActionFilters actionFilters, + LicenseService licenseService, ThreadPool threadPool, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { super(settings, PutLicenseAction.NAME, transportService, clusterService, threadPool, actionFilters, indexNameExpressionResolver, PutLicenseRequest::new); - this.licensesService = licensesService; + this.licenseService = licenseService; } @Override @@ -51,7 +51,7 @@ public class TransportPutLicenseAction extends TransportMasterNodeAction listener) throws ElasticsearchException { - licensesService.registerLicense(request, listener); + licenseService.registerLicense(request, listener); } } diff --git a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicensesService.java b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicenseService.java similarity index 98% rename from elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicensesService.java rename to elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicenseService.java index 1a1dd6414a2..7fd2cd77256 100644 --- a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicensesService.java +++ b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicenseService.java @@ -57,7 +57,7 @@ import java.util.stream.Collectors; * When a new license is notified as enabled to the registered listener, a notification is scheduled at the time of license expiry. * Registered listeners are notified using {@link #onUpdate(LicensesMetaData)} */ -public class LicensesService extends AbstractLifecycleComponent implements ClusterStateListener, SchedulerEngine.Listener { +public class LicenseService extends AbstractLifecycleComponent implements ClusterStateListener, SchedulerEngine.Listener { // pkg private for tests static final TimeValue TRIAL_LICENSE_DURATION = TimeValue.timeValueHours(30 * 24); @@ -98,8 +98,8 @@ public class LicensesService extends AbstractLifecycleComponent implements Clust private static final String ACKNOWLEDGEMENT_HEADER = "This license update requires acknowledgement. To acknowledge the license, " + "please read the following messages and update the license again, this time with the \"acknowledge=true\" parameter:"; - public LicensesService(Settings settings, ClusterService clusterService, Clock clock, Environment env, - ResourceWatcherService resourceWatcherService, List registeredLicensees) { + public LicenseService(Settings settings, ClusterService clusterService, Clock clock, Environment env, + ResourceWatcherService resourceWatcherService, List registeredLicensees) { super(settings); this.clusterService = clusterService; this.clock = clock; diff --git a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicenseState.java b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicenseState.java index 8db2f996199..85eebd76467 100644 --- a/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicenseState.java +++ b/elasticsearch/x-pack/license-plugin/src/main/java/org/elasticsearch/license/plugin/core/LicenseState.java @@ -8,7 +8,7 @@ package org.elasticsearch.license.plugin.core; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.license.core.License; -import static org.elasticsearch.license.plugin.core.LicensesService.days; +import static org.elasticsearch.license.plugin.core.LicenseService.days; /** * States of a registered licensee diff --git a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/LicensesServiceClusterTests.java b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/LicensesServiceClusterTests.java index d9e47d8f9eb..0350c2a8dcb 100644 --- a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/LicensesServiceClusterTests.java +++ b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/LicensesServiceClusterTests.java @@ -10,8 +10,8 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.env.Environment; import org.elasticsearch.license.core.License; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.license.plugin.core.LicenseState; -import org.elasticsearch.license.plugin.core.LicensesService; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.xpack.MockNetty3Plugin; @@ -170,7 +170,7 @@ public class LicensesServiceClusterTests extends AbstractLicensesIntegrationTest private void assertLicenseState(LicenseState state) throws InterruptedException { boolean success = awaitBusy(() -> { - for (LicensesService service : internalCluster().getDataNodeInstances(LicensesService.class)) { + for (LicenseService service : internalCluster().getDataNodeInstances(LicenseService.class)) { if (service.licenseeStatus().getLicenseState() == state) { return true; } @@ -182,7 +182,7 @@ public class LicensesServiceClusterTests extends AbstractLicensesIntegrationTest private void assertOperationMode(License.OperationMode operationMode) throws InterruptedException { boolean success = awaitBusy(() -> { - for (LicensesService service : internalCluster().getDataNodeInstances(LicensesService.class)) { + for (LicenseService service : internalCluster().getDataNodeInstances(LicenseService.class)) { if (service.licenseeStatus().getMode() == operationMode) { return true; } diff --git a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/TestUtils.java b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/TestUtils.java index 16b6b6a583e..6ae7b4a70e5 100644 --- a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/TestUtils.java +++ b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/TestUtils.java @@ -21,8 +21,8 @@ import org.elasticsearch.license.core.License; import org.elasticsearch.license.licensor.LicenseSigner; import org.elasticsearch.license.plugin.action.put.PutLicenseRequest; import org.elasticsearch.license.plugin.action.put.PutLicenseResponse; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.license.plugin.core.Licensee; -import org.elasticsearch.license.plugin.core.LicensesService; import org.elasticsearch.license.plugin.core.LicensesStatus; import org.junit.Assert; @@ -146,12 +146,12 @@ public class TestUtils { return PathUtils.get(TestUtils.class.getResource(resource).toURI()); } - public static void registerAndAckSignedLicenses(final LicensesService licensesService, License license, + public static void registerAndAckSignedLicenses(final LicenseService licenseService, License license, final LicensesStatus expectedStatus) { PutLicenseRequest putLicenseRequest = new PutLicenseRequest().license(license).acknowledge(true); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference status = new AtomicReference<>(); - licensesService.registerLicense(putLicenseRequest, new ActionListener() { + licenseService.registerLicense(putLicenseRequest, new ActionListener() { @Override public void onResponse(PutLicenseResponse licensesUpdateResponse) { status.set(licensesUpdateResponse.status()); diff --git a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/AbstractLicenseServiceTestCase.java b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/AbstractLicenseServiceTestCase.java index 9007df3e9f5..fc2977c8ff0 100644 --- a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/AbstractLicenseServiceTestCase.java +++ b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/AbstractLicenseServiceTestCase.java @@ -35,7 +35,7 @@ import static org.mockito.Mockito.when; public abstract class AbstractLicenseServiceTestCase extends ESTestCase { - protected LicensesService licensesService; + protected LicenseService licenseService; protected ClusterService clusterService; protected ResourceWatcherService resourceWatcherService; protected ClockMock clock; @@ -54,7 +54,7 @@ public abstract class AbstractLicenseServiceTestCase extends ESTestCase { protected void setInitialState(License license, Licensee... licensees) { Path tempDir = createTempDir(); when(environment.configFile()).thenReturn(tempDir); - licensesService = new LicensesService(Settings.EMPTY, clusterService, clock, environment, + licenseService = new LicenseService(Settings.EMPTY, clusterService, clock, environment, resourceWatcherService, Arrays.asList(licensees)); ClusterState state = mock(ClusterState.class); final ClusterBlocks noBlock = ClusterBlocks.builder().build(); @@ -74,6 +74,6 @@ public abstract class AbstractLicenseServiceTestCase extends ESTestCase { @After public void after() { - licensesService.stop(); + licenseService.stop(); } } diff --git a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicenseClusterChangeTests.java b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicenseClusterChangeTests.java index 38b79988deb..64e6cae8e72 100644 --- a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicenseClusterChangeTests.java +++ b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicenseClusterChangeTests.java @@ -37,12 +37,12 @@ public class LicenseClusterChangeTests extends AbstractLicenseServiceTestCase { public void setup() { licensee = new TestUtils.AssertingLicensee("LicenseClusterChangeTests", logger); setInitialState(null, licensee); - licensesService.start(); + licenseService.start(); } @After public void teardown() { - licensesService.stop(); + licenseService.stop(); } @@ -51,7 +51,7 @@ public class LicenseClusterChangeTests extends AbstractLicenseServiceTestCase { final License license = TestUtils.generateSignedLicense(TimeValue.timeValueHours(24)); MetaData metaData = MetaData.builder().putCustom(LicensesMetaData.TYPE, new LicensesMetaData(license)).build(); ClusterState newState = ClusterState.builder(new ClusterName("a")).metaData(metaData).build(); - licensesService.clusterChanged(new ClusterChangedEvent("simulated", newState, oldState)); + licenseService.clusterChanged(new ClusterChangedEvent("simulated", newState, oldState)); assertThat(licensee.statuses.size(), equalTo(1)); assertTrue(licensee.statuses.get(0).getLicenseState() == LicenseState.ENABLED); } @@ -61,7 +61,7 @@ public class LicenseClusterChangeTests extends AbstractLicenseServiceTestCase { MetaData metaData = MetaData.builder().putCustom(LicensesMetaData.TYPE, new LicensesMetaData(license)).build(); ClusterState newState = ClusterState.builder(new ClusterName("a")).metaData(metaData).build(); ClusterState oldState = ClusterState.builder(newState).build(); - licensesService.clusterChanged(new ClusterChangedEvent("simulated", newState, oldState)); + licenseService.clusterChanged(new ClusterChangedEvent("simulated", newState, oldState)); assertThat(licensee.statuses.size(), equalTo(0)); } @@ -72,13 +72,13 @@ public class LicenseClusterChangeTests extends AbstractLicenseServiceTestCase { when(discoveryNodes.isLocalNodeElectedMaster()).thenReturn(true); ClusterState newState = ClusterState.builder(oldState).nodes(discoveryNodes).build(); - licensesService.clusterChanged(new ClusterChangedEvent("simulated", newState, oldState)); + licenseService.clusterChanged(new ClusterChangedEvent("simulated", newState, oldState)); ArgumentCaptor stateUpdater = ArgumentCaptor.forClass(ClusterStateUpdateTask.class); verify(clusterService, times(1)).submitStateUpdateTask(any(), stateUpdater.capture()); ClusterState stateWithLicense = stateUpdater.getValue().execute(newState); LicensesMetaData licenseMetaData = stateWithLicense.metaData().custom(LicensesMetaData.TYPE); assertNotNull(licenseMetaData); assertNotNull(licenseMetaData.getLicense()); - assertEquals(clock.millis() + LicensesService.TRIAL_LICENSE_DURATION.millis(), licenseMetaData.getLicense().expiryDate()); + assertEquals(clock.millis() + LicenseService.TRIAL_LICENSE_DURATION.millis(), licenseMetaData.getLicense().expiryDate()); } } \ No newline at end of file diff --git a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicenseRegistrationTests.java b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicenseRegistrationTests.java index b351d92e228..a752bca9c89 100644 --- a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicenseRegistrationTests.java +++ b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicenseRegistrationTests.java @@ -25,7 +25,7 @@ public class LicenseRegistrationTests extends AbstractLicenseServiceTestCase { "testTrialLicenseRequestOnEmptyLicenseState", logger); setInitialState(null, licensee); when(discoveryNodes.isLocalNodeElectedMaster()).thenReturn(true); - licensesService.start(); + licenseService.start(); ClusterState state = ClusterState.builder(new ClusterName("a")).build(); ArgumentCaptor stateUpdater = ArgumentCaptor.forClass(ClusterStateUpdateTask.class); @@ -34,14 +34,14 @@ public class LicenseRegistrationTests extends AbstractLicenseServiceTestCase { LicensesMetaData licenseMetaData = stateWithLicense.metaData().custom(LicensesMetaData.TYPE); assertNotNull(licenseMetaData); assertNotNull(licenseMetaData.getLicense()); - assertEquals(clock.millis() + LicensesService.TRIAL_LICENSE_DURATION.millis(), licenseMetaData.getLicense().expiryDate()); + assertEquals(clock.millis() + LicenseService.TRIAL_LICENSE_DURATION.millis(), licenseMetaData.getLicense().expiryDate()); } public void testNotificationOnRegistration() throws Exception { TestUtils.AssertingLicensee licensee = new TestUtils.AssertingLicensee( "testNotificationOnRegistration", logger); setInitialState(TestUtils.generateSignedLicense(TimeValue.timeValueHours(2)), licensee); - licensesService.start(); + licenseService.start(); assertThat(licensee.statuses.size(), equalTo(1)); final LicenseState licenseState = licensee.statuses.get(0).getLicenseState(); assertTrue(licenseState == LicenseState.ENABLED); diff --git a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesAcknowledgementTests.java b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesAcknowledgementTests.java index 1ac4d815b9e..40cbd87d393 100644 --- a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesAcknowledgementTests.java +++ b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesAcknowledgementTests.java @@ -32,23 +32,23 @@ public class LicensesAcknowledgementTests extends AbstractLicenseServiceTestCase String[] acknowledgeMessages = new String[] {"message"}; TestUtils.AssertingLicensee licensee = new TestUtils.AssertingLicensee(id, logger); setInitialState(TestUtils.generateSignedLicense("trial", TimeValue.timeValueHours(2)), licensee); - licensesService.start(); + licenseService.start(); licensee.setAcknowledgementMessages(acknowledgeMessages); // try installing a signed license License signedLicense = generateSignedLicense(TimeValue.timeValueHours(10)); PutLicenseRequest putLicenseRequest = new PutLicenseRequest().license(signedLicense); // ensure acknowledgement message was part of the response - licensesService.registerLicense(putLicenseRequest, new AssertingLicensesUpdateResponse(false, LicensesStatus.VALID, + licenseService.registerLicense(putLicenseRequest, new AssertingLicensesUpdateResponse(false, LicensesStatus.VALID, Collections.singletonMap(id, acknowledgeMessages))); assertThat(licensee.acknowledgementRequested.size(), equalTo(1)); assertThat(licensee.acknowledgementRequested.get(0).v2(), equalTo(signedLicense.operationMode())); - assertThat(licensesService.getLicense(), not(signedLicense)); + assertThat(licenseService.getLicense(), not(signedLicense)); // try installing a signed license with acknowledgement putLicenseRequest = new PutLicenseRequest().license(signedLicense).acknowledge(true); // ensure license was installed and no acknowledgment message was returned licensee.setAcknowledgementMessages(new String[0]); - licensesService.registerLicense(putLicenseRequest, new AssertingLicensesUpdateResponse(true, LicensesStatus.VALID, + licenseService.registerLicense(putLicenseRequest, new AssertingLicensesUpdateResponse(true, LicensesStatus.VALID, Collections.emptyMap())); verify(clusterService, times(1)).submitStateUpdateTask(any(String.class), any(ClusterStateUpdateTask.class)); assertThat(licensee.acknowledgementRequested.size(), equalTo(1)); @@ -65,7 +65,7 @@ public class LicensesAcknowledgementTests extends AbstractLicenseServiceTestCase TestUtils.AssertingLicensee licensee2 = new TestUtils.AssertingLicensee(id2, logger); licensee2.setAcknowledgementMessages(acknowledgeMessages2); setInitialState(TestUtils.generateSignedLicense("trial", TimeValue.timeValueHours(2)), licensee1, licensee2); - licensesService.start(); + licenseService.start(); // try installing a signed license License signedLicense = generateSignedLicense(TimeValue.timeValueHours(10)); PutLicenseRequest putLicenseRequest = new PutLicenseRequest().license(signedLicense); @@ -73,21 +73,21 @@ public class LicensesAcknowledgementTests extends AbstractLicenseServiceTestCase final HashMap expectedMessages = new HashMap<>(); expectedMessages.put(id1, acknowledgeMessages1); expectedMessages.put(id2, acknowledgeMessages2); - licensesService.registerLicense(putLicenseRequest, new AssertingLicensesUpdateResponse(false, LicensesStatus.VALID, + licenseService.registerLicense(putLicenseRequest, new AssertingLicensesUpdateResponse(false, LicensesStatus.VALID, expectedMessages)); verify(clusterService, times(0)).submitStateUpdateTask(any(String.class), any(ClusterStateUpdateTask.class)); assertThat(licensee2.acknowledgementRequested.size(), equalTo(1)); assertThat(licensee2.acknowledgementRequested.get(0).v2(), equalTo(signedLicense.operationMode())); assertThat(licensee1.acknowledgementRequested.size(), equalTo(1)); assertThat(licensee1.acknowledgementRequested.get(0).v2(), equalTo(signedLicense.operationMode())); - assertThat(licensesService.getLicense(), not(signedLicense)); + assertThat(licenseService.getLicense(), not(signedLicense)); // try installing a signed license with acknowledgement putLicenseRequest = new PutLicenseRequest().license(signedLicense).acknowledge(true); // ensure license was installed and no acknowledgment message was returned licensee1.setAcknowledgementMessages(new String[0]); licensee2.setAcknowledgementMessages(new String[0]); - licensesService.registerLicense(putLicenseRequest, new AssertingLicensesUpdateResponse(true, LicensesStatus.VALID, + licenseService.registerLicense(putLicenseRequest, new AssertingLicensesUpdateResponse(true, LicensesStatus.VALID, Collections.emptyMap())); verify(clusterService, times(1)).submitStateUpdateTask(any(String.class), any(ClusterStateUpdateTask.class)); } diff --git a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesManagerServiceTests.java b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesManagerServiceTests.java index b4195860c2c..a63376a05e8 100644 --- a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesManagerServiceTests.java +++ b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesManagerServiceTests.java @@ -55,46 +55,46 @@ public class LicensesManagerServiceTests extends ESSingleNodeTestCase { } public void testStoreAndGetLicenses() throws Exception { - LicensesService licensesService = getInstanceFromNode(LicensesService.class); + LicenseService licenseService = getInstanceFromNode(LicenseService.class); ClusterService clusterService = getInstanceFromNode(ClusterService.class); License goldLicense = generateSignedLicense("gold", TimeValue.timeValueHours(1)); - TestUtils.registerAndAckSignedLicenses(licensesService, goldLicense, LicensesStatus.VALID); + TestUtils.registerAndAckSignedLicenses(licenseService, goldLicense, LicensesStatus.VALID); License silverLicense = generateSignedLicense("silver", TimeValue.timeValueHours(2)); - TestUtils.registerAndAckSignedLicenses(licensesService, silverLicense, LicensesStatus.VALID); + TestUtils.registerAndAckSignedLicenses(licenseService, silverLicense, LicensesStatus.VALID); License platinumLicense = generateSignedLicense("platinum", TimeValue.timeValueHours(1)); - TestUtils.registerAndAckSignedLicenses(licensesService, platinumLicense, LicensesStatus.VALID); + TestUtils.registerAndAckSignedLicenses(licenseService, platinumLicense, LicensesStatus.VALID); License basicLicense = generateSignedLicense("basic", TimeValue.timeValueHours(3)); - TestUtils.registerAndAckSignedLicenses(licensesService, basicLicense, LicensesStatus.VALID); + TestUtils.registerAndAckSignedLicenses(licenseService, basicLicense, LicensesStatus.VALID); LicensesMetaData licensesMetaData = clusterService.state().metaData().custom(LicensesMetaData.TYPE); assertThat(licensesMetaData.getLicense(), equalTo(basicLicense)); - final License getLicenses = licensesService.getLicense(); + final License getLicenses = licenseService.getLicense(); assertThat(getLicenses, equalTo(basicLicense)); } public void testEffectiveLicenses() throws Exception { - final LicensesService licensesService = getInstanceFromNode(LicensesService.class); + final LicenseService licenseService = getInstanceFromNode(LicenseService.class); final ClusterService clusterService = getInstanceFromNode(ClusterService.class); License goldLicense = generateSignedLicense("gold", TimeValue.timeValueSeconds(5)); // put gold license - TestUtils.registerAndAckSignedLicenses(licensesService, goldLicense, LicensesStatus.VALID); + TestUtils.registerAndAckSignedLicenses(licenseService, goldLicense, LicensesStatus.VALID); LicensesMetaData licensesMetaData = clusterService.state().metaData().custom(LicensesMetaData.TYPE); - assertThat(licensesService.getLicense(licensesMetaData), equalTo(goldLicense)); + assertThat(licenseService.getLicense(licensesMetaData), equalTo(goldLicense)); License platinumLicense = generateSignedLicense("platinum", TimeValue.timeValueSeconds(3)); // put platinum license - TestUtils.registerAndAckSignedLicenses(licensesService, platinumLicense, LicensesStatus.VALID); + TestUtils.registerAndAckSignedLicenses(licenseService, platinumLicense, LicensesStatus.VALID); licensesMetaData = clusterService.state().metaData().custom(LicensesMetaData.TYPE); - assertThat(licensesService.getLicense(licensesMetaData), equalTo(platinumLicense)); + assertThat(licenseService.getLicense(licensesMetaData), equalTo(platinumLicense)); License basicLicense = generateSignedLicense("basic", TimeValue.timeValueSeconds(3)); // put basic license - TestUtils.registerAndAckSignedLicenses(licensesService, basicLicense, LicensesStatus.VALID); + TestUtils.registerAndAckSignedLicenses(licenseService, basicLicense, LicensesStatus.VALID); licensesMetaData = clusterService.state().metaData().custom(LicensesMetaData.TYPE); - assertThat(licensesService.getLicense(licensesMetaData), equalTo(basicLicense)); + assertThat(licenseService.getLicense(licensesMetaData), equalTo(basicLicense)); } public void testInvalidLicenseStorage() throws Exception { - LicensesService licensesService = getInstanceFromNode(LicensesService.class); + LicenseService licenseService = getInstanceFromNode(LicenseService.class); ClusterService clusterService = getInstanceFromNode(ClusterService.class); License signedLicense = generateSignedLicense(TimeValue.timeValueMinutes(2)); @@ -105,7 +105,7 @@ public class LicensesManagerServiceTests extends ESSingleNodeTestCase { .validate() .build(); - TestUtils.registerAndAckSignedLicenses(licensesService, tamperedLicense, LicensesStatus.INVALID); + TestUtils.registerAndAckSignedLicenses(licenseService, tamperedLicense, LicensesStatus.INVALID); // ensure that the invalid license never made it to cluster state LicensesMetaData licensesMetaData = clusterService.state().metaData().custom(LicensesMetaData.TYPE); @@ -113,25 +113,25 @@ public class LicensesManagerServiceTests extends ESSingleNodeTestCase { } public void testRemoveLicenses() throws Exception { - LicensesService licensesService = getInstanceFromNode(LicensesService.class); + LicenseService licenseService = getInstanceFromNode(LicenseService.class); ClusterService clusterService = getInstanceFromNode(ClusterService.class); // generate signed licenses License license = generateSignedLicense(TimeValue.timeValueHours(1)); - TestUtils.registerAndAckSignedLicenses(licensesService, license, LicensesStatus.VALID); + TestUtils.registerAndAckSignedLicenses(licenseService, license, LicensesStatus.VALID); LicensesMetaData licensesMetaData = clusterService.state().metaData().custom(LicensesMetaData.TYPE); assertThat(licensesMetaData.getLicense(), not(LicensesMetaData.LICENSE_TOMBSTONE)); // remove signed licenses - removeAndAckSignedLicenses(licensesService); + removeAndAckSignedLicenses(licenseService); licensesMetaData = clusterService.state().metaData().custom(LicensesMetaData.TYPE); assertThat(licensesMetaData.getLicense(), equalTo(LicensesMetaData.LICENSE_TOMBSTONE)); } - private void removeAndAckSignedLicenses(final LicensesService licensesService) { + private void removeAndAckSignedLicenses(final LicenseService licenseService) { final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean success = new AtomicBoolean(false); - licensesService.removeLicense(new DeleteLicenseRequest(), new ActionListener() { + licenseService.removeLicense(new DeleteLicenseRequest(), new ActionListener() { @Override public void onResponse(ClusterStateUpdateResponse clusterStateUpdateResponse) { if (clusterStateUpdateResponse.isAcknowledged()) { diff --git a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesNotificationTests.java b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesNotificationTests.java index 21f6a28fe1b..3d3640d6062 100644 --- a/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesNotificationTests.java +++ b/elasticsearch/x-pack/license-plugin/src/test/java/org/elasticsearch/license/plugin/core/LicensesNotificationTests.java @@ -26,19 +26,19 @@ public class LicensesNotificationTests extends AbstractLicenseServiceTestCase { assertingLicensees[i] = new AssertingLicensee("testLicenseNotification" + i, logger); } setInitialState(license, assertingLicensees); - licensesService.start(); + licenseService.start(); for (int i = 0; i < assertingLicensees.length; i++) { assertLicenseStates(assertingLicensees[i], LicenseState.ENABLED); } clock.fastForward(TimeValue.timeValueMillis(license.expiryDate() - clock.millis())); final LicensesMetaData licensesMetaData = new LicensesMetaData(license); - licensesService.onUpdate(licensesMetaData); + licenseService.onUpdate(licensesMetaData); for (AssertingLicensee assertingLicensee : assertingLicensees) { assertLicenseStates(assertingLicensee, LicenseState.ENABLED, LicenseState.GRACE_PERIOD); } clock.fastForward(TimeValue.timeValueMillis((license.expiryDate() + LicenseState.GRACE_PERIOD_DURATION.getMillis()) - clock.millis())); - licensesService.onUpdate(licensesMetaData); + licenseService.onUpdate(licensesMetaData); for (AssertingLicensee assertingLicensee : assertingLicensees) { assertLicenseStates(assertingLicensee, LicenseState.ENABLED, LicenseState.GRACE_PERIOD, LicenseState.DISABLED); } @@ -46,7 +46,7 @@ public class LicensesNotificationTests extends AbstractLicenseServiceTestCase { final License newLicense = TestUtils.generateSignedLicense(TimeValue.timeValueHours(2)); clock.fastForward(TimeValue.timeValueHours(1)); LicensesMetaData licensesMetaData1 = new LicensesMetaData(newLicense); - licensesService.onUpdate(licensesMetaData1); + licenseService.onUpdate(licensesMetaData1); for (AssertingLicensee assertingLicensee : assertingLicensees) { assertLicenseStates(assertingLicensee, LicenseState.ENABLED, LicenseState.GRACE_PERIOD, LicenseState.DISABLED, LicenseState.ENABLED); diff --git a/elasticsearch/x-pack/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/agent/collector/cluster/ClusterStatsCollector.java b/elasticsearch/x-pack/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/agent/collector/cluster/ClusterStatsCollector.java index a24cf9e5d7e..b9819159c62 100644 --- a/elasticsearch/x-pack/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/agent/collector/cluster/ClusterStatsCollector.java +++ b/elasticsearch/x-pack/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/agent/collector/cluster/ClusterStatsCollector.java @@ -14,7 +14,7 @@ import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.license.plugin.core.LicenseUtils; -import org.elasticsearch.license.plugin.core.LicensesService; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.xpack.monitoring.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.MonitoringSettings; import org.elasticsearch.xpack.monitoring.agent.collector.AbstractCollector; @@ -40,16 +40,16 @@ public class ClusterStatsCollector extends AbstractCollector { public static final String NAME = "cluster-stats-collector"; - private final LicensesService licensesService; + private final LicenseService licenseService; private final Client client; @Inject public ClusterStatsCollector(Settings settings, ClusterService clusterService, MonitoringSettings monitoringSettings, MonitoringLicensee licensee, InternalClient client, - LicensesService licensesService) { + LicenseService licenseService) { super(settings, NAME, clusterService, monitoringSettings, licensee); this.client = client; - this.licensesService = licensesService; + this.licenseService = licenseService; } @Override @@ -85,7 +85,7 @@ public class ClusterStatsCollector extends AbstractCollector { clusterInfoDoc.setSourceNode(sourceNode); clusterInfoDoc.setClusterName(clusterService.getClusterName().value()); clusterInfoDoc.setVersion(Version.CURRENT.toString()); - clusterInfoDoc.setLicense(licensesService.getLicense()); + clusterInfoDoc.setLicense(licenseService.getLicense()); clusterInfoDoc.setClusterStats(clusterStats); results.add(clusterInfoDoc); diff --git a/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/agent/collector/AbstractCollectorTestCase.java b/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/agent/collector/AbstractCollectorTestCase.java index 59ddc194046..c491380eeeb 100644 --- a/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/agent/collector/AbstractCollectorTestCase.java +++ b/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/agent/collector/AbstractCollectorTestCase.java @@ -25,9 +25,9 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.env.Environment; import org.elasticsearch.license.core.License; import org.elasticsearch.license.plugin.Licensing; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.license.plugin.core.LicenseState; import org.elasticsearch.license.plugin.core.Licensee; -import org.elasticsearch.license.plugin.core.LicensesService; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.test.ESIntegTestCase; @@ -192,7 +192,7 @@ public abstract class AbstractCollectorTestCase extends MonitoringIntegTestCase @Override public Collection nodeModules() { - return Collections.singletonList(b -> b.bind(LicensesService.class).to(LicenseServiceForCollectors.class)); + return Collections.singletonList(b -> b.bind(LicenseService.class).to(LicenseServiceForCollectors.class)); } @Override @@ -202,9 +202,9 @@ public abstract class AbstractCollectorTestCase extends MonitoringIntegTestCase WatcherLicensee watcherLicensee = new WatcherLicensee(settings); MonitoringLicensee monitoringLicensee = new MonitoringLicensee(settings); GraphLicensee graphLicensee = new GraphLicensee(settings); - LicensesService licensesService = new LicenseServiceForCollectors(settings, environment, + LicenseService licenseService = new LicenseServiceForCollectors(settings, environment, resourceWatcherService, Arrays.asList(watcherLicensee, monitoringLicensee, graphLicensee)); - return Arrays.asList(licensesService, watcherLicensee, monitoringLicensee, graphLicensee); + return Arrays.asList(licenseService, watcherLicensee, monitoringLicensee, graphLicensee); } @Override @@ -226,7 +226,7 @@ public abstract class AbstractCollectorTestCase extends MonitoringIntegTestCase } } - public static class LicenseServiceForCollectors extends LicensesService { + public static class LicenseServiceForCollectors extends LicenseService { private final List licensees; private volatile License license; diff --git a/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/agent/collector/cluster/ClusterStatsCollectorTests.java b/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/agent/collector/cluster/ClusterStatsCollectorTests.java index 6bc24d3d12c..52dacb48da7 100644 --- a/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/agent/collector/cluster/ClusterStatsCollectorTests.java +++ b/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/agent/collector/cluster/ClusterStatsCollectorTests.java @@ -11,7 +11,7 @@ import org.apache.lucene.util.LuceneTestCase.BadApple; import org.elasticsearch.Version; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.license.plugin.core.LicensesService; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.xpack.monitoring.MonitoredSystem; import org.elasticsearch.xpack.monitoring.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.MonitoringSettings; @@ -133,7 +133,7 @@ public class ClusterStatsCollectorTests extends AbstractCollectorTestCase { internalCluster().getInstance(MonitoringSettings.class, nodeId), internalCluster().getInstance(MonitoringLicensee.class, nodeId), securedClient(nodeId), - internalCluster().getInstance(LicensesService.class, nodeId)); + internalCluster().getInstance(LicenseService.class, nodeId)); } private void assertCanCollect(AbstractCollector collector, Class... classes) { diff --git a/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/license/LicenseIntegrationTests.java b/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/license/LicenseIntegrationTests.java index 732016dc92a..d015f425c68 100644 --- a/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/license/LicenseIntegrationTests.java +++ b/elasticsearch/x-pack/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/license/LicenseIntegrationTests.java @@ -14,10 +14,9 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.license.core.License; import org.elasticsearch.license.plugin.Licensing; -import org.elasticsearch.license.plugin.core.AbstractLicenseeComponent; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.license.plugin.core.LicenseState; import org.elasticsearch.license.plugin.core.Licensee; -import org.elasticsearch.license.plugin.core.LicensesService; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; @@ -31,7 +30,6 @@ import org.elasticsearch.xpack.support.clock.Clock; import org.elasticsearch.xpack.watcher.WatcherLicensee; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -96,7 +94,7 @@ public class LicenseIntegrationTests extends MonitoringIntegTestCase { @Override public Collection nodeModules() { - return Collections.singletonList(b -> b.bind(LicensesService.class).to(MockLicenseService.class)); + return Collections.singletonList(b -> b.bind(LicenseService.class).to(MockLicenseService.class)); } @Override @@ -106,9 +104,9 @@ public class LicenseIntegrationTests extends MonitoringIntegTestCase { WatcherLicensee watcherLicensee = new WatcherLicensee(settings); MonitoringLicensee monitoringLicensee = new MonitoringLicensee(settings); GraphLicensee graphLicensee = new GraphLicensee(settings); - LicensesService licensesService = new MockLicenseService(settings, environment, resourceWatcherService, + LicenseService licenseService = new MockLicenseService(settings, environment, resourceWatcherService, Arrays.asList(watcherLicensee, monitoringLicensee, graphLicensee)); - return Arrays.asList(licensesService, watcherLicensee, monitoringLicensee, graphLicensee); + return Arrays.asList(licenseService, watcherLicensee, monitoringLicensee, graphLicensee); } @Override @@ -122,7 +120,7 @@ public class LicenseIntegrationTests extends MonitoringIntegTestCase { } } - public static class MockLicenseService extends LicensesService { + public static class MockLicenseService extends LicenseService { private final List licensees; diff --git a/elasticsearch/x-pack/security/src/test/java/org/elasticsearch/integration/LicensingTests.java b/elasticsearch/x-pack/security/src/test/java/org/elasticsearch/integration/LicensingTests.java index f5558bb9b73..e1710c6e61a 100644 --- a/elasticsearch/x-pack/security/src/test/java/org/elasticsearch/integration/LicensingTests.java +++ b/elasticsearch/x-pack/security/src/test/java/org/elasticsearch/integration/LicensingTests.java @@ -34,9 +34,9 @@ import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; import org.elasticsearch.license.core.License.OperationMode; import org.elasticsearch.license.plugin.Licensing; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.license.plugin.core.LicenseState; import org.elasticsearch.license.plugin.core.Licensee; -import org.elasticsearch.license.plugin.core.LicensesService; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.rest.RestStatus; @@ -237,7 +237,7 @@ public class LicensingTests extends SecurityIntegTestCase { } public static void disableLicensing(OperationMode operationMode) { - for (TestLicensesService service : internalCluster().getInstances(TestLicensesService.class)) { + for (TestLicenseService service : internalCluster().getInstances(TestLicenseService.class)) { service.disable(operationMode); } } @@ -247,7 +247,7 @@ public class LicensingTests extends SecurityIntegTestCase { } public static void enableLicensing(OperationMode operationMode) { - for (TestLicensesService service : internalCluster().getInstances(TestLicensesService.class)) { + for (TestLicenseService service : internalCluster().getInstances(TestLicenseService.class)) { service.enable(operationMode); } } @@ -256,7 +256,7 @@ public class LicensingTests extends SecurityIntegTestCase { @Override public Collection nodeModules() { - return Collections.singletonList(b -> b.bind(LicensesService.class).to(TestLicensesService.class)); + return Collections.singletonList(b -> b.bind(LicenseService.class).to(TestLicenseService.class)); } @Override @@ -267,7 +267,7 @@ public class LicensingTests extends SecurityIntegTestCase { WatcherLicensee watcherLicensee = new WatcherLicensee(settings); MonitoringLicensee monitoringLicensee = new MonitoringLicensee(settings); GraphLicensee graphLicensee = new GraphLicensee(settings); - TestLicensesService licensesService = new TestLicensesService(settings, environment, resourceWatcherService, + TestLicenseService licensesService = new TestLicenseService(settings, environment, resourceWatcherService, Arrays.asList(securityLicensee, watcherLicensee, monitoringLicensee, graphLicensee)); return Arrays.asList(securityLicensee, licensesService, watcherLicensee, monitoringLicensee, graphLicensee, securityLicenseState); @@ -296,12 +296,12 @@ public class LicensingTests extends SecurityIntegTestCase { } } - public static class TestLicensesService extends LicensesService { + public static class TestLicenseService extends LicenseService { private final List licensees; - public TestLicensesService(Settings settings, Environment env, ResourceWatcherService resourceWatcherService, - List licensees) { + public TestLicenseService(Settings settings, Environment env, ResourceWatcherService resourceWatcherService, + List licensees) { super(settings, null, null, env, resourceWatcherService, Collections.emptyList()); this.licensees = licensees; enable(OperationMode.BASIC); diff --git a/elasticsearch/x-pack/src/main/java/org/elasticsearch/xpack/XPackPlugin.java b/elasticsearch/x-pack/src/main/java/org/elasticsearch/xpack/XPackPlugin.java index d0db226238e..6543a8332bb 100644 --- a/elasticsearch/x-pack/src/main/java/org/elasticsearch/xpack/XPackPlugin.java +++ b/elasticsearch/x-pack/src/main/java/org/elasticsearch/xpack/XPackPlugin.java @@ -169,7 +169,7 @@ public class XPackPlugin extends Plugin implements ScriptPlugin, ActionPlugin, I if (transportClientMode == false) { modules.add(new TextTemplateModule()); - // Note: this only exists so LicensesService subclasses can be bound in mock tests + // Note: this only exists so LicenseService subclasses can be bound in mock tests modules.addAll(licensing.nodeModules()); } return modules; diff --git a/elasticsearch/x-pack/src/main/java/org/elasticsearch/xpack/action/TransportXPackInfoAction.java b/elasticsearch/x-pack/src/main/java/org/elasticsearch/xpack/action/TransportXPackInfoAction.java index 2473618c571..dfc9c6bcb6a 100644 --- a/elasticsearch/x-pack/src/main/java/org/elasticsearch/xpack/action/TransportXPackInfoAction.java +++ b/elasticsearch/x-pack/src/main/java/org/elasticsearch/xpack/action/TransportXPackInfoAction.java @@ -12,7 +12,7 @@ import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.license.core.License; -import org.elasticsearch.license.plugin.core.LicensesService; +import org.elasticsearch.license.plugin.core.LicenseService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.XPackBuild; @@ -27,16 +27,16 @@ import java.util.stream.Collectors; */ public class TransportXPackInfoAction extends HandledTransportAction { - private final LicensesService licensesService; + private final LicenseService licenseService; private final Set featureSets; @Inject public TransportXPackInfoAction(Settings settings, ThreadPool threadPool, TransportService transportService, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver, - LicensesService licensesService, Set featureSets) { + LicenseService licenseService, Set featureSets) { super(settings, XPackInfoAction.NAME, threadPool, transportService, actionFilters, indexNameExpressionResolver, XPackInfoRequest::new); - this.licensesService = licensesService; + this.licenseService = licenseService; this.featureSets = featureSets; } @@ -51,7 +51,7 @@ public class TransportXPackInfoAction extends HandledTransportAction featureSets = new HashSet<>(); int featureSetCount = randomIntBetween(0, 5); @@ -72,7 +72,7 @@ public class TransportXPackInfoActionTests extends ESTestCase { TransportXPackInfoAction action = new TransportXPackInfoAction(Settings.EMPTY, mock(ThreadPool.class), mock(TransportService.class), mock(ActionFilters.class), mock(IndexNameExpressionResolver.class), - licensesService, featureSets); + licenseService, featureSets); License license = mock(License.class); long expiryDate = randomLong(); @@ -85,7 +85,7 @@ public class TransportXPackInfoActionTests extends ESTestCase { when(license.operationMode()).thenReturn(mode); String uid = randomAsciiOfLength(30); when(license.uid()).thenReturn(uid); - when(licensesService.getLicense()).thenReturn(license); + when(licenseService.getLicense()).thenReturn(license); XPackInfoRequest request = new XPackInfoRequest(); request.setVerbose(randomBoolean()); diff --git a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/index/IndexActionIntegrationTests.java b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/index/IndexActionIntegrationTests.java deleted file mode 100644 index d2d08775b36..00000000000 --- a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/index/IndexActionIntegrationTests.java +++ /dev/null @@ -1,205 +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.actions.index; - -import org.apache.lucene.util.LuceneTestCase.AwaitsFix; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.search.SearchHit; -import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; -import org.elasticsearch.search.sort.SortOrder; -import org.elasticsearch.xpack.watcher.history.HistoryStore; -import org.elasticsearch.xpack.watcher.support.WatcherDateTimeUtils; -import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; -import org.elasticsearch.xpack.watcher.transport.actions.execute.ExecuteWatchResponse; -import org.elasticsearch.xpack.watcher.transport.actions.put.PutWatchResponse; -import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; - -import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.QueryBuilders.matchQuery; -import static org.elasticsearch.search.aggregations.AggregationBuilders.dateHistogram; -import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; -import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.indexAction; -import static org.elasticsearch.xpack.watcher.client.WatchSourceBuilders.watchBuilder; -import static org.elasticsearch.xpack.watcher.input.InputBuilders.searchInput; -import static org.elasticsearch.xpack.watcher.input.InputBuilders.simpleInput; -import static org.elasticsearch.xpack.watcher.transform.TransformBuilders.scriptTransform; -import static org.elasticsearch.xpack.watcher.trigger.TriggerBuilders.schedule; -import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.cron; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.is; - -/** - * - */ -@AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") -public class IndexActionIntegrationTests extends AbstractWatcherIntegrationTestCase { - public void testSimple() throws Exception { - PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() - .trigger(schedule(cron("0/1 * * * * ? 2020"))) - .input(simpleInput("foo", "bar")) - .addAction("index-buckets", indexAction("idx", "type").setExecutionTimeField("@timestamp"))) - .get(); - - assertThat(putWatchResponse.isCreated(), is(true)); - - DateTime now = timeWarped() ? timeWarp().clock().now(DateTimeZone.UTC) : DateTime.now(DateTimeZone.UTC); - - ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .get(); - - assertThat(executeWatchResponse.getRecordSource().getValue("state"), is((Object) "executed")); - - flush("idx"); - refresh(); - - SearchResponse searchResponse = client().prepareSearch("idx").setTypes("type").get(); - assertThat(searchResponse.getHits().totalHits(), is(1L)); - SearchHit hit = searchResponse.getHits().getAt(0); - if (timeWarped()) { - assertThat(hit.getSource(), hasEntry("@timestamp", (Object) WatcherDateTimeUtils.formatDate(now))); - } else { - assertThat(hit.getSource(), hasKey("@timestamp")); - DateTime timestamp = WatcherDateTimeUtils.parseDate((String) hit.getSource().get("@timestamp")); - assertThat(timestamp.isEqual(now) || timestamp.isAfter(now), is(true)); - } - assertThat(hit.getSource(), hasEntry("foo", (Object) "bar")); - } - - public void testSimpleWithDocField() throws Exception { - PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() - .trigger(schedule(cron("0/1 * * * * ? 2020"))) - .input(simpleInput("foo", "bar")) - .addAction("index-buckets", - scriptTransform("return [ '_doc' : ctx.payload ]"), - indexAction("idx", "type").setExecutionTimeField("@timestamp"))) - - .get(); - - assertThat(putWatchResponse.isCreated(), is(true)); - - DateTime now = timeWarped() ? timeWarp().clock().now(DateTimeZone.UTC) : DateTime.now(DateTimeZone.UTC); - - ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .get(); - - assertThat(executeWatchResponse.getRecordSource().getValue("state"), is((Object) "executed")); - - flush("idx"); - refresh(); - - SearchResponse searchResponse = client().prepareSearch("idx").setTypes("type").get(); - assertThat(searchResponse.getHits().totalHits(), is(1L)); - SearchHit hit = searchResponse.getHits().getAt(0); - if (timeWarped()) { - assertThat(hit.getSource(), hasEntry("@timestamp", (Object) WatcherDateTimeUtils.formatDate(now))); - } else { - assertThat(hit.getSource(), hasKey("@timestamp")); - DateTime timestamp = WatcherDateTimeUtils.parseDate((String) hit.getSource().get("@timestamp")); - assertThat(timestamp.isEqual(now) || timestamp.isAfter(now), is(true)); - } - assertThat(hit.getSource(), hasEntry("foo", (Object) "bar")); - } - - public void testSimpleWithDocFieldWrongFieldType() throws Exception { - PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() - .trigger(schedule(cron("0/1 * * * * ? 2020"))) - .input(simpleInput("foo", "bar")) - .addAction("index-buckets", - scriptTransform("return [ '_doc' : 1 ]"), - indexAction("idx", "type").setExecutionTimeField("@timestamp"))) - .get(); - - assertThat(putWatchResponse.isCreated(), is(true)); - - DateTime now = timeWarped() ? timeWarp().clock().now(DateTimeZone.UTC) : DateTime.now(DateTimeZone.UTC); - - ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .setRecordExecution(true) - .get(); - - assertThat(executeWatchResponse.getRecordSource().getValue("state"), is((Object) "executed")); - - flush(); - refresh(); - - assertThat(client().admin().indices().prepareExists("idx").get().isExists(), is(false)); - - assertThat(docCount(HistoryStore.INDEX_PREFIX_WITH_TEMPLATE + "*", HistoryStore.DOC_TYPE, searchSource() - .query(matchQuery("result.actions.status", "failure"))), is(1L)); - - } - - public void testIndexAggsBucketsAsDocuments() throws Exception { - DateTime now = timeWarped() ? timeWarp().clock().now(DateTimeZone.UTC) : DateTime.now(DateTimeZone.UTC); - long bucketCount = randomIntBetween(2, 5); - for (int i = 0; i < bucketCount; i++) { - index("idx", "type", jsonBuilder().startObject() - .field("timestamp", now.minusDays(i)) - .endObject()); - } - - flush("idx"); - refresh(); - - PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() - .trigger(schedule(cron("0/1 * * * * ? 2020"))) - .input(searchInput(new SearchRequest("idx") - .types("type") - .searchType(SearchType.QUERY_THEN_FETCH) - .source(searchSource() - .aggregation(dateHistogram("trend") - .field("timestamp") - .dateHistogramInterval(DateHistogramInterval.DAY))))) - .addAction("index-buckets", - - // this transform takes the bucket list and assigns it to `_doc` - // this means each bucket will be indexed as a separate doc, - // so we expect to have the same number of documents as the number - // of buckets. - scriptTransform("return [ '_doc' : ctx.payload.aggregations.trend.buckets]"), - - indexAction("idx", "bucket").setExecutionTimeField("@timestamp"))) - - .get(); - - assertThat(putWatchResponse.isCreated(), is(true)); - - ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .get(); - - assertThat(executeWatchResponse.getRecordSource().getValue("state"), is((Object) "executed")); - - flush("idx"); - refresh(); - - SearchResponse searchResponse = client().prepareSearch("idx").setTypes("bucket") - .addSort("key", SortOrder.DESC) - .get(); - assertThat(searchResponse.getHits().getTotalHits(), is(bucketCount)); - DateTime key = now.withMillisOfDay(0); - int i = 0; - for (SearchHit hit : searchResponse.getHits()) { - if (timeWarped()) { - assertThat(hit.getSource(), hasEntry("@timestamp", (Object) WatcherDateTimeUtils.formatDate(now))); - } else { - assertThat(hit.getSource(), hasKey("@timestamp")); - DateTime timestamp = WatcherDateTimeUtils.parseDate((String) hit.getSource().get("@timestamp")); - assertThat(timestamp.isEqual(now) || timestamp.isAfter(now), is(true)); - } - assertThat(hit.getSource(), hasEntry("key", (Object) key.getMillis())); - key = key.minusDays(1); - } - } -}