Search in sources :

Example 1 with EntityProfile

use of org.opensearch.ad.model.EntityProfile in project anomaly-detection by opensearch-project.

the class EntityProfileRunner method validateEntity.

/**
 * Verify if the input entity exists or not in case of typos.
 *
 * If a user deletes the entity after job start, then we will not be able to
 * get this entity in the index. For this case, we will not return a profile
 * for this entity even if it's running on some data node. the entity's model
 * will be deleted by another entity or by maintenance due to long inactivity.
 *
 * @param entity Entity accessor
 * @param categoryFields category fields defined for a detector
 * @param detectorId Detector Id
 * @param profilesToCollect Profile to collect from the input
 * @param detector Detector config accessor
 * @param listener Callback to send responses.
 */
private void validateEntity(Entity entity, List<String> categoryFields, String detectorId, Set<EntityProfileName> profilesToCollect, AnomalyDetector detector, ActionListener<EntityProfile> listener) {
    Map<String, String> attributes = entity.getAttributes();
    if (attributes == null || attributes.size() != categoryFields.size()) {
        listener.onFailure(new IllegalArgumentException(EMPTY_ENTITY_ATTRIBUTES));
        return;
    }
    for (String field : categoryFields) {
        if (false == attributes.containsKey(field)) {
            listener.onFailure(new IllegalArgumentException("Cannot find " + field));
            return;
        }
    }
    BoolQueryBuilder internalFilterQuery = QueryBuilders.boolQuery().filter(detector.getFilterQuery());
    for (TermQueryBuilder term : entity.getTermQueryBuilders()) {
        internalFilterQuery.filter(term);
    }
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(internalFilterQuery).size(1);
    SearchRequest searchRequest = new SearchRequest(detector.getIndices().toArray(new String[0]), searchSourceBuilder).preference(Preference.LOCAL.toString());
    client.search(searchRequest, ActionListener.wrap(searchResponse -> {
        try {
            if (searchResponse.getHits().getHits().length == 0) {
                listener.onFailure(new IllegalArgumentException(NO_ENTITY));
                return;
            }
            prepareEntityProfile(listener, detectorId, entity, profilesToCollect, detector, categoryFields.get(0));
        } catch (Exception e) {
            listener.onFailure(new IllegalArgumentException(NO_ENTITY));
            return;
        }
    }, e -> listener.onFailure(new IllegalArgumentException(NO_ENTITY))));
}
Also used : EntityProfileRequest(org.opensearch.ad.transport.EntityProfileRequest) EntityProfileName(org.opensearch.ad.model.EntityProfileName) XContentParser(org.opensearch.common.xcontent.XContentParser) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) EntityProfileResponse(org.opensearch.ad.transport.EntityProfileResponse) Map(java.util.Map) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SearchRequest(org.opensearch.action.search.SearchRequest) ActionListener(org.opensearch.action.ActionListener) EntityProfile(org.opensearch.ad.model.EntityProfile) NestedQueryBuilder(org.opensearch.index.query.NestedQueryBuilder) QueryBuilders(org.opensearch.index.query.QueryBuilders) Client(org.opensearch.client.Client) CommonName(org.opensearch.ad.constant.CommonName) NumericSetting(org.opensearch.ad.settings.NumericSetting) Preference(org.opensearch.cluster.routing.Preference) InitProgressProfile(org.opensearch.ad.model.InitProgressProfile) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ANOMALY_DETECTORS_INDEX(org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX) GetRequest(org.opensearch.action.get.GetRequest) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Set(java.util.Set) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) ScoreMode(org.apache.lucene.search.join.ScoreMode) MultiResponsesDelegateActionListener(org.opensearch.ad.util.MultiResponsesDelegateActionListener) AggregationBuilders(org.opensearch.search.aggregations.AggregationBuilders) List(java.util.List) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) Logger(org.apache.logging.log4j.Logger) AnomalyResult(org.opensearch.ad.model.AnomalyResult) Entity(org.opensearch.ad.model.Entity) EntityState(org.opensearch.ad.model.EntityState) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) Optional(java.util.Optional) XContentType(org.opensearch.common.xcontent.XContentType) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) LogManager(org.apache.logging.log4j.LogManager) EntityProfileAction(org.opensearch.ad.transport.EntityProfileAction) ParseUtils(org.opensearch.ad.util.ParseUtils) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) SearchRequest(org.opensearch.action.search.SearchRequest) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder)

Example 2 with EntityProfile

use of org.opensearch.ad.model.EntityProfile in project anomaly-detection by opensearch-project.

the class EntityProfileRunner method prepareEntityProfile.

private void prepareEntityProfile(ActionListener<EntityProfile> listener, String detectorId, Entity entityValue, Set<EntityProfileName> profilesToCollect, AnomalyDetector detector, String categoryField) {
    EntityProfileRequest request = new EntityProfileRequest(detectorId, entityValue, profilesToCollect);
    client.execute(EntityProfileAction.INSTANCE, request, ActionListener.wrap(r -> getJob(detectorId, entityValue, profilesToCollect, detector, r, listener), listener::onFailure));
}
Also used : EntityProfileRequest(org.opensearch.ad.transport.EntityProfileRequest) EntityProfileName(org.opensearch.ad.model.EntityProfileName) XContentParser(org.opensearch.common.xcontent.XContentParser) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) EntityProfileResponse(org.opensearch.ad.transport.EntityProfileResponse) Map(java.util.Map) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SearchRequest(org.opensearch.action.search.SearchRequest) ActionListener(org.opensearch.action.ActionListener) EntityProfile(org.opensearch.ad.model.EntityProfile) NestedQueryBuilder(org.opensearch.index.query.NestedQueryBuilder) QueryBuilders(org.opensearch.index.query.QueryBuilders) Client(org.opensearch.client.Client) CommonName(org.opensearch.ad.constant.CommonName) NumericSetting(org.opensearch.ad.settings.NumericSetting) Preference(org.opensearch.cluster.routing.Preference) InitProgressProfile(org.opensearch.ad.model.InitProgressProfile) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ANOMALY_DETECTORS_INDEX(org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX) GetRequest(org.opensearch.action.get.GetRequest) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Set(java.util.Set) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) ScoreMode(org.apache.lucene.search.join.ScoreMode) MultiResponsesDelegateActionListener(org.opensearch.ad.util.MultiResponsesDelegateActionListener) AggregationBuilders(org.opensearch.search.aggregations.AggregationBuilders) List(java.util.List) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) Logger(org.apache.logging.log4j.Logger) AnomalyResult(org.opensearch.ad.model.AnomalyResult) Entity(org.opensearch.ad.model.Entity) EntityState(org.opensearch.ad.model.EntityState) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) Optional(java.util.Optional) XContentType(org.opensearch.common.xcontent.XContentType) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) LogManager(org.apache.logging.log4j.LogManager) EntityProfileAction(org.opensearch.ad.transport.EntityProfileAction) ParseUtils(org.opensearch.ad.util.ParseUtils) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) EntityProfileRequest(org.opensearch.ad.transport.EntityProfileRequest)

Example 3 with EntityProfile

use of org.opensearch.ad.model.EntityProfile in project anomaly-detection by opensearch-project.

the class EntityProfileRunner method sendRunningState.

private void sendRunningState(Set<EntityProfileName> profilesToCollect, Entity entityValue, MultiResponsesDelegateActionListener<EntityProfile> delegateListener) {
    EntityProfile.Builder builder = new EntityProfile.Builder();
    if (profilesToCollect.contains(EntityProfileName.STATE)) {
        builder.state(EntityState.RUNNING);
    }
    if (profilesToCollect.contains(EntityProfileName.INIT_PROGRESS)) {
        InitProgressProfile initProgress = new InitProgressProfile("100%", 0, 0);
        builder.initProgress(initProgress);
    }
    delegateListener.onResponse(builder.build());
}
Also used : NestedQueryBuilder(org.opensearch.index.query.NestedQueryBuilder) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) InitProgressProfile(org.opensearch.ad.model.InitProgressProfile) EntityProfile(org.opensearch.ad.model.EntityProfile)

Example 4 with EntityProfile

use of org.opensearch.ad.model.EntityProfile in project anomaly-detection by opensearch-project.

the class EntityProfileRunnerTests method testJobIndexNotFound.

@SuppressWarnings("unchecked")
public void testJobIndexNotFound() throws InterruptedException {
    setUpExecuteEntityProfileAction(InittedEverResultStatus.INITTED);
    final CountDownLatch inProgressLatch = new CountDownLatch(1);
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        GetRequest request = (GetRequest) args[0];
        ActionListener<GetResponse> listener = (ActionListener<GetResponse>) args[1];
        String indexName = request.index();
        if (indexName.equals(ANOMALY_DETECTORS_INDEX)) {
            listener.onResponse(TestHelpers.createGetResponse(detector, detector.getDetectorId(), AnomalyDetector.ANOMALY_DETECTORS_INDEX));
        } else if (indexName.equals(ANOMALY_DETECTOR_JOB_INDEX)) {
            listener.onFailure(new IndexNotFoundException(ANOMALY_DETECTOR_JOB_INDEX));
        }
        return null;
    }).when(client).get(any(), any());
    EntityProfile expectedProfile = new EntityProfile.Builder().build();
    runner.profile(detectorId, entity, initNInfo, ActionListener.wrap(response -> {
        assertEquals(expectedProfile, response);
        inProgressLatch.countDown();
    }, exception -> {
        LOG.error("Unexpected error", exception);
        assertTrue("Should not reach here", false);
        inProgressLatch.countDown();
    }));
    assertTrue(inProgressLatch.await(100, TimeUnit.SECONDS));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Arrays(java.util.Arrays) ModelProfile(org.opensearch.ad.model.ModelProfile) DocValueFormat(org.opensearch.search.DocValueFormat) SearchHits(org.opensearch.search.SearchHits) EntityProfileName(org.opensearch.ad.model.EntityProfileName) ModelProfileOnNode(org.opensearch.ad.model.ModelProfileOnNode) HashSet(java.util.HashSet) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) EntityProfileResponse(org.opensearch.ad.transport.EntityProfileResponse) Mockito.doAnswer(org.mockito.Mockito.doAnswer) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) SearchRequest(org.opensearch.action.search.SearchRequest) ActionListener(org.opensearch.action.ActionListener) SearchResponse(org.opensearch.action.search.SearchResponse) GetResponse(org.opensearch.action.get.GetResponse) EntityProfile(org.opensearch.ad.model.EntityProfile) Collections.emptyMap(java.util.Collections.emptyMap) Client(org.opensearch.client.Client) CommonName(org.opensearch.ad.constant.CommonName) InitProgressProfile(org.opensearch.ad.model.InitProgressProfile) SearchHit(org.opensearch.search.SearchHit) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ANOMALY_DETECTORS_INDEX(org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX) GetRequest(org.opensearch.action.get.GetRequest) Set(java.util.Set) IOException(java.io.IOException) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) TimeUnit(java.util.concurrent.TimeUnit) TotalHits(org.apache.lucene.search.TotalHits) CountDownLatch(java.util.concurrent.CountDownLatch) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) ChronoUnit(java.time.temporal.ChronoUnit) Entity(org.opensearch.ad.model.Entity) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) EntityState(org.opensearch.ad.model.EntityState) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) Collections(java.util.Collections) EntityProfileAction(org.opensearch.ad.transport.EntityProfileAction) Text(org.opensearch.common.text.Text) Mockito.mock(org.mockito.Mockito.mock) ActionListener(org.opensearch.action.ActionListener) GetRequest(org.opensearch.action.get.GetRequest) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) EntityProfile(org.opensearch.ad.model.EntityProfile) CountDownLatch(java.util.concurrent.CountDownLatch) GetResponse(org.opensearch.action.get.GetResponse)

Example 5 with EntityProfile

use of org.opensearch.ad.model.EntityProfile in project anomaly-detection by opensearch-project.

the class GetAnomalyDetectorTransportActionTests method testGetAnomalyDetectorProfileResponse.

@SuppressWarnings("unchecked")
@Test
public void testGetAnomalyDetectorProfileResponse() throws IOException {
    BytesStreamOutput out = new BytesStreamOutput();
    AnomalyDetector detector = TestHelpers.randomAnomalyDetector(ImmutableMap.of("testKey", "testValue"), Instant.now());
    AnomalyDetectorJob adJob = TestHelpers.randomAnomalyDetectorJob();
    InitProgressProfile initProgress = new InitProgressProfile("99%", 2L, 2);
    EntityProfile entityProfile = new EntityProfile.Builder().initProgress(initProgress).build();
    GetAnomalyDetectorResponse response = new GetAnomalyDetectorResponse(4321, "1234", 5678, 9867, detector, adJob, false, mock(ADTask.class), mock(ADTask.class), false, RestStatus.OK, null, entityProfile, true);
    response.writeTo(out);
    NamedWriteableAwareStreamInput input = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), writableRegistry());
    GetAnomalyDetectorResponse newResponse = new GetAnomalyDetectorResponse(input);
    XContentBuilder builder = TestHelpers.builder();
    Assert.assertNotNull(newResponse.toXContent(builder, ToXContent.EMPTY_PARAMS));
    // {init_progress={percentage=99%, estimated_minutes_left=2, needed_shingles=2}}
    Map<String, Object> map = TestHelpers.XContentBuilderToMap(builder);
    Map<String, Object> parsedInitProgress = (Map<String, Object>) (map.get(CommonName.INIT_PROGRESS));
    Assert.assertEquals(initProgress.getPercentage(), parsedInitProgress.get(InitProgressProfile.PERCENTAGE).toString());
    assertTrue(initProgress.toString().contains("[percentage=99%,estimated_minutes_left=2,needed_shingles=2]"));
    Assert.assertEquals(String.valueOf(initProgress.getEstimatedMinutesLeft()), parsedInitProgress.get(InitProgressProfile.ESTIMATED_MINUTES_LEFT).toString());
    Assert.assertEquals(String.valueOf(initProgress.getNeededDataPoints()), parsedInitProgress.get(InitProgressProfile.NEEDED_SHINGLES).toString());
}
Also used : XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) InitProgressProfile(org.opensearch.ad.model.InitProgressProfile) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) BytesStreamOutput(org.opensearch.common.io.stream.BytesStreamOutput) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ADTask(org.opensearch.ad.model.ADTask) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) EntityProfile(org.opensearch.ad.model.EntityProfile) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) Test(org.junit.Test)

Aggregations

EntityProfile (org.opensearch.ad.model.EntityProfile)8 InitProgressProfile (org.opensearch.ad.model.InitProgressProfile)8 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)6 AnomalyDetectorJob (org.opensearch.ad.model.AnomalyDetectorJob)6 BoolQueryBuilder (org.opensearch.index.query.BoolQueryBuilder)6 NestedQueryBuilder (org.opensearch.index.query.NestedQueryBuilder)6 TermQueryBuilder (org.opensearch.index.query.TermQueryBuilder)6 SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)6 Map (java.util.Map)5 Set (java.util.Set)5 ActionListener (org.opensearch.action.ActionListener)5 GetRequest (org.opensearch.action.get.GetRequest)5 SearchRequest (org.opensearch.action.search.SearchRequest)5 CommonErrorMessages (org.opensearch.ad.constant.CommonErrorMessages)5 CommonName (org.opensearch.ad.constant.CommonName)5 ANOMALY_DETECTORS_INDEX (org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX)5 ANOMALY_DETECTOR_JOB_INDEX (org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX)5 Entity (org.opensearch.ad.model.Entity)5 EntityProfileName (org.opensearch.ad.model.EntityProfileName)5 EntityState (org.opensearch.ad.model.EntityState)5