Search in sources :

Example 41 with ClusterService

use of org.opensearch.cluster.service.ClusterService in project anomaly-detection by opensearch-project.

the class PriorityCacheTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    checkpoint = mock(CheckpointDao.class);
    modelManager = mock(ModelManager.class);
    clusterService = mock(ClusterService.class);
    ClusterSettings settings = new ClusterSettings(Settings.EMPTY, Collections.unmodifiableSet(new HashSet<>(Arrays.asList(AnomalyDetectorSettings.DEDICATED_CACHE_SIZE, AnomalyDetectorSettings.MODEL_MAX_SIZE_PERCENTAGE, AnomalyDetectorSettings.MODEL_MAX_SIZE_PERCENTAGE))));
    when(clusterService.getClusterSettings()).thenReturn(settings);
    dedicatedCacheSize = 1;
    threadPool = mock(ThreadPool.class);
    setUpADThreadPool(threadPool);
    EntityCache cache = new PriorityCache(checkpoint, dedicatedCacheSize, AnomalyDetectorSettings.CHECKPOINT_TTL, AnomalyDetectorSettings.MAX_INACTIVE_ENTITIES, memoryTracker, AnomalyDetectorSettings.NUM_TREES, clock, clusterService, AnomalyDetectorSettings.HOURLY_MAINTENANCE, threadPool, checkpointWriteQueue, AnomalyDetectorSettings.MAINTENANCE_FREQ_CONSTANT);
    cacheProvider = new CacheProvider(cache).get();
    when(memoryTracker.estimateTRCFModelSize(anyInt(), anyInt(), anyDouble(), anyInt(), anyBoolean())).thenReturn(memoryPerEntity);
    when(memoryTracker.canAllocateReserved(anyLong())).thenReturn(true);
    detector2 = mock(AnomalyDetector.class);
    detectorId2 = "456";
    when(detector2.getDetectorId()).thenReturn(detectorId2);
    when(detector2.getDetectionIntervalDuration()).thenReturn(detectorDuration);
    when(detector2.getDetectorIntervalInSeconds()).thenReturn(detectorDuration.getSeconds());
    point = new double[] { 0.1 };
}
Also used : CheckpointDao(org.opensearch.ad.ml.CheckpointDao) ClusterService(org.opensearch.cluster.service.ClusterService) ClusterSettings(org.opensearch.common.settings.ClusterSettings) ThreadPool(org.opensearch.threadpool.ThreadPool) ModelManager(org.opensearch.ad.ml.ModelManager) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) HashSet(java.util.HashSet) Before(org.junit.Before)

Example 42 with ClusterService

use of org.opensearch.cluster.service.ClusterService in project anomaly-detection by opensearch-project.

the class HourlyCronTests method templateHourlyCron.

@SuppressWarnings("unchecked")
public void templateHourlyCron(HourlyCronTestExecutionMode mode) {
    super.setUpLog4jForJUnit(HourlyCron.class);
    ClusterService clusterService = mock(ClusterService.class);
    ClusterState state = ClusterCreation.state(1);
    when(clusterService.state()).thenReturn(state);
    HashMap<String, String> ignoredAttributes = new HashMap<String, String>();
    ignoredAttributes.put(CommonName.BOX_TYPE_KEY, CommonName.WARM_BOX_TYPE);
    DiscoveryNodeFilterer nodeFilter = new DiscoveryNodeFilterer(clusterService);
    Client client = mock(Client.class);
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        assertTrue(String.format("The size of args is %d.  Its content is %s", args.length, Arrays.toString(args)), args.length == 3);
        assertTrue(args[2] instanceof ActionListener);
        ActionListener<CronResponse> listener = (ActionListener<CronResponse>) args[2];
        if (mode == HourlyCronTestExecutionMode.NODE_FAIL) {
            listener.onResponse(new CronResponse(new ClusterName("test"), Collections.singletonList(new CronNodeResponse(state.nodes().getLocalNode())), Collections.singletonList(new FailedNodeException("foo0", "blah", new OpenSearchException("bar")))));
        } else if (mode == HourlyCronTestExecutionMode.ALL_FAIL) {
            listener.onFailure(new OpenSearchException("bar"));
        } else {
            CronNodeResponse nodeResponse = new CronNodeResponse(state.nodes().getLocalNode());
            BytesStreamOutput nodeResponseOut = new BytesStreamOutput();
            nodeResponseOut.setVersion(Version.CURRENT);
            nodeResponse.writeTo(nodeResponseOut);
            StreamInput siNode = nodeResponseOut.bytes().streamInput();
            CronNodeResponse nodeResponseRead = new CronNodeResponse(siNode);
            CronResponse response = new CronResponse(new ClusterName("test"), Collections.singletonList(nodeResponseRead), Collections.EMPTY_LIST);
            BytesStreamOutput out = new BytesStreamOutput();
            out.setVersion(Version.CURRENT);
            response.writeTo(out);
            StreamInput si = out.bytes().streamInput();
            CronResponse responseRead = new CronResponse(si);
            listener.onResponse(responseRead);
        }
        return null;
    }).when(client).execute(eq(CronAction.INSTANCE), any(), any());
    HourlyCron cron = new HourlyCron(client, nodeFilter);
    cron.run();
    Logger LOG = LogManager.getLogger(HourlyCron.class);
    LOG.info(testAppender.messages);
    if (mode == HourlyCronTestExecutionMode.NODE_FAIL) {
        assertTrue(testAppender.containsMessage(HourlyCron.NODE_EXCEPTION_LOG_MSG));
    } else if (mode == HourlyCronTestExecutionMode.ALL_FAIL) {
        assertTrue(testAppender.containsMessage(HourlyCron.EXCEPTION_LOG_MSG));
    } else {
        assertTrue(testAppender.containsMessage(HourlyCron.SUCCEEDS_LOG_MSG));
    }
    super.tearDownLog4jForJUnit();
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) HashMap(java.util.HashMap) CronResponse(org.opensearch.ad.transport.CronResponse) Logger(org.apache.logging.log4j.Logger) BytesStreamOutput(org.opensearch.common.io.stream.BytesStreamOutput) ClusterService(org.opensearch.cluster.service.ClusterService) ActionListener(org.opensearch.action.ActionListener) CronNodeResponse(org.opensearch.ad.transport.CronNodeResponse) StreamInput(org.opensearch.common.io.stream.StreamInput) ClusterName(org.opensearch.cluster.ClusterName) FailedNodeException(org.opensearch.action.FailedNodeException) OpenSearchException(org.opensearch.OpenSearchException) Client(org.opensearch.client.Client)

Example 43 with ClusterService

use of org.opensearch.cluster.service.ClusterService in project anomaly-detection by opensearch-project.

the class MemoryTrackerTests method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    inputFeatures = 1;
    rcfSampleSize = 256;
    numberOfTrees = 30;
    rcfTimeDecay = 0.2;
    numMinSamples = 128;
    shingleSize = 8;
    dimension = inputFeatures * shingleSize;
    jvmService = mock(JvmService.class);
    JvmInfo info = mock(JvmInfo.class);
    mem = mock(Mem.class);
    // 800 MB is the limit
    largeHeapSize = 800_000_000;
    smallHeapSize = 1_000_000;
    when(jvmService.info()).thenReturn(info);
    when(info.getMem()).thenReturn(mem);
    modelMaxSizePercentage = 0.1;
    modelDesiredSizePercentage = 0.0002;
    clusterService = mock(ClusterService.class);
    modelMaxPercen = 0.1f;
    Settings settings = Settings.builder().put(AnomalyDetectorSettings.MODEL_MAX_SIZE_PERCENTAGE.getKey(), modelMaxPercen).build();
    ClusterSettings clusterSettings = new ClusterSettings(settings, Collections.unmodifiableSet(new HashSet<>(Arrays.asList(AnomalyDetectorSettings.MODEL_MAX_SIZE_PERCENTAGE))));
    when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
    expectedRCFModelSize = 382784;
    detectorId = "123";
    trcf = ThresholdedRandomCutForest.builder().dimensions(dimension).sampleSize(rcfSampleSize).numberOfTrees(numberOfTrees).timeDecay(rcfTimeDecay).outputAfter(numMinSamples).initialAcceptFraction(numMinSamples * 1.0d / rcfSampleSize).parallelExecutionEnabled(false).compact(true).precision(Precision.FLOAT_32).boundingBoxCacheFraction(AnomalyDetectorSettings.REAL_TIME_BOUNDING_BOX_CACHE_RATIO).shingleSize(shingleSize).internalShinglingEnabled(true).build();
    detector = mock(AnomalyDetector.class);
    when(detector.getEnabledFeatureIds()).thenReturn(Collections.singletonList("a"));
    when(detector.getShingleSize()).thenReturn(1);
    circuitBreaker = mock(ADCircuitBreakerService.class);
    when(circuitBreaker.isOpen()).thenReturn(false);
}
Also used : ClusterService(org.opensearch.cluster.service.ClusterService) ClusterSettings(org.opensearch.common.settings.ClusterSettings) ADCircuitBreakerService(org.opensearch.ad.breaker.ADCircuitBreakerService) JvmInfo(org.opensearch.monitor.jvm.JvmInfo) Mem(org.opensearch.monitor.jvm.JvmInfo.Mem) JvmService(org.opensearch.monitor.jvm.JvmService) Settings(org.opensearch.common.settings.Settings) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) ClusterSettings(org.opensearch.common.settings.ClusterSettings) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) HashSet(java.util.HashSet)

Example 44 with ClusterService

use of org.opensearch.cluster.service.ClusterService 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 45 with ClusterService

use of org.opensearch.cluster.service.ClusterService in project anomaly-detection by opensearch-project.

the class IndexAnomalyDetectorActionHandlerTests method setUp.

@SuppressWarnings("unchecked")
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    settings = Settings.EMPTY;
    clusterService = mock(ClusterService.class);
    clientMock = spy(new NodeClient(settings, threadPool));
    transportService = mock(TransportService.class);
    channel = mock(ActionListener.class);
    anomalyDetectionIndices = mock(AnomalyDetectionIndices.class);
    when(anomalyDetectionIndices.doesAnomalyDetectorIndexExist()).thenReturn(true);
    detectorId = "123";
    seqNo = 0L;
    primaryTerm = 0L;
    WriteRequest.RefreshPolicy refreshPolicy = WriteRequest.RefreshPolicy.IMMEDIATE;
    String field = "a";
    detector = TestHelpers.randomAnomalyDetectorUsingCategoryFields(detectorId, Arrays.asList(field));
    requestTimeout = new TimeValue(1000L);
    maxSingleEntityAnomalyDetectors = 1000;
    maxMultiEntityAnomalyDetectors = 10;
    maxAnomalyFeatures = 5;
    method = RestRequest.Method.POST;
    adTaskManager = mock(ADTaskManager.class);
    searchFeatureDao = mock(SearchFeatureDao.class);
    handler = new IndexAnomalyDetectorActionHandler(clusterService, clientMock, transportService, channel, anomalyDetectionIndices, detectorId, seqNo, primaryTerm, refreshPolicy, detector, requestTimeout, maxSingleEntityAnomalyDetectors, maxMultiEntityAnomalyDetectors, maxAnomalyFeatures, method, xContentRegistry(), null, adTaskManager, searchFeatureDao);
}
Also used : NodeClient(org.opensearch.client.node.NodeClient) ClusterService(org.opensearch.cluster.service.ClusterService) ActionListener(org.opensearch.action.ActionListener) TransportService(org.opensearch.transport.TransportService) ADTaskManager(org.opensearch.ad.task.ADTaskManager) WriteRequest(org.opensearch.action.support.WriteRequest) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) IndexAnomalyDetectorActionHandler(org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler) SearchFeatureDao(org.opensearch.ad.feature.SearchFeatureDao) TimeValue(org.opensearch.common.unit.TimeValue) Before(org.junit.Before)

Aggregations

ClusterService (org.opensearch.cluster.service.ClusterService)296 ThreadPool (org.opensearch.threadpool.ThreadPool)123 Settings (org.opensearch.common.settings.Settings)115 ClusterState (org.opensearch.cluster.ClusterState)106 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)103 TestThreadPool (org.opensearch.threadpool.TestThreadPool)93 TransportService (org.opensearch.transport.TransportService)86 ClusterSettings (org.opensearch.common.settings.ClusterSettings)76 ActionListener (org.opensearch.action.ActionListener)75 Before (org.junit.Before)66 ActionFilters (org.opensearch.action.support.ActionFilters)66 CountDownLatch (java.util.concurrent.CountDownLatch)65 HashSet (java.util.HashSet)63 TimeValue (org.opensearch.common.unit.TimeValue)61 IOException (java.io.IOException)56 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)53 OpenSearchTestCase (org.opensearch.test.OpenSearchTestCase)48 Collections (java.util.Collections)47 ClusterName (org.opensearch.cluster.ClusterName)47 Metadata (org.opensearch.cluster.metadata.Metadata)47