Skip to content

Commit

Permalink
put general error message into constants
Browse files Browse the repository at this point in the history
  • Loading branch information
ylwu-amzn committed Jul 30, 2021
1 parent c7b2d7e commit 713eb79
Show file tree
Hide file tree
Showing 17 changed files with 62 additions and 29 deletions.
3 changes: 2 additions & 1 deletion src/main/java/org/opensearch/ad/EntityProfileRunner.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public class EntityProfileRunner extends AbstractProfileRunner {
private final Logger logger = LogManager.getLogger(EntityProfileRunner.class);

static final String NOT_HC_DETECTOR_ERR_MSG = "This is not a high cardinality detector";
static final String EMPTY_ENTITY_ATTRIBUTES = "Empty entity attributes";
static final String NO_ENTITY = "Cannot find entity";
private Client client;
private NamedXContentRegistry xContentRegistry;
Expand Down Expand Up @@ -159,7 +160,7 @@ private void validateEntity(
) {
Map<String, String> attributes = entity.getAttributes();
if (attributes == null || attributes.size() != categoryFields.size()) {
listener.onFailure(new IllegalArgumentException("Empty entity attributes"));
listener.onFailure(new IllegalArgumentException(EMPTY_ENTITY_ATTRIBUTES));
return;
}
for (String field : categoryFields) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,12 @@ public class CommonErrorMessages {
"Having trouble querying data because all of your features have been disabled.";
public static final String INVALID_TIMESTAMP_ERR_MSG = "timestamp is invalid";
public static String FAIL_TO_PARSE_DETECTOR_MSG = "Fail to parse detector with id: ";
public static String FAIL_TO_FIND_DETECTOR_MSG = "Fail to find detector with id: ";
// change this error message to make it compatible with old version's integration(nexus) test
public static String FAIL_TO_FIND_DETECTOR_MSG = "Can't find detector with id: ";
public static String FAIL_TO_GET_PROFILE_MSG = "Fail to get profile for detector ";
public static String FAIL_TO_GET_TOTAL_ENTITIES = "Failed to get total entities for detector ";
public static String FAIL_TO_GET_USER_INFO = "Unable to get user information from detector ";
public static String NO_PERMISSION_TO_ACCESS_DETECTOR = "User does not have permissions to access detector: ";
public static String CATEGORICAL_FIELD_NUMBER_SURPASSED = "We don't support categorical fields more than ";
public static String EMPTY_PROFILES_COLLECT = "profiles to collect are missing or invalid";
public static String FAIL_FETCH_ERR_MSG = "Fail to fetch profile for ";
Expand All @@ -72,4 +75,16 @@ public static String getTooManyCategoricalFieldErr(int limit) {
public static String EXCEED_HISTORICAL_ANALYSIS_LIMIT = "Exceed max historical analysis limit per node";
public static String NO_ELIGIBLE_NODE_TO_RUN_DETECTOR = "No eligible node to run detector ";
public static String EMPTY_STALE_RUNNING_ENTITIES = "Empty stale running entities";

public static String FAIL_TO_GET_DETECTOR = "Fail to get detector";
public static String FAIL_TO_GET_DETECTOR_INFO = "Fail to get detector info";
public static String FAIL_TO_CREATE_DETECTOR = "Fail to create detector";
public static String FAIL_TO_UPDATE_DETECTOR = "Fail to update detector";
public static String FAIL_TO_PREVIEW_DETECTOR = "Fail to preview detector";
public static String FAIL_TO_START_DETECTOR = "Fail to start detector";
public static String FAIL_TO_STOP_DETECTOR = "Fail to stop detector";
public static String FAIL_TO_DELETE_DETECTOR = "Fail to delete detector";
public static String FAIL_TO_DELETE_AD_RESULT = "Fail to delete anomaly result";
public static String FAIL_TO_GET_STATS = "Fail to get stats";
public static String FAIL_TO_SEARCH = "Fail to search";
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

package org.opensearch.ad.rest.handler;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG;
import static org.opensearch.ad.model.ADTaskType.HISTORICAL_DETECTOR_TASK_TYPES;
import static org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX;
import static org.opensearch.ad.util.RestHandlerUtils.XCONTENT_WITH_TYPE;
Expand Down Expand Up @@ -229,7 +230,7 @@ private void updateAnomalyDetector(String detectorId) {

private void onGetAnomalyDetectorResponse(GetResponse response) {
if (!response.isExists()) {
listener.onFailure(new OpenSearchStatusException("AnomalyDetector is not found with id: " + detectorId, RestStatus.NOT_FOUND));
listener.onFailure(new OpenSearchStatusException(FAIL_TO_FIND_DETECTOR_MSG, RestStatus.NOT_FOUND));
return;
}
try (XContentParser parser = RestHandlerUtils.createXContentParserFromRegistry(xContentRegistry, response.getSourceAsBytesRef())) {
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/org/opensearch/ad/task/ADTaskManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import static org.opensearch.ad.AnomalyDetectorPlugin.AD_BATCH_TASK_THREAD_POOL_NAME;
import static org.opensearch.ad.constant.CommonErrorMessages.DETECTOR_IS_RUNNING;
import static org.opensearch.ad.constant.CommonErrorMessages.EXCEED_HISTORICAL_ANALYSIS_LIMIT;
import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG;
import static org.opensearch.ad.constant.CommonErrorMessages.NO_ELIGIBLE_NODE_TO_RUN_DETECTOR;
import static org.opensearch.ad.indices.AnomalyDetectionIndices.ALL_AD_RESULTS_INDEX_PATTERN;
import static org.opensearch.ad.model.ADTask.DETECTOR_ID_FIELD;
Expand Down Expand Up @@ -548,7 +549,7 @@ public <T> void getDetector(String detectorId, Consumer<AnomalyDetector> consume
GetRequest getRequest = new GetRequest(ANOMALY_DETECTORS_INDEX, detectorId);
client.get(getRequest, ActionListener.wrap(response -> {
if (!response.isExists()) {
listener.onFailure(new OpenSearchStatusException("AnomalyDetector is not found", RestStatus.NOT_FOUND));
listener.onFailure(new OpenSearchStatusException(FAIL_TO_FIND_DETECTOR_MSG, RestStatus.NOT_FOUND));
return;
}
try (XContentParser parser = createXContentParserFromRegistry(xContentRegistry, response.getSourceAsBytesRef())) {
Expand All @@ -574,7 +575,7 @@ public <T> void getDetector(
GetRequest getRequest = new GetRequest(ANOMALY_DETECTORS_INDEX, detectorId);
client.get(getRequest, ActionListener.wrap(response -> {
if (!response.isExists()) {
listener.onFailure(new OpenSearchStatusException("AnomalyDetector is not found", RestStatus.NOT_FOUND));
listener.onFailure(new OpenSearchStatusException(FAIL_TO_FIND_DETECTOR_MSG, RestStatus.NOT_FOUND));
return;
}
try (XContentParser parser = createXContentParserFromRegistry(xContentRegistry, response.getSourceAsBytesRef())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

package org.opensearch.ad.transport;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_START_DETECTOR;
import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_STOP_DETECTOR;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.REQUEST_TIMEOUT;
import static org.opensearch.ad.util.ParseUtils.getUserContext;
Expand Down Expand Up @@ -97,8 +99,8 @@ protected void doExecute(Task task, AnomalyDetectorJobRequest request, ActionLis
long primaryTerm = request.getPrimaryTerm();
String rawPath = request.getRawPath();
TimeValue requestTimeout = REQUEST_TIMEOUT.get(settings);
String action = rawPath.endsWith(RestHandlerUtils.START_JOB) ? "start" : "stop";
ActionListener<AnomalyDetectorJobResponse> listener = wrapRestActionListener(actionListener, "Failed to " + action + " detector");
String errorMessage = rawPath.endsWith(RestHandlerUtils.START_JOB) ? FAIL_TO_START_DETECTOR : FAIL_TO_STOP_DETECTOR;
ActionListener<AnomalyDetectorJobResponse> listener = wrapRestActionListener(actionListener, errorMessage);

// By the time request reaches here, the user permissions are validated by Security plugin.
User user = getUserContext(client);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

package org.opensearch.ad.transport;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_DELETE_DETECTOR;
import static org.opensearch.ad.model.ADTaskType.HISTORICAL_DETECTOR_TASK_TYPES;
import static org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES;
Expand Down Expand Up @@ -103,7 +104,7 @@ protected void doExecute(Task task, DeleteAnomalyDetectorRequest request, Action
String detectorId = request.getDetectorID();
LOG.info("Delete anomaly detector job {}", detectorId);
User user = getUserContext(client);
ActionListener<DeleteResponse> listener = wrapRestActionListener(actionListener, "Failed to delete detector");
ActionListener<DeleteResponse> listener = wrapRestActionListener(actionListener, FAIL_TO_DELETE_DETECTOR);
// By the time request reaches here, the user permissions are validated by Security plugin.
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
resolveUserAndExecute(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

package org.opensearch.ad.transport;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_DELETE_AD_RESULT;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES;
import static org.opensearch.ad.util.ParseUtils.addUserBackendRolesFilter;
import static org.opensearch.ad.util.ParseUtils.getUserContext;
Expand Down Expand Up @@ -55,7 +56,7 @@ public DeleteAnomalyResultsTransportAction(

@Override
protected void doExecute(Task task, DeleteByQueryRequest request, ActionListener<BulkByScrollResponse> actionListener) {
ActionListener<BulkByScrollResponse> listener = wrapRestActionListener(actionListener, "Failed to delete anomaly result");
ActionListener<BulkByScrollResponse> listener = wrapRestActionListener(actionListener, FAIL_TO_DELETE_AD_RESULT);
delete(request, listener);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

package org.opensearch.ad.transport;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG;
import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_GET_DETECTOR;
import static org.opensearch.ad.model.ADTaskType.ALL_DETECTOR_TASK_TYPES;
import static org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX;
import static org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX;
Expand Down Expand Up @@ -144,7 +146,7 @@ public GetAnomalyDetectorTransportAction(
protected void doExecute(Task task, GetAnomalyDetectorRequest request, ActionListener<GetAnomalyDetectorResponse> actionListener) {
String detectorID = request.getDetectorID();
User user = getUserContext(client);
ActionListener<GetAnomalyDetectorResponse> listener = wrapRestActionListener(actionListener, "Failed to get detector");
ActionListener<GetAnomalyDetectorResponse> listener = wrapRestActionListener(actionListener, FAIL_TO_GET_DETECTOR);
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
resolveUserAndExecute(
user,
Expand Down Expand Up @@ -295,10 +297,7 @@ public void onResponse(MultiGetResponse multiGetResponse) {
for (MultiGetItemResponse response : responses) {
if (ANOMALY_DETECTORS_INDEX.equals(response.getIndex())) {
if (response.getResponse() == null || !response.getResponse().isExists()) {
listener
.onFailure(
new OpenSearchStatusException("Can't find detector with id: " + detectorId, RestStatus.NOT_FOUND)
);
listener.onFailure(new OpenSearchStatusException(FAIL_TO_FIND_DETECTOR_MSG + detectorId, RestStatus.NOT_FOUND));
return;
}
id = response.getId();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

package org.opensearch.ad.transport;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_CREATE_DETECTOR;
import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_UPDATE_DETECTOR;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES;
import static org.opensearch.ad.util.ParseUtils.checkFilterByBackendRoles;
import static org.opensearch.ad.util.ParseUtils.getDetector;
Expand Down Expand Up @@ -100,8 +102,8 @@ protected void doExecute(Task task, IndexAnomalyDetectorRequest request, ActionL
User user = getUserContext(client);
String detectorId = request.getDetectorID();
RestRequest.Method method = request.getMethod();
String action = method == RestRequest.Method.PUT ? "update" : "create";
ActionListener<IndexAnomalyDetectorResponse> listener = wrapRestActionListener(actionListener, "Failed to " + action + " detector");
String errorMessage = method == RestRequest.Method.PUT ? FAIL_TO_UPDATE_DETECTOR : FAIL_TO_CREATE_DETECTOR;
ActionListener<IndexAnomalyDetectorResponse> listener = wrapRestActionListener(actionListener, errorMessage);
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
resolveUserAndExecute(user, detectorId, method, listener, (detector) -> adExecute(request, user, detector, context, listener));
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

package org.opensearch.ad.transport;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_PREVIEW_DETECTOR;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_ANOMALY_FEATURES;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_CONCURRENT_PREVIEW;
Expand Down Expand Up @@ -116,7 +117,7 @@ protected void doExecute(
) {
String detectorId = request.getDetectorId();
User user = getUserContext(client);
ActionListener<PreviewAnomalyDetectorResponse> listener = wrapRestActionListener(actionListener, "Failed to preview detector");
ActionListener<PreviewAnomalyDetectorResponse> listener = wrapRestActionListener(actionListener, FAIL_TO_PREVIEW_DETECTOR);
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
resolveUserAndExecute(
user,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

package org.opensearch.ad.transport;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_GET_DETECTOR_INFO;
import static org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX;
import static org.opensearch.ad.util.RestHandlerUtils.wrapRestActionListener;

Expand Down Expand Up @@ -74,7 +75,7 @@ protected void doExecute(
) {
String name = request.getName();
String rawPath = request.getRawPath();
ActionListener<SearchAnomalyDetectorInfoResponse> listener = wrapRestActionListener(actionListener, "Failed to get detector info");
ActionListener<SearchAnomalyDetectorInfoResponse> listener = wrapRestActionListener(actionListener, FAIL_TO_GET_DETECTOR_INFO);
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
SearchRequest searchRequest = new SearchRequest().indices(ANOMALY_DETECTORS_INDEX);
if (rawPath.endsWith(RestHandlerUtils.COUNT)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

package org.opensearch.ad.transport;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_GET_STATS;
import static org.opensearch.ad.util.RestHandlerUtils.wrapRestActionListener;

import java.util.HashMap;
Expand Down Expand Up @@ -83,7 +84,7 @@ public StatsAnomalyDetectorTransportAction(

@Override
protected void doExecute(Task task, ADStatsRequest request, ActionListener<StatsAnomalyDetectorResponse> actionListener) {
ActionListener<StatsAnomalyDetectorResponse> listener = wrapRestActionListener(actionListener, "Failed to get stats");
ActionListener<StatsAnomalyDetectorResponse> listener = wrapRestActionListener(actionListener, FAIL_TO_GET_STATS);
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
getStats(client, listener, request);
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

package org.opensearch.ad.transport;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_STOP_DETECTOR;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
Expand Down Expand Up @@ -87,10 +89,9 @@ protected void doExecute(Task task, ActionRequest actionRequest, ActionListener<
listener.onResponse(new StopDetectorResponse(false));
}));
} catch (Exception e) {
String errorMessage = "Fail to stop detector " + adID;
LOG.error(errorMessage, e);
LOG.error(FAIL_TO_STOP_DETECTOR + " " + adID, e);
Throwable cause = ExceptionsHelper.unwrapCause(e);
listener.onFailure(new InternalFailure(adID, errorMessage, cause));
listener.onFailure(new InternalFailure(adID, FAIL_TO_STOP_DETECTOR, cause));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

package org.opensearch.ad.transport.handler;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_SEARCH;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES;
import static org.opensearch.ad.util.ParseUtils.addUserBackendRolesFilter;
import static org.opensearch.ad.util.ParseUtils.getUserContext;
Expand Down Expand Up @@ -66,7 +67,7 @@ public ADSearchHandler(Settings settings, ClusterService clusterService, Client
*/
public void search(SearchRequest request, ActionListener<SearchResponse> actionListener) {
User user = getUserContext(client);
ActionListener<SearchResponse> listener = wrapRestActionListener(actionListener, "Failed to get stats");
ActionListener<SearchResponse> listener = wrapRestActionListener(actionListener, FAIL_TO_SEARCH);
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
validateRole(request, user, listener);
} catch (Exception e) {
Expand Down
9 changes: 6 additions & 3 deletions src/main/java/org/opensearch/ad/util/ParseUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@

package org.opensearch.ad.util;

import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG;
import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_GET_USER_INFO;
import static org.opensearch.ad.constant.CommonErrorMessages.NO_PERMISSION_TO_ACCESS_DETECTOR;
import static org.opensearch.ad.constant.CommonName.DATE_HISTOGRAM;
import static org.opensearch.ad.constant.CommonName.EPOCH_MILLIS_FORMAT;
import static org.opensearch.ad.constant.CommonName.FEATURE_AGGS;
Expand Down Expand Up @@ -562,13 +565,13 @@ public static void onGetAdResponse(
function.accept(detector);
} else {
logger.debug("User: " + requestUser.getName() + " does not have permissions to access detector: " + detectorId);
listener.onFailure(new AnomalyDetectionException("User does not have permissions to access detector: " + detectorId));
listener.onFailure(new AnomalyDetectionException(NO_PERMISSION_TO_ACCESS_DETECTOR + detectorId));
}
} catch (Exception e) {
listener.onFailure(new AnomalyDetectionException("Unable to get user information from detector " + detectorId));
listener.onFailure(new AnomalyDetectionException(FAIL_TO_GET_USER_INFO + detectorId));
}
} else {
listener.onFailure(new ResourceNotFoundException(detectorId, "AnomalyDetector is not found with id: " + detectorId));
listener.onFailure(new ResourceNotFoundException(detectorId, FAIL_TO_FIND_DETECTOR_MSG + detectorId));
}
}

Expand Down
Loading

0 comments on commit 713eb79

Please sign in to comment.