Search in sources :

Example 6 with EntityCache

use of org.opensearch.ad.caching.EntityCache in project anomaly-detection by opensearch-project.

the class EntityResultTransportActionTests method setUp.

@SuppressWarnings("unchecked")
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    actionFilters = mock(ActionFilters.class);
    transportService = mock(TransportService.class);
    adCircuitBreakerService = mock(ADCircuitBreakerService.class);
    when(adCircuitBreakerService.isOpen()).thenReturn(false);
    checkpointDao = mock(CheckpointDao.class);
    detectorId = "123";
    entities = new HashMap<>();
    start = 10L;
    end = 20L;
    request = new EntityResultRequest(detectorId, entities, start, end);
    clock = mock(Clock.class);
    now = Instant.now();
    when(clock.instant()).thenReturn(now);
    manager = new ModelManager(null, clock, 0, 0, 0, 0, 0, 0, null, null, mock(EntityColdStarter.class), null, null);
    provider = mock(CacheProvider.class);
    entityCache = mock(EntityCache.class);
    when(provider.get()).thenReturn(entityCache);
    String field = "a";
    detector = TestHelpers.randomAnomalyDetectorUsingCategoryFields(detectorId, Arrays.asList(field));
    stateManager = mock(NodeStateManager.class);
    doAnswer(invocation -> {
        ActionListener<Optional<AnomalyDetector>> listener = invocation.getArgument(1);
        listener.onResponse(Optional.of(detector));
        return null;
    }).when(stateManager).getAnomalyDetector(any(String.class), any(ActionListener.class));
    cacheMissEntity = "0.0.0.1";
    cacheMissData = new double[] { 0.1 };
    cacheHitEntity = "0.0.0.2";
    cacheHitData = new double[] { 0.2 };
    cacheMissEntityObj = Entity.createSingleAttributeEntity(detector.getCategoryField().get(0), cacheMissEntity);
    entities.put(cacheMissEntityObj, cacheMissData);
    cacheHitEntityObj = Entity.createSingleAttributeEntity(detector.getCategoryField().get(0), cacheHitEntity);
    entities.put(cacheHitEntityObj, cacheHitData);
    tooLongEntity = randomAlphaOfLength(AnomalyDetectorSettings.MAX_ENTITY_LENGTH + 1);
    tooLongData = new double[] { 0.3 };
    entities.put(Entity.createSingleAttributeEntity(detector.getCategoryField().get(0), tooLongEntity), tooLongData);
    ModelState<EntityModel> state = MLUtil.randomModelState(new RandomModelStateConfig.Builder().fullModel(true).build());
    when(entityCache.get(eq(cacheMissEntityObj.getModelId(detectorId).get()), any())).thenReturn(null);
    when(entityCache.get(eq(cacheHitEntityObj.getModelId(detectorId).get()), any())).thenReturn(state);
    List<Entity> coldEntities = new ArrayList<>();
    coldEntities.add(cacheMissEntityObj);
    when(entityCache.selectUpdateCandidate(any(), anyString(), any())).thenReturn(Pair.of(new ArrayList<>(), coldEntities));
    settings = Settings.builder().put(AnomalyDetectorSettings.COOLDOWN_MINUTES.getKey(), TimeValue.timeValueMinutes(5)).build();
    AnomalyDetectionIndices indexUtil = mock(AnomalyDetectionIndices.class);
    when(indexUtil.getSchemaVersion(any())).thenReturn(CommonValue.NO_SCHEMA_VERSION);
    resultWriteQueue = mock(ResultWriteWorker.class);
    checkpointReadQueue = mock(CheckpointReadWorker.class);
    minSamples = 1;
    coldStarter = mock(EntityColdStarter.class);
    doAnswer(invocation -> {
        ModelState<EntityModel> modelState = invocation.getArgument(0);
        modelState.getModel().clear();
        return null;
    }).when(coldStarter).trainModelFromExistingSamples(any(), anyInt());
    coldEntityQueue = mock(ColdEntityWorker.class);
    entityResult = new EntityResultTransportAction(actionFilters, transportService, manager, adCircuitBreakerService, provider, stateManager, indexUtil, resultWriteQueue, checkpointReadQueue, coldEntityQueue, threadPool);
    // timeout in 60 seconds
    timeoutMs = 60000L;
}
Also used : Entity(org.opensearch.ad.model.Entity) EntityCache(org.opensearch.ad.caching.EntityCache) ArrayList(java.util.ArrayList) CheckpointReadWorker(org.opensearch.ad.ratelimit.CheckpointReadWorker) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Clock(java.time.Clock) ResultWriteWorker(org.opensearch.ad.ratelimit.ResultWriteWorker) NodeStateManager(org.opensearch.ad.NodeStateManager) RandomModelStateConfig(test.org.opensearch.ad.util.RandomModelStateConfig) EntityColdStarter(org.opensearch.ad.ml.EntityColdStarter) ColdEntityWorker(org.opensearch.ad.ratelimit.ColdEntityWorker) ADCircuitBreakerService(org.opensearch.ad.breaker.ADCircuitBreakerService) Optional(java.util.Optional) EntityModel(org.opensearch.ad.ml.EntityModel) ActionFilters(org.opensearch.action.support.ActionFilters) ModelManager(org.opensearch.ad.ml.ModelManager) CacheProvider(org.opensearch.ad.caching.CacheProvider) CheckpointDao(org.opensearch.ad.ml.CheckpointDao) ActionListener(org.opensearch.action.ActionListener) TransportService(org.opensearch.transport.TransportService) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) Before(org.junit.Before)

Example 7 with EntityCache

use of org.opensearch.ad.caching.EntityCache in project anomaly-detection by opensearch-project.

the class DeleteModelTransportActionTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    ThreadPool threadPool = mock(ThreadPool.class);
    ClusterService clusterService = mock(ClusterService.class);
    localNodeID = "foo";
    when(clusterService.localNode()).thenReturn(new DiscoveryNode(localNodeID, buildNewFakeTransportAddress(), Version.CURRENT));
    when(clusterService.getClusterName()).thenReturn(new ClusterName("test"));
    TransportService transportService = mock(TransportService.class);
    ActionFilters actionFilters = mock(ActionFilters.class);
    NodeStateManager nodeStateManager = mock(NodeStateManager.class);
    ModelManager modelManager = mock(ModelManager.class);
    FeatureManager featureManager = mock(FeatureManager.class);
    CacheProvider cacheProvider = mock(CacheProvider.class);
    EntityCache entityCache = mock(EntityCache.class);
    when(cacheProvider.get()).thenReturn(entityCache);
    ADTaskCacheManager adTaskCacheManager = mock(ADTaskCacheManager.class);
    NodeStateManager stateManager = mock(NodeStateManager.class);
    action = new DeleteModelTransportAction(threadPool, clusterService, transportService, actionFilters, nodeStateManager, modelManager, featureManager, cacheProvider, adTaskCacheManager);
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) EntityCache(org.opensearch.ad.caching.EntityCache) ThreadPool(org.opensearch.threadpool.ThreadPool) ActionFilters(org.opensearch.action.support.ActionFilters) ModelManager(org.opensearch.ad.ml.ModelManager) CacheProvider(org.opensearch.ad.caching.CacheProvider) NodeStateManager(org.opensearch.ad.NodeStateManager) ClusterService(org.opensearch.cluster.service.ClusterService) ADTaskCacheManager(org.opensearch.ad.task.ADTaskCacheManager) TransportService(org.opensearch.transport.TransportService) ClusterName(org.opensearch.cluster.ClusterName) FeatureManager(org.opensearch.ad.feature.FeatureManager) Before(org.junit.Before)

Example 8 with EntityCache

use of org.opensearch.ad.caching.EntityCache in project anomaly-detection by opensearch-project.

the class AnomalyDetectorPlugin method createComponents.

@Override
public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool, ResourceWatcherService resourceWatcherService, ScriptService scriptService, NamedXContentRegistry xContentRegistry, Environment environment, NodeEnvironment nodeEnvironment, NamedWriteableRegistry namedWriteableRegistry, IndexNameExpressionResolver indexNameExpressionResolver, Supplier<RepositoriesService> repositoriesServiceSupplier) {
    EnabledSetting.getInstance().init(clusterService);
    NumericSetting.getInstance().init(clusterService);
    this.client = client;
    this.threadPool = threadPool;
    Settings settings = environment.settings();
    Throttler throttler = new Throttler(getClock());
    this.clientUtil = new ClientUtil(settings, client, throttler, threadPool);
    this.indexUtils = new IndexUtils(client, clientUtil, clusterService, indexNameExpressionResolver);
    this.nodeFilter = new DiscoveryNodeFilterer(clusterService);
    this.anomalyDetectionIndices = new AnomalyDetectionIndices(client, clusterService, threadPool, settings, nodeFilter, AnomalyDetectorSettings.MAX_UPDATE_RETRY_TIMES);
    this.clusterService = clusterService;
    SingleFeatureLinearUniformInterpolator singleFeatureLinearUniformInterpolator = new IntegerSensitiveSingleFeatureLinearUniformInterpolator();
    Interpolator interpolator = new LinearUniformInterpolator(singleFeatureLinearUniformInterpolator);
    SearchFeatureDao searchFeatureDao = new SearchFeatureDao(client, xContentRegistry, interpolator, clientUtil, settings, clusterService, AnomalyDetectorSettings.NUM_SAMPLES_PER_TREE);
    JvmService jvmService = new JvmService(environment.settings());
    RandomCutForestMapper mapper = new RandomCutForestMapper();
    mapper.setSaveExecutorContextEnabled(true);
    mapper.setSaveTreeStateEnabled(true);
    mapper.setPartialTreeStateEnabled(true);
    V1JsonToV2StateConverter converter = new V1JsonToV2StateConverter();
    double modelMaxSizePercent = AnomalyDetectorSettings.MODEL_MAX_SIZE_PERCENTAGE.get(settings);
    ADCircuitBreakerService adCircuitBreakerService = new ADCircuitBreakerService(jvmService).init();
    MemoryTracker memoryTracker = new MemoryTracker(jvmService, modelMaxSizePercent, AnomalyDetectorSettings.DESIRED_MODEL_SIZE_PERCENTAGE, clusterService, adCircuitBreakerService);
    NodeStateManager stateManager = new NodeStateManager(client, xContentRegistry, settings, clientUtil, getClock(), AnomalyDetectorSettings.HOURLY_MAINTENANCE, clusterService);
    FeatureManager featureManager = new FeatureManager(searchFeatureDao, interpolator, getClock(), 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, AD_THREAD_POOL_NAME);
    long heapSizeBytes = JvmInfo.jvmInfo().getMem().getHeapMax().getBytes();
    serializeRCFBufferPool = AccessController.doPrivileged(new PrivilegedAction<GenericObjectPool<LinkedBuffer>>() {

        @Override
        public GenericObjectPool<LinkedBuffer> run() {
            return new GenericObjectPool<>(new BasePooledObjectFactory<LinkedBuffer>() {

                @Override
                public LinkedBuffer create() throws Exception {
                    return LinkedBuffer.allocate(AnomalyDetectorSettings.SERIALIZATION_BUFFER_BYTES);
                }

                @Override
                public PooledObject<LinkedBuffer> wrap(LinkedBuffer obj) {
                    return new DefaultPooledObject<>(obj);
                }
            });
        }
    });
    serializeRCFBufferPool.setMaxTotal(AnomalyDetectorSettings.MAX_TOTAL_RCF_SERIALIZATION_BUFFERS);
    serializeRCFBufferPool.setMaxIdle(AnomalyDetectorSettings.MAX_TOTAL_RCF_SERIALIZATION_BUFFERS);
    serializeRCFBufferPool.setMinIdle(0);
    serializeRCFBufferPool.setBlockWhenExhausted(false);
    serializeRCFBufferPool.setTimeBetweenEvictionRuns(AnomalyDetectorSettings.HOURLY_MAINTENANCE);
    CheckpointDao checkpoint = new CheckpointDao(client, clientUtil, CommonName.CHECKPOINT_INDEX_NAME, gson, mapper, converter, new ThresholdedRandomCutForestMapper(), AccessController.doPrivileged((PrivilegedAction<Schema<ThresholdedRandomCutForestState>>) () -> RuntimeSchema.getSchema(ThresholdedRandomCutForestState.class)), HybridThresholdingModel.class, anomalyDetectionIndices, AnomalyDetectorSettings.MAX_CHECKPOINT_BYTES, serializeRCFBufferPool, AnomalyDetectorSettings.SERIALIZATION_BUFFER_BYTES, 1 - AnomalyDetectorSettings.THRESHOLD_MIN_PVALUE);
    Random random = new Random(42);
    CheckpointWriteWorker checkpointWriteQueue = new CheckpointWriteWorker(heapSizeBytes, AnomalyDetectorSettings.CHECKPOINT_WRITE_QUEUE_SIZE_IN_BYTES, AnomalyDetectorSettings.CHECKPOINT_WRITE_QUEUE_MAX_HEAP_PERCENT, clusterService, random, adCircuitBreakerService, threadPool, settings, AnomalyDetectorSettings.MAX_QUEUED_TASKS_RATIO, getClock(), AnomalyDetectorSettings.MEDIUM_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.LOW_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.MAINTENANCE_FREQ_CONSTANT, AnomalyDetectorSettings.QUEUE_MAINTENANCE, checkpoint, CommonName.CHECKPOINT_INDEX_NAME, AnomalyDetectorSettings.HOURLY_MAINTENANCE, stateManager, AnomalyDetectorSettings.HOURLY_MAINTENANCE);
    EntityCache cache = new PriorityCache(checkpoint, AnomalyDetectorSettings.DEDICATED_CACHE_SIZE.get(settings), AnomalyDetectorSettings.CHECKPOINT_TTL, AnomalyDetectorSettings.MAX_INACTIVE_ENTITIES, memoryTracker, AnomalyDetectorSettings.NUM_TREES, getClock(), clusterService, AnomalyDetectorSettings.HOURLY_MAINTENANCE, threadPool, checkpointWriteQueue, AnomalyDetectorSettings.MAINTENANCE_FREQ_CONSTANT);
    CacheProvider cacheProvider = new CacheProvider(cache);
    EntityColdStarter entityColdStarter = new EntityColdStarter(getClock(), threadPool, stateManager, AnomalyDetectorSettings.NUM_SAMPLES_PER_TREE, AnomalyDetectorSettings.NUM_TREES, AnomalyDetectorSettings.TIME_DECAY, AnomalyDetectorSettings.NUM_MIN_SAMPLES, AnomalyDetectorSettings.MAX_SAMPLE_STRIDE, AnomalyDetectorSettings.MAX_TRAIN_SAMPLE, interpolator, searchFeatureDao, AnomalyDetectorSettings.THRESHOLD_MIN_PVALUE, featureManager, settings, AnomalyDetectorSettings.HOURLY_MAINTENANCE, checkpointWriteQueue, AnomalyDetectorSettings.MAX_COLD_START_ROUNDS);
    EntityColdStartWorker coldstartQueue = new EntityColdStartWorker(heapSizeBytes, AnomalyDetectorSettings.ENTITY_REQUEST_SIZE_IN_BYTES, AnomalyDetectorSettings.ENTITY_COLD_START_QUEUE_MAX_HEAP_PERCENT, clusterService, random, adCircuitBreakerService, threadPool, settings, AnomalyDetectorSettings.MAX_QUEUED_TASKS_RATIO, getClock(), AnomalyDetectorSettings.MEDIUM_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.LOW_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.MAINTENANCE_FREQ_CONSTANT, AnomalyDetectorSettings.QUEUE_MAINTENANCE, entityColdStarter, AnomalyDetectorSettings.HOURLY_MAINTENANCE, stateManager);
    ModelManager modelManager = new ModelManager(checkpoint, getClock(), 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, featureManager, memoryTracker);
    MultiEntityResultHandler multiEntityResultHandler = new MultiEntityResultHandler(client, settings, threadPool, anomalyDetectionIndices, this.clientUtil, this.indexUtils, clusterService);
    ResultWriteWorker resultWriteQueue = new ResultWriteWorker(heapSizeBytes, AnomalyDetectorSettings.RESULT_WRITE_QUEUE_SIZE_IN_BYTES, AnomalyDetectorSettings.RESULT_WRITE_QUEUE_MAX_HEAP_PERCENT, clusterService, random, adCircuitBreakerService, threadPool, settings, AnomalyDetectorSettings.MAX_QUEUED_TASKS_RATIO, getClock(), AnomalyDetectorSettings.MEDIUM_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.LOW_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.MAINTENANCE_FREQ_CONSTANT, AnomalyDetectorSettings.QUEUE_MAINTENANCE, multiEntityResultHandler, xContentRegistry, stateManager, AnomalyDetectorSettings.HOURLY_MAINTENANCE);
    CheckpointReadWorker checkpointReadQueue = new CheckpointReadWorker(heapSizeBytes, AnomalyDetectorSettings.ENTITY_FEATURE_REQUEST_SIZE_IN_BYTES, AnomalyDetectorSettings.CHECKPOINT_READ_QUEUE_MAX_HEAP_PERCENT, clusterService, random, adCircuitBreakerService, threadPool, settings, AnomalyDetectorSettings.MAX_QUEUED_TASKS_RATIO, getClock(), AnomalyDetectorSettings.MEDIUM_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.LOW_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.MAINTENANCE_FREQ_CONSTANT, AnomalyDetectorSettings.QUEUE_MAINTENANCE, modelManager, checkpoint, coldstartQueue, resultWriteQueue, stateManager, anomalyDetectionIndices, cacheProvider, AnomalyDetectorSettings.HOURLY_MAINTENANCE, checkpointWriteQueue);
    ColdEntityWorker coldEntityQueue = new ColdEntityWorker(heapSizeBytes, AnomalyDetectorSettings.ENTITY_FEATURE_REQUEST_SIZE_IN_BYTES, AnomalyDetectorSettings.COLD_ENTITY_QUEUE_MAX_HEAP_PERCENT, clusterService, random, adCircuitBreakerService, threadPool, settings, AnomalyDetectorSettings.MAX_QUEUED_TASKS_RATIO, getClock(), AnomalyDetectorSettings.MEDIUM_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.LOW_SEGMENT_PRUNE_RATIO, AnomalyDetectorSettings.MAINTENANCE_FREQ_CONSTANT, checkpointReadQueue, AnomalyDetectorSettings.HOURLY_MAINTENANCE, stateManager);
    ADDataMigrator dataMigrator = new ADDataMigrator(client, clusterService, xContentRegistry, anomalyDetectionIndices);
    HashRing hashRing = new HashRing(nodeFilter, getClock(), settings, client, clusterService, dataMigrator, modelManager);
    anomalyDetectorRunner = new AnomalyDetectorRunner(modelManager, featureManager, AnomalyDetectorSettings.MAX_PREVIEW_RESULTS);
    Map<String, ADStat<?>> stats = ImmutableMap.<String, ADStat<?>>builder().put(StatNames.AD_EXECUTE_REQUEST_COUNT.getName(), new ADStat<>(false, new CounterSupplier())).put(StatNames.AD_EXECUTE_FAIL_COUNT.getName(), new ADStat<>(false, new CounterSupplier())).put(StatNames.AD_HC_EXECUTE_REQUEST_COUNT.getName(), new ADStat<>(false, new CounterSupplier())).put(StatNames.AD_HC_EXECUTE_FAIL_COUNT.getName(), new ADStat<>(false, new CounterSupplier())).put(StatNames.MODEL_INFORMATION.getName(), new ADStat<>(false, new ModelsOnNodeSupplier(modelManager, cacheProvider, settings, clusterService))).put(StatNames.ANOMALY_DETECTORS_INDEX_STATUS.getName(), new ADStat<>(true, new IndexStatusSupplier(indexUtils, AnomalyDetector.ANOMALY_DETECTORS_INDEX))).put(StatNames.ANOMALY_RESULTS_INDEX_STATUS.getName(), new ADStat<>(true, new IndexStatusSupplier(indexUtils, CommonName.ANOMALY_RESULT_INDEX_ALIAS))).put(StatNames.MODELS_CHECKPOINT_INDEX_STATUS.getName(), new ADStat<>(true, new IndexStatusSupplier(indexUtils, CommonName.CHECKPOINT_INDEX_NAME))).put(StatNames.ANOMALY_DETECTION_JOB_INDEX_STATUS.getName(), new ADStat<>(true, new IndexStatusSupplier(indexUtils, AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX))).put(StatNames.ANOMALY_DETECTION_STATE_STATUS.getName(), new ADStat<>(true, new IndexStatusSupplier(indexUtils, CommonName.DETECTION_STATE_INDEX))).put(StatNames.DETECTOR_COUNT.getName(), new ADStat<>(true, new SettableSupplier())).put(StatNames.SINGLE_ENTITY_DETECTOR_COUNT.getName(), new ADStat<>(true, new SettableSupplier())).put(StatNames.MULTI_ENTITY_DETECTOR_COUNT.getName(), new ADStat<>(true, new SettableSupplier())).put(StatNames.AD_EXECUTING_BATCH_TASK_COUNT.getName(), new ADStat<>(false, new CounterSupplier())).put(StatNames.AD_CANCELED_BATCH_TASK_COUNT.getName(), new ADStat<>(false, new CounterSupplier())).put(StatNames.AD_TOTAL_BATCH_TASK_EXECUTION_COUNT.getName(), new ADStat<>(false, new CounterSupplier())).put(StatNames.AD_BATCH_TASK_FAILURE_COUNT.getName(), new ADStat<>(false, new CounterSupplier())).put(StatNames.MODEL_COUNT.getName(), new ADStat<>(false, new ModelsOnNodeCountSupplier(modelManager, cacheProvider))).build();
    adStats = new ADStats(stats);
    adTaskCacheManager = new ADTaskCacheManager(settings, clusterService, memoryTracker);
    adTaskManager = new ADTaskManager(settings, clusterService, client, xContentRegistry, anomalyDetectionIndices, nodeFilter, hashRing, adTaskCacheManager, threadPool);
    AnomalyResultBulkIndexHandler anomalyResultBulkIndexHandler = new AnomalyResultBulkIndexHandler(client, settings, threadPool, this.clientUtil, this.indexUtils, clusterService, anomalyDetectionIndices);
    adBatchTaskRunner = new ADBatchTaskRunner(settings, threadPool, clusterService, client, adCircuitBreakerService, featureManager, adTaskManager, anomalyDetectionIndices, adStats, anomalyResultBulkIndexHandler, adTaskCacheManager, searchFeatureDao, hashRing, modelManager);
    ADSearchHandler adSearchHandler = new ADSearchHandler(settings, clusterService, client);
    // transport action handler constructors
    return ImmutableList.of(anomalyDetectionIndices, anomalyDetectorRunner, searchFeatureDao, singleFeatureLinearUniformInterpolator, interpolator, gson, jvmService, hashRing, featureManager, modelManager, stateManager, new ADClusterEventListener(clusterService, hashRing), adCircuitBreakerService, adStats, new MasterEventListener(clusterService, threadPool, client, getClock(), clientUtil, nodeFilter), nodeFilter, multiEntityResultHandler, checkpoint, cacheProvider, adTaskManager, adBatchTaskRunner, adSearchHandler, coldstartQueue, resultWriteQueue, checkpointReadQueue, checkpointWriteQueue, coldEntityQueue, entityColdStarter, adTaskCacheManager);
}
Also used : ModelsOnNodeSupplier(org.opensearch.ad.stats.suppliers.ModelsOnNodeSupplier) DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) EntityCache(org.opensearch.ad.caching.EntityCache) ClientUtil(org.opensearch.ad.util.ClientUtil) SearchFeatureDao(org.opensearch.ad.feature.SearchFeatureDao) ResultWriteWorker(org.opensearch.ad.ratelimit.ResultWriteWorker) AnomalyResultBulkIndexHandler(org.opensearch.ad.transport.handler.AnomalyResultBulkIndexHandler) Random(java.util.Random) IntegerSensitiveSingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.IntegerSensitiveSingleFeatureLinearUniformInterpolator) ADClusterEventListener(org.opensearch.ad.cluster.ADClusterEventListener) LinearUniformInterpolator(org.opensearch.ad.dataprocessor.LinearUniformInterpolator) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) IntegerSensitiveSingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.IntegerSensitiveSingleFeatureLinearUniformInterpolator) ThresholdedRandomCutForestState(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestState) ADSearchHandler(org.opensearch.ad.transport.handler.ADSearchHandler) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Settings(org.opensearch.common.settings.Settings) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) LegacyOpenDistroAnomalyDetectorSettings(org.opensearch.ad.settings.LegacyOpenDistroAnomalyDetectorSettings) ClusterSettings(org.opensearch.common.settings.ClusterSettings) Throttler(org.opensearch.ad.util.Throttler) ThresholdedRandomCutForestMapper(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestMapper) PriorityCache(org.opensearch.ad.caching.PriorityCache) CacheProvider(org.opensearch.ad.caching.CacheProvider) ModelManager(org.opensearch.ad.ml.ModelManager) CheckpointWriteWorker(org.opensearch.ad.ratelimit.CheckpointWriteWorker) CheckpointDao(org.opensearch.ad.ml.CheckpointDao) V1JsonToV2StateConverter(com.amazon.randomcutforest.serialize.json.v1.V1JsonToV2StateConverter) ModelsOnNodeCountSupplier(org.opensearch.ad.stats.suppliers.ModelsOnNodeCountSupplier) ADBatchTaskRunner(org.opensearch.ad.task.ADBatchTaskRunner) ADStat(org.opensearch.ad.stats.ADStat) CheckpointReadWorker(org.opensearch.ad.ratelimit.CheckpointReadWorker) EntityColdStartWorker(org.opensearch.ad.ratelimit.EntityColdStartWorker) HashRing(org.opensearch.ad.cluster.HashRing) CounterSupplier(org.opensearch.ad.stats.suppliers.CounterSupplier) IndexUtils(org.opensearch.ad.util.IndexUtils) EntityColdStarter(org.opensearch.ad.ml.EntityColdStarter) PrivilegedAction(java.security.PrivilegedAction) ColdEntityWorker(org.opensearch.ad.ratelimit.ColdEntityWorker) JvmService(org.opensearch.monitor.jvm.JvmService) Interpolator(org.opensearch.ad.dataprocessor.Interpolator) LinearUniformInterpolator(org.opensearch.ad.dataprocessor.LinearUniformInterpolator) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) IntegerSensitiveSingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.IntegerSensitiveSingleFeatureLinearUniformInterpolator) MasterEventListener(org.opensearch.ad.cluster.MasterEventListener) MultiEntityResultHandler(org.opensearch.ad.transport.handler.MultiEntityResultHandler) FeatureManager(org.opensearch.ad.feature.FeatureManager) LinkedBuffer(io.protostuff.LinkedBuffer) ADDataMigrator(org.opensearch.ad.cluster.ADDataMigrator) ADCircuitBreakerService(org.opensearch.ad.breaker.ADCircuitBreakerService) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) IntegerSensitiveSingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.IntegerSensitiveSingleFeatureLinearUniformInterpolator) SettableSupplier(org.opensearch.ad.stats.suppliers.SettableSupplier) IndexStatusSupplier(org.opensearch.ad.stats.suppliers.IndexStatusSupplier) ADTaskCacheManager(org.opensearch.ad.task.ADTaskCacheManager) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) PooledObject(org.apache.commons.pool2.PooledObject) ADTaskManager(org.opensearch.ad.task.ADTaskManager) ThresholdedRandomCutForestMapper(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestMapper) RandomCutForestMapper(com.amazon.randomcutforest.state.RandomCutForestMapper) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) ADStats(org.opensearch.ad.stats.ADStats)

Example 9 with EntityCache

use of org.opensearch.ad.caching.EntityCache in project anomaly-detection by opensearch-project.

the class MultiEntityResultTests method setUp.

@SuppressWarnings({ "serial", "unchecked" })
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    now = Instant.now();
    clock = mock(Clock.class);
    when(clock.instant()).thenReturn(now);
    detectorId = "123";
    String categoryField = "a";
    detector = TestHelpers.randomAnomalyDetectorUsingCategoryFields(detectorId, Collections.singletonList(categoryField));
    stateManager = mock(NodeStateManager.class);
    // make sure parameters are not null, otherwise this mock won't get invoked
    doAnswer(invocation -> {
        ActionListener<Optional<AnomalyDetector>> listener = invocation.getArgument(1);
        listener.onResponse(Optional.of(detector));
        return null;
    }).when(stateManager).getAnomalyDetector(anyString(), any(ActionListener.class));
    settings = Settings.builder().put(AnomalyDetectorSettings.COOLDOWN_MINUTES.getKey(), TimeValue.timeValueMinutes(5)).build();
    // make sure end time is larger enough than Clock.systemUTC().millis() to get PageIterator.hasNext() to pass
    request = new AnomalyResultRequest(detectorId, 100, Clock.systemUTC().millis() + 100_000);
    transportService = mock(TransportService.class);
    client = mock(Client.class);
    ThreadContext threadContext = new ThreadContext(settings);
    mockThreadPool = mock(ThreadPool.class);
    setUpADThreadPool(mockThreadPool);
    when(client.threadPool()).thenReturn(mockThreadPool);
    when(mockThreadPool.getThreadContext()).thenReturn(threadContext);
    featureQuery = mock(FeatureManager.class);
    normalModelManager = mock(ModelManager.class);
    hashRing = mock(HashRing.class);
    Set<Setting<?>> anomalyResultSetting = new HashSet<>(ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
    anomalyResultSetting.add(MAX_ENTITIES_PER_QUERY);
    anomalyResultSetting.add(PAGE_SIZE);
    anomalyResultSetting.add(MAX_RETRY_FOR_UNRESPONSIVE_NODE);
    anomalyResultSetting.add(BACKOFF_MINUTES);
    ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, anomalyResultSetting);
    DiscoveryNode discoveryNode = new DiscoveryNode("node1", OpenSearchTestCase.buildNewFakeTransportAddress(), Collections.emptyMap(), DiscoveryNodeRole.BUILT_IN_ROLES, Version.CURRENT);
    clusterService = ClusterServiceUtils.createClusterService(threadPool, discoveryNode, clusterSettings);
    indexNameResolver = new IndexNameExpressionResolver(new ThreadContext(Settings.EMPTY));
    adCircuitBreakerService = mock(ADCircuitBreakerService.class);
    when(adCircuitBreakerService.isOpen()).thenReturn(false);
    Map<String, ADStat<?>> statsMap = new HashMap<String, ADStat<?>>() {

        {
            put(StatNames.AD_EXECUTE_REQUEST_COUNT.getName(), new ADStat<>(false, new CounterSupplier()));
            put(StatNames.AD_EXECUTE_FAIL_COUNT.getName(), new ADStat<>(false, new CounterSupplier()));
            put(StatNames.AD_HC_EXECUTE_REQUEST_COUNT.getName(), new ADStat<>(false, new CounterSupplier()));
            put(StatNames.AD_HC_EXECUTE_FAIL_COUNT.getName(), new ADStat<>(false, new CounterSupplier()));
        }
    };
    adStats = new ADStats(statsMap);
    adTaskManager = mock(ADTaskManager.class);
    doAnswer(invocation -> {
        ActionListener<Boolean> listener = invocation.getArgument(3);
        listener.onResponse(true);
        return null;
    }).when(adTaskManager).initRealtimeTaskCacheAndCleanupStaleCache(anyString(), any(AnomalyDetector.class), any(TransportService.class), any(ActionListener.class));
    action = new AnomalyResultTransportAction(new ActionFilters(Collections.emptySet()), transportService, settings, client, stateManager, featureQuery, normalModelManager, hashRing, clusterService, indexNameResolver, adCircuitBreakerService, adStats, mockThreadPool, xContentRegistry(), adTaskManager);
    provider = mock(CacheProvider.class);
    entityCache = mock(EntityCache.class);
    when(provider.get()).thenReturn(entityCache);
    when(entityCache.get(any(), any())).thenReturn(MLUtil.randomModelState(new RandomModelStateConfig.Builder().fullModel(true).build()));
    when(entityCache.selectUpdateCandidate(any(), any(), any())).thenReturn(Pair.of(new ArrayList<Entity>(), new ArrayList<Entity>()));
    indexUtil = mock(AnomalyDetectionIndices.class);
    resultWriteQueue = mock(ResultWriteWorker.class);
    checkpointReadQueue = mock(CheckpointReadWorker.class);
    coldEntityQueue = mock(ColdEntityWorker.class);
    attrs1 = new HashMap<>();
    attrs1.put(serviceField, app0);
    attrs1.put(hostField, server1);
    attrs2 = new HashMap<>();
    attrs2.put(serviceField, app0);
    attrs2.put(hostField, server2);
    attrs3 = new HashMap<>();
    attrs3.put(serviceField, app0);
    attrs3.put(hostField, server3);
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ClusterSettings(org.opensearch.common.settings.ClusterSettings) EntityCache(org.opensearch.ad.caching.EntityCache) HashMap(java.util.HashMap) ADStat(org.opensearch.ad.stats.ADStat) ThreadPool(org.opensearch.threadpool.ThreadPool) ArrayList(java.util.ArrayList) CheckpointReadWorker(org.opensearch.ad.ratelimit.CheckpointReadWorker) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Clock(java.time.Clock) ResultWriteWorker(org.opensearch.ad.ratelimit.ResultWriteWorker) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) NodeStateManager(org.opensearch.ad.NodeStateManager) HashRing(org.opensearch.ad.cluster.HashRing) CounterSupplier(org.opensearch.ad.stats.suppliers.CounterSupplier) ColdEntityWorker(org.opensearch.ad.ratelimit.ColdEntityWorker) Client(org.opensearch.client.Client) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FeatureManager(org.opensearch.ad.feature.FeatureManager) HashSet(java.util.HashSet) ADCircuitBreakerService(org.opensearch.ad.breaker.ADCircuitBreakerService) Optional(java.util.Optional) Setting(org.opensearch.common.settings.Setting) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) ActionFilters(org.opensearch.action.support.ActionFilters) ModelManager(org.opensearch.ad.ml.ModelManager) CacheProvider(org.opensearch.ad.caching.CacheProvider) ActionListener(org.opensearch.action.ActionListener) TransportService(org.opensearch.transport.TransportService) ADTaskManager(org.opensearch.ad.task.ADTaskManager) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) ADStats(org.opensearch.ad.stats.ADStats) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) Before(org.junit.Before)

Example 10 with EntityCache

use of org.opensearch.ad.caching.EntityCache in project anomaly-detection by opensearch-project.

the class MultiEntityResultTests method testCacheSelection.

public void testCacheSelection() throws IOException, InterruptedException {
    CountDownLatch inProgress = setUpSearchResponse();
    setUpTransportInterceptor(this::entityResultHandler);
    when(hashRing.getOwningNodeWithSameLocalAdVersionForRealtimeAD(any(String.class))).thenReturn(Optional.of(testNodes[1].discoveryNode()));
    List<Entity> hotEntities = new ArrayList<>();
    Entity entity1 = Entity.createEntityByReordering(attrs1);
    hotEntities.add(entity1);
    List<Entity> coldEntities = new ArrayList<>();
    Entity entity2 = Entity.createEntityByReordering(attrs2);
    coldEntities.add(entity2);
    provider = mock(CacheProvider.class);
    entityCache = mock(EntityCache.class);
    when(provider.get()).thenReturn(entityCache);
    when(entityCache.selectUpdateCandidate(any(), any(), any())).thenReturn(Pair.of(hotEntities, coldEntities));
    when(entityCache.get(any(), any())).thenReturn(null);
    new EntityResultTransportAction(new ActionFilters(Collections.emptySet()), // since we send requests to testNodes[1]
    testNodes[1].transportService, normalModelManager, adCircuitBreakerService, provider, stateManager, indexUtil, resultWriteQueue, checkpointReadQueue, coldEntityQueue, threadPool);
    PlainActionFuture<AnomalyResultResponse> listener = new PlainActionFuture<>();
    action.doExecute(null, request, listener);
    assertTrue(inProgress.await(10000L, TimeUnit.MILLISECONDS));
    verify(checkpointReadQueue).putAll(argThat(new ArgumentMatcher<List<EntityFeatureRequest>>() {

        @Override
        public boolean matches(List<EntityFeatureRequest> argument) {
            List<EntityFeatureRequest> arg = (argument);
            LOG.info("size: " + arg.size() + " ; element: " + arg.get(0));
            return arg.size() == 1 && arg.get(0).getEntity().equals(entity1);
        }
    }));
    verify(coldEntityQueue).putAll(argThat(new ArgumentMatcher<List<EntityFeatureRequest>>() {

        @Override
        public boolean matches(List<EntityFeatureRequest> argument) {
            List<EntityFeatureRequest> arg = (argument);
            LOG.info("size: " + arg.size() + " ; element: " + arg.get(0));
            return arg.size() == 1 && arg.get(0).getEntity().equals(entity2);
        }
    }));
}
Also used : Entity(org.opensearch.ad.model.Entity) EntityCache(org.opensearch.ad.caching.EntityCache) EntityFeatureRequest(org.opensearch.ad.ratelimit.EntityFeatureRequest) ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ActionFilters(org.opensearch.action.support.ActionFilters) CountDownLatch(java.util.concurrent.CountDownLatch) CacheProvider(org.opensearch.ad.caching.CacheProvider) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) ArgumentMatcher(org.mockito.ArgumentMatcher) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList)

Aggregations

EntityCache (org.opensearch.ad.caching.EntityCache)13 CacheProvider (org.opensearch.ad.caching.CacheProvider)10 Before (org.junit.Before)8 ModelManager (org.opensearch.ad.ml.ModelManager)8 ActionFilters (org.opensearch.action.support.ActionFilters)6 ClusterService (org.opensearch.cluster.service.ClusterService)6 ArrayList (java.util.ArrayList)5 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)5 FeatureManager (org.opensearch.ad.feature.FeatureManager)5 Entity (org.opensearch.ad.model.Entity)5 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)5 ClusterSettings (org.opensearch.common.settings.ClusterSettings)5 Settings (org.opensearch.common.settings.Settings)5 TransportService (org.opensearch.transport.TransportService)5 HashSet (java.util.HashSet)4 NodeStateManager (org.opensearch.ad.NodeStateManager)4 AnomalyDetectionIndices (org.opensearch.ad.indices.AnomalyDetectionIndices)4 EntityModel (org.opensearch.ad.ml.EntityModel)4 CounterSupplier (org.opensearch.ad.stats.suppliers.CounterSupplier)4 ThreadPool (org.opensearch.threadpool.ThreadPool)4