diff --git a/pom.xml b/pom.xml index 4cbef88bd8b..6e56664bf4a 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ 4.0.0 org.elasticsearch - elasticsearch-alerts + elasticsearch-watcher 1.0.0-beta2-SNAPSHOT diff --git a/src/main/java/org/elasticsearch/alerts/AlertsModule.java b/src/main/java/org/elasticsearch/alerts/AlertsModule.java deleted file mode 100644 index 189029001a7..00000000000 --- a/src/main/java/org/elasticsearch/alerts/AlertsModule.java +++ /dev/null @@ -1,57 +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.alerts; - - -import org.elasticsearch.alerts.actions.ActionModule; -import org.elasticsearch.alerts.client.AlertsClientModule; -import org.elasticsearch.alerts.condition.ConditionModule; -import org.elasticsearch.alerts.history.HistoryModule; -import org.elasticsearch.alerts.input.InputModule; -import org.elasticsearch.alerts.rest.AlertsRestModule; -import org.elasticsearch.alerts.scheduler.SchedulerModule; -import org.elasticsearch.alerts.support.TemplateUtils; -import org.elasticsearch.alerts.support.clock.ClockModule; -import org.elasticsearch.alerts.support.init.InitializingModule; -import org.elasticsearch.alerts.support.template.TemplateModule; -import org.elasticsearch.alerts.transform.TransformModule; -import org.elasticsearch.alerts.transport.AlertsTransportModule; -import org.elasticsearch.common.collect.ImmutableList; -import org.elasticsearch.common.inject.AbstractModule; -import org.elasticsearch.common.inject.Module; -import org.elasticsearch.common.inject.SpawnModules; - - -public class AlertsModule extends AbstractModule implements SpawnModules { - - @Override - public Iterable spawnModules() { - return ImmutableList.of( - new InitializingModule(), - new TemplateModule(), - new ClockModule(), - new AlertsClientModule(), - new TransformModule(), - new AlertsRestModule(), - new SchedulerModule(), - new AlertsTransportModule(), - new ConditionModule(), - new InputModule(), - new ActionModule(), - new HistoryModule()); - } - - @Override - protected void configure() { - bind(Alert.Parser.class).asEagerSingleton(); - bind(AlertLockService.class).asEagerSingleton(); - bind(AlertsLifeCycleService.class).asEagerSingleton(); - bind(AlertsService.class).asEagerSingleton(); - bind(AlertsStore.class).asEagerSingleton(); - bind(TemplateUtils.class).asEagerSingleton(); - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/client/AlertsClient.java b/src/main/java/org/elasticsearch/alerts/client/AlertsClient.java deleted file mode 100644 index ffd9fe41435..00000000000 --- a/src/main/java/org/elasticsearch/alerts/client/AlertsClient.java +++ /dev/null @@ -1,253 +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.alerts.client; - -import org.elasticsearch.action.ActionFuture; -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.alerts.transport.actions.ack.AckAlertAction; -import org.elasticsearch.alerts.transport.actions.ack.AckAlertRequest; -import org.elasticsearch.alerts.transport.actions.ack.AckAlertRequestBuilder; -import org.elasticsearch.alerts.transport.actions.ack.AckAlertResponse; -import org.elasticsearch.alerts.transport.actions.delete.DeleteAlertAction; -import org.elasticsearch.alerts.transport.actions.delete.DeleteAlertRequest; -import org.elasticsearch.alerts.transport.actions.delete.DeleteAlertRequestBuilder; -import org.elasticsearch.alerts.transport.actions.delete.DeleteAlertResponse; -import org.elasticsearch.alerts.transport.actions.get.GetAlertAction; -import org.elasticsearch.alerts.transport.actions.get.GetAlertRequest; -import org.elasticsearch.alerts.transport.actions.get.GetAlertRequestBuilder; -import org.elasticsearch.alerts.transport.actions.get.GetAlertResponse; -import org.elasticsearch.alerts.transport.actions.put.PutAlertAction; -import org.elasticsearch.alerts.transport.actions.put.PutAlertRequest; -import org.elasticsearch.alerts.transport.actions.put.PutAlertRequestBuilder; -import org.elasticsearch.alerts.transport.actions.put.PutAlertResponse; -import org.elasticsearch.alerts.transport.actions.service.AlertsServiceAction; -import org.elasticsearch.alerts.transport.actions.service.AlertsServiceRequest; -import org.elasticsearch.alerts.transport.actions.service.AlertsServiceRequestBuilder; -import org.elasticsearch.alerts.transport.actions.service.AlertsServiceResponse; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsAction; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsRequest; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsRequestBuilder; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsResponse; -import org.elasticsearch.client.Client; -import org.elasticsearch.common.inject.Inject; - -/** - */ -public class AlertsClient { - - private final Client client; - - @Inject - public AlertsClient(Client client) { - this.client = client; - } - - /** - * Creates a request builder that gets an alert by name (id) - * - * @param alertName the name (id) of the alert - * @return The request builder - */ - public GetAlertRequestBuilder prepareGetAlert(String alertName) { - return new GetAlertRequestBuilder(client, alertName); - } - - /** - * Creates a request builder that gets an alert - * - * @return the request builder - */ - public GetAlertRequestBuilder prepareGetAlert() { - return new GetAlertRequestBuilder(client); - } - - /** - * Gets an alert from the alert index - * - * @param request The get alert request - * @param listener The listener for the get alert response containing the GetResponse for this alert - */ - public void getAlert(GetAlertRequest request, ActionListener listener) { - client.execute(GetAlertAction.INSTANCE, request, listener); - } - - /** - * Gets an alert from the alert index - * - * @param request The get alert request with the alert name (id) - * @return The response containing the GetResponse for this alert - */ - public ActionFuture getAlert(GetAlertRequest request) { - return client.execute(GetAlertAction.INSTANCE, request); - } - - /** - * Creates a request builder to delete an alert by name (id) - * - * @param alertName the name (id) of the alert - * @return The request builder - */ - public DeleteAlertRequestBuilder prepareDeleteAlert(String alertName) { - return new DeleteAlertRequestBuilder(client, alertName); - } - - /** - * Creates a request builder that deletes an alert - * - * @return The request builder - */ - public DeleteAlertRequestBuilder prepareDeleteAlert() { - return new DeleteAlertRequestBuilder(client); - } - - /** - * Deletes an alert - * - * @param request The delete request with the alert name (id) to be deleted - * @param listener The listener for the delete alert response containing the DeleteResponse for this action - */ - public void deleteAlert(DeleteAlertRequest request, ActionListener listener) { - client.execute(DeleteAlertAction.INSTANCE, request, listener); - } - - /** - * Deletes an alert - * - * @param request The delete request with the alert name (id) to be deleted - * @return The response containing the DeleteResponse for this action - */ - public ActionFuture deleteAlert(DeleteAlertRequest request) { - return client.execute(DeleteAlertAction.INSTANCE, request); - } - - /** - * Creates a request builder to build a request to put an alert - * - * @param alertName The name of the alert to put - * @return The builder to create the alert - */ - public PutAlertRequestBuilder preparePutAlert(String alertName) { - return new PutAlertRequestBuilder(client, alertName); - } - - /** - * Creates a request builder to build a request to put an alert - * - * @return The builder - */ - public PutAlertRequestBuilder preparePutAlert() { - return new PutAlertRequestBuilder(client); - } - - /** - * Put an alert and registers it with the scheduler - * - * @param request The request containing the alert to index and register - * @param listener The listener for the response containing the IndexResponse for this alert - */ - public void putAlert(PutAlertRequest request, ActionListener listener) { - client.execute(PutAlertAction.INSTANCE, request, listener); - } - - /** - * Put an alert and registers it with the scheduler - * - * @param request The request containing the alert to index and register - * @return The response containing the IndexResponse for this alert - */ - public ActionFuture putAlert(PutAlertRequest request) { - return client.execute(PutAlertAction.INSTANCE, request); - } - - /** - * Gets the alert stats - * - * @param request The request for the alert stats - * @return The response containing the StatsResponse for this action - */ - public ActionFuture alertsStats(AlertsStatsRequest request) { - return client.execute(AlertsStatsAction.INSTANCE, request); - } - - /** - * Creates a request builder to build a request to get the alerts stats - * - * @return The builder get the alerts stats - */ - public AlertsStatsRequestBuilder prepareAlertsStats() { - return new AlertsStatsRequestBuilder(client); - } - - /** - * Gets the alert stats - * - * @param request The request for the alert stats - * @param listener The listener for the response containing the AlertsStatsResponse - */ - public void alertsStats(AlertsStatsRequest request, ActionListener listener) { - client.execute(AlertsStatsAction.INSTANCE, request, listener); - } - - /** - * Creates a request builder to ack an alert by name (id) - * - * @param alertName the name (id) of the alert - * @return The request builder - */ - public AckAlertRequestBuilder prepareAckAlert(String alertName) { - return new AckAlertRequestBuilder(client, alertName); - } - - /** - * Creates a request builder that acks an alert - * - * @return The request builder - */ - public AckAlertRequestBuilder prepareAckAlert() { - return new AckAlertRequestBuilder(client); - } - - /** - * Ack an alert - * - * @param request The ack request with the alert name (id) to be acked - * @param listener The listener for the ack alert response - */ - public void ackAlert(AckAlertRequest request, ActionListener listener) { - client.execute(AckAlertAction.INSTANCE, request, listener); - } - - /** - * Acks an alert - * - * @param request The ack request with the alert name (id) to be acked - * @return The AckAlertResponse - */ - public ActionFuture ackAlert(AckAlertRequest request) { - return client.execute(AckAlertAction.INSTANCE, request); - } - - /** - * Prepare make an alert service request. - */ - public AlertsServiceRequestBuilder prepareAlertService() { - return new AlertsServiceRequestBuilder(client); - } - - /** - * Perform an alert service request to either start, stop or restart the alerting plugin. - */ - public void alertService(AlertsServiceRequest request, ActionListener listener) { - client.execute(AlertsServiceAction.INSTANCE, request, listener); - } - - /** - * Perform an alert service request to either start, stop or restart the alerting plugin. - */ - public ActionFuture alertService(AlertsServiceRequest request) { - return client.execute(AlertsServiceAction.INSTANCE, request); - } -} diff --git a/src/main/java/org/elasticsearch/alerts/history/HistoryStore.java b/src/main/java/org/elasticsearch/alerts/history/HistoryStore.java deleted file mode 100644 index 09c140e581c..00000000000 --- a/src/main/java/org/elasticsearch/alerts/history/HistoryStore.java +++ /dev/null @@ -1,189 +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.alerts.history; - -import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; -import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.action.search.*; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.alerts.support.TemplateUtils; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.cluster.ClusterState; -import org.elasticsearch.cluster.metadata.IndexMetaData; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.component.AbstractComponent; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.joda.time.DateTime; -import org.elasticsearch.common.joda.time.format.DateTimeFormat; -import org.elasticsearch.common.joda.time.format.DateTimeFormatter; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.search.SearchHit; -import org.elasticsearch.search.builder.SearchSourceBuilder; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - */ -public class HistoryStore extends AbstractComponent { - - public static final String ALERT_HISTORY_INDEX_PREFIX = ".alert_history_"; - public static final String ALERT_HISTORY_TYPE = "fired_alert"; - - static final DateTimeFormatter alertHistoryIndexTimeFormat = DateTimeFormat.forPattern("YYYY-MM-dd"); - - private final ClientProxy client; - private final TemplateUtils templateUtils; - private final int scrollSize; - private final TimeValue scrollTimeout; - private final FiredAlert.Parser alertRecordParser; - - @Inject - public HistoryStore(Settings settings, ClientProxy client, TemplateUtils templateUtils, FiredAlert.Parser alertRecordParser) { - super(settings); - this.client = client; - this.templateUtils = templateUtils; - this.alertRecordParser = alertRecordParser; - this.scrollTimeout = settings.getAsTime("alerts.scroll.timeout", TimeValue.timeValueSeconds(30)); - this.scrollSize = settings.getAsInt("alerts.scroll.size", 100); - } - - public void put(FiredAlert firedAlert) throws HistoryException { - String alertHistoryIndex = getAlertHistoryIndexNameForTime(firedAlert.scheduledTime()); - try { - IndexResponse response = client.prepareIndex(alertHistoryIndex, ALERT_HISTORY_TYPE, firedAlert.id()) - .setSource(XContentFactory.jsonBuilder().value(firedAlert)) - .setOpType(IndexRequest.OpType.CREATE) - .get(); - firedAlert.version(response.getVersion()); - } catch (IOException e) { - throw new HistoryException("persisting new fired alert [" + firedAlert + "] failed", e); - } - } - - public void update(FiredAlert firedAlert) throws HistoryException { - logger.debug("updating fired alert [{}]", firedAlert); - try { - BytesReference bytes = XContentFactory.jsonBuilder().value(firedAlert).bytes(); - IndexResponse response = client.prepareIndex(getAlertHistoryIndexNameForTime(firedAlert.scheduledTime()), ALERT_HISTORY_TYPE, firedAlert.id()) - .setSource(bytes) - .setVersion(firedAlert.version()) - .get(); - firedAlert.version(response.getVersion()); - logger.debug("updated fired alert [{}]", firedAlert); - } catch (IOException e) { - throw new HistoryException("persisting fired alert [" + firedAlert + "] failed", e); - } - } - - public LoadResult loadFiredAlerts(ClusterState state, FiredAlert.State firedAlertState) { - String[] indices = state.metaData().concreteIndices(IndicesOptions.lenientExpandOpen(), ALERT_HISTORY_INDEX_PREFIX + "*"); - if (indices.length == 0) { - logger.debug("No .alert_history indices found, skip loading of alert actions"); - templateUtils.ensureIndexTemplateIsLoaded(state, "alerthistory"); - return new LoadResult(true); - } - int numPrimaryShards = 0; - for (String index : indices) { - IndexMetaData indexMetaData = state.getMetaData().index(index); - if (indexMetaData != null) { - if (!state.routingTable().index(index).allPrimaryShardsActive()) { - logger.debug("Not all primary shards of the [{}] index are started. Schedule to retry alert action loading..", index); - return new LoadResult(false); - } else { - numPrimaryShards += indexMetaData.numberOfShards(); - } - } - } - - RefreshResponse refreshResponse = client.refresh(new RefreshRequest(ALERT_HISTORY_INDEX_PREFIX + "*")); - if (refreshResponse.getSuccessfulShards() < numPrimaryShards) { - return new LoadResult(false); - } - - SearchRequest searchRequest = createScanSearchRequest(firedAlertState); - SearchResponse response = client.search(searchRequest); - List alerts = new ArrayList<>(); - try { - if (response.getTotalShards() != response.getSuccessfulShards()) { - return new LoadResult(false); - } - - if (response.getHits().getTotalHits() > 0) { - response = client.searchScroll(response.getScrollId(), scrollTimeout); - while (response.getHits().hits().length != 0) { - for (SearchHit sh : response.getHits()) { - String historyId = sh.getId(); - FiredAlert historyEntry = alertRecordParser.parse(sh.getSourceRef(), historyId, sh.version()); - assert historyEntry.state() == FiredAlert.State.AWAITS_EXECUTION; - logger.debug("loaded fired alert from index [{}/{}/{}]", sh.index(), sh.type(), sh.id()); - alerts.add(historyEntry); - } - response = client.searchScroll(response.getScrollId(), scrollTimeout); - } - } - } finally { - client.clearScroll(response.getScrollId()); - } - templateUtils.ensureIndexTemplateIsLoaded(state, "alerthistory"); - return new LoadResult(true, alerts); - } - - /** - * Calculates the correct alert history index name for a given time using alertHistoryIndexTimeFormat - */ - public static String getAlertHistoryIndexNameForTime(DateTime time) { - return ALERT_HISTORY_INDEX_PREFIX + alertHistoryIndexTimeFormat.print(time); - } - - private SearchRequest createScanSearchRequest(FiredAlert.State firedAlertState) { - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder() - .query(QueryBuilders.termQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), firedAlertState.id())) - .size(scrollSize) - .version(true); - - SearchRequest searchRequest = new SearchRequest(ALERT_HISTORY_INDEX_PREFIX + "*"); - searchRequest.source(sourceBuilder); - searchRequest.searchType(SearchType.SCAN); - searchRequest.types(ALERT_HISTORY_TYPE); - searchRequest.scroll(scrollTimeout); - searchRequest.preference("_primary"); - return searchRequest; - } - - public class LoadResult implements Iterable { - - private final boolean succeeded; - private final List alerts; - - public LoadResult(boolean succeeded, List alerts) { - this.succeeded = succeeded; - this.alerts = alerts; - } - - public LoadResult(boolean succeeded) { - this.succeeded = succeeded; - this.alerts = Collections.emptyList(); - } - - @Override - public Iterator iterator() { - return alerts.iterator(); - } - - public boolean succeeded() { - return succeeded; - } - } -} diff --git a/src/main/java/org/elasticsearch/alerts/rest/action/RestAckAlertAction.java b/src/main/java/org/elasticsearch/alerts/rest/action/RestAckAlertAction.java deleted file mode 100644 index e662d622476..00000000000 --- a/src/main/java/org/elasticsearch/alerts/rest/action/RestAckAlertAction.java +++ /dev/null @@ -1,50 +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.alerts.rest.action; - -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.AlertsStore; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.transport.actions.ack.AckAlertRequest; -import org.elasticsearch.alerts.transport.actions.ack.AckAlertResponse; -import org.elasticsearch.client.Client; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.rest.*; -import org.elasticsearch.rest.action.support.RestBuilderListener; - -/** - * The rest action to ack an alert - */ -public class RestAckAlertAction extends BaseRestHandler { - - private final AlertsClient alertsClient; - - @Inject - protected RestAckAlertAction(Settings settings, RestController controller, Client client, AlertsClient alertsClient) { - super(settings, controller, client); - this.alertsClient = alertsClient; - controller.registerHandler(RestRequest.Method.PUT, AlertsStore.ALERT_INDEX + "/alert/{name}/_ack", this); - } - - @Override - protected void handleRequest(RestRequest request, RestChannel restChannel, Client client) throws Exception { - final AckAlertRequest ackAlertRequest = new AckAlertRequest(); - ackAlertRequest.setAlertName(request.param("name")); - alertsClient.ackAlert(ackAlertRequest, new RestBuilderListener(restChannel) { - - @Override - public RestResponse buildResponse(AckAlertResponse ackAlertResponse, XContentBuilder builder) throws Exception { - builder.startObject(); - builder.field(Alert.Parser.STATUS_FIELD.getPreferredName(), ackAlertResponse.getStatus().toString()); - builder.endObject(); - return new BytesRestResponse(RestStatus.OK, builder); - } - }); - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/rest/action/RestAlertServiceAction.java b/src/main/java/org/elasticsearch/alerts/rest/action/RestAlertServiceAction.java deleted file mode 100644 index 052c6c3a1b8..00000000000 --- a/src/main/java/org/elasticsearch/alerts/rest/action/RestAlertServiceAction.java +++ /dev/null @@ -1,70 +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.alerts.rest.action; - -import org.elasticsearch.alerts.AlertsStore; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.transport.actions.service.AlertsServiceRequest; -import org.elasticsearch.alerts.transport.actions.service.AlertsServiceResponse; -import org.elasticsearch.client.Client; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.rest.BaseRestHandler; -import org.elasticsearch.rest.RestChannel; -import org.elasticsearch.rest.RestController; -import org.elasticsearch.rest.RestRequest; -import org.elasticsearch.rest.action.support.AcknowledgedRestListener; - -/** - */ -public class RestAlertServiceAction extends BaseRestHandler { - - private final AlertsClient alertsClient; - - @Inject - protected RestAlertServiceAction(Settings settings, RestController controller, Client client, AlertsClient alertsClient) { - super(settings, controller, client); - this.alertsClient = alertsClient; - controller.registerHandler(RestRequest.Method.PUT, AlertsStore.ALERT_INDEX + "/_restart", this); - controller.registerHandler(RestRequest.Method.PUT, AlertsStore.ALERT_INDEX + "/_start", new StartRestHandler(settings, controller, client)); - controller.registerHandler(RestRequest.Method.PUT, AlertsStore.ALERT_INDEX + "/_stop", new StopRestHandler(settings, controller, client)); - } - - @Override - protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { - AlertsServiceRequest serviceRequest = new AlertsServiceRequest(); - serviceRequest.restart(); - alertsClient.alertService(serviceRequest, new AcknowledgedRestListener(channel)); - } - - final class StartRestHandler extends BaseRestHandler { - - public StartRestHandler(Settings settings, RestController controller, Client client) { - super(settings, controller, client); - } - - @Override - public void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { - AlertsServiceRequest serviceRequest = new AlertsServiceRequest(); - serviceRequest.start(); - alertsClient.alertService(serviceRequest, new AcknowledgedRestListener(channel)); - } - } - - final class StopRestHandler extends BaseRestHandler { - - public StopRestHandler(Settings settings, RestController controller, Client client) { - super(settings, controller, client); - } - - @Override - public void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { - AlertsServiceRequest serviceRequest = new AlertsServiceRequest(); - serviceRequest.stop(); - alertsClient.alertService(serviceRequest, new AcknowledgedRestListener(channel)); - } - } -} diff --git a/src/main/java/org/elasticsearch/alerts/rest/action/RestAlertsStatsAction.java b/src/main/java/org/elasticsearch/alerts/rest/action/RestAlertsStatsAction.java deleted file mode 100644 index bdb4596fcf4..00000000000 --- a/src/main/java/org/elasticsearch/alerts/rest/action/RestAlertsStatsAction.java +++ /dev/null @@ -1,63 +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.alerts.rest.action; - -import org.elasticsearch.alerts.AlertsStore; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsRequest; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsResponse; -import org.elasticsearch.client.Client; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.rest.*; -import org.elasticsearch.rest.action.support.RestBuilderListener; - -import java.util.Locale; - -import static org.elasticsearch.rest.RestRequest.Method.GET; -import static org.elasticsearch.rest.RestStatus.OK; - -/** - * The RestAction for alerts stats - */ -public class RestAlertsStatsAction extends BaseRestHandler { - - private final AlertsClient alertsClient; - - @Inject - protected RestAlertsStatsAction(Settings settings, RestController controller, Client client, AlertsClient alertsClient) { - super(settings, controller, client); - this.alertsClient = alertsClient; - controller.registerHandler(GET, AlertsStore.ALERT_INDEX + "/alert/_stats", this); - } - - @Override - protected void handleRequest(RestRequest request, RestChannel restChannel, Client client) throws Exception { - AlertsStatsRequest statsRequest = new AlertsStatsRequest(); - alertsClient.alertsStats(statsRequest, new RestBuilderListener(restChannel) { - @Override - public RestResponse buildResponse(AlertsStatsResponse alertsStatsResponse, XContentBuilder builder) throws Exception { - builder.startObject() - .field("alert_manager_state", alertsStatsResponse.getAlertManagerStarted().toString().toLowerCase(Locale.ENGLISH)) - .field("alert_action_manager_started", alertsStatsResponse.isAlertActionManagerStarted()) - .field("alert_action_queue_size", alertsStatsResponse.getAlertActionManagerQueueSize()) - .field("number_of_alerts", alertsStatsResponse.getNumberOfRegisteredAlerts()) - .field("alert_action_queue_max_size", alertsStatsResponse.getAlertActionManagerLargestQueueSize()); - - builder.startObject("version") - .field("number", alertsStatsResponse.getVersion().number()) - .field("build_hash", alertsStatsResponse.getBuild().hash()) - .field("build_timestamp", alertsStatsResponse.getBuild().timestamp()) - .field("build_snapshot", alertsStatsResponse.getVersion().snapshot) - .endObject(); - - return new BytesRestResponse(OK, builder); - - } - }); - } -} diff --git a/src/main/java/org/elasticsearch/alerts/rest/action/RestGetAlertAction.java b/src/main/java/org/elasticsearch/alerts/rest/action/RestGetAlertAction.java deleted file mode 100644 index 2a543e3cf29..00000000000 --- a/src/main/java/org/elasticsearch/alerts/rest/action/RestGetAlertAction.java +++ /dev/null @@ -1,63 +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.alerts.rest.action; - -import org.elasticsearch.action.get.GetResponse; -import org.elasticsearch.alerts.AlertsStore; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.transport.actions.get.GetAlertRequest; -import org.elasticsearch.alerts.transport.actions.get.GetAlertResponse; -import org.elasticsearch.client.Client; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.rest.*; -import org.elasticsearch.rest.action.support.RestBuilderListener; - -import static org.elasticsearch.rest.RestRequest.Method.GET; -import static org.elasticsearch.rest.RestStatus.NOT_FOUND; -import static org.elasticsearch.rest.RestStatus.OK; - -/** - * The rest action to get an alert - */ -public class RestGetAlertAction extends BaseRestHandler { - - private final AlertsClient alertsClient; - - @Inject - public RestGetAlertAction(Settings settings, RestController controller, Client client, AlertsClient alertsClient) { - super(settings, controller, client); - this.alertsClient = alertsClient; - controller.registerHandler(GET, AlertsStore.ALERT_INDEX + "/alert/{name}", this); - } - - @Override - protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { - final GetAlertRequest getAlertRequest = new GetAlertRequest(); - getAlertRequest.alertName(request.param("name")); - alertsClient.getAlert(getAlertRequest, new RestBuilderListener(channel) { - @Override - public RestResponse buildResponse(GetAlertResponse result, XContentBuilder builder) throws Exception { - GetResponse getResponse = result.getResponse(); - builder.startObject() - .field("found", getResponse.isExists()) - .field("_index", getResponse.getIndex()) - .field("_type", getResponse.getType()) - .field("_id", getResponse.getId()) - .field("_version", getResponse.getVersion()) - .field("alert", getResponse.getSource()) - .endObject(); - - RestStatus status = OK; - if (!getResponse.isExists()) { - status = NOT_FOUND; - } - return new BytesRestResponse(status, builder); - } - }); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/alerts/rest/action/RestPutAlertAction.java b/src/main/java/org/elasticsearch/alerts/rest/action/RestPutAlertAction.java deleted file mode 100644 index 54c403bacbf..00000000000 --- a/src/main/java/org/elasticsearch/alerts/rest/action/RestPutAlertAction.java +++ /dev/null @@ -1,63 +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.alerts.rest.action; - -import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.alerts.AlertsStore; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.transport.actions.put.PutAlertRequest; -import org.elasticsearch.alerts.transport.actions.put.PutAlertResponse; -import org.elasticsearch.client.Client; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.rest.*; -import org.elasticsearch.rest.action.support.RestBuilderListener; - -import static org.elasticsearch.rest.RestRequest.Method.POST; -import static org.elasticsearch.rest.RestRequest.Method.PUT; -import static org.elasticsearch.rest.RestStatus.CREATED; -import static org.elasticsearch.rest.RestStatus.OK; - -/** - */ -public class RestPutAlertAction extends BaseRestHandler { - - private final AlertsClient alertsClient; - - @Inject - public RestPutAlertAction(Settings settings, RestController controller, Client client, AlertsClient alertsClient) { - super(settings, controller, client); - this.alertsClient = alertsClient; - controller.registerHandler(POST, AlertsStore.ALERT_INDEX + "/alert/{name}", this); - controller.registerHandler(PUT, AlertsStore.ALERT_INDEX + "/alert/{name}", this); - } - - @Override - protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { - PutAlertRequest putAlertRequest = new PutAlertRequest(); - putAlertRequest.setAlertName(request.param("name")); - putAlertRequest.source(request.content(), request.contentUnsafe()); - alertsClient.putAlert(putAlertRequest, new RestBuilderListener(channel) { - @Override - public RestResponse buildResponse(PutAlertResponse response, XContentBuilder builder) throws Exception { - IndexResponse indexResponse = response.indexResponse(); - builder.startObject() - .field("_index", indexResponse.getIndex()) - .field("_type", indexResponse.getType()) - .field("_id", indexResponse.getId()) - .field("_version", indexResponse.getVersion()) - .field("created", indexResponse.isCreated()); - builder.endObject(); - RestStatus status = OK; - if (indexResponse.isCreated()) { - status = CREATED; - } - return new BytesRestResponse(status, builder); - } - }); - } -} diff --git a/src/main/java/org/elasticsearch/alerts/throttle/AckThrottler.java b/src/main/java/org/elasticsearch/alerts/throttle/AckThrottler.java deleted file mode 100644 index a4cf1b7f12f..00000000000 --- a/src/main/java/org/elasticsearch/alerts/throttle/AckThrottler.java +++ /dev/null @@ -1,24 +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.alerts.throttle; - -import org.elasticsearch.alerts.ExecutionContext; - -import static org.elasticsearch.alerts.support.AlertsDateUtils.formatDate; - -/** - * - */ -public class AckThrottler implements Throttler { - - @Override - public Result throttle(ExecutionContext ctx) { - if (ctx.alert().acked()) { - return Result.throttle("alert [" + ctx.alert().name() + "] was acked at [" + formatDate(ctx.alert().status().ackStatus().timestamp()) + "]"); - } - return Result.NO; - } -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/AlertsTransportModule.java b/src/main/java/org/elasticsearch/alerts/transport/AlertsTransportModule.java deleted file mode 100644 index 98a53545575..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/AlertsTransportModule.java +++ /dev/null @@ -1,47 +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.alerts.transport; - -import org.elasticsearch.action.ActionModule; -import org.elasticsearch.alerts.transport.actions.ack.AckAlertAction; -import org.elasticsearch.alerts.transport.actions.ack.TransportAckAlertAction; -import org.elasticsearch.alerts.transport.actions.delete.DeleteAlertAction; -import org.elasticsearch.alerts.transport.actions.delete.TransportDeleteAlertAction; -import org.elasticsearch.alerts.transport.actions.get.GetAlertAction; -import org.elasticsearch.alerts.transport.actions.get.TransportGetAlertAction; -import org.elasticsearch.alerts.transport.actions.put.PutAlertAction; -import org.elasticsearch.alerts.transport.actions.put.TransportPutAlertAction; -import org.elasticsearch.alerts.transport.actions.service.AlertsServiceAction; -import org.elasticsearch.alerts.transport.actions.service.TransportAlertsServiceAction; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsAction; -import org.elasticsearch.alerts.transport.actions.stats.TransportAlertsStatsAction; -import org.elasticsearch.common.inject.AbstractModule; -import org.elasticsearch.common.inject.Module; -import org.elasticsearch.common.inject.PreProcessModule; - -/** - * - */ -public class AlertsTransportModule extends AbstractModule implements PreProcessModule { - - @Override - public void processModule(Module module) { - if (module instanceof ActionModule) { - ActionModule actionModule = (ActionModule) module; - actionModule.registerAction(PutAlertAction.INSTANCE, TransportPutAlertAction.class); - actionModule.registerAction(DeleteAlertAction.INSTANCE, TransportDeleteAlertAction.class); - actionModule.registerAction(GetAlertAction.INSTANCE, TransportGetAlertAction.class); - actionModule.registerAction(AlertsStatsAction.INSTANCE, TransportAlertsStatsAction.class); - actionModule.registerAction(AckAlertAction.INSTANCE, TransportAckAlertAction.class); - actionModule.registerAction(AlertsServiceAction.INSTANCE, TransportAlertsServiceAction.class); - } - } - - @Override - protected void configure() { - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertAction.java b/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertAction.java deleted file mode 100644 index 4a9cc1aa03e..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertAction.java +++ /dev/null @@ -1,33 +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.alerts.transport.actions.ack; - -import org.elasticsearch.alerts.client.AlertsAction; -import org.elasticsearch.client.Client; - -/** - * This action acks an alert in memory, and the index - */ -public class AckAlertAction extends AlertsAction { - - public static final AckAlertAction INSTANCE = new AckAlertAction(); - public static final String NAME = "indices:data/write/alert/ack"; - - private AckAlertAction() { - super(NAME); - } - - @Override - public AckAlertResponse newResponse() { - return new AckAlertResponse(); - } - - @Override - public AckAlertRequestBuilder newRequestBuilder(Client client) { - return new AckAlertRequestBuilder(client); - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertRequestBuilder.java b/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertRequestBuilder.java deleted file mode 100644 index fd14006cbe1..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertRequestBuilder.java +++ /dev/null @@ -1,39 +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.alerts.transport.actions.ack; - -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.client.Client; - -/** - * A ack alert action request builder. - */ -public class AckAlertRequestBuilder extends MasterNodeOperationRequestBuilder { - - public AckAlertRequestBuilder(Client client) { - super(client, new AckAlertRequest()); - } - - public AckAlertRequestBuilder(Client client, String alertName) { - super(client, new AckAlertRequest(alertName)); - } - - /** - * Sets the name of the alert to be ack - */ - public AckAlertRequestBuilder setAlertName(String alertName) { - this.request().setAlertName(alertName); - return this; - } - - @Override - protected void doExecute(final ActionListener listener) { - new AlertsClient(client).ackAlert(request, listener); - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertAction.java b/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertAction.java deleted file mode 100644 index ac4593a4f7c..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertAction.java +++ /dev/null @@ -1,32 +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.alerts.transport.actions.delete; - -import org.elasticsearch.alerts.client.AlertsAction; -import org.elasticsearch.client.Client; - -/** - * This action deletes an alert from in memory, the scheduler and the index - */ -public class DeleteAlertAction extends AlertsAction { - - public static final DeleteAlertAction INSTANCE = new DeleteAlertAction(); - public static final String NAME = "indices:data/write/alert/delete"; - - private DeleteAlertAction() { - super(NAME); - } - - @Override - public DeleteAlertResponse newResponse() { - return new DeleteAlertResponse(); - } - - @Override - public DeleteAlertRequestBuilder newRequestBuilder(Client client) { - return new DeleteAlertRequestBuilder(client); - } -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertRequestBuilder.java b/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertRequestBuilder.java deleted file mode 100644 index 98fdded1a6c..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertRequestBuilder.java +++ /dev/null @@ -1,39 +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.alerts.transport.actions.delete; - -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.client.Client; - -/** - * A delete document action request builder. - */ -public class DeleteAlertRequestBuilder extends MasterNodeOperationRequestBuilder { - - public DeleteAlertRequestBuilder(Client client) { - super(client, new DeleteAlertRequest()); - } - - public DeleteAlertRequestBuilder(Client client, String alertName) { - super(client, new DeleteAlertRequest(alertName)); - } - - /** - * Sets the name of the alert to be deleted - */ - public DeleteAlertRequestBuilder setAlertName(String alertName) { - this.request().setAlertName(alertName); - return this; - } - - @Override - protected void doExecute(final ActionListener listener) { - new AlertsClient(client).deleteAlert(request, listener); - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertAction.java b/src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertAction.java deleted file mode 100644 index 5c5f7683efb..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertAction.java +++ /dev/null @@ -1,32 +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.alerts.transport.actions.get; - -import org.elasticsearch.alerts.client.AlertsAction; -import org.elasticsearch.client.Client; - -/** - * This action gets an alert by name - */ -public class GetAlertAction extends AlertsAction { - - public static final GetAlertAction INSTANCE = new GetAlertAction(); - public static final String NAME = "indices:data/read/alert/get"; - - private GetAlertAction() { - super(NAME); - } - - @Override - public GetAlertResponse newResponse() { - return new GetAlertResponse(); - } - - @Override - public GetAlertRequestBuilder newRequestBuilder(Client client) { - return new GetAlertRequestBuilder(client); - } -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertAction.java b/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertAction.java deleted file mode 100644 index d56be98a05a..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertAction.java +++ /dev/null @@ -1,32 +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.alerts.transport.actions.put; - -import org.elasticsearch.alerts.client.AlertsAction; -import org.elasticsearch.client.Client; - -/** - * This action puts an alert into the alert index and adds it to the scheduler - */ -public class PutAlertAction extends AlertsAction { - - public static final PutAlertAction INSTANCE = new PutAlertAction(); - public static final String NAME = "indices:data/write/alert/put"; - - private PutAlertAction() { - super(NAME); - } - - @Override - public PutAlertRequestBuilder newRequestBuilder(Client client) { - return new PutAlertRequestBuilder(client); - } - - @Override - public PutAlertResponse newResponse() { - return new PutAlertResponse(); - } -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertRequest.java b/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertRequest.java deleted file mode 100644 index f836fd9a90d..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertRequest.java +++ /dev/null @@ -1,119 +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.alerts.transport.actions.put; - - -import org.elasticsearch.action.ActionRequestValidationException; -import org.elasticsearch.action.ValidateActions; -import org.elasticsearch.action.support.master.MasterNodeOperationRequest; -import org.elasticsearch.alerts.client.AlertSourceBuilder; -import org.elasticsearch.client.Requests; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.common.xcontent.XContentType; - -import java.io.IOException; - -/** - * This request class contains the data needed to create an alert along with the name of the alert - * the name of the alert will become the ID of the indexed document. - */ -public class PutAlertRequest extends MasterNodeOperationRequest { - - private String alertName; - private BytesReference alertSource; - private boolean alertSourceUnsafe; - - public PutAlertRequest() { - } - - /** - * @param alertSource The alertSource - */ - public PutAlertRequest(BytesReference alertSource) { - this.alertSource = alertSource; - } - - /** - * @return The name that will be the ID of the indexed document - */ - public String getAlertName() { - return alertName; - } - - /** - * Set the alert name - */ - public void setAlertName(String alertName) { - this.alertName = alertName; - } - - /** - * @return The source of the alert - */ - public BytesReference getAlertSource() { - return alertSource; - } - - /** - * Set the source of the alert - */ - public void source(AlertSourceBuilder source) { - source(source.buildAsBytes(XContentType.JSON)); - } - - /** - * Set the source of the alert - */ - public void source(BytesReference alertSource) { - this.alertSource = alertSource; - this.alertSourceUnsafe = false; - } - - /** - * Set the source of the alert with boolean to control source safety - */ - public void source(BytesReference alertSource, boolean alertSourceUnsafe) { - this.alertSource = alertSource; - this.alertSourceUnsafe = alertSourceUnsafe; - } - - public void beforeLocalFork() { - if (alertSourceUnsafe) { - alertSource = alertSource.copyBytesArray(); - alertSourceUnsafe = false; - } - } - - @Override - public ActionRequestValidationException validate() { - ActionRequestValidationException validationException = null; - if (alertName == null) { - validationException = ValidateActions.addValidationError("alertName is missing", validationException); - } - if (alertSource == null) { - validationException = ValidateActions.addValidationError("alertSource is missing", validationException); - } - return validationException; - } - - @Override - public void readFrom(StreamInput in) throws IOException { - super.readFrom(in); - alertName = in.readString(); - alertSource = in.readBytesReference(); - alertSourceUnsafe = false; - } - - @Override - public void writeTo(StreamOutput out) throws IOException { - super.writeTo(out); - out.writeString(alertName); - out.writeBytesReference(alertSource); - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertRequestBuilder.java b/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertRequestBuilder.java deleted file mode 100644 index 7e0f57baf46..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertRequestBuilder.java +++ /dev/null @@ -1,57 +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.alerts.transport.actions.put; - -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder; -import org.elasticsearch.alerts.client.AlertSourceBuilder; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.client.Client; -import org.elasticsearch.common.bytes.BytesReference; - -/** - * A Builder to build a PutAlertRequest - */ -public class PutAlertRequestBuilder extends MasterNodeOperationRequestBuilder { - - public PutAlertRequestBuilder(Client client) { - super(client, new PutAlertRequest()); - } - - public PutAlertRequestBuilder(Client client, String alertName) { - super(client, new PutAlertRequest()); - request.setAlertName(alertName); - } - - /** - * @param alertName The alert name to be created - */ - public PutAlertRequestBuilder alertName(String alertName){ - request.setAlertName(alertName); - return this; - } - - /** - * @param source the source of the alert to be created - */ - public PutAlertRequestBuilder source(BytesReference source) { - request.source(source); - return this; - } - - /** - * @param source the source of the alert to be created - */ - public PutAlertRequestBuilder source(AlertSourceBuilder source) { - request.source(source); - return this; - } - - @Override - protected void doExecute(ActionListener listener) { - new AlertsClient(client).putAlert(request, listener); - } -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceAction.java b/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceAction.java deleted file mode 100644 index ce629e57d5e..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceAction.java +++ /dev/null @@ -1,32 +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.alerts.transport.actions.service; - -import org.elasticsearch.alerts.client.AlertsAction; -import org.elasticsearch.client.Client; - -/** - */ -public class AlertsServiceAction extends AlertsAction { - - public static final AlertsServiceAction INSTANCE = new AlertsServiceAction(); - public static final String NAME = "cluster:admin/alerts/service"; - - private AlertsServiceAction() { - super(NAME); - } - - @Override - public AlertsServiceResponse newResponse() { - return new AlertsServiceResponse(); - } - - @Override - public AlertsServiceRequestBuilder newRequestBuilder(Client client) { - return new AlertsServiceRequestBuilder(client); - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceRequestBuilder.java b/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceRequestBuilder.java deleted file mode 100644 index 2f2fec3474c..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceRequestBuilder.java +++ /dev/null @@ -1,49 +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.alerts.transport.actions.service; - -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.client.Client; - -/** - */ -public class AlertsServiceRequestBuilder extends MasterNodeOperationRequestBuilder { - - public AlertsServiceRequestBuilder(Client client) { - super(client, new AlertsServiceRequest()); - } - - /** - * Starts alerting if not already started. - */ - public AlertsServiceRequestBuilder start() { - request.start(); - return this; - } - - /** - * Stops alerting if not already stopped. - */ - public AlertsServiceRequestBuilder stop() { - request.stop(); - return this; - } - - /** - * Starts and stops alerting. - */ - public AlertsServiceRequestBuilder restart() { - request.restart(); - return this; - } - - @Override - protected void doExecute(ActionListener listener) { - new AlertsClient(client).alertService(request, listener); - } -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsAction.java b/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsAction.java deleted file mode 100644 index 2d28038e1ae..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsAction.java +++ /dev/null @@ -1,33 +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.alerts.transport.actions.stats; - -import org.elasticsearch.alerts.client.AlertsAction; -import org.elasticsearch.client.Client; - -/** - * This Action gets the stats for the alert plugin - */ -public class AlertsStatsAction extends AlertsAction { - - public static final AlertsStatsAction INSTANCE = new AlertsStatsAction(); - public static final String NAME = "cluster/alerts/stats"; - - private AlertsStatsAction() { - super(NAME); - } - - @Override - public AlertsStatsResponse newResponse() { - return new AlertsStatsResponse(); - } - - @Override - public AlertsStatsRequestBuilder newRequestBuilder(Client client) { - return new AlertsStatsRequestBuilder(client); - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsRequestBuilder.java b/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsRequestBuilder.java deleted file mode 100644 index 68955dda46f..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsRequestBuilder.java +++ /dev/null @@ -1,31 +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.alerts.transport.actions.stats; - -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.client.Client; - -/** - * An alert stats document action request builder. - */ -public class AlertsStatsRequestBuilder extends MasterNodeOperationRequestBuilder { - - /** - * The constructor for the AlertsStatsRequestBuilder - */ - public AlertsStatsRequestBuilder(Client client) { - super(client, new AlertsStatsRequest()); - } - - - @Override - protected void doExecute(final ActionListener listener) { - new AlertsClient(client).alertsStats(request, listener); - } - -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsResponse.java b/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsResponse.java deleted file mode 100644 index b4e110cc2fc..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsResponse.java +++ /dev/null @@ -1,133 +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.alerts.transport.actions.stats; - -import org.elasticsearch.action.ActionResponse; -import org.elasticsearch.alerts.AlertsBuild; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.AlertsVersion; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.io.stream.StreamOutput; - -import java.io.IOException; - -/** - * The AlertStatsResponse response - */ -public class AlertsStatsResponse extends ActionResponse { - - private AlertsVersion version; - private AlertsBuild build; - private long numberOfRegisteredAlerts; - private AlertsService.State alertManagerState; - private boolean alertActionManagerStarted; - private long alertActionManagerQueueSize; - private long alertActionManagerLargestQueueSize; - - public AlertsStatsResponse() { - } - - /** - * @return The current queue size in the alert action manager - */ - public long getAlertActionManagerQueueSize() { - return alertActionManagerQueueSize; - } - - void setAlertActionManagerQueueSize(long alertActionManagerQueueSize) { - this.alertActionManagerQueueSize = alertActionManagerQueueSize; - } - - /** - * @return The number of alerts currently registered in the system - */ - public long getNumberOfRegisteredAlerts() { - return numberOfRegisteredAlerts; - } - - void setNumberOfRegisteredAlerts(long numberOfRegisteredAlerts) { - this.numberOfRegisteredAlerts = numberOfRegisteredAlerts; - } - - /** - * Returns the state of the alert manager. - */ - public AlertsService.State getAlertManagerStarted() { - return alertManagerState; - } - - void setAlertManagerState(AlertsService.State alertManagerState) { - this.alertManagerState = alertManagerState; - } - - /** - * @return {@code true} if the alert action manager is started - */ - public boolean isAlertActionManagerStarted() { - return alertActionManagerStarted; - } - - void setAlertActionManagerStarted(boolean alertActionManagerStarted) { - this.alertActionManagerStarted = alertActionManagerStarted; - } - - /** - * @return The largest queue size the alert action manager queue has grown to - */ - public long getAlertActionManagerLargestQueueSize() { - return alertActionManagerLargestQueueSize; - } - - void setAlertActionManagerLargestQueueSize(long alertActionManagerLargestQueueSize) { - this.alertActionManagerLargestQueueSize = alertActionManagerLargestQueueSize; - } - - /** - * @return The alerts plugin version. - */ - public AlertsVersion getVersion() { - return version; - } - - void setVersion(AlertsVersion version) { - this.version = version; - } - - /** - * @return The alerts plugin build information. - */ - public AlertsBuild getBuild() { - return build; - } - - void setBuild(AlertsBuild build) { - this.build = build; - } - - @Override - public void readFrom(StreamInput in) throws IOException { - super.readFrom(in); - numberOfRegisteredAlerts = in.readLong(); - alertActionManagerQueueSize = in.readLong(); - alertActionManagerLargestQueueSize = in.readLong(); - alertManagerState = AlertsService.State.fromId(in.readByte()); - alertActionManagerStarted = in.readBoolean(); - version = AlertsVersion.readVersion(in); - build = AlertsBuild.readBuild(in); - } - - @Override - public void writeTo(StreamOutput out) throws IOException { - super.writeTo(out); - out.writeLong(numberOfRegisteredAlerts); - out.writeLong(alertActionManagerQueueSize); - out.writeLong(alertActionManagerLargestQueueSize); - out.writeByte(alertManagerState.getId()); - out.writeBoolean(alertActionManagerStarted); - AlertsVersion.writeVersion(version, out); - AlertsBuild.writeBuild(build, out); - } -} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/TransportAlertsStatsAction.java b/src/main/java/org/elasticsearch/alerts/transport/actions/stats/TransportAlertsStatsAction.java deleted file mode 100644 index 5be22cbfaac..00000000000 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/TransportAlertsStatsAction.java +++ /dev/null @@ -1,76 +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.alerts.transport.actions.stats; - -import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.support.ActionFilters; -import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction; -import org.elasticsearch.alerts.AlertsBuild; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.AlertsVersion; -import org.elasticsearch.alerts.history.HistoryService; -import org.elasticsearch.cluster.ClusterService; -import org.elasticsearch.cluster.ClusterState; -import org.elasticsearch.cluster.block.ClusterBlockException; -import org.elasticsearch.cluster.block.ClusterBlockLevel; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.threadpool.ThreadPool; -import org.elasticsearch.transport.TransportService; - -/** - * Performs the stats operation. - */ -public class TransportAlertsStatsAction extends TransportMasterNodeOperationAction { - - private final AlertsService alertsService; - private final HistoryService historyService; - - @Inject - public TransportAlertsStatsAction(Settings settings, TransportService transportService, ClusterService clusterService, - ThreadPool threadPool, ActionFilters actionFilters, AlertsService alertsService, - HistoryService historyService) { - super(settings, AlertsStatsAction.NAME, transportService, clusterService, threadPool, actionFilters); - this.alertsService = alertsService; - this.historyService = historyService; - } - - @Override - protected String executor() { - return ThreadPool.Names.MANAGEMENT; - } - - @Override - protected AlertsStatsRequest newRequest() { - return new AlertsStatsRequest(); - } - - @Override - protected AlertsStatsResponse newResponse() { - return new AlertsStatsResponse(); - } - - @Override - protected void masterOperation(AlertsStatsRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { - AlertsStatsResponse statsResponse = new AlertsStatsResponse(); - statsResponse.setAlertManagerState(alertsService.state()); - statsResponse.setAlertActionManagerStarted(historyService.started()); - statsResponse.setAlertActionManagerQueueSize(historyService.queueSize()); - statsResponse.setNumberOfRegisteredAlerts(alertsService.getNumberOfAlerts()); - statsResponse.setAlertActionManagerLargestQueueSize(historyService.largestQueueSize()); - statsResponse.setVersion(AlertsVersion.CURRENT); - statsResponse.setBuild(AlertsBuild.CURRENT); - listener.onResponse(statsResponse); - } - - @Override - protected ClusterBlockException checkBlock(AlertsStatsRequest request, ClusterState state) { - return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA); - } - - -} diff --git a/src/main/java/org/elasticsearch/alerts/AlertsBuild.java b/src/main/java/org/elasticsearch/watcher/WatcherBuild.java similarity index 82% rename from src/main/java/org/elasticsearch/alerts/AlertsBuild.java rename to src/main/java/org/elasticsearch/watcher/WatcherBuild.java index 558bc8aeb25..f050ea552d9 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertsBuild.java +++ b/src/main/java/org/elasticsearch/watcher/WatcherBuild.java @@ -3,7 +3,7 @@ * 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.alerts; +package org.elasticsearch.watcher; import org.elasticsearch.common.io.FastStringReader; import org.elasticsearch.common.io.Streams; @@ -17,9 +17,9 @@ import java.util.Properties; /** */ -public class AlertsBuild { +public class WatcherBuild { - public static final AlertsBuild CURRENT; + public static final WatcherBuild CURRENT; static { String hash = "NA"; @@ -27,7 +27,7 @@ public class AlertsBuild { String timestamp = "NA"; try { - String properties = Streams.copyToStringFromClasspath("/alerts-build.properties"); + String properties = Streams.copyToStringFromClasspath("/watcher-build.properties"); Properties props = new Properties(); props.load(new FastStringReader(properties)); hash = props.getProperty("hash", hash); @@ -42,14 +42,14 @@ public class AlertsBuild { // just ignore... } - CURRENT = new AlertsBuild(hash, hashShort, timestamp); + CURRENT = new WatcherBuild(hash, hashShort, timestamp); } private final String hash; private final String hashShort; private final String timestamp; - AlertsBuild(String hash, String hashShort, String timestamp) { + WatcherBuild(String hash, String hashShort, String timestamp) { this.hash = hash; this.hashShort = hashShort; this.timestamp = timestamp; @@ -72,7 +72,7 @@ public class AlertsBuild { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - AlertsBuild that = (AlertsBuild) o; + WatcherBuild that = (WatcherBuild) o; if (!hash.equals(that.hash)) return false; if (!hashShort.equals(that.hashShort)) return false; @@ -89,14 +89,14 @@ public class AlertsBuild { return result; } - public static AlertsBuild readBuild(StreamInput in) throws IOException { + public static WatcherBuild readBuild(StreamInput in) throws IOException { String hash = in.readString(); String hashShort = in.readString(); String timestamp = in.readString(); - return new AlertsBuild(hash, hashShort, timestamp); + return new WatcherBuild(hash, hashShort, timestamp); } - public static void writeBuild(AlertsBuild build, StreamOutput out) throws IOException { + public static void writeBuild(WatcherBuild build, StreamOutput out) throws IOException { out.writeString(build.hash()); out.writeString(build.hashShort()); out.writeString(build.timestamp()); diff --git a/src/main/java/org/elasticsearch/alerts/AlertsException.java b/src/main/java/org/elasticsearch/watcher/WatcherException.java similarity index 60% rename from src/main/java/org/elasticsearch/alerts/AlertsException.java rename to src/main/java/org/elasticsearch/watcher/WatcherException.java index 8de99a837c0..3d749203792 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertsException.java +++ b/src/main/java/org/elasticsearch/watcher/WatcherException.java @@ -3,20 +3,20 @@ * 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.alerts; +package org.elasticsearch.watcher; import org.elasticsearch.ElasticsearchException; /** - * A base class for all alerts exceptions + * A base class for all watcher exceptions */ -public class AlertsException extends ElasticsearchException { +public class WatcherException extends ElasticsearchException { - public AlertsException(String msg) { + public WatcherException(String msg) { super(msg); } - public AlertsException(String msg, Throwable cause) { + public WatcherException(String msg, Throwable cause) { super(msg, cause); } } diff --git a/src/main/java/org/elasticsearch/alerts/AlertsLifeCycleService.java b/src/main/java/org/elasticsearch/watcher/WatcherLifeCycleService.java similarity index 72% rename from src/main/java/org/elasticsearch/alerts/AlertsLifeCycleService.java rename to src/main/java/org/elasticsearch/watcher/WatcherLifeCycleService.java index 5657e47545a..29936d99910 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertsLifeCycleService.java +++ b/src/main/java/org/elasticsearch/watcher/WatcherLifeCycleService.java @@ -3,7 +3,7 @@ * 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.alerts; +package org.elasticsearch.watcher; import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterService; @@ -16,34 +16,35 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.gateway.GatewayService; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.threadpool.ThreadPool; +import org.elasticsearch.watcher.watch.WatchService; /** */ -public class AlertsLifeCycleService extends AbstractComponent implements ClusterStateListener { +public class WatcherLifeCycleService extends AbstractComponent implements ClusterStateListener { private final ThreadPool threadPool; - private final AlertsService alertsService; + private final WatchService watchService; private final ClusterService clusterService; // Maybe this should be a setting in the cluster settings? private volatile boolean manuallyStopped; @Inject - public AlertsLifeCycleService(Settings settings, ClusterService clusterService, IndicesService indicesService, ThreadPool threadPool, AlertsService alertsService) { + public WatcherLifeCycleService(Settings settings, ClusterService clusterService, IndicesService indicesService, ThreadPool threadPool, WatchService watchService) { super(settings); this.clusterService = clusterService; this.threadPool = threadPool; - this.alertsService = alertsService; + this.watchService = watchService; clusterService.add(this); // Close if the indices service is being stopped, so we don't run into search failures (locally) that will - // happen because we're shutting down and an alert is scheduled. + // happen because we're shutting down and an watch is scheduled. indicesService.addLifecycleListener(new LifecycleListener() { @Override public void beforeStop() { stop(false); } }); - manuallyStopped = !settings.getAsBoolean("alerts.start_immediately", true); + manuallyStopped = !settings.getAsBoolean("watcher.start_immediately", true); } public void start() { @@ -55,19 +56,19 @@ public class AlertsLifeCycleService extends AbstractComponent implements Cluster } private synchronized void start(ClusterState state) { - alertsService.start(state); + watchService.start(state); } private synchronized void stop(boolean manual) { manuallyStopped = manual; - alertsService.stop(); + watchService.stop(); } @Override public void clusterChanged(final ClusterChangedEvent event) { if (!event.localNodeMaster()) { - // We're no longer the master so we need to stop alerting. - // Stopping alerting may take a while since it will wait on the scheduler to complete shutdown, + // We're no longer the master so we need to stop the watcher. + // Stopping the watcher may take a while since it will wait on the scheduler to complete shutdown, // so we fork here so that we don't wait too long. Other events may need to be processed and // other cluster state listeners may need to be executed as well for this event. threadPool.executor(ThreadPool.Names.GENERIC).execute(new Runnable() { @@ -78,11 +79,11 @@ public class AlertsLifeCycleService extends AbstractComponent implements Cluster }); } else { if (event.state().blocks().hasGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK)) { - // wait until the gateway has recovered from disk, otherwise we think may not have .alerts and - // a .alerts_history index, but they may not have been restored from the cluster state on disk + // wait until the gateway has recovered from disk, otherwise we think may not have .watchs and + // a .watch_history index, but they may not have been restored from the cluster state on disk return; } - if (alertsService.state() == AlertsService.State.STOPPED && !manuallyStopped) { + if (watchService.state() == WatchService.State.STOPPED && !manuallyStopped) { threadPool.executor(ThreadPool.Names.GENERIC).execute(new Runnable() { @Override public void run() { diff --git a/src/main/java/org/elasticsearch/watcher/WatcherModule.java b/src/main/java/org/elasticsearch/watcher/WatcherModule.java new file mode 100644 index 00000000000..bab547c0bee --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/WatcherModule.java @@ -0,0 +1,55 @@ +/* + * 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.watcher; + + +import org.elasticsearch.watcher.actions.ActionModule; +import org.elasticsearch.watcher.client.WatcherClientModule; +import org.elasticsearch.watcher.condition.ConditionModule; +import org.elasticsearch.watcher.history.HistoryModule; +import org.elasticsearch.watcher.input.InputModule; +import org.elasticsearch.watcher.rest.WatcherRestModule; +import org.elasticsearch.watcher.scheduler.SchedulerModule; +import org.elasticsearch.watcher.support.TemplateUtils; +import org.elasticsearch.watcher.support.clock.ClockModule; +import org.elasticsearch.watcher.support.init.InitializingModule; +import org.elasticsearch.watcher.support.template.TemplateModule; +import org.elasticsearch.watcher.transform.TransformModule; +import org.elasticsearch.watcher.transport.WatcherTransportModule; +import org.elasticsearch.common.collect.ImmutableList; +import org.elasticsearch.common.inject.AbstractModule; +import org.elasticsearch.common.inject.Module; +import org.elasticsearch.common.inject.SpawnModules; +import org.elasticsearch.watcher.watch.WatchModule; + + +public class WatcherModule extends AbstractModule implements SpawnModules { + + @Override + public Iterable spawnModules() { + return ImmutableList.of( + new InitializingModule(), + new WatchModule(), + new TemplateModule(), + new ClockModule(), + new WatcherClientModule(), + new TransformModule(), + new WatcherRestModule(), + new SchedulerModule(), + new WatcherTransportModule(), + new ConditionModule(), + new InputModule(), + new ActionModule(), + new HistoryModule()); + } + + @Override + protected void configure() { + bind(WatcherLifeCycleService.class).asEagerSingleton(); + bind(TemplateUtils.class).asEagerSingleton(); + } + +} diff --git a/src/main/java/org/elasticsearch/alerts/AlertsPlugin.java b/src/main/java/org/elasticsearch/watcher/WatcherPlugin.java similarity index 79% rename from src/main/java/org/elasticsearch/alerts/AlertsPlugin.java rename to src/main/java/org/elasticsearch/watcher/WatcherPlugin.java index 8ec65fa7e7a..8c9babdf93f 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertsPlugin.java +++ b/src/main/java/org/elasticsearch/watcher/WatcherPlugin.java @@ -3,10 +3,10 @@ * 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.alerts; +package org.elasticsearch.watcher; -import org.elasticsearch.alerts.actions.email.service.InternalEmailService; -import org.elasticsearch.alerts.support.init.InitializingService; +import org.elasticsearch.watcher.actions.email.service.InternalEmailService; +import org.elasticsearch.watcher.support.init.InitializingService; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.inject.Module; @@ -18,14 +18,14 @@ import java.util.Collection; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; -public class AlertsPlugin extends AbstractPlugin { +public class WatcherPlugin extends AbstractPlugin { - public static final String NAME = "alerts"; - public static final String SCHEDULER_THREAD_POOL_NAME = "alerts_scheduler"; + public static final String NAME = "watcher"; + public static final String SCHEDULER_THREAD_POOL_NAME = "watcher_scheduler"; private final Settings settings; - public AlertsPlugin(Settings settings) { + public WatcherPlugin(Settings settings) { this.settings = settings; } @@ -34,12 +34,12 @@ public class AlertsPlugin extends AbstractPlugin { } @Override public String description() { - return "Elasticsearch Alerts"; + return "Elasticsearch Watcher"; } @Override public Collection> modules() { - return ImmutableList.>of(AlertsModule.class); + return ImmutableList.>of(WatcherModule.class); } @Override diff --git a/src/main/java/org/elasticsearch/alerts/AlertsSettingsException.java b/src/main/java/org/elasticsearch/watcher/WatcherSettingsException.java similarity index 59% rename from src/main/java/org/elasticsearch/alerts/AlertsSettingsException.java rename to src/main/java/org/elasticsearch/watcher/WatcherSettingsException.java index 04b77e558b7..e6a931e8dd8 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertsSettingsException.java +++ b/src/main/java/org/elasticsearch/watcher/WatcherSettingsException.java @@ -3,18 +3,18 @@ * 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.alerts; +package org.elasticsearch.watcher; /** * */ -public class AlertsSettingsException extends AlertsException { +public class WatcherSettingsException extends WatcherException { - public AlertsSettingsException(String msg, Throwable cause) { + public WatcherSettingsException(String msg, Throwable cause) { super(msg, cause); } - public AlertsSettingsException(String msg) { + public WatcherSettingsException(String msg) { super(msg); } } diff --git a/src/main/java/org/elasticsearch/alerts/AlertsVersion.java b/src/main/java/org/elasticsearch/watcher/WatcherVersion.java similarity index 80% rename from src/main/java/org/elasticsearch/alerts/AlertsVersion.java rename to src/main/java/org/elasticsearch/watcher/WatcherVersion.java index b715211fe45..21d8ecbe758 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertsVersion.java +++ b/src/main/java/org/elasticsearch/watcher/WatcherVersion.java @@ -3,7 +3,7 @@ * 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.alerts; +package org.elasticsearch.watcher; import org.elasticsearch.Version; import org.elasticsearch.common.Nullable; @@ -17,7 +17,7 @@ import java.io.Serializable; /** */ @SuppressWarnings("deprecation") -public class AlertsVersion implements Serializable { +public class WatcherVersion implements Serializable { // The logic for ID is: XXYYZZAA, where XX is major version, YY is minor version, ZZ is revision, and AA is Beta/RC indicator // AA values below 50 are beta builds, and below 99 are RC builds, with 99 indicating a release @@ -25,41 +25,41 @@ public class AlertsVersion implements Serializable { // The first internal beta has already been released, without this class being here, so we start version version 2. public static final int V_1_0_0_Beta2_ID = /*00*/1000002; - public static final AlertsVersion V_1_0_0_Beta2 = new AlertsVersion(V_1_0_0_Beta2_ID, true, Version.V_1_4_0); + public static final WatcherVersion V_1_0_0_Beta2 = new WatcherVersion(V_1_0_0_Beta2_ID, true, Version.V_1_4_0); - public static final AlertsVersion CURRENT = V_1_0_0_Beta2; + public static final WatcherVersion CURRENT = V_1_0_0_Beta2; - public static AlertsVersion readVersion(StreamInput in) throws IOException { + public static WatcherVersion readVersion(StreamInput in) throws IOException { return fromId(in.readVInt()); } - public static AlertsVersion fromId(int id) { + public static WatcherVersion fromId(int id) { switch (id) { case V_1_0_0_Beta2_ID: return V_1_0_0_Beta2; default: - return new AlertsVersion(id, null, Version.CURRENT); + return new WatcherVersion(id, null, Version.CURRENT); } } - public static void writeVersion(AlertsVersion version, StreamOutput out) throws IOException { + public static void writeVersion(WatcherVersion version, StreamOutput out) throws IOException { out.writeVInt(version.id); } /** * Returns the smallest version between the 2. */ - public static AlertsVersion smallest(AlertsVersion version1, AlertsVersion version2) { + public static WatcherVersion smallest(WatcherVersion version1, WatcherVersion version2) { return version1.id < version2.id ? version1 : version2; } /** * Returns the version given its string representation, current version if the argument is null or empty */ - public static AlertsVersion fromString(String version) { + public static WatcherVersion fromString(String version) { if (!Strings.hasLength(version)) { - return AlertsVersion.CURRENT; + return WatcherVersion.CURRENT; } String[] parts = version.split("\\."); @@ -100,7 +100,7 @@ public class AlertsVersion implements Serializable { public final Version minEsCompatibilityVersion; // TODO: Once licencing integration has been completed license version should be added to - AlertsVersion(int id, @Nullable Boolean snapshot, Version minEsCompatibilityVersion) { + WatcherVersion(int id, @Nullable Boolean snapshot, Version minEsCompatibilityVersion) { this.id = id; this.major = (byte) ((id / 1000000) % 100); this.minor = (byte) ((id / 10000) % 100); @@ -114,23 +114,23 @@ public class AlertsVersion implements Serializable { return snapshot != null && snapshot; } - public boolean after(AlertsVersion version) { + public boolean after(WatcherVersion version) { return version.id < id; } - public boolean onOrAfter(AlertsVersion version) { + public boolean onOrAfter(WatcherVersion version) { return version.id <= id; } - public boolean before(AlertsVersion version) { + public boolean before(WatcherVersion version) { return version.id > id; } - public boolean onOrBefore(AlertsVersion version) { + public boolean onOrBefore(WatcherVersion version) { return version.id >= id; } - public boolean compatibleWith(AlertsVersion version) { + public boolean compatibleWith(WatcherVersion version) { return version.onOrAfter(minimumCompatibilityVersion()); } @@ -145,8 +145,8 @@ public class AlertsVersion implements Serializable { * is in most of the cases the smallest major version release unless the current version * is a beta or RC release then the version itself is returned. */ - public AlertsVersion minimumCompatibilityVersion() { - return AlertsVersion.smallest(this, fromId(major * 1000000 + 99)); + public WatcherVersion minimumCompatibilityVersion() { + return WatcherVersion.smallest(this, fromId(major * 1000000 + 99)); } /** @@ -185,7 +185,7 @@ public class AlertsVersion implements Serializable { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - AlertsVersion that = (AlertsVersion) o; + WatcherVersion that = (WatcherVersion) o; if (id != that.id) return false; diff --git a/src/main/java/org/elasticsearch/alerts/actions/Action.java b/src/main/java/org/elasticsearch/watcher/actions/Action.java similarity index 90% rename from src/main/java/org/elasticsearch/alerts/actions/Action.java rename to src/main/java/org/elasticsearch/watcher/actions/Action.java index 1f196e8659a..1aa247c2708 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/Action.java +++ b/src/main/java/org/elasticsearch/watcher/actions/Action.java @@ -3,11 +3,11 @@ * 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.alerts.actions; +package org.elasticsearch.watcher.actions; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.transform.Transform; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.transform.Transform; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.xcontent.ToXContent; @@ -43,7 +43,7 @@ public abstract class Action implements ToXContent { /** * Executes this action */ - public R execute(ExecutionContext context) throws IOException { + public R execute(WatchExecutionContext context) throws IOException { Payload payload = context.payload(); Transform.Result transformResult = null; if (transform != null) { @@ -57,7 +57,7 @@ public abstract class Action implements ToXContent { return result; } - protected abstract R execute(ExecutionContext context, Payload payload) throws IOException; + protected abstract R execute(WatchExecutionContext context, Payload payload) throws IOException; /** * Parses xcontent to a concrete action of the same type. diff --git a/src/main/java/org/elasticsearch/alerts/actions/ActionBuilders.java b/src/main/java/org/elasticsearch/watcher/actions/ActionBuilders.java similarity index 75% rename from src/main/java/org/elasticsearch/alerts/actions/ActionBuilders.java rename to src/main/java/org/elasticsearch/watcher/actions/ActionBuilders.java index c106ba359f9..84e7650aa74 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/ActionBuilders.java +++ b/src/main/java/org/elasticsearch/watcher/actions/ActionBuilders.java @@ -3,12 +3,12 @@ * 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.alerts.actions; +package org.elasticsearch.watcher.actions; -import org.elasticsearch.alerts.actions.email.EmailAction; -import org.elasticsearch.alerts.actions.index.IndexAction; -import org.elasticsearch.alerts.actions.webhook.WebhookAction; -import org.elasticsearch.alerts.support.Script; +import org.elasticsearch.watcher.actions.email.EmailAction; +import org.elasticsearch.watcher.actions.index.IndexAction; +import org.elasticsearch.watcher.actions.webhook.WebhookAction; +import org.elasticsearch.watcher.support.Script; /** * diff --git a/src/main/java/org/elasticsearch/alerts/actions/ActionException.java b/src/main/java/org/elasticsearch/watcher/actions/ActionException.java similarity index 73% rename from src/main/java/org/elasticsearch/alerts/actions/ActionException.java rename to src/main/java/org/elasticsearch/watcher/actions/ActionException.java index 305bf43c840..fd5623ee88c 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/ActionException.java +++ b/src/main/java/org/elasticsearch/watcher/actions/ActionException.java @@ -3,14 +3,14 @@ * 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.alerts.actions; +package org.elasticsearch.watcher.actions; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; /** * */ -public class ActionException extends AlertsException { +public class ActionException extends WatcherException { public ActionException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/actions/ActionModule.java b/src/main/java/org/elasticsearch/watcher/actions/ActionModule.java similarity index 79% rename from src/main/java/org/elasticsearch/alerts/actions/ActionModule.java rename to src/main/java/org/elasticsearch/watcher/actions/ActionModule.java index f73025f316c..a9f77910c14 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/ActionModule.java +++ b/src/main/java/org/elasticsearch/watcher/actions/ActionModule.java @@ -3,14 +3,14 @@ * 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.alerts.actions; +package org.elasticsearch.watcher.actions; -import org.elasticsearch.alerts.actions.email.EmailAction; -import org.elasticsearch.alerts.actions.email.service.EmailService; -import org.elasticsearch.alerts.actions.email.service.InternalEmailService; -import org.elasticsearch.alerts.actions.index.IndexAction; -import org.elasticsearch.alerts.actions.webhook.HttpClient; -import org.elasticsearch.alerts.actions.webhook.WebhookAction; +import org.elasticsearch.watcher.actions.email.EmailAction; +import org.elasticsearch.watcher.actions.email.service.EmailService; +import org.elasticsearch.watcher.actions.email.service.InternalEmailService; +import org.elasticsearch.watcher.actions.index.IndexAction; +import org.elasticsearch.watcher.actions.webhook.HttpClient; +import org.elasticsearch.watcher.actions.webhook.WebhookAction; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.multibindings.MapBinder; diff --git a/src/main/java/org/elasticsearch/alerts/actions/ActionRegistry.java b/src/main/java/org/elasticsearch/watcher/actions/ActionRegistry.java similarity index 98% rename from src/main/java/org/elasticsearch/alerts/actions/ActionRegistry.java rename to src/main/java/org/elasticsearch/watcher/actions/ActionRegistry.java index 96d11da00c0..44f0d39eb49 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/ActionRegistry.java +++ b/src/main/java/org/elasticsearch/watcher/actions/ActionRegistry.java @@ -3,7 +3,7 @@ * 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.alerts.actions; +package org.elasticsearch.watcher.actions; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; diff --git a/src/main/java/org/elasticsearch/alerts/actions/ActionSettingsException.java b/src/main/java/org/elasticsearch/watcher/actions/ActionSettingsException.java similarity index 92% rename from src/main/java/org/elasticsearch/alerts/actions/ActionSettingsException.java rename to src/main/java/org/elasticsearch/watcher/actions/ActionSettingsException.java index 08dd19018d5..901edfcdc18 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/ActionSettingsException.java +++ b/src/main/java/org/elasticsearch/watcher/actions/ActionSettingsException.java @@ -3,7 +3,7 @@ * 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.alerts.actions; +package org.elasticsearch.watcher.actions; /** * diff --git a/src/main/java/org/elasticsearch/alerts/actions/Actions.java b/src/main/java/org/elasticsearch/watcher/actions/Actions.java similarity index 97% rename from src/main/java/org/elasticsearch/alerts/actions/Actions.java rename to src/main/java/org/elasticsearch/watcher/actions/Actions.java index 39bad55426c..81c69fea82d 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/Actions.java +++ b/src/main/java/org/elasticsearch/watcher/actions/Actions.java @@ -3,7 +3,7 @@ * 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.alerts.actions; +package org.elasticsearch.watcher.actions; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/EmailAction.java b/src/main/java/org/elasticsearch/watcher/actions/email/EmailAction.java similarity index 96% rename from src/main/java/org/elasticsearch/alerts/actions/email/EmailAction.java rename to src/main/java/org/elasticsearch/watcher/actions/email/EmailAction.java index 9cd58e8a597..b20a7c4f101 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/EmailAction.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/EmailAction.java @@ -3,17 +3,17 @@ * 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.alerts.actions.email; +package org.elasticsearch.watcher.actions.email; -import org.elasticsearch.alerts.ExecutionContext; -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.alerts.transform.Transform; -import org.elasticsearch.alerts.transform.TransformRegistry; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.ActionSettingsException; +import org.elasticsearch.watcher.actions.email.service.*; +import org.elasticsearch.watcher.support.Variables; +import org.elasticsearch.watcher.support.template.Template; +import org.elasticsearch.watcher.transform.Transform; +import org.elasticsearch.watcher.transform.TransformRegistry; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.component.AbstractComponent; @@ -67,7 +67,7 @@ public class EmailAction extends Action { } @Override - protected Result execute(ExecutionContext ctx, Payload payload) throws IOException { + protected Result execute(WatchExecutionContext ctx, Payload payload) throws IOException { Map model = Variables.createCtxModel(ctx, payload); Email.Builder email = Email.builder() @@ -91,8 +91,8 @@ public class EmailAction extends Action { EmailService.EmailSent sent = emailService.send(email.build(), auth, profile, account); return new Result.Success(sent); } catch (EmailException ee) { - logger.error("could not send email for alert [{}]", ee, ctx.alert().name()); - return new Result.Failure("could not send email for alert [" + ctx.alert().name() + "]. error: " + ee.getMessage()); + logger.error("could not send email for watch [{}]", ee, ctx.watch().name()); + return new Result.Failure("could not send email for watch [" + ctx.watch().name() + "]. error: " + ee.getMessage()); } } diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/Account.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/Account.java similarity index 98% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/Account.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/Account.java index b1c8296ebf2..c6018c7f58b 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/Account.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/Account.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.ImmutableSettings; @@ -166,8 +166,8 @@ public class Account { * holds email fields that can be configured on the account. These fields * will hold the default values for missing fields in email messages. Having * the ability to create these default can substantially reduced the configuration - * needed on each alert (e.g. if all the emails are always sent to the same recipients - * one could set those here and leave them out on the alert definition). + * needed on each watch (e.g. if all the emails are always sent to the same recipients + * one could set those here and leave them out on the watch definition). */ static class EmailDefaults { diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/Accounts.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/Accounts.java similarity index 97% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/Accounts.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/Accounts.java index 9f70adff620..04a8d5fe094 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/Accounts.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/Accounts.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.Settings; diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/Attachment.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/Attachment.java similarity index 97% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/Attachment.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/Attachment.java index a8ebdeb109c..c71ce6c58bf 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/Attachment.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/Attachment.java @@ -3,9 +3,9 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; -import org.elasticsearch.alerts.actions.email.service.support.BodyPartSource; +import org.elasticsearch.watcher.actions.email.service.support.BodyPartSource; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentType; diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/Authentication.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/Authentication.java similarity index 95% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/Authentication.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/Authentication.java index 7541f870cd5..3591403b507 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/Authentication.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/Authentication.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; /** * diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/Email.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/Email.java similarity index 99% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/Email.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/Email.java index c44f89c16b1..dcf42acdbcb 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/Email.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/Email.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.base.Charsets; @@ -316,7 +316,7 @@ public class Email implements ToXContent { } public Email build() { - assert id != null : "email id should not be null (should be set to the alert id"; + assert id != null : "email id should not be null (should be set to the watch id"; return new Email(id, from, replyTo, priority, sentDate, to, cc, bcc, subject, textBody, htmlBody, attachments.build(), inlines.build()); } diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/EmailException.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/EmailException.java similarity index 80% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/EmailException.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/EmailException.java index e48e10d6bf3..379f8f53d05 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/EmailException.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/EmailException.java @@ -3,9 +3,9 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; -import org.elasticsearch.alerts.actions.ActionException; +import org.elasticsearch.watcher.actions.ActionException; /** * diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/EmailService.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/EmailService.java similarity index 93% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/EmailService.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/EmailService.java index 0dbef98ce92..c0268026ab9 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/EmailService.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/EmailService.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; /** * diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/EmailSettingsException.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/EmailSettingsException.java similarity index 89% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/EmailSettingsException.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/EmailSettingsException.java index bd38be8a9c2..338609a405c 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/EmailSettingsException.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/EmailSettingsException.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; /** * diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/Inline.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/Inline.java similarity index 97% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/Inline.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/Inline.java index 8a925f20634..0812d6bd71f 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/Inline.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/Inline.java @@ -3,9 +3,9 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; -import org.elasticsearch.alerts.actions.email.service.support.BodyPartSource; +import org.elasticsearch.watcher.actions.email.service.support.BodyPartSource; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.inject.Provider; diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/InternalEmailService.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/InternalEmailService.java similarity index 98% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/InternalEmailService.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/InternalEmailService.java index 1f28ecac190..73646b0ed11 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/InternalEmailService.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/InternalEmailService.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.component.AbstractLifecycleComponent; diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/Profile.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/Profile.java similarity index 99% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/Profile.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/Profile.java index 547708a10df..08513239d50 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/Profile.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/Profile.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; import org.elasticsearch.common.base.Charsets; import org.elasticsearch.common.xcontent.ToXContent; diff --git a/src/main/java/org/elasticsearch/alerts/actions/email/service/support/BodyPartSource.java b/src/main/java/org/elasticsearch/watcher/actions/email/service/support/BodyPartSource.java similarity index 94% rename from src/main/java/org/elasticsearch/alerts/actions/email/service/support/BodyPartSource.java rename to src/main/java/org/elasticsearch/watcher/actions/email/service/support/BodyPartSource.java index f5339d49258..8fbb2827c5d 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/email/service/support/BodyPartSource.java +++ b/src/main/java/org/elasticsearch/watcher/actions/email/service/support/BodyPartSource.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service.support; +package org.elasticsearch.watcher.actions.email.service.support; import org.elasticsearch.common.xcontent.ToXContent; diff --git a/src/main/java/org/elasticsearch/alerts/actions/index/IndexAction.java b/src/main/java/org/elasticsearch/watcher/actions/index/IndexAction.java similarity index 93% rename from src/main/java/org/elasticsearch/alerts/actions/index/IndexAction.java rename to src/main/java/org/elasticsearch/watcher/actions/index/IndexAction.java index e8e4fe8e373..8d5af1a01c8 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/index/IndexAction.java +++ b/src/main/java/org/elasticsearch/watcher/actions/index/IndexAction.java @@ -3,19 +3,19 @@ * 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.alerts.actions.index; +package org.elasticsearch.watcher.actions.index; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.actions.Action; -import org.elasticsearch.alerts.actions.ActionException; -import org.elasticsearch.alerts.actions.ActionSettingsException; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.transform.Transform; -import org.elasticsearch.alerts.transform.TransformRegistry; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.ActionException; +import org.elasticsearch.watcher.actions.ActionSettingsException; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.transform.Transform; +import org.elasticsearch.watcher.transform.TransformRegistry; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.component.AbstractComponent; @@ -54,7 +54,7 @@ public class IndexAction extends Action { } @Override - protected Result execute(ExecutionContext ctx, Payload payload) throws IOException { + protected Result execute(WatchExecutionContext ctx, Payload payload) throws IOException { IndexRequest indexRequest = new IndexRequest(); indexRequest.index(index); indexRequest.type(type); @@ -66,7 +66,7 @@ public class IndexAction extends Action { resultBuilder.endObject(); indexRequest.source(resultBuilder); } catch (IOException ioe) { - logger.error("failed to index result for alert [{}]", ioe, ctx.alert().name()); + logger.error("failed to index result for watch [{}]", ioe, ctx.watch().name()); return new Result(null, "failed to build index request. " + ioe.getMessage(), false); } @@ -80,7 +80,7 @@ public class IndexAction extends Action { data.put("index", response.getIndex()); return new Result(new Payload.Simple(data), null, response.isCreated()); } catch (ElasticsearchException e) { - logger.error("failed to index result for alert [{}]", e, ctx.alert().name()); + logger.error("failed to index result for watch [{}]", e, ctx.watch().name()); return new Result(null, "failed to build index request. " + e.getMessage(), false); } } diff --git a/src/main/java/org/elasticsearch/alerts/actions/webhook/HttpClient.java b/src/main/java/org/elasticsearch/watcher/actions/webhook/HttpClient.java similarity index 97% rename from src/main/java/org/elasticsearch/alerts/actions/webhook/HttpClient.java rename to src/main/java/org/elasticsearch/watcher/actions/webhook/HttpClient.java index 0e5072f4f25..49fb375ed72 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/webhook/HttpClient.java +++ b/src/main/java/org/elasticsearch/watcher/actions/webhook/HttpClient.java @@ -3,7 +3,7 @@ * 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.alerts.actions.webhook; +package org.elasticsearch.watcher.actions.webhook; import org.elasticsearch.common.base.Charsets; import org.elasticsearch.common.component.AbstractComponent; diff --git a/src/main/java/org/elasticsearch/alerts/actions/webhook/WebhookAction.java b/src/main/java/org/elasticsearch/watcher/actions/webhook/WebhookAction.java similarity index 92% rename from src/main/java/org/elasticsearch/alerts/actions/webhook/WebhookAction.java rename to src/main/java/org/elasticsearch/watcher/actions/webhook/WebhookAction.java index 6fbc29cb7c2..86b07e02444 100644 --- a/src/main/java/org/elasticsearch/alerts/actions/webhook/WebhookAction.java +++ b/src/main/java/org/elasticsearch/watcher/actions/webhook/WebhookAction.java @@ -3,20 +3,20 @@ * 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.alerts.actions.webhook; +package org.elasticsearch.watcher.actions.webhook; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -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.alerts.transform.Transform; -import org.elasticsearch.alerts.transform.TransformRegistry; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.ActionException; +import org.elasticsearch.watcher.actions.ActionSettingsException; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.Variables; +import org.elasticsearch.watcher.support.template.Template; +import org.elasticsearch.watcher.support.template.XContentTemplate; +import org.elasticsearch.watcher.transform.Transform; +import org.elasticsearch.watcher.transform.TransformRegistry; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.component.AbstractComponent; @@ -57,7 +57,7 @@ public class WebhookAction extends Action { } @Override - protected Result execute(ExecutionContext ctx, Payload payload) throws IOException { + protected Result execute(WatchExecutionContext ctx, Payload payload) throws IOException { Map model = Variables.createCtxModel(ctx, payload); String urlText = url.render(model); String bodyText = body != null ? body.render(model) : XContentTemplate.YAML.render(model); @@ -74,7 +74,7 @@ public class WebhookAction extends Action { return new Result.Executed(status, urlText, bodyText); } catch (IOException ioe) { - logger.error("failed to connect to [{}] for alert [{}]", ioe, urlText, ctx.alert().name()); + logger.error("failed to connect to [{}] for watch [{}]", ioe, urlText, ctx.watch().name()); return new Result.Failure("failed to send http request. " + ioe.getMessage()); } } @@ -228,7 +228,7 @@ public class WebhookAction extends Action { try { urlTemplate = templateParser.parse(parser); } catch (Template.Parser.ParseException pe) { - throw new AlertsSettingsException("could not parse webhook action [url] template", pe); + throw new WatcherSettingsException("could not parse webhook action [url] template", pe); } } else if (BODY_FIELD.match(currentFieldName)) { try { diff --git a/src/main/java/org/elasticsearch/alerts/client/AlertSourceBuilder.java b/src/main/java/org/elasticsearch/watcher/client/WatchSourceBuilder.java similarity index 66% rename from src/main/java/org/elasticsearch/alerts/client/AlertSourceBuilder.java rename to src/main/java/org/elasticsearch/watcher/client/WatchSourceBuilder.java index bf298ff8773..5d6c62df393 100644 --- a/src/main/java/org/elasticsearch/alerts/client/AlertSourceBuilder.java +++ b/src/main/java/org/elasticsearch/watcher/client/WatchSourceBuilder.java @@ -3,16 +3,16 @@ * 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.alerts.client; +package org.elasticsearch.watcher.client; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.actions.Action; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.ConditionBuilders; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.NoneInput; -import org.elasticsearch.alerts.scheduler.schedule.Schedule; -import org.elasticsearch.alerts.transform.Transform; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionBuilders; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.NoneInput; +import org.elasticsearch.watcher.scheduler.schedule.Schedule; +import org.elasticsearch.watcher.transform.Transform; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.ToXContent; @@ -29,10 +29,10 @@ import java.util.Set; /** * */ -public class AlertSourceBuilder implements ToXContent { +public class WatchSourceBuilder implements ToXContent { - public static AlertSourceBuilder alertSourceBuilder() { - return new AlertSourceBuilder(); + public static WatchSourceBuilder watchSourceBuilder() { + return new WatchSourceBuilder(); } private Schedule schedule; @@ -43,37 +43,37 @@ public class AlertSourceBuilder implements ToXContent { private TimeValue throttlePeriod = null; private Map metadata; - public AlertSourceBuilder schedule(Schedule schedule) { + public WatchSourceBuilder schedule(Schedule schedule) { this.schedule = schedule; return this; } - public AlertSourceBuilder input(Input.SourceBuilder input) { + public WatchSourceBuilder input(Input.SourceBuilder input) { this.input = input; return this; } - public AlertSourceBuilder condition(Condition.SourceBuilder condition) { + public WatchSourceBuilder condition(Condition.SourceBuilder condition) { this.condition = condition; return this; } - public AlertSourceBuilder transform(Transform.SourceBuilder transform) { + public WatchSourceBuilder transform(Transform.SourceBuilder transform) { this.transform = transform; return this; } - public AlertSourceBuilder throttlePeriod(TimeValue throttlePeriod) { + public WatchSourceBuilder throttlePeriod(TimeValue throttlePeriod) { this.throttlePeriod = throttlePeriod; return this; } - public AlertSourceBuilder addAction(Action.SourceBuilder action) { + public WatchSourceBuilder addAction(Action.SourceBuilder action) { actions.add(action); return this; } - public AlertSourceBuilder metadata(Map metadata) { + public WatchSourceBuilder metadata(Map metadata) { this.metadata = metadata; return this; } @@ -82,36 +82,36 @@ public class AlertSourceBuilder implements ToXContent { public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); - builder.startObject(Alert.Parser.SCHEDULE_FIELD.getPreferredName()) + builder.startObject(Watch.Parser.SCHEDULE_FIELD.getPreferredName()) .field(schedule.type(), schedule) .endObject(); - builder.startObject(Alert.Parser.INPUT_FIELD.getPreferredName()) + builder.startObject(Watch.Parser.INPUT_FIELD.getPreferredName()) .field(input.type(), input) .endObject(); - builder.startObject(Alert.Parser.CONDITION_FIELD.getPreferredName()) + builder.startObject(Watch.Parser.CONDITION_FIELD.getPreferredName()) .field(condition.type(), condition) .endObject(); if (transform != null) { - builder.startObject(Alert.Parser.TRANSFORM_FIELD.getPreferredName()) + builder.startObject(Watch.Parser.TRANSFORM_FIELD.getPreferredName()) .field(transform.type(), transform) .endObject(); } if (throttlePeriod != null) { - builder.field(Alert.Parser.THROTTLE_PERIOD_FIELD.getPreferredName(), throttlePeriod.getMillis()); + builder.field(Watch.Parser.THROTTLE_PERIOD_FIELD.getPreferredName(), throttlePeriod.getMillis()); } - builder.startArray(Alert.Parser.ACTIONS_FIELD.getPreferredName()); + builder.startArray(Watch.Parser.ACTIONS_FIELD.getPreferredName()); for (Action.SourceBuilder action : actions) { builder.startObject().field(action.type(), action).endObject(); } builder.endArray(); if (metadata != null) { - builder.field(Alert.Parser.META_FIELD.getPreferredName(), metadata); + builder.field(Watch.Parser.META_FIELD.getPreferredName(), metadata); } return builder.endObject(); diff --git a/src/main/java/org/elasticsearch/alerts/client/AlertsAction.java b/src/main/java/org/elasticsearch/watcher/client/WatcherAction.java similarity index 56% rename from src/main/java/org/elasticsearch/alerts/client/AlertsAction.java rename to src/main/java/org/elasticsearch/watcher/client/WatcherAction.java index c563f254321..9831442cc74 100644 --- a/src/main/java/org/elasticsearch/alerts/client/AlertsAction.java +++ b/src/main/java/org/elasticsearch/watcher/client/WatcherAction.java @@ -3,7 +3,7 @@ * 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.alerts.client; +package org.elasticsearch.watcher.client; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestBuilder; @@ -12,11 +12,11 @@ import org.elasticsearch.action.ClientAction; import org.elasticsearch.client.Client; /** - * Base alert action class. + * All watcher related actions should extend this base class. */ -public abstract class AlertsAction> extends ClientAction { +public abstract class WatcherAction> extends ClientAction { - protected AlertsAction(String name) { + protected WatcherAction(String name) { super(name); } diff --git a/src/main/java/org/elasticsearch/watcher/client/WatcherClient.java b/src/main/java/org/elasticsearch/watcher/client/WatcherClient.java new file mode 100644 index 00000000000..71da4844c0f --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/client/WatcherClient.java @@ -0,0 +1,253 @@ +/* + * 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.watcher.client; + +import org.elasticsearch.action.ActionFuture; +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.watcher.transport.actions.ack.AckWatchAction; +import org.elasticsearch.watcher.transport.actions.ack.AckWatchRequest; +import org.elasticsearch.watcher.transport.actions.ack.AckWatchRequestBuilder; +import org.elasticsearch.watcher.transport.actions.ack.AckWatchResponse; +import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchAction; +import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchRequest; +import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchRequestBuilder; +import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchResponse; +import org.elasticsearch.watcher.transport.actions.get.GetWatchAction; +import org.elasticsearch.watcher.transport.actions.get.GetWatchRequest; +import org.elasticsearch.watcher.transport.actions.get.GetWatchRequestBuilder; +import org.elasticsearch.watcher.transport.actions.get.GetWatchResponse; +import org.elasticsearch.watcher.transport.actions.put.PutWatchAction; +import org.elasticsearch.watcher.transport.actions.put.PutWatchRequest; +import org.elasticsearch.watcher.transport.actions.put.PutWatchRequestBuilder; +import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; +import org.elasticsearch.watcher.transport.actions.service.WatcherServiceAction; +import org.elasticsearch.watcher.transport.actions.service.WatcherServiceRequest; +import org.elasticsearch.watcher.transport.actions.service.WatcherServiceRequestBuilder; +import org.elasticsearch.watcher.transport.actions.service.WatcherServiceResponse; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsAction; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsRequest; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsRequestBuilder; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.inject.Inject; + +/** + */ +public class WatcherClient { + + private final Client client; + + @Inject + public WatcherClient(Client client) { + this.client = client; + } + + /** + * Creates a request builder that gets an watch by name (id) + * + * @param watchName the name (id) of the watch + * @return The request builder + */ + public GetWatchRequestBuilder prepareGetWatch(String watchName) { + return new GetWatchRequestBuilder(client, watchName); + } + + /** + * Creates a request builder that gets an watch + * + * @return the request builder + */ + public GetWatchRequestBuilder prepareGetWatch() { + return new GetWatchRequestBuilder(client); + } + + /** + * Gets an watch from the watch index + * + * @param request The get watch request + * @param listener The listener for the get watch response containing the GetResponse for this watch + */ + public void getWatch(GetWatchRequest request, ActionListener listener) { + client.execute(GetWatchAction.INSTANCE, request, listener); + } + + /** + * Gets an watch from the watch index + * + * @param request The get watch request with the watch name (id) + * @return The response containing the GetResponse for this watch + */ + public ActionFuture getWatch(GetWatchRequest request) { + return client.execute(GetWatchAction.INSTANCE, request); + } + + /** + * Creates a request builder to delete an watch by name (id) + * + * @param watchName the name (id) of the watch + * @return The request builder + */ + public DeleteWatchRequestBuilder prepareDeleteWatch(String watchName) { + return new DeleteWatchRequestBuilder(client, watchName); + } + + /** + * Creates a request builder that deletes an watch + * + * @return The request builder + */ + public DeleteWatchRequestBuilder prepareDeleteWatch() { + return new DeleteWatchRequestBuilder(client); + } + + /** + * Deletes an watch + * + * @param request The delete request with the watch name (id) to be deleted + * @param listener The listener for the delete watch response containing the DeleteResponse for this action + */ + public void deleteWatch(DeleteWatchRequest request, ActionListener listener) { + client.execute(DeleteWatchAction.INSTANCE, request, listener); + } + + /** + * Deletes an watch + * + * @param request The delete request with the watch name (id) to be deleted + * @return The response containing the DeleteResponse for this action + */ + public ActionFuture deleteWatch(DeleteWatchRequest request) { + return client.execute(DeleteWatchAction.INSTANCE, request); + } + + /** + * Creates a request builder to build a request to put an watch + * + * @param watchName The name of the watch to put + * @return The builder to create the watch + */ + public PutWatchRequestBuilder preparePutWatch(String watchName) { + return new PutWatchRequestBuilder(client, watchName); + } + + /** + * Creates a request builder to build a request to put a watch + * + * @return The builder + */ + public PutWatchRequestBuilder preparePutWatch() { + return new PutWatchRequestBuilder(client); + } + + /** + * Adds the given watch to the watcher + * + * @param request The request containing the watch to be added + * @param listener The listener for the response containing the IndexResponse for this watch + */ + public void putWatch(PutWatchRequest request, ActionListener listener) { + client.execute(PutWatchAction.INSTANCE, request, listener); + } + + /** + * Adds a new watch + * + * @param request The request containing the watch to be added + * @return The response containing the IndexResponse for this watch + */ + public ActionFuture putWatch(PutWatchRequest request) { + return client.execute(PutWatchAction.INSTANCE, request); + } + + /** + * Gets the watcher stats + * + * @param request The request for the watcher stats + * @return The response containing the StatsResponse for this action + */ + public ActionFuture watcherStats(WatcherStatsRequest request) { + return client.execute(WatcherStatsAction.INSTANCE, request); + } + + /** + * Creates a request builder to build a request to get the watcher stats + * + * @return The builder get the watcher stats + */ + public WatcherStatsRequestBuilder prepareWatcherStats() { + return new WatcherStatsRequestBuilder(client); + } + + /** + * Gets the watcher stats + * + * @param request The request for the watcher stats + * @param listener The listener for the response containing the WatcherStatsResponse + */ + public void watcherStats(WatcherStatsRequest request, ActionListener listener) { + client.execute(WatcherStatsAction.INSTANCE, request, listener); + } + + /** + * Creates a request builder to ack a watch by name (id) + * + * @param watcherName the name (id) of the watch + * @return The request builder + */ + public AckWatchRequestBuilder prepareAckWatch(String watcherName) { + return new AckWatchRequestBuilder(client, watcherName); + } + + /** + * Creates a request builder that acks an watch + * + * @return The request builder + */ + public AckWatchRequestBuilder prepareAckWatch() { + return new AckWatchRequestBuilder(client); + } + + /** + * Ack a watch + * + * @param request The ack request with the watch name (id) to be acked + * @param listener The listener for the ack watch response + */ + public void ackWatch(AckWatchRequest request, ActionListener listener) { + client.execute(AckWatchAction.INSTANCE, request, listener); + } + + /** + * Acks an watch + * + * @param request The ack request with the watch name (id) to be acked + * @return The AckWatchResponse + */ + public ActionFuture ackWatch(AckWatchRequest request) { + return client.execute(AckWatchAction.INSTANCE, request); + } + + /** + * Prepare a watch service request. + */ + public WatcherServiceRequestBuilder prepareWatchService() { + return new WatcherServiceRequestBuilder(client); + } + + /** + * Perform an watcher service request to either start, stop or restart the service. + */ + public void watcherService(WatcherServiceRequest request, ActionListener listener) { + client.execute(WatcherServiceAction.INSTANCE, request, listener); + } + + /** + * Perform an watcher service request to either start, stop or restart the service. + */ + public ActionFuture watcherService(WatcherServiceRequest request) { + return client.execute(WatcherServiceAction.INSTANCE, request); + } +} diff --git a/src/main/java/org/elasticsearch/alerts/client/AlertsClientModule.java b/src/main/java/org/elasticsearch/watcher/client/WatcherClientModule.java similarity index 70% rename from src/main/java/org/elasticsearch/alerts/client/AlertsClientModule.java rename to src/main/java/org/elasticsearch/watcher/client/WatcherClientModule.java index 3fb8bf56a70..bd82a8369b1 100644 --- a/src/main/java/org/elasticsearch/alerts/client/AlertsClientModule.java +++ b/src/main/java/org/elasticsearch/watcher/client/WatcherClientModule.java @@ -3,17 +3,17 @@ * 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.alerts.client; +package org.elasticsearch.watcher.client; import org.elasticsearch.common.inject.AbstractModule; /** * */ -public class AlertsClientModule extends AbstractModule { +public class WatcherClientModule extends AbstractModule { @Override protected void configure() { - bind(AlertsClient.class).asEagerSingleton(); + bind(WatcherClient.class).asEagerSingleton(); } } diff --git a/src/main/java/org/elasticsearch/alerts/condition/Condition.java b/src/main/java/org/elasticsearch/watcher/condition/Condition.java similarity index 91% rename from src/main/java/org/elasticsearch/alerts/condition/Condition.java rename to src/main/java/org/elasticsearch/watcher/condition/Condition.java index 27bfdfbea8a..38ea0e4835d 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/Condition.java +++ b/src/main/java/org/elasticsearch/watcher/condition/Condition.java @@ -3,9 +3,9 @@ * 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.alerts.condition; +package org.elasticsearch.watcher.condition; -import org.elasticsearch.alerts.ExecutionContext; +import org.elasticsearch.watcher.watch.WatchExecutionContext; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.xcontent.ToXContent; @@ -34,7 +34,7 @@ public abstract class Condition implements ToXConten /** * Executes this condition */ - public abstract R execute(ExecutionContext ctx) throws IOException; + public abstract R execute(WatchExecutionContext ctx) throws IOException; /** diff --git a/src/main/java/org/elasticsearch/alerts/condition/ConditionBuilders.java b/src/main/java/org/elasticsearch/watcher/condition/ConditionBuilders.java similarity index 80% rename from src/main/java/org/elasticsearch/alerts/condition/ConditionBuilders.java rename to src/main/java/org/elasticsearch/watcher/condition/ConditionBuilders.java index 0b27a73b2ae..673510b227f 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/ConditionBuilders.java +++ b/src/main/java/org/elasticsearch/watcher/condition/ConditionBuilders.java @@ -3,10 +3,10 @@ * 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.alerts.condition; +package org.elasticsearch.watcher.condition; -import org.elasticsearch.alerts.condition.script.ScriptCondition; -import org.elasticsearch.alerts.condition.simple.AlwaysTrueCondition; +import org.elasticsearch.watcher.condition.script.ScriptCondition; +import org.elasticsearch.watcher.condition.simple.AlwaysTrueCondition; /** * diff --git a/src/main/java/org/elasticsearch/alerts/condition/ConditionException.java b/src/main/java/org/elasticsearch/watcher/condition/ConditionException.java similarity index 73% rename from src/main/java/org/elasticsearch/alerts/condition/ConditionException.java rename to src/main/java/org/elasticsearch/watcher/condition/ConditionException.java index e68f62207ab..83ddbf843a9 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/ConditionException.java +++ b/src/main/java/org/elasticsearch/watcher/condition/ConditionException.java @@ -3,14 +3,14 @@ * 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.alerts.condition; +package org.elasticsearch.watcher.condition; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; /** * */ -public class ConditionException extends AlertsException { +public class ConditionException extends WatcherException { public ConditionException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/condition/ConditionModule.java b/src/main/java/org/elasticsearch/watcher/condition/ConditionModule.java similarity index 87% rename from src/main/java/org/elasticsearch/alerts/condition/ConditionModule.java rename to src/main/java/org/elasticsearch/watcher/condition/ConditionModule.java index 475b38faf98..3d159ad9a59 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/ConditionModule.java +++ b/src/main/java/org/elasticsearch/watcher/condition/ConditionModule.java @@ -3,11 +3,11 @@ * 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.alerts.condition; +package org.elasticsearch.watcher.condition; -import org.elasticsearch.alerts.condition.script.ScriptCondition; -import org.elasticsearch.alerts.condition.simple.AlwaysFalseCondition; -import org.elasticsearch.alerts.condition.simple.AlwaysTrueCondition; +import org.elasticsearch.watcher.condition.script.ScriptCondition; +import org.elasticsearch.watcher.condition.simple.AlwaysFalseCondition; +import org.elasticsearch.watcher.condition.simple.AlwaysTrueCondition; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.multibindings.MapBinder; diff --git a/src/main/java/org/elasticsearch/alerts/condition/ConditionRegistry.java b/src/main/java/org/elasticsearch/watcher/condition/ConditionRegistry.java similarity index 98% rename from src/main/java/org/elasticsearch/alerts/condition/ConditionRegistry.java rename to src/main/java/org/elasticsearch/watcher/condition/ConditionRegistry.java index 5a05ec77bd6..76fe69ac360 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/ConditionRegistry.java +++ b/src/main/java/org/elasticsearch/watcher/condition/ConditionRegistry.java @@ -3,7 +3,7 @@ * 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.alerts.condition; +package org.elasticsearch.watcher.condition; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; diff --git a/src/main/java/org/elasticsearch/alerts/condition/script/ScriptCondition.java b/src/main/java/org/elasticsearch/watcher/condition/script/ScriptCondition.java similarity index 91% rename from src/main/java/org/elasticsearch/alerts/condition/script/ScriptCondition.java rename to src/main/java/org/elasticsearch/watcher/condition/script/ScriptCondition.java index f0f960d818b..700c189fdd4 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/script/ScriptCondition.java +++ b/src/main/java/org/elasticsearch/watcher/condition/script/ScriptCondition.java @@ -3,15 +3,15 @@ * 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.alerts.condition.script; +package org.elasticsearch.watcher.condition.script; -import org.elasticsearch.alerts.AlertsSettingsException; -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.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionException; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.Variables; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; @@ -52,7 +52,7 @@ public class ScriptCondition extends Condition { } @Override - public Result execute(ExecutionContext ctx) throws IOException { + public Result execute(WatchExecutionContext ctx) throws IOException { ImmutableMap model = ImmutableMap.builder() .putAll(script.params()) .putAll(Variables.createCtxModel(ctx, ctx.payload())) @@ -108,7 +108,7 @@ public class ScriptCondition extends Condition { Script script = Script.parse(parser); return new ScriptCondition(logger, scriptService, script); } catch (Script.ParseException pe) { - throw new AlertsSettingsException("could not parse [script] condition", pe); + throw new WatcherSettingsException("could not parse [script] condition", pe); } } diff --git a/src/main/java/org/elasticsearch/alerts/condition/simple/AlwaysFalseCondition.java b/src/main/java/org/elasticsearch/watcher/condition/simple/AlwaysFalseCondition.java similarity index 90% rename from src/main/java/org/elasticsearch/alerts/condition/simple/AlwaysFalseCondition.java rename to src/main/java/org/elasticsearch/watcher/condition/simple/AlwaysFalseCondition.java index c6fbe266239..f9fc6190787 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/simple/AlwaysFalseCondition.java +++ b/src/main/java/org/elasticsearch/watcher/condition/simple/AlwaysFalseCondition.java @@ -3,16 +3,15 @@ * 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.alerts.condition.simple; +package org.elasticsearch.watcher.condition.simple; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.ConditionException; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionException; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -43,7 +42,7 @@ public class AlwaysFalseCondition extends Condition { } @Override - public Result execute(ExecutionContext ctx) throws IOException { + public Result execute(WatchExecutionContext ctx) throws IOException { return RESULT; } diff --git a/src/main/java/org/elasticsearch/alerts/condition/simple/AlwaysTrueCondition.java b/src/main/java/org/elasticsearch/watcher/condition/simple/AlwaysTrueCondition.java similarity index 92% rename from src/main/java/org/elasticsearch/alerts/condition/simple/AlwaysTrueCondition.java rename to src/main/java/org/elasticsearch/watcher/condition/simple/AlwaysTrueCondition.java index 6c29229d40c..6cbba3a8e72 100644 --- a/src/main/java/org/elasticsearch/alerts/condition/simple/AlwaysTrueCondition.java +++ b/src/main/java/org/elasticsearch/watcher/condition/simple/AlwaysTrueCondition.java @@ -3,11 +3,11 @@ * 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.alerts.condition.simple; +package org.elasticsearch.watcher.condition.simple; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.ConditionException; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionException; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.logging.ESLogger; @@ -41,7 +41,7 @@ public class AlwaysTrueCondition extends Condition { } @Override - public Result execute(ExecutionContext ctx) throws IOException { + public Result execute(WatchExecutionContext ctx) throws IOException { return RESULT; } diff --git a/src/main/java/org/elasticsearch/alerts/history/HistoryException.java b/src/main/java/org/elasticsearch/watcher/history/HistoryException.java similarity index 73% rename from src/main/java/org/elasticsearch/alerts/history/HistoryException.java rename to src/main/java/org/elasticsearch/watcher/history/HistoryException.java index 17dc1810c2a..a92c3f5b55f 100644 --- a/src/main/java/org/elasticsearch/alerts/history/HistoryException.java +++ b/src/main/java/org/elasticsearch/watcher/history/HistoryException.java @@ -3,13 +3,13 @@ * 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.alerts.history; +package org.elasticsearch.watcher.history; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; /** */ -public class HistoryException extends AlertsException { +public class HistoryException extends WatcherException { public HistoryException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/history/HistoryModule.java b/src/main/java/org/elasticsearch/watcher/history/HistoryModule.java similarity index 65% rename from src/main/java/org/elasticsearch/alerts/history/HistoryModule.java rename to src/main/java/org/elasticsearch/watcher/history/HistoryModule.java index c24b0cfbb23..6dc0560f505 100644 --- a/src/main/java/org/elasticsearch/alerts/history/HistoryModule.java +++ b/src/main/java/org/elasticsearch/watcher/history/HistoryModule.java @@ -3,7 +3,7 @@ * 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.alerts.history; +package org.elasticsearch.watcher.history; import org.elasticsearch.common.inject.AbstractModule; @@ -11,22 +11,22 @@ import org.elasticsearch.common.inject.AbstractModule; */ public class HistoryModule extends AbstractModule { - private final Class executorClass; + private final Class executorClass; public HistoryModule() { - this(InternalAlertsExecutor.class); + this(InternalWatchExecutor.class); } - protected HistoryModule(Class executorClass) { + protected HistoryModule(Class executorClass) { this.executorClass = executorClass; } @Override protected void configure() { - bind(FiredAlert.Parser.class).asEagerSingleton(); + bind(WatchRecord.Parser.class).asEagerSingleton(); bind(HistoryStore.class).asEagerSingleton(); bind(HistoryService.class).asEagerSingleton(); bind(executorClass).asEagerSingleton(); - bind(AlertsExecutor.class).to(executorClass); + bind(WatchExecutor.class).to(executorClass); } } diff --git a/src/main/java/org/elasticsearch/alerts/history/HistoryService.java b/src/main/java/org/elasticsearch/watcher/history/HistoryService.java similarity index 53% rename from src/main/java/org/elasticsearch/alerts/history/HistoryService.java rename to src/main/java/org/elasticsearch/watcher/history/HistoryService.java index a0f062b645a..a5d36babce5 100644 --- a/src/main/java/org/elasticsearch/alerts/history/HistoryService.java +++ b/src/main/java/org/elasticsearch/watcher/history/HistoryService.java @@ -3,18 +3,17 @@ * 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.alerts.history; +package org.elasticsearch.watcher.history; import org.elasticsearch.ElasticsearchIllegalStateException; -import org.elasticsearch.alerts.*; -import org.elasticsearch.alerts.actions.Action; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.scheduler.Scheduler; -import org.elasticsearch.alerts.support.Callback; -import org.elasticsearch.alerts.support.clock.Clock; -import org.elasticsearch.alerts.throttle.Throttler; -import org.elasticsearch.alerts.transform.Transform; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.scheduler.Scheduler; +import org.elasticsearch.watcher.support.Callback; +import org.elasticsearch.watcher.support.clock.Clock; +import org.elasticsearch.watcher.throttle.Throttler; +import org.elasticsearch.watcher.transform.Transform; import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; @@ -24,9 +23,11 @@ import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; +import org.elasticsearch.watcher.watch.*; import java.io.IOException; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -36,24 +37,24 @@ import java.util.concurrent.atomic.AtomicInteger; public class HistoryService extends AbstractComponent { private final HistoryStore historyStore; - private final AlertsExecutor executor; - private final AlertsStore alertsStore; + private final WatchExecutor executor; + private final WatchStore watchStore; private final ClusterService clusterService; - private final AlertLockService alertLockService; + private final WatchLockService watchLockService; private final Clock clock; private final AtomicBoolean started = new AtomicBoolean(false); private final AtomicInteger initializationRetries = new AtomicInteger(); @Inject - public HistoryService(Settings settings, HistoryStore historyStore, AlertsExecutor executor, - AlertsStore alertsStore, AlertLockService alertLockService, Scheduler scheduler, + public HistoryService(Settings settings, HistoryStore historyStore, WatchExecutor executor, + WatchStore watchStore, WatchLockService watchLockService, Scheduler scheduler, ClusterService clusterService, Clock clock) { super(settings); this.historyStore = historyStore; this.executor = executor; - this.alertsStore = alertsStore; - this.alertLockService = alertLockService; + this.watchStore = watchStore; + this.watchLockService = watchLockService; this.clusterService = clusterService; this.clock = clock; scheduler.addListener(new SchedulerListener()); @@ -66,14 +67,14 @@ public class HistoryService extends AbstractComponent { } assert executor.queue().isEmpty() : "queue should be empty, but contains " + executor.queue().size() + " elements."; - HistoryStore.LoadResult loadResult = historyStore.loadFiredAlerts(state, FiredAlert.State.AWAITS_EXECUTION); - if (!loadResult.succeeded()) { + Collection records = historyStore.loadRecords(state, WatchRecord.State.AWAITS_EXECUTION); + if (records == null) { retry(callback); return; } if (started.compareAndSet(false, true)) { logger.debug("starting history service"); - executePreviouslyFiredAlerts(loadResult); + executeRecords(records); logger.debug("started history service"); } callback.onSuccess(state); @@ -105,55 +106,54 @@ public class HistoryService extends AbstractComponent { return executor.largestPoolSize(); } - void fire(Alert alert, DateTime scheduledFireTime, DateTime fireTime) throws HistoryException { + void execute(Watch watch, DateTime scheduledFireTime, DateTime fireTime) throws HistoryException { if (!started.get()) { throw new ElasticsearchIllegalStateException("not started"); } - FiredAlert firedAlert = new FiredAlert(alert, scheduledFireTime, fireTime); - logger.debug("adding fired alert [{}]", alert.name()); - historyStore.put(firedAlert); - executeAsync(firedAlert, alert); + WatchRecord watchRecord = new WatchRecord(watch, scheduledFireTime, fireTime); + logger.debug("saving watch record [{}]", watch.name()); + historyStore.put(watchRecord); + executeAsync(watchRecord, watch); } /* - The execution of an alert is split into operations, a schedule part which just makes sure that store the fact an alert - has fired and an execute part which actually executed the alert. + The execution of an watch is split into two phases: + 1. the trigger part which just makes sure to store the associated watch record in the history + 2. the actual processing of the watch - The reason this is split into two operations is that we don't want to lose the fact an alert has fired. If we - would not split the execution of an alert and many alerts fire in a small window of time then it can happen that - thread pool that receives fired jobs from the quartz scheduler is going to reject jobs and then we would never - know about jobs that have fired. By splitting the execution of fired jobs into two operations we lower the chance - we lose fired jobs signficantly. + The reason this split is that we don't want to lose the fact watch was triggered. This way, even if the + thread pool that executes the watches is completely busy, we don't lose the fact that the watch was + triggered (it'll have its history record) */ - void executeAsync(FiredAlert firedAlert, Alert alert) { + void executeAsync(WatchRecord watchRecord, Watch watch) { try { - executor.execute(new AlertExecutionTask(firedAlert, alert)); + executor.execute(new WatchExecutionTask(watchRecord, watch)); } catch (EsRejectedExecutionException e) { - logger.debug("[{}] failed to execute fired alert", firedAlert.name()); - firedAlert.update(FiredAlert.State.FAILED, "failed to run fired alert due to thread pool capacity"); - historyStore.update(firedAlert); + logger.debug("failed to execute triggered watch [{}]", watchRecord.name()); + watchRecord.update(WatchRecord.State.FAILED, "failed to run triggered watch [" + watchRecord.name() + "] due to thread pool capacity"); + historyStore.update(watchRecord); } } - AlertExecution execute(ExecutionContext ctx) throws IOException { - Alert alert = ctx.alert(); - Input.Result inputResult = alert.input().execute(ctx); + WatchExecution execute(WatchExecutionContext ctx) throws IOException { + Watch watch = ctx.watch(); + Input.Result inputResult = watch.input().execute(ctx); ctx.onInputResult(inputResult); - Condition.Result conditionResult = alert.condition().execute(ctx); + Condition.Result conditionResult = watch.condition().execute(ctx); ctx.onConditionResult(conditionResult); if (conditionResult.met()) { - Throttler.Result throttleResult = alert.throttler().throttle(ctx); + Throttler.Result throttleResult = watch.throttler().throttle(ctx); ctx.onThrottleResult(throttleResult); if (!throttleResult.throttle()) { - Transform transform = alert.transform(); + Transform transform = watch.transform(); if (transform != null) { - Transform.Result result = alert.transform().apply(ctx, inputResult.payload()); + Transform.Result result = watch.transform().apply(ctx, inputResult.payload()); ctx.onTransformResult(result); } - for (Action action : alert.actions()) { + for (Action action : watch.actions()) { Action.Result actionResult = action.execute(ctx); ctx.onActionResult(actionResult); } @@ -162,20 +162,19 @@ public class HistoryService extends AbstractComponent { return ctx.finish(); } - void executePreviouslyFiredAlerts(HistoryStore.LoadResult loadResult) { - if (loadResult != null) { - int counter = 0; - for (FiredAlert firedAlert : loadResult) { - Alert alert = alertsStore.getAlert(firedAlert.name()); - if (alert == null) { - logger.warn("unable to find alert [{}] in alert store, perhaps it has been deleted. skipping...", firedAlert.name()); - continue; - } - executeAsync(firedAlert, alert); - counter++; + void executeRecords(Collection records) { + assert records != null; + int counter = 0; + for (WatchRecord record : records) { + Watch watch = watchStore.get(record.name()); + if (watch == null) { + logger.warn("unable to find watch [{}] in watch store. perhaps it has been deleted. skipping...", record.name()); + continue; } - logger.debug("executed [{}] not executed previous fired alerts from the alert history index ", counter); + executeAsync(record, watch); + counter++; } + logger.debug("executed [{}] watches from the watch history", counter); } private void retry(final Callback callback) { @@ -204,42 +203,42 @@ public class HistoryService extends AbstractComponent { clusterService.add(clusterStateListener); } - private final class AlertExecutionTask implements Runnable { + private final class WatchExecutionTask implements Runnable { - private final FiredAlert firedAlert; - private final Alert alert; + private final WatchRecord watchRecord; + private final Watch watch; - private AlertExecutionTask(FiredAlert firedAlert, Alert alert) { - this.firedAlert = firedAlert; - this.alert = alert; + private WatchExecutionTask(WatchRecord watchRecord, Watch watch) { + this.watchRecord = watchRecord; + this.watch = watch; } @Override public void run() { if (!started.get()) { - logger.debug("can't run alert execution, because history service is not started, ignoring it..."); + logger.debug("can't initiate watch execution as history service is not started, ignoring it..."); return; } - AlertLockService.Lock lock = alertLockService.acquire(alert.name()); + WatchLockService.Lock lock = watchLockService.acquire(watch.name()); try { - firedAlert.update(FiredAlert.State.CHECKING, null); - logger.debug("checking alert [{}]", firedAlert.name()); - ExecutionContext ctx = new ExecutionContext(firedAlert.id(), alert, clock.now(), firedAlert.fireTime(), firedAlert.scheduledTime()); - AlertExecution alertExecution = execute(ctx); - firedAlert.update(alertExecution); - historyStore.update(firedAlert); + watchRecord.update(WatchRecord.State.CHECKING, null); + logger.debug("checking watch [{}]", watchRecord.name()); + WatchExecutionContext ctx = new WatchExecutionContext(watchRecord.id(), watch, clock.now(), watchRecord.fireTime(), watchRecord.scheduledTime()); + WatchExecution execution = execute(ctx); + watchRecord.seal(execution); + historyStore.update(watchRecord); } catch (Exception e) { if (started()) { - logger.warn("failed to run alert [{}]", e, firedAlert.name()); + logger.warn("failed to execute watch [{}]", e, watchRecord.name()); try { - firedAlert.update(FiredAlert.State.FAILED, e.getMessage()); - historyStore.update(firedAlert); + watchRecord.update(WatchRecord.State.FAILED, e.getMessage()); + historyStore.update(watchRecord); } catch (Exception e2) { - logger.error("failed to update fired alert [{}] with the error message", e2, firedAlert); + logger.error("failed to update watch record [{}] failure [{}]", e2, watchRecord, e.getMessage()); } } else { - logger.debug("failed to execute fired alert [{}] after shutdown", e, firedAlert); + logger.debug("failed to execute watch [{}] after shutdown", e, watchRecord); } } finally { lock.release(); @@ -254,15 +253,15 @@ public class HistoryService extends AbstractComponent { if (!started.get()) { throw new ElasticsearchIllegalStateException("not started"); } - Alert alert = alertsStore.getAlert(name); - if (alert == null) { - logger.warn("unable to find [{}] in the alert store, perhaps it has been deleted", name); + Watch watch = watchStore.get(name); + if (watch == null) { + logger.warn("unable to find watch [{}] in the watch store, perhaps it has been deleted", name); return; } try { - HistoryService.this.fire(alert, scheduledFireTime, fireTime); + HistoryService.this.execute(watch, scheduledFireTime, fireTime); } catch (Exception e) { - logger.error("failed to fire alert [{}]", e, name); + logger.error("failed to execute watch [{}]", e, name); } } } diff --git a/src/main/java/org/elasticsearch/watcher/history/HistoryStore.java b/src/main/java/org/elasticsearch/watcher/history/HistoryStore.java new file mode 100644 index 00000000000..8e4a13a3e59 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/history/HistoryStore.java @@ -0,0 +1,166 @@ +/* + * 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.watcher.history; + +import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; +import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.*; +import org.elasticsearch.action.support.IndicesOptions; +import org.elasticsearch.watcher.support.TemplateUtils; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.cluster.ClusterState; +import org.elasticsearch.cluster.metadata.IndexMetaData; +import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.component.AbstractComponent; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.joda.time.DateTime; +import org.elasticsearch.common.joda.time.format.DateTimeFormat; +import org.elasticsearch.common.joda.time.format.DateTimeFormatter; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.builder.SearchSourceBuilder; + +import java.io.IOException; +import java.util.*; + +/** + */ +public class HistoryStore extends AbstractComponent { + + public static final String INDEX_PREFIX = ".watch_history_"; + public static final String DOC_TYPE = "watch_record"; + public static final String INDEX_TEMPLATE_NAME = "watch_history"; + + static final DateTimeFormatter indexTimeFormat = DateTimeFormat.forPattern("YYYY-MM-dd"); + + private final ClientProxy client; + private final TemplateUtils templateUtils; + private final int scrollSize; + private final TimeValue scrollTimeout; + private final WatchRecord.Parser recordParser; + + @Inject + public HistoryStore(Settings settings, ClientProxy client, TemplateUtils templateUtils, WatchRecord.Parser recordParser) { + super(settings); + this.client = client; + this.templateUtils = templateUtils; + this.recordParser = recordParser; + this.scrollTimeout = componentSettings.getAsTime("scroll.timeout", TimeValue.timeValueSeconds(30)); + this.scrollSize = componentSettings.getAsInt("scroll.size", 100); + } + + public void put(WatchRecord watchRecord) throws HistoryException { + String index = getHistoryIndexNameForTime(watchRecord.scheduledTime()); + try { + IndexResponse response = client.prepareIndex(index, DOC_TYPE, watchRecord.id()) + .setSource(XContentFactory.jsonBuilder().value(watchRecord)) + .setOpType(IndexRequest.OpType.CREATE) + .get(); + watchRecord.version(response.getVersion()); + } catch (IOException e) { + throw new HistoryException("failed to persist watch record [" + watchRecord + "]", e); + } + } + + public void update(WatchRecord watchRecord) throws HistoryException { + logger.debug("updating watch record [{}]...", watchRecord); + try { + BytesReference bytes = XContentFactory.jsonBuilder().value(watchRecord).bytes(); + IndexResponse response = client.prepareIndex(getHistoryIndexNameForTime(watchRecord.scheduledTime()), DOC_TYPE, watchRecord.id()) + .setSource(bytes) + .setVersion(watchRecord.version()) + .get(); + watchRecord.version(response.getVersion()); + logger.debug("successfully updated watch record [{}]", watchRecord); + } catch (IOException e) { + throw new HistoryException("failed to update watch record [" + watchRecord + "]", e); + } + } + + /** + * tries to load all watch records that await execution. If for some reason the records could not be + * loaded (e.g. the not all primary shards of the history index are active), returns {@code null}. + */ + Collection loadRecords(ClusterState state, WatchRecord.State recordState) { + String[] indices = state.metaData().concreteIndices(IndicesOptions.lenientExpandOpen(), INDEX_PREFIX + "*"); + if (indices.length == 0) { + logger.debug("No .watch_history indices found. skipping loading awaiting watch records"); + templateUtils.ensureIndexTemplateIsLoaded(state, INDEX_TEMPLATE_NAME); + return Collections.emptySet(); + } + int numPrimaryShards = 0; + for (String index : indices) { + IndexMetaData indexMetaData = state.getMetaData().index(index); + if (indexMetaData != null) { + if (!state.routingTable().index(index).allPrimaryShardsActive()) { + logger.debug("Not all primary shards of the [{}] index are started. Schedule to retry loading awaiting watch records..", index); + return null; + } else { + numPrimaryShards += indexMetaData.numberOfShards(); + } + } + } + + RefreshResponse refreshResponse = client.refresh(new RefreshRequest(INDEX_PREFIX + "*")); + if (refreshResponse.getSuccessfulShards() < numPrimaryShards) { + return null; + } + + SearchRequest searchRequest = createScanSearchRequest(recordState); + SearchResponse response = client.search(searchRequest); + List records = new ArrayList<>(); + try { + if (response.getTotalShards() != response.getSuccessfulShards()) { + return null; + } + + if (response.getHits().getTotalHits() > 0) { + response = client.searchScroll(response.getScrollId(), scrollTimeout); + while (response.getHits().hits().length != 0) { + for (SearchHit sh : response.getHits()) { + String historyId = sh.getId(); + WatchRecord record = recordParser.parse(sh.getSourceRef(), historyId, sh.version()); + assert record.state() == recordState; + logger.debug("loaded watch record [{}/{}/{}]", sh.index(), sh.type(), sh.id()); + records.add(record); + } + response = client.searchScroll(response.getScrollId(), scrollTimeout); + } + } + } finally { + client.clearScroll(response.getScrollId()); + } + templateUtils.ensureIndexTemplateIsLoaded(state, INDEX_TEMPLATE_NAME); + return records; + } + + /** + * Calculates the correct history index name for a given time + */ + public static String getHistoryIndexNameForTime(DateTime time) { + return INDEX_PREFIX + indexTimeFormat.print(time); + } + + private SearchRequest createScanSearchRequest(WatchRecord.State recordState) { + SearchSourceBuilder sourceBuilder = new SearchSourceBuilder() + .query(QueryBuilders.termQuery(WatchRecord.Parser.STATE_FIELD.getPreferredName(), recordState.id())) + .size(scrollSize) + .version(true); + + SearchRequest searchRequest = new SearchRequest(INDEX_PREFIX + "*"); + searchRequest.source(sourceBuilder); + searchRequest.searchType(SearchType.SCAN); + searchRequest.types(DOC_TYPE); + searchRequest.scroll(scrollTimeout); + searchRequest.preference("_primary"); + return searchRequest; + } +} diff --git a/src/main/java/org/elasticsearch/alerts/history/InternalAlertsExecutor.java b/src/main/java/org/elasticsearch/watcher/history/InternalWatchExecutor.java similarity index 76% rename from src/main/java/org/elasticsearch/alerts/history/InternalAlertsExecutor.java rename to src/main/java/org/elasticsearch/watcher/history/InternalWatchExecutor.java index fbe48ddee4d..9587170ed8a 100644 --- a/src/main/java/org/elasticsearch/alerts/history/InternalAlertsExecutor.java +++ b/src/main/java/org/elasticsearch/watcher/history/InternalWatchExecutor.java @@ -3,9 +3,9 @@ * 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.alerts.history; +package org.elasticsearch.watcher.history; -import org.elasticsearch.alerts.AlertsPlugin; +import org.elasticsearch.watcher.WatcherPlugin; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.util.concurrent.EsThreadPoolExecutor; import org.elasticsearch.threadpool.ThreadPool; @@ -15,12 +15,12 @@ import java.util.concurrent.BlockingQueue; /** * */ -public class InternalAlertsExecutor implements AlertsExecutor { +public class InternalWatchExecutor implements WatchExecutor { private final ThreadPool threadPool; @Inject - public InternalAlertsExecutor(ThreadPool threadPool) { + public InternalWatchExecutor(ThreadPool threadPool) { this.threadPool = threadPool; } @@ -40,6 +40,6 @@ public class InternalAlertsExecutor implements AlertsExecutor { } private EsThreadPoolExecutor executor() { - return (EsThreadPoolExecutor) threadPool.executor(AlertsPlugin.NAME); + return (EsThreadPoolExecutor) threadPool.executor(WatcherPlugin.NAME); } } \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/alerts/history/AlertsExecutor.java b/src/main/java/org/elasticsearch/watcher/history/WatchExecutor.java similarity index 83% rename from src/main/java/org/elasticsearch/alerts/history/AlertsExecutor.java rename to src/main/java/org/elasticsearch/watcher/history/WatchExecutor.java index 6cf806503d7..b53caac80d1 100644 --- a/src/main/java/org/elasticsearch/alerts/history/AlertsExecutor.java +++ b/src/main/java/org/elasticsearch/watcher/history/WatchExecutor.java @@ -3,14 +3,14 @@ * 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.alerts.history; +package org.elasticsearch.watcher.history; import java.util.concurrent.BlockingQueue; /** * */ -public interface AlertsExecutor { +public interface WatchExecutor { BlockingQueue queue(); diff --git a/src/main/java/org/elasticsearch/alerts/history/FiredAlert.java b/src/main/java/org/elasticsearch/watcher/history/WatchRecord.java similarity index 67% rename from src/main/java/org/elasticsearch/alerts/history/FiredAlert.java rename to src/main/java/org/elasticsearch/watcher/history/WatchRecord.java index c1369d46044..9e6521d6ccf 100644 --- a/src/main/java/org/elasticsearch/alerts/history/FiredAlert.java +++ b/src/main/java/org/elasticsearch/watcher/history/WatchRecord.java @@ -3,19 +3,19 @@ * 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.alerts.history; +package org.elasticsearch.watcher.history; import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.AlertExecution; -import org.elasticsearch.alerts.AlertsException; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.actions.ActionRegistry; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.ConditionRegistry; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.InputRegistry; -import org.elasticsearch.alerts.transform.TransformRegistry; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchExecution; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.actions.ActionRegistry; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionRegistry; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.InputRegistry; +import org.elasticsearch.watcher.transform.TransformRegistry; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.bytes.BytesReference; @@ -33,7 +33,7 @@ import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -public class FiredAlert implements ToXContent { +public class WatchRecord implements ToXContent { private String id; private String name; @@ -42,7 +42,7 @@ public class FiredAlert implements ToXContent { private Input input; private Condition condition; private State state; - private AlertExecution execution; + private WatchExecution execution; private @Nullable String message; private @Nullable Map metadata; @@ -52,18 +52,18 @@ public class FiredAlert implements ToXContent { private final AtomicBoolean sealed = new AtomicBoolean(false); - FiredAlert() { + WatchRecord() { } - public FiredAlert(Alert alert, DateTime scheduledTime, DateTime fireTime) { - this.id = alert.name() + "#" + scheduledTime.toDateTimeISO(); - this.name = alert.name(); + public WatchRecord(Watch watch, DateTime scheduledTime, DateTime fireTime) { + this.id = watch.name() + "#" + scheduledTime.toDateTimeISO(); + this.name = watch.name(); this.fireTime = fireTime; this.scheduledTime = scheduledTime; - this.condition = alert.condition(); - this.input = alert.input(); + this.condition = watch.condition(); + this.input = watch.input(); this.state = State.AWAITS_EXECUTION; - this.metadata = alert.metadata(); + this.metadata = watch.metadata(); this.version = 1; } @@ -114,8 +114,8 @@ public class FiredAlert implements ToXContent { this.message = message; } - public void update(AlertExecution execution) { - assert sealed.compareAndSet(false, true) : "sealing an fired alert should only be done once"; + public void seal(WatchExecution execution) { + assert sealed.compareAndSet(false, true) : "sealing a watch record should only be done once"; this.execution = execution; if (!execution.conditionResult().met()) { state = State.EXECUTION_NOT_NEEDED; @@ -131,10 +131,10 @@ public class FiredAlert implements ToXContent { @Override public XContentBuilder toXContent(XContentBuilder historyEntry, Params params) throws IOException { historyEntry.startObject(); - historyEntry.field(Parser.ALERT_NAME_FIELD.getPreferredName(), name); + historyEntry.field(Parser.WATCH_NAME_FIELD.getPreferredName(), name); historyEntry.field(Parser.FIRE_TIME_FIELD.getPreferredName(), fireTime.toDateTimeISO()); historyEntry.field(Parser.SCHEDULED_FIRE_TIME_FIELD.getPreferredName(), scheduledTime.toDateTimeISO()); - historyEntry.startObject(Alert.Parser.CONDITION_FIELD.getPreferredName()).field(condition.type(), condition, params).endObject(); + historyEntry.startObject(Watch.Parser.CONDITION_FIELD.getPreferredName()).field(condition.type(), condition, params).endObject(); historyEntry.field(Parser.STATE_FIELD.getPreferredName(), state.id()); if (message != null) { @@ -145,7 +145,7 @@ public class FiredAlert implements ToXContent { } if (execution != null) { - historyEntry.field(Parser.ALERT_EXECUTION_FIELD.getPreferredName(), execution); + historyEntry.field(Parser.WATCH_EXECUTION_FIELD.getPreferredName(), execution); } historyEntry.endObject(); @@ -157,7 +157,7 @@ public class FiredAlert implements ToXContent { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - FiredAlert entry = (FiredAlert) o; + WatchRecord entry = (WatchRecord) o; if (!id.equals(entry.id)) return false; return true; @@ -190,7 +190,7 @@ public class FiredAlert implements ToXContent { try { return valueOf(id.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException iae) { - throw new AlertsSettingsException("unknown fired alert state [" + id + "]"); + throw new WatcherSettingsException("unknown watch record state [" + id + "]"); } } @@ -202,13 +202,13 @@ public class FiredAlert implements ToXContent { public static class Parser extends AbstractComponent { - public static final ParseField ALERT_NAME_FIELD = new ParseField("alert_name"); + public static final ParseField WATCH_NAME_FIELD = new ParseField("watch_name"); public static final ParseField FIRE_TIME_FIELD = new ParseField("fire_time"); public static final ParseField SCHEDULED_FIRE_TIME_FIELD = new ParseField("scheduled_fire_time"); public static final ParseField MESSAGE_FIELD = new ParseField("message"); public static final ParseField STATE_FIELD = new ParseField("state"); public static final ParseField METADATA_FIELD = new ParseField("meta"); - public static final ParseField ALERT_EXECUTION_FIELD = new ParseField("alert_execution"); + public static final ParseField WATCH_EXECUTION_FIELD = new ParseField("watch_execution"); private final ConditionRegistry conditionRegistry; private final ActionRegistry actionRegistry; @@ -225,18 +225,18 @@ public class FiredAlert implements ToXContent { this.transformRegistry = transformRegistry; } - public FiredAlert parse(BytesReference source, String historyId, long version) { + public WatchRecord parse(BytesReference source, String historyId, long version) { try (XContentParser parser = XContentHelper.createParser(source)) { return parse(parser, historyId, version); } catch (IOException e) { - throw new ElasticsearchException("Error during parsing alert record", e); + throw new ElasticsearchException("unable to parse watch record", e); } } - public FiredAlert parse(XContentParser parser, String id, long version) throws IOException { - FiredAlert alert = new FiredAlert(); - alert.id = id; - alert.version = version; + public WatchRecord parse(XContentParser parser, String id, long version) throws IOException { + WatchRecord record = new WatchRecord(); + record.id = id; + record.version = version; String currentFieldName = null; XContentParser.Token token = parser.nextToken(); @@ -245,37 +245,37 @@ public class FiredAlert implements ToXContent { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { - if (Alert.Parser.INPUT_FIELD.match(currentFieldName)) { - alert.input = inputRegistry.parse(parser); - } else if (Alert.Parser.CONDITION_FIELD.match(currentFieldName)) { - alert.condition = conditionRegistry.parse(parser); + if (Watch.Parser.INPUT_FIELD.match(currentFieldName)) { + record.input = inputRegistry.parse(parser); + } else if (Watch.Parser.CONDITION_FIELD.match(currentFieldName)) { + record.condition = conditionRegistry.parse(parser); } else if (METADATA_FIELD.match(currentFieldName)) { - alert.metadata = parser.map(); - } else if (ALERT_EXECUTION_FIELD.match(currentFieldName)) { - alert.execution = AlertExecution.Parser.parse(parser, conditionRegistry, actionRegistry, inputRegistry, transformRegistry); + record.metadata = parser.map(); + } else if (WATCH_EXECUTION_FIELD.match(currentFieldName)) { + record.execution = WatchExecution.Parser.parse(parser, conditionRegistry, actionRegistry, inputRegistry, transformRegistry); } else { - throw new AlertsException("unable to parse fired alert. unexpected field [" + currentFieldName + "]"); + throw new WatcherException("unable to parse watch record. unexpected field [" + currentFieldName + "]"); } } else if (token.isValue()) { - if (ALERT_NAME_FIELD.match(currentFieldName)) { - alert.name = parser.text(); + if (WATCH_NAME_FIELD.match(currentFieldName)) { + record.name = parser.text(); } else if (FIRE_TIME_FIELD.match(currentFieldName)) { - alert.fireTime = DateTime.parse(parser.text()); + record.fireTime = DateTime.parse(parser.text()); } else if (SCHEDULED_FIRE_TIME_FIELD.match(currentFieldName)) { - alert.scheduledTime = DateTime.parse(parser.text()); + record.scheduledTime = DateTime.parse(parser.text()); } else if (MESSAGE_FIELD.match(currentFieldName)) { - alert.message = parser.textOrNull(); + record.message = parser.textOrNull(); } else if (STATE_FIELD.match(currentFieldName)) { - alert.state = State.resolve(parser.text()); + record.state = State.resolve(parser.text()); } else { - throw new AlertsException("unable to parse fired alert. unexpected field [" + currentFieldName + "]"); + throw new WatcherException("unable to parse watch record. unexpected field [" + currentFieldName + "]"); } } else { - throw new AlertsException("unable to parse fired alert. unexpected token [" + token + "] for [" + currentFieldName + "]"); + throw new WatcherException("unable to parse watch record. unexpected token [" + token + "] for [" + currentFieldName + "]"); } } - return alert; + return record; } } } diff --git a/src/main/java/org/elasticsearch/alerts/input/Input.java b/src/main/java/org/elasticsearch/watcher/input/Input.java similarity index 91% rename from src/main/java/org/elasticsearch/alerts/input/Input.java rename to src/main/java/org/elasticsearch/watcher/input/Input.java index a34c09de20c..ac31ff5a301 100644 --- a/src/main/java/org/elasticsearch/alerts/input/Input.java +++ b/src/main/java/org/elasticsearch/watcher/input/Input.java @@ -3,10 +3,10 @@ * 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.alerts.input; +package org.elasticsearch.watcher.input; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.xcontent.ToXContent; @@ -34,7 +34,7 @@ public abstract class Input implements ToXContent { /** * Executes this input */ - public abstract R execute(ExecutionContext ctx) throws IOException; + public abstract R execute(WatchExecutionContext ctx) throws IOException; /** diff --git a/src/main/java/org/elasticsearch/alerts/input/InputBuilders.java b/src/main/java/org/elasticsearch/watcher/input/InputBuilders.java similarity index 86% rename from src/main/java/org/elasticsearch/alerts/input/InputBuilders.java rename to src/main/java/org/elasticsearch/watcher/input/InputBuilders.java index d7215c703d8..fcb24bd7ba8 100644 --- a/src/main/java/org/elasticsearch/alerts/input/InputBuilders.java +++ b/src/main/java/org/elasticsearch/watcher/input/InputBuilders.java @@ -3,12 +3,12 @@ * 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.alerts.input; +package org.elasticsearch.watcher.input; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchRequestBuilder; -import org.elasticsearch.alerts.input.search.SearchInput; -import org.elasticsearch.alerts.input.simple.SimpleInput; +import org.elasticsearch.watcher.input.search.SearchInput; +import org.elasticsearch.watcher.input.simple.SimpleInput; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/org/elasticsearch/alerts/input/InputException.java b/src/main/java/org/elasticsearch/watcher/input/InputException.java similarity index 73% rename from src/main/java/org/elasticsearch/alerts/input/InputException.java rename to src/main/java/org/elasticsearch/watcher/input/InputException.java index 2313e9491b7..05f8cd6d4c4 100644 --- a/src/main/java/org/elasticsearch/alerts/input/InputException.java +++ b/src/main/java/org/elasticsearch/watcher/input/InputException.java @@ -3,14 +3,14 @@ * 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.alerts.input; +package org.elasticsearch.watcher.input; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; /** * */ -public class InputException extends AlertsException { +public class InputException extends WatcherException { public InputException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/input/InputModule.java b/src/main/java/org/elasticsearch/watcher/input/InputModule.java similarity index 90% rename from src/main/java/org/elasticsearch/alerts/input/InputModule.java rename to src/main/java/org/elasticsearch/watcher/input/InputModule.java index 103cdece74a..6594dad5ae1 100644 --- a/src/main/java/org/elasticsearch/alerts/input/InputModule.java +++ b/src/main/java/org/elasticsearch/watcher/input/InputModule.java @@ -3,10 +3,10 @@ * 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.alerts.input; +package org.elasticsearch.watcher.input; -import org.elasticsearch.alerts.input.search.SearchInput; -import org.elasticsearch.alerts.input.simple.SimpleInput; +import org.elasticsearch.watcher.input.search.SearchInput; +import org.elasticsearch.watcher.input.simple.SimpleInput; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.multibindings.MapBinder; diff --git a/src/main/java/org/elasticsearch/alerts/input/InputRegistry.java b/src/main/java/org/elasticsearch/watcher/input/InputRegistry.java similarity index 98% rename from src/main/java/org/elasticsearch/alerts/input/InputRegistry.java rename to src/main/java/org/elasticsearch/watcher/input/InputRegistry.java index 787cda40f36..3748f346783 100644 --- a/src/main/java/org/elasticsearch/alerts/input/InputRegistry.java +++ b/src/main/java/org/elasticsearch/watcher/input/InputRegistry.java @@ -3,7 +3,7 @@ * 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.alerts.input; +package org.elasticsearch.watcher.input; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; diff --git a/src/main/java/org/elasticsearch/alerts/input/NoneInput.java b/src/main/java/org/elasticsearch/watcher/input/NoneInput.java similarity index 93% rename from src/main/java/org/elasticsearch/alerts/input/NoneInput.java rename to src/main/java/org/elasticsearch/watcher/input/NoneInput.java index 47407734e7d..c950180a3de 100644 --- a/src/main/java/org/elasticsearch/alerts/input/NoneInput.java +++ b/src/main/java/org/elasticsearch/watcher/input/NoneInput.java @@ -3,10 +3,10 @@ * 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.alerts.input; +package org.elasticsearch.watcher.input; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.logging.ESLogger; @@ -46,7 +46,7 @@ public class NoneInput extends Input { } @Override - public Result execute(ExecutionContext ctx) throws IOException { + public Result execute(WatchExecutionContext ctx) throws IOException { return Result.INSTANCE; } diff --git a/src/main/java/org/elasticsearch/alerts/input/search/SearchInput.java b/src/main/java/org/elasticsearch/watcher/input/search/SearchInput.java similarity index 86% rename from src/main/java/org/elasticsearch/alerts/input/search/SearchInput.java rename to src/main/java/org/elasticsearch/watcher/input/search/SearchInput.java index d3214d6f38d..53d0c71b65a 100644 --- a/src/main/java/org/elasticsearch/alerts/input/search/SearchInput.java +++ b/src/main/java/org/elasticsearch/watcher/input/search/SearchInput.java @@ -3,20 +3,20 @@ * 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.alerts.input.search; +package org.elasticsearch.watcher.input.search; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.InputException; -import org.elasticsearch.alerts.support.AlertUtils; -import org.elasticsearch.alerts.support.SearchRequestEquivalence; -import org.elasticsearch.alerts.support.Variables; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.InputException; +import org.elasticsearch.watcher.support.WatcherUtils; +import org.elasticsearch.watcher.support.SearchRequestEquivalence; +import org.elasticsearch.watcher.support.Variables; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; @@ -37,10 +37,10 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -import static org.elasticsearch.alerts.support.AlertsDateUtils.formatDate; +import static org.elasticsearch.watcher.support.WatcherDateUtils.formatDate; /** - * This class just defines an input that runs a search + * An input that executes search and returns the search response as the initial payload */ public class SearchInput extends Input { @@ -66,17 +66,17 @@ public class SearchInput extends Input { } @Override - public Result execute(ExecutionContext ctx) throws IOException { + public Result execute(WatchExecutionContext ctx) throws IOException { SearchRequest request = createSearchRequestWithTimes(this.searchRequest, ctx.scheduledTime(), ctx.fireTime(), ctx.executionTime(), scriptService); if (logger.isTraceEnabled()) { - logger.trace("[{}] running query for [{}] [{}]", ctx.id(), ctx.alert().name(), XContentHelper.convertToJson(request.source(), false, true)); + logger.trace("[{}] running query for [{}] [{}]", ctx.id(), ctx.watch().name(), XContentHelper.convertToJson(request.source(), false, true)); } // actionGet deals properly with InterruptedException SearchResponse response = client.search(request); if (logger.isDebugEnabled()) { - logger.debug("[{}] found [{}] hits", ctx.id(), ctx.alert().name(), response.getHits().getTotalHits()); + logger.debug("[{}] found [{}] hits", ctx.id(), ctx.watch().name(), response.getHits().getTotalHits()); for (SearchHit hit : response.getHits()) { logger.debug("[{}] hit [{}]", ctx.id(), XContentHelper.toString(hit)); } @@ -88,7 +88,7 @@ public class SearchInput extends Input { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - return AlertUtils.writeSearchRequest(searchRequest, builder, params); + return WatcherUtils.writeSearchRequest(searchRequest, builder, params); } @Override @@ -153,7 +153,7 @@ public class SearchInput extends Input { @Override protected XContentBuilder toXContentBody(XContentBuilder builder, Params params) throws IOException { builder.field(Parser.REQUEST_FIELD.getPreferredName()); - return AlertUtils.writeSearchRequest(request, builder, params); + return WatcherUtils.writeSearchRequest(request, builder, params); } } @@ -177,7 +177,7 @@ public class SearchInput extends Input { @Override public SearchInput parse(XContentParser parser) throws IOException { - SearchRequest request = AlertUtils.readSearchRequest(parser, DEFAULT_SEARCH_TYPE); + SearchRequest request = WatcherUtils.readSearchRequest(parser, DEFAULT_SEARCH_TYPE); if (request == null) { throw new InputException("could not parse [search] input. search request is missing or null."); } @@ -198,7 +198,7 @@ public class SearchInput extends Input { if (Input.Result.PAYLOAD_FIELD.match(currentFieldName)) { payload = new Payload.XContent(parser); } else if (REQUEST_FIELD.match(currentFieldName)) { - request = AlertUtils.readSearchRequest(parser, DEFAULT_SEARCH_TYPE); + request = WatcherUtils.readSearchRequest(parser, DEFAULT_SEARCH_TYPE); } else { throw new InputException("unable to parse [" + TYPE + "] input result. unexpected field [" + currentFieldName + "]"); } @@ -234,7 +234,7 @@ public class SearchInput extends Input { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - return AlertUtils.writeSearchRequest(request, builder, params); + return WatcherUtils.writeSearchRequest(request, builder, params); } } } diff --git a/src/main/java/org/elasticsearch/alerts/input/simple/SimpleInput.java b/src/main/java/org/elasticsearch/watcher/input/simple/SimpleInput.java similarity index 93% rename from src/main/java/org/elasticsearch/alerts/input/simple/SimpleInput.java rename to src/main/java/org/elasticsearch/watcher/input/simple/SimpleInput.java index d6fc921c23c..1a0a4071212 100644 --- a/src/main/java/org/elasticsearch/alerts/input/simple/SimpleInput.java +++ b/src/main/java/org/elasticsearch/watcher/input/simple/SimpleInput.java @@ -3,22 +3,20 @@ * 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.alerts.input.simple; +package org.elasticsearch.watcher.input.simple; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.InputException; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.InputException; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.Settings; -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; import java.util.Objects; @@ -42,7 +40,7 @@ public class SimpleInput extends Input { } @Override - public Result execute(ExecutionContext ctx) throws IOException { + public Result execute(WatchExecutionContext ctx) throws IOException { return new Result(TYPE, payload); } diff --git a/src/main/java/org/elasticsearch/watcher/rest/WatcherRestHandler.java b/src/main/java/org/elasticsearch/watcher/rest/WatcherRestHandler.java new file mode 100644 index 00000000000..31d6c4d4f01 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/rest/WatcherRestHandler.java @@ -0,0 +1,33 @@ +/* + * 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.watcher.rest; + +import org.elasticsearch.client.Client; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.rest.BaseRestHandler; +import org.elasticsearch.rest.RestChannel; +import org.elasticsearch.rest.RestController; +import org.elasticsearch.rest.RestRequest; +import org.elasticsearch.watcher.client.WatcherClient; + +/** + * + */ +public abstract class WatcherRestHandler extends BaseRestHandler { + + protected static String URI_BASE = "_watcher"; + + public WatcherRestHandler(Settings settings, RestController controller, Client client) { + super(settings, controller, client); + } + + @Override + protected final void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { + handleRequest(request, channel, new WatcherClient(client)); + } + + protected abstract void handleRequest(RestRequest request, RestChannel channel, WatcherClient client) throws Exception; +} diff --git a/src/main/java/org/elasticsearch/alerts/rest/AlertsRestModule.java b/src/main/java/org/elasticsearch/watcher/rest/WatcherRestModule.java similarity index 52% rename from src/main/java/org/elasticsearch/alerts/rest/AlertsRestModule.java rename to src/main/java/org/elasticsearch/watcher/rest/WatcherRestModule.java index c8962978406..dde2d2e15b0 100644 --- a/src/main/java/org/elasticsearch/alerts/rest/AlertsRestModule.java +++ b/src/main/java/org/elasticsearch/watcher/rest/WatcherRestModule.java @@ -3,9 +3,9 @@ * 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.alerts.rest; +package org.elasticsearch.watcher.rest; -import org.elasticsearch.alerts.rest.action.*; +import org.elasticsearch.watcher.rest.action.*; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.inject.PreProcessModule; @@ -14,18 +14,19 @@ import org.elasticsearch.rest.RestModule; /** * */ -public class AlertsRestModule extends AbstractModule implements PreProcessModule { +public class WatcherRestModule extends AbstractModule implements PreProcessModule { @Override public void processModule(Module module) { if (module instanceof RestModule) { RestModule restModule = (RestModule) module; - restModule.addRestAction(RestPutAlertAction.class); - restModule.addRestAction(RestDeleteAlertAction.class); - restModule.addRestAction(RestAlertsStatsAction.class); - restModule.addRestAction(RestGetAlertAction.class); - restModule.addRestAction(RestAlertServiceAction.class); - restModule.addRestAction(RestAckAlertAction.class); + restModule.addRestAction(RestPutWatchAction.class); + restModule.addRestAction(RestDeleteWatchAction.class); + restModule.addRestAction(RestWatcherStatsAction.class); + restModule.addRestAction(RestWatcherInfoAction.class); + restModule.addRestAction(RestGetWatchAction.class); + restModule.addRestAction(RestWatchServiceAction.class); + restModule.addRestAction(RestAckWatchAction.class); } } diff --git a/src/main/java/org/elasticsearch/watcher/rest/action/RestAckWatchAction.java b/src/main/java/org/elasticsearch/watcher/rest/action/RestAckWatchAction.java new file mode 100644 index 00000000000..a73aeea028f --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/rest/action/RestAckWatchAction.java @@ -0,0 +1,45 @@ +/* + * 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.watcher.rest.action; + +import org.elasticsearch.watcher.rest.WatcherRestHandler; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.transport.actions.ack.AckWatchRequest; +import org.elasticsearch.watcher.transport.actions.ack.AckWatchResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.rest.*; +import org.elasticsearch.rest.action.support.RestBuilderListener; + +/** + * The rest action to ack a watch + */ +public class RestAckWatchAction extends WatcherRestHandler { + + @Inject + protected RestAckWatchAction(Settings settings, RestController controller, Client client) { + super(settings, controller, client); + controller.registerHandler(RestRequest.Method.PUT, URI_BASE + "/watch/{name}/_ack", this); + } + + @Override + protected void handleRequest(RestRequest request, RestChannel restChannel, WatcherClient client) throws Exception { + AckWatchRequest ackWatchRequest = new AckWatchRequest(request.param("name")); + client.ackWatch(ackWatchRequest, new RestBuilderListener(restChannel) { + @Override + public RestResponse buildResponse(AckWatchResponse response, XContentBuilder builder) throws Exception { + return new BytesRestResponse(RestStatus.OK, builder.startObject() + .field(Watch.Parser.STATUS_FIELD.getPreferredName(), response.getStatus().toString()) + .endObject()); + + } + }); + } + +} diff --git a/src/main/java/org/elasticsearch/alerts/rest/action/RestDeleteAlertAction.java b/src/main/java/org/elasticsearch/watcher/rest/action/RestDeleteWatchAction.java similarity index 52% rename from src/main/java/org/elasticsearch/alerts/rest/action/RestDeleteAlertAction.java rename to src/main/java/org/elasticsearch/watcher/rest/action/RestDeleteWatchAction.java index e4bd468b29f..09e62f5c208 100644 --- a/src/main/java/org/elasticsearch/alerts/rest/action/RestDeleteAlertAction.java +++ b/src/main/java/org/elasticsearch/watcher/rest/action/RestDeleteWatchAction.java @@ -3,19 +3,19 @@ * 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.alerts.rest.action; +package org.elasticsearch.watcher.rest.action; import org.elasticsearch.action.delete.DeleteResponse; -import org.elasticsearch.alerts.AlertsStore; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.transport.actions.delete.DeleteAlertRequest; -import org.elasticsearch.alerts.transport.actions.delete.DeleteAlertResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.*; import org.elasticsearch.rest.action.support.RestBuilderListener; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.rest.WatcherRestHandler; +import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchRequest; +import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchResponse; import static org.elasticsearch.rest.RestRequest.Method.DELETE; import static org.elasticsearch.rest.RestStatus.NOT_FOUND; @@ -23,36 +23,27 @@ import static org.elasticsearch.rest.RestStatus.OK; /** */ -public class RestDeleteAlertAction extends BaseRestHandler { - - private final AlertsClient alertsClient; +public class RestDeleteWatchAction extends WatcherRestHandler { @Inject - public RestDeleteAlertAction(Settings settings, RestController controller, Client client, AlertsClient alertsClient) { + public RestDeleteWatchAction(Settings settings, RestController controller, Client client) { super(settings, controller, client); - this.alertsClient = alertsClient; - controller.registerHandler(DELETE, AlertsStore.ALERT_INDEX + "/alert/{name}", this); + controller.registerHandler(DELETE, URI_BASE + "/watch/{name}", this); } @Override - protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { - DeleteAlertRequest indexAlertRequest = new DeleteAlertRequest(); - indexAlertRequest.setAlertName(request.param("name")); - alertsClient.deleteAlert(indexAlertRequest, new RestBuilderListener(channel) { + protected void handleRequest(RestRequest request, RestChannel channel, WatcherClient client) throws Exception { + DeleteWatchRequest indexWatchRequest = new DeleteWatchRequest(request.param("name")); + client.deleteWatch(indexWatchRequest, new RestBuilderListener(channel) { @Override - public RestResponse buildResponse(DeleteAlertResponse result, XContentBuilder builder) throws Exception { + public RestResponse buildResponse(DeleteWatchResponse result, XContentBuilder builder) throws Exception { DeleteResponse deleteResponse = result.deleteResponse(); builder.startObject() .field("found", deleteResponse.isFound()) - .field("_index", deleteResponse.getIndex()) - .field("_type", deleteResponse.getType()) .field("_id", deleteResponse.getId()) .field("_version", deleteResponse.getVersion()) .endObject(); - RestStatus status = OK; - if (!deleteResponse.isFound()) { - status = NOT_FOUND; - } + RestStatus status = deleteResponse.isFound() ? OK : NOT_FOUND; return new BytesRestResponse(status, builder); } }); diff --git a/src/main/java/org/elasticsearch/watcher/rest/action/RestGetWatchAction.java b/src/main/java/org/elasticsearch/watcher/rest/action/RestGetWatchAction.java new file mode 100644 index 00000000000..95621d5bbd6 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/rest/action/RestGetWatchAction.java @@ -0,0 +1,51 @@ +/* + * 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.watcher.rest.action; + +import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.rest.*; +import org.elasticsearch.rest.action.support.RestBuilderListener; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.rest.WatcherRestHandler; +import org.elasticsearch.watcher.transport.actions.get.GetWatchRequest; +import org.elasticsearch.watcher.transport.actions.get.GetWatchResponse; + +import static org.elasticsearch.rest.RestRequest.Method.GET; +import static org.elasticsearch.rest.RestStatus.NOT_FOUND; +import static org.elasticsearch.rest.RestStatus.OK; + +public class RestGetWatchAction extends WatcherRestHandler { + + @Inject + public RestGetWatchAction(Settings settings, RestController controller, Client client) { + super(settings, controller, client); + controller.registerHandler(GET, URI_BASE + "/watch/{name}", this); + } + + @Override + protected void handleRequest(RestRequest request, RestChannel channel, WatcherClient client) throws Exception { + final GetWatchRequest getWatchRequest = new GetWatchRequest(request.param("name")); + client.getWatch(getWatchRequest, new RestBuilderListener(channel) { + @Override + public RestResponse buildResponse(GetWatchResponse response, XContentBuilder builder) throws Exception { + GetResponse getResponse = response.getResponse(); + builder.startObject() + .field("found", getResponse.isExists()) + .field("_id", getResponse.getId()) + .field("_version", getResponse.getVersion()) + .field("watch", getResponse.getSource()) + .endObject(); + + RestStatus status = getResponse.isExists() ? OK : NOT_FOUND; + return new BytesRestResponse(status, builder); + } + }); + } +} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/watcher/rest/action/RestPutWatchAction.java b/src/main/java/org/elasticsearch/watcher/rest/action/RestPutWatchAction.java new file mode 100644 index 00000000000..2f2eb700863 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/rest/action/RestPutWatchAction.java @@ -0,0 +1,53 @@ +/* + * 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.watcher.rest.action; + +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.rest.*; +import org.elasticsearch.rest.action.support.RestBuilderListener; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.rest.WatcherRestHandler; +import org.elasticsearch.watcher.transport.actions.put.PutWatchRequest; +import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; + +import static org.elasticsearch.rest.RestRequest.Method.POST; +import static org.elasticsearch.rest.RestRequest.Method.PUT; +import static org.elasticsearch.rest.RestStatus.CREATED; +import static org.elasticsearch.rest.RestStatus.OK; + +/** + */ +public class RestPutWatchAction extends WatcherRestHandler { + + @Inject + public RestPutWatchAction(Settings settings, RestController controller, Client client) { + super(settings, controller, client); + controller.registerHandler(POST, URI_BASE + "/watch/{name}", this); + controller.registerHandler(PUT, URI_BASE + "/watch/{name}", this); + } + + @Override + protected void handleRequest(RestRequest request, RestChannel channel, WatcherClient client) throws Exception { + PutWatchRequest putWatchRequest = new PutWatchRequest(request.param("name"), request.content(), request.contentUnsafe()); + client.putWatch(putWatchRequest, new RestBuilderListener(channel) { + @Override + public RestResponse buildResponse(PutWatchResponse response, XContentBuilder builder) throws Exception { + IndexResponse indexResponse = response.indexResponse(); + builder.startObject() + .field("_id", indexResponse.getId()) + .field("_version", indexResponse.getVersion()) + .field("created", indexResponse.isCreated()) + .endObject(); + RestStatus status = indexResponse.isCreated() ? CREATED : OK; + return new BytesRestResponse(status, builder); + } + }); + } +} diff --git a/src/main/java/org/elasticsearch/watcher/rest/action/RestWatchServiceAction.java b/src/main/java/org/elasticsearch/watcher/rest/action/RestWatchServiceAction.java new file mode 100644 index 00000000000..947d4e721ac --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/rest/action/RestWatchServiceAction.java @@ -0,0 +1,61 @@ +/* + * 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.watcher.rest.action; + +import org.elasticsearch.watcher.watch.WatchStore; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.transport.actions.service.WatcherServiceRequest; +import org.elasticsearch.watcher.transport.actions.service.WatcherServiceResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.rest.BaseRestHandler; +import org.elasticsearch.rest.RestChannel; +import org.elasticsearch.rest.RestController; +import org.elasticsearch.rest.RestRequest; +import org.elasticsearch.rest.action.support.AcknowledgedRestListener; + +/** + */ +public class RestWatchServiceAction extends BaseRestHandler { + + @Inject + protected RestWatchServiceAction(Settings settings, RestController controller, Client client) { + super(settings, controller, client); + controller.registerHandler(RestRequest.Method.PUT, WatchStore.INDEX + "/_restart", this); + controller.registerHandler(RestRequest.Method.PUT, WatchStore.INDEX + "/_start", new StartRestHandler(settings, controller, client)); + controller.registerHandler(RestRequest.Method.PUT, WatchStore.INDEX + "/_stop", new StopRestHandler(settings, controller, client)); + } + + @Override + protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { + new WatcherClient(client).watcherService(new WatcherServiceRequest().restart(), new AcknowledgedRestListener(channel)); + } + + static class StartRestHandler extends BaseRestHandler { + + public StartRestHandler(Settings settings, RestController controller, Client client) { + super(settings, controller, client); + } + + @Override + public void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { + new WatcherClient(client).watcherService(new WatcherServiceRequest().start(), new AcknowledgedRestListener(channel)); + } + } + + static class StopRestHandler extends BaseRestHandler { + + public StopRestHandler(Settings settings, RestController controller, Client client) { + super(settings, controller, client); + } + + @Override + public void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { + new WatcherClient(client).watcherService(new WatcherServiceRequest().stop(), new AcknowledgedRestListener(channel)); + } + } +} diff --git a/src/main/java/org/elasticsearch/watcher/rest/action/RestWatcherInfoAction.java b/src/main/java/org/elasticsearch/watcher/rest/action/RestWatcherInfoAction.java new file mode 100644 index 00000000000..8e39548c012 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/rest/action/RestWatcherInfoAction.java @@ -0,0 +1,50 @@ +/* + * 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.watcher.rest.action; + +import org.elasticsearch.client.Client; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.rest.*; +import org.elasticsearch.rest.action.support.RestBuilderListener; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.rest.WatcherRestHandler; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsRequest; + +import static org.elasticsearch.rest.RestRequest.Method.GET; +import static org.elasticsearch.rest.RestStatus.OK; + +public class RestWatcherInfoAction extends WatcherRestHandler { + + private final WatcherClient watcherClient; + + @Inject + protected RestWatcherInfoAction(Settings settings, RestController controller, Client client, WatcherClient watcherClient) { + super(settings, controller, client); + this.watcherClient = watcherClient; + controller.registerHandler(GET, URI_BASE, this); + } + + @Override + protected void handleRequest(RestRequest request, RestChannel restChannel, WatcherClient client) throws Exception { + watcherClient.watcherStats(new WatcherStatsRequest(), new RestBuilderListener(restChannel) { + @Override + public RestResponse buildResponse(WatcherStatsResponse watcherStatsResponse, XContentBuilder builder) throws Exception { + builder.startObject("version") + .field("number", watcherStatsResponse.getVersion().number()) + .field("build_hash", watcherStatsResponse.getBuild().hash()) + .field("build_timestamp", watcherStatsResponse.getBuild().timestamp()) + .field("build_snapshot", watcherStatsResponse.getVersion().snapshot) + .endObject(); + + return new BytesRestResponse(OK, builder); + + } + }); + } +} diff --git a/src/main/java/org/elasticsearch/watcher/rest/action/RestWatcherStatsAction.java b/src/main/java/org/elasticsearch/watcher/rest/action/RestWatcherStatsAction.java new file mode 100644 index 00000000000..05c992a139c --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/rest/action/RestWatcherStatsAction.java @@ -0,0 +1,53 @@ +/* + * 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.watcher.rest.action; + +import org.elasticsearch.client.Client; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.rest.*; +import org.elasticsearch.rest.action.support.RestBuilderListener; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.rest.WatcherRestHandler; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsRequest; + +import java.util.Locale; + +import static org.elasticsearch.rest.RestRequest.Method.GET; +import static org.elasticsearch.rest.RestStatus.OK; + +public class RestWatcherStatsAction extends WatcherRestHandler { + + private final WatcherClient watcherClient; + + @Inject + protected RestWatcherStatsAction(Settings settings, RestController controller, Client client, WatcherClient watcherClient) { + super(settings, controller, client); + this.watcherClient = watcherClient; + controller.registerHandler(GET, URI_BASE + "/stats", this); + } + + @Override + protected void handleRequest(RestRequest request, RestChannel restChannel, WatcherClient client) throws Exception { + watcherClient.watcherStats(new WatcherStatsRequest(), new RestBuilderListener(restChannel) { + @Override + public RestResponse buildResponse(WatcherStatsResponse watcherStatsResponse, XContentBuilder builder) throws Exception { + builder.field("watch_service_state", watcherStatsResponse.getWatchServiceState().toString().toLowerCase(Locale.ROOT)) + .field("watch_count", watcherStatsResponse.getWatchesCount()); + + builder.startObject("execution_queue") + .field("size", watcherStatsResponse.getExecutionQueueSize()) + .field("max_size", watcherStatsResponse.getWatchExecutionQueueMaxSize()) + .endObject(); + + return new BytesRestResponse(OK, builder); + + } + }); + } +} diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/InternalScheduler.java b/src/main/java/org/elasticsearch/watcher/scheduler/InternalScheduler.java similarity index 84% rename from src/main/java/org/elasticsearch/alerts/scheduler/InternalScheduler.java rename to src/main/java/org/elasticsearch/watcher/scheduler/InternalScheduler.java index 7767ad71c1e..9a4f4e5acd7 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/InternalScheduler.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/InternalScheduler.java @@ -3,14 +3,14 @@ * 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.alerts.scheduler; +package org.elasticsearch.watcher.scheduler; -import org.elasticsearch.alerts.AlertsPlugin; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.CronnableSchedule; -import org.elasticsearch.alerts.scheduler.schedule.IntervalSchedule; -import org.elasticsearch.alerts.scheduler.schedule.Schedule; -import org.elasticsearch.alerts.support.clock.Clock; +import org.elasticsearch.watcher.WatcherPlugin; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.CronnableSchedule; +import org.elasticsearch.watcher.scheduler.schedule.IntervalSchedule; +import org.elasticsearch.watcher.scheduler.schedule.Schedule; +import org.elasticsearch.watcher.support.clock.Clock; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.joda.time.DateTime; @@ -25,7 +25,7 @@ import org.quartz.simpl.SimpleJobFactory; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; -import static org.elasticsearch.alerts.scheduler.FireAlertQuartzJob.jobDetail; +import static org.elasticsearch.watcher.scheduler.WatcherQuartzJob.jobDetail; public class InternalScheduler extends AbstractComponent implements Scheduler { @@ -49,7 +49,7 @@ public class InternalScheduler extends AbstractComponent implements Scheduler { try { this.defaultTimeZone = DateTimeZone.forID(timeZoneStr); } catch (IllegalArgumentException iae) { - throw new AlertsSettingsException("unrecognized time zone setting [" + timeZoneStr + "]", iae); + throw new WatcherSettingsException("unrecognized time zone setting [" + timeZoneStr + "]", iae); } } @@ -59,7 +59,7 @@ public class InternalScheduler extends AbstractComponent implements Scheduler { logger.info("Starting scheduler"); // Can't start a scheduler that has been shutdown, so we need to re-create each time start() is invoked Properties properties = new Properties(); - properties.setProperty("org.quartz.threadPool.class", AlertQuartzThreadPool.class.getName()); + properties.setProperty("org.quartz.threadPool.class", WatcherQuartzThreadPool.class.getName()); properties.setProperty(StdSchedulerFactory.PROP_SCHED_SKIP_UPDATE_CHECK, "true"); properties.setProperty(StdSchedulerFactory.PROP_SCHED_INTERRUPT_JOBS_ON_SHUTDOWN, "true"); properties.setProperty(StdSchedulerFactory.PROP_SCHED_INTERRUPT_JOBS_ON_SHUTDOWN_WITH_WAIT, "true"); @@ -67,8 +67,8 @@ public class InternalScheduler extends AbstractComponent implements Scheduler { scheduler = schFactory.getScheduler(); scheduler.setJobFactory(new SimpleJobFactory()); Map> quartzJobs = new HashMap<>(); - for (Job alert : jobs) { - quartzJobs.put(jobDetail(alert.name(), this), createTrigger(alert.schedule(), defaultTimeZone, clock)); + for (Job job : jobs) { + quartzJobs.put(jobDetail(job.name(), this), createTrigger(job.schedule(), defaultTimeZone, clock)); } scheduler.scheduleJobs(quartzJobs, false); scheduler.start(); @@ -96,16 +96,16 @@ public class InternalScheduler extends AbstractComponent implements Scheduler { listeners.add(listener); } - void notifyListeners(String alertName, JobExecutionContext ctx) { + void notifyListeners(String name, JobExecutionContext ctx) { DateTime scheduledTime = new DateTime(ctx.getScheduledFireTime()); DateTime fireTime = new DateTime(ctx.getFireTime()); for (Listener listener : listeners) { - listener.fire(alertName, scheduledTime, fireTime); + listener.fire(name, scheduledTime, fireTime); } } /** - * Schedules the given alert + * Schedules the given job */ public void add(Job job) { try { @@ -147,13 +147,13 @@ public class InternalScheduler extends AbstractComponent implements Scheduler { } - // This Quartz thread pool will always accept. On this thread we will only index an alert action and add it to the work queue - public static final class AlertQuartzThreadPool implements org.quartz.spi.ThreadPool { + // This Quartz thread pool will always accept. On this thread we will only index a watch record and add it to the work queue + public static final class WatcherQuartzThreadPool implements org.quartz.spi.ThreadPool { private final EsThreadPoolExecutor executor; - public AlertQuartzThreadPool() { - this.executor = (EsThreadPoolExecutor) threadPool.executor(AlertsPlugin.SCHEDULER_THREAD_POOL_NAME); + public WatcherQuartzThreadPool() { + this.executor = (EsThreadPoolExecutor) threadPool.executor(WatcherPlugin.SCHEDULER_THREAD_POOL_NAME); } @Override diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/Scheduler.java b/src/main/java/org/elasticsearch/watcher/scheduler/Scheduler.java similarity index 90% rename from src/main/java/org/elasticsearch/alerts/scheduler/Scheduler.java rename to src/main/java/org/elasticsearch/watcher/scheduler/Scheduler.java index ff0c527894e..a3aa6aaa3f4 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/Scheduler.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/Scheduler.java @@ -3,9 +3,9 @@ * 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.alerts.scheduler; +package org.elasticsearch.watcher.scheduler; -import org.elasticsearch.alerts.scheduler.schedule.Schedule; +import org.elasticsearch.watcher.scheduler.schedule.Schedule; import org.elasticsearch.common.joda.time.DateTime; import java.util.Collection; diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/SchedulerException.java b/src/main/java/org/elasticsearch/watcher/scheduler/SchedulerException.java similarity index 73% rename from src/main/java/org/elasticsearch/alerts/scheduler/SchedulerException.java rename to src/main/java/org/elasticsearch/watcher/scheduler/SchedulerException.java index 0a408873d01..25cd748f733 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/SchedulerException.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/SchedulerException.java @@ -3,14 +3,14 @@ * 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.alerts.scheduler; +package org.elasticsearch.watcher.scheduler; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; /** * */ -public class SchedulerException extends AlertsException { +public class SchedulerException extends WatcherException { public SchedulerException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/SchedulerModule.java b/src/main/java/org/elasticsearch/watcher/scheduler/SchedulerModule.java similarity index 96% rename from src/main/java/org/elasticsearch/alerts/scheduler/SchedulerModule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/SchedulerModule.java index d56183dd2b4..25ce63eb77b 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/SchedulerModule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/SchedulerModule.java @@ -3,9 +3,9 @@ * 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.alerts.scheduler; +package org.elasticsearch.watcher.scheduler; -import org.elasticsearch.alerts.scheduler.schedule.*; +import org.elasticsearch.watcher.scheduler.schedule.*; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.multibindings.MapBinder; diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/FireAlertQuartzJob.java b/src/main/java/org/elasticsearch/watcher/scheduler/WatcherQuartzJob.java similarity index 58% rename from src/main/java/org/elasticsearch/alerts/scheduler/FireAlertQuartzJob.java rename to src/main/java/org/elasticsearch/watcher/scheduler/WatcherQuartzJob.java index a02ffe69500..deba6626e52 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/FireAlertQuartzJob.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/WatcherQuartzJob.java @@ -3,30 +3,30 @@ * 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.alerts.scheduler; +package org.elasticsearch.watcher.scheduler; import org.quartz.*; -public class FireAlertQuartzJob implements Job { +public class WatcherQuartzJob implements Job { static final String SCHEDULER_KEY = "scheduler"; - public FireAlertQuartzJob() { + public WatcherQuartzJob() { } @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { - String alertName = jobExecutionContext.getJobDetail().getKey().getName(); + String watchName = jobExecutionContext.getJobDetail().getKey().getName(); InternalScheduler scheduler = (InternalScheduler) jobExecutionContext.getJobDetail().getJobDataMap().get(SCHEDULER_KEY); - scheduler.notifyListeners(alertName, jobExecutionContext); + scheduler.notifyListeners(watchName, jobExecutionContext); } - static JobKey jobKey(String alertName) { - return new JobKey(alertName); + static JobKey jobKey(String watchName) { + return new JobKey(watchName); } - static JobDetail jobDetail(String alertName, InternalScheduler scheduler) { - JobDetail job = JobBuilder.newJob(FireAlertQuartzJob.class).withIdentity(alertName).build(); + static JobDetail jobDetail(String watchName, InternalScheduler scheduler) { + JobDetail job = JobBuilder.newJob(WatcherQuartzJob.class).withIdentity(watchName).build(); job.getJobDataMap().put("scheduler", scheduler); return job; } diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/CronSchedule.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/CronSchedule.java similarity index 77% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/CronSchedule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/CronSchedule.java index a93a2e16c60..7c1746a1be2 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/CronSchedule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/CronSchedule.java @@ -3,9 +3,9 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.quartz.CronExpression; @@ -69,24 +69,24 @@ public class CronSchedule extends CronnableSchedule { crons.add(parser.text()); break; default: - throw new AlertsSettingsException("could not parse [cron] schedule. expected a string value in the cron array but found [" + token + "]"); + throw new WatcherSettingsException("could not parse [cron] schedule. expected a string value in the cron array but found [" + token + "]"); } } if (crons.isEmpty()) { - throw new AlertsSettingsException("could not parse [cron] schedule. no cron expression found in cron array"); + throw new WatcherSettingsException("could not parse [cron] schedule. no cron expression found in cron array"); } return new CronSchedule(crons.toArray(new String[crons.size()])); } else { - throw new AlertsSettingsException("could not parse [cron] schedule. expected either a cron string value or an array of cron string values, but found [" + token + "]"); + throw new WatcherSettingsException("could not parse [cron] schedule. expected either a cron string value or an array of cron string values, but found [" + token + "]"); } } catch (ValidationException ve) { - throw new AlertsSettingsException("could not parse [cron] schedule. invalid cron expression [" + ve.expression + "]", ve); + throw new WatcherSettingsException("could not parse [cron] schedule. invalid cron expression [" + ve.expression + "]", ve); } } } - public static class ValidationException extends AlertsSettingsException { + public static class ValidationException extends WatcherSettingsException { private String expression; diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/CronnableSchedule.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/CronnableSchedule.java similarity index 94% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/CronnableSchedule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/CronnableSchedule.java index 12592d1cfea..9210d07cd83 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/CronnableSchedule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/CronnableSchedule.java @@ -3,7 +3,7 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; import java.util.Arrays; import java.util.Objects; diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/DailySchedule.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/DailySchedule.java similarity index 87% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/DailySchedule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/DailySchedule.java index f3fe176f43a..01ac6dcfc2f 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/DailySchedule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/DailySchedule.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.support.DayTimes; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.support.DayTimes; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -92,19 +92,19 @@ public class DailySchedule extends CronnableSchedule { try { times.add(DayTimes.parse(parser, token)); } catch (DayTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [daily] schedule. invalid time value for field [at] - [" + token + "]", pe); + throw new WatcherSettingsException("could not parse [daily] schedule. invalid time value for field [at] - [" + token + "]", pe); } } else { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { try { times.add(DayTimes.parse(parser, token)); } catch (DayTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [daily] schedule. invalid time value for field [at] - [" + token + "]", pe); + throw new WatcherSettingsException("could not parse [daily] schedule. invalid time value for field [at] - [" + token + "]", pe); } } } } else { - throw new AlertsSettingsException("could not parse [daily] schedule. unexpected field [" + currentFieldName + "]"); + throw new WatcherSettingsException("could not parse [daily] schedule. unexpected field [" + currentFieldName + "]"); } } diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/HourlySchedule.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/HourlySchedule.java similarity index 82% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/HourlySchedule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/HourlySchedule.java index 2e579341e66..085342867dd 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/HourlySchedule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/HourlySchedule.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.support.DayTimes; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.support.DayTimes; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.primitives.Ints; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -70,7 +70,7 @@ public class HourlySchedule extends CronnableSchedule { sb.append(","); } if (!validMinute(minutes[i])) { - throw new AlertsSettingsException("invalid hourly minute [" + minutes[i] + "]. minute must be between 0 and 59 incl."); + throw new WatcherSettingsException("invalid hourly minute [" + minutes[i] + "]. minute must be between 0 and 59 incl."); } sb.append(minutes[i]); } @@ -104,21 +104,21 @@ public class HourlySchedule extends CronnableSchedule { try { minutes.add(DayTimes.parseMinuteValue(parser, token)); } catch (DayTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [hourly] schedule. invalid value for [minute]", pe); + throw new WatcherSettingsException("could not parse [hourly] schedule. invalid value for [minute]", pe); } } else if (token == XContentParser.Token.START_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { try { minutes.add(DayTimes.parseMinuteValue(parser, token)); } catch (DayTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [hourly] schedule. invalid value for [minute]", pe); + throw new WatcherSettingsException("could not parse [hourly] schedule. invalid value for [minute]", pe); } } } else { - throw new AlertsSettingsException("could not parse [hourly] schedule. invalid minute value. expected either string/value or an array of string/number values, but found [" + token + "]"); + throw new WatcherSettingsException("could not parse [hourly] schedule. invalid minute value. expected either string/value or an array of string/number values, but found [" + token + "]"); } } else { - throw new AlertsSettingsException("could not parse [hourly] schedule. unexpected field [" + currentFieldName + "]"); + throw new WatcherSettingsException("could not parse [hourly] schedule. unexpected field [" + currentFieldName + "]"); } } diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/IntervalSchedule.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/IntervalSchedule.java similarity index 92% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/IntervalSchedule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/IntervalSchedule.java index b4ad85b2e69..bd97f57b824 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/IntervalSchedule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/IntervalSchedule.java @@ -3,9 +3,9 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -80,7 +80,7 @@ public class IntervalSchedule implements Schedule { String value = parser.text(); return new IntervalSchedule(Interval.parse(value)); } - throw new AlertsSettingsException("could not parse [interval] schedule. expected either a numeric value " + + throw new WatcherSettingsException("could not parse [interval] schedule. expected either a numeric value " + "(millis) or a string value representing time value (e.g. '5s'), but found [" + token + "]"); } } @@ -120,7 +120,7 @@ public class IntervalSchedule implements Schedule { try { return Long.parseLong(num); } catch (NumberFormatException nfe) { - throw new AlertsSettingsException("could not parse [interval] schedule. could not parse [" + throw new WatcherSettingsException("could not parse [interval] schedule. could not parse [" + num + "] as a " + name().toLowerCase(Locale.ROOT) + " duration"); } } @@ -181,7 +181,7 @@ public class IntervalSchedule implements Schedule { return new Interval(unit.parse(value), unit); } } - throw new AlertsSettingsException("could not parse [interval] schedule. unrecognized interval format [" + value + "]"); + throw new WatcherSettingsException("could not parse [interval] schedule. unrecognized interval format [" + value + "]"); } } } diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/MonthlySchedule.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/MonthlySchedule.java similarity index 86% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/MonthlySchedule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/MonthlySchedule.java index 171e012df5c..389d47aa971 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/MonthlySchedule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/MonthlySchedule.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.support.MonthTimes; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.support.MonthTimes; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -79,7 +79,7 @@ public class MonthlySchedule extends CronnableSchedule { try { return new MonthlySchedule(MonthTimes.parse(parser, parser.currentToken())); } catch (MonthTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [monthly] schedule. invalid month times", pe); + throw new WatcherSettingsException("could not parse [monthly] schedule. invalid month times", pe); } } if (parser.currentToken() == XContentParser.Token.START_ARRAY) { @@ -89,12 +89,12 @@ public class MonthlySchedule extends CronnableSchedule { try { times.add(MonthTimes.parse(parser, token)); } catch (MonthTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [monthly] schedule. invalid month times", pe); + throw new WatcherSettingsException("could not parse [monthly] schedule. invalid month times", pe); } } return times.isEmpty() ? new MonthlySchedule() : new MonthlySchedule(times.toArray(new MonthTimes[times.size()])); } - throw new AlertsSettingsException("could not parse [monthly] schedule. expected either an object or an array " + + throw new WatcherSettingsException("could not parse [monthly] schedule. expected either an object or an array " + "of objects representing month times, but found [" + parser.currentToken() + "] instead"); } } diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/Schedule.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/Schedule.java similarity index 91% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/Schedule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/Schedule.java index 58a7b12d41b..7fa21786bd4 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/Schedule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/Schedule.java @@ -3,7 +3,7 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentParser; diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/ScheduleRegistry.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/ScheduleRegistry.java similarity index 76% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/ScheduleRegistry.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/ScheduleRegistry.java index abde920456c..f8dcabadedb 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/ScheduleRegistry.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/ScheduleRegistry.java @@ -3,9 +3,9 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -40,11 +40,11 @@ public class ScheduleRegistry { } else if (type != null) { schedule = parse(type, parser); } else { - throw new AlertsSettingsException("could not parse schedule. expected a schedule type field, but found [" + token + "]"); + throw new WatcherSettingsException("could not parse schedule. expected a schedule type field, but found [" + token + "]"); } } if (schedule == null) { - throw new AlertsSettingsException("could not parse schedule. expected a schedule type field, but no fields were found"); + throw new WatcherSettingsException("could not parse schedule. expected a schedule type field, but no fields were found"); } return schedule; } @@ -52,7 +52,7 @@ public class ScheduleRegistry { public Schedule parse(String type, XContentParser parser) throws IOException { Schedule.Parser scheduleParser = parsers.get(type); if (scheduleParser == null) { - throw new AlertsSettingsException("could not parse schedule. unknown schedule type [" + type + "]"); + throw new WatcherSettingsException("could not parse schedule. unknown schedule type [" + type + "]"); } return scheduleParser.parse(parser); } diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/Schedules.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/Schedules.java similarity index 89% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/Schedules.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/Schedules.java index 78197e7ea6a..a605b90b40a 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/Schedules.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/Schedules.java @@ -3,7 +3,7 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; /** * A static factory for all available schedules. @@ -46,7 +46,7 @@ public class Schedules { * * @param cronExpressions one or more cron expressions * @return the newly created cron schedule. - * @throws org.elasticsearch.alerts.scheduler.schedule.CronSchedule.ValidationException if any of the given expression is invalid + * @throws org.elasticsearch.watcher.scheduler.schedule.CronSchedule.ValidationException if any of the given expression is invalid */ public static CronSchedule cron(String... cronExpressions) { return new CronSchedule(cronExpressions); @@ -58,7 +58,7 @@ public class Schedules { * @param minutes the minutes within the hour that the schedule should trigger at. values must be * between 0 and 59 (inclusive). * @return the newly created hourly schedule - * @throws org.elasticsearch.alerts.AlertsSettingsException if any of the provided minutes are out of valid range + * @throws org.elasticsearch.watcher.WatcherSettingsException if any of the provided minutes are out of valid range */ public static HourlySchedule hourly(int... minutes) { return new HourlySchedule(minutes); diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/WeeklySchedule.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/WeeklySchedule.java similarity index 86% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/WeeklySchedule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/WeeklySchedule.java index 7fc39f9a087..a4990b1dccc 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/WeeklySchedule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/WeeklySchedule.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.support.WeekTimes; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.support.WeekTimes; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -79,7 +79,7 @@ public class WeeklySchedule extends CronnableSchedule { try { return new WeeklySchedule(WeekTimes.parse(parser, parser.currentToken())); } catch (WeekTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [weekly] schedule. invalid weekly times", pe); + throw new WatcherSettingsException("could not parse [weekly] schedule. invalid weekly times", pe); } } if (parser.currentToken() == XContentParser.Token.START_ARRAY) { @@ -89,12 +89,12 @@ public class WeeklySchedule extends CronnableSchedule { try { times.add(WeekTimes.parse(parser, token)); } catch (WeekTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [weekly] schedule. invalid weekly times", pe); + throw new WatcherSettingsException("could not parse [weekly] schedule. invalid weekly times", pe); } } return times.isEmpty() ? new WeeklySchedule() : new WeeklySchedule(times.toArray(new WeekTimes[times.size()])); } - throw new AlertsSettingsException("could not parse [weekly] schedule. expected either an object or an array " + + throw new WatcherSettingsException("could not parse [weekly] schedule. expected either an object or an array " + "of objects representing weekly times, but found [" + parser.currentToken() + "] instead"); } } diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/YearlySchedule.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/YearlySchedule.java similarity index 86% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/YearlySchedule.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/YearlySchedule.java index c38cef16561..98a05d7f906 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/YearlySchedule.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/YearlySchedule.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.support.YearTimes; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.support.YearTimes; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -79,7 +79,7 @@ public class YearlySchedule extends CronnableSchedule { try { return new YearlySchedule(YearTimes.parse(parser, parser.currentToken())); } catch (YearTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [yearly] schedule. invalid year times", pe); + throw new WatcherSettingsException("could not parse [yearly] schedule. invalid year times", pe); } } if (parser.currentToken() == XContentParser.Token.START_ARRAY) { @@ -89,12 +89,12 @@ public class YearlySchedule extends CronnableSchedule { try { times.add(YearTimes.parse(parser, token)); } catch (YearTimes.ParseException pe) { - throw new AlertsSettingsException("could not parse [yearly] schedule. invalid year times", pe); + throw new WatcherSettingsException("could not parse [yearly] schedule. invalid year times", pe); } } return times.isEmpty() ? new YearlySchedule() : new YearlySchedule(times.toArray(new YearTimes[times.size()])); } - throw new AlertsSettingsException("could not parse [yearly] schedule. expected either an object or an array " + + throw new WatcherSettingsException("could not parse [yearly] schedule. expected either an object or an array " + "of objects representing year times, but found [" + parser.currentToken() + "] instead"); } } diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/DayOfWeek.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/DayOfWeek.java similarity index 97% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/DayOfWeek.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/DayOfWeek.java index 4c6575c2038..ef63d232c3b 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/DayOfWeek.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/DayOfWeek.java @@ -3,7 +3,7 @@ * 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.alerts.scheduler.schedule.support; +package org.elasticsearch.watcher.scheduler.schedule.support; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/DayTimes.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/DayTimes.java similarity index 94% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/DayTimes.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/DayTimes.java index 7ecd2cfa459..9a5280c193d 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/DayTimes.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/DayTimes.java @@ -3,11 +3,10 @@ * 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.alerts.scheduler.schedule.support; +package org.elasticsearch.watcher.scheduler.schedule.support; -import org.elasticsearch.alerts.AlertsException; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.common.ParseField; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.primitives.Ints; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -100,12 +99,12 @@ public class DayTimes implements Times { public void validate() { for (int i = 0; i < hour.length; i++) { if (!validHour(hour[i])) { - throw new AlertsSettingsException("invalid time [" + this + "]. invalid time hour value [" + hour[i] + "]. time hours must be between 0 and 23 incl."); + throw new WatcherSettingsException("invalid time [" + this + "]. invalid time hour value [" + hour[i] + "]. time hours must be between 0 and 23 incl."); } } for (int i = 0; i < minute.length; i++) { if (!validMinute(minute[i])) { - throw new AlertsSettingsException("invalid time [" + this + "]. invalid time minute value [" + minute[i] + "]. time minutes must be between 0 and 59 incl."); + throw new WatcherSettingsException("invalid time [" + this + "]. invalid time minute value [" + minute[i] + "]. time minutes must be between 0 and 59 incl."); } } } @@ -275,7 +274,7 @@ public class DayTimes implements Times { } } - public static class ParseException extends AlertsException { + public static class ParseException extends WatcherException { public ParseException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/Month.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/Month.java similarity index 98% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/Month.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/Month.java index 6ed67a7b970..18da8532eac 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/Month.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/Month.java @@ -3,7 +3,7 @@ * 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.alerts.scheduler.schedule.support; +package org.elasticsearch.watcher.scheduler.schedule.support; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/MonthTimes.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/MonthTimes.java similarity index 95% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/MonthTimes.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/MonthTimes.java index 5a491b83434..8926c022725 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/MonthTimes.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/MonthTimes.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler.schedule.support; +package org.elasticsearch.watcher.scheduler.schedule.support; -import org.elasticsearch.alerts.AlertsException; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.base.Joiner; import org.elasticsearch.common.collect.ImmutableSet; import org.elasticsearch.common.primitives.Ints; @@ -47,7 +47,7 @@ public class MonthTimes implements Times { void validate() { for (int day : days) { if (day < 1 || day > 32) { //32 represents the last day of the month - throw new AlertsSettingsException("invalid month day [" + day + "]"); + throw new WatcherSettingsException("invalid month day [" + day + "]"); } } for (DayTimes dayTimes : times) { @@ -177,7 +177,7 @@ public class MonthTimes implements Times { throw new MonthTimes.ParseException("invalid month day value. expected a string or a number value, but found [" + token + "]"); } - public static class ParseException extends AlertsException { + public static class ParseException extends WatcherException { public ParseException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/Times.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/Times.java similarity index 92% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/Times.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/Times.java index 9360a6d41c4..5ebea4e812a 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/Times.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/Times.java @@ -3,7 +3,7 @@ * 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.alerts.scheduler.schedule.support; +package org.elasticsearch.watcher.scheduler.schedule.support; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.xcontent.ToXContent; diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/WeekTimes.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/WeekTimes.java similarity index 97% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/WeekTimes.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/WeekTimes.java index 09cd78f5513..d03248ad64d 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/WeekTimes.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/WeekTimes.java @@ -3,9 +3,9 @@ * 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.alerts.scheduler.schedule.support; +package org.elasticsearch.watcher.scheduler.schedule.support; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; import org.elasticsearch.common.collect.ImmutableSet; import org.elasticsearch.common.primitives.Ints; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -148,7 +148,7 @@ public class WeekTimes implements Times { throw new WeekTimes.ParseException("invalid weekly day value. expected a string or a number value, but found [" + token + "]"); } - public static class ParseException extends AlertsException { + public static class ParseException extends WatcherException { public ParseException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/YearTimes.java b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/YearTimes.java similarity index 96% rename from src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/YearTimes.java rename to src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/YearTimes.java index 9d075738243..7a6a4e85818 100644 --- a/src/main/java/org/elasticsearch/alerts/scheduler/schedule/support/YearTimes.java +++ b/src/main/java/org/elasticsearch/watcher/scheduler/schedule/support/YearTimes.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler.schedule.support; +package org.elasticsearch.watcher.scheduler.schedule.support; -import org.elasticsearch.alerts.AlertsException; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.base.Joiner; import org.elasticsearch.common.collect.ImmutableSet; import org.elasticsearch.common.primitives.Ints; @@ -44,7 +44,7 @@ public class YearTimes implements Times { void validate() { for (int day : days) { if (day < 1 || day > 32) { //32 represents the last day of the month - throw new AlertsSettingsException("invalid month day [" + day + "]"); + throw new WatcherSettingsException("invalid month day [" + day + "]"); } } for (DayTimes dayTimes : times) { @@ -183,7 +183,7 @@ public class YearTimes implements Times { throw new YearTimes.ParseException("invalid year month value. expected a string or a number value, but found [" + token + "]"); } - public static class ParseException extends AlertsException { + public static class ParseException extends WatcherException { public ParseException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/support/Callback.java b/src/main/java/org/elasticsearch/watcher/support/Callback.java similarity index 88% rename from src/main/java/org/elasticsearch/alerts/support/Callback.java rename to src/main/java/org/elasticsearch/watcher/support/Callback.java index 3b9f72d0e6a..42ba2a59447 100644 --- a/src/main/java/org/elasticsearch/alerts/support/Callback.java +++ b/src/main/java/org/elasticsearch/watcher/support/Callback.java @@ -3,7 +3,7 @@ * 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.alerts.support; +package org.elasticsearch.watcher.support; /** */ diff --git a/src/main/java/org/elasticsearch/alerts/support/Script.java b/src/main/java/org/elasticsearch/watcher/support/Script.java similarity index 97% rename from src/main/java/org/elasticsearch/alerts/support/Script.java rename to src/main/java/org/elasticsearch/watcher/support/Script.java index 12c156e3156..ccca0a36b90 100644 --- a/src/main/java/org/elasticsearch/alerts/support/Script.java +++ b/src/main/java/org/elasticsearch/watcher/support/Script.java @@ -3,9 +3,9 @@ * 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.alerts.support; +package org.elasticsearch.watcher.support; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -152,7 +152,7 @@ public class Script implements ToXContent { return new Script(script, type, lang, params); } - public static class ParseException extends AlertsException { + public static class ParseException extends WatcherException { public ParseException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/support/SearchRequestEquivalence.java b/src/main/java/org/elasticsearch/watcher/support/SearchRequestEquivalence.java similarity index 81% rename from src/main/java/org/elasticsearch/alerts/support/SearchRequestEquivalence.java rename to src/main/java/org/elasticsearch/watcher/support/SearchRequestEquivalence.java index cc5efae59f0..6c70ce09c0f 100644 --- a/src/main/java/org/elasticsearch/alerts/support/SearchRequestEquivalence.java +++ b/src/main/java/org/elasticsearch/watcher/support/SearchRequestEquivalence.java @@ -3,15 +3,12 @@ * 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.alerts.support; +package org.elasticsearch.watcher.support; import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.alerts.AlertsException; -import org.elasticsearch.alerts.actions.email.service.Attachment; +import org.elasticsearch.watcher.WatcherException; import org.elasticsearch.common.base.Equivalence; -import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamOutput; -import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; import java.util.Arrays; @@ -42,7 +39,7 @@ public final class SearchRequestEquivalence extends Equivalence { byte[] bytes2 = output1.bytes().toBytes(); return Arrays.equals(bytes1, bytes2); } catch (Throwable t) { - throw new AlertsException("could not compare search requests", t); + throw new WatcherException("could not compare search requests", t); } } @@ -53,7 +50,7 @@ public final class SearchRequestEquivalence extends Equivalence { request.writeTo(output); return Arrays.hashCode(output.bytes().toBytes()); } catch (IOException ioe) { - throw new AlertsException("could not compute hashcode for search request", ioe); + throw new WatcherException("could not compute hashcode for search request", ioe); } } } diff --git a/src/main/java/org/elasticsearch/alerts/support/TemplateUtils.java b/src/main/java/org/elasticsearch/watcher/support/TemplateUtils.java similarity index 88% rename from src/main/java/org/elasticsearch/alerts/support/TemplateUtils.java rename to src/main/java/org/elasticsearch/watcher/support/TemplateUtils.java index 62367ddc4c6..6f1b80af057 100644 --- a/src/main/java/org/elasticsearch/alerts/support/TemplateUtils.java +++ b/src/main/java/org/elasticsearch/watcher/support/TemplateUtils.java @@ -3,13 +3,14 @@ * 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.alerts.support; +package org.elasticsearch.watcher.support; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest; import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateResponse; import org.elasticsearch.action.admin.indices.template.put.TransportPutIndexTemplateAction; -import org.elasticsearch.alerts.AlertsStore; +import org.elasticsearch.common.base.Charsets; +import org.elasticsearch.watcher.watch.WatchStore; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; import org.elasticsearch.common.component.AbstractComponent; @@ -28,6 +29,8 @@ import java.util.regex.Pattern; */ public class TemplateUtils extends AbstractComponent { + private final static Pattern TEMPLATE_VERSION_PATTERN = Pattern.compile("watcher.template_version\"\\s*:\\s*\"?(\\d+)\"?"); + private final TransportPutIndexTemplateAction transportPutIndexTemplateAction; @Inject @@ -45,7 +48,7 @@ public class TemplateUtils extends AbstractComponent { public void ensureIndexTemplateIsLoaded(ClusterState state, final String templateName) { final byte[] template; try { - InputStream is = AlertsStore.class.getResourceAsStream("/" + templateName + ".json"); + InputStream is = WatchStore.class.getResourceAsStream("/" + templateName + ".json"); if (is == null) { throw new FileNotFoundException("Resource [/" + templateName + ".json] not found in classpath"); } @@ -65,7 +68,7 @@ public class TemplateUtils extends AbstractComponent { IndexTemplateMetaData templateMetaData = state.metaData().templates().get(templateName); if (templateMetaData != null) { - int foundVersion = templateMetaData.getSettings().getAsInt("index.alerts.template_version", -1); + int foundVersion = templateMetaData.getSettings().getAsInt("index.watches.template_version", -1); if (foundVersion < 0) { logger.warn("found an existing index template [{}] but couldn't extract it's version. leaving it as is.", templateName); return; @@ -90,13 +93,11 @@ public class TemplateUtils extends AbstractComponent { } private static int parseIndexVersionFromTemplate(byte[] template) throws UnsupportedEncodingException { - Pattern versionRegex = Pattern.compile("alerts.template_version\"\\s*:\\s*\"?(\\d+)\"?"); - Matcher matcher = versionRegex.matcher(new String(template, "UTF-8")); - if (matcher.find()) { - return Integer.parseInt(matcher.group(1)); - } else { + Matcher matcher = TEMPLATE_VERSION_PATTERN.matcher(new String(template, Charsets.UTF_8)); + if (!matcher.find()) { return -1; } + return Integer.parseInt(matcher.group(1)); } } diff --git a/src/main/java/org/elasticsearch/alerts/support/Variables.java b/src/main/java/org/elasticsearch/watcher/support/Variables.java similarity index 67% rename from src/main/java/org/elasticsearch/alerts/support/Variables.java rename to src/main/java/org/elasticsearch/watcher/support/Variables.java index 60418f64ac9..0f0e6dfe7b3 100644 --- a/src/main/java/org/elasticsearch/alerts/support/Variables.java +++ b/src/main/java/org/elasticsearch/watcher/support/Variables.java @@ -3,10 +3,10 @@ * 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.alerts.support; +package org.elasticsearch.watcher.support; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; import org.elasticsearch.common.joda.time.DateTime; import java.util.HashMap; @@ -18,19 +18,19 @@ import java.util.Map; public final class Variables { public static final String CTX = "ctx"; - public static final String ALERT_NAME = "alert_name"; + public static final String WATCH_NAME = "watch_name"; public static final String EXECUTION_TIME = "execution_time"; 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.executionTime(), ctx.fireTime(), ctx.scheduledTime(), payload); + public static Map createCtxModel(WatchExecutionContext ctx, Payload payload) { + return createCtxModel(ctx.watch().name(), ctx.executionTime(), ctx.fireTime(), ctx.scheduledTime(), payload); } - public static Map createCtxModel(String alertName, DateTime executionTime, DateTime fireTime, DateTime scheduledTime, Payload payload) { + public static Map createCtxModel(String watchName, DateTime executionTime, DateTime fireTime, DateTime scheduledTime, Payload payload) { Map vars = new HashMap<>(); - vars.put(ALERT_NAME, alertName); + vars.put(WATCH_NAME, watchName); vars.put(EXECUTION_TIME, executionTime); vars.put(FIRE_TIME, fireTime); vars.put(SCHEDULED_FIRE_TIME, scheduledTime); diff --git a/src/main/java/org/elasticsearch/alerts/support/AlertsDateUtils.java b/src/main/java/org/elasticsearch/watcher/support/WatcherDateUtils.java similarity index 89% rename from src/main/java/org/elasticsearch/alerts/support/AlertsDateUtils.java rename to src/main/java/org/elasticsearch/watcher/support/WatcherDateUtils.java index fbda3480413..a3a65498048 100644 --- a/src/main/java/org/elasticsearch/alerts/support/AlertsDateUtils.java +++ b/src/main/java/org/elasticsearch/watcher/support/WatcherDateUtils.java @@ -3,9 +3,9 @@ * 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.alerts.support; +package org.elasticsearch.watcher.support; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.joda.FormatDateTimeFormatter; @@ -18,11 +18,11 @@ import java.io.IOException; /** * */ -public class AlertsDateUtils { +public class WatcherDateUtils { public static final FormatDateTimeFormatter dateTimeFormatter = DateFieldMapper.Defaults.DATE_TIME_FORMATTER; - private AlertsDateUtils() { + private WatcherDateUtils() { } public static DateTime parseDate(String format) { @@ -43,7 +43,7 @@ public class AlertsDateUtils { if (token == XContentParser.Token.VALUE_NULL) { return null; } - throw new AlertsSettingsException("could not parse date/time. expected [" + fieldName + + throw new WatcherSettingsException("could not parse date/time. expected [" + fieldName + "] to be either a number or a string but was [" + token + "] instead"); } diff --git a/src/main/java/org/elasticsearch/alerts/support/AlertUtils.java b/src/main/java/org/elasticsearch/watcher/support/WatcherUtils.java similarity index 95% rename from src/main/java/org/elasticsearch/alerts/support/AlertUtils.java rename to src/main/java/org/elasticsearch/watcher/support/WatcherUtils.java index 65e7fe6df84..67d7646d3c8 100644 --- a/src/main/java/org/elasticsearch/alerts/support/AlertUtils.java +++ b/src/main/java/org/elasticsearch/watcher/support/WatcherUtils.java @@ -3,14 +3,14 @@ * 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.alerts.support; +package org.elasticsearch.watcher.support; import org.elasticsearch.ElasticsearchIllegalArgumentException; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.alerts.AlertsException; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.unit.TimeValue; @@ -24,16 +24,16 @@ import java.io.IOException; import java.lang.reflect.Array; import java.util.*; -import static org.elasticsearch.alerts.support.AlertsDateUtils.formatDate; +import static org.elasticsearch.watcher.support.WatcherDateUtils.formatDate; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** */ -public final class AlertUtils { +public final class WatcherUtils { public final static IndicesOptions DEFAULT_INDICES_OPTIONS = IndicesOptions.lenientExpandOpen(); - private AlertUtils() { + private WatcherUtils() { } public static Map responseToData(ToXContent response) { @@ -41,7 +41,7 @@ public final class AlertUtils { XContentBuilder builder = jsonBuilder().startObject().value(response).endObject(); return XContentHelper.convertToMap(builder.bytes(), false).v2(); } catch (IOException ioe) { - throw new AlertsException("failed to convert search response to script parameters", ioe); + throw new WatcherException("failed to convert search response to script parameters", ioe); } } @@ -142,7 +142,7 @@ public final class AlertUtils { try { searchRequest.templateType(ScriptService.ScriptType.valueOf(parser.text().toUpperCase(Locale.ROOT))); } catch (IllegalArgumentException iae) { - throw new AlertsSettingsException("could not parse search request. unknown template type [" + parser.text() + "]"); + throw new WatcherSettingsException("could not parse search request. unknown template type [" + parser.text() + "]"); } } } else if (token == XContentParser.Token.START_OBJECT) { diff --git a/src/main/java/org/elasticsearch/alerts/support/clock/Clock.java b/src/main/java/org/elasticsearch/watcher/support/clock/Clock.java similarity index 90% rename from src/main/java/org/elasticsearch/alerts/support/clock/Clock.java rename to src/main/java/org/elasticsearch/watcher/support/clock/Clock.java index ff47001ca91..cda73da913e 100644 --- a/src/main/java/org/elasticsearch/alerts/support/clock/Clock.java +++ b/src/main/java/org/elasticsearch/watcher/support/clock/Clock.java @@ -3,7 +3,7 @@ * 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.alerts.support.clock; +package org.elasticsearch.watcher.support.clock; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.unit.TimeValue; diff --git a/src/main/java/org/elasticsearch/alerts/support/clock/ClockModule.java b/src/main/java/org/elasticsearch/watcher/support/clock/ClockModule.java similarity index 90% rename from src/main/java/org/elasticsearch/alerts/support/clock/ClockModule.java rename to src/main/java/org/elasticsearch/watcher/support/clock/ClockModule.java index 03e35235113..9d529a61e11 100644 --- a/src/main/java/org/elasticsearch/alerts/support/clock/ClockModule.java +++ b/src/main/java/org/elasticsearch/watcher/support/clock/ClockModule.java @@ -3,7 +3,7 @@ * 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.alerts.support.clock; +package org.elasticsearch.watcher.support.clock; import org.elasticsearch.common.inject.AbstractModule; diff --git a/src/main/java/org/elasticsearch/alerts/support/clock/SystemClock.java b/src/main/java/org/elasticsearch/watcher/support/clock/SystemClock.java similarity index 94% rename from src/main/java/org/elasticsearch/alerts/support/clock/SystemClock.java rename to src/main/java/org/elasticsearch/watcher/support/clock/SystemClock.java index 60e5e7bf5f1..2b159ce334f 100644 --- a/src/main/java/org/elasticsearch/alerts/support/clock/SystemClock.java +++ b/src/main/java/org/elasticsearch/watcher/support/clock/SystemClock.java @@ -3,7 +3,7 @@ * 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.alerts.support.clock; +package org.elasticsearch.watcher.support.clock; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.unit.TimeValue; diff --git a/src/main/java/org/elasticsearch/alerts/support/init/InitializingModule.java b/src/main/java/org/elasticsearch/watcher/support/init/InitializingModule.java similarity index 80% rename from src/main/java/org/elasticsearch/alerts/support/init/InitializingModule.java rename to src/main/java/org/elasticsearch/watcher/support/init/InitializingModule.java index f956918425f..d16f2dc2eaa 100644 --- a/src/main/java/org/elasticsearch/alerts/support/init/InitializingModule.java +++ b/src/main/java/org/elasticsearch/watcher/support/init/InitializingModule.java @@ -3,11 +3,11 @@ * 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.alerts.support.init; +package org.elasticsearch.watcher.support.init; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; -import org.elasticsearch.alerts.transform.ChainTransform; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.transform.ChainTransform; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.multibindings.Multibinder; diff --git a/src/main/java/org/elasticsearch/alerts/support/init/InitializingService.java b/src/main/java/org/elasticsearch/watcher/support/init/InitializingService.java similarity index 96% rename from src/main/java/org/elasticsearch/alerts/support/init/InitializingService.java rename to src/main/java/org/elasticsearch/watcher/support/init/InitializingService.java index fa8ea1a955c..f4a298c2d52 100644 --- a/src/main/java/org/elasticsearch/alerts/support/init/InitializingService.java +++ b/src/main/java/org/elasticsearch/watcher/support/init/InitializingService.java @@ -3,7 +3,7 @@ * 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.alerts.support.init; +package org.elasticsearch.watcher.support.init; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.component.AbstractLifecycleComponent; diff --git a/src/main/java/org/elasticsearch/alerts/support/init/proxy/ClientProxy.java b/src/main/java/org/elasticsearch/watcher/support/init/proxy/ClientProxy.java similarity index 96% rename from src/main/java/org/elasticsearch/alerts/support/init/proxy/ClientProxy.java rename to src/main/java/org/elasticsearch/watcher/support/init/proxy/ClientProxy.java index 137267ade46..5ee6d384f39 100644 --- a/src/main/java/org/elasticsearch/alerts/support/init/proxy/ClientProxy.java +++ b/src/main/java/org/elasticsearch/watcher/support/init/proxy/ClientProxy.java @@ -3,7 +3,7 @@ * 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.alerts.support.init.proxy; +package org.elasticsearch.watcher.support.init.proxy; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.ActionListener; @@ -16,7 +16,7 @@ import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.*; -import org.elasticsearch.alerts.support.init.InitializingService; +import org.elasticsearch.watcher.support.init.InitializingService; import org.elasticsearch.client.AdminClient; import org.elasticsearch.client.Client; import org.elasticsearch.common.inject.Injector; diff --git a/src/main/java/org/elasticsearch/alerts/support/init/proxy/ScriptServiceProxy.java b/src/main/java/org/elasticsearch/watcher/support/init/proxy/ScriptServiceProxy.java similarity index 93% rename from src/main/java/org/elasticsearch/alerts/support/init/proxy/ScriptServiceProxy.java rename to src/main/java/org/elasticsearch/watcher/support/init/proxy/ScriptServiceProxy.java index 3f9b2935d7b..da4fab826e7 100644 --- a/src/main/java/org/elasticsearch/alerts/support/init/proxy/ScriptServiceProxy.java +++ b/src/main/java/org/elasticsearch/watcher/support/init/proxy/ScriptServiceProxy.java @@ -3,9 +3,9 @@ * 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.alerts.support.init.proxy; +package org.elasticsearch.watcher.support.init.proxy; -import org.elasticsearch.alerts.support.init.InitializingService; +import org.elasticsearch.watcher.support.init.InitializingService; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.script.CompiledScript; import org.elasticsearch.script.ExecutableScript; diff --git a/src/main/java/org/elasticsearch/alerts/support/template/ScriptTemplate.java b/src/main/java/org/elasticsearch/watcher/support/template/ScriptTemplate.java similarity index 95% rename from src/main/java/org/elasticsearch/alerts/support/template/ScriptTemplate.java rename to src/main/java/org/elasticsearch/watcher/support/template/ScriptTemplate.java index e99d4469d55..e9b476832d2 100644 --- a/src/main/java/org/elasticsearch/alerts/support/template/ScriptTemplate.java +++ b/src/main/java/org/elasticsearch/watcher/support/template/ScriptTemplate.java @@ -3,10 +3,10 @@ * 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.alerts.support.template; +package org.elasticsearch.watcher.support.template; -import org.elasticsearch.alerts.support.Script; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; diff --git a/src/main/java/org/elasticsearch/alerts/support/template/Template.java b/src/main/java/org/elasticsearch/watcher/support/template/Template.java similarity index 83% rename from src/main/java/org/elasticsearch/alerts/support/template/Template.java rename to src/main/java/org/elasticsearch/watcher/support/template/Template.java index 8acb47a40b6..5d61a97afc6 100644 --- a/src/main/java/org/elasticsearch/alerts/support/template/Template.java +++ b/src/main/java/org/elasticsearch/watcher/support/template/Template.java @@ -3,9 +3,9 @@ * 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.alerts.support.template; +package org.elasticsearch.watcher.support.template; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentParser; @@ -23,7 +23,7 @@ public interface Template extends ToXContent { T parse(XContentParser parser) throws IOException, ParseException; - public static class ParseException extends AlertsException { + public static class ParseException extends WatcherException { public ParseException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/support/template/TemplateException.java b/src/main/java/org/elasticsearch/watcher/support/template/TemplateException.java similarity index 72% rename from src/main/java/org/elasticsearch/alerts/support/template/TemplateException.java rename to src/main/java/org/elasticsearch/watcher/support/template/TemplateException.java index 803ca634a6b..38d5a5aca14 100644 --- a/src/main/java/org/elasticsearch/alerts/support/template/TemplateException.java +++ b/src/main/java/org/elasticsearch/watcher/support/template/TemplateException.java @@ -3,14 +3,14 @@ * 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.alerts.support.template; +package org.elasticsearch.watcher.support.template; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; /** * */ -public class TemplateException extends AlertsException { +public class TemplateException extends WatcherException { public TemplateException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/support/template/TemplateModule.java b/src/main/java/org/elasticsearch/watcher/support/template/TemplateModule.java similarity index 90% rename from src/main/java/org/elasticsearch/alerts/support/template/TemplateModule.java rename to src/main/java/org/elasticsearch/watcher/support/template/TemplateModule.java index 0e906f30127..a89b6b5e58b 100644 --- a/src/main/java/org/elasticsearch/alerts/support/template/TemplateModule.java +++ b/src/main/java/org/elasticsearch/watcher/support/template/TemplateModule.java @@ -3,7 +3,7 @@ * 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.alerts.support.template; +package org.elasticsearch.watcher.support.template; import org.elasticsearch.common.inject.AbstractModule; diff --git a/src/main/java/org/elasticsearch/alerts/support/template/XContentTemplate.java b/src/main/java/org/elasticsearch/watcher/support/template/XContentTemplate.java similarity index 96% rename from src/main/java/org/elasticsearch/alerts/support/template/XContentTemplate.java rename to src/main/java/org/elasticsearch/watcher/support/template/XContentTemplate.java index d7e438832f6..c061cd6ca40 100644 --- a/src/main/java/org/elasticsearch/alerts/support/template/XContentTemplate.java +++ b/src/main/java/org/elasticsearch/watcher/support/template/XContentTemplate.java @@ -3,7 +3,7 @@ * 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.alerts.support.template; +package org.elasticsearch.watcher.support.template; import org.elasticsearch.common.xcontent.XContent; import org.elasticsearch.common.xcontent.XContentBuilder; diff --git a/src/main/java/org/elasticsearch/watcher/throttle/AckThrottler.java b/src/main/java/org/elasticsearch/watcher/throttle/AckThrottler.java new file mode 100644 index 00000000000..dd395fc1d9f --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/throttle/AckThrottler.java @@ -0,0 +1,24 @@ +/* + * 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.watcher.throttle; + +import org.elasticsearch.watcher.watch.WatchExecutionContext; + +import static org.elasticsearch.watcher.support.WatcherDateUtils.formatDate; + +/** + * + */ +public class AckThrottler implements Throttler { + + @Override + public Result throttle(WatchExecutionContext ctx) { + if (ctx.watch().acked()) { + return Result.throttle("watch [" + ctx.watch().name() + "] was acked at [" + formatDate(ctx.watch().status().ackStatus().timestamp()) + "]"); + } + return Result.NO; + } +} diff --git a/src/main/java/org/elasticsearch/alerts/throttle/PeriodThrottler.java b/src/main/java/org/elasticsearch/watcher/throttle/PeriodThrottler.java similarity index 81% rename from src/main/java/org/elasticsearch/alerts/throttle/PeriodThrottler.java rename to src/main/java/org/elasticsearch/watcher/throttle/PeriodThrottler.java index fbfdbe96e24..a7071815cbb 100644 --- a/src/main/java/org/elasticsearch/alerts/throttle/PeriodThrottler.java +++ b/src/main/java/org/elasticsearch/watcher/throttle/PeriodThrottler.java @@ -3,11 +3,11 @@ * 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.alerts.throttle; +package org.elasticsearch.watcher.throttle; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.support.clock.Clock; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.support.clock.Clock; import org.elasticsearch.common.joda.time.PeriodType; import org.elasticsearch.common.unit.TimeValue; @@ -35,8 +35,8 @@ public class PeriodThrottler implements Throttler { } @Override - public Result throttle(ExecutionContext ctx) { - Alert.Status status = ctx.alert().status(); + public Result throttle(WatchExecutionContext ctx) { + Watch.Status status = ctx.watch().status(); if (status.lastExecuted() != null) { TimeValue timeElapsed = clock.timeElapsedSince(status.lastExecuted()); if (timeElapsed.getMillis() <= period.getMillis()) { diff --git a/src/main/java/org/elasticsearch/alerts/throttle/Throttler.java b/src/main/java/org/elasticsearch/watcher/throttle/Throttler.java similarity index 82% rename from src/main/java/org/elasticsearch/alerts/throttle/Throttler.java rename to src/main/java/org/elasticsearch/watcher/throttle/Throttler.java index e9012be733f..39d5ed36638 100644 --- a/src/main/java/org/elasticsearch/alerts/throttle/Throttler.java +++ b/src/main/java/org/elasticsearch/watcher/throttle/Throttler.java @@ -3,9 +3,9 @@ * 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.alerts.throttle; +package org.elasticsearch.watcher.throttle; -import org.elasticsearch.alerts.ExecutionContext; +import org.elasticsearch.watcher.watch.WatchExecutionContext; /** * @@ -14,12 +14,12 @@ public interface Throttler { public static final Throttler NO_THROTTLE = new Throttler() { @Override - public Result throttle(ExecutionContext ctx) { + public Result throttle(WatchExecutionContext ctx) { return Result.NO; } }; - Result throttle(ExecutionContext ctx); + Result throttle(WatchExecutionContext ctx); static class Result { diff --git a/src/main/java/org/elasticsearch/alerts/throttle/AlertThrottler.java b/src/main/java/org/elasticsearch/watcher/throttle/WatchThrottler.java similarity index 72% rename from src/main/java/org/elasticsearch/alerts/throttle/AlertThrottler.java rename to src/main/java/org/elasticsearch/watcher/throttle/WatchThrottler.java index b6d243c757a..f4e3bb1d0be 100644 --- a/src/main/java/org/elasticsearch/alerts/throttle/AlertThrottler.java +++ b/src/main/java/org/elasticsearch/watcher/throttle/WatchThrottler.java @@ -3,34 +3,34 @@ * 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.alerts.throttle; +package org.elasticsearch.watcher.throttle; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.support.clock.Clock; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.support.clock.Clock; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.unit.TimeValue; /** * */ -public class AlertThrottler implements Throttler { +public class WatchThrottler implements Throttler { private static final AckThrottler ACK_THROTTLER = new AckThrottler(); private final PeriodThrottler periodThrottler; private final AckThrottler ackThrottler; - public AlertThrottler(Clock clock, @Nullable TimeValue throttlePeriod) { + public WatchThrottler(Clock clock, @Nullable TimeValue throttlePeriod) { this(throttlePeriod != null ? new PeriodThrottler(clock, throttlePeriod) : null, ACK_THROTTLER); } - AlertThrottler(PeriodThrottler periodThrottler, AckThrottler ackThrottler) { + WatchThrottler(PeriodThrottler periodThrottler, AckThrottler ackThrottler) { this.periodThrottler = periodThrottler; this.ackThrottler = ackThrottler; } @Override - public Result throttle(ExecutionContext ctx) { + public Result throttle(WatchExecutionContext ctx) { if (periodThrottler != null) { Result throttleResult = periodThrottler.throttle(ctx); if (throttleResult.throttle()) { diff --git a/src/main/java/org/elasticsearch/alerts/transform/ChainTransform.java b/src/main/java/org/elasticsearch/watcher/transform/ChainTransform.java similarity index 90% rename from src/main/java/org/elasticsearch/alerts/transform/ChainTransform.java rename to src/main/java/org/elasticsearch/watcher/transform/ChainTransform.java index 9831816b90d..dce27c2852f 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/ChainTransform.java +++ b/src/main/java/org/elasticsearch/watcher/transform/ChainTransform.java @@ -3,12 +3,12 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.support.init.InitializingService; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.support.init.InitializingService; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.inject.Injector; @@ -41,7 +41,7 @@ public class ChainTransform extends Transform { } @Override - public Result apply(ExecutionContext ctx, Payload payload) throws IOException { + public Result apply(WatchExecutionContext ctx, Payload payload) throws IOException { ImmutableList.Builder results = ImmutableList.builder(); for (Transform transform : transforms) { Transform.Result result = transform.apply(ctx, payload); @@ -133,7 +133,7 @@ public class ChainTransform extends Transform { public ChainTransform parse(XContentParser parser) throws IOException { XContentParser.Token token = parser.currentToken(); if (token != XContentParser.Token.START_ARRAY) { - throw new AlertsSettingsException("could not parse [chain] transform. expected an array of objects, but found [" + token + '}'); + throw new WatcherSettingsException("could not parse [chain] transform. expected an array of objects, but found [" + token + '}'); } ImmutableList.Builder builder = ImmutableList.builder(); @@ -141,7 +141,7 @@ public class ChainTransform extends Transform { String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token != XContentParser.Token.START_OBJECT) { - throw new AlertsSettingsException("could not parse [chain] transform. expected a transform object, but found [" + token + "]"); + throw new WatcherSettingsException("could not parse [chain] transform. expected a transform object, but found [" + token + "]"); } while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { @@ -149,7 +149,7 @@ public class ChainTransform extends Transform { } else if (token == XContentParser.Token.START_OBJECT) { builder.add(registry.parse(currentFieldName, parser)); } else { - throw new AlertsSettingsException("could not parse [chain] transform. expected a transform object, but found [" + token + "]"); + throw new WatcherSettingsException("could not parse [chain] transform. expected a transform object, but found [" + token + "]"); } } } diff --git a/src/main/java/org/elasticsearch/alerts/transform/ScriptTransform.java b/src/main/java/org/elasticsearch/watcher/transform/ScriptTransform.java similarity index 89% rename from src/main/java/org/elasticsearch/alerts/transform/ScriptTransform.java rename to src/main/java/org/elasticsearch/watcher/transform/ScriptTransform.java index b983d000d89..95c8e5d7182 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/ScriptTransform.java +++ b/src/main/java/org/elasticsearch/watcher/transform/ScriptTransform.java @@ -3,13 +3,13 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.support.Script; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -19,7 +19,7 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -import static org.elasticsearch.alerts.support.Variables.createCtxModel; +import static org.elasticsearch.watcher.support.Variables.createCtxModel; /** * @@ -46,7 +46,7 @@ public class ScriptTransform extends Transform { } @Override - public Result apply(ExecutionContext ctx, Payload payload) throws IOException { + public Result apply(WatchExecutionContext ctx, Payload payload) throws IOException { Map model = new HashMap<>(); model.putAll(script.params()); model.putAll(createCtxModel(ctx, payload)); @@ -112,7 +112,7 @@ public class ScriptTransform extends Transform { try { script = Script.parse(parser); } catch (Script.ParseException pe) { - throw new AlertsSettingsException("could not parse [script] transform", pe); + throw new WatcherSettingsException("could not parse [script] transform", pe); } return new ScriptTransform(scriptService, script); } diff --git a/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java b/src/main/java/org/elasticsearch/watcher/transform/SearchTransform.java similarity index 86% rename from src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java rename to src/main/java/org/elasticsearch/watcher/transform/SearchTransform.java index 980bd71c4b3..c17b1968a43 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/SearchTransform.java +++ b/src/main/java/org/elasticsearch/watcher/transform/SearchTransform.java @@ -3,17 +3,17 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.support.AlertUtils; -import org.elasticsearch.alerts.support.SearchRequestEquivalence; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.support.WatcherUtils; +import org.elasticsearch.watcher.support.SearchRequestEquivalence; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.MapBuilder; @@ -30,8 +30,8 @@ import org.elasticsearch.script.ScriptService; import java.io.IOException; -import static org.elasticsearch.alerts.support.AlertUtils.flattenModel; -import static org.elasticsearch.alerts.support.Variables.createCtxModel; +import static org.elasticsearch.watcher.support.WatcherUtils.flattenModel; +import static org.elasticsearch.watcher.support.Variables.createCtxModel; /** * @@ -61,7 +61,7 @@ public class SearchTransform extends Transform { } @Override - public Result apply(ExecutionContext ctx, Payload payload) throws IOException { + public Result apply(WatchExecutionContext ctx, Payload payload) throws IOException { SearchRequest req = createRequest(request, ctx, payload); SearchResponse resp = client.search(req); return new Result(TYPE, new Payload.XContent(resp)); @@ -69,7 +69,7 @@ public class SearchTransform extends Transform { @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { - return AlertUtils.writeSearchRequest(request, builder, params); + return WatcherUtils.writeSearchRequest(request, builder, params); } @Override @@ -89,7 +89,7 @@ public class SearchTransform extends Transform { return request.hashCode(); } - SearchRequest createRequest(SearchRequest requestPrototype, ExecutionContext ctx, Payload payload) throws IOException { + SearchRequest createRequest(SearchRequest requestPrototype, WatchExecutionContext ctx, Payload payload) throws IOException { SearchRequest request = new SearchRequest(requestPrototype) .indicesOptions(requestPrototype.indicesOptions()) .indices(requestPrototype.indices()); @@ -140,7 +140,7 @@ public class SearchTransform extends Transform { @Override public SearchTransform parse(XContentParser parser) throws IOException { - SearchRequest request = AlertUtils.readSearchRequest(parser, DEFAULT_SEARCH_TYPE); + SearchRequest request = WatcherUtils.readSearchRequest(parser, DEFAULT_SEARCH_TYPE); return new SearchTransform(logger, scriptService, client, request); } @@ -177,7 +177,7 @@ public class SearchTransform extends Transform { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - return AlertUtils.writeSearchRequest(request, builder, params); + return WatcherUtils.writeSearchRequest(request, builder, params); } } diff --git a/src/main/java/org/elasticsearch/alerts/transform/Transform.java b/src/main/java/org/elasticsearch/watcher/transform/Transform.java similarity index 89% rename from src/main/java/org/elasticsearch/alerts/transform/Transform.java rename to src/main/java/org/elasticsearch/watcher/transform/Transform.java index 7ec06cd7e09..e383cf29c22 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/Transform.java +++ b/src/main/java/org/elasticsearch/watcher/transform/Transform.java @@ -3,10 +3,10 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -21,7 +21,7 @@ public abstract class Transform implements ToXConten public abstract String type(); - public abstract Result apply(ExecutionContext ctx, Payload payload) throws IOException; + public abstract Result apply(WatchExecutionContext ctx, Payload payload) throws IOException; public static abstract class Result implements ToXContent { diff --git a/src/main/java/org/elasticsearch/alerts/transform/TransformBuilders.java b/src/main/java/org/elasticsearch/watcher/transform/TransformBuilders.java similarity index 75% rename from src/main/java/org/elasticsearch/alerts/transform/TransformBuilders.java rename to src/main/java/org/elasticsearch/watcher/transform/TransformBuilders.java index a688b0bb446..0b3a56b3d96 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/TransformBuilders.java +++ b/src/main/java/org/elasticsearch/watcher/transform/TransformBuilders.java @@ -3,14 +3,10 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.alerts.support.Script; -import org.elasticsearch.alerts.transform.ChainTransform; -import org.elasticsearch.alerts.transform.ScriptTransform; -import org.elasticsearch.alerts.transform.SearchTransform; -import org.elasticsearch.alerts.transform.Transform; +import org.elasticsearch.watcher.support.Script; /** * diff --git a/src/main/java/org/elasticsearch/alerts/transform/TransformException.java b/src/main/java/org/elasticsearch/watcher/transform/TransformException.java similarity index 73% rename from src/main/java/org/elasticsearch/alerts/transform/TransformException.java rename to src/main/java/org/elasticsearch/watcher/transform/TransformException.java index 3cbd50c218b..ffe16e24750 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/TransformException.java +++ b/src/main/java/org/elasticsearch/watcher/transform/TransformException.java @@ -3,14 +3,14 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; -import org.elasticsearch.alerts.AlertsException; +import org.elasticsearch.watcher.WatcherException; /** * */ -public class TransformException extends AlertsException { +public class TransformException extends WatcherException { public TransformException(String msg) { super(msg); diff --git a/src/main/java/org/elasticsearch/alerts/transform/TransformModule.java b/src/main/java/org/elasticsearch/watcher/transform/TransformModule.java similarity index 96% rename from src/main/java/org/elasticsearch/alerts/transform/TransformModule.java rename to src/main/java/org/elasticsearch/watcher/transform/TransformModule.java index e51d2b86d48..8a24c2a4b6e 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/TransformModule.java +++ b/src/main/java/org/elasticsearch/watcher/transform/TransformModule.java @@ -3,7 +3,7 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.multibindings.MapBinder; diff --git a/src/main/java/org/elasticsearch/alerts/transform/TransformRegistry.java b/src/main/java/org/elasticsearch/watcher/transform/TransformRegistry.java similarity index 92% rename from src/main/java/org/elasticsearch/alerts/transform/TransformRegistry.java rename to src/main/java/org/elasticsearch/watcher/transform/TransformRegistry.java index 2b55d56f007..4f61a46ea13 100644 --- a/src/main/java/org/elasticsearch/alerts/transform/TransformRegistry.java +++ b/src/main/java/org/elasticsearch/watcher/transform/TransformRegistry.java @@ -3,9 +3,9 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -42,7 +42,7 @@ public class TransformRegistry { public Transform parse(String type, XContentParser parser) throws IOException { Transform.Parser transformParser = parsers.get(type); if (transformParser == null) { - throw new AlertsSettingsException("unknown transform type [" + type + "]"); + throw new WatcherSettingsException("unknown transform type [" + type + "]"); } return transformParser.parse(parser); } diff --git a/src/main/java/org/elasticsearch/watcher/transport/WatcherTransportModule.java b/src/main/java/org/elasticsearch/watcher/transport/WatcherTransportModule.java new file mode 100644 index 00000000000..7cee18647e2 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/WatcherTransportModule.java @@ -0,0 +1,47 @@ +/* + * 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.watcher.transport; + +import org.elasticsearch.action.ActionModule; +import org.elasticsearch.watcher.transport.actions.ack.AckWatchAction; +import org.elasticsearch.watcher.transport.actions.ack.TransportAckWatchAction; +import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchAction; +import org.elasticsearch.watcher.transport.actions.delete.TransportDeleteWatchAction; +import org.elasticsearch.watcher.transport.actions.get.GetWatchAction; +import org.elasticsearch.watcher.transport.actions.get.TransportGetWatchAction; +import org.elasticsearch.watcher.transport.actions.put.PutWatchAction; +import org.elasticsearch.watcher.transport.actions.put.TransportPutWatchAction; +import org.elasticsearch.watcher.transport.actions.service.WatcherServiceAction; +import org.elasticsearch.watcher.transport.actions.service.TransportWatcherServiceAction; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsAction; +import org.elasticsearch.watcher.transport.actions.stats.TransportWatcherStatsAction; +import org.elasticsearch.common.inject.AbstractModule; +import org.elasticsearch.common.inject.Module; +import org.elasticsearch.common.inject.PreProcessModule; + +/** + * + */ +public class WatcherTransportModule extends AbstractModule implements PreProcessModule { + + @Override + public void processModule(Module module) { + if (module instanceof ActionModule) { + ActionModule actionModule = (ActionModule) module; + actionModule.registerAction(PutWatchAction.INSTANCE, TransportPutWatchAction.class); + actionModule.registerAction(DeleteWatchAction.INSTANCE, TransportDeleteWatchAction.class); + actionModule.registerAction(GetWatchAction.INSTANCE, TransportGetWatchAction.class); + actionModule.registerAction(WatcherStatsAction.INSTANCE, TransportWatcherStatsAction.class); + actionModule.registerAction(AckWatchAction.INSTANCE, TransportAckWatchAction.class); + actionModule.registerAction(WatcherServiceAction.INSTANCE, TransportWatcherServiceAction.class); + } + } + + @Override + protected void configure() { + } + +} diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchAction.java new file mode 100644 index 00000000000..e314d8bacd2 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchAction.java @@ -0,0 +1,33 @@ +/* + * 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.watcher.transport.actions.ack; + +import org.elasticsearch.watcher.client.WatcherAction; +import org.elasticsearch.client.Client; + +/** + * This action acks an watch in memory, and the index + */ +public class AckWatchAction extends WatcherAction { + + public static final AckWatchAction INSTANCE = new AckWatchAction(); + public static final String NAME = "indices:data/write/watch/ack"; + + private AckWatchAction() { + super(NAME); + } + + @Override + public AckWatchResponse newResponse() { + return new AckWatchResponse(); + } + + @Override + public AckWatchRequestBuilder newRequestBuilder(Client client) { + return new AckWatchRequestBuilder(client); + } + +} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertRequest.java b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchRequest.java similarity index 57% rename from src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertRequest.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchRequest.java index daa0f6f4eb7..103359a05b6 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertRequest.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchRequest.java @@ -3,50 +3,50 @@ * 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.alerts.transport.actions.ack; +package org.elasticsearch.watcher.transport.actions.ack; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ValidateActions; import org.elasticsearch.action.support.master.MasterNodeOperationRequest; -import org.elasticsearch.alerts.AlertsStore; +import org.elasticsearch.watcher.watch.WatchStore; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; /** - * A delete alert request to delete an alert by name (id) + * A delete watch request to delete an watch by name (id) */ -public class AckAlertRequest extends MasterNodeOperationRequest { +public class AckWatchRequest extends MasterNodeOperationRequest { - private String alertName; + private String watchName; - public AckAlertRequest() { + public AckWatchRequest() { } - public AckAlertRequest(String alertName) { - this.alertName = alertName; + public AckWatchRequest(String watchName) { + this.watchName = watchName; } /** - * @return The name of the alert to be acked + * @return The name of the watch to be acked */ - public String getAlertName() { - return alertName; + public String getWatchName() { + return watchName; } /** - * Sets the name of the alert to be acked + * Sets the name of the watch to be acked */ - public void setAlertName(String alertName) { - this.alertName = alertName; + public void setWatchName(String watchName) { + this.watchName = watchName; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; - if (alertName == null){ - validationException = ValidateActions.addValidationError("alertName is missing", validationException); + if (watchName == null){ + validationException = ValidateActions.addValidationError("watch name is missing", validationException); } return validationException; } @@ -54,17 +54,17 @@ public class AckAlertRequest extends MasterNodeOperationRequest @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); - alertName = in.readString(); + watchName = in.readString(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - out.writeString(alertName); + out.writeString(watchName); } @Override public String toString() { - return "ack {[" + AlertsStore.ALERT_INDEX + "][" + alertName + "]}"; + return "ack {[" + WatchStore.INDEX + "][" + watchName + "]}"; } } diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchRequestBuilder.java b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchRequestBuilder.java new file mode 100644 index 00000000000..c225f2a58c3 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchRequestBuilder.java @@ -0,0 +1,39 @@ +/* + * 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.watcher.transport.actions.ack; + +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.client.Client; + +/** + * A ack watch action request builder. + */ +public class AckWatchRequestBuilder extends MasterNodeOperationRequestBuilder { + + public AckWatchRequestBuilder(Client client) { + super(client, new AckWatchRequest()); + } + + public AckWatchRequestBuilder(Client client, String watchName) { + super(client, new AckWatchRequest(watchName)); + } + + /** + * Sets the name of the watch to be ack + */ + public AckWatchRequestBuilder setWatchName(String watchName) { + this.request().setWatchName(watchName); + return this; + } + + @Override + protected void doExecute(final ActionListener listener) { + new WatcherClient(client).ackWatch(request, listener); + } + +} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertResponse.java b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchResponse.java similarity index 65% rename from src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertResponse.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchResponse.java index 3e4f8b28adf..ef275110987 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/AckAlertResponse.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/AckWatchResponse.java @@ -3,10 +3,10 @@ * 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.alerts.transport.actions.ack; +package org.elasticsearch.watcher.transport.actions.ack; import org.elasticsearch.action.ActionResponse; -import org.elasticsearch.alerts.Alert; +import org.elasticsearch.watcher.watch.Watch; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; @@ -14,30 +14,30 @@ import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; /** - * This class contains the ackState of the alert, if the alert was successfully acked this will be ACK + * This class contains the ackState of the watch, if the watch was successfully acked this will be ACK */ -public class AckAlertResponse extends ActionResponse { +public class AckWatchResponse extends ActionResponse { - private Alert.Status status; + private Watch.Status status; - public AckAlertResponse() { + public AckWatchResponse() { } - public AckAlertResponse(@Nullable Alert.Status status) { + public AckWatchResponse(@Nullable Watch.Status status) { this.status = status; } /** - * @return The ack state for the alert + * @return The ack state for the watch */ - public Alert.Status getStatus() { + public Watch.Status getStatus() { return status; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); - status = in.readBoolean() ? Alert.Status.read(in) : null; + status = in.readBoolean() ? Watch.Status.read(in) : null; } @Override diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/TransportAckAlertAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/TransportAckWatchAction.java similarity index 59% rename from src/main/java/org/elasticsearch/alerts/transport/actions/ack/TransportAckAlertAction.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/ack/TransportAckWatchAction.java index 8b7df0e28a0..96c54e48e3c 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/ack/TransportAckAlertAction.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/ack/TransportAckWatchAction.java @@ -3,14 +3,14 @@ * 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.alerts.transport.actions.ack; +package org.elasticsearch.watcher.transport.actions.ack; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.AlertsStore; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.watch.WatchStore; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; @@ -23,15 +23,15 @@ import org.elasticsearch.transport.TransportService; /** * Performs the delete operation. */ -public class TransportAckAlertAction extends TransportMasterNodeOperationAction { +public class TransportAckWatchAction extends TransportMasterNodeOperationAction { - private final AlertsService alertsService; + private final WatchService watchService; @Inject - public TransportAckAlertAction(Settings settings, TransportService transportService, ClusterService clusterService, - ThreadPool threadPool, ActionFilters actionFilters, AlertsService alertsService) { - super(settings, AckAlertAction.NAME, transportService, clusterService, threadPool, actionFilters); - this.alertsService = alertsService; + public TransportAckWatchAction(Settings settings, TransportService transportService, ClusterService clusterService, + ThreadPool threadPool, ActionFilters actionFilters, WatchService watchService) { + super(settings, AckWatchAction.NAME, transportService, clusterService, threadPool, actionFilters); + this.watchService = watchService; } @Override @@ -40,19 +40,19 @@ public class TransportAckAlertAction extends TransportMasterNodeOperationAction< } @Override - protected AckAlertRequest newRequest() { - return new AckAlertRequest(); + protected AckWatchRequest newRequest() { + return new AckWatchRequest(); } @Override - protected AckAlertResponse newResponse() { - return new AckAlertResponse(); + protected AckWatchResponse newResponse() { + return new AckWatchResponse(); } @Override - protected void masterOperation(AckAlertRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { + protected void masterOperation(AckWatchRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { try { - AckAlertResponse response = new AckAlertResponse(alertsService.ackAlert(request.getAlertName())); + AckWatchResponse response = new AckWatchResponse(watchService.ackWatch(request.getWatchName())); listener.onResponse(response); } catch (Exception e) { listener.onFailure(e); @@ -60,8 +60,8 @@ public class TransportAckAlertAction extends TransportMasterNodeOperationAction< } @Override - protected ClusterBlockException checkBlock(AckAlertRequest request, ClusterState state) { - return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, AlertsStore.ALERT_INDEX); + protected ClusterBlockException checkBlock(AckWatchRequest request, ClusterState state) { + return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, WatchStore.INDEX); } diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/delete/DeleteWatchAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/delete/DeleteWatchAction.java new file mode 100644 index 00000000000..cb0eafd55cd --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/delete/DeleteWatchAction.java @@ -0,0 +1,32 @@ +/* + * 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.watcher.transport.actions.delete; + +import org.elasticsearch.watcher.client.WatcherAction; +import org.elasticsearch.client.Client; + +/** + * This action deletes an watch from in memory, the scheduler and the index + */ +public class DeleteWatchAction extends WatcherAction { + + public static final DeleteWatchAction INSTANCE = new DeleteWatchAction(); + public static final String NAME = "indices:data/write/watch/delete"; + + private DeleteWatchAction() { + super(NAME); + } + + @Override + public DeleteWatchResponse newResponse() { + return new DeleteWatchResponse(); + } + + @Override + public DeleteWatchRequestBuilder newRequestBuilder(Client client) { + return new DeleteWatchRequestBuilder(client); + } +} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertRequest.java b/src/main/java/org/elasticsearch/watcher/transport/actions/delete/DeleteWatchRequest.java similarity index 65% rename from src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertRequest.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/delete/DeleteWatchRequest.java index e4153869dc9..87a8be03321 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertRequest.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/delete/DeleteWatchRequest.java @@ -3,12 +3,12 @@ * 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.alerts.transport.actions.delete; +package org.elasticsearch.watcher.transport.actions.delete; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ValidateActions; import org.elasticsearch.action.support.master.MasterNodeOperationRequest; -import org.elasticsearch.alerts.AlertsStore; +import org.elasticsearch.watcher.watch.WatchStore; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.lucene.uid.Versions; @@ -16,32 +16,32 @@ import org.elasticsearch.common.lucene.uid.Versions; import java.io.IOException; /** - * A delete alert request to delete an alert by name (id) + * A delete watch request to delete an watch by name (id) */ -public class DeleteAlertRequest extends MasterNodeOperationRequest { +public class DeleteWatchRequest extends MasterNodeOperationRequest { - private String alertName; + private String watchName; private long version = Versions.MATCH_ANY; - public DeleteAlertRequest() { + public DeleteWatchRequest() { } - public DeleteAlertRequest(String alertName) { - this.alertName = alertName; + public DeleteWatchRequest(String watchName) { + this.watchName = watchName; } /** - * @return The name of the alert to be deleted + * @return The name of the watch to be deleted */ - public String getAlertName() { - return alertName; + public String getWatchName() { + return watchName; } /** - * Sets the name of the alert to be deleted + * Sets the name of the watch to be deleted */ - public void setAlertName(String alertName) { - this.alertName = alertName; + public void setWatchName(String watchName) { + this.watchName = watchName; } /** @@ -59,8 +59,8 @@ public class DeleteAlertRequest extends MasterNodeOperationRequest { + + public DeleteWatchRequestBuilder(Client client) { + super(client, new DeleteWatchRequest()); + } + + public DeleteWatchRequestBuilder(Client client, String watchName) { + super(client, new DeleteWatchRequest(watchName)); + } + + /** + * Sets the name of the watch to be deleted + */ + public DeleteWatchRequestBuilder setWatchName(String watchName) { + this.request().setWatchName(watchName); + return this; + } + + @Override + protected void doExecute(final ActionListener listener) { + new WatcherClient(client).deleteWatch(request, listener); + } + +} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertResponse.java b/src/main/java/org/elasticsearch/watcher/transport/actions/delete/DeleteWatchResponse.java similarity index 85% rename from src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertResponse.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/delete/DeleteWatchResponse.java index a1a278fd4c1..c95f6e4a358 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/DeleteAlertResponse.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/delete/DeleteWatchResponse.java @@ -3,7 +3,7 @@ * 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.alerts.transport.actions.delete; +package org.elasticsearch.watcher.transport.actions.delete; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.delete.DeleteResponse; @@ -15,14 +15,14 @@ import java.io.IOException; /** */ -public class DeleteAlertResponse extends ActionResponse { +public class DeleteWatchResponse extends ActionResponse { private DeleteResponse deleteResponse; - public DeleteAlertResponse() { + public DeleteWatchResponse() { } - public DeleteAlertResponse(@Nullable DeleteResponse deleteResponse) { + public DeleteWatchResponse(@Nullable DeleteResponse deleteResponse) { this.deleteResponse = deleteResponse; } diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/TransportDeleteAlertAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/delete/TransportDeleteWatchAction.java similarity index 58% rename from src/main/java/org/elasticsearch/alerts/transport/actions/delete/TransportDeleteAlertAction.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/delete/TransportDeleteWatchAction.java index a86a1c46cb9..0bd5fed4beb 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/delete/TransportDeleteAlertAction.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/delete/TransportDeleteWatchAction.java @@ -3,14 +3,14 @@ * 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.alerts.transport.actions.delete; +package org.elasticsearch.watcher.transport.actions.delete; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.AlertsStore; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.watch.WatchStore; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; @@ -23,15 +23,15 @@ import org.elasticsearch.transport.TransportService; /** * Performs the delete operation. */ -public class TransportDeleteAlertAction extends TransportMasterNodeOperationAction { +public class TransportDeleteWatchAction extends TransportMasterNodeOperationAction { - private final AlertsService alertsService; + private final WatchService watchService; @Inject - public TransportDeleteAlertAction(Settings settings, TransportService transportService, ClusterService clusterService, - ThreadPool threadPool, ActionFilters actionFilters, AlertsService alertsService) { - super(settings, DeleteAlertAction.NAME, transportService, clusterService, threadPool, actionFilters); - this.alertsService = alertsService; + public TransportDeleteWatchAction(Settings settings, TransportService transportService, ClusterService clusterService, + ThreadPool threadPool, ActionFilters actionFilters, WatchService watchService) { + super(settings, DeleteWatchAction.NAME, transportService, clusterService, threadPool, actionFilters); + this.watchService = watchService; } @Override @@ -40,19 +40,19 @@ public class TransportDeleteAlertAction extends TransportMasterNodeOperationActi } @Override - protected DeleteAlertRequest newRequest() { - return new DeleteAlertRequest(); + protected DeleteWatchRequest newRequest() { + return new DeleteWatchRequest(); } @Override - protected DeleteAlertResponse newResponse() { - return new DeleteAlertResponse(); + protected DeleteWatchResponse newResponse() { + return new DeleteWatchResponse(); } @Override - protected void masterOperation(DeleteAlertRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { + protected void masterOperation(DeleteWatchRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { try { - DeleteAlertResponse response = new DeleteAlertResponse(alertsService.deleteAlert(request.getAlertName()).deleteResponse()); + DeleteWatchResponse response = new DeleteWatchResponse(watchService.deleteWatch(request.getWatchName()).deleteResponse()); listener.onResponse(response); } catch (Exception e) { listener.onFailure(e); @@ -60,8 +60,8 @@ public class TransportDeleteAlertAction extends TransportMasterNodeOperationActi } @Override - protected ClusterBlockException checkBlock(DeleteAlertRequest request, ClusterState state) { - return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, AlertsStore.ALERT_INDEX); + protected ClusterBlockException checkBlock(DeleteWatchRequest request, ClusterState state) { + return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, WatchStore.INDEX); } diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchAction.java new file mode 100644 index 00000000000..3be38bb4ec9 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchAction.java @@ -0,0 +1,32 @@ +/* + * 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.watcher.transport.actions.get; + +import org.elasticsearch.watcher.client.WatcherAction; +import org.elasticsearch.client.Client; + +/** + * This action gets an watch by name + */ +public class GetWatchAction extends WatcherAction { + + public static final GetWatchAction INSTANCE = new GetWatchAction(); + public static final String NAME = "indices:data/read/watch/get"; + + private GetWatchAction() { + super(NAME); + } + + @Override + public GetWatchResponse newResponse() { + return new GetWatchResponse(); + } + + @Override + public GetWatchRequestBuilder newRequestBuilder(Client client) { + return new GetWatchRequestBuilder(client); + } +} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertRequest.java b/src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchRequest.java similarity index 67% rename from src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertRequest.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchRequest.java index ef65a50b777..03040619043 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertRequest.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchRequest.java @@ -3,12 +3,12 @@ * 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.alerts.transport.actions.get; +package org.elasticsearch.watcher.transport.actions.get; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ValidateActions; import org.elasticsearch.action.support.master.MasterNodeOperationRequest; -import org.elasticsearch.alerts.AlertsStore; +import org.elasticsearch.watcher.watch.WatchStore; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.lucene.uid.Versions; @@ -17,45 +17,45 @@ import org.elasticsearch.index.VersionType; import java.io.IOException; /** - * The request to get the alert by name (id) + * The request to get the watch by name (id) */ -public class GetAlertRequest extends MasterNodeOperationRequest { +public class GetWatchRequest extends MasterNodeOperationRequest { - private String alertName; + private String watchName; private long version = Versions.MATCH_ANY; private VersionType versionType = VersionType.INTERNAL; - public GetAlertRequest() { + public GetWatchRequest() { } /** - * @param alertName name (id) of the alert to retrieve + * @param watchName name (id) of the watch to retrieve */ - public GetAlertRequest(String alertName) { - this.alertName = alertName; + public GetWatchRequest(String watchName) { + this.watchName = watchName; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; - if (alertName == null) { - validationException = ValidateActions.addValidationError("alertName is missing", validationException); + if (watchName == null) { + validationException = ValidateActions.addValidationError("watchName is missing", validationException); } return validationException; } /** - * @return The name of the alert to retrieve + * @return The name of the watch to retrieve */ - public String alertName() { - return alertName; + public String watchName() { + return watchName; } - public GetAlertRequest alertName(String alertName){ - this.alertName = alertName; + public GetWatchRequest watchName(String watchName){ + this.watchName = watchName; return this; } @@ -63,7 +63,7 @@ public class GetAlertRequest extends MasterNodeOperationRequest * Sets the version, which will cause the delete operation to only be performed if a matching * version exists and no changes happened on the doc since then. */ - public GetAlertRequest version(long version) { + public GetWatchRequest version(long version) { this.version = version; return this; } @@ -72,7 +72,7 @@ public class GetAlertRequest extends MasterNodeOperationRequest return this.version; } - public GetAlertRequest versionType(VersionType versionType) { + public GetWatchRequest versionType(VersionType versionType) { this.versionType = versionType; return this; } @@ -86,7 +86,7 @@ public class GetAlertRequest extends MasterNodeOperationRequest super.readFrom(in); version = Versions.readVersion(in); versionType = VersionType.fromValue(in.readByte()); - alertName = in.readString(); + watchName = in.readString(); } @Override @@ -94,11 +94,11 @@ public class GetAlertRequest extends MasterNodeOperationRequest super.writeTo(out); Versions.writeVersion(version, out); out.writeByte(versionType.getValue()); - out.writeString(alertName); + out.writeString(watchName); } @Override public String toString() { - return "delete {[" + AlertsStore.ALERT_INDEX + "][" + alertName +"]}"; + return "delete {[" + WatchStore.INDEX + "][" + watchName +"]}"; } } diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertRequestBuilder.java b/src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchRequestBuilder.java similarity index 51% rename from src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertRequestBuilder.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchRequestBuilder.java index 2e8c80df0e4..5d89732f14a 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertRequestBuilder.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchRequestBuilder.java @@ -3,43 +3,43 @@ * 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.alerts.transport.actions.get; +package org.elasticsearch.watcher.transport.actions.get; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionRequestBuilder; -import org.elasticsearch.alerts.client.AlertsClient; +import org.elasticsearch.watcher.client.WatcherClient; import org.elasticsearch.client.Client; import org.elasticsearch.index.VersionType; /** * A delete document action request builder. */ -public class GetAlertRequestBuilder extends ActionRequestBuilder { +public class GetWatchRequestBuilder extends ActionRequestBuilder { - public GetAlertRequestBuilder(Client client, String alertName) { - super(client, new GetAlertRequest(alertName)); + public GetWatchRequestBuilder(Client client, String watchName) { + super(client, new GetWatchRequest(watchName)); } - public GetAlertRequestBuilder(Client client) { - super(client, new GetAlertRequest()); + public GetWatchRequestBuilder(Client client) { + super(client, new GetWatchRequest()); } - public GetAlertRequestBuilder setAlertName(String alertName) { - request.alertName(alertName); + public GetWatchRequestBuilder setWatchName(String watchName) { + request.watchName(watchName); return this; } /** * Sets the type of versioning to use. Defaults to {@link org.elasticsearch.index.VersionType#INTERNAL}. */ - public GetAlertRequestBuilder setVersionType(VersionType versionType) { + public GetWatchRequestBuilder setVersionType(VersionType versionType) { request.versionType(versionType); return this; } @Override - protected void doExecute(final ActionListener listener) { - new AlertsClient(client).getAlert(request, listener); + protected void doExecute(final ActionListener listener) { + new WatcherClient(client).getWatch(request, listener); } } diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertResponse.java b/src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchResponse.java similarity index 77% rename from src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertResponse.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchResponse.java index 67253c942a6..1ead4b315f2 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/get/GetAlertResponse.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/get/GetWatchResponse.java @@ -3,7 +3,7 @@ * 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.alerts.transport.actions.get; +package org.elasticsearch.watcher.transport.actions.get; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.get.GetResponse; @@ -12,22 +12,19 @@ import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; -/** - * The GetAlertResponse the response class wraps a GetResponse containing the alert source - */ -public class GetAlertResponse extends ActionResponse { +public class GetWatchResponse extends ActionResponse { private GetResponse getResponse; - public GetAlertResponse() { + public GetWatchResponse() { } - public GetAlertResponse(GetResponse getResponse) { + public GetWatchResponse(GetResponse getResponse) { this.getResponse = getResponse; } /** - * Sets the GetResponse containing the alert source + * Sets the GetResponse containing the watch source */ public void getResponse(GetResponse getResponse) { this.getResponse = getResponse; diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/get/TransportGetAlertAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/get/TransportGetWatchAction.java similarity index 56% rename from src/main/java/org/elasticsearch/alerts/transport/actions/get/TransportGetAlertAction.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/get/TransportGetWatchAction.java index e01d15a45da..1510c8d6439 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/get/TransportGetAlertAction.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/get/TransportGetWatchAction.java @@ -3,16 +3,16 @@ * 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.alerts.transport.actions.get; +package org.elasticsearch.watcher.transport.actions.get; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.AlertsStore; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.watch.WatchStore; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; @@ -31,15 +31,15 @@ import java.io.IOException; /** * Performs the get operation. */ -public class TransportGetAlertAction extends TransportMasterNodeOperationAction { +public class TransportGetWatchAction extends TransportMasterNodeOperationAction { - private final AlertsService alertsService; + private final WatchService watchService; @Inject - public TransportGetAlertAction(Settings settings, TransportService transportService, ClusterService clusterService, - ThreadPool threadPool, ActionFilters actionFilters, AlertsService alertsService) { - super(settings, GetAlertAction.NAME, transportService, clusterService, threadPool, actionFilters); - this.alertsService = alertsService; + public TransportGetWatchAction(Settings settings, TransportService transportService, ClusterService clusterService, + ThreadPool threadPool, ActionFilters actionFilters, WatchService watchService) { + super(settings, GetWatchAction.NAME, transportService, clusterService, threadPool, actionFilters); + this.watchService = watchService; } @Override @@ -48,36 +48,36 @@ public class TransportGetAlertAction extends TransportMasterNodeOperationAction< } @Override - protected GetAlertRequest newRequest() { - return new GetAlertRequest(); + protected GetWatchRequest newRequest() { + return new GetWatchRequest(); } @Override - protected GetAlertResponse newResponse() { - return new GetAlertResponse(); + protected GetWatchResponse newResponse() { + return new GetWatchResponse(); } @Override - protected void masterOperation(GetAlertRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { - Alert alert = alertsService.getAlert(request.alertName()); + protected void masterOperation(GetWatchRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { + Watch watch = watchService.getWatch(request.watchName()); GetResult getResult; - if (alert != null) { - BytesReference alertSource = null; + if (watch != null) { + BytesReference watchSource = null; try (XContentBuilder builder = JsonXContent.contentBuilder()) { - builder.value(alert); - alertSource = builder.bytes(); + builder.value(watch); + watchSource = builder.bytes(); } catch (IOException e) { listener.onFailure(e); } - getResult = new GetResult(AlertsStore.ALERT_INDEX, AlertsStore.ALERT_TYPE, alert.name(), alert.status().version(), true, alertSource, null); + getResult = new GetResult(WatchStore.INDEX, WatchStore.DOC_TYPE, watch.name(), watch.status().version(), true, watchSource, null); } else { - getResult = new GetResult(AlertsStore.ALERT_INDEX, AlertsStore.ALERT_TYPE, request.alertName(), -1, false, null, null); + getResult = new GetResult(WatchStore.INDEX, WatchStore.DOC_TYPE, request.watchName(), -1, false, null, null); } - listener.onResponse(new GetAlertResponse(new GetResponse(getResult))); + listener.onResponse(new GetWatchResponse(new GetResponse(getResult))); } @Override - protected ClusterBlockException checkBlock(GetAlertRequest request, ClusterState state) { - return state.blocks().indexBlockedException(ClusterBlockLevel.READ, AlertsStore.ALERT_INDEX); + protected ClusterBlockException checkBlock(GetWatchRequest request, ClusterState state) { + return state.blocks().indexBlockedException(ClusterBlockLevel.READ, WatchStore.INDEX); } } diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/get/package-info.java b/src/main/java/org/elasticsearch/watcher/transport/actions/get/package-info.java similarity index 82% rename from src/main/java/org/elasticsearch/alerts/transport/actions/get/package-info.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/get/package-info.java index 414c52afb23..ea7977fb3af 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/get/package-info.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/get/package-info.java @@ -7,4 +7,4 @@ /** * Delete action. */ -package org.elasticsearch.alerts.transport.actions.get; \ No newline at end of file +package org.elasticsearch.watcher.transport.actions.get; \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchAction.java new file mode 100644 index 00000000000..423a50fa2ef --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchAction.java @@ -0,0 +1,32 @@ +/* + * 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.watcher.transport.actions.put; + +import org.elasticsearch.watcher.client.WatcherAction; +import org.elasticsearch.client.Client; + +/** + * This action puts an watch into the watch index and adds it to the scheduler + */ +public class PutWatchAction extends WatcherAction { + + public static final PutWatchAction INSTANCE = new PutWatchAction(); + public static final String NAME = "indices:data/write/watch/put"; + + private PutWatchAction() { + super(NAME); + } + + @Override + public PutWatchRequestBuilder newRequestBuilder(Client client) { + return new PutWatchRequestBuilder(client); + } + + @Override + public PutWatchResponse newResponse() { + return new PutWatchResponse(); + } +} diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchRequest.java b/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchRequest.java new file mode 100644 index 00000000000..4c5f941cb92 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchRequest.java @@ -0,0 +1,121 @@ +/* + * 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.watcher.transport.actions.put; + + +import org.elasticsearch.action.ActionRequestValidationException; +import org.elasticsearch.action.ValidateActions; +import org.elasticsearch.action.support.master.MasterNodeOperationRequest; +import org.elasticsearch.watcher.client.WatchSourceBuilder; +import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.common.xcontent.XContentType; + +import java.io.IOException; + +/** + * This request class contains the data needed to create a watch along with the name of the watch. + * The name of the watch will become the ID of the indexed document. + */ +public class PutWatchRequest extends MasterNodeOperationRequest { + + private String name; + private BytesReference source; + private boolean sourceUnsafe; + + public PutWatchRequest() { + } + + public PutWatchRequest(String name, WatchSourceBuilder source) { + this(name, source.buildAsBytes(XContentType.JSON), false); + } + + public PutWatchRequest(String name, BytesReference source, boolean sourceUnsafe) { + this.name = name; + this.source = source; + this.sourceUnsafe = sourceUnsafe; + } + + /** + * @return The name that will be the ID of the indexed document + */ + public String getName() { + return name; + } + + /** + * Set the watch name + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return The source of the watch + */ + public BytesReference getSource() { + return source; + } + + /** + * Set the source of the watch + */ + public void source(WatchSourceBuilder source) { + source(source.buildAsBytes(XContentType.JSON)); + } + + /** + * Set the source of the watch + */ + public void source(BytesReference source) { + this.source = source; + this.sourceUnsafe = false; + } + + /** + * Set the source of the watch with boolean to control source safety + */ + public void source(BytesReference source, boolean sourceUnsafe) { + this.source = source; + this.sourceUnsafe = sourceUnsafe; + } + + public void beforeLocalFork() { + if (sourceUnsafe) { + source = source.copyBytesArray(); + sourceUnsafe = false; + } + } + + @Override + public ActionRequestValidationException validate() { + ActionRequestValidationException validationException = null; + if (name == null) { + validationException = ValidateActions.addValidationError("watch name is missing", validationException); + } + if (source == null) { + validationException = ValidateActions.addValidationError("watch source is missing", validationException); + } + return validationException; + } + + @Override + public void readFrom(StreamInput in) throws IOException { + super.readFrom(in); + name = in.readString(); + source = in.readBytesReference(); + sourceUnsafe = false; + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + super.writeTo(out); + out.writeString(name); + out.writeBytesReference(source); + } + +} diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchRequestBuilder.java b/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchRequestBuilder.java new file mode 100644 index 00000000000..e6119051f5c --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchRequestBuilder.java @@ -0,0 +1,54 @@ +/* + * 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.watcher.transport.actions.put; + +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder; +import org.elasticsearch.watcher.client.WatchSourceBuilder; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.bytes.BytesReference; + +public class PutWatchRequestBuilder extends MasterNodeOperationRequestBuilder { + + public PutWatchRequestBuilder(Client client) { + super(client, new PutWatchRequest()); + } + + public PutWatchRequestBuilder(Client client, String watchName) { + super(client, new PutWatchRequest()); + request.setName(watchName); + } + + /** + * @param watchName The watch name to be created + */ + public PutWatchRequestBuilder watchName(String watchName){ + request.setName(watchName); + return this; + } + + /** + * @param source the source of the watch to be created + */ + public PutWatchRequestBuilder source(BytesReference source) { + request.source(source); + return this; + } + + /** + * @param source the source of the watch to be created + */ + public PutWatchRequestBuilder source(WatchSourceBuilder source) { + request.source(source); + return this; + } + + @Override + protected void doExecute(ActionListener listener) { + new WatcherClient(client).putWatch(request, listener); + } +} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertResponse.java b/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchResponse.java similarity index 73% rename from src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertResponse.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchResponse.java index 09b18779720..cf43df39368 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/put/PutAlertResponse.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/put/PutWatchResponse.java @@ -3,7 +3,7 @@ * 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.alerts.transport.actions.put; +package org.elasticsearch.watcher.transport.actions.put; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.index.IndexResponse; @@ -13,31 +13,24 @@ import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; /** - * The Response for a put alert - * This response wraps the #IndexResponse returned from the persisting of the alert + * The Response for a put watch action */ -public class PutAlertResponse extends ActionResponse { +public class PutWatchResponse extends ActionResponse { private IndexResponse indexResponse; - public PutAlertResponse(IndexResponse indexResponse) { + public PutWatchResponse(IndexResponse indexResponse) { this.indexResponse = indexResponse; } - public PutAlertResponse() { + public PutWatchResponse() { indexResponse = null; } - /** - * @return The IndexResponse for this PutAlertResponse - */ public IndexResponse indexResponse(){ return indexResponse; } - /** - * Set the IndexResponse on this PutAlertResponse - */ public void indexResponse(IndexResponse indexResponse){ this.indexResponse = indexResponse; } diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/put/TransportPutAlertAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/put/TransportPutWatchAction.java similarity index 58% rename from src/main/java/org/elasticsearch/alerts/transport/actions/put/TransportPutAlertAction.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/put/TransportPutWatchAction.java index 513f0227a78..c85d11599a1 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/put/TransportPutAlertAction.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/put/TransportPutWatchAction.java @@ -3,15 +3,15 @@ * 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.alerts.transport.actions.put; +package org.elasticsearch.watcher.transport.actions.put; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.AlertsStore; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.watch.WatchStore; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; @@ -23,15 +23,15 @@ import org.elasticsearch.transport.TransportService; /** */ -public class TransportPutAlertAction extends TransportMasterNodeOperationAction { +public class TransportPutWatchAction extends TransportMasterNodeOperationAction { - private final AlertsService alertsService; + private final WatchService watchService; @Inject - public TransportPutAlertAction(Settings settings, TransportService transportService, ClusterService clusterService, - ThreadPool threadPool, ActionFilters actionFilters, AlertsService alertsService) { - super(settings, PutAlertAction.NAME, transportService, clusterService, threadPool, actionFilters); - this.alertsService = alertsService; + public TransportPutWatchAction(Settings settings, TransportService transportService, ClusterService clusterService, + ThreadPool threadPool, ActionFilters actionFilters, WatchService watchService) { + super(settings, PutWatchAction.NAME, transportService, clusterService, threadPool, actionFilters); + this.watchService = watchService; } @Override @@ -40,29 +40,29 @@ public class TransportPutAlertAction extends TransportMasterNodeOperationAction< } @Override - protected PutAlertRequest newRequest() { - return new PutAlertRequest(); + protected PutWatchRequest newRequest() { + return new PutWatchRequest(); } @Override - protected PutAlertResponse newResponse() { - return new PutAlertResponse(); + protected PutWatchResponse newResponse() { + return new PutWatchResponse(); } @Override - protected void masterOperation(PutAlertRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { + protected void masterOperation(PutWatchRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { try { - IndexResponse indexResponse = alertsService.putAlert(request.getAlertName(), request.getAlertSource()); - listener.onResponse(new PutAlertResponse(indexResponse)); + IndexResponse indexResponse = watchService.putWatch(request.getName(), request.getSource()); + listener.onResponse(new PutWatchResponse(indexResponse)); } catch (Exception e) { listener.onFailure(e); } } @Override - protected ClusterBlockException checkBlock(PutAlertRequest request, ClusterState state) { - request.beforeLocalFork(); // This is the best place to make the alert source safe - return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, AlertsStore.ALERT_INDEX); + protected ClusterBlockException checkBlock(PutWatchRequest request, ClusterState state) { + request.beforeLocalFork(); // This is the best place to make the watch source safe + return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, WatchStore.INDEX); } } diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/service/TransportAlertsServiceAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/service/TransportWatcherServiceAction.java similarity index 54% rename from src/main/java/org/elasticsearch/alerts/transport/actions/service/TransportAlertsServiceAction.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/service/TransportWatcherServiceAction.java index 8bdcd5a5de7..09a9734aaf1 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/service/TransportAlertsServiceAction.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/service/TransportWatcherServiceAction.java @@ -3,14 +3,14 @@ * 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.alerts.transport.actions.service; +package org.elasticsearch.watcher.transport.actions.service; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalArgumentException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction; -import org.elasticsearch.alerts.AlertsLifeCycleService; +import org.elasticsearch.watcher.WatcherLifeCycleService; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; @@ -22,14 +22,14 @@ import org.elasticsearch.transport.TransportService; /** */ -public class TransportAlertsServiceAction extends TransportMasterNodeOperationAction { +public class TransportWatcherServiceAction extends TransportMasterNodeOperationAction { - private final AlertsLifeCycleService alertsLifeCycleService; + private final WatcherLifeCycleService lifeCycleService; @Inject - public TransportAlertsServiceAction(Settings settings, String actionName, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, ActionFilters actionFilters, AlertsLifeCycleService alertsLifeCycleService) { + public TransportWatcherServiceAction(Settings settings, String actionName, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, ActionFilters actionFilters, WatcherLifeCycleService lifeCycleService) { super(settings, actionName, transportService, clusterService, threadPool, actionFilters); - this.alertsLifeCycleService = alertsLifeCycleService; + this.lifeCycleService = lifeCycleService; } @Override @@ -38,37 +38,37 @@ public class TransportAlertsServiceAction extends TransportMasterNodeOperationAc } @Override - protected AlertsServiceRequest newRequest() { - return new AlertsServiceRequest(); + protected WatcherServiceRequest newRequest() { + return new WatcherServiceRequest(); } @Override - protected AlertsServiceResponse newResponse() { - return new AlertsServiceResponse(); + protected WatcherServiceResponse newResponse() { + return new WatcherServiceResponse(); } @Override - protected void masterOperation(AlertsServiceRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { + protected void masterOperation(WatcherServiceRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { switch (request.getCommand()) { - case "start": - alertsLifeCycleService.start(); + case START: + lifeCycleService.start(); break; - case "stop": - alertsLifeCycleService.stop(); + case STOP: + lifeCycleService.stop(); break; - case "restart": - alertsLifeCycleService.start(); - alertsLifeCycleService.stop(); + case RESTART: + lifeCycleService.start(); + lifeCycleService.stop(); break; default: listener.onFailure(new ElasticsearchIllegalArgumentException("Command [" + request.getCommand() + "] is undefined")); return; } - listener.onResponse(new AlertsServiceResponse(true)); + listener.onResponse(new WatcherServiceResponse(true)); } @Override - protected ClusterBlockException checkBlock(AlertsServiceRequest request, ClusterState state) { + protected ClusterBlockException checkBlock(WatcherServiceRequest request, ClusterState state) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA); } } diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/service/WatcherServiceAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/service/WatcherServiceAction.java new file mode 100644 index 00000000000..84c5487bb5f --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/service/WatcherServiceAction.java @@ -0,0 +1,32 @@ +/* + * 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.watcher.transport.actions.service; + +import org.elasticsearch.watcher.client.WatcherAction; +import org.elasticsearch.client.Client; + +/** + */ +public class WatcherServiceAction extends WatcherAction { + + public static final WatcherServiceAction INSTANCE = new WatcherServiceAction(); + public static final String NAME = "cluster:admin/watcher/service"; + + private WatcherServiceAction() { + super(NAME); + } + + @Override + public WatcherServiceResponse newResponse() { + return new WatcherServiceResponse(); + } + + @Override + public WatcherServiceRequestBuilder newRequestBuilder(Client client) { + return new WatcherServiceRequestBuilder(client); + } + +} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceRequest.java b/src/main/java/org/elasticsearch/watcher/transport/actions/service/WatcherServiceRequest.java similarity index 55% rename from src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceRequest.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/service/WatcherServiceRequest.java index 26abe04f061..ccefc46c42a 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceRequest.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/service/WatcherServiceRequest.java @@ -3,7 +3,7 @@ * 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.alerts.transport.actions.service; +package org.elasticsearch.watcher.transport.actions.service; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ValidateActions; @@ -12,35 +12,44 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; +import java.util.Locale; /** */ -public class AlertsServiceRequest extends MasterNodeOperationRequest { +public class WatcherServiceRequest extends MasterNodeOperationRequest { - private String command; + static enum Command { START, STOP, RESTART } - /** - * Starts alerting if not already started. - */ - public void start() { - command = "start"; + private Command command; + + public WatcherServiceRequest() { } /** - * Stops alerting if not already stopped. + * Starts the watcher service if not already started. */ - public void stop() { - command = "stop"; + public WatcherServiceRequest start() { + command = Command.START; + return this; } /** - * Starts and stops alerting. + * Stops the watcher service if not already stopped. */ - public void restart() { - command = "restart"; + public WatcherServiceRequest stop() { + command = Command.STOP; + return this; } - String getCommand() { + /** + * Starts and stops the watcher. + */ + public WatcherServiceRequest restart() { + command = Command.RESTART; + return this; + } + + Command getCommand() { return command; } @@ -56,12 +65,12 @@ public class AlertsServiceRequest extends MasterNodeOperationRequest { + + public WatcherServiceRequestBuilder(Client client) { + super(client, new WatcherServiceRequest()); + } + + /** + * Starts the watcher if not already started. + */ + public WatcherServiceRequestBuilder start() { + request.start(); + return this; + } + + /** + * Stops the watcher if not already stopped. + */ + public WatcherServiceRequestBuilder stop() { + request.stop(); + return this; + } + + /** + * Starts and stops the watcher. + */ + public WatcherServiceRequestBuilder restart() { + request.restart(); + return this; + } + + @Override + protected void doExecute(ActionListener listener) { + new WatcherClient(client).watcherService(request, listener); + } +} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceResponse.java b/src/main/java/org/elasticsearch/watcher/transport/actions/service/WatcherServiceResponse.java similarity index 66% rename from src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceResponse.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/service/WatcherServiceResponse.java index f926ed5f6cd..c56b710ff0f 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/service/AlertsServiceResponse.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/service/WatcherServiceResponse.java @@ -3,19 +3,19 @@ * 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.alerts.transport.actions.service; +package org.elasticsearch.watcher.transport.actions.service; import org.elasticsearch.action.support.master.AcknowledgedResponse; /** * Empty response, so if it returns, it means all is fine. */ -public class AlertsServiceResponse extends AcknowledgedResponse { +public class WatcherServiceResponse extends AcknowledgedResponse { - AlertsServiceResponse() { + WatcherServiceResponse() { } - public AlertsServiceResponse(boolean acknowledged) { + public WatcherServiceResponse(boolean acknowledged) { super(acknowledged); } } diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/stats/TransportWatcherStatsAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/stats/TransportWatcherStatsAction.java new file mode 100644 index 00000000000..b570656fbe5 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/stats/TransportWatcherStatsAction.java @@ -0,0 +1,75 @@ +/* + * 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.watcher.transport.actions.stats; + +import org.elasticsearch.ElasticsearchException; +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.support.ActionFilters; +import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction; +import org.elasticsearch.watcher.WatcherBuild; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.WatcherVersion; +import org.elasticsearch.watcher.history.HistoryService; +import org.elasticsearch.cluster.ClusterService; +import org.elasticsearch.cluster.ClusterState; +import org.elasticsearch.cluster.block.ClusterBlockException; +import org.elasticsearch.cluster.block.ClusterBlockLevel; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.threadpool.ThreadPool; +import org.elasticsearch.transport.TransportService; + +/** + * Performs the stats operation. + */ +public class TransportWatcherStatsAction extends TransportMasterNodeOperationAction { + + private final WatchService watchService; + private final HistoryService historyService; + + @Inject + public TransportWatcherStatsAction(Settings settings, TransportService transportService, ClusterService clusterService, + ThreadPool threadPool, ActionFilters actionFilters, WatchService watchService, + HistoryService historyService) { + super(settings, WatcherStatsAction.NAME, transportService, clusterService, threadPool, actionFilters); + this.watchService = watchService; + this.historyService = historyService; + } + + @Override + protected String executor() { + return ThreadPool.Names.MANAGEMENT; + } + + @Override + protected WatcherStatsRequest newRequest() { + return new WatcherStatsRequest(); + } + + @Override + protected WatcherStatsResponse newResponse() { + return new WatcherStatsResponse(); + } + + @Override + protected void masterOperation(WatcherStatsRequest request, ClusterState state, ActionListener listener) throws ElasticsearchException { + WatcherStatsResponse statsResponse = new WatcherStatsResponse(); + statsResponse.setWatchServiceState(watchService.state()); + statsResponse.setWatchExecutionQueueSize(historyService.queueSize()); + statsResponse.setWatchesCount(watchService.watchesCount()); + statsResponse.setWatchExecutionQueueMaxSize(historyService.largestQueueSize()); + statsResponse.setVersion(WatcherVersion.CURRENT); + statsResponse.setBuild(WatcherBuild.CURRENT); + listener.onResponse(statsResponse); + } + + @Override + protected ClusterBlockException checkBlock(WatcherStatsRequest request, ClusterState state) { + return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA); + } + + +} diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/stats/WatcherStatsAction.java b/src/main/java/org/elasticsearch/watcher/transport/actions/stats/WatcherStatsAction.java new file mode 100644 index 00000000000..f5f1ccf1eec --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/stats/WatcherStatsAction.java @@ -0,0 +1,33 @@ +/* + * 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.watcher.transport.actions.stats; + +import org.elasticsearch.watcher.client.WatcherAction; +import org.elasticsearch.client.Client; + +/** + * This Action gets the stats for the watcher plugin + */ +public class WatcherStatsAction extends WatcherAction { + + public static final WatcherStatsAction INSTANCE = new WatcherStatsAction(); + public static final String NAME = "cluster/watcher/stats"; + + private WatcherStatsAction() { + super(NAME); + } + + @Override + public WatcherStatsResponse newResponse() { + return new WatcherStatsResponse(); + } + + @Override + public WatcherStatsRequestBuilder newRequestBuilder(Client client) { + return new WatcherStatsRequestBuilder(client); + } + +} diff --git a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsRequest.java b/src/main/java/org/elasticsearch/watcher/transport/actions/stats/WatcherStatsRequest.java similarity index 78% rename from src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsRequest.java rename to src/main/java/org/elasticsearch/watcher/transport/actions/stats/WatcherStatsRequest.java index e5ee58e4398..46e34017167 100644 --- a/src/main/java/org/elasticsearch/alerts/transport/actions/stats/AlertsStatsRequest.java +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/stats/WatcherStatsRequest.java @@ -3,7 +3,7 @@ * 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.alerts.transport.actions.stats; +package org.elasticsearch.watcher.transport.actions.stats; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.support.master.MasterNodeOperationRequest; @@ -13,12 +13,12 @@ import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; /** - * The Request to get the alert stats + * The Request to get the watcher stats */ -public class AlertsStatsRequest extends MasterNodeOperationRequest { +public class WatcherStatsRequest extends MasterNodeOperationRequest { - public AlertsStatsRequest() { + public WatcherStatsRequest() { } @Override @@ -38,6 +38,6 @@ public class AlertsStatsRequest extends MasterNodeOperationRequest { + + public WatcherStatsRequestBuilder(Client client) { + super(client, new WatcherStatsRequest()); + } + + + @Override + protected void doExecute(final ActionListener listener) { + new WatcherClient(client).watcherStats(request, listener); + } + +} diff --git a/src/main/java/org/elasticsearch/watcher/transport/actions/stats/WatcherStatsResponse.java b/src/main/java/org/elasticsearch/watcher/transport/actions/stats/WatcherStatsResponse.java new file mode 100644 index 00000000000..e7a9a578b19 --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/transport/actions/stats/WatcherStatsResponse.java @@ -0,0 +1,116 @@ +/* + * 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.watcher.transport.actions.stats; + +import org.elasticsearch.action.ActionResponse; +import org.elasticsearch.watcher.WatcherBuild; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.WatcherVersion; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; + +import java.io.IOException; + +public class WatcherStatsResponse extends ActionResponse { + + private WatcherVersion version; + private WatcherBuild build; + private long watchesCount; + private WatchService.State watchServiceState; + private long watchExecutionQueueSize; + private long watchExecutionQueueMaxSize; + + public WatcherStatsResponse() { + } + + /** + * @return The current watch execution queue size + */ + public long getExecutionQueueSize() { + return watchExecutionQueueSize; + } + + void setWatchExecutionQueueSize(long watchExecutionQueueSize) { + this.watchExecutionQueueSize = watchExecutionQueueSize; + } + + /** + * @return The max size of the watch execution queue + */ + public long getWatchExecutionQueueMaxSize() { + return watchExecutionQueueMaxSize; + } + + void setWatchExecutionQueueMaxSize(long watchExecutionQueueMaxSize) { + this.watchExecutionQueueMaxSize = watchExecutionQueueMaxSize; + } + + /** + * @return The number of watches currently registered in the system + */ + public long getWatchesCount() { + return watchesCount; + } + + void setWatchesCount(long watchesCount) { + this.watchesCount = watchesCount; + } + + /** + * @return The state of the watch service. + */ + public WatchService.State getWatchServiceState() { + return watchServiceState; + } + + void setWatchServiceState(WatchService.State watcherServiceState) { + this.watchServiceState = watcherServiceState; + } + + /** + * @return The watcher plugin version. + */ + public WatcherVersion getVersion() { + return version; + } + + void setVersion(WatcherVersion version) { + this.version = version; + } + + /** + * @return The watcher plugin build information. + */ + public WatcherBuild getBuild() { + return build; + } + + void setBuild(WatcherBuild build) { + this.build = build; + } + + @Override + public void readFrom(StreamInput in) throws IOException { + super.readFrom(in); + watchesCount = in.readLong(); + watchExecutionQueueSize = in.readLong(); + watchExecutionQueueMaxSize = in.readLong(); + watchServiceState = WatchService.State.fromId(in.readByte()); + version = WatcherVersion.readVersion(in); + build = WatcherBuild.readBuild(in); + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + super.writeTo(out); + out.writeLong(watchesCount); + out.writeLong(watchExecutionQueueSize); + out.writeLong(watchExecutionQueueMaxSize); + out.writeByte(watchServiceState.getId()); + WatcherVersion.writeVersion(version, out); + WatcherBuild.writeBuild(build, out); + } +} diff --git a/src/main/java/org/elasticsearch/alerts/Payload.java b/src/main/java/org/elasticsearch/watcher/watch/Payload.java similarity index 89% rename from src/main/java/org/elasticsearch/alerts/Payload.java rename to src/main/java/org/elasticsearch/watcher/watch/Payload.java index a0c4d227f69..6b6e6b9cf8e 100644 --- a/src/main/java/org/elasticsearch/alerts/Payload.java +++ b/src/main/java/org/elasticsearch/watcher/watch/Payload.java @@ -3,18 +3,19 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; +import org.elasticsearch.watcher.WatcherException; import java.io.IOException; import java.util.HashMap; import java.util.Map; -import static org.elasticsearch.alerts.support.AlertUtils.responseToData; +import static org.elasticsearch.watcher.support.WatcherUtils.responseToData; /** * @@ -81,7 +82,7 @@ public interface Payload extends ToXContent { try { return parser.mapOrdered(); } catch (IOException ioe) { - throw new AlertsException("could not build a payload out of xcontent", ioe); + throw new WatcherException("could not build a payload out of xcontent", ioe); } } } diff --git a/src/main/java/org/elasticsearch/alerts/Alert.java b/src/main/java/org/elasticsearch/watcher/watch/Watch.java similarity index 84% rename from src/main/java/org/elasticsearch/alerts/Alert.java rename to src/main/java/org/elasticsearch/watcher/watch/Watch.java index 99af1147f01..d69f4221982 100644 --- a/src/main/java/org/elasticsearch/alerts/Alert.java +++ b/src/main/java/org/elasticsearch/watcher/watch/Watch.java @@ -3,24 +3,26 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; -import org.elasticsearch.alerts.actions.ActionRegistry; -import org.elasticsearch.alerts.actions.Actions; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.ConditionRegistry; -import org.elasticsearch.alerts.condition.simple.AlwaysTrueCondition; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.InputRegistry; -import org.elasticsearch.alerts.input.NoneInput; -import org.elasticsearch.alerts.scheduler.Scheduler; -import org.elasticsearch.alerts.scheduler.schedule.Schedule; -import org.elasticsearch.alerts.scheduler.schedule.ScheduleRegistry; -import org.elasticsearch.alerts.support.clock.Clock; -import org.elasticsearch.alerts.throttle.AlertThrottler; -import org.elasticsearch.alerts.throttle.Throttler; -import org.elasticsearch.alerts.transform.Transform; -import org.elasticsearch.alerts.transform.TransformRegistry; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.actions.ActionRegistry; +import org.elasticsearch.watcher.actions.Actions; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionRegistry; +import org.elasticsearch.watcher.condition.simple.AlwaysTrueCondition; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.InputRegistry; +import org.elasticsearch.watcher.input.NoneInput; +import org.elasticsearch.watcher.scheduler.Scheduler; +import org.elasticsearch.watcher.scheduler.schedule.Schedule; +import org.elasticsearch.watcher.scheduler.schedule.ScheduleRegistry; +import org.elasticsearch.watcher.support.clock.Clock; +import org.elasticsearch.watcher.throttle.WatchThrottler; +import org.elasticsearch.watcher.throttle.Throttler; +import org.elasticsearch.watcher.transform.Transform; +import org.elasticsearch.watcher.transform.TransformRegistry; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.bytes.BytesReference; @@ -42,9 +44,9 @@ import java.io.IOException; import java.util.Locale; import java.util.Map; -import static org.elasticsearch.alerts.support.AlertsDateUtils.*; +import static org.elasticsearch.watcher.support.WatcherDateUtils.*; -public class Alert implements Scheduler.Job, ToXContent { +public class Watch implements Scheduler.Job, ToXContent { private final String name; private final Schedule schedule; @@ -61,7 +63,7 @@ public class Alert implements Scheduler.Job, ToXContent { @Nullable private final Transform transform; - public Alert(String name, Clock clock, Schedule schedule, Input input, Condition condition, @Nullable Transform transform, Actions actions, @Nullable Map metadata, @Nullable TimeValue throttlePeriod, @Nullable Status status) { + public Watch(String name, Clock clock, Schedule schedule, Input input, Condition condition, @Nullable Transform transform, Actions actions, @Nullable Map metadata, @Nullable TimeValue throttlePeriod, @Nullable Status status) { this.name = name; this.schedule = schedule; this.input = input; @@ -71,7 +73,7 @@ public class Alert implements Scheduler.Job, ToXContent { this.throttlePeriod = throttlePeriod; this.metadata = metadata; this.transform = transform; - throttler = new AlertThrottler(clock, throttlePeriod); + throttler = new WatchThrottler(clock, throttlePeriod); } public String name() { @@ -113,9 +115,9 @@ public class Alert implements Scheduler.Job, ToXContent { } /** - * Acks this alert. + * Acks this watch. * - * @return {@code true} if the status of this alert changed, {@code false} otherwise. + * @return {@code true} if the status of this watch changed, {@code false} otherwise. */ public boolean ack() { return status.onAck(new DateTime()); @@ -130,8 +132,8 @@ public class Alert implements Scheduler.Job, ToXContent { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - Alert alert = (Alert) o; - return alert.name.equals(name); + Watch watch = (Watch) o; + return watch.name.equals(name); } @Override @@ -198,18 +200,18 @@ public class Alert implements Scheduler.Job, ToXContent { this.defaultCondition = new AlwaysTrueCondition(logger); } - public Alert parse(String name, boolean includeStatus, BytesReference source) { + public Watch parse(String name, boolean includeStatus, BytesReference source) { if (logger.isTraceEnabled()) { - logger.trace("parsing alert [{}] ", source.toUtf8()); + logger.trace("parsing watch [{}] ", source.toUtf8()); } try (XContentParser parser = XContentHelper.createParser(source)) { return parse(name, includeStatus, parser); } catch (IOException ioe) { - throw new AlertsException("could not parse alert [" + name + "]", ioe); + throw new WatcherException("could not parse watch [" + name + "]", ioe); } } - public Alert parse(String name, boolean includeStatus, XContentParser parser) throws IOException { + public Watch parse(String name, boolean includeStatus, XContentParser parser) throws IOException { Schedule schedule = null; Input input = defaultInput; Condition condition = defaultCondition; @@ -225,7 +227,7 @@ public class Alert implements Scheduler.Job, ToXContent { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == null ){ - throw new AlertsException("could not parse alert [" + name + "]. null token"); + throw new WatcherException("could not parse watch [" + name + "]. null token"); } else if ((token.isValue() || token == XContentParser.Token.START_OBJECT || token == XContentParser.Token.START_ARRAY) && currentFieldName !=null ) { if (SCHEDULE_FIELD.match(currentFieldName)) { schedule = scheduleRegistry.parse(parser); @@ -247,19 +249,19 @@ public class Alert implements Scheduler.Job, ToXContent { } else if (token == XContentParser.Token.VALUE_NUMBER) { throttlePeriod = TimeValue.timeValueMillis(parser.longValue()); } else { - throw new AlertsSettingsException("could not parse alert [" + name + "] throttle period. could not parse token [" + token + "] as time value (must either be string or number)"); + throw new WatcherSettingsException("could not parse watch [" + name + "] throttle period. could not parse token [" + token + "] as time value (must either be string or number)"); } } } } if (schedule == null) { - throw new AlertsSettingsException("could not parse alert [" + name + "]. missing alert schedule"); + throw new WatcherSettingsException("could not parse watch [" + name + "]. missing watch schedule"); } if (actions == null) { - throw new AlertsSettingsException("could not parse alert [" + name + "]. missing alert actions"); + throw new WatcherSettingsException("could not parse watch [" + name + "]. missing watch actions"); } - return new Alert(name, clock, schedule, input, condition, transform, actions, metatdata, throttlePeriod, status); + return new Watch(name, clock, schedule, input, condition, transform, actions, metatdata, throttlePeriod, status); } } @@ -373,10 +375,10 @@ public class Alert implements Scheduler.Job, ToXContent { } /** - * Called whenever an alert is checked, ie. the condition of the alert is evaluated to see if - * the alert should be executed. + * Called whenever an watch is checked, ie. the condition of the watch is evaluated to see if + * the watch should be executed. * - * @param metCondition indicates whether the alert's condition was met. + * @param metCondition indicates whether the watch's condition was met. */ public void onCheck(boolean metCondition, DateTime timestamp) { lastChecked = timestamp; @@ -389,15 +391,15 @@ public class Alert implements Scheduler.Job, ToXContent { } /** - * Called whenever an alert run is throttled + * Called whenever an watch run is throttled */ public void onThrottle(DateTime timestamp, String reason) { lastThrottle = new Throttle(timestamp, reason); } /** - * Notified this status that the alert was executed. If the current state is {@link org.elasticsearch.alerts.Alert.Status.AckStatus.State#AWAITS_EXECUTION}, it will change to - * {@link org.elasticsearch.alerts.Alert.Status.AckStatus.State#ACKABLE}. + * Notified this status that the watch was executed. If the current state is {@link Watch.Status.AckStatus.State#AWAITS_EXECUTION}, it will change to + * {@link Watch.Status.AckStatus.State#ACKABLE}. */ public void onExecution(DateTime timestamp) { lastExecuted = timestamp; @@ -407,8 +409,8 @@ public class Alert implements Scheduler.Job, ToXContent { } /** - * Notifies this status that the alert was acked. If the current state is {@link org.elasticsearch.alerts.Alert.Status.AckStatus.State#ACKABLE}, then we'll change it - * to {@link org.elasticsearch.alerts.Alert.Status.AckStatus.State#ACKED} (when set to {@link org.elasticsearch.alerts.Alert.Status.AckStatus.State#ACKED}, the {@link org.elasticsearch.alerts.throttle.AckThrottler} will lastThrottle the + * Notifies this status that the watch was acked. If the current state is {@link Watch.Status.AckStatus.State#ACKABLE}, then we'll change it + * to {@link Watch.Status.AckStatus.State#ACKED} (when set to {@link Watch.Status.AckStatus.State#ACKED}, the {@link org.elasticsearch.watcher.throttle.AckThrottler} will lastThrottle the * execution. * * @return {@code true} if the state of changed due to the ack, {@code false} otherwise. @@ -449,7 +451,7 @@ public class Alert implements Scheduler.Job, ToXContent { } public static Status read(StreamInput in) throws IOException { - Alert.Status status = new Alert.Status(); + Watch.Status status = new Watch.Status(); status.readFrom(in); return status; } @@ -496,19 +498,19 @@ public class Alert implements Scheduler.Job, ToXContent { if (token.isValue()) { lastChecked = parseDate(currentFieldName, token, parser); } else { - throw new AlertsException("expecting field [" + currentFieldName + "] to hold a date value, found [" + token + "] instead"); + throw new WatcherException("expecting field [" + currentFieldName + "] to hold a date value, found [" + token + "] instead"); } } else if (LAST_MET_CONDITION_FIELD.match(currentFieldName)) { if (token.isValue()) { lastMetCondition = parseDate(currentFieldName, token, parser); } else { - throw new AlertsException("expecting field [" + currentFieldName + "] to hold a date value, found [" + token + "] instead"); + throw new WatcherException("expecting field [" + currentFieldName + "] to hold a date value, found [" + token + "] instead"); } } else if (LAST_EXECUTED_FIELD.match(currentFieldName)) { if (token.isValue()) { lastExecuted = parseDate(currentFieldName, token, parser); } else { - throw new AlertsException("expecting field [" + currentFieldName + "] to hold a date value, found [" + token + "] instead"); + throw new WatcherException("expecting field [" + currentFieldName + "] to hold a date value, found [" + token + "] instead"); } } else if (LAST_THROTTLED_FIELD.match(currentFieldName)) { if (token == XContentParser.Token.START_OBJECT) { @@ -523,13 +525,13 @@ public class Alert implements Scheduler.Job, ToXContent { } else if (REASON_FIELD.match(currentFieldName)) { reason = parser.text(); } else { - throw new AlertsException("unknown filed [" + currentFieldName + "] in alert status throttle entry"); + throw new WatcherException("unknown filed [" + currentFieldName + "] in watch status throttle entry"); } } } lastThrottle = new Throttle(timestamp, reason); } else { - throw new AlertsException("expecting field [" + currentFieldName + "] to be an object, found [" + token + "] instead"); + throw new WatcherException("expecting field [" + currentFieldName + "] to be an object, found [" + token + "] instead"); } } else if (ACK_FIELD.match(currentFieldName)) { if (token == XContentParser.Token.START_OBJECT) { @@ -544,13 +546,13 @@ public class Alert implements Scheduler.Job, ToXContent { } else if (STATE_FIELD.match(currentFieldName)) { state = AckStatus.State.valueOf(parser.text().toUpperCase(Locale.ROOT)); } else { - throw new AlertsException("unknown filed [" + currentFieldName + "] in alert status throttle entry"); + throw new WatcherException("unknown filed [" + currentFieldName + "] in watch status throttle entry"); } } } ackStatus = new AckStatus(state, timestamp); } else { - throw new AlertsException("expecting field [" + currentFieldName + "] to be an object, found [" + token + "] instead"); + throw new WatcherException("expecting field [" + currentFieldName + "] to be an object, found [" + token + "] instead"); } } } diff --git a/src/main/java/org/elasticsearch/alerts/AlertExecution.java b/src/main/java/org/elasticsearch/watcher/watch/WatchExecution.java similarity index 82% rename from src/main/java/org/elasticsearch/alerts/AlertExecution.java rename to src/main/java/org/elasticsearch/watcher/watch/WatchExecution.java index 28d9368f931..40a7d9071bb 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertExecution.java +++ b/src/main/java/org/elasticsearch/watcher/watch/WatchExecution.java @@ -3,17 +3,18 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; -import org.elasticsearch.alerts.actions.Action; -import org.elasticsearch.alerts.actions.ActionRegistry; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.ConditionRegistry; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.InputRegistry; -import org.elasticsearch.alerts.throttle.Throttler; -import org.elasticsearch.alerts.transform.Transform; -import org.elasticsearch.alerts.transform.TransformRegistry; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.ActionRegistry; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionRegistry; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.InputRegistry; +import org.elasticsearch.watcher.throttle.Throttler; +import org.elasticsearch.watcher.transform.Transform; +import org.elasticsearch.watcher.transform.TransformRegistry; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.xcontent.ToXContent; @@ -27,7 +28,7 @@ import java.util.Map; /** * */ -public class AlertExecution implements ToXContent { +public class WatchExecution implements ToXContent { private final Input.Result inputResult; private final Condition.Result conditionResult; @@ -35,11 +36,11 @@ public class AlertExecution implements ToXContent { private final @Nullable Transform.Result transformResult; private final Map actionsResults; - public AlertExecution(ExecutionContext context) { + public WatchExecution(WatchExecutionContext context) { this(context.inputResult(), context.conditionResult(), context.throttleResult(), context.transformResult(), context.actionsResults()); } - AlertExecution(Input.Result inputResult, Condition.Result conditionResult, Throttler.Result throttleResult, @Nullable Transform.Result transformResult, Map actionsResults) { + WatchExecution(Input.Result inputResult, Condition.Result conditionResult, Throttler.Result throttleResult, @Nullable Transform.Result transformResult, Map actionsResults) { this.inputResult = inputResult; this.conditionResult = conditionResult; this.throttleResult = throttleResult; @@ -104,7 +105,7 @@ public class AlertExecution implements ToXContent { public static final ParseField THROTTLED = new ParseField("throttled"); public static final ParseField THROTTLE_REASON = new ParseField("throttle_reason"); - public static AlertExecution parse(XContentParser parser, ConditionRegistry conditionRegistry, ActionRegistry actionRegistry, + public static WatchExecution parse(XContentParser parser, ConditionRegistry conditionRegistry, ActionRegistry actionRegistry, InputRegistry inputRegistry, TransformRegistry transformRegistry) throws IOException { boolean throttled = false; String throttleReason = null; @@ -124,7 +125,7 @@ public class AlertExecution implements ToXContent { } else if (THROTTLED.match(currentFieldName)) { throttled = parser.booleanValue(); } else { - throw new AlertsException("unable to parse alert run. unexpected field [" + currentFieldName + "]"); + throw new WatcherException("unable to parse watch execution. unexpected field [" + currentFieldName + "]"); } } else if (token == XContentParser.Token.START_OBJECT) { if (INPUT_RESULT_FIELD.match(currentFieldName)) { @@ -134,21 +135,21 @@ public class AlertExecution implements ToXContent { } else if (Transform.Parser.TRANSFORM_RESULT_FIELD.match(currentFieldName)) { transformResult = transformRegistry.parseResult(parser); } else { - throw new AlertsException("unable to parse alert run. unexpected field [" + currentFieldName + "]"); + throw new WatcherException("unable to parse watch execution. unexpected field [" + currentFieldName + "]"); } } else if (token == XContentParser.Token.START_ARRAY) { if (ACTIONS_RESULTS.match(currentFieldName)) { actionResults = parseActionResults(parser, actionRegistry); } else { - throw new AlertsException("unable to parse alert run. unexpected field [" + currentFieldName + "]"); + throw new WatcherException("unable to parse watch execution. unexpected field [" + currentFieldName + "]"); } } else { - throw new AlertsException("unable to parse alert run. unexpected token [" + token + "]"); + throw new WatcherException("unable to parse watch execution. unexpected token [" + token + "]"); } } Throttler.Result throttleResult = throttled ? Throttler.Result.throttle(throttleReason) : Throttler.Result.NO; - return new AlertExecution(inputResult, conditionResult, throttleResult, transformResult, actionResults); + return new WatchExecution(inputResult, conditionResult, throttleResult, transformResult, actionResults); } diff --git a/src/main/java/org/elasticsearch/alerts/ExecutionContext.java b/src/main/java/org/elasticsearch/watcher/watch/WatchExecutionContext.java similarity index 75% rename from src/main/java/org/elasticsearch/alerts/ExecutionContext.java rename to src/main/java/org/elasticsearch/watcher/watch/WatchExecutionContext.java index e5a32bf99a0..1dbff27429a 100644 --- a/src/main/java/org/elasticsearch/alerts/ExecutionContext.java +++ b/src/main/java/org/elasticsearch/watcher/watch/WatchExecutionContext.java @@ -3,13 +3,13 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; -import org.elasticsearch.alerts.actions.Action; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.throttle.Throttler; -import org.elasticsearch.alerts.transform.Transform; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.throttle.Throttler; +import org.elasticsearch.watcher.transform.Transform; import org.elasticsearch.common.joda.time.DateTime; import java.util.HashMap; @@ -18,10 +18,10 @@ import java.util.Map; /** * */ -public class ExecutionContext { +public class WatchExecutionContext { private final String id; - private final Alert alert; + private final Watch watch; private final DateTime executionTime; private final DateTime fireTime; private final DateTime scheduledTime; @@ -34,9 +34,9 @@ public class ExecutionContext { private Payload payload; - public ExecutionContext(String id, Alert alert, DateTime executionTime, DateTime fireTime, DateTime scheduledTime) { + public WatchExecutionContext(String id, Watch watch, DateTime executionTime, DateTime fireTime, DateTime scheduledTime) { this.id = id; - this.alert = alert; + this.watch = watch; this.executionTime = executionTime; this.fireTime = fireTime; this.scheduledTime = scheduledTime; @@ -46,8 +46,8 @@ public class ExecutionContext { return id; } - public Alert alert() { - return alert; + public Watch watch() { + return watch; } public DateTime executionTime() { @@ -76,7 +76,7 @@ public class ExecutionContext { } public void onConditionResult(Condition.Result conditionResult) { - alert.status().onCheck(conditionResult.met(), executionTime); + watch.status().onCheck(conditionResult.met(), executionTime); this.conditionResult = conditionResult; } @@ -87,9 +87,9 @@ public class ExecutionContext { public void onThrottleResult(Throttler.Result throttleResult) { this.throttleResult = throttleResult; if (throttleResult.throttle()) { - alert.status().onThrottle(executionTime, throttleResult.reason()); + watch.status().onThrottle(executionTime, throttleResult.reason()); } else { - alert.status().onExecution(executionTime); + watch.status().onExecution(executionTime); } } @@ -114,8 +114,8 @@ public class ExecutionContext { return actionsResults; } - public AlertExecution finish() { - return new AlertExecution(this); + public WatchExecution finish() { + return new WatchExecution(this); } } diff --git a/src/main/java/org/elasticsearch/alerts/AlertLockService.java b/src/main/java/org/elasticsearch/watcher/watch/WatchLockService.java similarity index 62% rename from src/main/java/org/elasticsearch/alerts/AlertLockService.java rename to src/main/java/org/elasticsearch/watcher/watch/WatchLockService.java index 97577ebead0..2077344bee8 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertLockService.java +++ b/src/main/java/org/elasticsearch/watcher/watch/WatchLockService.java @@ -3,7 +3,7 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.common.util.concurrent.KeyedLock; @@ -13,9 +13,9 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * */ -public class AlertLockService { +public class WatchLockService { - private final KeyedLock alertLock = new KeyedLock<>(); + private final KeyedLock watchLocks = new KeyedLock<>(); private final AtomicBoolean running = new AtomicBoolean(false); public Lock acquire(String name) { @@ -23,8 +23,8 @@ public class AlertLockService { throw new ElasticsearchIllegalStateException("not started"); } - alertLock.acquire(name); - return new Lock(name, alertLock); + watchLocks.acquire(name); + return new Lock(name, watchLocks); } public void start() { @@ -36,14 +36,14 @@ public class AlertLockService { public void stop() { if (running.compareAndSet(true, false)) { // It can happen we have still ongoing operations and we wait those operations to finish to avoid - // that AlertManager or any of its components end up in a illegal state after the state as been set to stopped. + // that watch service or any of its components end up in a illegal state after the state as been set to stopped. // - // For example: An alert action entry may be added while we stopping alerting if we don't wait for - // ongoing operations to complete. Resulting in once the alert service starts again that more than - // expected alert action entries are processed. + // For example: A watch action entry may be added while we stopping watcher if we don't wait for + // ongoing operations to complete. Resulting in once the watch service starts again that more than + // expected watch records are processed. // // Note: new operations will fail now because the running has been set to false - while (alertLock.hasLockedKeys()) { + while (watchLocks.hasLockedKeys()) { try { Thread.sleep(100); } catch (InterruptedException ie) { @@ -52,23 +52,23 @@ public class AlertLockService { } } - KeyedLock getAlertLock() { - return alertLock; + KeyedLock getWatchLocks() { + return watchLocks; } public static class Lock { private final String name; - private final KeyedLock alertLock; + private final KeyedLock watchLocks; - private Lock(String name, KeyedLock alertLock) { + private Lock(String name, KeyedLock watchLocks) { this.name = name; - this.alertLock = alertLock; + this.watchLocks = watchLocks; } public void release() { - alertLock.release(name); + watchLocks.release(name); } } } diff --git a/src/main/java/org/elasticsearch/watcher/watch/WatchModule.java b/src/main/java/org/elasticsearch/watcher/watch/WatchModule.java new file mode 100644 index 00000000000..1a83ff432ac --- /dev/null +++ b/src/main/java/org/elasticsearch/watcher/watch/WatchModule.java @@ -0,0 +1,22 @@ +/* + * 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.watcher.watch; + +import org.elasticsearch.common.inject.AbstractModule; + +/** + * + */ +public class WatchModule extends AbstractModule { + + @Override + protected void configure() { + bind(Watch.Parser.class).asEagerSingleton(); + bind(WatchLockService.class).asEagerSingleton(); + bind(WatchService.class).asEagerSingleton(); + bind(WatchStore.class).asEagerSingleton(); + } +} diff --git a/src/main/java/org/elasticsearch/alerts/AlertsService.java b/src/main/java/org/elasticsearch/watcher/watch/WatchService.java similarity index 57% rename from src/main/java/org/elasticsearch/alerts/AlertsService.java rename to src/main/java/org/elasticsearch/watcher/watch/WatchService.java index 4fc6712bb4e..d8587236a9f 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertsService.java +++ b/src/main/java/org/elasticsearch/watcher/watch/WatchService.java @@ -3,14 +3,15 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.alerts.history.HistoryService; -import org.elasticsearch.alerts.scheduler.Scheduler; -import org.elasticsearch.alerts.support.Callback; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.history.HistoryService; +import org.elasticsearch.watcher.scheduler.Scheduler; +import org.elasticsearch.watcher.support.Callback; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.component.AbstractComponent; @@ -21,31 +22,31 @@ import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReference; -public class AlertsService extends AbstractComponent { +public class WatchService extends AbstractComponent { private final Scheduler scheduler; - private final AlertsStore alertsStore; - private final AlertLockService alertLockService; + private final WatchStore watchStore; + private final WatchLockService watchLockService; private final HistoryService historyService; private final AtomicReference state = new AtomicReference<>(State.STOPPED); @Inject - public AlertsService(Settings settings, Scheduler scheduler, AlertsStore alertsStore, HistoryService historyService, - AlertLockService alertLockService) { + public WatchService(Settings settings, Scheduler scheduler, WatchStore watchStore, HistoryService historyService, + WatchLockService watchLockService) { super(settings); this.scheduler = scheduler; - this.alertsStore = alertsStore; - this.alertLockService = alertLockService; + this.watchStore = watchStore; + this.watchLockService = watchLockService; this.historyService = historyService; } public void start(ClusterState clusterState) { if (state.compareAndSet(State.STOPPED, State.STARTING)) { - logger.info("starting alert service..."); - alertLockService.start(); + logger.info("starting watch service..."); + watchLockService.start(); - // Try to load alert store before the action service, b/c action depends on alert store - alertsStore.start(clusterState, new Callback(){ + // Try to load watch store before the history service, b/c action depends on watch store + watchStore.start(clusterState, new Callback(){ @Override public void onSuccess(ClusterState clusterState) { @@ -53,21 +54,21 @@ public class AlertsService extends AbstractComponent { @Override public void onSuccess(ClusterState clusterState) { - scheduler.start(alertsStore.getAlerts().values()); + scheduler.start(watchStore.watches().values()); state.set(State.STARTED); - logger.info("alert service has started"); + logger.info("watch service has started"); } @Override public void onFailure(Throwable e) { - logger.error("failed to start alert service", e); + logger.error("failed to start watch service", e); } }); } @Override public void onFailure(Throwable e) { - logger.error("failed to start alert service", e); + logger.error("failed to start watch service", e); } }); } @@ -75,21 +76,21 @@ public class AlertsService extends AbstractComponent { public void stop() { if (state.compareAndSet(State.STARTED, State.STOPPING)) { - logger.info("stopping alert service..."); - alertLockService.stop(); + logger.info("stopping watch service..."); + watchLockService.stop(); historyService.stop(); scheduler.stop(); - alertsStore.stop(); + watchStore.stop(); state.set(State.STOPPED); - logger.info("alert service has stopped"); + logger.info("watch service has stopped"); } } - public AlertsStore.AlertDelete deleteAlert(String name) throws InterruptedException, ExecutionException { + public WatchStore.WatchDelete deleteWatch(String name) throws InterruptedException, ExecutionException { ensureStarted(); - AlertLockService.Lock lock = alertLockService.acquire(name); + WatchLockService.Lock lock = watchLockService.acquire(name); try { - AlertsStore.AlertDelete delete = alertsStore.deleteAlert(name); + WatchStore.WatchDelete delete = watchStore.delete(name); if (delete.deleteResponse().isFound()) { scheduler.remove(name); } @@ -99,11 +100,11 @@ public class AlertsService extends AbstractComponent { } } - public IndexResponse putAlert(String name, BytesReference alertSource) { + public IndexResponse putWatch(String name, BytesReference watchSource) { ensureStarted(); - AlertLockService.Lock lock = alertLockService.acquire(name); + WatchLockService.Lock lock = watchLockService.acquire(name); try { - AlertsStore.AlertPut result = alertsStore.putAlert(name, alertSource); + WatchStore.WatchPut result = watchStore.put(name, watchSource); if (result.previous() == null || !result.previous().schedule().equals(result.current().schedule())) { scheduler.add(result.current()); } @@ -116,8 +117,8 @@ public class AlertsService extends AbstractComponent { /** * TODO: add version, fields, etc support that the core get api has as well. */ - public Alert getAlert(String name) { - return alertsStore.getAlert(name); + public Watch getWatch(String name) { + return watchStore.get(name); } public State state() { @@ -125,32 +126,32 @@ public class AlertsService extends AbstractComponent { } /** - * Acks the alert if needed + * Acks the watch if needed */ - public Alert.Status ackAlert(String name) { + public Watch.Status ackWatch(String name) { ensureStarted(); - AlertLockService.Lock lock = alertLockService.acquire(name); + WatchLockService.Lock lock = watchLockService.acquire(name); try { - Alert alert = alertsStore.getAlert(name); - if (alert == null) { - throw new AlertsException("alert [" + name + "] does not exist"); + Watch watch = watchStore.get(name); + if (watch == null) { + throw new WatcherException("watch [" + name + "] does not exist"); } - if (alert.ack()) { + if (watch.ack()) { try { - alertsStore.updateAlertStatus(alert); + watchStore.updateStatus(watch); } catch (IOException ioe) { - throw new AlertsException("failed to update the alert on ack", ioe); + throw new WatcherException("failed to update the watch on ack", ioe); } } // we need to create a safe copy of the status - return new Alert.Status(alert.status()); + return new Watch.Status(watch.status()); } finally { lock.release(); } } - public long getNumberOfAlerts() { - return alertsStore.getAlerts().size(); + public long watchesCount() { + return watchStore.watches().size(); } private void ensureStarted() { @@ -160,27 +161,27 @@ public class AlertsService extends AbstractComponent { } /** - * Encapsulates the state of the alerts plugin. + * Encapsulates the state of the watcher plugin. */ public static enum State { /** - * The alerts plugin is not running and not functional. + * The watcher plugin is not running and not functional. */ STOPPED(0), /** - * The alerts plugin is performing the necessary operations to get into a started state. + * The watcher plugin is performing the necessary operations to get into a started state. */ STARTING(1), /** - * The alerts plugin is running and completely functional. + * The watcher plugin is running and completely functional. */ STARTED(2), /** - * The alerts plugin is shutting down and not functional. + * The watcher plugin is shutting down and not functional. */ STOPPING(3); @@ -205,7 +206,7 @@ public class AlertsService extends AbstractComponent { case 3: return STOPPING; default: - throw new AlertsException("unknown id alerts service state id [" + id + "]"); + throw new WatcherException("unknown watch service state id [" + id + "]"); } } } diff --git a/src/main/java/org/elasticsearch/alerts/AlertsStore.java b/src/main/java/org/elasticsearch/watcher/watch/WatchStore.java similarity index 57% rename from src/main/java/org/elasticsearch/alerts/AlertsStore.java rename to src/main/java/org/elasticsearch/watcher/watch/WatchStore.java index 192e29de12a..12137fb3a2c 100644 --- a/src/main/java/org/elasticsearch/alerts/AlertsStore.java +++ b/src/main/java/org/elasticsearch/watcher/watch/WatchStore.java @@ -3,7 +3,7 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalStateException; @@ -14,9 +14,10 @@ import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.*; -import org.elasticsearch.alerts.support.Callback; -import org.elasticsearch.alerts.support.TemplateUtils; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.support.Callback; +import org.elasticsearch.watcher.support.TemplateUtils; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; @@ -40,19 +41,19 @@ import java.util.concurrent.atomic.AtomicInteger; /** */ -public class AlertsStore extends AbstractComponent { +public class WatchStore extends AbstractComponent { - public static final String ALERT_INDEX = ".alerts"; - public static final String ALERT_INDEX_TEMPLATE = "alerts"; - public static final String ALERT_TYPE = "alert"; + public static final String INDEX = ".watches"; + public static final String INDEX_TEMPLATE = "watches"; + public static final String DOC_TYPE = "watch"; private final ClientProxy client; private final TemplateUtils templateUtils; - private final Alert.Parser alertParser; + private final Watch.Parser watchParser; private final ClusterService clusterService; private final ThreadPool threadPool; - private final ConcurrentMap alertMap; + private final ConcurrentMap watches; private final AtomicBoolean started = new AtomicBoolean(false); private final AtomicInteger initializationRetries = new AtomicInteger(); @@ -60,15 +61,15 @@ public class AlertsStore extends AbstractComponent { private final TimeValue scrollTimeout; @Inject - public AlertsStore(Settings settings, ClientProxy client, TemplateUtils templateUtils, Alert.Parser alertParser, - ClusterService clusterService, ThreadPool threadPool) { + public WatchStore(Settings settings, ClientProxy client, TemplateUtils templateUtils, Watch.Parser watchParser, + ClusterService clusterService, ThreadPool threadPool) { super(settings); this.client = client; this.templateUtils = templateUtils; - this.alertParser = alertParser; + this.watchParser = watchParser; this.clusterService = clusterService; this.threadPool = threadPool; - this.alertMap = ConcurrentCollections.newConcurrentMap(); + this.watches = ConcurrentCollections.newConcurrentMap(); this.scrollTimeout = componentSettings.getAsTime("scroll.timeout", TimeValue.timeValueSeconds(30)); this.scrollSize = componentSettings.getAsInt("scroll.size", 100); @@ -80,31 +81,31 @@ public class AlertsStore extends AbstractComponent { return; } - IndexMetaData alertIndexMetaData = state.getMetaData().index(ALERT_INDEX); - if (alertIndexMetaData == null) { - logger.trace("alerts index [{}] was not found. skipping alerts loading...", ALERT_INDEX); - templateUtils.ensureIndexTemplateIsLoaded(state, ALERT_INDEX_TEMPLATE); + IndexMetaData watchesIndexMetaData = state.getMetaData().index(INDEX); + if (watchesIndexMetaData == null) { + logger.trace("watches index [{}] was not found. skipping loading watches...", INDEX); + templateUtils.ensureIndexTemplateIsLoaded(state, INDEX_TEMPLATE); started.set(true); callback.onSuccess(state); return; } - if (state.routingTable().index(ALERT_INDEX).allPrimaryShardsActive()) { - logger.debug("alerts index [{}] found with all active primary shards. loading alerts...", ALERT_INDEX); + if (state.routingTable().index(INDEX).allPrimaryShardsActive()) { + logger.debug("watches index [{}] found with all active primary shards. loading watches...", INDEX); try { - int count = loadAlerts(alertIndexMetaData.numberOfShards()); - logger.debug("loaded [{}] alerts from the alert index [{}]", count, ALERT_INDEX); + int count = loadWatches(watchesIndexMetaData.numberOfShards()); + logger.debug("loaded [{}] watches from the watches index [{}]", count, INDEX); } catch (Exception e) { - logger.debug("failed to load alerts for alert index [{}]. scheduled to retry alert loading...", e, ALERT_INDEX); - alertMap.clear(); + logger.debug("failed to load watches for watch index [{}]. scheduled to retry watches loading...", e, INDEX); + watches.clear(); retry(callback); return; } - templateUtils.ensureIndexTemplateIsLoaded(state, ALERT_INDEX_TEMPLATE); + templateUtils.ensureIndexTemplateIsLoaded(state, INDEX_TEMPLATE); started.set(true); callback.onSuccess(state); } else { - logger.debug("not all primary shards of the alerts index [{}] are started. scheduled to retry alert loading...", ALERT_INDEX); + logger.debug("not all primary shards of the watches index [{}] are started. scheduled to retry loading watches...", INDEX); retry(callback); } } @@ -115,79 +116,79 @@ public class AlertsStore extends AbstractComponent { public void stop() { if (started.compareAndSet(true, false)) { - alertMap.clear(); - logger.info("stopped alerts store"); + watches.clear(); + logger.info("stopped watch store"); } } /** - * Returns the alert with the specified name otherwise null is returned. + * Returns the watch with the specified name otherwise null is returned. */ - public Alert getAlert(String name) { + public Watch get(String name) { ensureStarted(); - return alertMap.get(name); + return watches.get(name); } /** - * Creates an alert with the specified name and source. If an alert with the specified name already exists it will + * Creates an watch with the specified name and source. If an watch with the specified name already exists it will * get overwritten. */ - public AlertPut putAlert(String alertName, BytesReference alertSource) { + public WatchPut put(String name, BytesReference source) { ensureStarted(); - Alert alert = alertParser.parse(alertName, false, alertSource); - IndexRequest indexRequest = createIndexRequest(alertName, alertSource); + Watch watch = watchParser.parse(name, false, source); + IndexRequest indexRequest = createIndexRequest(name, source); IndexResponse response = client.index(indexRequest).actionGet(); - alert.status().version(response.getVersion()); - Alert previous = alertMap.put(alertName, alert); - return new AlertPut(previous, alert, response); + watch.status().version(response.getVersion()); + Watch previous = watches.put(name, watch); + return new WatchPut(previous, watch, response); } /** - * Updates and persists the status of the given alert + * Updates and persists the status of the given watch */ - void updateAlertStatus(Alert alert) throws IOException { - // at the moment we store the status together with the alert, - // so we just need to update the alert itself - // TODO: consider storing the status in a different documment (alert_status doc) (must smaller docs... faster for frequent updates) - updateAlert(alert); + void updateStatus(Watch watch) throws IOException { + // at the moment we store the status together with the watch, + // so we just need to update the watch itself + // TODO: consider storing the status in a different documment (watch_status doc) (must smaller docs... faster for frequent updates) + update(watch); } /** - * Updates and persists the given alert + * Updates and persists the given watch */ - void updateAlert(Alert alert) throws IOException { + void update(Watch watch) throws IOException { ensureStarted(); - assert alert == alertMap.get(alert.name()) : "update alert can only be applied to an already loaded alert"; - BytesReference source = JsonXContent.contentBuilder().value(alert).bytes(); - IndexResponse response = client.index(createIndexRequest(alert.name(), source)).actionGet(); - alert.status().version(response.getVersion()); - // Don't need to update the alertMap, since we are working on an instance from it. + assert watch == watches.get(watch.name()) : "update watch can only be applied to an already loaded watch"; + BytesReference source = JsonXContent.contentBuilder().value(watch).bytes(); + IndexResponse response = client.index(createIndexRequest(watch.name(), source)).actionGet(); + watch.status().version(response.getVersion()); + // Don't need to update the watches, since we are working on an instance from it. } /** - * Deletes the alert with the specified name if exists + * Deletes the watch with the specified name if exists */ - public AlertDelete deleteAlert(String name) { + public WatchDelete delete(String name) { ensureStarted(); - Alert alert = alertMap.remove(name); - // even if the alert was not found in the alert map, we should still try to delete it + Watch watch = watches.remove(name); + // even if the watch was not found in the watch map, we should still try to delete it // from the index, just to make sure we don't leave traces of it - DeleteRequest request = new DeleteRequest(ALERT_INDEX, ALERT_TYPE, name); - if (alert != null) { - request.version(alert.status().version()); + DeleteRequest request = new DeleteRequest(INDEX, DOC_TYPE, name); + if (watch != null) { + request.version(watch.status().version()); } DeleteResponse response = client.delete(request).actionGet(); - return new AlertDelete(response); + return new WatchDelete(response); } - public ConcurrentMap getAlerts() { - return alertMap; + public ConcurrentMap watches() { + return watches; } - IndexRequest createIndexRequest(String alertName, BytesReference alertSource) { - IndexRequest indexRequest = new IndexRequest(ALERT_INDEX, ALERT_TYPE, alertName); + IndexRequest createIndexRequest(String name, BytesReference source) { + IndexRequest indexRequest = new IndexRequest(INDEX, DOC_TYPE, name); indexRequest.listenerThreaded(false); - indexRequest.source(alertSource, false); + indexRequest.source(source, false); return indexRequest; } @@ -196,9 +197,9 @@ public class AlertsStore extends AbstractComponent { @Override public void clusterChanged(ClusterChangedEvent event) { final ClusterState state = event.state(); - IndexMetaData alertIndexMetaData = state.getMetaData().index(ALERT_INDEX); - if (alertIndexMetaData != null) { - if (state.routingTable().index(ALERT_INDEX).allPrimaryShardsActive()) { + IndexMetaData watchesIndexMetaData = state.getMetaData().index(INDEX); + if (watchesIndexMetaData != null) { + if (state.routingTable().index(INDEX).allPrimaryShardsActive()) { // Remove listener, so that it doesn't get called on the next cluster state update: assert initializationRetries.decrementAndGet() == 0 : "Only one retry can run at the time"; clusterService.remove(this); @@ -222,19 +223,19 @@ public class AlertsStore extends AbstractComponent { } /** - * scrolls all the alert documents in the alerts index, parses them, and loads them into + * scrolls all the watch documents in the watches index, parses them, and loads them into * the given map. */ - int loadAlerts(int numPrimaryShards) { - assert alertMap.isEmpty() : "no alerts should reside, but there are [" + alertMap.size() + "] alerts."; - RefreshResponse refreshResponse = client.refresh(new RefreshRequest(ALERT_INDEX)); + int loadWatches(int numPrimaryShards) { + assert watches.isEmpty() : "no watches should reside, but there are [" + watches.size() + "] watches."; + RefreshResponse refreshResponse = client.refresh(new RefreshRequest(INDEX)); if (refreshResponse.getSuccessfulShards() < numPrimaryShards) { - throw new AlertsException("not all required shards have been refreshed"); + throw new WatcherException("not all required shards have been refreshed"); } int count = 0; - SearchRequest searchRequest = new SearchRequest(ALERT_INDEX) - .types(ALERT_TYPE) + SearchRequest searchRequest = new SearchRequest(INDEX) + .types(DOC_TYPE) .preference("_primary") .searchType(SearchType.SCAN) .scroll(scrollTimeout) @@ -244,7 +245,7 @@ public class AlertsStore extends AbstractComponent { SearchResponse response = client.search(searchRequest); try { if (response.getTotalShards() != response.getSuccessfulShards()) { - throw new ElasticsearchException("Partial response while loading alerts"); + throw new ElasticsearchException("Partial response while loading watches"); } if (response.getHits().getTotalHits() > 0) { @@ -252,9 +253,9 @@ public class AlertsStore extends AbstractComponent { while (response.getHits().hits().length != 0) { for (SearchHit hit : response.getHits()) { String name = hit.getId(); - Alert alert = alertParser.parse(name, true, hit.getSourceRef()); - alert.status().version(hit.version()); - alertMap.put(name, alert); + Watch watch = watchParser.parse(name, true, hit.getSourceRef()); + watch.status().version(hit.version()); + watches.put(name, watch); count++; } response = client.searchScroll(response.getScrollId(), scrollTimeout); @@ -268,27 +269,27 @@ public class AlertsStore extends AbstractComponent { private void ensureStarted() { if (!started.get()) { - throw new ElasticsearchIllegalStateException("Alert store not started"); + throw new ElasticsearchIllegalStateException("watch store not started"); } } - public class AlertPut { + public class WatchPut { - private final Alert previous; - private final Alert current; + private final Watch previous; + private final Watch current; private final IndexResponse response; - public AlertPut(Alert previous, Alert current, IndexResponse response) { + public WatchPut(Watch previous, Watch current, IndexResponse response) { this.current = current; this.previous = previous; this.response = response; } - public Alert current() { + public Watch current() { return current; } - public Alert previous() { + public Watch previous() { return previous; } @@ -297,11 +298,11 @@ public class AlertsStore extends AbstractComponent { } } - public class AlertDelete { + public class WatchDelete { private final DeleteResponse response; - public AlertDelete(DeleteResponse response) { + public WatchDelete(DeleteResponse response) { this.response = response; } diff --git a/src/main/resources/es-plugin.properties b/src/main/resources/es-plugin.properties index ffd992853f2..589da666a18 100644 --- a/src/main/resources/es-plugin.properties +++ b/src/main/resources/es-plugin.properties @@ -1,2 +1,2 @@ -plugin=org.elasticsearch.alerts.AlertsPlugin +plugin=org.elasticsearch.watcher.WatcherPlugin version=${project.version} \ No newline at end of file diff --git a/src/main/resources/alerthistory.json b/src/main/resources/watch_history.json similarity index 85% rename from src/main/resources/alerthistory.json rename to src/main/resources/watch_history.json index 02159e381a9..8c8d170544a 100644 --- a/src/main/resources/alerthistory.json +++ b/src/main/resources/watch_history.json @@ -1,17 +1,17 @@ { - "template": ".alert_history*", + "template": ".watch_history*", "order": 2147483647, "settings": { "index.number_of_shards": 1, "index.number_of_replicas": 1, - "index.alerts.template_version": 1, + "index.watcher.template_version": 1, "index.mapper.dynamic" : false }, "mappings": { - "fired_alert": { + "watch_record": { "dynamic" : "strict", "properties": { - "alert_name": { + "watch_name": { "type": "string", "index": "not_analyzed" }, @@ -33,7 +33,7 @@ "enabled" : false, "dynamic" : true }, - "alert_execution" : { + "watch_execution" : { "type" : "object", "enabled" : false, "dynamic" : true diff --git a/src/main/resources/alerts-build.properties b/src/main/resources/watcher-build.properties similarity index 100% rename from src/main/resources/alerts-build.properties rename to src/main/resources/watcher-build.properties diff --git a/src/main/resources/alerts.json b/src/main/resources/watches.json similarity index 92% rename from src/main/resources/alerts.json rename to src/main/resources/watches.json index 428f143519c..bc5d2c4a4af 100644 --- a/src/main/resources/alerts.json +++ b/src/main/resources/watches.json @@ -1,14 +1,14 @@ { - "template": ".alerts", + "template": ".watches", "order": 2147483647, "settings": { "index.number_of_shards": 1, "index.number_of_replicas": 1, - "index.alerts.template_version": 1, + "index.watcher.template_version": 1, "index.mapper.dynamic" : false }, "mappings": { - "alert": { + "watch": { "dynamic" : "strict", "properties": { "schedule": { diff --git a/src/test/java/org/elasticsearch/alerts/AlertServiceTests.java b/src/test/java/org/elasticsearch/alerts/AlertServiceTests.java deleted file mode 100644 index ff020690dd6..00000000000 --- a/src/test/java/org/elasticsearch/alerts/AlertServiceTests.java +++ /dev/null @@ -1,171 +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.alerts; - -import org.elasticsearch.action.delete.DeleteResponse; -import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.alerts.history.HistoryService; -import org.elasticsearch.alerts.scheduler.Scheduler; -import org.elasticsearch.alerts.scheduler.schedule.Schedule; -import org.elasticsearch.common.bytes.BytesArray; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.settings.ImmutableSettings; -import org.elasticsearch.test.ElasticsearchTestCase; -import org.junit.Before; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.util.concurrent.atomic.AtomicReference; - -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.sameInstance; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -/** - */ -public class AlertServiceTests extends ElasticsearchTestCase { - - private Scheduler scheduler; - private AlertsStore alertsStore; - private AlertsService alertsService; - private HistoryService historyService; - private AlertLockService alertLockService; - - @Before - public void init() throws Exception { - scheduler = mock(Scheduler.class); - alertsStore = mock(AlertsStore.class); - historyService = mock(HistoryService.class); - alertLockService = mock(AlertLockService.class); - alertsService = new AlertsService(ImmutableSettings.EMPTY, scheduler, alertsStore, historyService, alertLockService); - Field field = AlertsService.class.getDeclaredField("state"); - field.setAccessible(true); - AtomicReference state = (AtomicReference) field.get(alertsService); - state.set(AlertsService.State.STARTED); - } - - @Test - public void testPutAlert() { - IndexResponse indexResponse = mock(IndexResponse.class); - Alert alert = mock(Alert.class); - AlertsStore.AlertPut alertPut = mock(AlertsStore.AlertPut.class); - when(alertPut.indexResponse()).thenReturn(indexResponse); - when(alertPut.current()).thenReturn(alert); - - AlertLockService.Lock lock = mock(AlertLockService.Lock.class); - when(alertLockService.acquire(any(String.class))).thenReturn(lock); - when(alertsStore.putAlert(any(String.class), any(BytesReference.class))).thenReturn(alertPut); - IndexResponse response = alertsService.putAlert("_name", new BytesArray("{}")); - assertThat(response, sameInstance(indexResponse)); - - verify(scheduler, times(1)).add(any(Scheduler.Job.class)); - } - - @Test - public void testPutAlert_notSchedule() { - Schedule schedule = mock(Schedule.class); - - IndexResponse indexResponse = mock(IndexResponse.class); - Alert alert = mock(Alert.class); - when(alert.schedule()).thenReturn(schedule); - AlertsStore.AlertPut alertPut = mock(AlertsStore.AlertPut.class); - when(alertPut.indexResponse()).thenReturn(indexResponse); - when(alertPut.current()).thenReturn(alert); - Alert previousAlert = mock(Alert.class); - when(previousAlert.schedule()).thenReturn(schedule); - when(alertPut.previous()).thenReturn(previousAlert); - - AlertLockService.Lock lock = mock(AlertLockService.Lock.class); - when(alertLockService.acquire(any(String.class))).thenReturn(lock); - when(alertsStore.putAlert(any(String.class), any(BytesReference.class))).thenReturn(alertPut); - IndexResponse response = alertsService.putAlert("_name", new BytesArray("{}")); - assertThat(response, sameInstance(indexResponse)); - - verifyZeroInteractions(scheduler); - } - - @Test - public void testDeleteAlert() throws Exception { - AlertLockService.Lock lock = mock(AlertLockService.Lock.class); - when(alertLockService.acquire("_name")).thenReturn(lock); - - AlertsStore.AlertDelete expectedAlertDelete = mock(AlertsStore.AlertDelete.class); - DeleteResponse deleteResponse = mock(DeleteResponse.class); - when(deleteResponse.isFound()).thenReturn(true); - when(expectedAlertDelete.deleteResponse()).thenReturn(deleteResponse); - when(alertsStore.deleteAlert("_name")).thenReturn(expectedAlertDelete); - AlertsStore.AlertDelete alertDelete = alertsService.deleteAlert("_name"); - - assertThat(alertDelete, sameInstance(expectedAlertDelete)); - verify(scheduler, times(1)).remove("_name"); - } - - @Test - public void testDeleteAlert_notFound() throws Exception { - AlertLockService.Lock lock = mock(AlertLockService.Lock.class); - when(alertLockService.acquire("_name")).thenReturn(lock); - - AlertsStore.AlertDelete expectedAlertDelete = mock(AlertsStore.AlertDelete.class); - DeleteResponse deleteResponse = mock(DeleteResponse.class); - when(deleteResponse.isFound()).thenReturn(false); - when(expectedAlertDelete.deleteResponse()).thenReturn(deleteResponse); - when(alertsStore.deleteAlert("_name")).thenReturn(expectedAlertDelete); - AlertsStore.AlertDelete alertDelete = alertsService.deleteAlert("_name"); - - assertThat(alertDelete, sameInstance(expectedAlertDelete)); - verifyZeroInteractions(scheduler); - } - - @Test - public void testAckAlert() throws Exception { - AlertLockService.Lock lock = mock(AlertLockService.Lock.class); - when(alertLockService.acquire("_name")).thenReturn(lock); - Alert alert = mock(Alert.class); - when(alert.ack()).thenReturn(true); - Alert.Status status = new Alert.Status(); - when(alert.status()).thenReturn(status); - when(alertsStore.getAlert("_name")).thenReturn(alert); - - Alert.Status result = alertsService.ackAlert("_name"); - assertThat(result, not(sameInstance(status))); - - verify(alertsStore, times(1)).updateAlertStatus(alert); - } - - @Test - public void testAckAlert_notAck() throws Exception { - AlertLockService.Lock lock = mock(AlertLockService.Lock.class); - when(alertLockService.acquire("_name")).thenReturn(lock); - Alert alert = mock(Alert.class); - when(alert.ack()).thenReturn(false); - Alert.Status status = new Alert.Status(); - when(alert.status()).thenReturn(status); - when(alertsStore.getAlert("_name")).thenReturn(alert); - - Alert.Status result = alertsService.ackAlert("_name"); - assertThat(result, not(sameInstance(status))); - - verify(alertsStore, never()).updateAlertStatus(alert); - } - - @Test - public void testAckAlert_noAlert() throws Exception { - AlertLockService.Lock lock = mock(AlertLockService.Lock.class); - when(alertLockService.acquire("_name")).thenReturn(lock); - when(alertsStore.getAlert("_name")).thenReturn(null); - - try { - alertsService.ackAlert("_name"); - fail(); - } catch (AlertsException e) { - // expected - } - - verify(alertsStore, never()).updateAlertStatus(any(Alert.class)); - } - -} diff --git a/src/test/java/org/elasticsearch/alerts/history/FiredAlertTests.java b/src/test/java/org/elasticsearch/alerts/history/FiredAlertTests.java deleted file mode 100644 index 057d0e30cfc..00000000000 --- a/src/test/java/org/elasticsearch/alerts/history/FiredAlertTests.java +++ /dev/null @@ -1,97 +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.alerts.history; - -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.AlertExecution; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.actions.email.EmailAction; -import org.elasticsearch.alerts.actions.webhook.WebhookAction; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.simple.AlwaysFalseCondition; -import org.elasticsearch.alerts.condition.simple.AlwaysTrueCondition; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.simple.SimpleInput; -import org.elasticsearch.alerts.test.AbstractAlertsIntegrationTests; -import org.elasticsearch.alerts.test.AlertsTestUtils; -import org.elasticsearch.alerts.throttle.Throttler; -import org.elasticsearch.common.joda.time.DateTime; -import org.elasticsearch.common.xcontent.ToXContent; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.common.xcontent.XContentFactory; -import org.junit.Test; - -import static org.hamcrest.Matchers.equalTo; - -/** - */ -public class FiredAlertTests extends AbstractAlertsIntegrationTests { - - @Test - public void testParser() throws Exception { - Alert alert = AlertsTestUtils.createTestAlert("fired_test", scriptService(), httpClient(), noopEmailService(), logger); - FiredAlert firedAlert = new FiredAlert(alert, new DateTime(), new DateTime()); - XContentBuilder jsonBuilder = XContentFactory.jsonBuilder(); - firedAlert.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS); - FiredAlert parsedFiredAlert = firedAlertParser().parse(jsonBuilder.bytes(), firedAlert.id(), 0); - - XContentBuilder jsonBuilder2 = XContentFactory.jsonBuilder(); - parsedFiredAlert.toXContent(jsonBuilder2, ToXContent.EMPTY_PARAMS); - - assertThat(jsonBuilder.bytes().toUtf8(), equalTo(jsonBuilder2.bytes().toUtf8())); - } - - @Test - public void testParser_WithSealedFiredAlert() throws Exception { - Alert alert = AlertsTestUtils.createTestAlert("fired_test", scriptService(), httpClient(), noopEmailService(), logger); - FiredAlert firedAlert = new FiredAlert(alert, new DateTime(), new DateTime()); - ExecutionContext ctx = new ExecutionContext(firedAlert.id(), alert, new DateTime(), new DateTime(), new DateTime()); - ctx.onActionResult(new EmailAction.Result.Failure("failed to send because blah")); - ctx.onActionResult(new WebhookAction.Result.Executed(300, "http://localhost:8000/alertfoo", "{'awesome' : 'us'}")); - Input.Result inputResult = new SimpleInput.Result(SimpleInput.TYPE, new Payload.Simple()); - Condition.Result conditionResult = AlwaysTrueCondition.RESULT; - ctx.onThrottleResult(Throttler.NO_THROTTLE.throttle(ctx)); - ctx.onInputResult(inputResult); - ctx.onConditionResult(conditionResult); - firedAlert.update(new AlertExecution(ctx)); - - XContentBuilder jsonBuilder = XContentFactory.jsonBuilder(); - firedAlert.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS); - FiredAlert parsedFiredAlert = firedAlertParser().parse(jsonBuilder.bytes(), firedAlert.id(), 0); - - XContentBuilder jsonBuilder2 = XContentFactory.jsonBuilder(); - parsedFiredAlert.toXContent(jsonBuilder2, ToXContent.EMPTY_PARAMS); - - assertThat(jsonBuilder.bytes().toUtf8(), equalTo(jsonBuilder2.bytes().toUtf8())); - } - - @Test - public void testParser_WithSealedFiredAlert_WithScriptSearchCondition() throws Exception { - Alert alert = AlertsTestUtils.createTestAlert("fired_test", scriptService(), httpClient(), noopEmailService(), logger); - FiredAlert firedAlert = new FiredAlert(alert, new DateTime(), new DateTime()); - ExecutionContext ctx = new ExecutionContext(firedAlert.id(), alert, new DateTime(), new DateTime(), new DateTime()); - ctx.onActionResult(new EmailAction.Result.Failure("failed to send because blah")); - ctx.onActionResult(new WebhookAction.Result.Executed(300, "http://localhost:8000/alertfoo", "{'awesome' : 'us'}")); - Input.Result inputResult = new SimpleInput.Result(SimpleInput.TYPE, new Payload.Simple()); - Condition.Result conditionResult = AlwaysFalseCondition.RESULT; - ctx.onThrottleResult(Throttler.NO_THROTTLE.throttle(ctx)); - ctx.onInputResult(inputResult); - ctx.onConditionResult(conditionResult); - firedAlert.update(new AlertExecution(ctx)); - - XContentBuilder jsonBuilder = XContentFactory.jsonBuilder(); - firedAlert.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS); - FiredAlert parsedFiredAlert = firedAlertParser().parse(jsonBuilder.bytes(), firedAlert.id(), 0); - - XContentBuilder jsonBuilder2 = XContentFactory.jsonBuilder(); - parsedFiredAlert.toXContent(jsonBuilder2, ToXContent.EMPTY_PARAMS); - - assertThat(jsonBuilder.bytes().toUtf8(), equalTo(jsonBuilder2.bytes().toUtf8())); - } - - -} diff --git a/src/test/java/org/elasticsearch/alerts/history/HistoryServiceTests.java b/src/test/java/org/elasticsearch/alerts/history/HistoryServiceTests.java deleted file mode 100644 index 7f3e520a4ca..00000000000 --- a/src/test/java/org/elasticsearch/alerts/history/HistoryServiceTests.java +++ /dev/null @@ -1,188 +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.alerts.history; - -import org.elasticsearch.alerts.*; -import org.elasticsearch.alerts.actions.Action; -import org.elasticsearch.alerts.actions.Actions; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.simple.AlwaysFalseCondition; -import org.elasticsearch.alerts.condition.simple.AlwaysTrueCondition; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.scheduler.Scheduler; -import org.elasticsearch.alerts.support.clock.SystemClock; -import org.elasticsearch.alerts.throttle.Throttler; -import org.elasticsearch.alerts.transform.Transform; -import org.elasticsearch.cluster.ClusterService; -import org.elasticsearch.common.joda.time.DateTime; -import org.elasticsearch.common.settings.ImmutableSettings; -import org.elasticsearch.test.ElasticsearchTestCase; -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; - -import static org.hamcrest.Matchers.*; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.same; -import static org.mockito.Mockito.*; - -/** - */ -public class HistoryServiceTests extends ElasticsearchTestCase { - - private Payload payload; - private Input input; - private Input.Result inputResult; - - private HistoryService historyService; - - @Before - public void init() throws Exception { - payload = mock(Payload.class); - input = mock(Input.class); - inputResult = mock(Input.Result.class); - when(inputResult.payload()).thenReturn(payload); - when(input.execute(any(ExecutionContext.class))).thenReturn(inputResult); - - HistoryStore historyStore = mock(HistoryStore.class); - AlertsExecutor executor = mock(AlertsExecutor.class); - AlertsStore alertsStore = mock(AlertsStore.class); - AlertLockService alertLockService = mock(AlertLockService.class); - Scheduler scheduler = mock(Scheduler.class); - ClusterService clusterService = mock(ClusterService.class); - historyService = new HistoryService(ImmutableSettings.EMPTY, historyStore, executor, alertsStore, alertLockService, scheduler, clusterService, SystemClock.INSTANCE); - } - - @Test - public void testExecute() throws Exception { - Condition.Result conditionResult = AlwaysTrueCondition.RESULT; - Throttler.Result throttleResult = Throttler.Result.NO; - Transform.Result transformResult = mock(Transform.Result.class); - when(transformResult.payload()).thenReturn(payload); - Action.Result actionResult = mock(Action.Result.class); - when(actionResult.type()).thenReturn("_action_type"); - - Condition condition = mock(Condition.class); - when(condition.execute(any(ExecutionContext.class))).thenReturn(conditionResult); - Throttler throttler = mock(Throttler.class); - when(throttler.throttle(any(ExecutionContext.class))).thenReturn(throttleResult); - Transform transform = mock(Transform.class); - when(transform.apply(any(ExecutionContext.class), same(payload))).thenReturn(transformResult); - Action action = mock(Action.class); - when(action.execute(any(ExecutionContext.class))).thenReturn(actionResult); - Actions actions = new Actions(Arrays.asList(action)); - - Alert.Status alertStatus = new Alert.Status(); - Alert alert = mock(Alert.class); - when(alert.input()).thenReturn(input); - when(alert.condition()).thenReturn(condition); - when(alert.throttler()).thenReturn(throttler); - when(alert.transform()).thenReturn(transform); - when(alert.actions()).thenReturn(actions); - when(alert.status()).thenReturn(alertStatus); - - ExecutionContext context = new ExecutionContext("1", alert, DateTime.now(), DateTime.now(), DateTime.now()); - AlertExecution alertExecution = historyService.execute(context); - assertThat(alertExecution.conditionResult(), sameInstance(conditionResult)); - assertThat(alertExecution.transformResult(), sameInstance(transformResult)); - assertThat(alertExecution.throttleResult(), sameInstance(throttleResult)); - assertThat(alertExecution.actionsResults().get("_action_type"), sameInstance(actionResult)); - - verify(condition, times(1)).execute(any(ExecutionContext.class)); - verify(throttler, times(1)).throttle(any(ExecutionContext.class)); - verify(transform, times(1)).apply(any(ExecutionContext.class), same(payload)); - verify(action, times(1)).execute(any(ExecutionContext.class)); - } - - @Test - public void testExecute_throttled() throws Exception { - Condition.Result conditionResult = AlwaysTrueCondition.RESULT; - Throttler.Result throttleResult = mock(Throttler.Result.class); - when(throttleResult.throttle()).thenReturn(true); - - Transform.Result transformResult = mock(Transform.Result.class); - when(transformResult.payload()).thenReturn(payload); - Action.Result actionResult = mock(Action.Result.class); - when(actionResult.type()).thenReturn("_action_type"); - - Condition condition = mock(Condition.class); - when(condition.execute(any(ExecutionContext.class))).thenReturn(conditionResult); - Throttler throttler = mock(Throttler.class); - when(throttler.throttle(any(ExecutionContext.class))).thenReturn(throttleResult); - Transform transform = mock(Transform.class); - when(transform.apply(any(ExecutionContext.class), same(payload))).thenReturn(transformResult); - Action action = mock(Action.class); - when(action.execute(any(ExecutionContext.class))).thenReturn(actionResult); - Actions actions = new Actions(Arrays.asList(action)); - - Alert.Status alertStatus = new Alert.Status(); - Alert alert = mock(Alert.class); - when(alert.input()).thenReturn(input); - when(alert.condition()).thenReturn(condition); - when(alert.throttler()).thenReturn(throttler); - when(alert.transform()).thenReturn(transform); - when(alert.actions()).thenReturn(actions); - when(alert.status()).thenReturn(alertStatus); - - ExecutionContext context = new ExecutionContext("1", alert, DateTime.now(), DateTime.now(), DateTime.now()); - AlertExecution alertExecution = historyService.execute(context); - assertThat(alertExecution.inputResult(), sameInstance(inputResult)); - assertThat(alertExecution.conditionResult(), sameInstance(conditionResult)); - assertThat(alertExecution.throttleResult(), sameInstance(throttleResult)); - assertThat(alertExecution.actionsResults().isEmpty(), is(true)); - assertThat(alertExecution.transformResult(), nullValue()); - - verify(condition, times(1)).execute(any(ExecutionContext.class)); - verify(throttler, times(1)).throttle(any(ExecutionContext.class)); - verify(transform, never()).apply(any(ExecutionContext.class), same(payload)); - verify(action, never()).execute(any(ExecutionContext.class)); - } - - @Test - public void testExecute_conditionNotMet() throws Exception { - Condition.Result conditionResult = AlwaysFalseCondition.RESULT; - Throttler.Result throttleResult = mock(Throttler.Result.class); - when(throttleResult.throttle()).thenReturn(true); - - Transform.Result transformResult = mock(Transform.Result.class); - Action.Result actionResult = mock(Action.Result.class); - when(actionResult.type()).thenReturn("_action_type"); - - Condition condition = mock(Condition.class); - when(condition.execute(any(ExecutionContext.class))).thenReturn(conditionResult); - Throttler throttler = mock(Throttler.class); - when(throttler.throttle(any(ExecutionContext.class))).thenReturn(throttleResult); - Transform transform = mock(Transform.class); - when(transform.apply(any(ExecutionContext.class), same(payload))).thenReturn(transformResult); - Action action = mock(Action.class); - when(action.execute(any(ExecutionContext.class))).thenReturn(actionResult); - Actions actions = new Actions(Arrays.asList(action)); - - Alert.Status alertStatus = new Alert.Status(); - Alert alert = mock(Alert.class); - when(alert.input()).thenReturn(input); - when(alert.condition()).thenReturn(condition); - when(alert.throttler()).thenReturn(throttler); - when(alert.transform()).thenReturn(transform); - when(alert.actions()).thenReturn(actions); - when(alert.status()).thenReturn(alertStatus); - - ExecutionContext context = new ExecutionContext("1", alert, DateTime.now(), DateTime.now(), DateTime.now()); - AlertExecution alertExecution = historyService.execute(context); - assertThat(alertExecution.inputResult(), sameInstance(inputResult)); - assertThat(alertExecution.conditionResult(), sameInstance(conditionResult)); - assertThat(alertExecution.throttleResult(), nullValue()); - assertThat(alertExecution.transformResult(), nullValue()); - assertThat(alertExecution.actionsResults().isEmpty(), is(true)); - - verify(condition, times(1)).execute(any(ExecutionContext.class)); - verify(throttler, never()).throttle(any(ExecutionContext.class)); - verify(transform, never()).apply(any(ExecutionContext.class), same(payload)); - verify(action, never()).execute(any(ExecutionContext.class)); - } - -} diff --git a/src/test/java/org/elasticsearch/alerts/history/HistoryStoreLifeCycleTest.java b/src/test/java/org/elasticsearch/alerts/history/HistoryStoreLifeCycleTest.java deleted file mode 100644 index 8e10beb5920..00000000000 --- a/src/test/java/org/elasticsearch/alerts/history/HistoryStoreLifeCycleTest.java +++ /dev/null @@ -1,73 +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.alerts.history; - -import com.google.common.collect.ImmutableList; -import org.elasticsearch.action.get.GetResponse; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.simple.AlwaysTrueCondition; -import org.elasticsearch.alerts.support.clock.SystemClock; -import org.elasticsearch.alerts.test.AbstractAlertsSingleNodeTests; -import org.elasticsearch.cluster.ClusterService; -import org.elasticsearch.common.joda.time.DateTime; -import org.elasticsearch.common.joda.time.DateTimeZone; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; - -/** - */ -public class HistoryStoreLifeCycleTest extends AbstractAlertsSingleNodeTests { - - @Test - public void testPutLoadUpdate() throws Exception { - Condition condition = new AlwaysTrueCondition(logger); - HistoryStore historyStore = getInstanceFromNode(HistoryStore.class); - Alert alert = new Alert("_name", SystemClock.INSTANCE, null, null, condition, null, null, null, null, null); - - // Put fired alerts and verify that these are stored - FiredAlert[] firedAlerts = new FiredAlert[randomIntBetween(1, 50)]; - for (int i = 0; i < firedAlerts.length; i++) { - DateTime dateTime = new DateTime(i, DateTimeZone.UTC); - firedAlerts[i] = new FiredAlert(alert, dateTime, dateTime); - historyStore.put(firedAlerts[i]); - GetResponse getResponse = client().prepareGet(HistoryStore.getAlertHistoryIndexNameForTime(dateTime), HistoryStore.ALERT_HISTORY_TYPE, firedAlerts[i].id()) - .setVersion(1) - .get(); - assertThat(getResponse.isExists(), equalTo(true)); - } - - // Load the stored alerts - ClusterService clusterService = getInstanceFromNode(ClusterService.class); - HistoryStore.LoadResult loadResult = historyStore.loadFiredAlerts(clusterService.state(), FiredAlert.State.AWAITS_EXECUTION); - assertThat(loadResult.succeeded(), is(true)); - List loadedFiredAlerts = ImmutableList.copyOf(loadResult); - assertThat(loadedFiredAlerts.size(), equalTo(firedAlerts.length)); - - // Change the state to executed and update the alerts and then verify if the changes have been persisted too - for (FiredAlert firedAlert : firedAlerts) { - assertThat(loadedFiredAlerts.contains(firedAlert), is(true)); - assertThat(firedAlert.version(), equalTo(1l)); - firedAlert.update(FiredAlert.State.EXECUTED, "_message"); - historyStore.update(firedAlert); - GetResponse getResponse = client().prepareGet(HistoryStore.getAlertHistoryIndexNameForTime(firedAlert.scheduledTime()), HistoryStore.ALERT_HISTORY_TYPE, firedAlert.id()) - .setVersion(2l) - .get(); - assertThat(getResponse.isExists(), equalTo(true)); - } - - // try to load fired alerts, but none are in the await state, so no alerts are loaded. - loadResult = historyStore.loadFiredAlerts(clusterService.state(), FiredAlert.State.AWAITS_EXECUTION); - assertThat(loadResult.succeeded(), is(true)); - loadedFiredAlerts = ImmutableList.copyOf(loadResult); - assertThat(loadedFiredAlerts.size(), equalTo(0)); - } - -} diff --git a/src/test/java/org/elasticsearch/alerts/test/bench/AlertsBenchmark.java b/src/test/java/org/elasticsearch/alerts/test/bench/AlertsBenchmark.java index 2f3fdad7dc5..11bc2fb4f1a 100644 --- a/src/test/java/org/elasticsearch/alerts/test/bench/AlertsBenchmark.java +++ b/src/test/java/org/elasticsearch/alerts/test/bench/AlertsBenchmark.java @@ -6,31 +6,30 @@ package org.elasticsearch.alerts.test.bench; import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.alerts.AlertsPlugin; -import org.elasticsearch.alerts.client.AlertSourceBuilder; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.scheduler.Scheduler; -import org.elasticsearch.alerts.scheduler.SchedulerMock; -import org.elasticsearch.alerts.scheduler.SchedulerModule; -import org.elasticsearch.alerts.transport.actions.put.PutAlertRequest; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.node.NodeBuilder; import org.elasticsearch.node.internal.InternalNode; import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.watcher.WatcherPlugin; +import org.elasticsearch.watcher.client.WatchSourceBuilder; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.scheduler.Scheduler; +import org.elasticsearch.watcher.scheduler.SchedulerMock; +import org.elasticsearch.watcher.scheduler.SchedulerModule; +import org.elasticsearch.watcher.transport.actions.put.PutWatchRequest; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import static org.elasticsearch.alerts.actions.ActionBuilders.indexAction; -import static org.elasticsearch.alerts.condition.ConditionBuilders.scriptCondition; -import static org.elasticsearch.alerts.input.InputBuilders.searchInput; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.interval; +import static org.elasticsearch.watcher.actions.ActionBuilders.indexAction; +import static org.elasticsearch.watcher.condition.ConditionBuilders.scriptCondition; +import static org.elasticsearch.watcher.input.InputBuilders.searchInput; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.interval; /** */ @@ -46,23 +45,20 @@ public class AlertsBenchmark { InternalNode node = (InternalNode) NodeBuilder.nodeBuilder().settings(settings).data(false).node(); node.client().admin().cluster().prepareHealth().setWaitForGreenStatus().get(); Thread.sleep(5000); - AlertsClient alertsClient = node.injector().getInstance(AlertsClient.class); + WatcherClient alertsClient = node.injector().getInstance(WatcherClient.class); int numAlerts = 1000; for (int i = 0; i < numAlerts; i++) { final String name = "_name" + i; - PutAlertRequest putAlertRequest = new PutAlertRequest( - new AlertSourceBuilder() + PutWatchRequest putAlertRequest = new PutWatchRequest(name, new WatchSourceBuilder() .schedule(interval("5s")) .input(searchInput(new SearchRequest().source( new SearchSourceBuilder() ))) .condition(scriptCondition("1 == 1")) - .addAction(indexAction("index", "type")) - .buildAsBytes(XContentType.JSON) - ); - putAlertRequest.setAlertName(name); - alertsClient.putAlert(putAlertRequest).actionGet(); + .addAction(indexAction("index", "type"))); + putAlertRequest.setName(name); + alertsClient.putWatch(putAlertRequest).actionGet(); } int numThreads = 50; @@ -92,7 +88,7 @@ public class AlertsBenchmark { } } - public static final class BenchmarkAlertPlugin extends AlertsPlugin { + public static final class BenchmarkAlertPlugin extends WatcherPlugin { public BenchmarkAlertPlugin(Settings settings) { super(settings); @@ -101,10 +97,10 @@ public class AlertsBenchmark { @Override public Collection> modules() { - return ImmutableList.>of(AlertsModule.class); + return ImmutableList.>of(WatcherModule.class); } - public static class AlertsModule extends org.elasticsearch.alerts.AlertsModule { + public static class WatcherModule extends org.elasticsearch.watcher.WatcherModule { @Override public Iterable spawnModules() { diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/AlertStatsTests.java b/src/test/java/org/elasticsearch/alerts/test/integration/AlertStatsTests.java deleted file mode 100644 index 7441a6f4168..00000000000 --- a/src/test/java/org/elasticsearch/alerts/test/integration/AlertStatsTests.java +++ /dev/null @@ -1,81 +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.alerts.test.integration; - -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.alerts.AlertsBuild; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.AlertsVersion; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.test.AbstractAlertsIntegrationTests; -import org.elasticsearch.alerts.test.AlertsTestUtils; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsRequest; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsResponse; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; -import org.junit.Test; - -import java.util.concurrent.TimeUnit; - -import static org.elasticsearch.index.query.QueryBuilders.termQuery; -import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; -import static org.elasticsearch.test.ElasticsearchIntegrationTest.Scope.TEST; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.core.IsEqual.equalTo; - - -/** - */ -@ClusterScope(scope = TEST, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false) -public class AlertStatsTests extends AbstractAlertsIntegrationTests { - - @Test - public void testStartedStats() throws Exception { - AlertsStatsRequest alertsStatsRequest = alertClient().prepareAlertsStats().request(); - AlertsStatsResponse response = alertClient().alertsStats(alertsStatsRequest).actionGet(); - - assertThat(response.isAlertActionManagerStarted(), is(true)); - assertThat(response.getAlertManagerStarted(), is(AlertsService.State.STARTED)); - assertThat(response.getAlertActionManagerQueueSize(), is(0L)); - assertThat(response.getNumberOfRegisteredAlerts(), is(0L)); - assertThat(response.getAlertActionManagerLargestQueueSize(), is(timeWarped() ? 1L : 0L)); - assertThat(response.getVersion(), is(AlertsVersion.CURRENT)); - assertThat(response.getBuild(), is(AlertsBuild.CURRENT)); - } - - @Test - public void testAlertCountStats() throws Exception { - AlertsClient alertsClient = alertClient(); - - AlertsStatsRequest alertsStatsRequest = alertsClient.prepareAlertsStats().request(); - AlertsStatsResponse response = alertsClient.alertsStats(alertsStatsRequest).actionGet(); - - assertThat(response.isAlertActionManagerStarted(), is(true)); - assertThat(response.getAlertManagerStarted(), equalTo(AlertsService.State.STARTED)); - - SearchRequest searchRequest = AlertsTestUtils.newInputSearchRequest("idx").source(searchSource().query(termQuery("field", "value"))); - BytesReference alertSource = createAlertSource("* * * * * ? *", searchRequest, "ctx.payload.hits.total == 1"); - alertClient().preparePutAlert("_name") - .source(alertSource) - .get(); - - if (timeWarped()) { - timeWarp().scheduler().fire("_name", 30, TimeValue.timeValueSeconds(1)); - } else { - //Wait a little until we should have queued an action - Thread.sleep(TimeUnit.SECONDS.toMillis(5)); - } - - response = alertClient().alertsStats(alertsStatsRequest).actionGet(); - - assertThat(response.isAlertActionManagerStarted(), is(true)); - assertThat(response.getAlertManagerStarted(), is(AlertsService.State.STARTED)); - assertThat(response.getNumberOfRegisteredAlerts(), is(1L)); - assertThat(response.getAlertActionManagerLargestQueueSize(), greaterThan(0L)); - } -} diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/BootStrapTests.java b/src/test/java/org/elasticsearch/alerts/test/integration/BootStrapTests.java deleted file mode 100644 index 229a4233b0d..00000000000 --- a/src/test/java/org/elasticsearch/alerts/test/integration/BootStrapTests.java +++ /dev/null @@ -1,196 +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.alerts.test.integration; - -import org.elasticsearch.action.WriteConsistencyLevel; -import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.AlertsStore; -import org.elasticsearch.alerts.actions.Action; -import org.elasticsearch.alerts.actions.Actions; -import org.elasticsearch.alerts.condition.script.ScriptCondition; -import org.elasticsearch.alerts.history.FiredAlert; -import org.elasticsearch.alerts.history.HistoryStore; -import org.elasticsearch.alerts.input.search.SearchInput; -import org.elasticsearch.alerts.scheduler.schedule.CronSchedule; -import org.elasticsearch.alerts.support.Script; -import org.elasticsearch.alerts.support.clock.SystemClock; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.test.AbstractAlertsIntegrationTests; -import org.elasticsearch.alerts.test.AlertsTestUtils; -import org.elasticsearch.alerts.transform.SearchTransform; -import org.elasticsearch.alerts.transport.actions.put.PutAlertResponse; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsResponse; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.joda.time.DateTime; -import org.elasticsearch.common.joda.time.DateTimeZone; -import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.xcontent.ToXContent; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.test.junit.annotations.TestLogging; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.QueryBuilders.termQuery; -import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.core.IsEqual.equalTo; - -/** - */ -public class BootStrapTests extends AbstractAlertsIntegrationTests { - - @Test - public void testBootStrapAlerts() throws Exception { - ensureAlertingStarted(); - - SearchRequest searchRequest = AlertsTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); - 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) - .get(); - - client().admin().indices().prepareRefresh(AlertsStore.ALERT_INDEX).get(); - stopAlerting(); - startAlerting(); - - AlertsStatsResponse response = alertClient().prepareAlertsStats().get(); - assertThat(response.isAlertActionManagerStarted(), is(true)); - assertThat(response.getAlertManagerStarted(), equalTo(AlertsService.State.STARTED)); - assertThat(response.getNumberOfRegisteredAlerts(), equalTo(1L)); - } - - @Test - @TestLogging("alerts.actions:DEBUG") - public void testBootstrapHistory() throws Exception { - ensureAlertingStarted(); - - AlertsStatsResponse response = alertClient().prepareAlertsStats().get(); - assertThat(response.isAlertActionManagerStarted(), is(true)); - assertThat(response.getAlertManagerStarted(), equalTo(AlertsService.State.STARTED)); - assertThat(response.getNumberOfRegisteredAlerts(), equalTo(0L)); - - SearchRequest searchRequest = AlertsTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); - Alert alert = new Alert( - "test-serialization", - SystemClock.INSTANCE, - new CronSchedule("0/5 * * * * ? 2035"), //Set this into the future so we don't get any extra runs - new SearchInput(logger, scriptService(), ClientProxy.of(client()), searchRequest), - new ScriptCondition(logger, scriptService(), new Script("return true")), - new SearchTransform(logger, scriptService(), ClientProxy.of(client()), searchRequest), - new Actions(new ArrayList()), - null, // metadata - new TimeValue(0), - new Alert.Status()); - - XContentBuilder builder = jsonBuilder().value(alert); - IndexResponse indexResponse = client().prepareIndex(AlertsStore.ALERT_INDEX, AlertsStore.ALERT_TYPE, alert.name()) - .setSource(builder).get(); - ensureGreen(AlertsStore.ALERT_INDEX); - refresh(); - assertThat(indexResponse.isCreated(), is(true)); - - DateTime scheduledFireTime = new DateTime(DateTimeZone.UTC); - FiredAlert firedAlert = new FiredAlert(alert, scheduledFireTime, scheduledFireTime); - String actionHistoryIndex = HistoryStore.getAlertHistoryIndexNameForTime(scheduledFireTime); - - createIndex(actionHistoryIndex); - ensureGreen(actionHistoryIndex); - logger.info("Created index {}", actionHistoryIndex); - - indexResponse = client().prepareIndex(actionHistoryIndex, HistoryStore.ALERT_HISTORY_TYPE, firedAlert.id()) - .setConsistencyLevel(WriteConsistencyLevel.ALL) - .setSource(jsonBuilder().value(firedAlert)) - .get(); - assertThat(indexResponse.isCreated(), is(true)); - - stopAlerting(); - startAlerting(); - - response = alertClient().prepareAlertsStats().get(); - assertThat(response.isAlertActionManagerStarted(), is(true)); - assertThat(response.getAlertManagerStarted(), equalTo(AlertsService.State.STARTED)); - assertThat(response.getNumberOfRegisteredAlerts(), equalTo(1L)); - assertThat(response.getAlertActionManagerLargestQueueSize(), greaterThanOrEqualTo(1l)); - } - - @Test - @TestLogging("alerts.actions:DEBUG") - public void testBootStrapManyHistoryIndices() throws Exception { - DateTime now = new DateTime(DateTimeZone.UTC); - long numberOfAlertHistoryIndices = randomIntBetween(2, 8); - long numberOfAlertHistoryEntriesPerIndex = randomIntBetween(5, 10); - SearchRequest searchRequest = AlertsTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); - - for (int i = 0; i < numberOfAlertHistoryIndices; i++) { - DateTime historyIndexDate = now.minus((new TimeValue(i, TimeUnit.DAYS)).getMillis()); - String actionHistoryIndex = HistoryStore.getAlertHistoryIndexNameForTime(historyIndexDate); - createIndex(actionHistoryIndex); - ensureGreen(actionHistoryIndex); - logger.info("Created index {}", actionHistoryIndex); - - for (int j = 0; j < numberOfAlertHistoryEntriesPerIndex; j++) { - - Alert alert = new Alert( - "action-test-" + i + " " + j, - SystemClock.INSTANCE, - new CronSchedule("0/5 * * * * ? 2035"), //Set a cron schedule far into the future so this alert is never scheduled - new SearchInput(logger, scriptService(), ClientProxy.of(client()), - searchRequest), - new ScriptCondition(logger, scriptService(), new Script("return true")), - new SearchTransform(logger, scriptService(), ClientProxy.of(client()), searchRequest), - new Actions(new ArrayList()), - null, // metatdata - new TimeValue(0), - new Alert.Status()); - XContentBuilder jsonBuilder = jsonBuilder(); - alert.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS); - - PutAlertResponse putAlertResponse = alertClient().preparePutAlert(alert.name()).source(jsonBuilder.bytes()).get(); - assertThat(putAlertResponse.indexResponse().isCreated(), is(true)); - - FiredAlert firedAlert = new FiredAlert(alert, historyIndexDate, historyIndexDate); - - XContentBuilder jsonBuilder2 = jsonBuilder(); - firedAlert.toXContent(jsonBuilder2, ToXContent.EMPTY_PARAMS); - - IndexResponse indexResponse = client().prepareIndex(actionHistoryIndex, HistoryStore.ALERT_HISTORY_TYPE, firedAlert.id()) - .setConsistencyLevel(WriteConsistencyLevel.ALL) - .setSource(jsonBuilder2.bytes()) - .get(); - assertThat(indexResponse.isCreated(), is(true)); - } - client().admin().indices().prepareRefresh(actionHistoryIndex).get(); - } - - stopAlerting(); - startAlerting(); - AlertsStatsResponse response = alertClient().prepareAlertsStats().get(); - - assertThat(response.isAlertActionManagerStarted(), is(true)); - assertThat(response.getAlertManagerStarted(), equalTo(AlertsService.State.STARTED)); - final long totalHistoryEntries = numberOfAlertHistoryEntriesPerIndex * numberOfAlertHistoryIndices; - - assertBusy(new Runnable() { - @Override - public void run() { - long count = docCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*", HistoryStore.ALERT_HISTORY_TYPE, - termQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.EXECUTED.id())); - assertThat(count, is(totalHistoryEntries)); - } - }, 30, TimeUnit.SECONDS); - - } - - -} diff --git a/src/test/java/org/elasticsearch/alerts/throttle/AckThrottlerTests.java b/src/test/java/org/elasticsearch/alerts/throttle/AckThrottlerTests.java deleted file mode 100644 index ad98dce3928..00000000000 --- a/src/test/java/org/elasticsearch/alerts/throttle/AckThrottlerTests.java +++ /dev/null @@ -1,59 +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.alerts.throttle; - -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.test.AlertsTestUtils; -import org.elasticsearch.common.joda.time.DateTime; -import org.elasticsearch.test.ElasticsearchTestCase; -import org.junit.Test; - -import static org.elasticsearch.alerts.support.AlertsDateUtils.formatDate; -import static org.elasticsearch.alerts.test.AlertsTestUtils.EMPTY_PAYLOAD; -import static org.elasticsearch.alerts.test.AlertsTestUtils.mockExecutionContext; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.is; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * - */ -public class AckThrottlerTests extends ElasticsearchTestCase { - - @Test - public void testWhenAcked() throws Exception { - DateTime timestamp = new DateTime(); - ExecutionContext ctx = mockExecutionContext("_alert", EMPTY_PAYLOAD); - Alert alert = ctx.alert(); - Alert.Status status = mock(Alert.Status.class); - when(status.ackStatus()).thenReturn(new Alert.Status.AckStatus(Alert.Status.AckStatus.State.ACKED, timestamp)); - when(alert.status()).thenReturn(status); - when(alert.name()).thenReturn("_alert"); - when(alert.acked()).thenReturn(true); - AckThrottler throttler = new AckThrottler(); - Throttler.Result result = throttler.throttle(ctx); - assertThat(result.throttle(), is(true)); - assertThat(result.reason(), is("alert [_alert] was acked at [" + formatDate(timestamp) + "]")); - } - - @Test - public void testWhenNotAcked() throws Exception { - DateTime timestamp = new DateTime(); - ExecutionContext ctx = mockExecutionContext("_alert", EMPTY_PAYLOAD); - Alert alert = ctx.alert(); - Alert.Status status = mock(Alert.Status.class); - Alert.Status.AckStatus.State state = randomFrom(Alert.Status.AckStatus.State.AWAITS_EXECUTION, Alert.Status.AckStatus.State.ACKABLE); - when(status.ackStatus()).thenReturn(new Alert.Status.AckStatus(state, timestamp)); - when(alert.status()).thenReturn(status); - when(alert.acked()).thenReturn(false); - AckThrottler throttler = new AckThrottler(); - Throttler.Result result = throttler.throttle(ctx); - assertThat(result.throttle(), is(false)); - assertThat(result.reason(), nullValue()); - } -} diff --git a/src/test/java/org/elasticsearch/alerts/AlertsLifeCycleServiceTest.java b/src/test/java/org/elasticsearch/watcher/WatcherLifeCycleServiceTest.java similarity index 66% rename from src/test/java/org/elasticsearch/alerts/AlertsLifeCycleServiceTest.java rename to src/test/java/org/elasticsearch/watcher/WatcherLifeCycleServiceTest.java index ff3f3d4269a..21b6d468e09 100644 --- a/src/test/java/org/elasticsearch/alerts/AlertsLifeCycleServiceTest.java +++ b/src/test/java/org/elasticsearch/watcher/WatcherLifeCycleServiceTest.java @@ -3,7 +3,7 @@ * 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.alerts; +package org.elasticsearch.watcher; import com.google.common.util.concurrent.MoreExecutors; import org.elasticsearch.cluster.ClusterChangedEvent; @@ -17,6 +17,7 @@ import org.elasticsearch.gateway.GatewayService; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.threadpool.ThreadPool; +import org.elasticsearch.watcher.watch.WatchService; import org.junit.Before; import org.junit.Test; @@ -25,22 +26,22 @@ import static org.mockito.Mockito.*; /** */ -public class AlertsLifeCycleServiceTest extends ElasticsearchTestCase { +public class WatcherLifeCycleServiceTest extends ElasticsearchTestCase { private ThreadPool threadPool; - private AlertsService alertsService; + private WatchService watchService; private ClusterService clusterService; private IndicesService indicesService; - private AlertsLifeCycleService lifeCycleService; + private WatcherLifeCycleService lifeCycleService; @Before public void prepareServices() { threadPool = mock(ThreadPool.class); when(threadPool.executor(anyString())).thenReturn(MoreExecutors.sameThreadExecutor()); - alertsService = mock(AlertsService.class); + watchService = mock(WatchService.class); clusterService = mock(ClusterService.class); indicesService = mock(IndicesService.class); - lifeCycleService = new AlertsLifeCycleService(ImmutableSettings.EMPTY, clusterService, indicesService, threadPool, alertsService); + lifeCycleService = new WatcherLifeCycleService(ImmutableSettings.EMPTY, clusterService, indicesService, threadPool, watchService); } @Test @@ -49,24 +50,24 @@ public class AlertsLifeCycleServiceTest extends ElasticsearchTestCase { DiscoveryNodes.Builder nodes = new DiscoveryNodes.Builder().masterNodeId("id1").localNodeId("id1"); ClusterState clusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes).build(); - when(alertsService.state()).thenReturn(AlertsService.State.STOPPED); + when(watchService.state()).thenReturn(WatchService.State.STOPPED); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); - verify(alertsService, times(1)).start(clusterState); - verify(alertsService, never()).stop(); + verify(watchService, times(1)).start(clusterState); + verify(watchService, never()).stop(); // Trying to start a second time, but that should have no affect. - when(alertsService.state()).thenReturn(AlertsService.State.STARTED); + when(watchService.state()).thenReturn(WatchService.State.STARTED); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); - verify(alertsService, times(1)).start(clusterState); - verify(alertsService, never()).stop(); + verify(watchService, times(1)).start(clusterState); + verify(watchService, never()).stop(); // Stopping because local node is no longer master node nodes = new DiscoveryNodes.Builder().masterNodeId("id1").localNodeId("id2"); ClusterState noMasterClusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes).build(); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", noMasterClusterState, noMasterClusterState)); - verify(alertsService, times(1)).stop(); - verify(alertsService, times(1)).start(clusterState); + verify(watchService, times(1)).stop(); + verify(watchService, times(1)).start(clusterState); } @Test @@ -75,52 +76,52 @@ public class AlertsLifeCycleServiceTest extends ElasticsearchTestCase { ClusterState clusterState = ClusterState.builder(new ClusterName("my-cluster")) .blocks(ClusterBlocks.builder().addGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK)) .nodes(nodes).build(); - when(alertsService.state()).thenReturn(AlertsService.State.STOPPED); + when(watchService.state()).thenReturn(WatchService.State.STOPPED); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); - verify(alertsService, never()).start(any(ClusterState.class)); + verify(watchService, never()).start(any(ClusterState.class)); } @Test public void testManualStartStop() { lifeCycleService.start(); - verify(alertsService, times(1)).start(any(ClusterState.class)); - verify(alertsService, never()).stop(); + verify(watchService, times(1)).start(any(ClusterState.class)); + verify(watchService, never()).stop(); lifeCycleService.stop(); - verify(alertsService, times(1)).start(any(ClusterState.class)); - verify(alertsService, times(1)).stop(); + verify(watchService, times(1)).start(any(ClusterState.class)); + verify(watchService, times(1)).stop(); // Starting via cluster state update, we shouldn't start because we have been stopped manually. DiscoveryNodes.Builder nodes = new DiscoveryNodes.Builder().masterNodeId("id1").localNodeId("id1"); ClusterState clusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes).build(); - when(alertsService.state()).thenReturn(AlertsService.State.STOPPED); + when(watchService.state()).thenReturn(WatchService.State.STOPPED); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); - verify(alertsService, times(1)).start(any(ClusterState.class)); - verify(alertsService, times(1)).stop(); + verify(watchService, times(1)).start(any(ClusterState.class)); + verify(watchService, times(1)).stop(); // we can only start, if we start manually lifeCycleService.start(); - verify(alertsService, times(2)).start(any(ClusterState.class)); - verify(alertsService, times(1)).stop(); + verify(watchService, times(2)).start(any(ClusterState.class)); + verify(watchService, times(1)).stop(); - // stop alerting via cluster state update + // stop watcher via cluster state update nodes = new DiscoveryNodes.Builder().masterNodeId("id1").localNodeId("id2"); clusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes).build(); - when(alertsService.state()).thenReturn(AlertsService.State.STOPPED); + when(watchService.state()).thenReturn(WatchService.State.STOPPED); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); - verify(alertsService, times(2)).start(any(ClusterState.class)); - verify(alertsService, times(2)).stop(); + verify(watchService, times(2)).start(any(ClusterState.class)); + verify(watchService, times(2)).stop(); - // starting alerting via cluster state update, which should work, because we manually started before + // starting watcher via cluster state update, which should work, because we manually started before nodes = new DiscoveryNodes.Builder().masterNodeId("id1").localNodeId("id1"); clusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes).build(); - when(alertsService.state()).thenReturn(AlertsService.State.STOPPED); + when(watchService.state()).thenReturn(WatchService.State.STOPPED); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); - verify(alertsService, times(3)).start(any(ClusterState.class)); - verify(alertsService, times(2)).stop(); + verify(watchService, times(3)).start(any(ClusterState.class)); + verify(watchService, times(2)).stop(); } } diff --git a/src/test/java/org/elasticsearch/alerts/actions/email/EmailActionTests.java b/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java similarity index 96% rename from src/test/java/org/elasticsearch/alerts/actions/email/EmailActionTests.java rename to src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java index 54ade05eb8a..b635f0cba5c 100644 --- a/src/test/java/org/elasticsearch/alerts/actions/email/EmailActionTests.java +++ b/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java @@ -3,18 +3,18 @@ * 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.alerts.actions.email; +package org.elasticsearch.watcher.actions.email; import com.carrotsearch.randomizedtesting.annotations.Repeat; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.actions.ActionSettingsException; -import org.elasticsearch.alerts.actions.email.service.*; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; -import org.elasticsearch.alerts.support.template.ScriptTemplate; -import org.elasticsearch.alerts.support.template.Template; -import org.elasticsearch.alerts.transform.Transform; -import org.elasticsearch.alerts.transform.TransformRegistry; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.actions.ActionSettingsException; +import org.elasticsearch.watcher.actions.email.service.*; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.support.template.ScriptTemplate; +import org.elasticsearch.watcher.support.template.Template; +import org.elasticsearch.watcher.transform.Transform; +import org.elasticsearch.watcher.transform.TransformRegistry; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.joda.time.DateTime; @@ -30,7 +30,7 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -import static org.elasticsearch.alerts.test.AlertsTestUtils.mockExecutionContext; +import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.mock; @@ -82,7 +82,7 @@ public class EmailActionTests extends ElasticsearchTestCase { DateTime now = DateTime.now(DateTimeZone.UTC); String ctxId = randomAsciiOfLength(5); - ExecutionContext ctx = mockExecutionContext(now, "alert1", payload); + WatchExecutionContext ctx = mockExecutionContext(now, "watch1", payload); when(ctx.id()).thenReturn(ctxId); if (transform != null) { Transform.Result transformResult = mock(Transform.Result.class); @@ -92,7 +92,7 @@ public class EmailActionTests extends ElasticsearchTestCase { } Map expectedModel = ImmutableMap.builder() .put("ctx", ImmutableMap.builder() - .put("alert_name", "alert1") + .put("watch_name", "watch1") .put("payload", transform == null ? data : new Payload.Simple("_key", "_value").data()) .put("execution_time", now) .put("fire_time", now) @@ -429,7 +429,7 @@ public class EmailActionTests extends ElasticsearchTestCase { } @Override - public Result apply(ExecutionContext ctx, Payload payload) throws IOException { + public Result apply(WatchExecutionContext ctx, Payload payload) throws IOException { return new Result("_transform", new Payload.Simple("_key", "_value")); } diff --git a/src/test/java/org/elasticsearch/alerts/actions/email/service/AccountTests.java b/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountTests.java similarity index 98% rename from src/test/java/org/elasticsearch/alerts/actions/email/service/AccountTests.java rename to src/test/java/org/elasticsearch/watcher/actions/email/service/AccountTests.java index 15fa087e4b2..cc9649aad88 100644 --- a/src/test/java/org/elasticsearch/alerts/actions/email/service/AccountTests.java +++ b/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountTests.java @@ -3,9 +3,9 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; -import org.elasticsearch.alerts.actions.email.service.support.EmailServer; +import org.elasticsearch.watcher.actions.email.service.support.EmailServer; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ElasticsearchTestCase; diff --git a/src/test/java/org/elasticsearch/alerts/actions/email/service/AccountsTests.java b/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountsTests.java similarity index 98% rename from src/test/java/org/elasticsearch/alerts/actions/email/service/AccountsTests.java rename to src/test/java/org/elasticsearch/watcher/actions/email/service/AccountsTests.java index d13a90ba258..c169632af0e 100644 --- a/src/test/java/org/elasticsearch/alerts/actions/email/service/AccountsTests.java +++ b/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountsTests.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.test.ElasticsearchTestCase; diff --git a/src/test/java/org/elasticsearch/alerts/actions/email/service/InternalEmailServiceTests.java b/src/test/java/org/elasticsearch/watcher/actions/email/service/InternalEmailServiceTests.java similarity index 97% rename from src/test/java/org/elasticsearch/alerts/actions/email/service/InternalEmailServiceTests.java rename to src/test/java/org/elasticsearch/watcher/actions/email/service/InternalEmailServiceTests.java index f4f07f08d3a..16e5d320baa 100644 --- a/src/test/java/org/elasticsearch/alerts/actions/email/service/InternalEmailServiceTests.java +++ b/src/test/java/org/elasticsearch/watcher/actions/email/service/InternalEmailServiceTests.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.ImmutableSettings; diff --git a/src/test/java/org/elasticsearch/alerts/actions/email/service/ManualPublicSmtpServersTests.java b/src/test/java/org/elasticsearch/watcher/actions/email/service/ManualPublicSmtpServersTests.java similarity index 50% rename from src/test/java/org/elasticsearch/alerts/actions/email/service/ManualPublicSmtpServersTests.java rename to src/test/java/org/elasticsearch/watcher/actions/email/service/ManualPublicSmtpServersTests.java index 545d1edad74..e478b51b1df 100644 --- a/src/test/java/org/elasticsearch/alerts/actions/email/service/ManualPublicSmtpServersTests.java +++ b/src/test/java/org/elasticsearch/watcher/actions/email/service/ManualPublicSmtpServersTests.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service; +package org.elasticsearch.watcher.actions.email.service; import org.elasticsearch.common.cli.Terminal; import org.elasticsearch.common.inject.Provider; @@ -29,13 +29,13 @@ public class ManualPublicSmtpServersTests { public static void main(String[] args) throws Exception { test(Profile.GMAIL, ImmutableSettings.builder() - .put("alerts.actions.email.service.account.gmail.smtp.auth", true) - .put("alerts.actions.email.service.account.gmail.smtp.starttls.enable", true) - .put("alerts.actions.email.service.account.gmail.smtp.host", "smtp.gmail.com") - .put("alerts.actions.email.service.account.gmail.smtp.port", 587) - .put("alerts.actions.email.service.account.gmail.smtp.user", terminal.readText("username: ")) - .put("alerts.actions.email.service.account.gmail.smtp.password", new String(terminal.readSecret("password: "))) - .put("alerts.actions.email.service.account.gmail.email_defaults.to", terminal.readText("to: ")) + .put("watcher.actions.email.service.account.gmail.smtp.auth", true) + .put("watcher.actions.email.service.account.gmail.smtp.starttls.enable", true) + .put("watcher.actions.email.service.account.gmail.smtp.host", "smtp.gmail.com") + .put("watcher.actions.email.service.account.gmail.smtp.port", 587) + .put("watcher.actions.email.service.account.gmail.smtp.user", terminal.readText("username: ")) + .put("watcher.actions.email.service.account.gmail.smtp.password", new String(terminal.readSecret("password: "))) + .put("watcher.actions.email.service.account.gmail.email_defaults.to", terminal.readText("to: ")) ); } @@ -45,13 +45,13 @@ public class ManualPublicSmtpServersTests { public static void main(String[] args) throws Exception { test(Profile.STANDARD, ImmutableSettings.builder() - .put("alerts.actions.email.service.account.outlook.smtp.auth", true) - .put("alerts.actions.email.service.account.outlook.smtp.starttls.enable", true) - .put("alerts.actions.email.service.account.outlook.smtp.host", "smtp-mail.outlook.com") - .put("alerts.actions.email.service.account.outlook.smtp.port", 587) - .put("alerts.actions.email.service.account.outlook.smtp.user", "elastic.user@outlook.com") - .put("alerts.actions.email.service.account.outlook.smtp.password", "fantastic42") - .put("alerts.actions.email.service.account.outlook.email_defaults.to", "elastic.user@outlook.com") + .put("watcher.actions.email.service.account.outlook.smtp.auth", true) + .put("watcher.actions.email.service.account.outlook.smtp.starttls.enable", true) + .put("watcher.actions.email.service.account.outlook.smtp.host", "smtp-mail.outlook.com") + .put("watcher.actions.email.service.account.outlook.smtp.port", 587) + .put("watcher.actions.email.service.account.outlook.smtp.user", "elastic.user@outlook.com") + .put("watcher.actions.email.service.account.outlook.smtp.password", "fantastic42") + .put("watcher.actions.email.service.account.outlook.email_defaults.to", "elastic.user@outlook.com") .put() ); } @@ -61,15 +61,15 @@ public class ManualPublicSmtpServersTests { public static void main(String[] args) throws Exception { test(Profile.STANDARD, ImmutableSettings.builder() - .put("alerts.actions.email.service.account.yahoo.smtp.starttls.enable", true) - .put("alerts.actions.email.service.account.yahoo.smtp.auth", true) - .put("alerts.actions.email.service.account.yahoo.smtp.host", "smtp.mail.yahoo.com") - .put("alerts.actions.email.service.account.yahoo.smtp.port", 587) - .put("alerts.actions.email.service.account.yahoo.smtp.user", "elastic.user@yahoo.com") - .put("alerts.actions.email.service.account.yahoo.smtp.password", "fantastic42") + .put("watcher.actions.email.service.account.yahoo.smtp.starttls.enable", true) + .put("watcher.actions.email.service.account.yahoo.smtp.auth", true) + .put("watcher.actions.email.service.account.yahoo.smtp.host", "smtp.mail.yahoo.com") + .put("watcher.actions.email.service.account.yahoo.smtp.port", 587) + .put("watcher.actions.email.service.account.yahoo.smtp.user", "elastic.user@yahoo.com") + .put("watcher.actions.email.service.account.yahoo.smtp.password", "fantastic42") // note: from must be set to the same authenticated user account - .put("alerts.actions.email.service.account.yahoo.email_defaults.from", "elastic.user@yahoo.com") - .put("alerts.actions.email.service.account.yahoo.email_defaults.to", "elastic.user@yahoo.com") + .put("watcher.actions.email.service.account.yahoo.email_defaults.from", "elastic.user@yahoo.com") + .put("watcher.actions.email.service.account.yahoo.email_defaults.to", "elastic.user@yahoo.com") ); } } @@ -79,15 +79,15 @@ public class ManualPublicSmtpServersTests { public static void main(String[] args) throws Exception { test(Profile.STANDARD, ImmutableSettings.builder() - .put("alerts.actions.email.service.account.ses.smtp.auth", true) - .put("alerts.actions.email.service.account.ses.smtp.starttls.enable", true) - .put("alerts.actions.email.service.account.ses.smtp.starttls.required", true) - .put("alerts.actions.email.service.account.ses.smtp.host", "email-smtp.us-east-1.amazonaws.com") - .put("alerts.actions.email.service.account.ses.smtp.port", 587) - .put("alerts.actions.email.service.account.ses.smtp.user", terminal.readText("user: ")) - .put("alerts.actions.email.service.account.ses.smtp.password", new String(terminal.readSecret("password: "))) - .put("alerts.actions.email.service.account.ses.email_defaults.from", "dummy.user@elasticsearch.com") - .put("alerts.actions.email.service.account.ses.email_defaults.to", terminal.readText("to: ")) + .put("watcher.actions.email.service.account.ses.smtp.auth", true) + .put("watcher.actions.email.service.account.ses.smtp.starttls.enable", true) + .put("watcher.actions.email.service.account.ses.smtp.starttls.required", true) + .put("watcher.actions.email.service.account.ses.smtp.host", "email-smtp.us-east-1.amazonaws.com") + .put("watcher.actions.email.service.account.ses.smtp.port", 587) + .put("watcher.actions.email.service.account.ses.smtp.user", terminal.readText("user: ")) + .put("watcher.actions.email.service.account.ses.smtp.password", new String(terminal.readSecret("password: "))) + .put("watcher.actions.email.service.account.ses.email_defaults.from", "dummy.user@elasticsearch.com") + .put("watcher.actions.email.service.account.ses.email_defaults.to", terminal.readText("to: ")) ); } } @@ -116,7 +116,7 @@ public class ManualPublicSmtpServersTests { .inline(new Inline.Stream("logo", "logo.jpg", new Provider() { @Override public InputStream get() { - return InternalEmailServiceTests.class.getResourceAsStream("logo.jpg"); + return InternalEmailServiceTests.class.getResourceAsStream("logo.png"); } })) .build(); diff --git a/src/test/java/org/elasticsearch/alerts/actions/email/service/support/EmailServer.java b/src/test/java/org/elasticsearch/watcher/actions/email/service/support/EmailServer.java similarity index 98% rename from src/test/java/org/elasticsearch/alerts/actions/email/service/support/EmailServer.java rename to src/test/java/org/elasticsearch/watcher/actions/email/service/support/EmailServer.java index 36dbcb9fb79..522db183c41 100644 --- a/src/test/java/org/elasticsearch/alerts/actions/email/service/support/EmailServer.java +++ b/src/test/java/org/elasticsearch/watcher/actions/email/service/support/EmailServer.java @@ -3,7 +3,7 @@ * 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.alerts.actions.email.service.support; +package org.elasticsearch.watcher.actions.email.service.support; import org.subethamail.smtp.TooMuchDataException; import org.subethamail.smtp.auth.EasyAuthenticationHandlerFactory; diff --git a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionSearchTests.java b/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionSearchTests.java similarity index 86% rename from src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionSearchTests.java rename to src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionSearchTests.java index 08fa54a5f78..ed28aa7ef34 100644 --- a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionSearchTests.java +++ b/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionSearchTests.java @@ -3,15 +3,15 @@ * 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.alerts.condition.script; +package org.elasticsearch.watcher.condition.script; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.ShardSearchFailure; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.support.Script; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; -import org.elasticsearch.alerts.test.AbstractAlertsSingleNodeTests; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.test.AbstractWatcherSingleNodeTests; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.text.StringText; @@ -35,13 +35,13 @@ import org.junit.Test; import java.util.HashSet; import java.util.Set; -import static org.elasticsearch.alerts.test.AlertsTestUtils.mockExecutionContext; +import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; /** */ -public class ScriptConditionSearchTests extends AbstractAlertsSingleNodeTests { +public class ScriptConditionSearchTests extends AbstractWatcherSingleNodeTests { private ThreadPool tp = null; private ScriptServiceProxy scriptService; @@ -78,7 +78,7 @@ public class ScriptConditionSearchTests extends AbstractAlertsSingleNodeTests { ScriptCondition condition = new ScriptCondition(logger, scriptService, new Script("ctx.payload.aggregations.rate.buckets[0]?.doc_count >= 5")); - ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); + WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertFalse(condition.execute(ctx).met()); client().prepareIndex("my-index", "my-type").setTimestamp("2005-01-01T00:40").setSource("{}").get(); @@ -102,7 +102,7 @@ public class ScriptConditionSearchTests extends AbstractAlertsSingleNodeTests { InternalSearchResponse internalSearchResponse = new InternalSearchResponse(new InternalSearchHits(new InternalSearchHit[]{hit}, 1l, 1f), null, null, null, false, null); SearchResponse response = new SearchResponse(internalSearchResponse, "", 3, 3, 500l, new ShardSearchFailure[0]); - ExecutionContext ctx = mockExecutionContext("_alert_name", new Payload.XContent(response)); + WatchExecutionContext ctx = mockExecutionContext("_watch_name", new Payload.XContent(response)); assertThat(condition.execute(ctx).met(), is(true)); hit.score(2f); when(ctx.payload()).thenReturn(new Payload.XContent(response)); diff --git a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java b/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java similarity index 89% rename from src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java rename to src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java index 25a90a6d89a..80c16b036c9 100644 --- a/src/test/java/org/elasticsearch/alerts/condition/script/ScriptConditionTests.java +++ b/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java @@ -3,16 +3,16 @@ * 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.alerts.condition.script; +package org.elasticsearch.watcher.condition.script; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.ShardSearchFailure; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.ExecutionContext; -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.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.condition.ConditionException; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; @@ -35,7 +35,7 @@ import java.io.IOException; import java.util.HashSet; import java.util.Set; -import static org.elasticsearch.alerts.test.AlertsTestUtils.mockExecutionContext; +import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** @@ -60,7 +60,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); 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 = mockExecutionContext("_name", new Payload.XContent(response)); + WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertFalse(condition.execute(ctx).met()); } @@ -70,7 +70,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase { 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 = mockExecutionContext("_name", new Payload.XContent(response)); + WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertFalse(condition.execute(ctx).met()); } @@ -84,7 +84,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase { ScriptCondition condition = conditionParser.parse(parser); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); - ExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); + WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); assertFalse(condition.execute(ctx).met()); @@ -99,7 +99,7 @@ public class ScriptConditionTests extends ElasticsearchTestCase { assertTrue(condition.execute(ctx).met()); } - @Test(expected = AlertsSettingsException.class) + @Test(expected = WatcherSettingsException.class) public void testParser_InValid() throws Exception { ScriptCondition.Parser conditionParser = new ScriptCondition.Parser(ImmutableSettings.settingsBuilder().build(), getScriptServiceProxy(tp)); XContentBuilder builder = XContentFactory.jsonBuilder(); diff --git a/src/test/java/org/elasticsearch/alerts/condition/simple/AlwaysFalseConditionTests.java b/src/test/java/org/elasticsearch/watcher/condition/simple/AlwaysFalseConditionTests.java similarity index 95% rename from src/test/java/org/elasticsearch/alerts/condition/simple/AlwaysFalseConditionTests.java rename to src/test/java/org/elasticsearch/watcher/condition/simple/AlwaysFalseConditionTests.java index 648cb79a815..d074ca8ba07 100644 --- a/src/test/java/org/elasticsearch/alerts/condition/simple/AlwaysFalseConditionTests.java +++ b/src/test/java/org/elasticsearch/watcher/condition/simple/AlwaysFalseConditionTests.java @@ -3,10 +3,10 @@ * 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.alerts.condition.simple; +package org.elasticsearch.watcher.condition.simple; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.ConditionException; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionException; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; diff --git a/src/test/java/org/elasticsearch/alerts/condition/simple/AlwaysTrueConditionTests.java b/src/test/java/org/elasticsearch/watcher/condition/simple/AlwaysTrueConditionTests.java similarity index 95% rename from src/test/java/org/elasticsearch/alerts/condition/simple/AlwaysTrueConditionTests.java rename to src/test/java/org/elasticsearch/watcher/condition/simple/AlwaysTrueConditionTests.java index 6436aebb89c..ae83b9f6be9 100644 --- a/src/test/java/org/elasticsearch/alerts/condition/simple/AlwaysTrueConditionTests.java +++ b/src/test/java/org/elasticsearch/watcher/condition/simple/AlwaysTrueConditionTests.java @@ -3,10 +3,10 @@ * 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.alerts.condition.simple; +package org.elasticsearch.watcher.condition.simple; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.ConditionException; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionException; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; diff --git a/src/test/java/org/elasticsearch/watcher/history/HistoryServiceTests.java b/src/test/java/org/elasticsearch/watcher/history/HistoryServiceTests.java new file mode 100644 index 00000000000..75a9d89bf28 --- /dev/null +++ b/src/test/java/org/elasticsearch/watcher/history/HistoryServiceTests.java @@ -0,0 +1,188 @@ +/* + * 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.watcher.history; + +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.Actions; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.simple.AlwaysFalseCondition; +import org.elasticsearch.watcher.condition.simple.AlwaysTrueCondition; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.scheduler.Scheduler; +import org.elasticsearch.watcher.support.clock.SystemClock; +import org.elasticsearch.watcher.throttle.Throttler; +import org.elasticsearch.watcher.transform.Transform; +import org.elasticsearch.cluster.ClusterService; +import org.elasticsearch.common.joda.time.DateTime; +import org.elasticsearch.common.settings.ImmutableSettings; +import org.elasticsearch.test.ElasticsearchTestCase; +import org.elasticsearch.watcher.watch.*; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; + +import static org.hamcrest.Matchers.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.same; +import static org.mockito.Mockito.*; + +/** + */ +public class HistoryServiceTests extends ElasticsearchTestCase { + + private Payload payload; + private Input input; + private Input.Result inputResult; + + private HistoryService historyService; + + @Before + public void init() throws Exception { + payload = mock(Payload.class); + input = mock(Input.class); + inputResult = mock(Input.Result.class); + when(inputResult.payload()).thenReturn(payload); + when(input.execute(any(WatchExecutionContext.class))).thenReturn(inputResult); + + HistoryStore historyStore = mock(HistoryStore.class); + WatchExecutor executor = mock(WatchExecutor.class); + WatchStore watchStore = mock(WatchStore.class); + WatchLockService watchLockService = mock(WatchLockService.class); + Scheduler scheduler = mock(Scheduler.class); + ClusterService clusterService = mock(ClusterService.class); + historyService = new HistoryService(ImmutableSettings.EMPTY, historyStore, executor, watchStore, watchLockService, scheduler, clusterService, SystemClock.INSTANCE); + } + + @Test + public void testExecute() throws Exception { + Condition.Result conditionResult = AlwaysTrueCondition.RESULT; + Throttler.Result throttleResult = Throttler.Result.NO; + Transform.Result transformResult = mock(Transform.Result.class); + when(transformResult.payload()).thenReturn(payload); + Action.Result actionResult = mock(Action.Result.class); + when(actionResult.type()).thenReturn("_action_type"); + + Condition condition = mock(Condition.class); + when(condition.execute(any(WatchExecutionContext.class))).thenReturn(conditionResult); + Throttler throttler = mock(Throttler.class); + when(throttler.throttle(any(WatchExecutionContext.class))).thenReturn(throttleResult); + Transform transform = mock(Transform.class); + when(transform.apply(any(WatchExecutionContext.class), same(payload))).thenReturn(transformResult); + Action action = mock(Action.class); + when(action.execute(any(WatchExecutionContext.class))).thenReturn(actionResult); + Actions actions = new Actions(Arrays.asList(action)); + + Watch.Status watchStatus = new Watch.Status(); + Watch watch = mock(Watch.class); + when(watch.input()).thenReturn(input); + when(watch.condition()).thenReturn(condition); + when(watch.throttler()).thenReturn(throttler); + when(watch.transform()).thenReturn(transform); + when(watch.actions()).thenReturn(actions); + when(watch.status()).thenReturn(watchStatus); + + WatchExecutionContext context = new WatchExecutionContext("1", watch, DateTime.now(), DateTime.now(), DateTime.now()); + WatchExecution watchExecution = historyService.execute(context); + assertThat(watchExecution.conditionResult(), sameInstance(conditionResult)); + assertThat(watchExecution.transformResult(), sameInstance(transformResult)); + assertThat(watchExecution.throttleResult(), sameInstance(throttleResult)); + assertThat(watchExecution.actionsResults().get("_action_type"), sameInstance(actionResult)); + + verify(condition, times(1)).execute(any(WatchExecutionContext.class)); + verify(throttler, times(1)).throttle(any(WatchExecutionContext.class)); + verify(transform, times(1)).apply(any(WatchExecutionContext.class), same(payload)); + verify(action, times(1)).execute(any(WatchExecutionContext.class)); + } + + @Test + public void testExecute_throttled() throws Exception { + Condition.Result conditionResult = AlwaysTrueCondition.RESULT; + Throttler.Result throttleResult = mock(Throttler.Result.class); + when(throttleResult.throttle()).thenReturn(true); + + Transform.Result transformResult = mock(Transform.Result.class); + when(transformResult.payload()).thenReturn(payload); + Action.Result actionResult = mock(Action.Result.class); + when(actionResult.type()).thenReturn("_action_type"); + + Condition condition = mock(Condition.class); + when(condition.execute(any(WatchExecutionContext.class))).thenReturn(conditionResult); + Throttler throttler = mock(Throttler.class); + when(throttler.throttle(any(WatchExecutionContext.class))).thenReturn(throttleResult); + Transform transform = mock(Transform.class); + when(transform.apply(any(WatchExecutionContext.class), same(payload))).thenReturn(transformResult); + Action action = mock(Action.class); + when(action.execute(any(WatchExecutionContext.class))).thenReturn(actionResult); + Actions actions = new Actions(Arrays.asList(action)); + + Watch.Status watchStatus = new Watch.Status(); + Watch watch = mock(Watch.class); + when(watch.input()).thenReturn(input); + when(watch.condition()).thenReturn(condition); + when(watch.throttler()).thenReturn(throttler); + when(watch.transform()).thenReturn(transform); + when(watch.actions()).thenReturn(actions); + when(watch.status()).thenReturn(watchStatus); + + WatchExecutionContext context = new WatchExecutionContext("1", watch, DateTime.now(), DateTime.now(), DateTime.now()); + WatchExecution watchExecution = historyService.execute(context); + assertThat(watchExecution.inputResult(), sameInstance(inputResult)); + assertThat(watchExecution.conditionResult(), sameInstance(conditionResult)); + assertThat(watchExecution.throttleResult(), sameInstance(throttleResult)); + assertThat(watchExecution.actionsResults().isEmpty(), is(true)); + assertThat(watchExecution.transformResult(), nullValue()); + + verify(condition, times(1)).execute(any(WatchExecutionContext.class)); + verify(throttler, times(1)).throttle(any(WatchExecutionContext.class)); + verify(transform, never()).apply(any(WatchExecutionContext.class), same(payload)); + verify(action, never()).execute(any(WatchExecutionContext.class)); + } + + @Test + public void testExecute_conditionNotMet() throws Exception { + Condition.Result conditionResult = AlwaysFalseCondition.RESULT; + Throttler.Result throttleResult = mock(Throttler.Result.class); + when(throttleResult.throttle()).thenReturn(true); + + Transform.Result transformResult = mock(Transform.Result.class); + Action.Result actionResult = mock(Action.Result.class); + when(actionResult.type()).thenReturn("_action_type"); + + Condition condition = mock(Condition.class); + when(condition.execute(any(WatchExecutionContext.class))).thenReturn(conditionResult); + Throttler throttler = mock(Throttler.class); + when(throttler.throttle(any(WatchExecutionContext.class))).thenReturn(throttleResult); + Transform transform = mock(Transform.class); + when(transform.apply(any(WatchExecutionContext.class), same(payload))).thenReturn(transformResult); + Action action = mock(Action.class); + when(action.execute(any(WatchExecutionContext.class))).thenReturn(actionResult); + Actions actions = new Actions(Arrays.asList(action)); + + Watch.Status watchStatus = new Watch.Status(); + Watch watch = mock(Watch.class); + when(watch.input()).thenReturn(input); + when(watch.condition()).thenReturn(condition); + when(watch.throttler()).thenReturn(throttler); + when(watch.transform()).thenReturn(transform); + when(watch.actions()).thenReturn(actions); + when(watch.status()).thenReturn(watchStatus); + + WatchExecutionContext context = new WatchExecutionContext("1", watch, DateTime.now(), DateTime.now(), DateTime.now()); + WatchExecution watchExecution = historyService.execute(context); + assertThat(watchExecution.inputResult(), sameInstance(inputResult)); + assertThat(watchExecution.conditionResult(), sameInstance(conditionResult)); + assertThat(watchExecution.throttleResult(), nullValue()); + assertThat(watchExecution.transformResult(), nullValue()); + assertThat(watchExecution.actionsResults().isEmpty(), is(true)); + + verify(condition, times(1)).execute(any(WatchExecutionContext.class)); + verify(throttler, never()).throttle(any(WatchExecutionContext.class)); + verify(transform, never()).apply(any(WatchExecutionContext.class), same(payload)); + verify(action, never()).execute(any(WatchExecutionContext.class)); + } + +} diff --git a/src/test/java/org/elasticsearch/watcher/history/HistoryStoreLifeCycleTest.java b/src/test/java/org/elasticsearch/watcher/history/HistoryStoreLifeCycleTest.java new file mode 100644 index 00000000000..fbc43975c19 --- /dev/null +++ b/src/test/java/org/elasticsearch/watcher/history/HistoryStoreLifeCycleTest.java @@ -0,0 +1,69 @@ +/* + * 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.watcher.history; + +import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.cluster.ClusterService; +import org.elasticsearch.common.joda.time.DateTime; +import org.elasticsearch.common.joda.time.DateTimeZone; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.simple.AlwaysTrueCondition; +import org.elasticsearch.watcher.support.clock.SystemClock; +import org.elasticsearch.watcher.test.AbstractWatcherSingleNodeTests; +import org.elasticsearch.watcher.watch.Watch; +import org.junit.Test; + +import java.util.Collection; + +import static org.hamcrest.Matchers.*; + +/** + */ +public class HistoryStoreLifeCycleTest extends AbstractWatcherSingleNodeTests { + + @Test + public void testPutLoadUpdate() throws Exception { + Condition condition = new AlwaysTrueCondition(logger); + HistoryStore historyStore = getInstanceFromNode(HistoryStore.class); + Watch watch = new Watch("_name", SystemClock.INSTANCE, null, null, condition, null, null, null, null, null); + + // Put watch records and verify that these are stored + WatchRecord[] watchRecords = new WatchRecord[randomIntBetween(1, 50)]; + for (int i = 0; i < watchRecords.length; i++) { + DateTime dateTime = new DateTime(i, DateTimeZone.UTC); + watchRecords[i] = new WatchRecord(watch, dateTime, dateTime); + historyStore.put(watchRecords[i]); + GetResponse getResponse = client().prepareGet(HistoryStore.getHistoryIndexNameForTime(dateTime), HistoryStore.DOC_TYPE, watchRecords[i].id()) + .setVersion(1) + .get(); + assertThat(getResponse.isExists(), equalTo(true)); + } + + // Load the stored watch records + ClusterService clusterService = getInstanceFromNode(ClusterService.class); + Collection records = historyStore.loadRecords(clusterService.state(), WatchRecord.State.AWAITS_EXECUTION); + assertThat(records, notNullValue()); + assertThat(records, hasSize(watchRecords.length)); + + // Change the state to executed and update the watch records and then verify if the changes have been persisted too + for (WatchRecord watchRecord : watchRecords) { + assertThat(records.contains(watchRecord), is(true)); + assertThat(watchRecord.version(), equalTo(1l)); + watchRecord.update(WatchRecord.State.EXECUTED, "_message"); + historyStore.update(watchRecord); + GetResponse getResponse = client().prepareGet(HistoryStore.getHistoryIndexNameForTime(watchRecord.scheduledTime()), HistoryStore.DOC_TYPE, watchRecord.id()) + .setVersion(2l) + .get(); + assertThat(getResponse.isExists(), equalTo(true)); + } + + // try to load watch records, but none are in the await state, so no watch records are loaded. + records = historyStore.loadRecords(clusterService.state(), WatchRecord.State.AWAITS_EXECUTION); + assertThat(records, notNullValue()); + assertThat(records, hasSize(0)); + } + +} diff --git a/src/test/java/org/elasticsearch/alerts/history/HistoryStoreTests.java b/src/test/java/org/elasticsearch/watcher/history/HistoryStoreTests.java similarity index 73% rename from src/test/java/org/elasticsearch/alerts/history/HistoryStoreTests.java rename to src/test/java/org/elasticsearch/watcher/history/HistoryStoreTests.java index 83b8ba57de8..5a67ff0d916 100644 --- a/src/test/java/org/elasticsearch/alerts/history/HistoryStoreTests.java +++ b/src/test/java/org/elasticsearch/watcher/history/HistoryStoreTests.java @@ -3,19 +3,16 @@ * 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.alerts.history; +package org.elasticsearch.watcher.history; -import com.google.common.collect.ImmutableSet; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.action.search.*; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.condition.simple.AlwaysTrueCondition; -import org.elasticsearch.alerts.support.TemplateUtils; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; +import org.elasticsearch.action.search.ClearScrollResponse; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; @@ -36,11 +33,20 @@ import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHits; import org.elasticsearch.search.internal.InternalSearchResponse; import org.elasticsearch.test.ElasticsearchTestCase; +import org.elasticsearch.watcher.condition.simple.AlwaysTrueCondition; +import org.elasticsearch.watcher.support.TemplateUtils; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.watch.Watch; +import org.hamcrest.core.IsNull; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.Matchers.is; +import java.util.Collection; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.nullValue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; @@ -51,24 +57,24 @@ public class HistoryStoreTests extends ElasticsearchTestCase { private HistoryStore historyStore; private ClientProxy clientProxy; private TemplateUtils templateUtils; - private FiredAlert.Parser parser; + private WatchRecord.Parser parser; @Before public void init() { clientProxy = mock(ClientProxy.class); templateUtils = mock(TemplateUtils.class); - parser = mock(FiredAlert.Parser.class); + parser = mock(WatchRecord.Parser.class); historyStore = new HistoryStore(ImmutableSettings.EMPTY, clientProxy, templateUtils, parser); } @Test public void testPut() throws Exception { - Alert alert = mock(Alert.class); - when(alert.name()).thenReturn("_name"); - when(alert.condition()).thenReturn(new AlwaysTrueCondition(logger)); - when(alert.input()).thenReturn(null); - when(alert.metadata()).thenReturn(null); - FiredAlert firedAlert = new FiredAlert(alert, new DateTime(0, DateTimeZone.UTC), new DateTime(0, DateTimeZone.UTC)); + Watch watch = mock(Watch.class); + when(watch.name()).thenReturn("_name"); + when(watch.condition()).thenReturn(new AlwaysTrueCondition(logger)); + when(watch.input()).thenReturn(null); + when(watch.metadata()).thenReturn(null); + WatchRecord watchRecord = new WatchRecord(watch, new DateTime(0, DateTimeZone.UTC), new DateTime(0, DateTimeZone.UTC)); IndexRequestBuilder builder = mock(IndexRequestBuilder.class); when(builder.setSource(any(XContentBuilder.class))).thenReturn(builder); @@ -78,24 +84,24 @@ public class HistoryStoreTests extends ElasticsearchTestCase { when(indexResponse.getVersion()).thenReturn(version); when(builder.get()).thenReturn(indexResponse); - when(clientProxy.prepareIndex(".alert_history_1970-01-01", HistoryStore.ALERT_HISTORY_TYPE, "_name#1970-01-01T00:00:00.000Z")).thenReturn(builder); - historyStore.put(firedAlert); - assertThat(firedAlert.version(), equalTo(version)); + when(clientProxy.prepareIndex(".watch_history_1970-01-01", HistoryStore.DOC_TYPE, "_name#1970-01-01T00:00:00.000Z")).thenReturn(builder); + historyStore.put(watchRecord); + assertThat(watchRecord.version(), equalTo(version)); verify(builder, times(1)).setSource(any(XContentBuilder.class)); verify(builder, times(1)).setOpType(IndexRequest.OpType.CREATE); - verify(clientProxy, times(1)).prepareIndex(".alert_history_1970-01-01", HistoryStore.ALERT_HISTORY_TYPE, "_name#1970-01-01T00:00:00.000Z"); + verify(clientProxy, times(1)).prepareIndex(".watch_history_1970-01-01", HistoryStore.DOC_TYPE, "_name#1970-01-01T00:00:00.000Z"); } @Test public void testUpdate() throws Exception { - Alert alert = mock(Alert.class); - when(alert.name()).thenReturn("_name"); - when(alert.condition()).thenReturn(new AlwaysTrueCondition(logger)); - when(alert.input()).thenReturn(null); - when(alert.metadata()).thenReturn(null); - FiredAlert firedAlert = new FiredAlert(alert, new DateTime(0, DateTimeZone.UTC), new DateTime(0, DateTimeZone.UTC)); - firedAlert.version(4l); + Watch watch = mock(Watch.class); + when(watch.name()).thenReturn("_name"); + when(watch.condition()).thenReturn(new AlwaysTrueCondition(logger)); + when(watch.input()).thenReturn(null); + when(watch.metadata()).thenReturn(null); + WatchRecord watchRecord = new WatchRecord(watch, new DateTime(0, DateTimeZone.UTC), new DateTime(0, DateTimeZone.UTC)); + watchRecord.version(4l); IndexRequestBuilder builder = mock(IndexRequestBuilder.class); when(builder.setSource(any(BytesReference.class))).thenReturn(builder); @@ -105,31 +111,31 @@ public class HistoryStoreTests extends ElasticsearchTestCase { when(indexResponse.getVersion()).thenReturn(version); when(builder.get()).thenReturn(indexResponse); - when(clientProxy.prepareIndex(".alert_history_1970-01-01", HistoryStore.ALERT_HISTORY_TYPE, "_name#1970-01-01T00:00:00.000Z")).thenReturn(builder); - historyStore.update(firedAlert); - assertThat(firedAlert.version(), equalTo(version)); + when(clientProxy.prepareIndex(".watch_history_1970-01-01", HistoryStore.DOC_TYPE, "_name#1970-01-01T00:00:00.000Z")).thenReturn(builder); + historyStore.update(watchRecord); + assertThat(watchRecord.version(), equalTo(version)); verify(builder, times(1)).setSource(any(BytesReference.class)); verify(builder, times(1)).setVersion(4l); - verify(clientProxy, times(1)).prepareIndex(".alert_history_1970-01-01", HistoryStore.ALERT_HISTORY_TYPE, "_name#1970-01-01T00:00:00.000Z"); + verify(clientProxy, times(1)).prepareIndex(".watch_history_1970-01-01", HistoryStore.DOC_TYPE, "_name#1970-01-01T00:00:00.000Z"); } @Test - public void testLoadFiredAlerts_noPriorHistoryIndices() throws Exception { + public void testLoadWatchRecords_noPriorHistoryIndices() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("name")); MetaData.Builder metaDateBuilder = MetaData.builder(); csBuilder.metaData(metaDateBuilder); ClusterState cs = csBuilder.build(); - HistoryStore.LoadResult result = historyStore.loadFiredAlerts(cs, FiredAlert.State.AWAITS_EXECUTION); - assertThat(result.succeeded(), is(true)); - assertThat(ImmutableSet.copyOf(result).size(), equalTo(0)); - verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "alerthistory"); + Collection records = historyStore.loadRecords(cs, WatchRecord.State.AWAITS_EXECUTION); + assertThat(records, notNullValue()); + assertThat(records, hasSize(0)); + verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "watch_history"); verifyZeroInteractions(clientProxy); } @Test - public void testLoadFiredAlerts_noActivePrimaryShards() throws Exception { + public void testLoadWatchRecords_noActivePrimaryShards() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); @@ -137,7 +143,7 @@ public class HistoryStoreTests extends ElasticsearchTestCase { int numIndices = randomIntBetween(2, 10); int numStartedShards = randomIntBetween(1, numIndices - 1); for (int i = 0; i < numIndices; i++) { - String indexName = HistoryStore.ALERT_HISTORY_INDEX_PREFIX + i; + String indexName = HistoryStore.INDEX_PREFIX + i; Settings settings = ImmutableSettings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) @@ -160,21 +166,20 @@ public class HistoryStoreTests extends ElasticsearchTestCase { csBuilder.routingTable(routingTableBuilder); ClusterState cs = csBuilder.build(); - HistoryStore.LoadResult result = historyStore.loadFiredAlerts(cs, FiredAlert.State.AWAITS_EXECUTION); - assertThat(result.succeeded(), is(false)); - assertThat(ImmutableSet.copyOf(result).size(), equalTo(0)); + Collection records = historyStore.loadRecords(cs, WatchRecord.State.AWAITS_EXECUTION); + assertThat(records, nullValue()); verifyZeroInteractions(templateUtils); verifyZeroInteractions(clientProxy); } @Test - public void testLoadFiredAlerts_refreshNotHittingAllShards() throws Exception { + public void testLoadWatchRecords_refreshNotHittingAllShards() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); MetaData.Builder metaDateBuilder = MetaData.builder(); - String indexName = HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "1"; + String indexName = HistoryStore.INDEX_PREFIX + "1"; Settings settings = ImmutableSettings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) @@ -192,21 +197,20 @@ public class HistoryStoreTests extends ElasticsearchTestCase { RefreshResponse refreshResponse = mockRefreshResponse(1, 0); when(clientProxy.refresh(any(RefreshRequest.class))).thenReturn(refreshResponse); - HistoryStore.LoadResult result = historyStore.loadFiredAlerts(cs, FiredAlert.State.AWAITS_EXECUTION); - assertThat(result.succeeded(), is(false)); - assertThat(ImmutableSet.copyOf(result).size(), equalTo(0)); + Collection records = historyStore.loadRecords(cs, WatchRecord.State.AWAITS_EXECUTION); + assertThat(records, nullValue()); verifyZeroInteractions(templateUtils); verify(clientProxy, times(1)).refresh(any(RefreshRequest.class)); } @Test - public void testLoadFiredAlerts_searchNotHittingAllShards() throws Exception { + public void testLoadWatchRecords_searchNotHittingAllShards() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); MetaData.Builder metaDateBuilder = MetaData.builder(); - String indexName = HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "1"; + String indexName = HistoryStore.INDEX_PREFIX + "1"; Settings settings = ImmutableSettings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) @@ -232,21 +236,20 @@ public class HistoryStoreTests extends ElasticsearchTestCase { when(clientProxy.clearScroll(anyString())).thenReturn(new ClearScrollResponse(true, 1)); - HistoryStore.LoadResult result = historyStore.loadFiredAlerts(cs, FiredAlert.State.AWAITS_EXECUTION); - assertThat(result.succeeded(), is(false)); - assertThat(ImmutableSet.copyOf(result).size(), equalTo(0)); + Collection records = historyStore.loadRecords(cs, WatchRecord.State.AWAITS_EXECUTION); + assertThat(records, nullValue()); verifyZeroInteractions(templateUtils); verify(clientProxy, times(1)).refresh(any(RefreshRequest.class)); } @Test - public void testLoadFiredAlerts_noHistoryEntries() throws Exception { + public void testLoadWatchRecords_noHistoryEntries() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); MetaData.Builder metaDateBuilder = MetaData.builder(); - String indexName = HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "1"; + String indexName = HistoryStore.INDEX_PREFIX + "1"; Settings settings = ImmutableSettings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) @@ -273,21 +276,21 @@ public class HistoryStoreTests extends ElasticsearchTestCase { when(clientProxy.clearScroll(anyString())).thenReturn(new ClearScrollResponse(true, 1)); - HistoryStore.LoadResult result = historyStore.loadFiredAlerts(cs, FiredAlert.State.AWAITS_EXECUTION); - assertThat(result.succeeded(), is(true)); - assertThat(ImmutableSet.copyOf(result).size(), equalTo(0)); + Collection records = historyStore.loadRecords(cs, WatchRecord.State.AWAITS_EXECUTION); + assertThat(records, IsNull.notNullValue()); + assertThat(records, hasSize(0)); - verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "alerthistory"); + verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "watch_history"); verify(clientProxy, times(1)).refresh(any(RefreshRequest.class)); } @Test - public void testLoadFiredAlerts_foundHistoryEntries() throws Exception { + public void testLoadWatchRecords_foundHistoryEntries() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); MetaData.Builder metaDateBuilder = MetaData.builder(); - String indexName = HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "1"; + String indexName = HistoryStore.INDEX_PREFIX + "1"; Settings settings = ImmutableSettings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) @@ -324,26 +327,26 @@ public class HistoryStoreTests extends ElasticsearchTestCase { SearchResponse searchResponse2 = new SearchResponse(InternalSearchResponse.empty(), null, 1, 1, 1, null); when(clientProxy.searchScroll(anyString(), any(TimeValue.class))).thenReturn(searchResponse2); - FiredAlert firedAlert = mock(FiredAlert.class); - when(firedAlert.state()).thenReturn(FiredAlert.State.AWAITS_EXECUTION); - when(parser.parse(any(BytesReference.class), eq("_id"), eq(1l))).thenReturn(firedAlert); + WatchRecord watchRecord = mock(WatchRecord.class); + when(watchRecord.state()).thenReturn(WatchRecord.State.AWAITS_EXECUTION); + when(parser.parse(any(BytesReference.class), eq("_id"), eq(1l))).thenReturn(watchRecord); when(clientProxy.clearScroll(anyString())).thenReturn(new ClearScrollResponse(true, 1)); - HistoryStore.LoadResult result = historyStore.loadFiredAlerts(cs, FiredAlert.State.AWAITS_EXECUTION); - assertThat(result.succeeded(), is(true)); - assertThat(ImmutableSet.copyOf(result).size(), equalTo(0)); + Collection records = historyStore.loadRecords(cs, WatchRecord.State.AWAITS_EXECUTION); + assertThat(records, notNullValue()); + assertThat(records, hasSize(0)); - verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "alerthistory"); + verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "watch_history"); verify(clientProxy, times(1)).refresh(any(RefreshRequest.class)); } @Test public void testIndexNameGeneration() { - assertThat(HistoryStore.getAlertHistoryIndexNameForTime(new DateTime(0, DateTimeZone.UTC)), equalTo(".alert_history_1970-01-01")); - assertThat(HistoryStore.getAlertHistoryIndexNameForTime(new DateTime(100000000000L, DateTimeZone.UTC)), equalTo(".alert_history_1973-03-03")); - assertThat(HistoryStore.getAlertHistoryIndexNameForTime(new DateTime(1416582852000L, DateTimeZone.UTC)), equalTo(".alert_history_2014-11-21")); - assertThat(HistoryStore.getAlertHistoryIndexNameForTime(new DateTime(2833165811000L, DateTimeZone.UTC)), equalTo(".alert_history_2059-10-12")); + assertThat(HistoryStore.getHistoryIndexNameForTime(new DateTime(0, DateTimeZone.UTC)), equalTo(".watch_history_1970-01-01")); + assertThat(HistoryStore.getHistoryIndexNameForTime(new DateTime(100000000000L, DateTimeZone.UTC)), equalTo(".watch_history_1973-03-03")); + assertThat(HistoryStore.getHistoryIndexNameForTime(new DateTime(1416582852000L, DateTimeZone.UTC)), equalTo(".watch_history_2014-11-21")); + assertThat(HistoryStore.getHistoryIndexNameForTime(new DateTime(2833165811000L, DateTimeZone.UTC)), equalTo(".watch_history_2059-10-12")); } private RefreshResponse mockRefreshResponse(int total, int successful) { diff --git a/src/test/java/org/elasticsearch/watcher/history/WatchRecordTests.java b/src/test/java/org/elasticsearch/watcher/history/WatchRecordTests.java new file mode 100644 index 00000000000..3ce129d867f --- /dev/null +++ b/src/test/java/org/elasticsearch/watcher/history/WatchRecordTests.java @@ -0,0 +1,97 @@ +/* + * 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.watcher.history; + +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchExecution; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.actions.email.EmailAction; +import org.elasticsearch.watcher.actions.webhook.WebhookAction; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.simple.AlwaysFalseCondition; +import org.elasticsearch.watcher.condition.simple.AlwaysTrueCondition; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.simple.SimpleInput; +import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTests; +import org.elasticsearch.watcher.test.WatcherTestUtils; +import org.elasticsearch.watcher.throttle.Throttler; +import org.elasticsearch.common.joda.time.DateTime; +import org.elasticsearch.common.xcontent.ToXContent; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.junit.Test; + +import static org.hamcrest.Matchers.equalTo; + +/** + */ +public class WatchRecordTests extends AbstractWatcherIntegrationTests { + + @Test + public void testParser() throws Exception { + Watch watch = WatcherTestUtils.createTestWatch("fired_test", scriptService(), httpClient(), noopEmailService(), logger); + WatchRecord watchRecord = new WatchRecord(watch, new DateTime(), new DateTime()); + XContentBuilder jsonBuilder = XContentFactory.jsonBuilder(); + watchRecord.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS); + WatchRecord parsedWatchRecord = watchRecordParser().parse(jsonBuilder.bytes(), watchRecord.id(), 0); + + XContentBuilder jsonBuilder2 = XContentFactory.jsonBuilder(); + parsedWatchRecord.toXContent(jsonBuilder2, ToXContent.EMPTY_PARAMS); + + assertThat(jsonBuilder.bytes().toUtf8(), equalTo(jsonBuilder2.bytes().toUtf8())); + } + + @Test + public void testParser_WithSealedWatchRecord() throws Exception { + Watch watch = WatcherTestUtils.createTestWatch("fired_test", scriptService(), httpClient(), noopEmailService(), logger); + WatchRecord watchRecord = new WatchRecord(watch, new DateTime(), new DateTime()); + WatchExecutionContext ctx = new WatchExecutionContext(watchRecord.id(), watch, new DateTime(), new DateTime(), new DateTime()); + ctx.onActionResult(new EmailAction.Result.Failure("failed to send because blah")); + ctx.onActionResult(new WebhookAction.Result.Executed(300, "http://localhost:8000/watchfoo", "{'awesome' : 'us'}")); + Input.Result inputResult = new SimpleInput.Result(SimpleInput.TYPE, new Payload.Simple()); + Condition.Result conditionResult = AlwaysTrueCondition.RESULT; + ctx.onThrottleResult(Throttler.NO_THROTTLE.throttle(ctx)); + ctx.onInputResult(inputResult); + ctx.onConditionResult(conditionResult); + watchRecord.seal(new WatchExecution(ctx)); + + XContentBuilder jsonBuilder = XContentFactory.jsonBuilder(); + watchRecord.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS); + WatchRecord parsedWatchRecord = watchRecordParser().parse(jsonBuilder.bytes(), watchRecord.id(), 0); + + XContentBuilder jsonBuilder2 = XContentFactory.jsonBuilder(); + parsedWatchRecord.toXContent(jsonBuilder2, ToXContent.EMPTY_PARAMS); + + assertThat(jsonBuilder.bytes().toUtf8(), equalTo(jsonBuilder2.bytes().toUtf8())); + } + + @Test + public void testParser_WithSealedWatchRecord_WithScriptSearchCondition() throws Exception { + Watch watch = WatcherTestUtils.createTestWatch("fired_test", scriptService(), httpClient(), noopEmailService(), logger); + WatchRecord watchRecord = new WatchRecord(watch, new DateTime(), new DateTime()); + WatchExecutionContext ctx = new WatchExecutionContext(watchRecord.id(), watch, new DateTime(), new DateTime(), new DateTime()); + ctx.onActionResult(new EmailAction.Result.Failure("failed to send because blah")); + ctx.onActionResult(new WebhookAction.Result.Executed(300, "http://localhost:8000/watchfoo", "{'awesome' : 'us'}")); + Input.Result inputResult = new SimpleInput.Result(SimpleInput.TYPE, new Payload.Simple()); + Condition.Result conditionResult = AlwaysFalseCondition.RESULT; + ctx.onThrottleResult(Throttler.NO_THROTTLE.throttle(ctx)); + ctx.onInputResult(inputResult); + ctx.onConditionResult(conditionResult); + watchRecord.seal(new WatchExecution(ctx)); + + XContentBuilder jsonBuilder = XContentFactory.jsonBuilder(); + watchRecord.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS); + WatchRecord parsedWatchRecord = watchRecordParser().parse(jsonBuilder.bytes(), watchRecord.id(), 0); + + XContentBuilder jsonBuilder2 = XContentFactory.jsonBuilder(); + parsedWatchRecord.toXContent(jsonBuilder2, ToXContent.EMPTY_PARAMS); + + assertThat(jsonBuilder.bytes().toUtf8(), equalTo(jsonBuilder2.bytes().toUtf8())); + } + + +} diff --git a/src/test/java/org/elasticsearch/alerts/input/search/SearchInputTests.java b/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java similarity index 85% rename from src/test/java/org/elasticsearch/alerts/input/search/SearchInputTests.java rename to src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java index 914cb102c63..52469bfde47 100644 --- a/src/test/java/org/elasticsearch/alerts/input/search/SearchInputTests.java +++ b/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java @@ -3,25 +3,10 @@ * 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.alerts.input.search; +package org.elasticsearch.watcher.input.search; import org.elasticsearch.action.search.SearchRequest; 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.actions.Action; -import org.elasticsearch.alerts.actions.Actions; -import org.elasticsearch.alerts.condition.simple.AlwaysTrueCondition; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.InputException; -import org.elasticsearch.alerts.input.simple.SimpleInput; -import org.elasticsearch.alerts.scheduler.schedule.IntervalSchedule; -import org.elasticsearch.alerts.support.AlertUtils; -import org.elasticsearch.alerts.support.Variables; -import org.elasticsearch.alerts.support.clock.ClockMock; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.joda.time.DateTimeZone; import org.elasticsearch.common.settings.ImmutableSettings; @@ -34,6 +19,21 @@ import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.test.ElasticsearchIntegrationTest; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.Actions; +import org.elasticsearch.watcher.condition.simple.AlwaysTrueCondition; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.InputException; +import org.elasticsearch.watcher.input.simple.SimpleInput; +import org.elasticsearch.watcher.scheduler.schedule.IntervalSchedule; +import org.elasticsearch.watcher.support.Variables; +import org.elasticsearch.watcher.support.WatcherUtils; +import org.elasticsearch.watcher.support.clock.ClockMock; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchExecutionContext; import org.junit.Test; import java.util.ArrayList; @@ -56,8 +56,7 @@ public class SearchInputTests extends ElasticsearchIntegrationTest { @Test public void testExecute() throws Exception { 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) @@ -67,8 +66,8 @@ public class SearchInputTests extends ElasticsearchIntegrationTest { SearchInput searchInput = new SearchInput(logger, ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class)), ClientProxy.of(client()), request); - ExecutionContext ctx = new ExecutionContext("test-alert", - new Alert("test-alert", + WatchExecutionContext ctx = new WatchExecutionContext("test-watch", + new Watch("test-alert", new ClockMock(), new IntervalSchedule(new IntervalSchedule.Interval(1, IntervalSchedule.Interval.Unit.MINUTES)), new SimpleInput(logger, new Payload.Simple()), @@ -77,7 +76,7 @@ public class SearchInputTests extends ElasticsearchIntegrationTest { new Actions(new ArrayList()), null, null, - new Alert.Status()), + new Watch.Status()), new DateTime(0, DateTimeZone.UTC), new DateTime(0, DateTimeZone.UTC), new DateTime(0, DateTimeZone.UTC)); SearchInput.Result result = searchInput.execute(ctx); @@ -103,8 +102,8 @@ public class SearchInputTests extends ElasticsearchIntegrationTest { SearchInput searchInput = new SearchInput(logger, ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class)), ClientProxy.of(client()), request); - ExecutionContext ctx = new ExecutionContext("test-alert", - new Alert("test-alert", + WatchExecutionContext ctx = new WatchExecutionContext("test-watch", + new Watch("test-alert", new ClockMock(), new IntervalSchedule(new IntervalSchedule.Interval(1, IntervalSchedule.Interval.Unit.MINUTES)), new SimpleInput(logger, new Payload.Simple()), @@ -113,7 +112,7 @@ public class SearchInputTests extends ElasticsearchIntegrationTest { new Actions(new ArrayList()), null, null, - new Alert.Status()), + new Watch.Status()), new DateTime(0, DateTimeZone.UTC), new DateTime(0, DateTimeZone.UTC), new DateTime(0, DateTimeZone.UTC)); SearchInput.Result result = searchInput.execute(ctx); @@ -132,7 +131,7 @@ public class SearchInputTests extends ElasticsearchIntegrationTest { .source(searchSource() .query(filteredQuery(matchQuery("event_type", "a"), rangeFilter("_timestamp").from("{{" + Variables.SCHEDULED_FIRE_TIME + "}}||-30s").to("{{" + Variables.SCHEDULED_FIRE_TIME + "}}")))); - XContentBuilder builder = AlertUtils.writeSearchRequest(request, jsonBuilder(), ToXContent.EMPTY_PARAMS); + XContentBuilder builder = WatcherUtils.writeSearchRequest(request, jsonBuilder(), ToXContent.EMPTY_PARAMS); XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes()); parser.nextToken(); @@ -181,7 +180,7 @@ public class SearchInputTests extends ElasticsearchIntegrationTest { jsonBuilder.startObject(); jsonBuilder.field(Input.Result.PAYLOAD_FIELD.getPreferredName(), data); jsonBuilder.field(SearchInput.Parser.REQUEST_FIELD.getPreferredName()); - AlertUtils.writeSearchRequest(request, jsonBuilder, ToXContent.EMPTY_PARAMS); + WatcherUtils.writeSearchRequest(request, jsonBuilder, ToXContent.EMPTY_PARAMS); jsonBuilder.endObject(); Input.Parser searchInputParser = new SearchInput.Parser(ImmutableSettings.settingsBuilder().build(), diff --git a/src/test/java/org/elasticsearch/alerts/input/simple/SimpleInputTests.java b/src/test/java/org/elasticsearch/watcher/input/simple/SimpleInputTests.java similarity index 95% rename from src/test/java/org/elasticsearch/alerts/input/simple/SimpleInputTests.java rename to src/test/java/org/elasticsearch/watcher/input/simple/SimpleInputTests.java index defb4575e61..f5c8c78cca1 100644 --- a/src/test/java/org/elasticsearch/alerts/input/simple/SimpleInputTests.java +++ b/src/test/java/org/elasticsearch/watcher/input/simple/SimpleInputTests.java @@ -3,11 +3,11 @@ * 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.alerts.input.simple; +package org.elasticsearch.watcher.input.simple; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.InputException; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.InputException; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/InternalSchedulerTests.java b/src/test/java/org/elasticsearch/watcher/scheduler/InternalSchedulerTests.java similarity index 92% rename from src/test/java/org/elasticsearch/alerts/scheduler/InternalSchedulerTests.java rename to src/test/java/org/elasticsearch/watcher/scheduler/InternalSchedulerTests.java index cfbcaaab98c..2ad2fb50584 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/InternalSchedulerTests.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/InternalSchedulerTests.java @@ -3,14 +3,14 @@ * 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.alerts.scheduler; +package org.elasticsearch.watcher.scheduler; import org.apache.lucene.util.LuceneTestCase.Slow; -import org.elasticsearch.alerts.AlertsPlugin; -import org.elasticsearch.alerts.scheduler.schedule.Schedule; -import org.elasticsearch.alerts.scheduler.schedule.support.DayOfWeek; -import org.elasticsearch.alerts.scheduler.schedule.support.WeekTimes; -import org.elasticsearch.alerts.support.clock.SystemClock; +import org.elasticsearch.watcher.WatcherPlugin; +import org.elasticsearch.watcher.scheduler.schedule.Schedule; +import org.elasticsearch.watcher.scheduler.schedule.support.DayOfWeek; +import org.elasticsearch.watcher.scheduler.schedule.support.WeekTimes; +import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.joda.time.DateTimeZone; import org.elasticsearch.common.settings.ImmutableSettings; @@ -28,7 +28,7 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.*; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.*; import static org.hamcrest.Matchers.is; /** @@ -42,7 +42,7 @@ public class InternalSchedulerTests extends ElasticsearchTestCase { @Before public void init() throws Exception { - AlertsPlugin plugin = new AlertsPlugin(ImmutableSettings.EMPTY); + WatcherPlugin plugin = new WatcherPlugin(ImmutableSettings.EMPTY); Settings settings = ImmutableSettings.builder() .put(plugin.additionalSettings()) .put("name", "test") @@ -81,7 +81,7 @@ public class InternalSchedulerTests extends ElasticsearchTestCase { }); scheduler.start(jobs); if (!latch.await(5, TimeUnit.SECONDS)) { - fail("waiting too long for all alerts to be fired"); + fail("waiting too long for all watches to be triggered"); } scheduler.stop(); assertThat(bits.cardinality(), is(count)); @@ -114,7 +114,7 @@ public class InternalSchedulerTests extends ElasticsearchTestCase { long secondsToWait = now.getSecondOfMinute() < 29 ? 62 - now.getSecondOfMinute() : 122 - now.getSecondOfMinute(); logger.info("waiting at least [{}] seconds for response", secondsToWait); if (!latch.await(secondsToWait, TimeUnit.SECONDS)) { - fail("waiting too long for alert to be fired"); + fail("waiting too long for all watches to be triggered"); } } @@ -147,7 +147,7 @@ public class InternalSchedulerTests extends ElasticsearchTestCase { long secondsToWait = now.getSecondOfMinute() < 29 ? 62 - now.getSecondOfMinute() : 122 - now.getSecondOfMinute(); logger.info("waiting at least [{}] seconds for response", secondsToWait); if (!latch.await(secondsToWait, TimeUnit.SECONDS)) { - fail("waiting too long for alert to be fired"); + fail("waiting too long for all watches to be triggered"); } } @@ -182,7 +182,7 @@ public class InternalSchedulerTests extends ElasticsearchTestCase { long secondsToWait = now.getSecondOfMinute() < 29 ? 62 - now.getSecondOfMinute() : 122 - now.getSecondOfMinute(); logger.info("waiting at least [{}] seconds for response", secondsToWait); if (!latch.await(secondsToWait, TimeUnit.SECONDS)) { - fail("waiting too long for alert to be fired"); + fail("waiting too long for all watches to be triggered"); } } diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/SchedulerMock.java b/src/test/java/org/elasticsearch/watcher/scheduler/SchedulerMock.java similarity index 94% rename from src/test/java/org/elasticsearch/alerts/scheduler/SchedulerMock.java rename to src/test/java/org/elasticsearch/watcher/scheduler/SchedulerMock.java index 6e0faef639b..4f8d0958100 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/SchedulerMock.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/SchedulerMock.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler; +package org.elasticsearch.watcher.scheduler; -import org.elasticsearch.alerts.support.clock.Clock; -import org.elasticsearch.alerts.support.clock.ClockMock; +import org.elasticsearch.watcher.support.clock.Clock; +import org.elasticsearch.watcher.support.clock.ClockMock; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.logging.ESLogger; diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/CronScheduleTests.java b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/CronScheduleTests.java similarity index 92% rename from src/test/java/org/elasticsearch/alerts/scheduler/schedule/CronScheduleTests.java rename to src/test/java/org/elasticsearch/watcher/scheduler/schedule/CronScheduleTests.java index 01a722098fb..916f4bb2560 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/CronScheduleTests.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/CronScheduleTests.java @@ -3,9 +3,9 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -63,13 +63,13 @@ public class CronScheduleTests extends ScheduleTestCase { try { new CronSchedule.Parser().parse(parser); fail("expected cron parsing to fail when using invalid cron expression"); - } catch (AlertsSettingsException ase) { + } catch (WatcherSettingsException ase) { // expected assertThat(ase.getCause(), instanceOf(CronSchedule.ValidationException.class)); } } - @Test(expected = AlertsSettingsException.class) + @Test(expected = WatcherSettingsException.class) public void testParse_Invalid_Empty() throws Exception { XContentBuilder builder = jsonBuilder(); BytesReference bytes = builder.bytes(); @@ -78,7 +78,7 @@ public class CronScheduleTests extends ScheduleTestCase { new CronSchedule.Parser().parse(parser); } - @Test(expected = AlertsSettingsException.class) + @Test(expected = WatcherSettingsException.class) public void testParse_Invalid_Object() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = builder.bytes(); @@ -87,7 +87,7 @@ public class CronScheduleTests extends ScheduleTestCase { new CronSchedule.Parser().parse(parser); } - @Test(expected = AlertsSettingsException.class) + @Test(expected = WatcherSettingsException.class) public void testParse_Invalid_EmptyArray() throws Exception { XContentBuilder builder = jsonBuilder().value(new String[0]); BytesReference bytes = builder.bytes(); diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/DailyScheduleTests.java b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/DailyScheduleTests.java similarity index 92% rename from src/test/java/org/elasticsearch/alerts/scheduler/schedule/DailyScheduleTests.java rename to src/test/java/org/elasticsearch/watcher/scheduler/schedule/DailyScheduleTests.java index bbc62aa71e5..9abddc2a2d2 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/DailyScheduleTests.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/DailyScheduleTests.java @@ -3,11 +3,11 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; import com.carrotsearch.randomizedtesting.annotations.Repeat; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.support.DayTimes; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.support.DayTimes; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.primitives.Ints; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -45,10 +45,10 @@ public class DailyScheduleTests extends ScheduleTestCase { try { HourAndMinute ham = invalidDayTime(); new DayTimes(ham.hour, ham.minute); - fail("expected either a parse exception or an alerts settings exception on invalid time input"); + fail("expected either a parse exception or an watcher settings exception on invalid time input"); } catch (DayTimes.ParseException pe) { // expected - } catch (AlertsSettingsException ase) { + } catch (WatcherSettingsException ase) { // expected } } @@ -95,7 +95,7 @@ public class DailyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0], is(time)); } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_SingleTime_Object_Invalid() throws Exception { HourAndMinute time = invalidDayTime(); XContentBuilder builder = jsonBuilder() @@ -127,7 +127,7 @@ public class DailyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0], is(DayTimes.parse(timeStr))); } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_SingleTime_String_Invalid() throws Exception { XContentBuilder builder = jsonBuilder() .startObject() @@ -157,7 +157,7 @@ public class DailyScheduleTests extends ScheduleTestCase { } } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_MultipleTimes_Objects_Invalid() throws Exception { HourAndMinute[] times = invalidDayTimes(); XContentBuilder builder = jsonBuilder() @@ -188,7 +188,7 @@ public class DailyScheduleTests extends ScheduleTestCase { } } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_MultipleTimes_Strings_Invalid() throws Exception { String[] times = invalidDayTimesAsStrings(); XContentBuilder builder = jsonBuilder() diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/HourlyScheduleTests.java b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/HourlyScheduleTests.java similarity index 93% rename from src/test/java/org/elasticsearch/alerts/scheduler/schedule/HourlyScheduleTests.java rename to src/test/java/org/elasticsearch/watcher/scheduler/schedule/HourlyScheduleTests.java index b60473750c2..fe7d3928239 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/HourlyScheduleTests.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/HourlyScheduleTests.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; import com.carrotsearch.randomizedtesting.annotations.Repeat; -import org.elasticsearch.alerts.AlertsSettingsException; +import org.elasticsearch.watcher.WatcherSettingsException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Collections2; import org.elasticsearch.common.primitives.Ints; @@ -40,7 +40,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(crons, arrayContaining("0 " + minute + " * * * ?")); } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void test_SingleMinute_Invalid() throws Exception { new HourlySchedule(invalidMinute()); } @@ -55,7 +55,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(crons, arrayContaining("0 " + minutesStr + " * * * ?")); } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void test_MultipleMinutes_Invalid() throws Exception { int[] minutes = invalidMinutes(); new HourlySchedule(minutes); @@ -89,7 +89,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(schedule.minutes()[0], is(minute)); } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_SingleMinute_Number_Invalid() throws Exception { XContentBuilder builder = jsonBuilder() .startObject() @@ -117,7 +117,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(schedule.minutes()[0], is(minute)); } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_SingleMinute_String_Invalid() throws Exception { XContentBuilder builder = jsonBuilder() .startObject() @@ -147,7 +147,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { } } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_MultipleMinutes_Numbers_Invalid() throws Exception { int[] minutes = invalidMinutes(); XContentBuilder builder = jsonBuilder() @@ -178,7 +178,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { } } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_MultipleMinutes_Strings_Invalid() throws Exception { int[] minutes = invalidMinutes(); XContentBuilder builder = jsonBuilder() diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/IntervalScheduleTests.java b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/IntervalScheduleTests.java similarity index 90% rename from src/test/java/org/elasticsearch/alerts/scheduler/schedule/IntervalScheduleTests.java rename to src/test/java/org/elasticsearch/watcher/scheduler/schedule/IntervalScheduleTests.java index 4ce76380bff..a4dc5497b3e 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/IntervalScheduleTests.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/IntervalScheduleTests.java @@ -3,10 +3,10 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.IntervalSchedule.Interval.Unit; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.IntervalSchedule.Interval.Unit; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -47,7 +47,7 @@ public class IntervalScheduleTests extends ElasticsearchTestCase { assertThat(schedule.interval(), is(value)); } - @Test(expected = AlertsSettingsException.class) + @Test(expected = WatcherSettingsException.class) public void testParse_Invalid_String() throws Exception { XContentBuilder builder = jsonBuilder().value("43S"); BytesReference bytes = builder.bytes(); @@ -56,7 +56,7 @@ public class IntervalScheduleTests extends ElasticsearchTestCase { new IntervalSchedule.Parser().parse(parser); } - @Test(expected = AlertsSettingsException.class) + @Test(expected = WatcherSettingsException.class) public void testParse_Invalid_Object() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = builder.bytes(); diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/MonthlyScheduleTests.java b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/MonthlyScheduleTests.java similarity index 93% rename from src/test/java/org/elasticsearch/alerts/scheduler/schedule/MonthlyScheduleTests.java rename to src/test/java/org/elasticsearch/watcher/scheduler/schedule/MonthlyScheduleTests.java index a5887db8c10..5966d2a4b6c 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/MonthlyScheduleTests.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/MonthlyScheduleTests.java @@ -3,12 +3,12 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; import com.carrotsearch.randomizedtesting.annotations.Repeat; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.support.DayTimes; -import org.elasticsearch.alerts.scheduler.schedule.support.MonthTimes; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.support.DayTimes; +import org.elasticsearch.watcher.scheduler.schedule.support.MonthTimes; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.primitives.Ints; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -104,7 +104,7 @@ public class MonthlyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0].times(), hasItemInArray(time)); } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_SingleTime_Invalid() throws Exception { HourAndMinute time = invalidDayTime(); XContentBuilder builder = jsonBuilder() @@ -136,7 +136,7 @@ public class MonthlyScheduleTests extends ScheduleTestCase { } } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_MultipleTimes_Invalid() throws Exception { HourAndMinute[] times = invalidDayTimes(); XContentBuilder builder = jsonBuilder() diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/ScheduleRegistryTests.java b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/ScheduleRegistryTests.java similarity index 97% rename from src/test/java/org/elasticsearch/alerts/scheduler/schedule/ScheduleRegistryTests.java rename to src/test/java/org/elasticsearch/watcher/scheduler/schedule/ScheduleRegistryTests.java index b99526f1d41..e199e0e0ed8 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/ScheduleRegistryTests.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/ScheduleRegistryTests.java @@ -3,7 +3,7 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; import com.carrotsearch.randomizedtesting.annotations.Repeat; import org.elasticsearch.common.bytes.BytesReference; @@ -16,7 +16,7 @@ import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.cron; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.cron; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.*; diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/ScheduleTestCase.java b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/ScheduleTestCase.java similarity index 97% rename from src/test/java/org/elasticsearch/alerts/scheduler/schedule/ScheduleTestCase.java rename to src/test/java/org/elasticsearch/watcher/scheduler/schedule/ScheduleTestCase.java index 761e0bea022..fc4f226126a 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/ScheduleTestCase.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/ScheduleTestCase.java @@ -3,11 +3,11 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; import com.google.common.primitives.Ints; -import org.elasticsearch.alerts.scheduler.schedule.IntervalSchedule.Interval.Unit; -import org.elasticsearch.alerts.scheduler.schedule.support.*; +import org.elasticsearch.watcher.scheduler.schedule.IntervalSchedule.Interval.Unit; +import org.elasticsearch.watcher.scheduler.schedule.support.*; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.test.ElasticsearchTestCase; @@ -17,7 +17,7 @@ import java.util.EnumSet; import java.util.HashSet; import java.util.Set; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.*; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.*; /** * diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/WeeklyScheduleTests.java b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/WeeklyScheduleTests.java similarity index 92% rename from src/test/java/org/elasticsearch/alerts/scheduler/schedule/WeeklyScheduleTests.java rename to src/test/java/org/elasticsearch/watcher/scheduler/schedule/WeeklyScheduleTests.java index 3cd14c37344..4a847df4bf7 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/WeeklyScheduleTests.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/WeeklyScheduleTests.java @@ -3,13 +3,13 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; import com.carrotsearch.randomizedtesting.annotations.Repeat; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.support.DayTimes; -import org.elasticsearch.alerts.scheduler.schedule.support.DayOfWeek; -import org.elasticsearch.alerts.scheduler.schedule.support.WeekTimes; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.support.DayTimes; +import org.elasticsearch.watcher.scheduler.schedule.support.DayOfWeek; +import org.elasticsearch.watcher.scheduler.schedule.support.WeekTimes; import org.elasticsearch.common.base.Joiner; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.primitives.Ints; @@ -97,7 +97,7 @@ public class WeeklyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0].times(), hasItemInArray(time)); } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_SingleTime_Invalid() throws Exception { HourAndMinute time = invalidDayTime(); XContentBuilder builder = jsonBuilder() @@ -129,7 +129,7 @@ public class WeeklyScheduleTests extends ScheduleTestCase { } } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_MultipleTimes_Objects_Invalid() throws Exception { HourAndMinute[] times = invalidDayTimes(); XContentBuilder builder = jsonBuilder() diff --git a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/YearlyScheduleTests.java b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/YearlyScheduleTests.java similarity index 94% rename from src/test/java/org/elasticsearch/alerts/scheduler/schedule/YearlyScheduleTests.java rename to src/test/java/org/elasticsearch/watcher/scheduler/schedule/YearlyScheduleTests.java index 82738cf53c3..758fdcc334e 100644 --- a/src/test/java/org/elasticsearch/alerts/scheduler/schedule/YearlyScheduleTests.java +++ b/src/test/java/org/elasticsearch/watcher/scheduler/schedule/YearlyScheduleTests.java @@ -3,12 +3,12 @@ * 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.alerts.scheduler.schedule; +package org.elasticsearch.watcher.scheduler.schedule; import com.carrotsearch.randomizedtesting.annotations.Repeat; -import org.elasticsearch.alerts.AlertsSettingsException; -import org.elasticsearch.alerts.scheduler.schedule.support.DayTimes; -import org.elasticsearch.alerts.scheduler.schedule.support.YearTimes; +import org.elasticsearch.watcher.WatcherSettingsException; +import org.elasticsearch.watcher.scheduler.schedule.support.DayTimes; +import org.elasticsearch.watcher.scheduler.schedule.support.YearTimes; import org.elasticsearch.common.base.Joiner; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.primitives.Ints; @@ -109,7 +109,7 @@ public class YearlyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0].times(), hasItemInArray(time)); } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_SingleTime_Invalid() throws Exception { HourAndMinute time = invalidDayTime(); XContentBuilder builder = jsonBuilder() @@ -142,7 +142,7 @@ public class YearlyScheduleTests extends ScheduleTestCase { } } - @Test(expected = AlertsSettingsException.class) @Repeat(iterations = 20) + @Test(expected = WatcherSettingsException.class) @Repeat(iterations = 20) public void testParser_MultipleTimes_Invalid() throws Exception { HourAndMinute[] times = invalidDayTimes(); XContentBuilder builder = jsonBuilder() diff --git a/src/test/java/org/elasticsearch/alerts/support/AlertUtilsTests.java b/src/test/java/org/elasticsearch/watcher/support/WatcherUtilsTests.java similarity index 89% rename from src/test/java/org/elasticsearch/alerts/support/AlertUtilsTests.java rename to src/test/java/org/elasticsearch/watcher/support/WatcherUtilsTests.java index 1b5349a7668..d68ff25fa1c 100644 --- a/src/test/java/org/elasticsearch/alerts/support/AlertUtilsTests.java +++ b/src/test/java/org/elasticsearch/watcher/support/WatcherUtilsTests.java @@ -3,12 +3,12 @@ * 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.alerts.support; +package org.elasticsearch.watcher.support; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.alerts.input.search.SearchInput; +import org.elasticsearch.watcher.input.search.SearchInput; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.joda.time.DateTime; @@ -25,15 +25,15 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import static org.elasticsearch.alerts.support.AlertUtils.flattenModel; -import static org.elasticsearch.alerts.support.AlertsDateUtils.formatDate; +import static org.elasticsearch.watcher.support.WatcherUtils.flattenModel; +import static org.elasticsearch.watcher.support.WatcherDateUtils.formatDate; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.*; /** * */ -public class AlertUtilsTests extends ElasticsearchTestCase { +public class WatcherUtilsTests extends ElasticsearchTestCase { @Test public void testFlattenModel() throws Exception { @@ -78,7 +78,7 @@ public class AlertUtilsTests extends ElasticsearchTestCase { return builder; } }; - Map result = AlertUtils.responseToData(content); + Map result = WatcherUtils.responseToData(content); assertThat(result, equalTo(expected)); } @@ -86,7 +86,7 @@ public class AlertUtilsTests extends ElasticsearchTestCase { public void testSerializeSearchRequest() throws Exception { String[] randomIndices = generateRandomStringArray(5, 5); SearchRequest expectedRequest = new SearchRequest(randomIndices); - expectedRequest.indicesOptions(IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), AlertUtils.DEFAULT_INDICES_OPTIONS)); + expectedRequest.indicesOptions(IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), WatcherUtils.DEFAULT_INDICES_OPTIONS)); expectedRequest.searchType(randomFrom(SearchType.values())); SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery()).size(11); @@ -109,10 +109,10 @@ public class AlertUtilsTests extends ElasticsearchTestCase { } XContentBuilder builder = jsonBuilder(); - builder = AlertUtils.writeSearchRequest(expectedRequest, builder, ToXContent.EMPTY_PARAMS); + builder = WatcherUtils.writeSearchRequest(expectedRequest, builder, ToXContent.EMPTY_PARAMS); XContentParser parser = XContentHelper.createParser(builder.bytes()); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); - SearchRequest result = AlertUtils.readSearchRequest(parser, SearchInput.DEFAULT_SEARCH_TYPE); + SearchRequest result = WatcherUtils.readSearchRequest(parser, SearchInput.DEFAULT_SEARCH_TYPE); assertThat(result.indices(), arrayContainingInAnyOrder(expectedRequest.indices())); assertThat(result.indicesOptions(), equalTo(expectedRequest.indicesOptions())); diff --git a/src/test/java/org/elasticsearch/alerts/support/clock/ClockMock.java b/src/test/java/org/elasticsearch/watcher/support/clock/ClockMock.java similarity index 96% rename from src/test/java/org/elasticsearch/alerts/support/clock/ClockMock.java rename to src/test/java/org/elasticsearch/watcher/support/clock/ClockMock.java index 30369ff47b4..f445f16b6f7 100644 --- a/src/test/java/org/elasticsearch/alerts/support/clock/ClockMock.java +++ b/src/test/java/org/elasticsearch/watcher/support/clock/ClockMock.java @@ -3,7 +3,7 @@ * 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.alerts.support.clock; +package org.elasticsearch.watcher.support.clock; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.joda.time.Duration; diff --git a/src/test/java/org/elasticsearch/alerts/support/template/ScriptTemplateTests.java b/src/test/java/org/elasticsearch/watcher/support/template/ScriptTemplateTests.java similarity index 97% rename from src/test/java/org/elasticsearch/alerts/support/template/ScriptTemplateTests.java rename to src/test/java/org/elasticsearch/watcher/support/template/ScriptTemplateTests.java index d276030fa37..c5e459e11c5 100644 --- a/src/test/java/org/elasticsearch/alerts/support/template/ScriptTemplateTests.java +++ b/src/test/java/org/elasticsearch/watcher/support/template/ScriptTemplateTests.java @@ -3,10 +3,10 @@ * 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.alerts.support.template; +package org.elasticsearch.watcher.support.template; -import org.elasticsearch.alerts.support.Script; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.settings.ImmutableSettings; diff --git a/src/test/java/org/elasticsearch/alerts/support/template/XContentTemplateTests.java b/src/test/java/org/elasticsearch/watcher/support/template/XContentTemplateTests.java similarity index 98% rename from src/test/java/org/elasticsearch/alerts/support/template/XContentTemplateTests.java rename to src/test/java/org/elasticsearch/watcher/support/template/XContentTemplateTests.java index 5972197eda2..affefa1769a 100644 --- a/src/test/java/org/elasticsearch/alerts/support/template/XContentTemplateTests.java +++ b/src/test/java/org/elasticsearch/watcher/support/template/XContentTemplateTests.java @@ -3,7 +3,7 @@ * 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.alerts.support.template; +package org.elasticsearch.watcher.support.template; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.xcontent.XContentParser; diff --git a/src/test/java/org/elasticsearch/alerts/test/AbstractAlertsIntegrationTests.java b/src/test/java/org/elasticsearch/watcher/test/AbstractWatcherIntegrationTests.java similarity index 63% rename from src/test/java/org/elasticsearch/alerts/test/AbstractAlertsIntegrationTests.java rename to src/test/java/org/elasticsearch/watcher/test/AbstractWatcherIntegrationTests.java index 30e6ce68ceb..7a929ea84f1 100644 --- a/src/test/java/org/elasticsearch/alerts/test/AbstractAlertsIntegrationTests.java +++ b/src/test/java/org/elasticsearch/watcher/test/AbstractWatcherIntegrationTests.java @@ -3,33 +3,33 @@ * 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.alerts.test; +package org.elasticsearch.watcher.test; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.AlertsPlugin; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.actions.email.service.Authentication; -import org.elasticsearch.alerts.actions.email.service.Email; -import org.elasticsearch.alerts.actions.email.service.EmailService; -import org.elasticsearch.alerts.actions.email.service.Profile; -import org.elasticsearch.alerts.actions.webhook.HttpClient; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.history.FiredAlert; -import org.elasticsearch.alerts.history.HistoryStore; -import org.elasticsearch.alerts.scheduler.Scheduler; -import org.elasticsearch.alerts.scheduler.SchedulerMock; -import org.elasticsearch.alerts.scheduler.schedule.Schedule; -import org.elasticsearch.alerts.scheduler.schedule.Schedules; -import org.elasticsearch.alerts.support.AlertUtils; -import org.elasticsearch.alerts.support.clock.ClockMock; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; -import org.elasticsearch.alerts.support.template.Template; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsResponse; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.WatcherPlugin; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.actions.email.service.Authentication; +import org.elasticsearch.watcher.actions.email.service.Email; +import org.elasticsearch.watcher.actions.email.service.EmailService; +import org.elasticsearch.watcher.actions.email.service.Profile; +import org.elasticsearch.watcher.actions.webhook.HttpClient; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.history.WatchRecord; +import org.elasticsearch.watcher.history.HistoryStore; +import org.elasticsearch.watcher.scheduler.Scheduler; +import org.elasticsearch.watcher.scheduler.SchedulerMock; +import org.elasticsearch.watcher.scheduler.schedule.Schedule; +import org.elasticsearch.watcher.scheduler.schedule.Schedules; +import org.elasticsearch.watcher.support.WatcherUtils; +import org.elasticsearch.watcher.support.clock.ClockMock; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.support.template.Template; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; @@ -66,7 +66,7 @@ import static org.hamcrest.core.IsNot.not; /** */ @ClusterScope(scope = SUITE, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false) -public abstract class AbstractAlertsIntegrationTests extends ElasticsearchIntegrationTest { +public abstract class AbstractWatcherIntegrationTests extends ElasticsearchIntegrationTest { private static final boolean timeWarpEnabled = SystemPropertyUtil.getBoolean("tests.timewarp", true); @@ -77,7 +77,7 @@ public abstract class AbstractAlertsIntegrationTests extends ElasticsearchIntegr return ImmutableSettings.builder() .put(super.nodeSettings(nodeOrdinal)) .put("scroll.size", randomIntBetween(1, 100)) - .put("plugin.types", timeWarped() ? TimeWarpedAlertsPlugin.class.getName() : AlertsPlugin.class.getName()) + .put("plugin.types", timeWarped() ? TimeWarpedWatcherPlugin.class.getName() : WatcherPlugin.class.getName()) .build(); } @@ -111,32 +111,32 @@ public abstract class AbstractAlertsIntegrationTests extends ElasticsearchIntegr @Override protected TestCluster buildTestCluster(Scope scope, long seed) throws IOException { - // This overwrites the wipe logic of the test cluster to not remove the alerts and alerthistory templates. By default all templates are removed + // This overwrites the wipe logic of the test cluster to not remove the watches and watch_history templates. By default all templates are removed // TODO: We should have the notion of a hidden template (like hidden index / type) that only gets removed when specifically mentioned. final TestCluster testCluster = super.buildTestCluster(scope, seed); - return new AlertingWrappingCluster(seed, testCluster); + return new WatcherWrappingCluster(seed, testCluster); } @Before - public void startAlertsIfNodesExist() throws Exception { + public void startWatcherIfNodesExist() throws Exception { if (internalTestCluster().size() > 0) { - AlertsStatsResponse response = alertClient().prepareAlertsStats().get(); - if (response.getAlertManagerStarted() == AlertsService.State.STOPPED) { - logger.info("[{}#{}]: starting alerts", getTestClass().getSimpleName(), getTestName()); - startAlerting(); + WatcherStatsResponse response = watcherClient().prepareWatcherStats().get(); + if (response.getWatchServiceState() == WatchService.State.STOPPED) { + logger.info("[{}#{}]: starting watcher", getTestClass().getSimpleName(), getTestName()); + startWatcher(); } else { - logger.info("[{}#{}]: not starting alerts, because alerts is in state [{}]", getTestClass().getSimpleName(), getTestName(), response.getAlertManagerStarted()); + logger.info("[{}#{}]: not starting watcher, because watcher is in state [{}]", getTestClass().getSimpleName(), getTestName(), response.getWatchServiceState()); } } else { - logger.info("[{}#{}]: not starting alerts, because test cluster has no nodes", getTestClass().getSimpleName(), getTestName()); + logger.info("[{}#{}]: not starting watcher, because test cluster has no nodes", getTestClass().getSimpleName(), getTestName()); } } @After - public void clearAlerts() throws Exception { - // Clear all internal alerting state for the next test method: - logger.info("[{}#{}]: clearing alerts", getTestClass().getSimpleName(), getTestName()); - stopAlerting(); + public void clearWatches() throws Exception { + // Clear all internal watcher state for the next test method: + logger.info("[{}#{}]: clearing watches", getTestClass().getSimpleName(), getTestName()); + stopWatcher(); } protected long docCount(String index, String type, QueryBuilder query) { @@ -152,19 +152,19 @@ public abstract class AbstractAlertsIntegrationTests extends ElasticsearchIntegr return builder.get().getHits().getTotalHits(); } - protected BytesReference createAlertSource(String cron, SearchRequest conditionRequest, String conditionScript) throws IOException { - return createAlertSource(cron, conditionRequest, conditionScript, null); + protected BytesReference createWatchSource(String cron, SearchRequest conditionRequest, String conditionScript) throws IOException { + return createWatchSource(cron, conditionRequest, conditionScript, null); } - protected BytesReference createAlertSource(Schedule schedule, SearchRequest conditionRequest, String conditionScript) throws IOException { - return createAlertSource(schedule, conditionRequest, conditionScript, null); + protected BytesReference createWatchSource(Schedule schedule, SearchRequest conditionRequest, String conditionScript) throws IOException { + return createWatchSource(schedule, conditionRequest, conditionScript, null); } - protected BytesReference createAlertSource(String cron, SearchRequest conditionRequest, String conditionScript, Map metadata) throws IOException { - return createAlertSource(Schedules.cron(cron), conditionRequest, conditionScript, metadata); + protected BytesReference createWatchSource(String cron, SearchRequest conditionRequest, String conditionScript, Map metadata) throws IOException { + return createWatchSource(Schedules.cron(cron), conditionRequest, conditionScript, metadata); } - protected BytesReference createAlertSource(Schedule schedule, SearchRequest conditionRequest, String conditionScript, Map metadata) throws IOException { + protected BytesReference createWatchSource(Schedule schedule, SearchRequest conditionRequest, String conditionScript, Map metadata) throws IOException { XContentBuilder builder = jsonBuilder(); builder.startObject(); { @@ -179,7 +179,7 @@ public abstract class AbstractAlertsIntegrationTests extends ElasticsearchIntegr builder.startObject("input"); { builder.field("search"); - AlertUtils.writeSearchRequest(conditionRequest, builder, ToXContent.EMPTY_PARAMS); + WatcherUtils.writeSearchRequest(conditionRequest, builder, ToXContent.EMPTY_PARAMS); } builder.endObject(); @@ -210,16 +210,16 @@ public abstract class AbstractAlertsIntegrationTests extends ElasticsearchIntegr return builder.bytes(); } - protected Alert.Parser alertParser() { - return internalTestCluster().getInstance(Alert.Parser.class, internalTestCluster().getMasterName()); + protected Watch.Parser watchParser() { + return internalTestCluster().getInstance(Watch.Parser.class, internalTestCluster().getMasterName()); } protected Scheduler scheduler() { return internalTestCluster().getInstance(Scheduler.class, internalTestCluster().getMasterName()); } - protected AlertsClient alertClient() { - return internalTestCluster().getInstance(AlertsClient.class); + protected WatcherClient watcherClient() { + return internalTestCluster().getInstance(WatcherClient.class); } protected ScriptServiceProxy scriptService() { @@ -238,125 +238,125 @@ public abstract class AbstractAlertsIntegrationTests extends ElasticsearchIntegr return new NoopEmailService(); } - protected FiredAlert.Parser firedAlertParser() { - return internalTestCluster().getInstance(FiredAlert.Parser.class); + protected WatchRecord.Parser watchRecordParser() { + return internalTestCluster().getInstance(WatchRecord.Parser.class); } - protected void assertAlertWithExactPerformedActionsCount(final String alertName, final long expectedAlertActionsWithActionPerformed) throws Exception { + protected void assertWatchWithExactPerformedActionsCount(final String watchName, final long expectedWatchActionsWithActionPerformed) throws Exception { assertBusy(new Runnable() { @Override public void run() { ClusterState state = client().admin().cluster().prepareState().get().getState(); - String[] alertHistoryIndices = state.metaData().concreteIndices(IndicesOptions.lenientExpandOpen(), HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*"); - assertThat(alertHistoryIndices, not(emptyArray())); - for (String index : alertHistoryIndices) { + String[] watchHistoryIndices = state.metaData().concreteIndices(IndicesOptions.lenientExpandOpen(), HistoryStore.INDEX_PREFIX + "*"); + assertThat(watchHistoryIndices, not(emptyArray())); + for (String index : watchHistoryIndices) { IndexRoutingTable routingTable = state.getRoutingTable().index(index); assertThat(routingTable, notNullValue()); assertThat(routingTable.allPrimaryShardsActive(), is(true)); } - assertThat(findNumberOfPerformedActions(alertName), equalTo(expectedAlertActionsWithActionPerformed)); + assertThat(findNumberOfPerformedActions(watchName), equalTo(expectedWatchActionsWithActionPerformed)); } }); } - protected void assertAlertWithMinimumPerformedActionsCount(final String alertName, final long minimumExpectedAlertActionsWithActionPerformed) throws Exception { - assertAlertWithMinimumPerformedActionsCount(alertName, minimumExpectedAlertActionsWithActionPerformed, true); + protected void assertWatchWithMinimumPerformedActionsCount(final String watchName, final long minimumExpectedWatchActionsWithActionPerformed) throws Exception { + assertWatchWithMinimumPerformedActionsCount(watchName, minimumExpectedWatchActionsWithActionPerformed, true); } - protected void assertAlertWithMinimumPerformedActionsCount(final String alertName, final long minimumExpectedAlertActionsWithActionPerformed, final boolean assertConditionMet) throws Exception { + protected void assertWatchWithMinimumPerformedActionsCount(final String watchName, final long minimumExpectedWatchActionsWithActionPerformed, final boolean assertConditionMet) throws Exception { assertBusy(new Runnable() { @Override public void run() { ClusterState state = client().admin().cluster().prepareState().get().getState(); - String[] alertHistoryIndices = state.metaData().concreteIndices(IndicesOptions.lenientExpandOpen(), HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*"); - assertThat(alertHistoryIndices, not(emptyArray())); - for (String index : alertHistoryIndices) { + String[] watchHistoryIndices = state.metaData().concreteIndices(IndicesOptions.lenientExpandOpen(), HistoryStore.INDEX_PREFIX + "*"); + assertThat(watchHistoryIndices, not(emptyArray())); + for (String index : watchHistoryIndices) { IndexRoutingTable routingTable = state.getRoutingTable().index(index); assertThat(routingTable, notNullValue()); assertThat(routingTable.allPrimaryShardsActive(), is(true)); } - SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") + SearchResponse searchResponse = client().prepareSearch(HistoryStore.INDEX_PREFIX + "*") .setIndicesOptions(IndicesOptions.lenientExpandOpen()) - .setQuery(boolQuery().must(matchQuery("alert_name", alertName)).must(matchQuery("state", FiredAlert.State.EXECUTED.id()))) + .setQuery(boolQuery().must(matchQuery("watch_name", watchName)).must(matchQuery("state", WatchRecord.State.EXECUTED.id()))) .get(); - assertThat("could not find executed fired alert", searchResponse.getHits().getTotalHits(), greaterThanOrEqualTo(minimumExpectedAlertActionsWithActionPerformed)); + assertThat("could not find executed watch record", searchResponse.getHits().getTotalHits(), greaterThanOrEqualTo(minimumExpectedWatchActionsWithActionPerformed)); if (assertConditionMet) { - assertThat((Integer) XContentMapValues.extractValue("alert_execution.input_result.search.payload.hits.total", searchResponse.getHits().getAt(0).sourceAsMap()), greaterThanOrEqualTo(1)); + assertThat((Integer) XContentMapValues.extractValue("watch_execution.input_result.search.payload.hits.total", searchResponse.getHits().getAt(0).sourceAsMap()), greaterThanOrEqualTo(1)); } } }); } - protected long findNumberOfPerformedActions(String alertName) { - SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") + protected long findNumberOfPerformedActions(String watchName) { + SearchResponse searchResponse = client().prepareSearch(HistoryStore.INDEX_PREFIX + "*") .setIndicesOptions(IndicesOptions.lenientExpandOpen()) - .setQuery(boolQuery().must(matchQuery("alert_name", alertName)).must(matchQuery("state", FiredAlert.State.EXECUTED.id()))) + .setQuery(boolQuery().must(matchQuery("watch_name", watchName)).must(matchQuery("state", WatchRecord.State.EXECUTED.id()))) .get(); return searchResponse.getHits().getTotalHits(); } - protected void assertAlertWithNoActionNeeded(final String alertName, final long expectedAlertActionsWithNoActionNeeded) throws Exception { + protected void assertWatchWithNoActionNeeded(final String watchName, final long expectedWatchActionsWithNoActionNeeded) throws Exception { assertBusy(new Runnable() { @Override public void run() { - // The alerthistory index gets created in the background when the first alert fires, so we to check first is this index is created and shards are started + // The watch_history index gets created in the background when the first watch is triggered, so we to check first is this index is created and shards are started ClusterState state = client().admin().cluster().prepareState().get().getState(); - String[] alertHistoryIndices = state.metaData().concreteIndices(IndicesOptions.lenientExpandOpen(), HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*"); - assertThat(alertHistoryIndices, not(emptyArray())); - for (String index : alertHistoryIndices) { + String[] watchHistoryIndices = state.metaData().concreteIndices(IndicesOptions.lenientExpandOpen(), HistoryStore.INDEX_PREFIX + "*"); + assertThat(watchHistoryIndices, not(emptyArray())); + for (String index : watchHistoryIndices) { IndexRoutingTable routingTable = state.getRoutingTable().index(index); assertThat(routingTable, notNullValue()); assertThat(routingTable.allPrimaryShardsActive(), is(true)); } - SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") + SearchResponse searchResponse = client().prepareSearch(HistoryStore.INDEX_PREFIX + "*") .setIndicesOptions(IndicesOptions.lenientExpandOpen()) - .setQuery(boolQuery().must(matchQuery("alert_name", alertName)).must(matchQuery("state", FiredAlert.State.EXECUTION_NOT_NEEDED.id()))) + .setQuery(boolQuery().must(matchQuery("watch_name", watchName)).must(matchQuery("state", WatchRecord.State.EXECUTION_NOT_NEEDED.id()))) .get(); - assertThat(searchResponse.getHits().getTotalHits(), greaterThanOrEqualTo(expectedAlertActionsWithNoActionNeeded)); + assertThat(searchResponse.getHits().getTotalHits(), greaterThanOrEqualTo(expectedWatchActionsWithNoActionNeeded)); } }); } - protected void ensureAlertingStarted() throws Exception { + protected void ensureWatcherStarted() throws Exception { assertBusy(new Runnable() { @Override public void run() { - assertThat(alertClient().prepareAlertsStats().get().getAlertManagerStarted(), is(AlertsService.State.STARTED)); + assertThat(watcherClient().prepareWatcherStats().get().getWatchServiceState(), is(WatchService.State.STARTED)); } }); } - protected void ensureAlertingStopped() throws Exception { + protected void ensureWatcherStopped() throws Exception { assertBusy(new Runnable() { @Override public void run() { - assertThat(alertClient().prepareAlertsStats().get().getAlertManagerStarted(), is(AlertsService.State.STOPPED)); + assertThat(watcherClient().prepareWatcherStats().get().getWatchServiceState(), is(WatchService.State.STOPPED)); } }); } - protected void startAlerting() throws Exception { - alertClient().prepareAlertService().start().get(); - ensureAlertingStarted(); + protected void startWatcher() throws Exception { + watcherClient().prepareWatchService().start().get(); + ensureWatcherStarted(); } - protected void stopAlerting() throws Exception { - alertClient().prepareAlertService().stop().get(); - ensureAlertingStopped(); + protected void stopWatcher() throws Exception { + watcherClient().prepareWatchService().stop().get(); + ensureWatcherStopped(); } protected static InternalTestCluster internalTestCluster() { - return (InternalTestCluster) ((AlertingWrappingCluster) cluster()).testCluster; + return (InternalTestCluster) ((WatcherWrappingCluster) cluster()).testCluster; } - private final class AlertingWrappingCluster extends TestCluster { + private final class WatcherWrappingCluster extends TestCluster { private final TestCluster testCluster; - private AlertingWrappingCluster(long seed, TestCluster testCluster) { + private WatcherWrappingCluster(long seed, TestCluster testCluster) { super(seed); this.testCluster = testCluster; } @@ -375,7 +375,7 @@ public abstract class AbstractAlertsIntegrationTests extends ElasticsearchIntegr List templatesToWipe = new ArrayList<>(); ClusterState state = client().admin().cluster().prepareState().get().getState(); for (ObjectObjectCursor cursor : state.getMetaData().templates()) { - if (cursor.key.equals("alerts") || cursor.key.equals("alerthistory")) { + if (cursor.key.equals("watches") || cursor.key.equals("watch_history")) { continue; } templatesToWipe.add(cursor.key); @@ -428,39 +428,39 @@ public abstract class AbstractAlertsIntegrationTests extends ElasticsearchIntegr String masterNode = _testCluster.getMasterName(); nodes.remove(masterNode); - // First manually stop alerting on non elected master node, this will prevent that alerting becomes active + // First manually stop watcher on non elected master node, this will prevent that watcher becomes active // on these nodes for (String node : nodes) { - AlertsService alertsService = _testCluster.getInstance(AlertsService.class, node); - assertThat(alertsService.state(), equalTo(AlertsService.State.STOPPED)); - alertsService.stop(); // Prevents these nodes from starting alerting when new elected master node is picked. + WatchService watchService = _testCluster.getInstance(WatchService.class, node); + assertThat(watchService.state(), equalTo(WatchService.State.STOPPED)); + watchService.stop(); // Prevents these nodes from starting watcher when new elected master node is picked. } - // Then stop alerting on elected master node and wait until alerting has stopped on it. - final AlertsService alertsService = _testCluster.getInstance(AlertsService.class, masterNode); + // Then stop watcher on elected master node and wait until watcher has stopped on it. + final WatchService watchService = _testCluster.getInstance(WatchService.class, masterNode); try { assertBusy(new Runnable() { @Override public void run() { - assertThat(alertsService.state(), not(equalTo(AlertsService.State.STARTING))); + assertThat(watchService.state(), not(equalTo(WatchService.State.STARTING))); } }); } catch (Exception e) { throw new RuntimeException(e); } - alertsService.stop(); + watchService.stop(); try { assertBusy(new Runnable() { @Override public void run() { - assertThat(alertsService.state(), equalTo(AlertsService.State.STOPPED)); + assertThat(watchService.state(), equalTo(WatchService.State.STOPPED)); } }); } catch (Exception e) { throw new RuntimeException(e); } - // Now when can close nodes, without alerting trying to become active while nodes briefly become master + // Now when can close nodes, without watcher trying to become active while nodes briefly become master // during cluster shutdown. testCluster.close(); } diff --git a/src/test/java/org/elasticsearch/alerts/test/AbstractAlertsSingleNodeTests.java b/src/test/java/org/elasticsearch/watcher/test/AbstractWatcherSingleNodeTests.java similarity index 86% rename from src/test/java/org/elasticsearch/alerts/test/AbstractAlertsSingleNodeTests.java rename to src/test/java/org/elasticsearch/watcher/test/AbstractWatcherSingleNodeTests.java index 22f5d4c38fa..1ac5ecd557c 100644 --- a/src/test/java/org/elasticsearch/alerts/test/AbstractAlertsSingleNodeTests.java +++ b/src/test/java/org/elasticsearch/watcher/test/AbstractWatcherSingleNodeTests.java @@ -3,15 +3,15 @@ * 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.alerts.test; +package org.elasticsearch.watcher.test; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.alerts.AlertsLifeCycleService; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.WatcherLifeCycleService; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.client.Requests; import org.elasticsearch.common.Priority; import org.elasticsearch.common.unit.TimeValue; @@ -28,16 +28,16 @@ import static org.hamcrest.Matchers.equalTo; /** * */ -public abstract class AbstractAlertsSingleNodeTests extends ElasticsearchSingleNodeTest { +public abstract class AbstractWatcherSingleNodeTests extends ElasticsearchSingleNodeTest { @BeforeClass public static void initSuite() throws Exception { - getInstanceFromNode(AlertsLifeCycleService.class).start(); + getInstanceFromNode(WatcherLifeCycleService.class).start(); } @AfterClass public static void cleanupSuite() throws Exception { - getInstanceFromNode(AlertsLifeCycleService.class).stop(); + getInstanceFromNode(WatcherLifeCycleService.class).stop(); } @Override diff --git a/src/test/java/org/elasticsearch/alerts/test/TimeWarpedAlertsPlugin.java b/src/test/java/org/elasticsearch/watcher/test/TimeWarpedWatcherPlugin.java similarity index 73% rename from src/test/java/org/elasticsearch/alerts/test/TimeWarpedAlertsPlugin.java rename to src/test/java/org/elasticsearch/watcher/test/TimeWarpedWatcherPlugin.java index 73726b591db..4cc14eade8f 100644 --- a/src/test/java/org/elasticsearch/alerts/test/TimeWarpedAlertsPlugin.java +++ b/src/test/java/org/elasticsearch/watcher/test/TimeWarpedWatcherPlugin.java @@ -3,16 +3,16 @@ * 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.alerts.test; +package org.elasticsearch.watcher.test; -import org.elasticsearch.alerts.AlertsPlugin; -import org.elasticsearch.alerts.history.AlertsExecutor; -import org.elasticsearch.alerts.history.HistoryModule; -import org.elasticsearch.alerts.scheduler.SchedulerMock; -import org.elasticsearch.alerts.scheduler.SchedulerModule; -import org.elasticsearch.alerts.support.clock.Clock; -import org.elasticsearch.alerts.support.clock.ClockMock; -import org.elasticsearch.alerts.support.clock.ClockModule; +import org.elasticsearch.watcher.WatcherPlugin; +import org.elasticsearch.watcher.history.WatchExecutor; +import org.elasticsearch.watcher.history.HistoryModule; +import org.elasticsearch.watcher.scheduler.SchedulerMock; +import org.elasticsearch.watcher.scheduler.SchedulerModule; +import org.elasticsearch.watcher.support.clock.Clock; +import org.elasticsearch.watcher.support.clock.ClockMock; +import org.elasticsearch.watcher.support.clock.ClockModule; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.logging.Loggers; @@ -27,23 +27,23 @@ import java.util.concurrent.BlockingQueue; /** * */ -public class TimeWarpedAlertsPlugin extends AlertsPlugin { +public class TimeWarpedWatcherPlugin extends WatcherPlugin { - public TimeWarpedAlertsPlugin(Settings settings) { + public TimeWarpedWatcherPlugin(Settings settings) { super(settings); - Loggers.getLogger(TimeWarpedAlertsPlugin.class, settings).info("using time warped alerts plugin"); + Loggers.getLogger(TimeWarpedWatcherPlugin.class, settings).info("using time warped watchers plugin"); } @Override public Collection> modules() { - return ImmutableList.>of(AlertsModule.class); + return ImmutableList.>of(WatcherModule.class); } /** * */ - public static class AlertsModule extends org.elasticsearch.alerts.AlertsModule { + public static class WatcherModule extends org.elasticsearch.watcher.WatcherModule { @Override public Iterable spawnModules() { @@ -61,7 +61,7 @@ public class TimeWarpedAlertsPlugin extends AlertsPlugin { modules.add(new MockClockModule()); } else if (module instanceof HistoryModule) { - // replacing the history module so all the alerts will be + // replacing the history module so all the watches will be // executed on the same thread as the schedule fire modules.add(new MockHistoryModule()); @@ -94,7 +94,7 @@ public class TimeWarpedAlertsPlugin extends AlertsPlugin { super(SameThreadExecutor.class); } - public static class SameThreadExecutor implements AlertsExecutor { + public static class SameThreadExecutor implements WatchExecutor { @Override public BlockingQueue queue() { diff --git a/src/test/java/org/elasticsearch/alerts/test/AlertsTestUtils.java b/src/test/java/org/elasticsearch/watcher/test/WatcherTestUtils.java similarity index 63% rename from src/test/java/org/elasticsearch/alerts/test/AlertsTestUtils.java rename to src/test/java/org/elasticsearch/watcher/test/WatcherTestUtils.java index 02117f42287..41232eecc54 100644 --- a/src/test/java/org/elasticsearch/alerts/test/AlertsTestUtils.java +++ b/src/test/java/org/elasticsearch/watcher/test/WatcherTestUtils.java @@ -3,33 +3,33 @@ * 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.alerts.test; +package org.elasticsearch.watcher.test; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.actions.Action; -import org.elasticsearch.alerts.actions.Actions; -import org.elasticsearch.alerts.actions.email.EmailAction; -import org.elasticsearch.alerts.actions.email.service.Authentication; -import org.elasticsearch.alerts.actions.email.service.Email; -import org.elasticsearch.alerts.actions.email.service.EmailService; -import org.elasticsearch.alerts.actions.email.service.Profile; -import org.elasticsearch.alerts.actions.webhook.HttpClient; -import org.elasticsearch.alerts.actions.webhook.WebhookAction; -import org.elasticsearch.alerts.condition.script.ScriptCondition; -import org.elasticsearch.alerts.input.search.SearchInput; -import org.elasticsearch.alerts.scheduler.schedule.CronSchedule; -import org.elasticsearch.alerts.support.AlertUtils; -import org.elasticsearch.alerts.support.Script; -import org.elasticsearch.alerts.support.clock.SystemClock; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; -import org.elasticsearch.alerts.support.template.ScriptTemplate; -import org.elasticsearch.alerts.support.template.Template; -import org.elasticsearch.alerts.transform.SearchTransform; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.Actions; +import org.elasticsearch.watcher.actions.email.EmailAction; +import org.elasticsearch.watcher.actions.email.service.Authentication; +import org.elasticsearch.watcher.actions.email.service.Email; +import org.elasticsearch.watcher.actions.email.service.EmailService; +import org.elasticsearch.watcher.actions.email.service.Profile; +import org.elasticsearch.watcher.actions.webhook.HttpClient; +import org.elasticsearch.watcher.actions.webhook.WebhookAction; +import org.elasticsearch.watcher.condition.script.ScriptCondition; +import org.elasticsearch.watcher.input.search.SearchInput; +import org.elasticsearch.watcher.scheduler.schedule.CronSchedule; +import org.elasticsearch.watcher.support.WatcherUtils; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.clock.SystemClock; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.support.template.ScriptTemplate; +import org.elasticsearch.watcher.support.template.Template; +import org.elasticsearch.watcher.transform.SearchTransform; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.joda.time.DateTime; @@ -54,16 +54,16 @@ import static org.mockito.Mockito.when; /** * */ -public final class AlertsTestUtils { +public final class WatcherTestUtils { public static final Payload EMPTY_PAYLOAD = new Payload.Simple(ImmutableMap.of()); - private AlertsTestUtils() { + private WatcherTestUtils() { } public static SearchRequest newInputSearchRequest(String... indices) { SearchRequest request = new SearchRequest(indices); - request.indicesOptions(AlertUtils.DEFAULT_INDICES_OPTIONS); + request.indicesOptions(WatcherUtils.DEFAULT_INDICES_OPTIONS); request.searchType(SearchInput.DEFAULT_SEARCH_TYPE); return request; } @@ -85,27 +85,27 @@ public final class AlertsTestUtils { return new Payload.Simple(key, value); } - public static ExecutionContext mockExecutionContext(String alertName, Payload payload) { - return mockExecutionContext(DateTime.now(), alertName, payload); + public static WatchExecutionContext mockExecutionContext(String watchName, Payload payload) { + return mockExecutionContext(DateTime.now(), watchName, payload); } - public static ExecutionContext mockExecutionContext(DateTime time, String alertName, Payload payload) { - return mockExecutionContext(time, time, time, alertName, payload); + public static WatchExecutionContext mockExecutionContext(DateTime time, String watchName, Payload payload) { + return mockExecutionContext(time, time, time, watchName, payload); } - public static ExecutionContext mockExecutionContext(DateTime executionTime, DateTime firedTime, DateTime scheduledTime, String alertName, Payload payload) { - ExecutionContext ctx = mock(ExecutionContext.class); + public static WatchExecutionContext mockExecutionContext(DateTime executionTime, DateTime firedTime, DateTime scheduledTime, String watchName, Payload payload) { + WatchExecutionContext ctx = mock(WatchExecutionContext.class); when(ctx.executionTime()).thenReturn(executionTime); when(ctx.fireTime()).thenReturn(firedTime); when(ctx.scheduledTime()).thenReturn(scheduledTime); - Alert alert = mock(Alert.class); - when(alert.name()).thenReturn(alertName); - when(ctx.alert()).thenReturn(alert); + Watch watch = mock(Watch.class); + when(watch.name()).thenReturn(watchName); + when(ctx.watch()).thenReturn(watch); when(ctx.payload()).thenReturn(payload); return ctx; } - public static Alert createTestAlert(String alertName, ScriptServiceProxy scriptService, HttpClient httpClient, EmailService emailService, ESLogger logger) throws AddressException { + public static Watch createTestWatch(String watchName, ScriptServiceProxy scriptService, HttpClient httpClient, EmailService emailService, ESLogger logger) throws AddressException { SearchRequest conditionRequest = newInputSearchRequest("my-condition-index").source(searchSource().query(matchAllQuery())); SearchRequest transformRequest = newInputSearchRequest("my-payload-index").source(searchSource().query(matchAllQuery())); transformRequest.searchType(SearchTransform.DEFAULT_SEARCH_TYPE); @@ -113,8 +113,8 @@ public final class AlertsTestUtils { List actions = new ArrayList<>(); - Template url = new ScriptTemplate(scriptService, "http://localhost/foobarbaz/{{alert_name}}"); - Template body = new ScriptTemplate(scriptService, "{{alert_name}} executed with {{response.hits.total}} hits"); + Template url = new ScriptTemplate(scriptService, "http://localhost/foobarbaz/{{watch_name}}"); + Template body = new ScriptTemplate(scriptService, "{{watch_name}} executed with {{response.hits.total}} hits"); actions.add(new WebhookAction(logger, null, httpClient, HttpMethod.GET, url, body)); @@ -137,8 +137,8 @@ public final class AlertsTestUtils { Map metadata = new LinkedHashMap<>(); metadata.put("foo", "bar"); - return new Alert( - alertName, + return new Watch( + watchName, SystemClock.INSTANCE, new CronSchedule("0/5 * * * * ? *"), new SearchInput(logger, scriptService, ClientProxy.of(ElasticsearchIntegrationTest.client()), conditionRequest), @@ -147,6 +147,6 @@ public final class AlertsTestUtils { new Actions(actions), metadata, new TimeValue(0), - new Alert.Status()); + new Watch.Status()); } } diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/BasicAlertsTests.java b/src/test/java/org/elasticsearch/watcher/test/integration/BasicWatcherTests.java similarity index 59% rename from src/test/java/org/elasticsearch/alerts/test/integration/BasicAlertsTests.java rename to src/test/java/org/elasticsearch/watcher/test/integration/BasicWatcherTests.java index fa3eca68077..45af82b0a9b 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/BasicAlertsTests.java +++ b/src/test/java/org/elasticsearch/watcher/test/integration/BasicWatcherTests.java @@ -3,33 +3,33 @@ * 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.alerts.test.integration; +package org.elasticsearch.watcher.test.integration; import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.alerts.AlertsException; -import org.elasticsearch.alerts.AlertsStore; -import org.elasticsearch.alerts.client.AlertSourceBuilder; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.scheduler.schedule.IntervalSchedule; -import org.elasticsearch.alerts.support.AlertUtils; -import org.elasticsearch.alerts.test.AbstractAlertsIntegrationTests; -import org.elasticsearch.alerts.transport.actions.delete.DeleteAlertResponse; -import org.elasticsearch.alerts.transport.actions.get.GetAlertResponse; -import org.elasticsearch.alerts.transport.actions.put.PutAlertResponse; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.watch.WatchStore; +import org.elasticsearch.watcher.client.WatchSourceBuilder; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.scheduler.schedule.IntervalSchedule; +import org.elasticsearch.watcher.support.WatcherUtils; +import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTests; +import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchResponse; +import org.elasticsearch.watcher.transport.actions.get.GetWatchResponse; +import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.Test; -import static org.elasticsearch.alerts.actions.ActionBuilders.indexAction; -import static org.elasticsearch.alerts.client.AlertSourceBuilder.alertSourceBuilder; -import static org.elasticsearch.alerts.condition.ConditionBuilders.scriptCondition; -import static org.elasticsearch.alerts.input.InputBuilders.searchInput; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.cron; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.interval; -import static org.elasticsearch.alerts.support.Variables.*; -import static org.elasticsearch.alerts.test.AlertsTestUtils.newInputSearchRequest; +import static org.elasticsearch.watcher.actions.ActionBuilders.indexAction; +import static org.elasticsearch.watcher.client.WatchSourceBuilder.watchSourceBuilder; +import static org.elasticsearch.watcher.condition.ConditionBuilders.scriptCondition; +import static org.elasticsearch.watcher.input.InputBuilders.searchInput; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.cron; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.interval; +import static org.elasticsearch.watcher.support.Variables.*; +import static org.elasticsearch.watcher.test.WatcherTestUtils.newInputSearchRequest; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.FilterBuilders.rangeFilter; import static org.elasticsearch.index.query.QueryBuilders.*; @@ -40,18 +40,18 @@ import static org.hamcrest.Matchers.*; /** */ -public class BasicAlertsTests extends AbstractAlertsIntegrationTests { +public class BasicWatcherTests extends AbstractWatcherIntegrationTests { @Test - public void testIndexAlert() throws Exception { - AlertsClient alertsClient = alertClient(); + public void testIndexWatch() throws Exception { + WatcherClient watcherClient = watcherClient(); createIndex("idx"); - // Have a sample document in the index, the alert is going to evaluate + // Have a sample document in the index, the watch is going to evaluate client().prepareIndex("idx", "type").setSource("field", "value").get(); refresh(); SearchRequest searchRequest = newInputSearchRequest("idx").source(searchSource().query(termQuery("field", "value"))); - alertsClient.preparePutAlert("_name") - .source(alertSourceBuilder() + watcherClient.preparePutWatch("_name") + .source(watchSourceBuilder() .schedule(interval(5, IntervalSchedule.Interval.Unit.SECONDS)) .input(searchInput(searchRequest)) .condition(scriptCondition("ctx.payload.hits.total == 1"))) @@ -62,19 +62,19 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { refresh(); } - assertAlertWithMinimumPerformedActionsCount("_name", 1); + assertWatchWithMinimumPerformedActionsCount("_name", 1); - GetAlertResponse getAlertResponse = alertClient().prepareGetAlert().setAlertName("_name").get(); - assertThat(getAlertResponse.getResponse().isExists(), is(true)); - assertThat(getAlertResponse.getResponse().isSourceEmpty(), is(false)); + GetWatchResponse getWatchResponse = watcherClient().prepareGetWatch().setWatchName("_name").get(); + assertThat(getWatchResponse.getResponse().isExists(), is(true)); + assertThat(getWatchResponse.getResponse().isSourceEmpty(), is(false)); } @Test - public void testIndexAlert_registerAlertBeforeTargetIndex() throws Exception { - AlertsClient alertsClient = alertClient(); + public void testIndexWatch_registerWatchBeforeTargetIndex() throws Exception { + WatcherClient watcherClient = watcherClient(); SearchRequest searchRequest = newInputSearchRequest("idx").source(searchSource().query(termQuery("field", "value"))); - alertsClient.preparePutAlert("_name") - .source(alertSourceBuilder() + watcherClient.preparePutWatch("_name") + .source(watchSourceBuilder() .schedule(interval(5, IntervalSchedule.Interval.Unit.SECONDS)) .input(searchInput(searchRequest)) .condition(scriptCondition("ctx.payload.hits.total == 1"))) @@ -85,10 +85,10 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { refresh(); } - // The alert's condition won't meet because there is no data that matches with the query - assertAlertWithNoActionNeeded("_name", 1); + // The watch's condition won't meet because there is no data that matches with the query + assertWatchWithNoActionNeeded("_name", 1); - // Index sample doc after we register the alert and the alert's condition should meet + // Index sample doc after we register the watch and the watch's condition should meet client().prepareIndex("idx", "type").setSource("field", "value").get(); refresh(); @@ -97,15 +97,15 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { refresh(); } - assertAlertWithMinimumPerformedActionsCount("_name", 1); + assertWatchWithMinimumPerformedActionsCount("_name", 1); } @Test - public void testDeleteAlert() throws Exception { - AlertsClient alertsClient = alertClient(); + public void testDeleteWatch() throws Exception { + WatcherClient watcherClient = watcherClient(); SearchRequest searchRequest = newInputSearchRequest("idx").source(searchSource().query(matchAllQuery())); - PutAlertResponse indexResponse = alertsClient.preparePutAlert("_name") - .source(alertSourceBuilder() + PutWatchResponse indexResponse = watcherClient.preparePutWatch("_name") + .source(watchSourceBuilder() .schedule(interval(5, IntervalSchedule.Interval.Unit.SECONDS)) .input(searchInput(searchRequest)) .condition(scriptCondition("ctx.payload.hits.total == 1"))) @@ -113,72 +113,72 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { assertThat(indexResponse.indexResponse().isCreated(), is(true)); if (!timeWarped()) { - // Although there is no added benefit in this test for waiting for the alert to fire, however - // we need to wait here because of a test timing issue. When we tear down a test we delete the alert and delete all - // indices, but there may still be inflight fired alerts, which may trigger the alert history to be created again, before + // Although there is no added benefit in this test for waiting for the watch to fire, however + // we need to wait here because of a test timing issue. When we tear down a test we delete the watch and delete all + // indices, but there may still be inflight fired watches, which may trigger the watch history to be created again, before // we finished the tear down phase. - assertAlertWithNoActionNeeded("_name", 1); + assertWatchWithNoActionNeeded("_name", 1); } - DeleteAlertResponse deleteAlertResponse = alertsClient.prepareDeleteAlert("_name").get(); - assertThat(deleteAlertResponse.deleteResponse(), notNullValue()); - assertThat(deleteAlertResponse.deleteResponse().isFound(), is(true)); + DeleteWatchResponse deleteWatchResponse = watcherClient.prepareDeleteWatch("_name").get(); + assertThat(deleteWatchResponse.deleteResponse(), notNullValue()); + assertThat(deleteWatchResponse.deleteResponse().isFound(), is(true)); refresh(); - assertHitCount(client().prepareCount(AlertsStore.ALERT_INDEX).get(), 0l); + assertHitCount(client().prepareCount(WatchStore.INDEX).get(), 0l); - // Deleting the same alert for the second time - deleteAlertResponse = alertsClient.prepareDeleteAlert("_name").get(); - assertThat(deleteAlertResponse.deleteResponse(), notNullValue()); - assertThat(deleteAlertResponse.deleteResponse().isFound(), is(false)); + // Deleting the same watch for the second time + deleteWatchResponse = watcherClient.prepareDeleteWatch("_name").get(); + assertThat(deleteWatchResponse.deleteResponse(), notNullValue()); + assertThat(deleteWatchResponse.deleteResponse().isFound(), is(false)); } @Test - public void testMalformedAlert() throws Exception { - AlertsClient alertsClient = alertClient(); + public void testMalformedWatch() throws Exception { + WatcherClient watcherClient = watcherClient(); createIndex("idx"); - // Have a sample document in the index, the alert is going to evaluate + // Have a sample document in the index, the watch is going to evaluate client().prepareIndex("idx", "type").setSource("field", "value").get(); - XContentBuilder alertSource = jsonBuilder(); + XContentBuilder watchSource = jsonBuilder(); - alertSource.startObject(); - alertSource.field("unknown_field", "x"); - alertSource.startObject("schedule").field("cron", "0/5 * * * * ? *").endObject(); + watchSource.startObject(); + watchSource.field("unknown_field", "x"); + watchSource.startObject("schedule").field("cron", "0/5 * * * * ? *").endObject(); - alertSource.startObject("condition").startObject("script").field("script", "return true").field("request"); - AlertUtils.writeSearchRequest(newInputSearchRequest(), alertSource, ToXContent.EMPTY_PARAMS); - alertSource.endObject(); + watchSource.startObject("condition").startObject("script").field("script", "return true").field("request"); + WatcherUtils.writeSearchRequest(newInputSearchRequest(), watchSource, ToXContent.EMPTY_PARAMS); + watchSource.endObject(); - alertSource.endObject(); + watchSource.endObject(); try { - alertsClient.preparePutAlert("_name") - .source(alertSource.bytes()) + watcherClient.preparePutWatch("_name") + .source(watchSource.bytes()) .get(); fail(); - } catch (AlertsException e) { - // In AlertStore we fail parsing if an alert contains undefined fields. + } catch (WatcherException e) { + // In watch store we fail parsing if an watch contains undefined fields. } try { - client().prepareIndex(AlertsStore.ALERT_INDEX, AlertsStore.ALERT_TYPE, "_name") - .setSource(alertSource) + client().prepareIndex(WatchStore.INDEX, WatchStore.DOC_TYPE, "_name") + .setSource(watchSource) .get(); fail(); } catch (Exception e) { - // The alert index template the mapping is defined as strict + // The watch index template the mapping is defined as strict } } @Test - public void testModifyAlerts() throws Exception { + public void testModifyWatches() throws Exception { SearchRequest searchRequest = newInputSearchRequest("idx") .source(searchSource().query(matchAllQuery())); - AlertSourceBuilder source = alertSourceBuilder() + WatchSourceBuilder source = watchSourceBuilder() .schedule(interval("5s")) .input(searchInput(searchRequest)) .addAction(indexAction("idx", "action")); - alertClient().preparePutAlert("_name") + watcherClient().preparePutWatch("_name") .source(source.condition(scriptCondition("ctx.payload.hits.total == 1"))) .get(); @@ -186,9 +186,9 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { timeWarp().scheduler().fire("_name"); refresh(); } - assertAlertWithMinimumPerformedActionsCount("_name", 0, false); + assertWatchWithMinimumPerformedActionsCount("_name", 0, false); - alertClient().preparePutAlert("_name") + watcherClient().preparePutWatch("_name") .source(source.condition(scriptCondition("ctx.payload.hits.total == 0"))) .get(); @@ -196,9 +196,9 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { timeWarp().scheduler().fire("_name"); refresh(); } - assertAlertWithMinimumPerformedActionsCount("_name", 1, false); + assertWatchWithMinimumPerformedActionsCount("_name", 1, false); - alertClient().preparePutAlert("_name") + watcherClient().preparePutWatch("_name") .source(source.schedule(cron("0/1 * * * * ? 2020")).condition(scriptCondition("ctx.payload.hits.total == 0"))) .get(); @@ -255,12 +255,12 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { } private void testConditionSearch(SearchRequest request) throws Exception { - String alertName = "_name"; + String watchName = "_name"; assertAcked(prepareCreate("events").addMapping("event", "_timestamp", "enabled=true", "level", "type=string")); - alertClient().prepareDeleteAlert(alertName).get(); - alertClient().preparePutAlert(alertName) - .source(createAlertSource(interval("5s"), request, "return ctx.payload.hits.total >= 3")) + watcherClient().prepareDeleteWatch(watchName).get(); + watcherClient().preparePutWatch(watchName) + .source(createWatchSource(interval("5s"), request, "return ctx.payload.hits.total >= 3")) .get(); client().prepareIndex("events", "event") @@ -274,12 +274,12 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { refresh(); if (timeWarped()) { timeWarp().clock().fastForwardSeconds(5); - timeWarp().scheduler().fire(alertName); + timeWarp().scheduler().fire(watchName); refresh(); } else { Thread.sleep(5000); } - assertAlertWithNoActionNeeded(alertName, 1); + assertWatchWithNoActionNeeded(watchName, 1); client().prepareIndex("events", "event") .setCreate(true) @@ -288,12 +288,12 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { refresh(); if (timeWarped()) { timeWarp().clock().fastForwardSeconds(5); - timeWarp().scheduler().fire(alertName); + timeWarp().scheduler().fire(watchName); refresh(); } else { Thread.sleep(5000); } - assertAlertWithNoActionNeeded(alertName, 2); + assertWatchWithNoActionNeeded(watchName, 2); client().prepareIndex("events", "event") .setCreate(true) @@ -302,11 +302,11 @@ public class BasicAlertsTests extends AbstractAlertsIntegrationTests { refresh(); if (timeWarped()) { timeWarp().clock().fastForwardSeconds(5); - timeWarp().scheduler().fire(alertName); + timeWarp().scheduler().fire(watchName); refresh(); } else { Thread.sleep(5000); } - assertAlertWithMinimumPerformedActionsCount(alertName, 1); + assertWatchWithMinimumPerformedActionsCount(watchName, 1); } } diff --git a/src/test/java/org/elasticsearch/watcher/test/integration/BootStrapTests.java b/src/test/java/org/elasticsearch/watcher/test/integration/BootStrapTests.java new file mode 100644 index 00000000000..e550d57fff5 --- /dev/null +++ b/src/test/java/org/elasticsearch/watcher/test/integration/BootStrapTests.java @@ -0,0 +1,192 @@ +/* + * 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.watcher.test.integration; + +import org.elasticsearch.action.WriteConsistencyLevel; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.watch.WatchStore; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.Actions; +import org.elasticsearch.watcher.condition.script.ScriptCondition; +import org.elasticsearch.watcher.history.WatchRecord; +import org.elasticsearch.watcher.history.HistoryStore; +import org.elasticsearch.watcher.input.search.SearchInput; +import org.elasticsearch.watcher.scheduler.schedule.CronSchedule; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.clock.SystemClock; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTests; +import org.elasticsearch.watcher.test.WatcherTestUtils; +import org.elasticsearch.watcher.transform.SearchTransform; +import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; +import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.joda.time.DateTime; +import org.elasticsearch.common.joda.time.DateTimeZone; +import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.xcontent.ToXContent; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.test.junit.annotations.TestLogging; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsEqual.equalTo; + +/** + */ +public class BootStrapTests extends AbstractWatcherIntegrationTests { + + @Test + public void testBootStrapWatcher() throws Exception { + ensureWatcherStarted(); + + SearchRequest searchRequest = WatcherTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); + BytesReference watchSource = createWatchSource("0 0/5 * * * ? *", searchRequest, "ctx.payload.hits.total == 1"); + client().prepareIndex(WatchStore.INDEX, WatchStore.DOC_TYPE, "my-first-watch") + .setSource(watchSource) + .setConsistencyLevel(WriteConsistencyLevel.ALL) + .get(); + + client().admin().indices().prepareRefresh(WatchStore.INDEX).get(); + stopWatcher(); + startWatcher(); + + WatcherStatsResponse response = watcherClient().prepareWatcherStats().get(); + assertThat(response.getWatchServiceState(), equalTo(WatchService.State.STARTED)); + assertThat(response.getWatchesCount(), equalTo(1L)); + } + + @Test + @TestLogging("watcher.actions:DEBUG") + public void testBootstrapHistory() throws Exception { + ensureWatcherStarted(); + + WatcherStatsResponse response = watcherClient().prepareWatcherStats().get(); + assertThat(response.getWatchServiceState(), equalTo(WatchService.State.STARTED)); + assertThat(response.getWatchesCount(), equalTo(0L)); + + SearchRequest searchRequest = WatcherTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); + Watch watch = new Watch( + "test-serialization", + SystemClock.INSTANCE, + new CronSchedule("0/5 * * * * ? 2035"), //Set this into the future so we don't get any extra runs + new SearchInput(logger, scriptService(), ClientProxy.of(client()), searchRequest), + new ScriptCondition(logger, scriptService(), new Script("return true")), + new SearchTransform(logger, scriptService(), ClientProxy.of(client()), searchRequest), + new Actions(new ArrayList()), + null, // metadata + new TimeValue(0), + new Watch.Status()); + + XContentBuilder builder = jsonBuilder().value(watch); + IndexResponse indexResponse = client().prepareIndex(WatchStore.INDEX, WatchStore.DOC_TYPE, watch.name()) + .setSource(builder).get(); + ensureGreen(WatchStore.INDEX); + refresh(); + assertThat(indexResponse.isCreated(), is(true)); + + DateTime scheduledFireTime = new DateTime(DateTimeZone.UTC); + WatchRecord watchRecord = new WatchRecord(watch, scheduledFireTime, scheduledFireTime); + String actionHistoryIndex = HistoryStore.getHistoryIndexNameForTime(scheduledFireTime); + + createIndex(actionHistoryIndex); + ensureGreen(actionHistoryIndex); + logger.info("Created index {}", actionHistoryIndex); + + indexResponse = client().prepareIndex(actionHistoryIndex, HistoryStore.DOC_TYPE, watchRecord.id()) + .setConsistencyLevel(WriteConsistencyLevel.ALL) + .setSource(jsonBuilder().value(watchRecord)) + .get(); + assertThat(indexResponse.isCreated(), is(true)); + + stopWatcher(); + startWatcher(); + + response = watcherClient().prepareWatcherStats().get(); + assertThat(response.getWatchServiceState(), equalTo(WatchService.State.STARTED)); + assertThat(response.getWatchesCount(), equalTo(1L)); + assertThat(response.getWatchExecutionQueueMaxSize(), greaterThanOrEqualTo(1l)); + } + + @Test + @TestLogging("watcher.actions:DEBUG") + public void testBootStrapManyHistoryIndices() throws Exception { + DateTime now = new DateTime(DateTimeZone.UTC); + long numberOfWatchHistoryIndices = randomIntBetween(2, 8); + long numberOfWatchRecordsPerIndex = randomIntBetween(5, 10); + SearchRequest searchRequest = WatcherTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); + + for (int i = 0; i < numberOfWatchHistoryIndices; i++) { + DateTime historyIndexDate = now.minus((new TimeValue(i, TimeUnit.DAYS)).getMillis()); + String actionHistoryIndex = HistoryStore.getHistoryIndexNameForTime(historyIndexDate); + createIndex(actionHistoryIndex); + ensureGreen(actionHistoryIndex); + logger.info("Created index {}", actionHistoryIndex); + + for (int j = 0; j < numberOfWatchRecordsPerIndex; j++) { + + Watch watch = new Watch( + "action-test-" + i + " " + j, + SystemClock.INSTANCE, + new CronSchedule("0/5 * * * * ? 2035"), //Set a cron schedule far into the future so this watch is never scheduled + new SearchInput(logger, scriptService(), ClientProxy.of(client()), + searchRequest), + new ScriptCondition(logger, scriptService(), new Script("return true")), + new SearchTransform(logger, scriptService(), ClientProxy.of(client()), searchRequest), + new Actions(new ArrayList()), + null, // metatdata + new TimeValue(0), + new Watch.Status()); + XContentBuilder jsonBuilder = jsonBuilder(); + watch.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS); + + PutWatchResponse putWatchResponse = watcherClient().preparePutWatch(watch.name()).source(jsonBuilder.bytes()).get(); + assertThat(putWatchResponse.indexResponse().isCreated(), is(true)); + + WatchRecord watchRecord = new WatchRecord(watch, historyIndexDate, historyIndexDate); + + XContentBuilder jsonBuilder2 = jsonBuilder(); + watchRecord.toXContent(jsonBuilder2, ToXContent.EMPTY_PARAMS); + + IndexResponse indexResponse = client().prepareIndex(actionHistoryIndex, HistoryStore.DOC_TYPE, watchRecord.id()) + .setConsistencyLevel(WriteConsistencyLevel.ALL) + .setSource(jsonBuilder2.bytes()) + .get(); + assertThat(indexResponse.isCreated(), is(true)); + } + client().admin().indices().prepareRefresh(actionHistoryIndex).get(); + } + + stopWatcher(); + startWatcher(); + WatcherStatsResponse response = watcherClient().prepareWatcherStats().get(); + + assertThat(response.getWatchServiceState(), equalTo(WatchService.State.STARTED)); + final long totalHistoryEntries = numberOfWatchRecordsPerIndex * numberOfWatchHistoryIndices; + + assertBusy(new Runnable() { + @Override + public void run() { + long count = docCount(HistoryStore.INDEX_PREFIX + "*", HistoryStore.DOC_TYPE, + termQuery(WatchRecord.Parser.STATE_FIELD.getPreferredName(), WatchRecord.State.EXECUTED.id())); + assertThat(count, is(totalHistoryEntries)); + } + }, 30, TimeUnit.SECONDS); + + } + + +} diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/NoMasterNodeTests.java b/src/test/java/org/elasticsearch/watcher/test/integration/NoMasterNodeTests.java similarity index 58% rename from src/test/java/org/elasticsearch/alerts/test/integration/NoMasterNodeTests.java rename to src/test/java/org/elasticsearch/watcher/test/integration/NoMasterNodeTests.java index 1722b3fe26b..f65259471f0 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/NoMasterNodeTests.java +++ b/src/test/java/org/elasticsearch/watcher/test/integration/NoMasterNodeTests.java @@ -3,16 +3,16 @@ * 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.alerts.test.integration; +package org.elasticsearch.watcher.test.integration; import org.apache.lucene.util.LuceneTestCase.Slow; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.alerts.AlertsService; -import org.elasticsearch.alerts.test.AbstractAlertsIntegrationTests; -import org.elasticsearch.alerts.test.AlertsTestUtils; -import org.elasticsearch.alerts.transport.actions.delete.DeleteAlertResponse; -import org.elasticsearch.alerts.transport.actions.stats.AlertsStatsResponse; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTests; +import org.elasticsearch.watcher.test.WatcherTestUtils; +import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchResponse; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.base.Predicate; @@ -41,7 +41,7 @@ import static org.hamcrest.core.Is.is; */ @Slow @ClusterScope(scope = TEST, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false, numDataNodes = 0) -public class NoMasterNodeTests extends AbstractAlertsIntegrationTests { +public class NoMasterNodeTests extends AbstractWatcherIntegrationTests { private ClusterDiscoveryConfiguration.UnicastZen config; @@ -67,85 +67,85 @@ public class NoMasterNodeTests extends AbstractAlertsIntegrationTests { config = new ClusterDiscoveryConfiguration.UnicastZen(2); internalTestCluster().startNodesAsync(2).get(); createIndex("my-index"); - ensureAlertingStarted(); + ensureWatcherStarted(); - // Have a sample document in the index, the alert is going to evaluate + // Have a sample document in the index, the watch 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, "ctx.payload.hits.total == 1"); - alertClient().preparePutAlert("my-first-alert") - .source(alertSource) + SearchRequest searchRequest = WatcherTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); + BytesReference watchSource = createWatchSource("0/5 * * * * ? *", searchRequest, "ctx.payload.hits.total == 1"); + watcherClient().preparePutWatch("my-first-watch") + .source(watchSource) .get(); - assertAlertWithMinimumPerformedActionsCount("my-first-alert", 1); + assertWatchWithMinimumPerformedActionsCount("my-first-watch", 1); // Stop the elected master, no new master will be elected b/c of m_m_n is set to 2 stopElectedMasterNodeAndWait(); try { - // any alerting action should fail, because there is no elected master node - alertClient().prepareDeleteAlert("my-first-alert").setMasterNodeTimeout(TimeValue.timeValueSeconds(1)).get(); + // any watch action should fail, because there is no elected master node + watcherClient().prepareDeleteWatch("my-first-watch").setMasterNodeTimeout(TimeValue.timeValueSeconds(1)).get(); fail(); } catch (Exception e) { assertThat(ExceptionsHelper.unwrapCause(e), instanceOf(MasterNotDiscoveredException.class)); } - // Bring back the 2nd node and wait for elected master node to come back and alerting to work as expected. + // Bring back the 2nd node and wait for elected master node to come back and watcher to work as expected. startElectedMasterNodeAndWait(); - // Our first alert's condition should at least have been met twice - assertAlertWithMinimumPerformedActionsCount("my-first-alert", 2); + // Our first watch's condition should at least have been met twice + assertWatchWithMinimumPerformedActionsCount("my-first-watch", 2); - // Delete the existing alert - DeleteAlertResponse response = alertClient().prepareDeleteAlert("my-first-alert").get(); + // Delete the existing watch + DeleteWatchResponse response = watcherClient().prepareDeleteWatch("my-first-watch").get(); assertThat(response.deleteResponse().isFound(), is(true)); - // Add a new alert and wait for its condition to be met - alertClient().preparePutAlert("my-second-alert") - .source(alertSource) + // Add a new watch and wait for its condition to be met + watcherClient().preparePutWatch("my-second-watch") + .source(watchSource) .get(); - assertAlertWithMinimumPerformedActionsCount("my-second-alert", 1); + assertWatchWithMinimumPerformedActionsCount("my-second-watch", 1); } @Test - @TestLogging("alerts:TRACE,cluster.service:TRACE,indices.recovery:TRACE,indices.cluster:TRACE") + @TestLogging("watcher:TRACE,cluster.service:TRACE,indices.recovery:TRACE,indices.cluster:TRACE") public void testMultipleFailures() throws Exception { int numberOfFailures = scaledRandomIntBetween(2, 9); - int numberOfAlerts = scaledRandomIntBetween(numberOfFailures, 12); - logger.info("Number of failures [{}], number of alerts [{}]", numberOfFailures, numberOfAlerts); + int numberOfWatches = scaledRandomIntBetween(numberOfFailures, 12); + logger.info("number of failures [{}], number of watches [{}]", numberOfFailures, numberOfWatches); config = new ClusterDiscoveryConfiguration.UnicastZen(2 + numberOfFailures); internalTestCluster().startNodesAsync(2).get(); createIndex("my-index"); client().prepareIndex("my-index", "my-type").setSource("field", "value").get(); - // Alerting starts in the background, it can happen we get here too soon, so wait until alerting has started. - ensureAlertingStarted(); - 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, "ctx.payload.hits.total == 1"); - alertClient().preparePutAlert(alertName) - .source(alertSource) + // watcher starts in the background, it can happen we get here too soon, so wait until watcher has started. + ensureWatcherStarted(); + for (int i = 1; i <= numberOfWatches; i++) { + String watchName = "watch" + i; + SearchRequest searchRequest = WatcherTestUtils.newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); + BytesReference watchSource = createWatchSource("0/5 * * * * ? *", searchRequest, "ctx.payload.hits.total == 1"); + watcherClient().preparePutWatch(watchName) + .source(watchSource) .get(); } ensureGreen(); for (int i = 1; i <= numberOfFailures; i++) { - logger.info("Failure round {}", i); + logger.info("failure round {}", i); - for (int j = 1; j < numberOfAlerts; j++) { - String alertName = "alert" + i; - assertAlertWithMinimumPerformedActionsCount(alertName, i); + for (int j = 1; j < numberOfWatches; j++) { + String watchName = "watch" + i; + assertWatchWithMinimumPerformedActionsCount(watchName, i); } ensureGreen(); stopElectedMasterNodeAndWait(); startElectedMasterNodeAndWait(); - AlertsStatsResponse statsResponse = alertClient().prepareAlertsStats().get(); - assertThat(statsResponse.getNumberOfRegisteredAlerts(), equalTo((long) numberOfAlerts)); + WatcherStatsResponse statsResponse = watcherClient().prepareWatcherStats().get(); + assertThat(statsResponse.getWatchesCount(), equalTo((long) numberOfWatches)); } } private void stopElectedMasterNodeAndWait() throws Exception { internalTestCluster().stopCurrentMasterNode(); - // Can't use ensureAlertingStopped, b/c that relies on the alerts stats api which requires an elected master node + // Can't use ensureWatcherStopped, b/c that relies on the watcher stats api which requires an elected master node assertThat(awaitBusy(new Predicate() { public boolean apply(Object obj) { for (Client client : clients()) { @@ -157,15 +157,15 @@ public class NoMasterNodeTests extends AbstractAlertsIntegrationTests { return true; } }, 30, TimeUnit.SECONDS), equalTo(true)); - // Ensure that the alert manager doesn't run elsewhere - for (AlertsService alertsService : internalTestCluster().getInstances(AlertsService.class)) { - assertThat(alertsService.state(), is(AlertsService.State.STOPPED)); + // Ensure that the watch manager doesn't run elsewhere + for (WatchService watchService : internalTestCluster().getInstances(WatchService.class)) { + assertThat(watchService.state(), is(WatchService.State.STOPPED)); } } private void startElectedMasterNodeAndWait() throws Exception { internalTestCluster().startNode(); - ensureAlertingStarted(); + ensureWatcherStarted(); } } diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/TransformSearchTests.java b/src/test/java/org/elasticsearch/watcher/test/integration/TransformSearchTests.java similarity index 62% rename from src/test/java/org/elasticsearch/alerts/test/integration/TransformSearchTests.java rename to src/test/java/org/elasticsearch/watcher/test/integration/TransformSearchTests.java index 0bd6c9bf5c1..e7e31f7dda9 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/TransformSearchTests.java +++ b/src/test/java/org/elasticsearch/watcher/test/integration/TransformSearchTests.java @@ -3,15 +3,15 @@ * 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.alerts.test.integration; +package org.elasticsearch.watcher.test.integration; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.alerts.scheduler.schedule.IntervalSchedule.Interval; -import org.elasticsearch.alerts.test.AbstractAlertsIntegrationTests; -import org.elasticsearch.alerts.test.AlertsTestUtils; -import org.elasticsearch.alerts.transform.SearchTransform; -import org.elasticsearch.alerts.transport.actions.put.PutAlertResponse; +import org.elasticsearch.watcher.scheduler.schedule.IntervalSchedule.Interval; +import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTests; +import org.elasticsearch.watcher.test.WatcherTestUtils; +import org.elasticsearch.watcher.transform.SearchTransform; +import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.search.SearchHit; import org.junit.Test; @@ -19,18 +19,18 @@ import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static org.elasticsearch.alerts.actions.ActionBuilders.indexAction; -import static org.elasticsearch.alerts.client.AlertSourceBuilder.alertSourceBuilder; -import static org.elasticsearch.alerts.input.InputBuilders.searchInput; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.interval; -import static org.elasticsearch.alerts.transform.TransformBuilders.searchTransform; +import static org.elasticsearch.watcher.actions.ActionBuilders.indexAction; +import static org.elasticsearch.watcher.client.WatchSourceBuilder.watchSourceBuilder; +import static org.elasticsearch.watcher.input.InputBuilders.searchInput; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.interval; +import static org.elasticsearch.watcher.transform.TransformBuilders.searchTransform; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.hamcrest.Matchers.*; /** */ -public class TransformSearchTests extends AbstractAlertsIntegrationTests { +public class TransformSearchTests extends AbstractWatcherIntegrationTests { @Test public void testTransformSearchRequest() throws Exception { @@ -40,16 +40,16 @@ public class TransformSearchTests extends AbstractAlertsIntegrationTests { index("my-payload-index", "payload", "mytestresult"); refresh(); - SearchRequest inputRequest = AlertsTestUtils.newInputSearchRequest("my-condition-index").source(searchSource().query(matchAllQuery())); - SearchRequest transformRequest = AlertsTestUtils.newInputSearchRequest("my-payload-index").source(searchSource().query(matchAllQuery())); + SearchRequest inputRequest = WatcherTestUtils.newInputSearchRequest("my-condition-index").source(searchSource().query(matchAllQuery())); + SearchRequest transformRequest = WatcherTestUtils.newInputSearchRequest("my-payload-index").source(searchSource().query(matchAllQuery())); transformRequest.searchType(SearchTransform.DEFAULT_SEARCH_TYPE); Map metadata = new HashMap<>(); metadata.put("foo", "bar"); metadata.put("list", "baz"); - PutAlertResponse putAlertResponse = alertClient().preparePutAlert("test-payload") - .source(alertSourceBuilder() + PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("test-payload") + .source(watchSourceBuilder() .schedule(interval(5, Interval.Unit.SECONDS)) .input(searchInput(inputRequest)) .transform(searchTransform(transformRequest)) @@ -57,14 +57,14 @@ public class TransformSearchTests extends AbstractAlertsIntegrationTests { .metadata(metadata) .throttlePeriod(TimeValue.timeValueSeconds(0))) .get(); - assertThat(putAlertResponse.indexResponse().isCreated(), is(true)); + assertThat(putWatchResponse.indexResponse().isCreated(), is(true)); if (timeWarped()) { timeWarp().scheduler().fire("test-payload"); refresh(); } - assertAlertWithMinimumPerformedActionsCount("test-payload", 1, false); + assertWatchWithMinimumPerformedActionsCount("test-payload", 1, false); refresh(); SearchRequest searchRequest = client().prepareSearch("my-payload-output").request(); diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/AlertMetadataTests.java b/src/test/java/org/elasticsearch/watcher/test/integration/WatchMetadataTests.java similarity index 63% rename from src/test/java/org/elasticsearch/alerts/test/integration/AlertMetadataTests.java rename to src/test/java/org/elasticsearch/watcher/test/integration/WatchMetadataTests.java index d029e03de08..b84e677da3a 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/AlertMetadataTests.java +++ b/src/test/java/org/elasticsearch/watcher/test/integration/WatchMetadataTests.java @@ -3,12 +3,12 @@ * 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.alerts.test.integration; +package org.elasticsearch.watcher.test.integration; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.alerts.history.HistoryStore; -import org.elasticsearch.alerts.test.AbstractAlertsIntegrationTests; -import org.elasticsearch.alerts.test.AlertsTestUtils; +import org.elasticsearch.watcher.history.HistoryStore; +import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTests; +import org.elasticsearch.watcher.test.WatcherTestUtils; import org.junit.Test; import java.util.ArrayList; @@ -16,10 +16,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.elasticsearch.alerts.client.AlertSourceBuilder.alertSourceBuilder; -import static org.elasticsearch.alerts.condition.ConditionBuilders.scriptCondition; -import static org.elasticsearch.alerts.input.InputBuilders.searchInput; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.cron; +import static org.elasticsearch.watcher.client.WatchSourceBuilder.watchSourceBuilder; +import static org.elasticsearch.watcher.condition.ConditionBuilders.scriptCondition; +import static org.elasticsearch.watcher.input.InputBuilders.searchInput; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.cron; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; @@ -28,10 +28,10 @@ import static org.hamcrest.Matchers.greaterThan; /** * */ -public class AlertMetadataTests extends AbstractAlertsIntegrationTests { +public class WatchMetadataTests extends AbstractWatcherIntegrationTests { @Test - public void testAlertMetadata() throws Exception { + public void testWatchMetadata() throws Exception { Map metadata = new HashMap<>(); metadata.put("foo", "bar"); List metaList = new ArrayList<>(); @@ -41,10 +41,10 @@ public class AlertMetadataTests extends AbstractAlertsIntegrationTests { metaList.add("test"); metadata.put("baz", metaList); - alertClient().preparePutAlert("_name") - .source(alertSourceBuilder() + watcherClient().preparePutWatch("_name") + .source(watchSourceBuilder() .schedule(cron("0/5 * * * * ? *")) - .input(searchInput(AlertsTestUtils.newInputSearchRequest("my-index").source(searchSource().query(matchAllQuery())))) + .input(searchInput(WatcherTestUtils.newInputSearchRequest("my-index").source(searchSource().query(matchAllQuery())))) .condition(scriptCondition("ctx.payload.hits.total == 1")) .metadata(metadata)) .get(); @@ -53,11 +53,11 @@ public class AlertMetadataTests extends AbstractAlertsIntegrationTests { timeWarp().scheduler().fire("_name"); } else { // Wait for a no action entry to be added. (the condition search request will not match, because there are no docs in my-index) - assertAlertWithNoActionNeeded("_name", 1); + assertWatchWithNoActionNeeded("_name", 1); } refresh(); - SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") + SearchResponse searchResponse = client().prepareSearch(HistoryStore.INDEX_PREFIX + "*") .setQuery(termQuery("meta.foo", "bar")) .get(); assertThat(searchResponse.getHits().getTotalHits(), greaterThan(0L)); diff --git a/src/test/java/org/elasticsearch/watcher/test/integration/WatchStatsTests.java b/src/test/java/org/elasticsearch/watcher/test/integration/WatchStatsTests.java new file mode 100644 index 00000000000..7dd1372131a --- /dev/null +++ b/src/test/java/org/elasticsearch/watcher/test/integration/WatchStatsTests.java @@ -0,0 +1,78 @@ +/* + * 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.watcher.test.integration; + +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.watcher.WatcherBuild; +import org.elasticsearch.watcher.watch.WatchService; +import org.elasticsearch.watcher.WatcherVersion; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTests; +import org.elasticsearch.watcher.test.WatcherTestUtils; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsRequest; +import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; +import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; + +import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; +import static org.elasticsearch.test.ElasticsearchIntegrationTest.Scope.TEST; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsEqual.equalTo; + + +/** + */ +@ClusterScope(scope = TEST, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false) +public class WatchStatsTests extends AbstractWatcherIntegrationTests { + + @Test + public void testStartedStats() throws Exception { + WatcherStatsRequest watcherStatsRequest = watcherClient().prepareWatcherStats().request(); + WatcherStatsResponse response = watcherClient().watcherStats(watcherStatsRequest).actionGet(); + + assertThat(response.getWatchServiceState(), is(WatchService.State.STARTED)); + assertThat(response.getExecutionQueueSize(), is(0L)); + assertThat(response.getWatchesCount(), is(0L)); + assertThat(response.getWatchExecutionQueueMaxSize(), is(timeWarped() ? 1L : 0L)); + assertThat(response.getVersion(), is(WatcherVersion.CURRENT)); + assertThat(response.getBuild(), is(WatcherBuild.CURRENT)); + } + + @Test + public void testWatchCountStats() throws Exception { + WatcherClient watcherClient = watcherClient(); + + WatcherStatsRequest watcherStatsRequest = watcherClient.prepareWatcherStats().request(); + WatcherStatsResponse response = watcherClient.watcherStats(watcherStatsRequest).actionGet(); + + assertThat(response.getWatchServiceState(), equalTo(WatchService.State.STARTED)); + + SearchRequest searchRequest = WatcherTestUtils.newInputSearchRequest("idx").source(searchSource().query(termQuery("field", "value"))); + BytesReference watchSource = createWatchSource("* * * * * ? *", searchRequest, "ctx.payload.hits.total == 1"); + watcherClient().preparePutWatch("_name") + .source(watchSource) + .get(); + + if (timeWarped()) { + timeWarp().scheduler().fire("_name", 30, TimeValue.timeValueSeconds(1)); + } else { + //Wait a little until we should have queued an action + Thread.sleep(TimeUnit.SECONDS.toMillis(5)); + } + + response = watcherClient().watcherStats(watcherStatsRequest).actionGet(); + + assertThat(response.getWatchServiceState(), is(WatchService.State.STARTED)); + assertThat(response.getWatchesCount(), is(1L)); + assertThat(response.getWatchExecutionQueueMaxSize(), greaterThan(0L)); + } +} diff --git a/src/test/java/org/elasticsearch/alerts/test/integration/AlertThrottleTests.java b/src/test/java/org/elasticsearch/watcher/test/integration/WatchThrottleTests.java similarity index 65% rename from src/test/java/org/elasticsearch/alerts/test/integration/AlertThrottleTests.java rename to src/test/java/org/elasticsearch/watcher/test/integration/WatchThrottleTests.java index 8370b22b719..42369d4415d 100644 --- a/src/test/java/org/elasticsearch/alerts/test/integration/AlertThrottleTests.java +++ b/src/test/java/org/elasticsearch/watcher/test/integration/WatchThrottleTests.java @@ -3,32 +3,32 @@ * 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.alerts.test.integration; +package org.elasticsearch.watcher.test.integration; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.actions.ActionBuilders; -import org.elasticsearch.alerts.client.AlertsClient; -import org.elasticsearch.alerts.history.FiredAlert; -import org.elasticsearch.alerts.history.HistoryStore; -import org.elasticsearch.alerts.test.AbstractAlertsIntegrationTests; -import org.elasticsearch.alerts.transport.actions.ack.AckAlertResponse; -import org.elasticsearch.alerts.transport.actions.get.GetAlertResponse; -import org.elasticsearch.alerts.transport.actions.put.PutAlertResponse; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.actions.ActionBuilders; +import org.elasticsearch.watcher.client.WatcherClient; +import org.elasticsearch.watcher.history.WatchRecord; +import org.elasticsearch.watcher.history.HistoryStore; +import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTests; +import org.elasticsearch.watcher.transport.actions.ack.AckWatchResponse; +import org.elasticsearch.watcher.transport.actions.get.GetWatchResponse; +import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.unit.TimeValue; import org.junit.Test; import java.util.concurrent.TimeUnit; -import static org.elasticsearch.alerts.client.AlertSourceBuilder.alertSourceBuilder; -import static org.elasticsearch.alerts.condition.ConditionBuilders.scriptCondition; -import static org.elasticsearch.alerts.input.InputBuilders.searchInput; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.cron; -import static org.elasticsearch.alerts.scheduler.schedule.Schedules.interval; -import static org.elasticsearch.alerts.test.AlertsTestUtils.matchAllRequest; -import static org.elasticsearch.alerts.transform.TransformBuilders.searchTransform; +import static org.elasticsearch.watcher.client.WatchSourceBuilder.watchSourceBuilder; +import static org.elasticsearch.watcher.condition.ConditionBuilders.scriptCondition; +import static org.elasticsearch.watcher.input.InputBuilders.searchInput; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.cron; +import static org.elasticsearch.watcher.scheduler.schedule.Schedules.interval; +import static org.elasticsearch.watcher.test.WatcherTestUtils.matchAllRequest; +import static org.elasticsearch.watcher.transform.TransformBuilders.searchTransform; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.hamcrest.Matchers.*; @@ -36,11 +36,11 @@ import static org.hamcrest.core.IsEqual.equalTo; /** */ -public class AlertThrottleTests extends AbstractAlertsIntegrationTests { +public class WatchThrottleTests extends AbstractWatcherIntegrationTests { @Test public void testAckThrottle() throws Exception { - AlertsClient alertsClient = alertClient(); + WatcherClient watcherClient = watcherClient(); createIndex("actions", "events"); ensureGreen("actions", "events"); @@ -50,9 +50,9 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { assertThat(eventIndexResponse.isCreated(), is(true)); refresh(); - PutAlertResponse putAlertResponse = alertsClient.preparePutAlert() - .alertName("_name") - .source(alertSourceBuilder() + PutWatchResponse putWatchResponse = watcherClient.preparePutWatch() + .watchName("_name") + .source(watchSourceBuilder() .schedule(cron("0/5 * * * * ? *")) .input(searchInput(matchAllRequest().indices("events"))) .condition(scriptCondition("ctx.payload.hits.total > 0")) @@ -60,15 +60,15 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { .addAction(ActionBuilders.indexAction("actions", "action"))) .get(); - assertThat(putAlertResponse.indexResponse().isCreated(), is(true)); + assertThat(putWatchResponse.indexResponse().isCreated(), is(true)); if (timeWarped()) { timeWarp().scheduler().fire("_name", 4, TimeValue.timeValueSeconds(5)); } else { Thread.sleep(20000); } - AckAlertResponse ackResponse = alertsClient.prepareAckAlert("_name").get(); - assertThat(ackResponse.getStatus().ackStatus().state(), is(Alert.Status.AckStatus.State.ACKED)); + AckWatchResponse ackResponse = watcherClient.prepareAckWatch("_name").get(); + assertThat(ackResponse.getStatus().ackStatus().state(), is(Watch.Status.AckStatus.State.ACKED)); refresh(); long countAfterAck = docCount("actions", "action", matchAllQuery()); @@ -81,7 +81,7 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { } refresh(); - // There shouldn't be more actions in the index after we ack the alert, even though the alert was fired + // There shouldn't be more actions in the index after we ack the watch, even though the watch was triggered long countAfterPostAckFires = docCount("actions", "action", matchAllQuery()); assertThat(countAfterPostAckFires, equalTo(countAfterAck)); @@ -96,22 +96,22 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { Thread.sleep(20000); } - GetAlertResponse getAlertResponse = alertsClient.prepareGetAlert("_name").get(); - assertThat(getAlertResponse.getResponse().isExists(), is(true)); + GetWatchResponse getWatchResponse = watcherClient.prepareGetWatch("_name").get(); + assertThat(getWatchResponse.getResponse().isExists(), is(true)); - Alert parsedAlert = alertParser().parse(getAlertResponse.getResponse().getId(), true, - getAlertResponse.getResponse().getSourceAsBytesRef()); - assertThat(parsedAlert.status().ackStatus().state(), is(Alert.Status.AckStatus.State.AWAITS_EXECUTION)); + Watch parsedWatch = watchParser().parse(getWatchResponse.getResponse().getId(), true, + getWatchResponse.getResponse().getSourceAsBytesRef()); + assertThat(parsedWatch.status().ackStatus().state(), is(Watch.Status.AckStatus.State.AWAITS_EXECUTION)); - long throttledCount = docCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*", null, - matchQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.THROTTLED.id())); + long throttledCount = docCount(HistoryStore.INDEX_PREFIX + "*", null, + matchQuery(WatchRecord.Parser.STATE_FIELD.getPreferredName(), WatchRecord.State.THROTTLED.id())); assertThat(throttledCount, greaterThan(0L)); } @Test public void testTimeThrottle() throws Exception { - AlertsClient alertsClient = alertClient(); + WatcherClient watcherClient = watcherClient(); createIndex("actions", "events"); ensureGreen("actions", "events"); @@ -121,9 +121,9 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { assertTrue(eventIndexResponse.isCreated()); refresh(); - PutAlertResponse putAlertResponse = alertsClient.preparePutAlert() - .alertName("_name") - .source(alertSourceBuilder() + PutWatchResponse putWatchResponse = watcherClient.preparePutWatch() + .watchName("_name") + .source(watchSourceBuilder() .schedule(interval("5s")) .input(searchInput(matchAllRequest().indices("events"))) .condition(scriptCondition("ctx.payload.hits.total > 0")) @@ -131,7 +131,7 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { .addAction(ActionBuilders.indexAction("actions", "action")) .throttlePeriod(TimeValue.timeValueSeconds(10))) .get(); - assertThat(putAlertResponse.indexResponse().isCreated(), is(true)); + assertThat(putWatchResponse.indexResponse().isCreated(), is(true)); if (timeWarped()) { timeWarp().clock().setTime(DateTime.now()); @@ -159,8 +159,8 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { actionsCount = docCount("actions", "action", matchAllQuery()); assertThat(actionsCount, is(2L)); - long throttledCount = docCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*", null, - matchQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.THROTTLED.id())); + long throttledCount = docCount(HistoryStore.INDEX_PREFIX + "*", null, + matchQuery(WatchRecord.Parser.STATE_FIELD.getPreferredName(), WatchRecord.State.THROTTLED.id())); assertThat(throttledCount, is(1L)); } else { @@ -178,8 +178,8 @@ public class AlertThrottleTests extends AbstractAlertsIntegrationTests { actionsCount = docCount("actions", "action", matchAllQuery()); assertThat(actionsCount, is(1L)); - long throttledCount = docCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*", null, - matchQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.THROTTLED.id())); + long throttledCount = docCount(HistoryStore.INDEX_PREFIX + "*", null, + matchQuery(WatchRecord.Parser.STATE_FIELD.getPreferredName(), WatchRecord.State.THROTTLED.id())); assertThat(throttledCount, greaterThanOrEqualTo(1L)); } } diff --git a/src/test/java/org/elasticsearch/watcher/throttle/AckThrottlerTests.java b/src/test/java/org/elasticsearch/watcher/throttle/AckThrottlerTests.java new file mode 100644 index 00000000000..1b8f72065d8 --- /dev/null +++ b/src/test/java/org/elasticsearch/watcher/throttle/AckThrottlerTests.java @@ -0,0 +1,58 @@ +/* + * 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.watcher.throttle; + +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.common.joda.time.DateTime; +import org.elasticsearch.test.ElasticsearchTestCase; +import org.junit.Test; + +import static org.elasticsearch.watcher.support.WatcherDateUtils.formatDate; +import static org.elasticsearch.watcher.test.WatcherTestUtils.EMPTY_PAYLOAD; +import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * + */ +public class AckThrottlerTests extends ElasticsearchTestCase { + + @Test + public void testWhenAcked() throws Exception { + DateTime timestamp = new DateTime(); + WatchExecutionContext ctx = mockExecutionContext("_watch", EMPTY_PAYLOAD); + Watch watch = ctx.watch(); + Watch.Status status = mock(Watch.Status.class); + when(status.ackStatus()).thenReturn(new Watch.Status.AckStatus(Watch.Status.AckStatus.State.ACKED, timestamp)); + when(watch.status()).thenReturn(status); + when(watch.name()).thenReturn("_watch"); + when(watch.acked()).thenReturn(true); + AckThrottler throttler = new AckThrottler(); + Throttler.Result result = throttler.throttle(ctx); + assertThat(result.throttle(), is(true)); + assertThat(result.reason(), is("watch [_watch] was acked at [" + formatDate(timestamp) + "]")); + } + + @Test + public void testWhenNotAcked() throws Exception { + DateTime timestamp = new DateTime(); + WatchExecutionContext ctx = mockExecutionContext("_watch", EMPTY_PAYLOAD); + Watch watch = ctx.watch(); + Watch.Status status = mock(Watch.Status.class); + Watch.Status.AckStatus.State state = randomFrom(Watch.Status.AckStatus.State.AWAITS_EXECUTION, Watch.Status.AckStatus.State.ACKABLE); + when(status.ackStatus()).thenReturn(new Watch.Status.AckStatus(state, timestamp)); + when(watch.status()).thenReturn(status); + when(watch.acked()).thenReturn(false); + AckThrottler throttler = new AckThrottler(); + Throttler.Result result = throttler.throttle(ctx); + assertThat(result.throttle(), is(false)); + assertThat(result.reason(), nullValue()); + } +} diff --git a/src/test/java/org/elasticsearch/alerts/throttle/PeriodThrottlerTests.java b/src/test/java/org/elasticsearch/watcher/throttle/PeriodThrottlerTests.java similarity index 75% rename from src/test/java/org/elasticsearch/alerts/throttle/PeriodThrottlerTests.java rename to src/test/java/org/elasticsearch/watcher/throttle/PeriodThrottlerTests.java index d44966df87d..51b4c3932b3 100644 --- a/src/test/java/org/elasticsearch/alerts/throttle/PeriodThrottlerTests.java +++ b/src/test/java/org/elasticsearch/watcher/throttle/PeriodThrottlerTests.java @@ -3,20 +3,20 @@ * 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.alerts.throttle; +package org.elasticsearch.watcher.throttle; import com.carrotsearch.randomizedtesting.annotations.Repeat; -import org.elasticsearch.alerts.Alert; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.support.clock.SystemClock; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.joda.time.PeriodType; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.test.ElasticsearchTestCase; import org.junit.Test; -import static org.elasticsearch.alerts.test.AlertsTestUtils.EMPTY_PAYLOAD; -import static org.elasticsearch.alerts.test.AlertsTestUtils.mockExecutionContext; +import static org.elasticsearch.watcher.test.WatcherTestUtils.EMPTY_PAYLOAD; +import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.mock; @@ -33,9 +33,9 @@ public class PeriodThrottlerTests extends ElasticsearchTestCase { TimeValue period = TimeValue.timeValueSeconds(randomIntBetween(2, 5)); PeriodThrottler throttler = new PeriodThrottler(SystemClock.INSTANCE, period, periodType); - ExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD); - Alert.Status status = mock(Alert.Status.class); - when(ctx.alert().status()).thenReturn(status); + WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD); + Watch.Status status = mock(Watch.Status.class); + when(ctx.watch().status()).thenReturn(status); when(status.lastExecuted()).thenReturn(new DateTime().minusSeconds((int) period.seconds() - 1)); Throttler.Result result = throttler.throttle(ctx); @@ -51,9 +51,9 @@ public class PeriodThrottlerTests extends ElasticsearchTestCase { TimeValue period = TimeValue.timeValueSeconds(randomIntBetween(2, 5)); PeriodThrottler throttler = new PeriodThrottler(SystemClock.INSTANCE, period, periodType); - ExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD); - Alert.Status status = mock(Alert.Status.class); - when(ctx.alert().status()).thenReturn(status); + WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD); + Watch.Status status = mock(Watch.Status.class); + when(ctx.watch().status()).thenReturn(status); when(status.lastExecuted()).thenReturn(new DateTime().minusSeconds((int) period.seconds() + 1)); Throttler.Result result = throttler.throttle(ctx); diff --git a/src/test/java/org/elasticsearch/alerts/throttle/AlertThrottlerTests.java b/src/test/java/org/elasticsearch/watcher/throttle/WatchThrottlerTests.java similarity index 80% rename from src/test/java/org/elasticsearch/alerts/throttle/AlertThrottlerTests.java rename to src/test/java/org/elasticsearch/watcher/throttle/WatchThrottlerTests.java index 37fb496e75a..27e7522468f 100644 --- a/src/test/java/org/elasticsearch/alerts/throttle/AlertThrottlerTests.java +++ b/src/test/java/org/elasticsearch/watcher/throttle/WatchThrottlerTests.java @@ -3,9 +3,9 @@ * 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.alerts.throttle; +package org.elasticsearch.watcher.throttle; -import org.elasticsearch.alerts.ExecutionContext; +import org.elasticsearch.watcher.watch.WatchExecutionContext; import org.elasticsearch.test.ElasticsearchTestCase; import org.junit.Test; @@ -18,17 +18,17 @@ import static org.mockito.Mockito.when; /** * */ -public class AlertThrottlerTests extends ElasticsearchTestCase { +public class WatchThrottlerTests extends ElasticsearchTestCase { @Test public void testThrottle_DueToAck() throws Exception { PeriodThrottler periodThrottler = mock(PeriodThrottler.class); AckThrottler ackThrottler = mock(AckThrottler.class); - ExecutionContext ctx = mock(ExecutionContext.class); + WatchExecutionContext ctx = mock(WatchExecutionContext.class); when(periodThrottler.throttle(ctx)).thenReturn(Throttler.Result.NO); Throttler.Result expectedResult = Throttler.Result.throttle("_reason"); when(ackThrottler.throttle(ctx)).thenReturn(expectedResult); - AlertThrottler throttler = new AlertThrottler(periodThrottler, ackThrottler); + WatchThrottler throttler = new WatchThrottler(periodThrottler, ackThrottler); Throttler.Result result = throttler.throttle(ctx); assertThat(result, notNullValue()); assertThat(result, is(expectedResult)); @@ -38,11 +38,11 @@ public class AlertThrottlerTests extends ElasticsearchTestCase { public void testThrottle_DueToPeriod() throws Exception { PeriodThrottler periodThrottler = mock(PeriodThrottler.class); AckThrottler ackThrottler = mock(AckThrottler.class); - ExecutionContext ctx = mock(ExecutionContext.class); + WatchExecutionContext ctx = mock(WatchExecutionContext.class); Throttler.Result expectedResult = Throttler.Result.throttle("_reason"); when(periodThrottler.throttle(ctx)).thenReturn(expectedResult); when(ackThrottler.throttle(ctx)).thenReturn(Throttler.Result.NO); - AlertThrottler throttler = new AlertThrottler(periodThrottler, ackThrottler); + WatchThrottler throttler = new WatchThrottler(periodThrottler, ackThrottler); Throttler.Result result = throttler.throttle(ctx); assertThat(result, notNullValue()); assertThat(result, is(expectedResult)); @@ -52,12 +52,12 @@ public class AlertThrottlerTests extends ElasticsearchTestCase { public void testThrottle_DueBoth() throws Exception { PeriodThrottler periodThrottler = mock(PeriodThrottler.class); AckThrottler ackThrottler = mock(AckThrottler.class); - ExecutionContext ctx = mock(ExecutionContext.class); + WatchExecutionContext ctx = mock(WatchExecutionContext.class); Throttler.Result periodResult = Throttler.Result.throttle("_reason_period"); when(periodThrottler.throttle(ctx)).thenReturn(periodResult); Throttler.Result ackResult = Throttler.Result.throttle("_reason_ack"); when(ackThrottler.throttle(ctx)).thenReturn(ackResult); - AlertThrottler throttler = new AlertThrottler(periodThrottler, ackThrottler); + WatchThrottler throttler = new WatchThrottler(periodThrottler, ackThrottler); Throttler.Result result = throttler.throttle(ctx); assertThat(result, notNullValue()); // we always check the period first... so the result will come for the period throttler @@ -68,10 +68,10 @@ public class AlertThrottlerTests extends ElasticsearchTestCase { public void testNoThrottle() throws Exception { PeriodThrottler periodThrottler = mock(PeriodThrottler.class); AckThrottler ackThrottler = mock(AckThrottler.class); - ExecutionContext ctx = mock(ExecutionContext.class); + WatchExecutionContext ctx = mock(WatchExecutionContext.class); when(periodThrottler.throttle(ctx)).thenReturn(Throttler.Result.NO); when(ackThrottler.throttle(ctx)).thenReturn(Throttler.Result.NO); - AlertThrottler throttler = new AlertThrottler(periodThrottler, ackThrottler); + WatchThrottler throttler = new WatchThrottler(periodThrottler, ackThrottler); Throttler.Result result = throttler.throttle(ctx); assertThat(result, notNullValue()); assertThat(result, is(Throttler.Result.NO)); @@ -80,10 +80,10 @@ public class AlertThrottlerTests extends ElasticsearchTestCase { @Test public void testWithoutPeriod() throws Exception { AckThrottler ackThrottler = mock(AckThrottler.class); - ExecutionContext ctx = mock(ExecutionContext.class); + WatchExecutionContext ctx = mock(WatchExecutionContext.class); Throttler.Result ackResult = mock(Throttler.Result.class); when(ackThrottler.throttle(ctx)).thenReturn(ackResult); - AlertThrottler throttler = new AlertThrottler(null, ackThrottler); + WatchThrottler throttler = new WatchThrottler(null, ackThrottler); Throttler.Result result = throttler.throttle(ctx); assertThat(result, notNullValue()); assertThat(result, sameInstance(ackResult)); diff --git a/src/test/java/org/elasticsearch/alerts/transform/ChainTransformTests.java b/src/test/java/org/elasticsearch/watcher/transform/ChainTransformTests.java similarity index 94% rename from src/test/java/org/elasticsearch/alerts/transform/ChainTransformTests.java rename to src/test/java/org/elasticsearch/watcher/transform/ChainTransformTests.java index fe50fa5547a..845fb6e754e 100644 --- a/src/test/java/org/elasticsearch/alerts/transform/ChainTransformTests.java +++ b/src/test/java/org/elasticsearch/watcher/transform/ChainTransformTests.java @@ -3,10 +3,10 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -37,7 +37,7 @@ public class ChainTransformTests extends ElasticsearchTestCase { new NamedTransform("name2"), new NamedTransform("name3"))); - ExecutionContext ctx = mock(ExecutionContext.class); + WatchExecutionContext ctx = mock(WatchExecutionContext.class); Payload payload = new Payload.Simple(new HashMap()); Transform.Result result = transform.apply(ctx, payload); @@ -92,7 +92,7 @@ public class ChainTransformTests extends ElasticsearchTestCase { } @Override - public Result apply(ExecutionContext ctx, Payload payload) throws IOException { + public Result apply(WatchExecutionContext ctx, Payload payload) throws IOException { Map data = new HashMap<>(payload.data()); List names = (List) data.get("names"); diff --git a/src/test/java/org/elasticsearch/alerts/transform/ScriptTransformTests.java b/src/test/java/org/elasticsearch/watcher/transform/ScriptTransformTests.java similarity index 88% rename from src/test/java/org/elasticsearch/alerts/transform/ScriptTransformTests.java rename to src/test/java/org/elasticsearch/watcher/transform/ScriptTransformTests.java index dd6d8a2daff..24d7895bf87 100644 --- a/src/test/java/org/elasticsearch/alerts/transform/ScriptTransformTests.java +++ b/src/test/java/org/elasticsearch/watcher/transform/ScriptTransformTests.java @@ -3,13 +3,13 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.support.Script; -import org.elasticsearch.alerts.support.Variables; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.Variables; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -22,7 +22,7 @@ import org.junit.Test; import java.util.Collections; import java.util.Map; -import static org.elasticsearch.alerts.test.AlertsTestUtils.*; +import static org.elasticsearch.watcher.test.WatcherTestUtils.*; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.mock; @@ -41,7 +41,7 @@ public class ScriptTransformTests extends ElasticsearchTestCase { Script script = new Script("_script", type, "_lang", params); ScriptTransform transform = new ScriptTransform(service, script); - ExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD); + WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD); Payload payload = simplePayload("key", "value"); diff --git a/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java b/src/test/java/org/elasticsearch/watcher/transform/SearchTransformTests.java similarity index 91% rename from src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java rename to src/test/java/org/elasticsearch/watcher/transform/SearchTransformTests.java index 1f671ee88b5..93424d1a3f6 100644 --- a/src/test/java/org/elasticsearch/alerts/transform/SearchTransformTests.java +++ b/src/test/java/org/elasticsearch/watcher/transform/SearchTransformTests.java @@ -3,16 +3,16 @@ * 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.alerts.transform; +package org.elasticsearch.watcher.transform; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.alerts.ExecutionContext; -import org.elasticsearch.alerts.Payload; -import org.elasticsearch.alerts.support.Variables; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.test.AbstractAlertsSingleNodeTests; +import org.elasticsearch.watcher.watch.WatchExecutionContext; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.support.Variables; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.test.AbstractWatcherSingleNodeTests; import org.elasticsearch.client.Requests; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.ImmutableSettings; @@ -25,8 +25,8 @@ import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static org.elasticsearch.alerts.support.AlertsDateUtils.parseDate; -import static org.elasticsearch.alerts.test.AlertsTestUtils.*; +import static org.elasticsearch.watcher.support.WatcherDateUtils.parseDate; +import static org.elasticsearch.watcher.test.WatcherTestUtils.*; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.FilterBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.filteredQuery; @@ -37,7 +37,7 @@ import static org.hamcrest.Matchers.*; /** * */ -public class SearchTransformTests extends AbstractAlertsSingleNodeTests { +public class SearchTransformTests extends AbstractWatcherSingleNodeTests { @Test public void testApply() throws Exception { @@ -53,7 +53,7 @@ public class SearchTransformTests extends AbstractAlertsSingleNodeTests { .endObject()); SearchTransform transform = new SearchTransform(logger, scriptService(), ClientProxy.of(client()), request); - ExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD); + WatchExecutionContext ctx = mockExecutionContext("_name", EMPTY_PAYLOAD); Transform.Result result = transform.apply(ctx, EMPTY_PAYLOAD); assertThat(result, notNullValue()); @@ -110,7 +110,7 @@ public class SearchTransformTests extends AbstractAlertsSingleNodeTests { SearchTransform transform = new SearchTransform(logger, scriptService(), ClientProxy.of(client()), request); - ExecutionContext ctx = mockExecutionContext(parseDate("2015-01-04T00:00:00"), parseDate("2015-01-04T00:00:00"), parseDate("2015-01-01T00:00:00"), "_name", EMPTY_PAYLOAD); + WatchExecutionContext ctx = mockExecutionContext(parseDate("2015-01-04T00:00:00"), parseDate("2015-01-04T00:00:00"), parseDate("2015-01-01T00:00:00"), "_name", EMPTY_PAYLOAD); Payload payload = simplePayload("value", "val_3"); diff --git a/src/test/java/org/elasticsearch/alerts/AlertLockServiceTests.java b/src/test/java/org/elasticsearch/watcher/watch/WatchLockServiceTests.java similarity index 69% rename from src/test/java/org/elasticsearch/alerts/AlertLockServiceTests.java rename to src/test/java/org/elasticsearch/watcher/watch/WatchLockServiceTests.java index efb6feb9077..621e81bbd18 100644 --- a/src/test/java/org/elasticsearch/alerts/AlertLockServiceTests.java +++ b/src/test/java/org/elasticsearch/watcher/watch/WatchLockServiceTests.java @@ -3,7 +3,7 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.test.ElasticsearchTestCase; @@ -15,11 +15,11 @@ import static org.hamcrest.Matchers.is; /** */ -public class AlertLockServiceTests extends ElasticsearchTestCase { +public class WatchLockServiceTests extends ElasticsearchTestCase { @Test public void testLocking_notStarted() { - AlertLockService lockService = new AlertLockService(); + WatchLockService lockService = new WatchLockService(); try { lockService.acquire("_name"); fail("exception expected"); @@ -30,20 +30,20 @@ public class AlertLockServiceTests extends ElasticsearchTestCase { @Test public void testLocking() { - AlertLockService lockService = new AlertLockService(); + WatchLockService lockService = new WatchLockService(); lockService.start(); - AlertLockService.Lock lock = lockService.acquire("_name"); - assertThat(lockService.getAlertLock().hasLockedKeys(), is(true)); + WatchLockService.Lock lock = lockService.acquire("_name"); + assertThat(lockService.getWatchLocks().hasLockedKeys(), is(true)); lock.release(); - assertThat(lockService.getAlertLock().hasLockedKeys(), is(false)); + assertThat(lockService.getWatchLocks().hasLockedKeys(), is(false)); lockService.stop(); } @Test public void testLocking_alreadyHeld() { - AlertLockService lockService = new AlertLockService(); + WatchLockService lockService = new WatchLockService(); lockService.start(); - AlertLockService.Lock lock1 = lockService.acquire("_name"); + WatchLockService.Lock lock1 = lockService.acquire("_name"); try { lockService.acquire("_name"); fail("exception expected"); diff --git a/src/test/java/org/elasticsearch/watcher/watch/WatchServiceTests.java b/src/test/java/org/elasticsearch/watcher/watch/WatchServiceTests.java new file mode 100644 index 00000000000..25c698353f9 --- /dev/null +++ b/src/test/java/org/elasticsearch/watcher/watch/WatchServiceTests.java @@ -0,0 +1,172 @@ +/* + * 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.watcher.watch; + +import org.elasticsearch.action.delete.DeleteResponse; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.watcher.WatcherException; +import org.elasticsearch.watcher.history.HistoryService; +import org.elasticsearch.watcher.scheduler.Scheduler; +import org.elasticsearch.watcher.scheduler.schedule.Schedule; +import org.elasticsearch.common.bytes.BytesArray; +import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.settings.ImmutableSettings; +import org.elasticsearch.test.ElasticsearchTestCase; +import org.junit.Before; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.util.concurrent.atomic.AtomicReference; + +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.sameInstance; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + +/** + */ +public class WatchServiceTests extends ElasticsearchTestCase { + + private Scheduler scheduler; + private WatchStore watchStore; + private WatchService watchService; + private HistoryService historyService; + private WatchLockService watchLockService; + + @Before + public void init() throws Exception { + scheduler = mock(Scheduler.class); + watchStore = mock(WatchStore.class); + historyService = mock(HistoryService.class); + watchLockService = mock(WatchLockService.class); + watchService = new WatchService(ImmutableSettings.EMPTY, scheduler, watchStore, historyService, watchLockService); + Field field = WatchService.class.getDeclaredField("state"); + field.setAccessible(true); + AtomicReference state = (AtomicReference) field.get(watchService); + state.set(WatchService.State.STARTED); + } + + @Test + public void testPutWatch() { + IndexResponse indexResponse = mock(IndexResponse.class); + Watch watch = mock(Watch.class); + WatchStore.WatchPut watchPut = mock(WatchStore.WatchPut.class); + when(watchPut.indexResponse()).thenReturn(indexResponse); + when(watchPut.current()).thenReturn(watch); + + WatchLockService.Lock lock = mock(WatchLockService.Lock.class); + when(watchLockService.acquire(any(String.class))).thenReturn(lock); + when(watchStore.put(any(String.class), any(BytesReference.class))).thenReturn(watchPut); + IndexResponse response = watchService.putWatch("_name", new BytesArray("{}")); + assertThat(response, sameInstance(indexResponse)); + + verify(scheduler, times(1)).add(any(Scheduler.Job.class)); + } + + @Test + public void testPutWatch_NotSchedule() { + Schedule schedule = mock(Schedule.class); + + IndexResponse indexResponse = mock(IndexResponse.class); + Watch watch = mock(Watch.class); + when(watch.schedule()).thenReturn(schedule); + WatchStore.WatchPut watchPut = mock(WatchStore.WatchPut.class); + when(watchPut.indexResponse()).thenReturn(indexResponse); + when(watchPut.current()).thenReturn(watch); + Watch previousWatch = mock(Watch.class); + when(previousWatch.schedule()).thenReturn(schedule); + when(watchPut.previous()).thenReturn(previousWatch); + + WatchLockService.Lock lock = mock(WatchLockService.Lock.class); + when(watchLockService.acquire(any(String.class))).thenReturn(lock); + when(watchStore.put(any(String.class), any(BytesReference.class))).thenReturn(watchPut); + IndexResponse response = watchService.putWatch("_name", new BytesArray("{}")); + assertThat(response, sameInstance(indexResponse)); + + verifyZeroInteractions(scheduler); + } + + @Test + public void testDeleteWatch() throws Exception { + WatchLockService.Lock lock = mock(WatchLockService.Lock.class); + when(watchLockService.acquire("_name")).thenReturn(lock); + + WatchStore.WatchDelete expectedWatchDelete = mock(WatchStore.WatchDelete.class); + DeleteResponse deleteResponse = mock(DeleteResponse.class); + when(deleteResponse.isFound()).thenReturn(true); + when(expectedWatchDelete.deleteResponse()).thenReturn(deleteResponse); + when(watchStore.delete("_name")).thenReturn(expectedWatchDelete); + WatchStore.WatchDelete watchDelete = watchService.deleteWatch("_name"); + + assertThat(watchDelete, sameInstance(expectedWatchDelete)); + verify(scheduler, times(1)).remove("_name"); + } + + @Test + public void testDeleteWatch_NotFound() throws Exception { + WatchLockService.Lock lock = mock(WatchLockService.Lock.class); + when(watchLockService.acquire("_name")).thenReturn(lock); + + WatchStore.WatchDelete expectedWatchDelete = mock(WatchStore.WatchDelete.class); + DeleteResponse deleteResponse = mock(DeleteResponse.class); + when(deleteResponse.isFound()).thenReturn(false); + when(expectedWatchDelete.deleteResponse()).thenReturn(deleteResponse); + when(watchStore.delete("_name")).thenReturn(expectedWatchDelete); + WatchStore.WatchDelete watchDelete = watchService.deleteWatch("_name"); + + assertThat(watchDelete, sameInstance(expectedWatchDelete)); + verifyZeroInteractions(scheduler); + } + + @Test + public void testAckWatch() throws Exception { + WatchLockService.Lock lock = mock(WatchLockService.Lock.class); + when(watchLockService.acquire("_name")).thenReturn(lock); + Watch watch = mock(Watch.class); + when(watch.ack()).thenReturn(true); + Watch.Status status = new Watch.Status(); + when(watch.status()).thenReturn(status); + when(watchStore.get("_name")).thenReturn(watch); + + Watch.Status result = watchService.ackWatch("_name"); + assertThat(result, not(sameInstance(status))); + + verify(watchStore, times(1)).updateStatus(watch); + } + + @Test + public void testAckWatch_NotAck() throws Exception { + WatchLockService.Lock lock = mock(WatchLockService.Lock.class); + when(watchLockService.acquire("_name")).thenReturn(lock); + Watch watch = mock(Watch.class); + when(watch.ack()).thenReturn(false); + Watch.Status status = new Watch.Status(); + when(watch.status()).thenReturn(status); + when(watchStore.get("_name")).thenReturn(watch); + + Watch.Status result = watchService.ackWatch("_name"); + assertThat(result, not(sameInstance(status))); + + verify(watchStore, never()).updateStatus(watch); + } + + @Test + public void testAckWatch_NoWatch() throws Exception { + WatchLockService.Lock lock = mock(WatchLockService.Lock.class); + when(watchLockService.acquire("_name")).thenReturn(lock); + when(watchStore.get("_name")).thenReturn(null); + + try { + watchService.ackWatch("_name"); + fail(); + } catch (WatcherException e) { + // expected + } + + verify(watchStore, never()).updateStatus(any(Watch.class)); + } + +} diff --git a/src/test/java/org/elasticsearch/alerts/AlertStoreTests.java b/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java similarity index 77% rename from src/test/java/org/elasticsearch/alerts/AlertStoreTests.java rename to src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java index e97f0a1a9ee..0b9c1e22690 100644 --- a/src/test/java/org/elasticsearch/alerts/AlertStoreTests.java +++ b/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java @@ -3,14 +3,14 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.search.*; -import org.elasticsearch.alerts.support.Callback; -import org.elasticsearch.alerts.support.TemplateUtils; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.support.Callback; +import org.elasticsearch.watcher.support.TemplateUtils; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; @@ -42,12 +42,12 @@ import static org.mockito.Mockito.*; /** */ -public class AlertStoreTests extends ElasticsearchTestCase { +public class WatchStoreTests extends ElasticsearchTestCase { - private AlertsStore alertsStore; + private WatchStore watchStore; private ClientProxy clientProxy; private TemplateUtils templateUtils; - private Alert.Parser parser; + private Watch.Parser parser; private ClusterService clusterService; private ThreadPool threadPool; private Callback callback; @@ -56,30 +56,30 @@ public class AlertStoreTests extends ElasticsearchTestCase { public void init() { clientProxy = mock(ClientProxy.class); templateUtils = mock(TemplateUtils.class); - parser = mock(Alert.Parser.class); + parser = mock(Watch.Parser.class); clusterService = mock(ClusterService.class); threadPool = mock(ThreadPool.class); callback = mock(Callback.class); - alertsStore = new AlertsStore(ImmutableSettings.EMPTY, clientProxy, templateUtils, parser, clusterService, threadPool); + watchStore = new WatchStore(ImmutableSettings.EMPTY, clientProxy, templateUtils, parser, clusterService, threadPool); } @Test - public void testStartNoPreviousAlertsIndex() { + public void testStartNoPreviousWatchesIndex() { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); MetaData.Builder metaDateBuilder = MetaData.builder(); csBuilder.metaData(metaDateBuilder); ClusterState cs = csBuilder.build(); - alertsStore.start(cs, callback); - assertThat(alertsStore.started(), is(true)); - assertThat(alertsStore.getAlerts().size(), equalTo(0)); + watchStore.start(cs, callback); + assertThat(watchStore.started(), is(true)); + assertThat(watchStore.watches().size(), equalTo(0)); verify(callback, times(1)).onSuccess(any(ClusterState.class)); verify(callback, never()).onFailure(any(Throwable.class)); - verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "alerts"); + verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "watches"); verifyZeroInteractions(clientProxy); verifyZeroInteractions(clusterService); - alertsStore.start(cs, callback); + watchStore.start(cs, callback); verify(callback, times(2)).onSuccess(any(ClusterState.class)); verify(callback, never()).onFailure(any(Throwable.class)); verifyNoMoreInteractions(templateUtils); @@ -96,10 +96,10 @@ public class AlertStoreTests extends ElasticsearchTestCase { .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .build(); - metaDateBuilder.put(IndexMetaData.builder(AlertsStore.ALERT_INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); - IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(AlertsStore.ALERT_INDEX); - indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(AlertsStore.ALERT_INDEX, 0), false) - .addShard(new ImmutableShardRouting(AlertsStore.ALERT_INDEX, 0, "_node_id", null, true, ShardRoutingState.UNASSIGNED, 1)) + metaDateBuilder.put(IndexMetaData.builder(WatchStore.INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); + IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(WatchStore.INDEX); + indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(WatchStore.INDEX, 0), false) + .addShard(new ImmutableShardRouting(WatchStore.INDEX, 0, "_node_id", null, true, ShardRoutingState.UNASSIGNED, 1)) .build()); indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); @@ -108,7 +108,7 @@ public class AlertStoreTests extends ElasticsearchTestCase { ClusterState cs = csBuilder.build(); - alertsStore.start(cs, callback); + watchStore.start(cs, callback); verify(clusterService, timeout(1)).add(any(ClusterStateListener.class)); verifyZeroInteractions(callback); verifyZeroInteractions(templateUtils); @@ -124,10 +124,10 @@ public class AlertStoreTests extends ElasticsearchTestCase { .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .build(); - metaDateBuilder.put(IndexMetaData.builder(AlertsStore.ALERT_INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); - IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(AlertsStore.ALERT_INDEX); - indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(AlertsStore.ALERT_INDEX, 0), false) - .addShard(new ImmutableShardRouting(AlertsStore.ALERT_INDEX, 0, "_node_id", null, true, ShardRoutingState.STARTED, 1)) + metaDateBuilder.put(IndexMetaData.builder(WatchStore.INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); + IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(WatchStore.INDEX); + indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(WatchStore.INDEX, 0), false) + .addShard(new ImmutableShardRouting(WatchStore.INDEX, 0, "_node_id", null, true, ShardRoutingState.STARTED, 1)) .build()); indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); @@ -139,7 +139,7 @@ public class AlertStoreTests extends ElasticsearchTestCase { ClusterState cs = csBuilder.build(); - alertsStore.start(cs, callback); + watchStore.start(cs, callback); verify(clusterService, timeout(1)).add(any(ClusterStateListener.class)); verifyZeroInteractions(callback); verifyZeroInteractions(templateUtils); @@ -157,10 +157,10 @@ public class AlertStoreTests extends ElasticsearchTestCase { .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .build(); - metaDateBuilder.put(IndexMetaData.builder(AlertsStore.ALERT_INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); - IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(AlertsStore.ALERT_INDEX); - indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(AlertsStore.ALERT_INDEX, 0), false) - .addShard(new ImmutableShardRouting(AlertsStore.ALERT_INDEX, 0, "_node_id", null, true, ShardRoutingState.STARTED, 1)) + metaDateBuilder.put(IndexMetaData.builder(WatchStore.INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); + IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(WatchStore.INDEX); + indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(WatchStore.INDEX, 0), false) + .addShard(new ImmutableShardRouting(WatchStore.INDEX, 0, "_node_id", null, true, ShardRoutingState.STARTED, 1)) .build()); indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); @@ -177,7 +177,7 @@ public class AlertStoreTests extends ElasticsearchTestCase { ClusterState cs = csBuilder.build(); - alertsStore.start(cs, callback); + watchStore.start(cs, callback); verify(clusterService, timeout(1)).add(any(ClusterStateListener.class)); verifyZeroInteractions(callback); verifyZeroInteractions(templateUtils); @@ -187,7 +187,7 @@ public class AlertStoreTests extends ElasticsearchTestCase { } @Test - public void testStartNoAlertStored() { + public void testStartNoWatchStored() { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); MetaData.Builder metaDateBuilder = MetaData.builder(); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); @@ -195,10 +195,10 @@ public class AlertStoreTests extends ElasticsearchTestCase { .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .build(); - metaDateBuilder.put(IndexMetaData.builder(AlertsStore.ALERT_INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); - IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(AlertsStore.ALERT_INDEX); - indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(AlertsStore.ALERT_INDEX, 0), false) - .addShard(new ImmutableShardRouting(AlertsStore.ALERT_INDEX, 0, "_node_id", null, true, ShardRoutingState.STARTED, 1)) + metaDateBuilder.put(IndexMetaData.builder(WatchStore.INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); + IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(WatchStore.INDEX); + indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(WatchStore.INDEX, 0), false) + .addShard(new ImmutableShardRouting(WatchStore.INDEX, 0, "_node_id", null, true, ShardRoutingState.STARTED, 1)) .build()); indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); @@ -215,20 +215,20 @@ public class AlertStoreTests extends ElasticsearchTestCase { ClusterState cs = csBuilder.build(); - alertsStore.start(cs, callback); + watchStore.start(cs, callback); verifyZeroInteractions(clusterService); - assertThat(alertsStore.started(), is(true)); - assertThat(alertsStore.getAlerts().size(), equalTo(0)); + assertThat(watchStore.started(), is(true)); + assertThat(watchStore.watches().size(), equalTo(0)); verify(callback, times(1)).onSuccess(any(ClusterState.class)); verify(callback, never()).onFailure(any(Throwable.class)); - verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "alerts"); + verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "watches"); verify(clientProxy, times(1)).refresh(any(RefreshRequest.class)); verify(clientProxy, times(1)).search(any(SearchRequest.class)); verify(clientProxy, times(1)).clearScroll(anyString()); } @Test - public void testStartAlertStored() { + public void testStartWatchStored() { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); MetaData.Builder metaDateBuilder = MetaData.builder(); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); @@ -236,10 +236,10 @@ public class AlertStoreTests extends ElasticsearchTestCase { .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .build(); - metaDateBuilder.put(IndexMetaData.builder(AlertsStore.ALERT_INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); - IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(AlertsStore.ALERT_INDEX); - indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(AlertsStore.ALERT_INDEX, 0), false) - .addShard(new ImmutableShardRouting(AlertsStore.ALERT_INDEX, 0, "_node_id", null, true, ShardRoutingState.STARTED, 1)) + metaDateBuilder.put(IndexMetaData.builder(WatchStore.INDEX).settings(settings).numberOfShards(1).numberOfReplicas(1)); + IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(WatchStore.INDEX); + indexRoutingTableBuilder.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId(WatchStore.INDEX, 0), false) + .addShard(new ImmutableShardRouting(WatchStore.INDEX, 0, "_node_id", null, true, ShardRoutingState.STARTED, 1)) .build()); indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); @@ -261,25 +261,25 @@ public class AlertStoreTests extends ElasticsearchTestCase { SearchResponse searchResponse3 = mockSearchResponse(1, 1, 2); when(clientProxy.searchScroll(anyString(), any(TimeValue.class))).thenReturn(searchResponse2, searchResponse3); - Alert alert1 = mock(Alert.class); - Alert.Status status = new Alert.Status(); - when(alert1.status()).thenReturn(status); - Alert alert2 = mock(Alert.class); - when(alert2.status()).thenReturn(status); - when(parser.parse("_id1", true, source)).thenReturn(alert1); - when(parser.parse("_id2", true, source)).thenReturn(alert2); + Watch watch1 = mock(Watch.class); + Watch.Status status = new Watch.Status(); + when(watch1.status()).thenReturn(status); + Watch watch2 = mock(Watch.class); + when(watch2.status()).thenReturn(status); + when(parser.parse("_id1", true, source)).thenReturn(watch1); + when(parser.parse("_id2", true, source)).thenReturn(watch2); when(clientProxy.clearScroll(anyString())).thenReturn(new ClearScrollResponse(true, 0)); ClusterState cs = csBuilder.build(); - alertsStore.start(cs, callback); + watchStore.start(cs, callback); verifyZeroInteractions(clusterService); - assertThat(alertsStore.started(), is(true)); - assertThat(alertsStore.getAlerts().size(), equalTo(2)); + assertThat(watchStore.started(), is(true)); + assertThat(watchStore.watches().size(), equalTo(2)); verify(callback, times(1)).onSuccess(any(ClusterState.class)); verify(callback, never()).onFailure(any(Throwable.class)); - verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "alerts"); + verify(templateUtils, times(1)).ensureIndexTemplateIsLoaded(cs, "watches"); verify(clientProxy, times(1)).refresh(any(RefreshRequest.class)); verify(clientProxy, times(1)).search(any(SearchRequest.class)); verify(clientProxy, times(2)).searchScroll(anyString(), any(TimeValue.class)); diff --git a/src/test/java/org/elasticsearch/alerts/AlertTests.java b/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java similarity index 79% rename from src/test/java/org/elasticsearch/alerts/AlertTests.java rename to src/test/java/org/elasticsearch/watcher/watch/WatchTests.java index d66a672d2ea..35d54f69990 100644 --- a/src/test/java/org/elasticsearch/alerts/AlertTests.java +++ b/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java @@ -3,38 +3,37 @@ * 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.alerts; +package org.elasticsearch.watcher.watch; import com.carrotsearch.randomizedtesting.annotations.Repeat; -import org.elasticsearch.alerts.actions.Action; -import org.elasticsearch.alerts.actions.ActionRegistry; -import org.elasticsearch.alerts.actions.Actions; -import org.elasticsearch.alerts.actions.email.EmailAction; -import org.elasticsearch.alerts.actions.email.service.Email; -import org.elasticsearch.alerts.actions.email.service.EmailService; -import org.elasticsearch.alerts.actions.email.service.Profile; -import org.elasticsearch.alerts.actions.index.IndexAction; -import org.elasticsearch.alerts.actions.webhook.HttpClient; -import org.elasticsearch.alerts.actions.webhook.WebhookAction; -import org.elasticsearch.alerts.condition.Condition; -import org.elasticsearch.alerts.condition.ConditionRegistry; -import org.elasticsearch.alerts.condition.script.ScriptCondition; -import org.elasticsearch.alerts.condition.simple.AlwaysTrueCondition; -import org.elasticsearch.alerts.input.Input; -import org.elasticsearch.alerts.input.InputRegistry; -import org.elasticsearch.alerts.input.search.SearchInput; -import org.elasticsearch.alerts.input.simple.SimpleInput; -import org.elasticsearch.alerts.scheduler.schedule.*; -import org.elasticsearch.alerts.scheduler.schedule.support.*; -import org.elasticsearch.alerts.support.AlertUtils; -import org.elasticsearch.alerts.support.Script; -import org.elasticsearch.alerts.support.clock.SystemClock; -import org.elasticsearch.alerts.support.init.proxy.ClientProxy; -import org.elasticsearch.alerts.support.init.proxy.ScriptServiceProxy; -import org.elasticsearch.alerts.support.template.ScriptTemplate; -import org.elasticsearch.alerts.support.template.Template; -import org.elasticsearch.alerts.test.AlertsTestUtils; -import org.elasticsearch.alerts.transform.*; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.ActionRegistry; +import org.elasticsearch.watcher.actions.Actions; +import org.elasticsearch.watcher.actions.email.EmailAction; +import org.elasticsearch.watcher.actions.email.service.Email; +import org.elasticsearch.watcher.actions.email.service.EmailService; +import org.elasticsearch.watcher.actions.email.service.Profile; +import org.elasticsearch.watcher.actions.index.IndexAction; +import org.elasticsearch.watcher.actions.webhook.HttpClient; +import org.elasticsearch.watcher.actions.webhook.WebhookAction; +import org.elasticsearch.watcher.condition.Condition; +import org.elasticsearch.watcher.condition.ConditionRegistry; +import org.elasticsearch.watcher.condition.script.ScriptCondition; +import org.elasticsearch.watcher.condition.simple.AlwaysTrueCondition; +import org.elasticsearch.watcher.input.Input; +import org.elasticsearch.watcher.input.InputRegistry; +import org.elasticsearch.watcher.input.search.SearchInput; +import org.elasticsearch.watcher.input.simple.SimpleInput; +import org.elasticsearch.watcher.scheduler.schedule.*; +import org.elasticsearch.watcher.scheduler.schedule.support.*; +import org.elasticsearch.watcher.support.WatcherUtils; +import org.elasticsearch.watcher.support.Script; +import org.elasticsearch.watcher.support.clock.SystemClock; +import org.elasticsearch.watcher.support.init.proxy.ClientProxy; +import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; +import org.elasticsearch.watcher.support.template.ScriptTemplate; +import org.elasticsearch.watcher.support.template.Template; +import org.elasticsearch.watcher.test.WatcherTestUtils; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.collect.ImmutableMap; @@ -46,16 +45,17 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.test.ElasticsearchTestCase; +import org.elasticsearch.watcher.transform.*; import org.junit.Before; import org.junit.Test; import java.util.Map; -import static org.elasticsearch.alerts.test.AlertsTestUtils.matchAllRequest; +import static org.elasticsearch.watcher.test.WatcherTestUtils.matchAllRequest; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.mock; -public class AlertTests extends ElasticsearchTestCase { +public class WatchTests extends ElasticsearchTestCase { private ScriptServiceProxy scriptService; private ClientProxy client; @@ -72,7 +72,7 @@ public class AlertTests extends ElasticsearchTestCase { httpClient = mock(HttpClient.class); emailService = mock(EmailService.class); templateParser = new ScriptTemplate.Parser(settings, scriptService); - logger = Loggers.getLogger(AlertTests.class); + logger = Loggers.getLogger(WatchTests.class); } @Test @Repeat(iterations = 20) @@ -96,30 +96,30 @@ public class AlertTests extends ElasticsearchTestCase { Map metadata = ImmutableMap.of("_key", "_val"); - Alert.Status status = new Alert.Status(); + Watch.Status status = new Watch.Status(); TimeValue throttlePeriod = randomBoolean() ? null : TimeValue.timeValueSeconds(randomIntBetween(5, 10)); - Alert alert = new Alert("_name", SystemClock.INSTANCE, schedule, input, condition, transform, actions, metadata, throttlePeriod, status); + Watch watch = new Watch("_name", SystemClock.INSTANCE, schedule, input, condition, transform, actions, metadata, throttlePeriod, status); - BytesReference bytes = XContentFactory.jsonBuilder().value(alert).bytes(); + BytesReference bytes = XContentFactory.jsonBuilder().value(watch).bytes(); logger.info(bytes.toUtf8()); - Alert.Parser alertParser = new Alert.Parser(settings, conditionRegistry, scheduleRegistry, transformRegistry, actionRegistry, inputRegistry, SystemClock.INSTANCE); + Watch.Parser watchParser = new Watch.Parser(settings, conditionRegistry, scheduleRegistry, transformRegistry, actionRegistry, inputRegistry, SystemClock.INSTANCE); boolean includeStatus = randomBoolean(); - Alert parsedAlert = alertParser.parse("_name", includeStatus, bytes); + Watch parsedWatch = watchParser.parse("_name", includeStatus, bytes); if (includeStatus) { - assertThat(parsedAlert.status(), equalTo(status)); + assertThat(parsedWatch.status(), equalTo(status)); } - assertThat(parsedAlert.schedule(), equalTo(schedule)); - assertThat(parsedAlert.input(), equalTo(input)); - assertThat(parsedAlert.condition(), equalTo(condition)); + assertThat(parsedWatch.schedule(), equalTo(schedule)); + assertThat(parsedWatch.input(), equalTo(input)); + assertThat(parsedWatch.condition(), equalTo(condition)); if (throttlePeriod != null) { - assertThat(parsedAlert.throttlePeriod().millis(), equalTo(throttlePeriod.millis())); + assertThat(parsedWatch.throttlePeriod().millis(), equalTo(throttlePeriod.millis())); } - assertThat(parsedAlert.metadata(), equalTo(metadata)); - assertThat(parsedAlert.actions(), equalTo(actions)); + assertThat(parsedWatch.metadata(), equalTo(metadata)); + assertThat(parsedWatch.actions(), equalTo(actions)); } private static Schedule randomSchedule() { @@ -175,7 +175,7 @@ public class AlertTests extends ElasticsearchTestCase { String type = randomFrom(SearchInput.TYPE, SimpleInput.TYPE); switch (type) { case SearchInput.TYPE: - return new SearchInput(logger, scriptService, client, AlertsTestUtils.newInputSearchRequest("idx")); + return new SearchInput(logger, scriptService, client, WatcherTestUtils.newInputSearchRequest("idx")); default: return new SimpleInput(logger, new Payload.Simple(ImmutableMap.builder().put("_key", "_val").build())); } @@ -221,10 +221,10 @@ public class AlertTests extends ElasticsearchTestCase { case ScriptTransform.TYPE: return new ScriptTransform(scriptService, new Script("_script")); case SearchTransform.TYPE: - return new SearchTransform(logger, scriptService, client, matchAllRequest(AlertUtils.DEFAULT_INDICES_OPTIONS)); + return new SearchTransform(logger, scriptService, client, matchAllRequest(WatcherUtils.DEFAULT_INDICES_OPTIONS)); default: // chain return new ChainTransform(ImmutableList.of( - new SearchTransform(logger, scriptService, client, matchAllRequest(AlertUtils.DEFAULT_INDICES_OPTIONS)), + new SearchTransform(logger, scriptService, client, matchAllRequest(WatcherUtils.DEFAULT_INDICES_OPTIONS)), new ScriptTransform(scriptService, new Script("_script")))); } } diff --git a/src/test/resources/org/elasticsearch/alerts/actions/email/service/logo.jpg b/src/test/resources/org/elasticsearch/alerts/actions/email/service/logo.jpg deleted file mode 100644 index f45114b4b99..00000000000 Binary files a/src/test/resources/org/elasticsearch/alerts/actions/email/service/logo.jpg and /dev/null differ diff --git a/src/test/resources/org/elasticsearch/watcher/actions/email/service/logo.png b/src/test/resources/org/elasticsearch/watcher/actions/email/service/logo.png new file mode 100644 index 00000000000..9f84883503f Binary files /dev/null and b/src/test/resources/org/elasticsearch/watcher/actions/email/service/logo.png differ