Search in sources :

Example 26 with Client

use of org.opensearch.client.Client in project anomaly-detection by opensearch-project.

the class ParseUtils method getDetector.

/**
 * If filterByEnabled is true, get detector and check if the user has permissions to access the detector,
 * then execute function; otherwise, get detector and execute function
 * @param requestUser user from request
 * @param detectorId detector id
 * @param listener action listener
 * @param function consumer function
 * @param client client
 * @param clusterService cluster service
 * @param xContentRegistry XContent registry
 * @param filterByBackendRole filter by backend role or not
 */
public static void getDetector(User requestUser, String detectorId, ActionListener listener, Consumer<AnomalyDetector> function, Client client, ClusterService clusterService, NamedXContentRegistry xContentRegistry, boolean filterByBackendRole) {
    if (clusterService.state().metadata().indices().containsKey(AnomalyDetector.ANOMALY_DETECTORS_INDEX)) {
        GetRequest request = new GetRequest(AnomalyDetector.ANOMALY_DETECTORS_INDEX).id(detectorId);
        client.get(request, ActionListener.wrap(response -> onGetAdResponse(response, requestUser, detectorId, listener, function, xContentRegistry, filterByBackendRole), exception -> {
            logger.error("Failed to get anomaly detector: " + detectorId, exception);
            listener.onFailure(exception);
        }));
    } else {
        listener.onFailure(new IndexNotFoundException(AnomalyDetector.ANOMALY_DETECTORS_INDEX));
    }
}
Also used : Max(org.opensearch.search.aggregations.metrics.Max) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) BaseAggregationBuilder(org.opensearch.search.aggregations.BaseAggregationBuilder) FAIL_TO_GET_USER_INFO(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_GET_USER_INFO) FAIL_TO_FIND_DETECTOR_MSG(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG) PipelineAggregationBuilder(org.opensearch.search.aggregations.PipelineAggregationBuilder) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) XContentParser(org.opensearch.common.xcontent.XContentParser) AggregationBuilder(org.opensearch.search.aggregations.AggregationBuilder) Matcher(java.util.regex.Matcher) DateHistogramValuesSourceBuilder(org.opensearch.search.aggregations.bucket.composite.DateHistogramValuesSourceBuilder) Map(java.util.Map) ActionListener(org.opensearch.action.ActionListener) DateRangeAggregationBuilder(org.opensearch.search.aggregations.bucket.range.DateRangeAggregationBuilder) GetResponse(org.opensearch.action.get.GetResponse) ParsingException(org.opensearch.common.ParsingException) NestedQueryBuilder(org.opensearch.index.query.NestedQueryBuilder) Client(org.opensearch.client.Client) Collection(java.util.Collection) Feature(org.opensearch.ad.model.Feature) QUERY_PARAM_PERIOD_END(org.opensearch.ad.model.AnomalyDetector.QUERY_PARAM_PERIOD_END) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Set(java.util.Set) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) Instant(java.time.Instant) ScoreMode(org.apache.lucene.search.join.ScoreMode) Objects(java.util.Objects) NO_PERMISSION_TO_ACCESS_DETECTOR(org.opensearch.ad.constant.CommonErrorMessages.NO_PERMISSION_TO_ACCESS_DETECTOR) List(java.util.List) Logger(org.apache.logging.log4j.Logger) QueryBuilder(org.opensearch.index.query.QueryBuilder) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) Entry(java.util.Map.Entry) DATE_HISTOGRAM(org.opensearch.ad.constant.CommonName.DATE_HISTOGRAM) Optional(java.util.Optional) TermsQueryBuilder(org.opensearch.index.query.TermsQueryBuilder) FEATURE_AGGS(org.opensearch.ad.constant.CommonName.FEATURE_AGGS) XContentType(org.opensearch.common.xcontent.XContentType) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) ConfigConstants(org.opensearch.commons.ConfigConstants) AggregatorFactories(org.opensearch.search.aggregations.AggregatorFactories) FeatureData(org.opensearch.ad.model.FeatureData) DoubleArrayList(com.carrotsearch.hppc.DoubleArrayList) DateHistogramInterval(org.opensearch.search.aggregations.bucket.histogram.DateHistogramInterval) ArrayList(java.util.ArrayList) CompositeAggregationBuilder(org.opensearch.search.aggregations.bucket.composite.CompositeAggregationBuilder) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) EPOCH_MILLIS_FORMAT(org.opensearch.ad.constant.CommonName.EPOCH_MILLIS_FORMAT) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SearchResponse(org.opensearch.action.search.SearchResponse) MAX_BATCH_TASK_PIECE_SIZE(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_BATCH_TASK_PIECE_SIZE) GetAnomalyDetectorResponse(org.opensearch.ad.transport.GetAnomalyDetectorResponse) QueryBuilders(org.opensearch.index.query.QueryBuilders) CommonName(org.opensearch.ad.constant.CommonName) RangeQueryBuilder(org.opensearch.index.query.RangeQueryBuilder) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) GetRequest(org.opensearch.action.get.GetRequest) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) IOException(java.io.IOException) Consumer(java.util.function.Consumer) CompositeValuesSourceBuilder(org.opensearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder) VALID_AGG_NAME(org.opensearch.search.aggregations.AggregatorFactories.VALID_AGG_NAME) Entity(org.opensearch.ad.model.Entity) AggregationBuilders.dateRange(org.opensearch.search.aggregations.AggregationBuilders.dateRange) User(org.opensearch.commons.authuser.User) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) LogManager(org.apache.logging.log4j.LogManager) QUERY_PARAM_PERIOD_START(org.opensearch.ad.model.AnomalyDetector.QUERY_PARAM_PERIOD_START) GetRequest(org.opensearch.action.get.GetRequest) IndexNotFoundException(org.opensearch.index.IndexNotFoundException)

Example 27 with Client

use of org.opensearch.client.Client in project anomaly-detection by opensearch-project.

the class CheckpointDeleteTests method setUp.

@SuppressWarnings("unchecked")
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    super.setUpLog4jForJUnit(CheckpointDao.class);
    client = mock(Client.class);
    clientUtil = mock(ClientUtil.class);
    gson = null;
    indexUtil = mock(AnomalyDetectionIndices.class);
    detectorId = "123";
    maxCheckpointBytes = 1_000_000;
    RandomCutForestMapper mapper = mock(RandomCutForestMapper.class);
    V1JsonToV2StateConverter converter = mock(V1JsonToV2StateConverter.class);
    objectPool = mock(GenericObjectPool.class);
    int deserializeRCFBufferSize = 512;
    anomalyRate = 0.005;
    checkpointDao = new CheckpointDao(client, clientUtil, CommonName.CHECKPOINT_INDEX_NAME, gson, mapper, converter, ercfMapper, ercfSchema, HybridThresholdingModel.class, indexUtil, maxCheckpointBytes, objectPool, deserializeRCFBufferSize, anomalyRate);
}
Also used : ClientUtil(org.opensearch.ad.util.ClientUtil) ThresholdedRandomCutForestMapper(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestMapper) RandomCutForestMapper(com.amazon.randomcutforest.state.RandomCutForestMapper) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) V1JsonToV2StateConverter(com.amazon.randomcutforest.serialize.json.v1.V1JsonToV2StateConverter) Client(org.opensearch.client.Client) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) Before(org.junit.Before)

Example 28 with Client

use of org.opensearch.client.Client in project anomaly-detection by opensearch-project.

the class EntityColdStarterTests method setUp.

@SuppressWarnings("unchecked")
@Override
public void setUp() throws Exception {
    super.setUp();
    numMinSamples = AnomalyDetectorSettings.NUM_MIN_SAMPLES;
    clock = mock(Clock.class);
    when(clock.instant()).thenReturn(Instant.now());
    threadPool = mock(ThreadPool.class);
    setUpADThreadPool(threadPool);
    settings = Settings.EMPTY;
    Client client = mock(Client.class);
    clientUtil = mock(ClientUtil.class);
    detector = TestHelpers.AnomalyDetectorBuilder.newInstance().setDetectionInterval(new IntervalTimeConfiguration(1, ChronoUnit.MINUTES)).setCategoryFields(ImmutableList.of(randomAlphaOfLength(5))).build();
    job = TestHelpers.randomAnomalyDetectorJob(true, Instant.ofEpochMilli(1602401500000L), null);
    doAnswer(invocation -> {
        GetRequest request = invocation.getArgument(0);
        ActionListener<GetResponse> listener = invocation.getArgument(2);
        if (request.index().equals(AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX)) {
            listener.onResponse(TestHelpers.createGetResponse(job, detectorId, AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX));
        } else {
            listener.onResponse(TestHelpers.createGetResponse(detector, detectorId, AnomalyDetector.ANOMALY_DETECTORS_INDEX));
        }
        return null;
    }).when(clientUtil).asyncRequest(any(GetRequest.class), any(), any(ActionListener.class));
    Set<Setting<?>> nodestateSetting = new HashSet<>(ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
    nodestateSetting.add(MAX_RETRY_FOR_UNRESPONSIVE_NODE);
    nodestateSetting.add(BACKOFF_MINUTES);
    ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, nodestateSetting);
    DiscoveryNode discoveryNode = new DiscoveryNode("node1", OpenSearchTestCase.buildNewFakeTransportAddress(), Collections.emptyMap(), DiscoveryNodeRole.BUILT_IN_ROLES, Version.CURRENT);
    ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool, discoveryNode, clusterSettings);
    stateManager = new NodeStateManager(client, xContentRegistry(), settings, clientUtil, clock, AnomalyDetectorSettings.HOURLY_MAINTENANCE, clusterService);
    SingleFeatureLinearUniformInterpolator singleFeatureLinearUniformInterpolator = new IntegerSensitiveSingleFeatureLinearUniformInterpolator();
    interpolator = new LinearUniformInterpolator(singleFeatureLinearUniformInterpolator);
    searchFeatureDao = mock(SearchFeatureDao.class);
    checkpoint = mock(CheckpointDao.class);
    featureManager = new FeatureManager(searchFeatureDao, interpolator, clock, AnomalyDetectorSettings.MAX_TRAIN_SAMPLE, AnomalyDetectorSettings.MAX_SAMPLE_STRIDE, AnomalyDetectorSettings.TRAIN_SAMPLE_TIME_RANGE_IN_HOURS, AnomalyDetectorSettings.MIN_TRAIN_SAMPLES, AnomalyDetectorSettings.MAX_SHINGLE_PROPORTION_MISSING, AnomalyDetectorSettings.MAX_IMPUTATION_NEIGHBOR_DISTANCE, AnomalyDetectorSettings.PREVIEW_SAMPLE_RATE, AnomalyDetectorSettings.MAX_PREVIEW_SAMPLES, AnomalyDetectorSettings.HOURLY_MAINTENANCE, threadPool, AnomalyDetectorPlugin.AD_THREAD_POOL_NAME);
    checkpointWriteQueue = mock(CheckpointWriteWorker.class);
    rcfSeed = 2051L;
    entityColdStarter = new EntityColdStarter(clock, threadPool, stateManager, AnomalyDetectorSettings.NUM_SAMPLES_PER_TREE, AnomalyDetectorSettings.NUM_TREES, AnomalyDetectorSettings.TIME_DECAY, numMinSamples, AnomalyDetectorSettings.MAX_SAMPLE_STRIDE, AnomalyDetectorSettings.MAX_TRAIN_SAMPLE, interpolator, searchFeatureDao, AnomalyDetectorSettings.THRESHOLD_MIN_PVALUE, featureManager, settings, AnomalyDetectorSettings.HOURLY_MAINTENANCE, checkpointWriteQueue, rcfSeed, AnomalyDetectorSettings.MAX_COLD_START_ROUNDS);
    detectorId = "123";
    modelId = "123_entity_abc";
    entityName = "abc";
    priority = 0.3f;
    entity = Entity.createSingleAttributeEntity("field", entityName);
    released = new AtomicBoolean();
    inProgressLatch = new CountDownLatch(1);
    releaseSemaphore = () -> {
        released.set(true);
        inProgressLatch.countDown();
    };
    listener = ActionListener.wrap(releaseSemaphore);
    modelManager = new ModelManager(mock(CheckpointDao.class), mock(Clock.class), AnomalyDetectorSettings.NUM_TREES, AnomalyDetectorSettings.NUM_SAMPLES_PER_TREE, AnomalyDetectorSettings.TIME_DECAY, AnomalyDetectorSettings.NUM_MIN_SAMPLES, AnomalyDetectorSettings.THRESHOLD_MIN_PVALUE, AnomalyDetectorSettings.MIN_PREVIEW_SIZE, AnomalyDetectorSettings.HOURLY_MAINTENANCE, AnomalyDetectorSettings.HOURLY_MAINTENANCE, entityColdStarter, mock(FeatureManager.class), mock(MemoryTracker.class));
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ClusterSettings(org.opensearch.common.settings.ClusterSettings) ClientUtil(org.opensearch.ad.util.ClientUtil) ThreadPool(org.opensearch.threadpool.ThreadPool) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) SearchFeatureDao(org.opensearch.ad.feature.SearchFeatureDao) Clock(java.time.Clock) NodeStateManager(org.opensearch.ad.NodeStateManager) IntegerSensitiveSingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.IntegerSensitiveSingleFeatureLinearUniformInterpolator) GetRequest(org.opensearch.action.get.GetRequest) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) IntegerSensitiveSingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.IntegerSensitiveSingleFeatureLinearUniformInterpolator) LinearUniformInterpolator(org.opensearch.ad.dataprocessor.LinearUniformInterpolator) Client(org.opensearch.client.Client) FeatureManager(org.opensearch.ad.feature.FeatureManager) HashSet(java.util.HashSet) Setting(org.opensearch.common.settings.Setting) CountDownLatch(java.util.concurrent.CountDownLatch) GetResponse(org.opensearch.action.get.GetResponse) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) IntegerSensitiveSingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.IntegerSensitiveSingleFeatureLinearUniformInterpolator) CheckpointWriteWorker(org.opensearch.ad.ratelimit.CheckpointWriteWorker) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClusterService(org.opensearch.cluster.service.ClusterService) ActionListener(org.opensearch.action.ActionListener)

Example 29 with Client

use of org.opensearch.client.Client in project anomaly-detection by opensearch-project.

the class MultiEntityResultTests method testNullFeatures.

public void testNullFeatures() throws InterruptedException {
    final CountDownLatch inProgressLatch = new CountDownLatch(1);
    CompositeAggregation emptyComposite = mock(CompositeAggregation.class);
    when(emptyComposite.getName()).thenReturn(null);
    when(emptyComposite.afterKey()).thenReturn(null);
    // empty bucket
    when(emptyComposite.getBuckets()).thenAnswer((Answer<List<CompositeAggregation.Bucket>>) invocation -> {
        return new ArrayList<CompositeAggregation.Bucket>();
    });
    Aggregations emptyAggs = new Aggregations(Collections.singletonList(emptyComposite));
    SearchResponseSections emptySections = new SearchResponseSections(SearchHits.empty(), emptyAggs, null, false, null, null, 1);
    SearchResponse nullResponse = new SearchResponse(emptySections, null, 1, 1, 0, 0, ShardSearchFailure.EMPTY_ARRAY, Clusters.EMPTY);
    doAnswer(invocation -> {
        ActionListener<SearchResponse> listener = invocation.getArgument(1);
        listener.onResponse(nullResponse);
        inProgressLatch.countDown();
        return null;
    }).when(client).search(any(), any());
    PlainActionFuture<AnomalyResultResponse> listener = new PlainActionFuture<>();
    action.doExecute(null, request, listener);
    AnomalyResultResponse response = listener.actionGet(10000L);
    assertEquals(Double.NaN, response.getAnomalyGrade(), 0.01);
    assertTrue(inProgressLatch.await(10000L, TimeUnit.MILLISECONDS));
    PlainActionFuture<AnomalyResultResponse> listener2 = new PlainActionFuture<>();
    action.doExecute(null, request, listener2);
    AnomalyResultResponse response2 = listener2.actionGet(10000L);
    assertEquals(Double.NaN, response2.getAnomalyGrade(), 0.01);
}
Also used : Arrays(java.util.Arrays) ModelManager(org.opensearch.ad.ml.ModelManager) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) HashRing(org.opensearch.ad.cluster.HashRing) ThresholdingResult(org.opensearch.ad.ml.ThresholdingResult) TransportInterceptor(org.opensearch.transport.TransportInterceptor) AbstractADTest(org.opensearch.ad.AbstractADTest) Version(org.opensearch.Version) LimitExceededException(org.opensearch.ad.common.exception.LimitExceededException) Transport(org.opensearch.transport.Transport) Pair(org.apache.commons.lang3.tuple.Pair) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) ActionListener(org.opensearch.action.ActionListener) Bwc(org.opensearch.ad.util.Bwc) BACKOFF_MINUTES(org.opensearch.ad.settings.AnomalyDetectorSettings.BACKOFF_MINUTES) AfterClass(org.junit.AfterClass) Client(org.opensearch.client.Client) TimeValue(org.opensearch.common.unit.TimeValue) Clusters(org.opensearch.action.search.SearchResponse.Clusters) MAX_RETRY_FOR_UNRESPONSIVE_NODE(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_RETRY_FOR_UNRESPONSIVE_NODE) TransportRequestOptions(org.opensearch.transport.TransportRequestOptions) Set(java.util.Set) ADTaskManager(org.opensearch.ad.task.ADTaskManager) Settings(org.opensearch.common.settings.Settings) DiscoveryNodeRole(org.opensearch.cluster.node.DiscoveryNodeRole) TransportService(org.opensearch.transport.TransportService) ColdEntityWorker(org.opensearch.ad.ratelimit.ColdEntityWorker) CountDownLatch(java.util.concurrent.CountDownLatch) ActionFilters(org.opensearch.action.support.ActionFilters) Matchers.argThat(org.mockito.Matchers.argThat) NodeStateManager(org.opensearch.ad.NodeStateManager) TestHelpers(org.opensearch.ad.TestHelpers) MLUtil(test.org.opensearch.ad.util.MLUtil) OpenSearchTimeoutException(org.opensearch.OpenSearchTimeoutException) Matchers.containsString(org.hamcrest.Matchers.containsString) TransportException(org.opensearch.transport.TransportException) Mockito.mock(org.mockito.Mockito.mock) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) ADCircuitBreakerService(org.opensearch.ad.breaker.ADCircuitBreakerService) ThreadPool(org.opensearch.threadpool.ThreadPool) Aggregations(org.opensearch.search.aggregations.Aggregations) SearchHits(org.opensearch.search.SearchHits) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) ArrayList(java.util.ArrayList) Answer(org.mockito.stubbing.Answer) PAGE_SIZE(org.opensearch.ad.settings.AnomalyDetectorSettings.PAGE_SIZE) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) Before(org.junit.Before) EntityFeatureRequest(org.opensearch.ad.ratelimit.EntityFeatureRequest) InternalFailure(org.opensearch.ad.common.exception.InternalFailure) CounterSupplier(org.opensearch.ad.stats.suppliers.CounterSupplier) FeatureManager(org.opensearch.ad.feature.FeatureManager) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) ADStat(org.opensearch.ad.stats.ADStat) CheckpointReadWorker(org.opensearch.ad.ratelimit.CheckpointReadWorker) BwcTests(org.opensearch.BwcTests) CompositeRetriever(org.opensearch.ad.feature.CompositeRetriever) Mockito.never(org.mockito.Mockito.never) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) ChronoUnit(java.time.temporal.ChronoUnit) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) ClusterService(org.opensearch.cluster.service.ClusterService) SearchPhaseExecutionException(org.opensearch.action.search.SearchPhaseExecutionException) StatNames(org.opensearch.ad.stats.StatNames) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) InternalMin(org.opensearch.search.aggregations.metrics.InternalMin) Aggregation(org.opensearch.search.aggregations.Aggregation) ADStats(org.opensearch.ad.stats.ADStats) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) ArgumentMatcher(org.mockito.ArgumentMatcher) ResultWriteWorker(org.opensearch.ad.ratelimit.ResultWriteWorker) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) After(org.junit.After) RandomModelStateConfig(test.org.opensearch.ad.util.RandomModelStateConfig) GetResponse(org.opensearch.action.get.GetResponse) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) TransportResponse(org.opensearch.transport.TransportResponse) Instant(java.time.Instant) List(java.util.List) Optional(java.util.Optional) ClusterServiceUtils(org.opensearch.test.ClusterServiceUtils) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) MAX_ENTITIES_PER_QUERY(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_ENTITIES_PER_QUERY) CacheProvider(org.opensearch.ad.caching.CacheProvider) BeforeClass(org.junit.BeforeClass) DocValueFormat(org.opensearch.search.DocValueFormat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Function(java.util.function.Function) HashSet(java.util.HashSet) ArgumentCaptor(org.mockito.ArgumentCaptor) ImmutableList(com.google.common.collect.ImmutableList) EntityCache(org.opensearch.ad.caching.EntityCache) SearchResponse(org.opensearch.action.search.SearchResponse) ClusterSettings(org.opensearch.common.settings.ClusterSettings) NoSuchElementException(java.util.NoSuchElementException) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) EndRunException(org.opensearch.ad.common.exception.EndRunException) StreamInput(org.opensearch.common.io.stream.StreamInput) Setting(org.opensearch.common.settings.Setting) ClientUtil(org.opensearch.ad.util.ClientUtil) TransportRequest(org.opensearch.transport.TransportRequest) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) GetRequest(org.opensearch.action.get.GetRequest) TransportResponseHandler(org.opensearch.transport.TransportResponseHandler) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) Mockito.when(org.mockito.Mockito.when) CompositeAggregation(org.opensearch.search.aggregations.bucket.composite.CompositeAggregation) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) Entity(org.opensearch.ad.model.Entity) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) Clock(java.time.Clock) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) Collections(java.util.Collections) CompositeAggregation(org.opensearch.search.aggregations.bucket.composite.CompositeAggregation) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) Aggregations(org.opensearch.search.aggregations.Aggregations) CountDownLatch(java.util.concurrent.CountDownLatch) SearchResponse(org.opensearch.action.search.SearchResponse) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList)

Example 30 with Client

use of org.opensearch.client.Client in project anomaly-detection by opensearch-project.

the class DeleteTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    node1 = "node1";
    node2 = "node2";
    nodename1 = "nodename1";
    nodename2 = "nodename2";
    DiscoveryNode discoveryNode1 = new DiscoveryNode(nodename1, node1, new TransportAddress(TransportAddress.META_ADDRESS, 9300), emptyMap(), emptySet(), Version.CURRENT);
    DiscoveryNode discoveryNode2 = new DiscoveryNode(nodename2, node2, new TransportAddress(TransportAddress.META_ADDRESS, 9301), emptyMap(), emptySet(), Version.CURRENT);
    List<DiscoveryNode> discoveryNodes = new ArrayList<DiscoveryNode>(2);
    discoveryNodes.add(discoveryNode1);
    discoveryNodes.add(discoveryNode2);
    DeleteModelNodeResponse nodeResponse1 = new DeleteModelNodeResponse(discoveryNode1);
    DeleteModelNodeResponse nodeResponse2 = new DeleteModelNodeResponse(discoveryNode2);
    deleteModelResponse = new ArrayList<>();
    deleteModelResponse.add(nodeResponse1);
    deleteModelResponse.add(nodeResponse2);
    failures = new ArrayList<>();
    failures.add(new FailedNodeException("node3", "blah", new OpenSearchException("foo")));
    response = new DeleteModelResponse(new ClusterName("Cluster"), deleteModelResponse, failures);
    clusterService = mock(ClusterService.class);
    when(clusterService.localNode()).thenReturn(discoveryNode1);
    when(clusterService.state()).thenReturn(ClusterCreation.state(new ClusterName("test"), discoveryNode2, discoveryNode1, discoveryNodes));
    transportService = mock(TransportService.class);
    threadPool = mock(ThreadPool.class);
    actionFilters = mock(ActionFilters.class);
    Settings settings = Settings.builder().put("plugins.anomaly_detection.request_timeout", TimeValue.timeValueSeconds(10)).build();
    task = mock(Task.class);
    when(task.getId()).thenReturn(1000L);
    client = mock(Client.class);
    when(client.settings()).thenReturn(settings);
    when(client.threadPool()).thenReturn(threadPool);
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) Task(org.opensearch.tasks.Task) TransportAddress(org.opensearch.common.transport.TransportAddress) ArrayList(java.util.ArrayList) ThreadPool(org.opensearch.threadpool.ThreadPool) ActionFilters(org.opensearch.action.support.ActionFilters) ClusterService(org.opensearch.cluster.service.ClusterService) TransportService(org.opensearch.transport.TransportService) ClusterName(org.opensearch.cluster.ClusterName) FailedNodeException(org.opensearch.action.FailedNodeException) OpenSearchException(org.opensearch.OpenSearchException) Client(org.opensearch.client.Client) Settings(org.opensearch.common.settings.Settings) Before(org.junit.Before)

Aggregations

Client (org.opensearch.client.Client)324 Settings (org.opensearch.common.settings.Settings)130 Test (org.junit.Test)90 IndexRequest (org.opensearch.action.index.IndexRequest)86 RestHelper (org.opensearch.security.test.helper.rest.RestHelper)69 ClusterService (org.opensearch.cluster.service.ClusterService)65 ArrayList (java.util.ArrayList)60 ActionListener (org.opensearch.action.ActionListener)59 SingleClusterTest (org.opensearch.security.test.SingleClusterTest)57 HttpResponse (org.opensearch.security.test.helper.rest.RestHelper.HttpResponse)57 List (java.util.List)53 Matchers.containsString (org.hamcrest.Matchers.containsString)51 SearchResponse (org.opensearch.action.search.SearchResponse)49 IOException (java.io.IOException)48 Map (java.util.Map)48 ThreadPool (org.opensearch.threadpool.ThreadPool)48 CreateIndexRequest (org.opensearch.action.admin.indices.create.CreateIndexRequest)46 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)43 HashSet (java.util.HashSet)39 GetResponse (org.opensearch.action.get.GetResponse)38