Search in sources :

Example 16 with ClientUtil

use of org.opensearch.ad.util.ClientUtil in project anomaly-detection by opensearch-project.

the class CheckpointDaoTests method test_getModelCheckpoint_returnExpectedToListener.

@SuppressWarnings("unchecked")
public void test_getModelCheckpoint_returnExpectedToListener() {
    // ArgumentCaptor<GetRequest> requestCaptor = ArgumentCaptor.forClass(GetRequest.class);
    UpdateResponse updateResponse = new UpdateResponse(new ReplicationResponse.ShardInfo(3, 2), new ShardId(CommonName.CHECKPOINT_INDEX_NAME, "uuid", 2), CommonName.CHECKPOINT_INDEX_NAME, "1", 7, 17, 2, UPDATED);
    AtomicReference<GetRequest> getRequest = new AtomicReference<>();
    doAnswer(invocation -> {
        ActionRequest request = invocation.getArgument(0);
        if (request instanceof GetRequest) {
            getRequest.set((GetRequest) request);
            ActionListener<GetResponse> listener = invocation.getArgument(2);
            listener.onResponse(getResponse);
        } else {
            UpdateRequest updateRequest = (UpdateRequest) request;
            when(getResponse.getSource()).thenReturn(updateRequest.doc().sourceAsMap());
            ActionListener<UpdateResponse> listener = invocation.getArgument(2);
            listener.onResponse(updateResponse);
        }
        return null;
    }).when(clientUtil).asyncRequest(any(), any(BiConsumer.class), any(ActionListener.class));
    when(getResponse.isExists()).thenReturn(true);
    ThresholdedRandomCutForest trcf = createTRCF();
    final CountDownLatch inProgressLatch = new CountDownLatch(1);
    checkpointDao.putTRCFCheckpoint(modelId, trcf, ActionListener.wrap(response -> {
        inProgressLatch.countDown();
    }, exception -> {
        assertTrue("Should not reach here ", false);
        inProgressLatch.countDown();
    }));
    ActionListener<Optional<ThresholdedRandomCutForest>> listener = mock(ActionListener.class);
    checkpointDao.getTRCFModel(modelId, listener);
    GetRequest capturedGetRequest = getRequest.get();
    assertEquals(indexName, capturedGetRequest.index());
    assertEquals(modelId, capturedGetRequest.id());
    ArgumentCaptor<Optional<ThresholdedRandomCutForest>> responseCaptor = ArgumentCaptor.forClass(Optional.class);
    verify(listener).onResponse(responseCaptor.capture());
    Optional<ThresholdedRandomCutForest> result = responseCaptor.getValue();
    assertTrue(result.isPresent());
    RandomCutForest deserializedForest = result.get().getForest();
    RandomCutForest serializedForest = trcf.getForest();
    assertEquals(deserializedForest.getDimensions(), serializedForest.getDimensions());
    assertEquals(deserializedForest.getNumberOfTrees(), serializedForest.getNumberOfTrees());
    assertEquals(deserializedForest.getSampleSize(), serializedForest.getSampleSize());
}
Also used : Arrays(java.util.Arrays) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ThresholdedRandomCutForestMapper(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestMapper) ActionRequest(org.opensearch.action.ActionRequest) BulkAction(org.opensearch.action.bulk.BulkAction) GsonBuilder(com.google.gson.GsonBuilder) Mockito.doThrow(org.mockito.Mockito.doThrow) MockitoAnnotations(org.mockito.MockitoAnnotations) Pair(org.apache.commons.lang3.tuple.Pair) V1JsonToV2StateConverter(com.amazon.randomcutforest.serialize.json.v1.V1JsonToV2StateConverter) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) ZoneOffset(java.time.ZoneOffset) ActionListener(org.opensearch.action.ActionListener) Mockito.doReturn(org.mockito.Mockito.doReturn) DeleteRequest(org.opensearch.action.delete.DeleteRequest) MultiGetAction(org.opensearch.action.get.MultiGetAction) Client(org.opensearch.client.Client) Set(java.util.Set) Matchers.any(org.mockito.Matchers.any) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) CountDownLatch(java.util.concurrent.CountDownLatch) UPDATED(org.opensearch.action.DocWriteResponse.Result.UPDATED) ThresholdedRandomCutForestState(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestState) Logger(org.apache.logging.log4j.Logger) MLUtil(test.org.opensearch.ad.util.MLUtil) DocWriteResponse(org.opensearch.action.DocWriteResponse) UpdateRequest(org.opensearch.action.update.UpdateRequest) AccessController(java.security.AccessController) Mockito.mock(org.mockito.Mockito.mock) Mock(org.mockito.Mock) UpdateResponse(org.opensearch.action.update.UpdateResponse) DocWriteRequest(org.opensearch.action.DocWriteRequest) FIELD_MODELV2(org.opensearch.ad.ml.CheckpointDao.FIELD_MODELV2) Mockito.spy(org.mockito.Mockito.spy) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) BiConsumer(java.util.function.BiConsumer) DeleteResponse(org.opensearch.action.delete.DeleteResponse) Before(org.junit.Before) CommonName(org.opensearch.ad.constant.CommonName) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) File(java.io.File) Mockito.never(org.mockito.Mockito.never) MultiGetItemResponse(org.opensearch.action.get.MultiGetItemResponse) BufferedReader(java.io.BufferedReader) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) BasePooledObjectFactory(org.apache.commons.pool2.BasePooledObjectFactory) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) URISyntaxException(java.net.URISyntaxException) PooledObject(org.apache.commons.pool2.PooledObject) BulkRequest(org.opensearch.action.bulk.BulkRequest) Random(java.util.Random) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) Gson(com.google.gson.Gson) RandomModelStateConfig(test.org.opensearch.ad.util.RandomModelStateConfig) RandomCutForestMapper(com.amazon.randomcutforest.state.RandomCutForestMapper) GetResponse(org.opensearch.action.get.GetResponse) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) PrivilegedAction(java.security.PrivilegedAction) Instant(java.time.Instant) FileNotFoundException(java.io.FileNotFoundException) OffsetDateTime(java.time.OffsetDateTime) Entry(java.util.Map.Entry) Optional(java.util.Optional) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) Queue(java.util.Queue) JsonDeserializer(test.org.opensearch.ad.util.JsonDeserializer) Precision(com.amazon.randomcutforest.config.Precision) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) ArgumentCaptor(org.mockito.ArgumentCaptor) Schema(io.protostuff.Schema) FIELD_MODEL(org.opensearch.ad.ml.CheckpointDao.FIELD_MODEL) NoSuchElementException(java.util.NoSuchElementException) Answers(org.mockito.Answers) ClientUtil(org.opensearch.ad.util.ClientUtil) TIMESTAMP(org.opensearch.ad.ml.CheckpointDao.TIMESTAMP) Month(java.time.Month) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) GetRequest(org.opensearch.action.get.GetRequest) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) RuntimeSchema(io.protostuff.runtime.RuntimeSchema) Mockito.when(org.mockito.Mockito.when) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) LinkedBuffer(io.protostuff.LinkedBuffer) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) ShardId(org.opensearch.index.shard.ShardId) BulkResponse(org.opensearch.action.bulk.BulkResponse) ThresholdedRandomCutForest(com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest) Clock(java.time.Clock) FileReader(java.io.FileReader) IndexRequest(org.opensearch.action.index.IndexRequest) LogManager(org.apache.logging.log4j.LogManager) Optional(java.util.Optional) UpdateRequest(org.opensearch.action.update.UpdateRequest) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) ThresholdedRandomCutForest(com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) GetResponse(org.opensearch.action.get.GetResponse) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) ShardId(org.opensearch.index.shard.ShardId) UpdateResponse(org.opensearch.action.update.UpdateResponse) ActionListener(org.opensearch.action.ActionListener) ActionRequest(org.opensearch.action.ActionRequest) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) GetRequest(org.opensearch.action.get.GetRequest) BiConsumer(java.util.function.BiConsumer) ThresholdedRandomCutForest(com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest)

Example 17 with ClientUtil

use of org.opensearch.ad.util.ClientUtil in project anomaly-detection by opensearch-project.

the class CheckpointDaoTests method test_getModelCheckpoint_Bwc.

@SuppressWarnings("unchecked")
public void test_getModelCheckpoint_Bwc() {
    // ArgumentCaptor<GetRequest> requestCaptor = ArgumentCaptor.forClass(GetRequest.class);
    UpdateResponse updateResponse = new UpdateResponse(new ReplicationResponse.ShardInfo(3, 2), new ShardId(CommonName.CHECKPOINT_INDEX_NAME, "uuid", 2), CommonName.CHECKPOINT_INDEX_NAME, "1", 7, 17, 2, UPDATED);
    AtomicReference<GetRequest> getRequest = new AtomicReference<>();
    doAnswer(invocation -> {
        ActionRequest request = invocation.getArgument(0);
        if (request instanceof GetRequest) {
            getRequest.set((GetRequest) request);
            ActionListener<GetResponse> listener = invocation.getArgument(2);
            listener.onResponse(getResponse);
        } else {
            UpdateRequest updateRequest = (UpdateRequest) request;
            when(getResponse.getSource()).thenReturn(updateRequest.doc().sourceAsMap());
            ActionListener<UpdateResponse> listener = invocation.getArgument(2);
            listener.onResponse(updateResponse);
        }
        return null;
    }).when(clientUtil).asyncRequest(any(), any(BiConsumer.class), any(ActionListener.class));
    when(getResponse.isExists()).thenReturn(true);
    ThresholdedRandomCutForest trcf = createTRCF();
    final CountDownLatch inProgressLatch = new CountDownLatch(1);
    checkpointDao.putTRCFCheckpoint(modelId, trcf, ActionListener.wrap(response -> {
        inProgressLatch.countDown();
    }, exception -> {
        assertTrue("Should not reach here ", false);
        inProgressLatch.countDown();
    }));
    ActionListener<Optional<ThresholdedRandomCutForest>> listener = mock(ActionListener.class);
    checkpointDao.getTRCFModel(modelId, listener);
    GetRequest capturedGetRequest = getRequest.get();
    assertEquals(indexName, capturedGetRequest.index());
    assertEquals(modelId, capturedGetRequest.id());
    ArgumentCaptor<Optional<ThresholdedRandomCutForest>> responseCaptor = ArgumentCaptor.forClass(Optional.class);
    verify(listener).onResponse(responseCaptor.capture());
    Optional<ThresholdedRandomCutForest> result = responseCaptor.getValue();
    assertTrue(result.isPresent());
    RandomCutForest deserializedForest = result.get().getForest();
    RandomCutForest serializedForest = trcf.getForest();
    assertEquals(deserializedForest.getDimensions(), serializedForest.getDimensions());
    assertEquals(deserializedForest.getNumberOfTrees(), serializedForest.getNumberOfTrees());
    assertEquals(deserializedForest.getSampleSize(), serializedForest.getSampleSize());
}
Also used : Arrays(java.util.Arrays) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ThresholdedRandomCutForestMapper(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestMapper) ActionRequest(org.opensearch.action.ActionRequest) BulkAction(org.opensearch.action.bulk.BulkAction) GsonBuilder(com.google.gson.GsonBuilder) Mockito.doThrow(org.mockito.Mockito.doThrow) MockitoAnnotations(org.mockito.MockitoAnnotations) Pair(org.apache.commons.lang3.tuple.Pair) V1JsonToV2StateConverter(com.amazon.randomcutforest.serialize.json.v1.V1JsonToV2StateConverter) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) ZoneOffset(java.time.ZoneOffset) ActionListener(org.opensearch.action.ActionListener) Mockito.doReturn(org.mockito.Mockito.doReturn) DeleteRequest(org.opensearch.action.delete.DeleteRequest) MultiGetAction(org.opensearch.action.get.MultiGetAction) Client(org.opensearch.client.Client) Set(java.util.Set) Matchers.any(org.mockito.Matchers.any) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) CountDownLatch(java.util.concurrent.CountDownLatch) UPDATED(org.opensearch.action.DocWriteResponse.Result.UPDATED) ThresholdedRandomCutForestState(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestState) Logger(org.apache.logging.log4j.Logger) MLUtil(test.org.opensearch.ad.util.MLUtil) DocWriteResponse(org.opensearch.action.DocWriteResponse) UpdateRequest(org.opensearch.action.update.UpdateRequest) AccessController(java.security.AccessController) Mockito.mock(org.mockito.Mockito.mock) Mock(org.mockito.Mock) UpdateResponse(org.opensearch.action.update.UpdateResponse) DocWriteRequest(org.opensearch.action.DocWriteRequest) FIELD_MODELV2(org.opensearch.ad.ml.CheckpointDao.FIELD_MODELV2) Mockito.spy(org.mockito.Mockito.spy) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) BiConsumer(java.util.function.BiConsumer) DeleteResponse(org.opensearch.action.delete.DeleteResponse) Before(org.junit.Before) CommonName(org.opensearch.ad.constant.CommonName) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) File(java.io.File) Mockito.never(org.mockito.Mockito.never) MultiGetItemResponse(org.opensearch.action.get.MultiGetItemResponse) BufferedReader(java.io.BufferedReader) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) BasePooledObjectFactory(org.apache.commons.pool2.BasePooledObjectFactory) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) URISyntaxException(java.net.URISyntaxException) PooledObject(org.apache.commons.pool2.PooledObject) BulkRequest(org.opensearch.action.bulk.BulkRequest) Random(java.util.Random) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) Gson(com.google.gson.Gson) RandomModelStateConfig(test.org.opensearch.ad.util.RandomModelStateConfig) RandomCutForestMapper(com.amazon.randomcutforest.state.RandomCutForestMapper) GetResponse(org.opensearch.action.get.GetResponse) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) PrivilegedAction(java.security.PrivilegedAction) Instant(java.time.Instant) FileNotFoundException(java.io.FileNotFoundException) OffsetDateTime(java.time.OffsetDateTime) Entry(java.util.Map.Entry) Optional(java.util.Optional) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) Queue(java.util.Queue) JsonDeserializer(test.org.opensearch.ad.util.JsonDeserializer) Precision(com.amazon.randomcutforest.config.Precision) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) ArgumentCaptor(org.mockito.ArgumentCaptor) Schema(io.protostuff.Schema) FIELD_MODEL(org.opensearch.ad.ml.CheckpointDao.FIELD_MODEL) NoSuchElementException(java.util.NoSuchElementException) Answers(org.mockito.Answers) ClientUtil(org.opensearch.ad.util.ClientUtil) TIMESTAMP(org.opensearch.ad.ml.CheckpointDao.TIMESTAMP) Month(java.time.Month) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) GetRequest(org.opensearch.action.get.GetRequest) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) RuntimeSchema(io.protostuff.runtime.RuntimeSchema) Mockito.when(org.mockito.Mockito.when) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) LinkedBuffer(io.protostuff.LinkedBuffer) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) ShardId(org.opensearch.index.shard.ShardId) BulkResponse(org.opensearch.action.bulk.BulkResponse) ThresholdedRandomCutForest(com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest) Clock(java.time.Clock) FileReader(java.io.FileReader) IndexRequest(org.opensearch.action.index.IndexRequest) LogManager(org.apache.logging.log4j.LogManager) Optional(java.util.Optional) UpdateRequest(org.opensearch.action.update.UpdateRequest) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) ThresholdedRandomCutForest(com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) GetResponse(org.opensearch.action.get.GetResponse) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) ShardId(org.opensearch.index.shard.ShardId) UpdateResponse(org.opensearch.action.update.UpdateResponse) ActionListener(org.opensearch.action.ActionListener) ActionRequest(org.opensearch.action.ActionRequest) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) GetRequest(org.opensearch.action.get.GetRequest) BiConsumer(java.util.function.BiConsumer) ThresholdedRandomCutForest(com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest)

Example 18 with ClientUtil

use of org.opensearch.ad.util.ClientUtil in project anomaly-detection by opensearch-project.

the class CheckpointDaoTests method test_batch_read.

@SuppressWarnings("unchecked")
public void test_batch_read() throws InterruptedException {
    doAnswer(invocation -> {
        ActionListener<MultiGetResponse> listener = invocation.getArgument(2);
        MultiGetItemResponse[] items = new MultiGetItemResponse[1];
        items[0] = new MultiGetItemResponse(null, new MultiGetResponse.Failure(CommonName.CHECKPOINT_INDEX_NAME, "_doc", "modelId", new IndexNotFoundException(CommonName.CHECKPOINT_INDEX_NAME)));
        listener.onResponse(new MultiGetResponse(items));
        return null;
    }).when(clientUtil).execute(eq(MultiGetAction.INSTANCE), any(MultiGetRequest.class), any(ActionListener.class));
    final CountDownLatch processingLatch = new CountDownLatch(1);
    checkpointDao.batchRead(new MultiGetRequest(), ActionListener.wrap(response -> processingLatch.countDown(), e -> {
        assertTrue(false);
    }));
    // we don't expect the waiting time elapsed before the count reached zero
    assertTrue(processingLatch.await(100, TimeUnit.SECONDS));
    verify(clientUtil, times(1)).execute(any(), any(), any());
}
Also used : Arrays(java.util.Arrays) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ThresholdedRandomCutForestMapper(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestMapper) ActionRequest(org.opensearch.action.ActionRequest) BulkAction(org.opensearch.action.bulk.BulkAction) GsonBuilder(com.google.gson.GsonBuilder) Mockito.doThrow(org.mockito.Mockito.doThrow) MockitoAnnotations(org.mockito.MockitoAnnotations) Pair(org.apache.commons.lang3.tuple.Pair) V1JsonToV2StateConverter(com.amazon.randomcutforest.serialize.json.v1.V1JsonToV2StateConverter) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) ZoneOffset(java.time.ZoneOffset) ActionListener(org.opensearch.action.ActionListener) Mockito.doReturn(org.mockito.Mockito.doReturn) DeleteRequest(org.opensearch.action.delete.DeleteRequest) MultiGetAction(org.opensearch.action.get.MultiGetAction) Client(org.opensearch.client.Client) Set(java.util.Set) Matchers.any(org.mockito.Matchers.any) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) CountDownLatch(java.util.concurrent.CountDownLatch) UPDATED(org.opensearch.action.DocWriteResponse.Result.UPDATED) ThresholdedRandomCutForestState(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestState) Logger(org.apache.logging.log4j.Logger) MLUtil(test.org.opensearch.ad.util.MLUtil) DocWriteResponse(org.opensearch.action.DocWriteResponse) UpdateRequest(org.opensearch.action.update.UpdateRequest) AccessController(java.security.AccessController) Mockito.mock(org.mockito.Mockito.mock) Mock(org.mockito.Mock) UpdateResponse(org.opensearch.action.update.UpdateResponse) DocWriteRequest(org.opensearch.action.DocWriteRequest) FIELD_MODELV2(org.opensearch.ad.ml.CheckpointDao.FIELD_MODELV2) Mockito.spy(org.mockito.Mockito.spy) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) BiConsumer(java.util.function.BiConsumer) DeleteResponse(org.opensearch.action.delete.DeleteResponse) Before(org.junit.Before) CommonName(org.opensearch.ad.constant.CommonName) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) File(java.io.File) Mockito.never(org.mockito.Mockito.never) MultiGetItemResponse(org.opensearch.action.get.MultiGetItemResponse) BufferedReader(java.io.BufferedReader) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) BasePooledObjectFactory(org.apache.commons.pool2.BasePooledObjectFactory) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) URISyntaxException(java.net.URISyntaxException) PooledObject(org.apache.commons.pool2.PooledObject) BulkRequest(org.opensearch.action.bulk.BulkRequest) Random(java.util.Random) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) Gson(com.google.gson.Gson) RandomModelStateConfig(test.org.opensearch.ad.util.RandomModelStateConfig) RandomCutForestMapper(com.amazon.randomcutforest.state.RandomCutForestMapper) GetResponse(org.opensearch.action.get.GetResponse) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) PrivilegedAction(java.security.PrivilegedAction) Instant(java.time.Instant) FileNotFoundException(java.io.FileNotFoundException) OffsetDateTime(java.time.OffsetDateTime) Entry(java.util.Map.Entry) Optional(java.util.Optional) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) Queue(java.util.Queue) JsonDeserializer(test.org.opensearch.ad.util.JsonDeserializer) Precision(com.amazon.randomcutforest.config.Precision) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) ArgumentCaptor(org.mockito.ArgumentCaptor) Schema(io.protostuff.Schema) FIELD_MODEL(org.opensearch.ad.ml.CheckpointDao.FIELD_MODEL) NoSuchElementException(java.util.NoSuchElementException) Answers(org.mockito.Answers) ClientUtil(org.opensearch.ad.util.ClientUtil) TIMESTAMP(org.opensearch.ad.ml.CheckpointDao.TIMESTAMP) Month(java.time.Month) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) GetRequest(org.opensearch.action.get.GetRequest) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) RuntimeSchema(io.protostuff.runtime.RuntimeSchema) Mockito.when(org.mockito.Mockito.when) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) LinkedBuffer(io.protostuff.LinkedBuffer) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) ShardId(org.opensearch.index.shard.ShardId) BulkResponse(org.opensearch.action.bulk.BulkResponse) ThresholdedRandomCutForest(com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest) Clock(java.time.Clock) FileReader(java.io.FileReader) IndexRequest(org.opensearch.action.index.IndexRequest) LogManager(org.apache.logging.log4j.LogManager) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) MultiGetItemResponse(org.opensearch.action.get.MultiGetItemResponse) ActionListener(org.opensearch.action.ActionListener) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) CountDownLatch(java.util.concurrent.CountDownLatch) MultiGetRequest(org.opensearch.action.get.MultiGetRequest)

Example 19 with ClientUtil

use of org.opensearch.ad.util.ClientUtil in project anomaly-detection by opensearch-project.

the class CheckpointDao method saveModelCheckpointAsync.

/**
 * Update the model doc using fields in source.  This ensures we won't touch
 * the old checkpoint and nodes with old/new logic can coexist in a cluster.
 * This is useful for introducing compact rcf new model format.
 *
 * @param source fields to update
 * @param modelId model Id, used as doc id in the checkpoint index
 * @param listener Listener to return response
 */
private void saveModelCheckpointAsync(Map<String, Object> source, String modelId, ActionListener<Void> listener) {
    UpdateRequest updateRequest = new UpdateRequest(indexName, modelId);
    updateRequest.doc(source);
    // If the document does not already exist, the contents of the upsert element are inserted as a new document.
    // If the document exists, update fields in the map
    updateRequest.docAsUpsert(true);
    clientUtil.<UpdateRequest, UpdateResponse>asyncRequest(updateRequest, client::update, ActionListener.wrap(r -> listener.onResponse(null), listener::onFailure));
}
Also used : JsonObject(com.google.gson.JsonObject) Arrays(java.util.Arrays) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) IndexResponse(org.opensearch.action.index.IndexResponse) ThresholdedRandomCutForestMapper(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestMapper) ZonedDateTime(java.time.ZonedDateTime) BulkRequest(org.opensearch.action.bulk.BulkRequest) BulkAction(org.opensearch.action.bulk.BulkAction) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) ADIndex(org.opensearch.ad.indices.ADIndex) Locale(java.util.Locale) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) V1JsonToV2StateConverter(com.amazon.randomcutforest.serialize.json.v1.V1JsonToV2StateConverter) Gson(com.google.gson.Gson) Map(java.util.Map) ZoneOffset(java.time.ZoneOffset) ActionListener(org.opensearch.action.ActionListener) RandomCutForestMapper(com.amazon.randomcutforest.state.RandomCutForestMapper) GetResponse(org.opensearch.action.get.GetResponse) DeleteRequest(org.opensearch.action.delete.DeleteRequest) MultiGetAction(org.opensearch.action.get.MultiGetAction) Client(org.opensearch.client.Client) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) ExceptionsHelper(org.opensearch.ExceptionsHelper) PrivilegedAction(java.security.PrivilegedAction) Instant(java.time.Instant) ScrollableHitSource(org.opensearch.index.reindex.ScrollableHitSource) RandomCutForest(com.amazon.randomcutforest.RandomCutForest) Base64(java.util.Base64) List(java.util.List) ThresholdedRandomCutForestState(com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestState) Logger(org.apache.logging.log4j.Logger) ProtostuffIOUtil(io.protostuff.ProtostuffIOUtil) Entry(java.util.Map.Entry) Optional(java.util.Optional) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) UpdateRequest(org.opensearch.action.update.UpdateRequest) AccessController(java.security.AccessController) RandomCutForestState(com.amazon.randomcutforest.state.RandomCutForestState) Precision(com.amazon.randomcutforest.config.Precision) UpdateResponse(org.opensearch.action.update.UpdateResponse) HashMap(java.util.HashMap) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) IndicesOptions(org.opensearch.action.support.IndicesOptions) JsonParser(com.google.gson.JsonParser) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ArrayList(java.util.ArrayList) Schema(io.protostuff.Schema) DeleteResponse(org.opensearch.action.delete.DeleteResponse) CommonName(org.opensearch.ad.constant.CommonName) ClientUtil(org.opensearch.ad.util.ClientUtil) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) GetRequest(org.opensearch.action.get.GetRequest) IOException(java.io.IOException) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) LinkedBuffer(io.protostuff.LinkedBuffer) BulkByScrollResponse(org.opensearch.index.reindex.BulkByScrollResponse) Entity(org.opensearch.ad.model.Entity) BulkResponse(org.opensearch.action.bulk.BulkResponse) ThresholdedRandomCutForest(com.amazon.randomcutforest.parkservices.ThresholdedRandomCutForest) MatchQueryBuilder(org.opensearch.index.query.MatchQueryBuilder) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) DeleteByQueryAction(org.opensearch.index.reindex.DeleteByQueryAction) ArrayDeque(java.util.ArrayDeque) IndexRequest(org.opensearch.action.index.IndexRequest) LogManager(org.apache.logging.log4j.LogManager) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) UpdateResponse(org.opensearch.action.update.UpdateResponse) UpdateRequest(org.opensearch.action.update.UpdateRequest)

Example 20 with ClientUtil

use of org.opensearch.ad.util.ClientUtil in project anomaly-detection by opensearch-project.

the class SearchFeatureDao method getLatestDataTime.

/**
 * Returns epoch time of the latest data under the detector.
 *
 * @deprecated use getLatestDataTime with listener instead.
 *
 * @param detector info about the indices and documents
 * @return epoch time of the latest data in milliseconds
 */
@Deprecated
public Optional<Long> getLatestDataTime(AnomalyDetector detector) {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().aggregation(AggregationBuilders.max(CommonName.AGG_NAME_MAX_TIME).field(detector.getTimeField())).size(0);
    SearchRequest searchRequest = new SearchRequest().indices(detector.getIndices().toArray(new String[0])).source(searchSourceBuilder);
    return clientUtil.<SearchRequest, SearchResponse>timedRequest(searchRequest, logger, client::search).map(SearchResponse::getAggregations).map(aggs -> aggs.asMap()).map(map -> (Max) map.get(CommonName.AGG_NAME_MAX_TIME)).map(agg -> (long) agg.getValue());
}
Also used : Arrays(java.util.Arrays) Max(org.opensearch.search.aggregations.metrics.Max) Aggregation(org.opensearch.search.aggregations.Aggregation) ZonedDateTime(java.time.ZonedDateTime) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) AggregationBuilder(org.opensearch.search.aggregations.AggregationBuilder) FieldSortBuilder(org.opensearch.search.sort.FieldSortBuilder) Locale(java.util.Locale) Map(java.util.Map) ParseUtils.batchFeatureQuery(org.opensearch.ad.util.ParseUtils.batchFeatureQuery) ActionListener(org.opensearch.action.ActionListener) Interpolator(org.opensearch.ad.dataprocessor.Interpolator) Client(org.opensearch.client.Client) Settings(org.opensearch.common.settings.Settings) MultiBucketsAggregation(org.opensearch.search.aggregations.bucket.MultiBucketsAggregation) Terms(org.opensearch.search.aggregations.bucket.terms.Terms) Collectors(java.util.stream.Collectors) List(java.util.List) Logger(org.apache.logging.log4j.Logger) PREVIEW_TIMEOUT_IN_MILLIS(org.opensearch.ad.settings.AnomalyDetectorSettings.PREVIEW_TIMEOUT_IN_MILLIS) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) Entry(java.util.Map.Entry) DATE_HISTOGRAM(org.opensearch.ad.constant.CommonName.DATE_HISTOGRAM) Optional(java.util.Optional) Bucket(org.opensearch.search.aggregations.bucket.range.InternalDateRange.Bucket) TermsValuesSourceBuilder(org.opensearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) InternalDateRange(org.opensearch.search.aggregations.bucket.range.InternalDateRange) MatrixUtils.createRealMatrix(org.apache.commons.math3.linear.MatrixUtils.createRealMatrix) HashMap(java.util.HashMap) Aggregations(org.opensearch.search.aggregations.Aggregations) ArrayList(java.util.ArrayList) SortOrder(org.opensearch.search.sort.SortOrder) PAGE_SIZE(org.opensearch.ad.settings.AnomalyDetectorSettings.PAGE_SIZE) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SearchRequest(org.opensearch.action.search.SearchRequest) SearchResponse(org.opensearch.action.search.SearchResponse) SimpleEntry(java.util.AbstractMap.SimpleEntry) MAX_ENTITIES_FOR_PREVIEW(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_ENTITIES_FOR_PREVIEW) QueryBuilders(org.opensearch.index.query.QueryBuilders) CommonName(org.opensearch.ad.constant.CommonName) ClientUtil(org.opensearch.ad.util.ClientUtil) RangeQueryBuilder(org.opensearch.index.query.RangeQueryBuilder) InternalComposite(org.opensearch.search.aggregations.bucket.composite.InternalComposite) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) IOException(java.io.IOException) PipelineAggregatorBuilders(org.opensearch.search.aggregations.PipelineAggregatorBuilders) Min(org.opensearch.search.aggregations.metrics.Min) CompositeAggregation(org.opensearch.search.aggregations.bucket.composite.CompositeAggregation) AggregationBuilders(org.opensearch.search.aggregations.AggregationBuilders) Entity(org.opensearch.ad.model.Entity) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) Clock(java.time.Clock) ArrayDeque(java.util.ArrayDeque) Comparator(java.util.Comparator) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) ParseUtils(org.opensearch.ad.util.ParseUtils) SearchRequest(org.opensearch.action.search.SearchRequest) Max(org.opensearch.search.aggregations.metrics.Max) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) SearchResponse(org.opensearch.action.search.SearchResponse)

Aggregations

ClientUtil (org.opensearch.ad.util.ClientUtil)20 Client (org.opensearch.client.Client)14 Clock (java.time.Clock)13 ActionListener (org.opensearch.action.ActionListener)12 GetResponse (org.opensearch.action.get.GetResponse)9 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 Before (org.junit.Before)8 GetRequest (org.opensearch.action.get.GetRequest)8 AnomalyDetectionIndices (org.opensearch.ad.indices.AnomalyDetectionIndices)8 ThresholdedRandomCutForestMapper (com.amazon.randomcutforest.parkservices.state.ThresholdedRandomCutForestMapper)7 V1JsonToV2StateConverter (com.amazon.randomcutforest.serialize.json.v1.V1JsonToV2StateConverter)7 RandomCutForestMapper (com.amazon.randomcutforest.state.RandomCutForestMapper)7 Arrays (java.util.Arrays)7 Map (java.util.Map)7 Entry (java.util.Map.Entry)7 Optional (java.util.Optional)7 CountDownLatch (java.util.concurrent.CountDownLatch)7 GenericObjectPool (org.apache.commons.pool2.impl.GenericObjectPool)7 LogManager (org.apache.logging.log4j.LogManager)7