Search in sources :

Example 6 with TestThreadPool

use of org.opensearch.threadpool.TestThreadPool in project asynchronous-search by opensearch-project.

the class AsynchronousSearchPartialResponseIT method testCase.

private void testCase(Client client, SearchRequest request) throws Exception {
    AtomicReference<SearchResponse> responseRef = new AtomicReference<>();
    AtomicInteger reduceContextInvocation = new AtomicInteger();
    TestThreadPool threadPool = null;
    AsynchronousSearchProgressListener listener;
    try {
        threadPool = new TestThreadPool(AsynchronousSearchProgressListenerIT.class.getName());
        SearchService service = internalCluster().getInstance(SearchService.class);
        InternalAggregation.ReduceContextBuilder reduceContextBuilder = service.aggReduceContextBuilder(request);
        AtomicReference<Exception> exceptionRef = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(1);
        Function<SearchResponse, AsynchronousSearchResponse> responseFunction = (r) -> null;
        Function<Exception, AsynchronousSearchResponse> failureFunction = (e) -> null;
        listener = new AsynchronousSearchProgressListener(threadPool.relativeTimeInMillis(), responseFunction, failureFunction, threadPool.generic(), threadPool::relativeTimeInMillis, () -> reduceContextBuilder) {

            @Override
            public void onResponse(SearchResponse searchResponse) {
                assertTrue(responseRef.compareAndSet(null, searchResponse));
                AsynchronousSearchAssertions.assertSearchResponses(responseRef.get(), this.partialResponse());
                latch.countDown();
            }

            @Override
            protected void onPartialReduce(List<SearchShard> shards, TotalHits totalHits, InternalAggregations aggs, int reducePhase) {
                super.onPartialReduce(shards, totalHits, aggs, reducePhase);
                Terms terms = this.partialResponse().getAggregations().get("keys");
                List<? extends Terms.Bucket> buckets = terms.getBuckets();
                assertThat(buckets.size(), lessThanOrEqualTo(aggregationSize));
                reduceContextInvocation.incrementAndGet();
            }

            @Override
            protected void onFinalReduce(List<SearchShard> shards, TotalHits totalHits, InternalAggregations aggs, int reducePhase) {
                super.onFinalReduce(shards, totalHits, aggs, reducePhase);
                Terms terms = this.partialResponse().getAggregations().get("keys");
                List<? extends Terms.Bucket> buckets = terms.getBuckets();
                assertThat(buckets.size(), equalTo(aggregationSize));
            }

            @Override
            public void onFailure(Exception exception) {
                assertTrue(exceptionRef.compareAndSet(null, exception));
                latch.countDown();
            }
        };
        client.execute(SearchAction.INSTANCE, new SearchRequest(request) {

            @Override
            public SearchTask createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) {
                SearchTask task = super.createTask(id, type, action, parentTaskId, headers);
                task.setProgressListener(listener);
                return task;
            }
        }, listener);
        latch.await();
        Terms terms = responseRef.get().getAggregations().get("keys");
        assertThat(reduceContextInvocation.get(), equalTo(responseRef.get().getNumReducePhases() - 1));
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        assertThat(buckets.size(), equalTo(aggregationSize));
    } finally {
        ThreadPool.terminate(threadPool, 100, TimeUnit.MILLISECONDS);
    }
}
Also used : AsynchronousSearchResponse(org.opensearch.search.asynchronous.response.AsynchronousSearchResponse) IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) SearchAction(org.opensearch.action.search.SearchAction) AsynchronousSearchAssertions(org.opensearch.search.asynchronous.utils.AsynchronousSearchAssertions) XContentFactory.jsonBuilder(org.opensearch.common.xcontent.XContentFactory.jsonBuilder) BucketOrder(org.opensearch.search.aggregations.BucketOrder) Arrays(java.util.Arrays) ThreadPool(org.opensearch.threadpool.ThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool) OpenSearchAssertions.assertSearchResponse(org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse) AsynchronousSearchResponse(org.opensearch.search.asynchronous.response.AsynchronousSearchResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) AggregationBuilders.terms(org.opensearch.search.aggregations.AggregationBuilders.terms) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) QueryBuilders.matchAllQuery(org.opensearch.index.query.QueryBuilders.matchAllQuery) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) Map(java.util.Map) SearchRequest(org.opensearch.action.search.SearchRequest) SearchResponse(org.opensearch.action.search.SearchResponse) SearchService(org.opensearch.search.SearchService) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) Client(org.opensearch.client.Client) SearchTask(org.opensearch.action.search.SearchTask) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) TaskId(org.opensearch.tasks.TaskId) Terms(org.opensearch.search.aggregations.bucket.terms.Terms) SearchShard(org.opensearch.action.search.SearchShard) TotalHits(org.apache.lucene.search.TotalHits) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Matchers.is(org.hamcrest.Matchers.is) Aggregator(org.opensearch.search.aggregations.Aggregator) InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) TotalHits(org.apache.lucene.search.TotalHits) SearchRequest(org.opensearch.action.search.SearchRequest) TaskId(org.opensearch.tasks.TaskId) TestThreadPool(org.opensearch.threadpool.TestThreadPool) SearchTask(org.opensearch.action.search.SearchTask) SearchService(org.opensearch.search.SearchService) ArrayList(java.util.ArrayList) List(java.util.List) SearchShard(org.opensearch.action.search.SearchShard) Terms(org.opensearch.search.aggregations.bucket.terms.Terms) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) OpenSearchAssertions.assertSearchResponse(org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse) AsynchronousSearchResponse(org.opensearch.search.asynchronous.response.AsynchronousSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse) InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 7 with TestThreadPool

use of org.opensearch.threadpool.TestThreadPool in project asynchronous-search by opensearch-project.

the class AsynchronousSearchActiveContextTests method testInitializeContext.

public void testInitializeContext() {
    TestThreadPool threadPool = null;
    try {
        int writeThreadPoolSize = randomIntBetween(1, 2);
        int writeThreadPoolQueueSize = randomIntBetween(1, 2);
        Settings settings = Settings.builder().put("thread_pool." + AsynchronousSearchPlugin.OPEN_DISTRO_ASYNC_SEARCH_GENERIC_THREAD_POOL_NAME + ".size", writeThreadPoolSize).put("thread_pool." + AsynchronousSearchPlugin.OPEN_DISTRO_ASYNC_SEARCH_GENERIC_THREAD_POOL_NAME + ".queue_size", writeThreadPoolQueueSize).build();
        final int availableProcessors = OpenSearchExecutors.allocatedProcessors(settings);
        ScalingExecutorBuilder scalingExecutorBuilder = new ScalingExecutorBuilder(AsynchronousSearchPlugin.OPEN_DISTRO_ASYNC_SEARCH_GENERIC_THREAD_POOL_NAME, 1, Math.min(2 * availableProcessors, Math.max(128, 512)), TimeValue.timeValueMinutes(30));
        threadPool = new TestThreadPool("Tests", settings, scalingExecutorBuilder);
        String node = UUID.randomUUID().toString();
        AsynchronousSearchProgressListener asProgressListener = mockAsynchronousSearchProgressListener(threadPool);
        AsynchronousSearchContextId asContextId = new AsynchronousSearchContextId(UUID.randomUUID().toString(), randomNonNegativeLong());
        boolean keepOnCompletion = randomBoolean();
        User user = TestClientUtils.randomUser();
        TimeValue keepAlive = TimeValue.timeValueDays(randomInt(100));
        AsynchronousSearchActiveContext context = new AsynchronousSearchActiveContext(asContextId, node, keepAlive, keepOnCompletion, threadPool, threadPool::absoluteTimeInMillis, asProgressListener, user, () -> true);
        assertEquals(AsynchronousSearchState.INIT, context.getAsynchronousSearchState());
        assertNull(context.getTask());
        assertNull(context.getAsynchronousSearchId());
        assertEquals(context.getAsynchronousSearchState(), AsynchronousSearchState.INIT);
    } finally {
        ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS);
    }
}
Also used : ScalingExecutorBuilder(org.opensearch.threadpool.ScalingExecutorBuilder) User(org.opensearch.commons.authuser.User) AsynchronousSearchContextId(org.opensearch.search.asynchronous.context.AsynchronousSearchContextId) Matchers.containsString(org.hamcrest.Matchers.containsString) TestThreadPool(org.opensearch.threadpool.TestThreadPool) Settings(org.opensearch.common.settings.Settings) TimeValue(org.opensearch.common.unit.TimeValue) AsynchronousSearchProgressListener(org.opensearch.search.asynchronous.listener.AsynchronousSearchProgressListener)

Example 8 with TestThreadPool

use of org.opensearch.threadpool.TestThreadPool in project asynchronous-search by opensearch-project.

the class AsynchronousSearchActiveStoreTests method testGetNonExistentContext.

public void testGetNonExistentContext() {
    DiscoveryNode node = new DiscoveryNode("node", OpenSearchTestCase.buildNewFakeTransportAddress(), Collections.emptyMap(), DiscoveryNodeRole.BUILT_IN_ROLES, Version.CURRENT);
    ThreadPool testThreadPool = null;
    try {
        testThreadPool = new TestThreadPool(this.getClass().getName(), executorBuilder);
        ClusterService mockClusterService = ClusterServiceUtils.createClusterService(testThreadPool, node, clusterSettings);
        AsynchronousSearchActiveStore activeStore = new AsynchronousSearchActiveStore(mockClusterService);
        AsynchronousSearchContextId asContextId = new AsynchronousSearchContextId(UUID.randomUUID().toString(), randomNonNegativeLong());
        Optional<AsynchronousSearchActiveContext> optional = activeStore.getContext(asContextId);
        assertFalse(optional.isPresent());
        assertEquals(activeStore.getAllContexts().size(), 0);
    } finally {
        ThreadPool.terminate(testThreadPool, 10, TimeUnit.SECONDS);
    }
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ClusterService(org.opensearch.cluster.service.ClusterService) AsynchronousSearchContextId(org.opensearch.search.asynchronous.context.AsynchronousSearchContextId) ThreadPool(org.opensearch.threadpool.ThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool)

Example 9 with TestThreadPool

use of org.opensearch.threadpool.TestThreadPool in project asynchronous-search by opensearch-project.

the class AsynchronousSearchContextPermitsTests method setupThreadPool.

@BeforeClass
public static void setupThreadPool() {
    int writeThreadPoolSize = randomIntBetween(1, 2);
    int writeThreadPoolQueueSize = randomIntBetween(1, 2);
    Settings settings = Settings.builder().put("thread_pool." + AsynchronousSearchPlugin.OPEN_DISTRO_ASYNC_SEARCH_GENERIC_THREAD_POOL_NAME + ".size", writeThreadPoolSize).put("thread_pool." + AsynchronousSearchPlugin.OPEN_DISTRO_ASYNC_SEARCH_GENERIC_THREAD_POOL_NAME + ".queue_size", writeThreadPoolQueueSize).build();
    final int availableProcessors = OpenSearchExecutors.allocatedProcessors(settings);
    ScalingExecutorBuilder scalingExecutorBuilder = new ScalingExecutorBuilder(AsynchronousSearchPlugin.OPEN_DISTRO_ASYNC_SEARCH_GENERIC_THREAD_POOL_NAME, 1, Math.min(2 * availableProcessors, Math.max(128, 512)), TimeValue.timeValueMinutes(30));
    threadPool = new TestThreadPool("PermitsTests", settings, scalingExecutorBuilder);
}
Also used : ScalingExecutorBuilder(org.opensearch.threadpool.ScalingExecutorBuilder) TestThreadPool(org.opensearch.threadpool.TestThreadPool) Settings(org.opensearch.common.settings.Settings) BeforeClass(org.junit.BeforeClass)

Example 10 with TestThreadPool

use of org.opensearch.threadpool.TestThreadPool in project asynchronous-search by opensearch-project.

the class AsynchronousSearchServiceFreeContextTests method testFreeContextPermitAcquisitionFailure.

public void testFreeContextPermitAcquisitionFailure() throws InterruptedException {
    DiscoveryNode discoveryNode = new DiscoveryNode("node", OpenSearchTestCase.buildNewFakeTransportAddress(), emptyMap(), DiscoveryNodeRole.BUILT_IN_ROLES, Version.CURRENT);
    ThreadPool testThreadPool = null;
    try {
        testThreadPool = new TestThreadPool(OPEN_DISTRO_ASYNC_SEARCH_GENERIC_THREAD_POOL_NAME, executorBuilder);
        ClusterService mockClusterService = getClusterService(discoveryNode, testThreadPool);
        MockClient mockClient = new MockClient(testThreadPool);
        AsynchronousSearchActiveStore mockStore = mock(AsynchronousSearchActiveStore.class);
        AsynchronousSearchPersistenceService persistenceService = new AsynchronousSearchPersistenceService(mockClient, mockClusterService, testThreadPool);
        AsynchronousSearchService asService = new AsynchronousSearchService(persistenceService, mockStore, mockClient, mockClusterService, testThreadPool, new InternalAsynchronousSearchStats(), new NamedWriteableRegistry(emptyList()));
        TimeValue keepAlive = timeValueDays(9);
        boolean keepOnCompletion = true;
        User user1 = randomBoolean() ? randomUser() : null;
        SearchRequest searchRequest = new SearchRequest();
        SubmitAsynchronousSearchRequest submitAsynchronousSearchRequest = new SubmitAsynchronousSearchRequest(searchRequest);
        submitAsynchronousSearchRequest.keepOnCompletion(keepOnCompletion);
        submitAsynchronousSearchRequest.keepAlive(keepAlive);
        AsynchronousSearchProgressListener asProgressListener = mockAsynchronousSearchProgressListener(testThreadPool);
        AsynchronousSearchContextId asContextId = new AsynchronousSearchContextId(UUID.randomUUID().toString(), randomNonNegativeLong());
        MockAsynchronousSearchActiveContext asActiveContext = new MockAsynchronousSearchActiveContext(asContextId, discoveryNode.getId(), keepAlive, true, testThreadPool, testThreadPool::absoluteTimeInMillis, asProgressListener, user1);
        // bootstrap search
        AsynchronousSearchTask task = new AsynchronousSearchTask(randomNonNegativeLong(), "transport", SearchAction.NAME, TaskId.EMPTY_TASK_ID, emptyMap(), asActiveContext, null, (c) -> {
        });
        asActiveContext.setTask(task);
        simulateUncheckedException = true;
        persisted = false;
        when(mockStore.getContext(asContextId)).thenReturn(Optional.of(asActiveContext));
        CountDownLatch latch = new CountDownLatch(1);
        asService.freeContext(asActiveContext.getAsynchronousSearchId(), asActiveContext.getContextId(), null, new LatchedActionListener<>(wrap(r -> fail("Expected resource_not_found_exception. Got acknowledgement " + r), e -> {
            assertTrue(e.getClass().getName(), e instanceof ResourceNotFoundException);
        }), latch));
        latch.await();
        assertEquals(1, (int) mockClient.deleteCount);
        mockClusterService.stop();
    } finally {
        ThreadPool.terminate(testThreadPool, 30, TimeUnit.SECONDS);
    }
}
Also used : NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) SubmitAsynchronousSearchRequest(org.opensearch.search.asynchronous.request.SubmitAsynchronousSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) TestClientUtils.randomUser(org.opensearch.search.asynchronous.utils.TestClientUtils.randomUser) User(org.opensearch.commons.authuser.User) SubmitAsynchronousSearchRequest(org.opensearch.search.asynchronous.request.SubmitAsynchronousSearchRequest) AsynchronousSearchContextId(org.opensearch.search.asynchronous.context.AsynchronousSearchContextId) TestThreadPool(org.opensearch.threadpool.TestThreadPool) ThreadPool(org.opensearch.threadpool.ThreadPool) InternalAsynchronousSearchStats(org.opensearch.search.asynchronous.stats.InternalAsynchronousSearchStats) TestThreadPool(org.opensearch.threadpool.TestThreadPool) CountDownLatch(java.util.concurrent.CountDownLatch) AsynchronousSearchActiveStore(org.opensearch.search.asynchronous.context.active.AsynchronousSearchActiveStore) AsynchronousSearchProgressListener(org.opensearch.search.asynchronous.listener.AsynchronousSearchProgressListener) AsynchronousSearchTestCase.mockAsynchronousSearchProgressListener(org.opensearch.search.asynchronous.commons.AsynchronousSearchTestCase.mockAsynchronousSearchProgressListener) AsynchronousSearchTask(org.opensearch.search.asynchronous.task.AsynchronousSearchTask) ClusterService(org.opensearch.cluster.service.ClusterService) ResourceNotFoundException(org.opensearch.ResourceNotFoundException) TimeValue(org.opensearch.common.unit.TimeValue)

Aggregations

TestThreadPool (org.opensearch.threadpool.TestThreadPool)151 ThreadPool (org.opensearch.threadpool.ThreadPool)79 ClusterService (org.opensearch.cluster.service.ClusterService)55 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)52 CountDownLatch (java.util.concurrent.CountDownLatch)50 TimeValue (org.opensearch.common.unit.TimeValue)43 Settings (org.opensearch.common.settings.Settings)41 Before (org.junit.Before)40 SearchRequest (org.opensearch.action.search.SearchRequest)37 NamedWriteableRegistry (org.opensearch.common.io.stream.NamedWriteableRegistry)33 SubmitAsynchronousSearchRequest (org.opensearch.search.asynchronous.request.SubmitAsynchronousSearchRequest)32 AsynchronousSearchActiveStore (org.opensearch.search.asynchronous.context.active.AsynchronousSearchActiveStore)31 InternalAsynchronousSearchStats (org.opensearch.search.asynchronous.stats.InternalAsynchronousSearchStats)30 ArrayList (java.util.ArrayList)27 AsynchronousSearchContextId (org.opensearch.search.asynchronous.context.AsynchronousSearchContextId)24 AsynchronousSearchTask (org.opensearch.search.asynchronous.task.AsynchronousSearchTask)24 User (org.opensearch.commons.authuser.User)22 AsynchronousSearchActiveContext (org.opensearch.search.asynchronous.context.active.AsynchronousSearchActiveContext)21 TimeUnit (java.util.concurrent.TimeUnit)20 AsynchronousSearchProgressListener (org.opensearch.search.asynchronous.listener.AsynchronousSearchProgressListener)20