Search in sources :

Example 6 with Client

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

the class StatsAnomalyDetectorTransportAction method getClusterStats.

/**
 * Make async request to get the number of detectors in AnomalyDetector.ANOMALY_DETECTORS_INDEX if necessary
 * and, onResponse, gather the cluster statistics
 *
 * @param client Client
 * @param listener MultiResponsesDelegateActionListener to be used once both requests complete
 * @param adStatsRequest Request containing stats to be retrieved
 */
private void getClusterStats(Client client, MultiResponsesDelegateActionListener<ADStatsResponse> listener, ADStatsRequest adStatsRequest) {
    ADStatsResponse adStatsResponse = new ADStatsResponse();
    if ((adStatsRequest.getStatsToBeRetrieved().contains(StatNames.DETECTOR_COUNT.getName()) || adStatsRequest.getStatsToBeRetrieved().contains(StatNames.SINGLE_ENTITY_DETECTOR_COUNT.getName()) || adStatsRequest.getStatsToBeRetrieved().contains(StatNames.MULTI_ENTITY_DETECTOR_COUNT.getName())) && clusterService.state().getRoutingTable().hasIndex(AnomalyDetector.ANOMALY_DETECTORS_INDEX)) {
        TermsAggregationBuilder termsAgg = AggregationBuilders.terms(DETECTOR_TYPE_AGG).field(AnomalyDetector.DETECTOR_TYPE_FIELD);
        SearchRequest request = new SearchRequest().indices(AnomalyDetector.ANOMALY_DETECTORS_INDEX).source(new SearchSourceBuilder().aggregation(termsAgg).size(0).trackTotalHits(true));
        client.search(request, ActionListener.wrap(r -> {
            StringTerms aggregation = r.getAggregations().get(DETECTOR_TYPE_AGG);
            List<StringTerms.Bucket> buckets = aggregation.getBuckets();
            long totalDetectors = r.getHits().getTotalHits().value;
            long totalSingleEntityDetectors = 0;
            long totalMultiEntityDetectors = 0;
            for (StringTerms.Bucket b : buckets) {
                if (AnomalyDetectorType.SINGLE_ENTITY.name().equals(b.getKeyAsString()) || AnomalyDetectorType.REALTIME_SINGLE_ENTITY.name().equals(b.getKeyAsString()) || AnomalyDetectorType.HISTORICAL_SINGLE_ENTITY.name().equals(b.getKeyAsString())) {
                    totalSingleEntityDetectors += b.getDocCount();
                }
                if (AnomalyDetectorType.MULTI_ENTITY.name().equals(b.getKeyAsString()) || AnomalyDetectorType.REALTIME_MULTI_ENTITY.name().equals(b.getKeyAsString()) || AnomalyDetectorType.HISTORICAL_MULTI_ENTITY.name().equals(b.getKeyAsString())) {
                    totalMultiEntityDetectors += b.getDocCount();
                }
            }
            if (adStatsRequest.getStatsToBeRetrieved().contains(StatNames.DETECTOR_COUNT.getName())) {
                adStats.getStat(StatNames.DETECTOR_COUNT.getName()).setValue(totalDetectors);
            }
            if (adStatsRequest.getStatsToBeRetrieved().contains(StatNames.SINGLE_ENTITY_DETECTOR_COUNT.getName())) {
                adStats.getStat(StatNames.SINGLE_ENTITY_DETECTOR_COUNT.getName()).setValue(totalSingleEntityDetectors);
            }
            if (adStatsRequest.getStatsToBeRetrieved().contains(StatNames.MULTI_ENTITY_DETECTOR_COUNT.getName())) {
                adStats.getStat(StatNames.MULTI_ENTITY_DETECTOR_COUNT.getName()).setValue(totalMultiEntityDetectors);
            }
            adStatsResponse.setClusterStats(getClusterStatsMap(adStatsRequest));
            listener.onResponse(adStatsResponse);
        }, e -> listener.onFailure(e)));
    } else {
        adStatsResponse.setClusterStats(getClusterStatsMap(adStatsRequest));
        listener.onResponse(adStatsResponse);
    }
}
Also used : HandledTransportAction(org.opensearch.action.support.HandledTransportAction) StringTerms(org.opensearch.search.aggregations.bucket.terms.StringTerms) ADStats(org.opensearch.ad.stats.ADStats) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) HashMap(java.util.HashMap) ADStatsResponse(org.opensearch.ad.stats.ADStatsResponse) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) AnomalyDetectorType(org.opensearch.ad.model.AnomalyDetectorType) Map(java.util.Map) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SearchRequest(org.opensearch.action.search.SearchRequest) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) RestHandlerUtils.wrapRestActionListener(org.opensearch.ad.util.RestHandlerUtils.wrapRestActionListener) Client(org.opensearch.client.Client) Set(java.util.Set) Task(org.opensearch.tasks.Task) RestStatus(org.opensearch.rest.RestStatus) TransportService(org.opensearch.transport.TransportService) FAIL_TO_GET_STATS(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_GET_STATS) MultiResponsesDelegateActionListener(org.opensearch.ad.util.MultiResponsesDelegateActionListener) ActionFilters(org.opensearch.action.support.ActionFilters) AggregationBuilders(org.opensearch.search.aggregations.AggregationBuilders) List(java.util.List) Logger(org.apache.logging.log4j.Logger) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) ClusterService(org.opensearch.cluster.service.ClusterService) StatNames(org.opensearch.ad.stats.StatNames) LogManager(org.apache.logging.log4j.LogManager) SearchRequest(org.opensearch.action.search.SearchRequest) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) StringTerms(org.opensearch.search.aggregations.bucket.terms.StringTerms) ADStatsResponse(org.opensearch.ad.stats.ADStatsResponse) List(java.util.List) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder)

Example 7 with Client

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

the class DeleteAnomalyDetectorTransportAction method doExecute.

@Override
protected void doExecute(Task task, DeleteAnomalyDetectorRequest request, ActionListener<DeleteResponse> actionListener) {
    String detectorId = request.getDetectorID();
    LOG.info("Delete anomaly detector job {}", detectorId);
    User user = getUserContext(client);
    ActionListener<DeleteResponse> listener = wrapRestActionListener(actionListener, FAIL_TO_DELETE_DETECTOR);
    // By the time request reaches here, the user permissions are validated by Security plugin.
    try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
        resolveUserAndExecute(user, detectorId, filterByEnabled, listener, (anomalyDetector) -> adTaskManager.getDetector(detectorId, detector -> {
            if (!detector.isPresent()) {
                // In a mixed cluster, if delete detector request routes to node running AD1.0, then it will
                // not delete detector tasks. User can re-delete these deleted detector after cluster upgraded,
                // in that case, the detector is not present.
                LOG.info("Can't find anomaly detector {}", detectorId);
                adTaskManager.deleteADTasks(detectorId, () -> deleteAnomalyDetectorJobDoc(detectorId, listener), listener);
                return;
            }
            // Check if there is realtime job or historical analysis task running. If none of these running, we
            // can delete the detector.
            getDetectorJob(detectorId, listener, () -> {
                adTaskManager.getAndExecuteOnLatestDetectorLevelTask(detectorId, HISTORICAL_DETECTOR_TASK_TYPES, adTask -> {
                    if (adTask.isPresent() && !adTask.get().isDone()) {
                        listener.onFailure(new OpenSearchStatusException("Detector is running", RestStatus.INTERNAL_SERVER_ERROR));
                    } else {
                        adTaskManager.deleteADTasks(detectorId, () -> deleteAnomalyDetectorJobDoc(detectorId, listener), listener);
                    }
                }, transportService, true, listener);
            });
        }, listener), client, clusterService, xContentRegistry);
    } catch (Exception e) {
        LOG.error(e);
        listener.onFailure(e);
    }
}
Also used : HandledTransportAction(org.opensearch.action.support.HandledTransportAction) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) ParseUtils.resolveUserAndExecute(org.opensearch.ad.util.ParseUtils.resolveUserAndExecute) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) AnomalyDetectorFunction(org.opensearch.ad.rest.handler.AnomalyDetectorFunction) XContentParser(org.opensearch.common.xcontent.XContentParser) WriteRequest(org.opensearch.action.support.WriteRequest) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) ParseUtils.getUserContext(org.opensearch.ad.util.ParseUtils.getUserContext) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) DeleteResponse(org.opensearch.action.delete.DeleteResponse) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) GetResponse(org.opensearch.action.get.GetResponse) RestHandlerUtils.wrapRestActionListener(org.opensearch.ad.util.RestHandlerUtils.wrapRestActionListener) DeleteRequest(org.opensearch.action.delete.DeleteRequest) HISTORICAL_DETECTOR_TASK_TYPES(org.opensearch.ad.model.ADTaskType.HISTORICAL_DETECTOR_TASK_TYPES) Client(org.opensearch.client.Client) CommonName(org.opensearch.ad.constant.CommonName) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) FILTER_BY_BACKEND_ROLES(org.opensearch.ad.settings.AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES) GetRequest(org.opensearch.action.get.GetRequest) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) IOException(java.io.IOException) ADTaskManager(org.opensearch.ad.task.ADTaskManager) Settings(org.opensearch.common.settings.Settings) Task(org.opensearch.tasks.Task) RestStatus(org.opensearch.rest.RestStatus) TransportService(org.opensearch.transport.TransportService) ActionFilters(org.opensearch.action.support.ActionFilters) Logger(org.apache.logging.log4j.Logger) FAIL_TO_DELETE_DETECTOR(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_DELETE_DETECTOR) User(org.opensearch.commons.authuser.User) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) DocWriteResponse(org.opensearch.action.DocWriteResponse) LogManager(org.apache.logging.log4j.LogManager) RestHandlerUtils(org.opensearch.ad.util.RestHandlerUtils) User(org.opensearch.commons.authuser.User) DeleteResponse(org.opensearch.action.delete.DeleteResponse) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IOException(java.io.IOException) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Example 8 with Client

use of org.opensearch.client.Client in project k-NN by opensearch-project.

the class TrainingJobRouterTransportActionTests method testMultiNode_withCapacity_withoutPreferredAvailable.

public void testMultiNode_withCapacity_withoutPreferredAvailable() {
    // Mock datanodes in the cluster through mocking the cluster service
    List<String> nodeIds = ImmutableList.of("node-1", "node-2", "node-3");
    String preferredNode = nodeIds.get(2);
    ImmutableOpenMap<String, DiscoveryNode> discoveryNodesMap = generateDiscoveryNodes(nodeIds);
    ClusterService clusterService = generateMockedClusterService(discoveryNodesMap);
    // Create a response to be returned with job route decision info
    List<TrainingJobRouteDecisionInfoNodeResponse> responseList = new ArrayList<>();
    // First node has capacity
    responseList.add(new TrainingJobRouteDecisionInfoNodeResponse(discoveryNodesMap.get(nodeIds.get(0)), 0));
    // Second node has capacity
    responseList.add(new TrainingJobRouteDecisionInfoNodeResponse(discoveryNodesMap.get(nodeIds.get(1)), 0));
    // Third node with no capacity (preferred node)
    responseList.add(new TrainingJobRouteDecisionInfoNodeResponse(discoveryNodesMap.get(nodeIds.get(1)), 1));
    TrainingJobRouteDecisionInfoResponse infoResponse = new TrainingJobRouteDecisionInfoResponse(ClusterName.DEFAULT, responseList, Collections.emptyList());
    TransportService transportService = mock(TransportService.class);
    Client client = mock(Client.class);
    // Setup the action
    TrainingJobRouterTransportAction transportAction = new TrainingJobRouterTransportAction(transportService, new ActionFilters(Collections.emptySet()), clusterService, client);
    // Select the node
    DiscoveryNode selectedNode = transportAction.selectNode(preferredNode, infoResponse);
    assertNotNull(selectedNode);
    assertNotEquals(preferredNode, selectedNode.getId());
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ArrayList(java.util.ArrayList) ActionFilters(org.opensearch.action.support.ActionFilters) ClusterService(org.opensearch.cluster.service.ClusterService) TransportService(org.opensearch.transport.TransportService) Client(org.opensearch.client.Client)

Example 9 with Client

use of org.opensearch.client.Client in project k-NN by opensearch-project.

the class TrainingJobRouterTransportActionTests method testSingleNode_withoutCapacity.

public void testSingleNode_withoutCapacity() {
    // Mock datanodes in the cluster through mocking the cluster service
    List<String> nodeIds = ImmutableList.of("node-1");
    ImmutableOpenMap<String, DiscoveryNode> discoveryNodesMap = generateDiscoveryNodes(nodeIds);
    ClusterService clusterService = generateMockedClusterService(discoveryNodesMap);
    // Create a response to be returned with job route decision info
    List<TrainingJobRouteDecisionInfoNodeResponse> responseList = new ArrayList<>();
    nodeIds.forEach(id -> responseList.add(new TrainingJobRouteDecisionInfoNodeResponse(discoveryNodesMap.get(id), // node has no capacity
    1)));
    TrainingJobRouteDecisionInfoResponse infoResponse = new TrainingJobRouteDecisionInfoResponse(ClusterName.DEFAULT, responseList, Collections.emptyList());
    TransportService transportService = mock(TransportService.class);
    Client client = mock(Client.class);
    // Setup the action
    TrainingJobRouterTransportAction transportAction = new TrainingJobRouterTransportAction(transportService, new ActionFilters(Collections.emptySet()), clusterService, client);
    // Select the node
    DiscoveryNode selectedNode = transportAction.selectNode(null, infoResponse);
    assertNull(selectedNode);
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ArrayList(java.util.ArrayList) ActionFilters(org.opensearch.action.support.ActionFilters) ClusterService(org.opensearch.cluster.service.ClusterService) TransportService(org.opensearch.transport.TransportService) Client(org.opensearch.client.Client)

Example 10 with Client

use of org.opensearch.client.Client in project k-NN by opensearch-project.

the class TrainingJobRouterTransportActionTests method testMultiNode_withCapacity_withPreferredAvailable.

public void testMultiNode_withCapacity_withPreferredAvailable() {
    // Mock datanodes in the cluster through mocking the cluster service
    List<String> nodeIds = ImmutableList.of("node-1", "node-2", "node-3");
    String preferredNode = nodeIds.get(2);
    ImmutableOpenMap<String, DiscoveryNode> discoveryNodesMap = generateDiscoveryNodes(nodeIds);
    ClusterService clusterService = generateMockedClusterService(discoveryNodesMap);
    // Create a response to be returned with job route decision info
    List<TrainingJobRouteDecisionInfoNodeResponse> responseList = new ArrayList<>();
    // First node has capacity
    responseList.add(new TrainingJobRouteDecisionInfoNodeResponse(discoveryNodesMap.get(nodeIds.get(0)), 0));
    // Second node has capacity
    responseList.add(new TrainingJobRouteDecisionInfoNodeResponse(discoveryNodesMap.get(nodeIds.get(1)), 0));
    // Third node with capacity
    responseList.add(new TrainingJobRouteDecisionInfoNodeResponse(discoveryNodesMap.get(nodeIds.get(2)), 0));
    TrainingJobRouteDecisionInfoResponse infoResponse = new TrainingJobRouteDecisionInfoResponse(ClusterName.DEFAULT, responseList, Collections.emptyList());
    TransportService transportService = mock(TransportService.class);
    Client client = mock(Client.class);
    // Setup the action
    TrainingJobRouterTransportAction transportAction = new TrainingJobRouterTransportAction(transportService, new ActionFilters(Collections.emptySet()), clusterService, client);
    // Select the node
    DiscoveryNode selectedNode = transportAction.selectNode(preferredNode, infoResponse);
    assertEquals(preferredNode, selectedNode.getId());
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ArrayList(java.util.ArrayList) ActionFilters(org.opensearch.action.support.ActionFilters) ClusterService(org.opensearch.cluster.service.ClusterService) TransportService(org.opensearch.transport.TransportService) Client(org.opensearch.client.Client)

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