Search in sources :

Example 16 with AnomalyDetectionException

use of org.opensearch.ad.common.exception.AnomalyDetectionException in project anomaly-detection by opensearch-project.

the class NodeStateTests method testMaintenanceLastColdStartRemoved.

public void testMaintenanceLastColdStartRemoved() {
    when(clock.instant()).thenReturn(Instant.ofEpochMilli(1000));
    state.setException(new AnomalyDetectionException("123", ""));
    when(clock.instant()).thenReturn(Instant.ofEpochSecond(3700));
    assertTrue(state.expired(duration));
}
Also used : AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException)

Example 17 with AnomalyDetectionException

use of org.opensearch.ad.common.exception.AnomalyDetectionException in project anomaly-detection by opensearch-project.

the class PriorityCacheTests method testFailedConcurrentMaintenance.

public void testFailedConcurrentMaintenance() throws InterruptedException {
    setUpConcurrentMaintenance();
    final CountDownLatch scheduleCountDown = new CountDownLatch(1);
    final CountDownLatch scheduledThreadCountDown = new CountDownLatch(1);
    doThrow(NullPointerException.class).when(memoryTracker).releaseMemory(anyLong(), anyBoolean(), any(MemoryTracker.Origin.class));
    doAnswer(invovacation -> {
        scheduleCountDown.await(100, TimeUnit.SECONDS);
        return null;
    }).when(memoryTracker).syncMemoryState(any(MemoryTracker.Origin.class), anyLong(), anyLong());
    AtomicReference<Runnable> runnable = new AtomicReference<Runnable>();
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        runnable.set((Runnable) args[0]);
        scheduleCountDown.countDown();
        return mock(ScheduledCancellable.class);
    }).when(threadPool).schedule(any(), any(), any());
    try {
        // both maintenance call will be blocked until schedule gets called
        new Thread(new FailedCleanRunnable(scheduledThreadCountDown)).start();
        cacheProvider.maintenance();
    } catch (AnomalyDetectionException e) {
        scheduledThreadCountDown.countDown();
    }
    scheduledThreadCountDown.await(100, TimeUnit.SECONDS);
    // first thread finishes and throw exception
    assertTrue(runnable.get() != null);
    try {
        // invoke second thread's runnable object
        runnable.get().run();
    } catch (Exception e2) {
        // runnable will log a line and return. It won't cause any exception.
        assertTrue(false);
        return;
    }
    // we should return here
    return;
}
Also used : AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) LimitExceededException(org.opensearch.ad.common.exception.LimitExceededException) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException)

Example 18 with AnomalyDetectionException

use of org.opensearch.ad.common.exception.AnomalyDetectionException in project anomaly-detection by opensearch-project.

the class AnomalyIndexHandler method save.

// TODO: Upgrade custom result index mapping to latest version?
// It may bring some issue if we upgrade the custom result index mapping while user is using that index
// for other use cases. One easy solution is to tell user only use custom result index for AD plugin.
// For the first release of custom result index, it's not a issue. Will leave this to next phase.
protected void save(T toSave, String detectorId, String indexName) {
    try (XContentBuilder builder = jsonBuilder()) {
        IndexRequest indexRequest = new IndexRequest(indexName).source(toSave.toXContent(builder, RestHandlerUtils.XCONTENT_WITH_TYPE));
        if (fixedDoc) {
            indexRequest.id(detectorId);
        }
        saveIteration(indexRequest, detectorId, savingBackoffPolicy.iterator());
    } catch (Exception e) {
        LOG.error(String.format(Locale.ROOT, "Failed to save %s", indexName), e);
        throw new AnomalyDetectionException(detectorId, String.format(Locale.ROOT, "Cannot save %s", indexName));
    }
}
Also used : AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) IndexRequest(org.opensearch.action.index.IndexRequest) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) EndRunException(org.opensearch.ad.common.exception.EndRunException) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException)

Example 19 with AnomalyDetectionException

use of org.opensearch.ad.common.exception.AnomalyDetectionException in project anomaly-detection by opensearch-project.

the class ParseUtils method onGetAdResponse.

public static void onGetAdResponse(GetResponse response, User requestUser, String detectorId, ActionListener<GetAnomalyDetectorResponse> listener, Consumer<AnomalyDetector> function, NamedXContentRegistry xContentRegistry, boolean filterByBackendRole) {
    if (response.isExists()) {
        try (XContentParser parser = RestHandlerUtils.createXContentParserFromRegistry(xContentRegistry, response.getSourceAsBytesRef())) {
            ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser);
            AnomalyDetector detector = AnomalyDetector.parse(parser);
            User resourceUser = detector.getUser();
            if (!filterByBackendRole || checkUserPermissions(requestUser, resourceUser, detectorId)) {
                function.accept(detector);
            } else {
                logger.debug("User: " + requestUser.getName() + " 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(FAIL_TO_GET_USER_INFO + detectorId));
        }
    } else {
        listener.onFailure(new ResourceNotFoundException(detectorId, FAIL_TO_FIND_DETECTOR_MSG + detectorId));
    }
}
Also used : AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) User(org.opensearch.commons.authuser.User) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) XContentParser(org.opensearch.common.xcontent.XContentParser) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) ParsingException(org.opensearch.common.ParsingException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IOException(java.io.IOException)

Example 20 with AnomalyDetectionException

use of org.opensearch.ad.common.exception.AnomalyDetectionException in project anomaly-detection by opensearch-project.

the class ParseUtils method addUserBackendRolesFilter.

public static SearchSourceBuilder addUserBackendRolesFilter(User user, SearchSourceBuilder searchSourceBuilder) {
    if (user == null) {
        return searchSourceBuilder;
    }
    BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    String userFieldName = "user";
    String userBackendRoleFieldName = "user.backend_roles.keyword";
    List<String> backendRoles = user.getBackendRoles() != null ? user.getBackendRoles() : ImmutableList.of();
    // For normal case, user should have backend roles.
    TermsQueryBuilder userRolesFilterQuery = QueryBuilders.termsQuery(userBackendRoleFieldName, backendRoles);
    NestedQueryBuilder nestedQueryBuilder = new NestedQueryBuilder(userFieldName, userRolesFilterQuery, ScoreMode.None);
    boolQueryBuilder.must(nestedQueryBuilder);
    QueryBuilder query = searchSourceBuilder.query();
    if (query == null) {
        searchSourceBuilder.query(boolQueryBuilder);
    } else if (query instanceof BoolQueryBuilder) {
        ((BoolQueryBuilder) query).filter(boolQueryBuilder);
    } else {
        throw new AnomalyDetectionException("Search API does not support queries other than BoolQuery");
    }
    return searchSourceBuilder;
}
Also used : AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) TermsQueryBuilder(org.opensearch.index.query.TermsQueryBuilder) NestedQueryBuilder(org.opensearch.index.query.NestedQueryBuilder) NestedQueryBuilder(org.opensearch.index.query.NestedQueryBuilder) QueryBuilder(org.opensearch.index.query.QueryBuilder) TermsQueryBuilder(org.opensearch.index.query.TermsQueryBuilder) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) RangeQueryBuilder(org.opensearch.index.query.RangeQueryBuilder) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder)

Aggregations

AnomalyDetectionException (org.opensearch.ad.common.exception.AnomalyDetectionException)28 ActionListener (org.opensearch.action.ActionListener)10 IOException (java.io.IOException)9 Optional (java.util.Optional)8 EndRunException (org.opensearch.ad.common.exception.EndRunException)7 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)7 LogManager (org.apache.logging.log4j.LogManager)6 Logger (org.apache.logging.log4j.Logger)6 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)6 ClusterService (org.opensearch.cluster.service.ClusterService)6 Settings (org.opensearch.common.settings.Settings)6 ArrayList (java.util.ArrayList)5 List (java.util.List)5 ModelManager (org.opensearch.ad.ml.ModelManager)5 Instant (java.time.Instant)4 Map (java.util.Map)4 ThreadedActionListener (org.opensearch.action.support.ThreadedActionListener)4 LimitExceededException (org.opensearch.ad.common.exception.LimitExceededException)4 ResourceNotFoundException (org.opensearch.ad.common.exception.ResourceNotFoundException)4 Entity (org.opensearch.ad.model.Entity)4