Search in sources :

Example 26 with TransportService

use of org.elasticsearch.transport.TransportService in project elasticsearch by elastic.

the class TransportBulkActionIngestTests method testIngestLocal.

public void testIngestLocal() throws Exception {
    Exception exception = new Exception("fake exception");
    BulkRequest bulkRequest = new BulkRequest();
    IndexRequest indexRequest1 = new IndexRequest("index", "type", "id");
    indexRequest1.source(Collections.emptyMap());
    indexRequest1.setPipeline("testpipeline");
    IndexRequest indexRequest2 = new IndexRequest("index", "type", "id");
    indexRequest2.source(Collections.emptyMap());
    indexRequest2.setPipeline("testpipeline");
    bulkRequest.add(indexRequest1);
    bulkRequest.add(indexRequest2);
    AtomicBoolean responseCalled = new AtomicBoolean(false);
    AtomicBoolean failureCalled = new AtomicBoolean(false);
    action.execute(null, bulkRequest, ActionListener.wrap(response -> {
        BulkItemResponse itemResponse = response.iterator().next();
        assertThat(itemResponse.getFailure().getMessage(), containsString("fake exception"));
        responseCalled.set(true);
    }, e -> {
        assertThat(e, sameInstance(exception));
        failureCalled.set(true);
    }));
    // check failure works, and passes through to the listener
    // haven't executed yet
    assertFalse(action.isExecuted);
    assertFalse(responseCalled.get());
    assertFalse(failureCalled.get());
    verify(executionService).executeBulkRequest(bulkDocsItr.capture(), failureHandler.capture(), completionHandler.capture());
    completionHandler.getValue().accept(exception);
    assertTrue(failureCalled.get());
    // now check success
    Iterator<DocWriteRequest> req = bulkDocsItr.getValue().iterator();
    // have an exception for our one index request
    failureHandler.getValue().accept((IndexRequest) req.next(), exception);
    // this is done by the real pipeline execution service when processing
    indexRequest2.setPipeline(null);
    completionHandler.getValue().accept(null);
    assertTrue(action.isExecuted);
    // listener would only be called by real index action, not our mocked one
    assertFalse(responseCalled.get());
    verifyZeroInteractions(transportService);
}
Also used : IngestService(org.elasticsearch.ingest.IngestService) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) PipelineExecutionService(org.elasticsearch.ingest.PipelineExecutionService) ClusterService(org.elasticsearch.cluster.service.ClusterService) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Captor(org.mockito.Captor) Supplier(java.util.function.Supplier) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) MockitoAnnotations(org.mockito.MockitoAnnotations) IndexRequest(org.elasticsearch.action.index.IndexRequest) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Settings(org.elasticsearch.common.settings.Settings) ArgumentCaptor(org.mockito.ArgumentCaptor) Matchers.eq(org.mockito.Matchers.eq) Mockito.doAnswer(org.mockito.Mockito.doAnswer) BiConsumer(java.util.function.BiConsumer) IndexResponse(org.elasticsearch.action.index.IndexResponse) ThreadPool(org.elasticsearch.threadpool.ThreadPool) IndicesService(org.elasticsearch.indices.IndicesService) ESTestCase(org.elasticsearch.test.ESTestCase) TransportService(org.elasticsearch.transport.TransportService) ClusterStateApplier(org.elasticsearch.cluster.ClusterStateApplier) Before(org.junit.Before) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) ActionFilters(org.elasticsearch.action.support.ActionFilters) Iterator(java.util.Iterator) AtomicArray(org.elasticsearch.common.util.concurrent.AtomicArray) Mockito.when(org.mockito.Mockito.when) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) ClusterChangedEvent(org.elasticsearch.cluster.ClusterChangedEvent) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) Matchers.any(org.mockito.Matchers.any) IndexAction(org.elasticsearch.action.index.IndexAction) Mockito.never(org.mockito.Mockito.never) Matchers.sameInstance(org.hamcrest.Matchers.sameInstance) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) Task(org.elasticsearch.tasks.Task) Collections(java.util.Collections) Matchers.containsString(org.hamcrest.Matchers.containsString) Mockito.reset(org.mockito.Mockito.reset) ActionListener(org.elasticsearch.action.ActionListener) Mockito.mock(org.mockito.Mockito.mock) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IndexRequest(org.elasticsearch.action.index.IndexRequest) DocWriteRequest(org.elasticsearch.action.DocWriteRequest)

Example 27 with TransportService

use of org.elasticsearch.transport.TransportService in project elasticsearch by elastic.

the class TransportBulkActionTookTests method createAction.

private TransportBulkAction createAction(boolean controlled, AtomicLong expected) {
    CapturingTransport capturingTransport = new CapturingTransport();
    TransportService transportService = new TransportService(clusterService.getSettings(), capturingTransport, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, boundAddress -> clusterService.localNode(), null);
    transportService.start();
    transportService.acceptIncomingRequests();
    IndexNameExpressionResolver resolver = new Resolver(Settings.EMPTY);
    ActionFilters actionFilters = new ActionFilters(new HashSet<>());
    TransportCreateIndexAction createIndexAction = new TransportCreateIndexAction(Settings.EMPTY, transportService, clusterService, threadPool, null, actionFilters, resolver);
    if (controlled) {
        return new TestTransportBulkAction(Settings.EMPTY, threadPool, transportService, clusterService, null, createIndexAction, actionFilters, resolver, null, expected::get) {

            @Override
            void executeBulk(Task task, BulkRequest bulkRequest, long startTimeNanos, ActionListener<BulkResponse> listener, AtomicArray<BulkItemResponse> responses) {
                expected.set(1000000);
                super.executeBulk(task, bulkRequest, startTimeNanos, listener, responses);
            }
        };
    } else {
        return new TestTransportBulkAction(Settings.EMPTY, threadPool, transportService, clusterService, null, createIndexAction, actionFilters, resolver, null, System::nanoTime) {

            @Override
            void executeBulk(Task task, BulkRequest bulkRequest, long startTimeNanos, ActionListener<BulkResponse> listener, AtomicArray<BulkItemResponse> responses) {
                long elapsed = spinForAtLeastOneMillisecond();
                expected.set(elapsed);
                super.executeBulk(task, bulkRequest, startTimeNanos, listener, responses);
            }
        };
    }
}
Also used : Task(org.elasticsearch.tasks.Task) AtomicArray(org.elasticsearch.common.util.concurrent.AtomicArray) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) ActionFilters(org.elasticsearch.action.support.ActionFilters) TransportCreateIndexAction(org.elasticsearch.action.admin.indices.create.TransportCreateIndexAction) ActionListener(org.elasticsearch.action.ActionListener) TransportService(org.elasticsearch.transport.TransportService) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver)

Example 28 with TransportService

use of org.elasticsearch.transport.TransportService in project elasticsearch by elastic.

the class TransportMultiSearchActionTests method testBatchExecute.

public void testBatchExecute() throws Exception {
    // Initialize dependencies of TransportMultiSearchAction
    Settings settings = Settings.builder().put("node.name", TransportMultiSearchActionTests.class.getSimpleName()).build();
    ActionFilters actionFilters = mock(ActionFilters.class);
    when(actionFilters.filters()).thenReturn(new ActionFilter[0]);
    ThreadPool threadPool = new ThreadPool(settings);
    TaskManager taskManager = mock(TaskManager.class);
    TransportService transportService = new TransportService(Settings.EMPTY, null, null, TransportService.NOOP_TRANSPORT_INTERCEPTOR, boundAddress -> DiscoveryNode.createLocal(settings, boundAddress.publishAddress(), UUIDs.randomBase64UUID()), null) {

        @Override
        public TaskManager getTaskManager() {
            return taskManager;
        }
    };
    ClusterService clusterService = mock(ClusterService.class);
    when(clusterService.state()).thenReturn(ClusterState.builder(new ClusterName("test")).build());
    IndexNameExpressionResolver resolver = new IndexNameExpressionResolver(Settings.EMPTY);
    // Keep track of the number of concurrent searches started by multi search api,
    // and if there are more searches than is allowed create an error and remember that.
    int maxAllowedConcurrentSearches = scaledRandomIntBetween(1, 16);
    AtomicInteger counter = new AtomicInteger();
    AtomicReference<AssertionError> errorHolder = new AtomicReference<>();
    // randomize whether or not requests are executed asynchronously
    final List<String> threadPoolNames = Arrays.asList(ThreadPool.Names.GENERIC, ThreadPool.Names.SAME);
    Randomness.shuffle(threadPoolNames);
    final ExecutorService commonExecutor = threadPool.executor(threadPoolNames.get(0));
    final ExecutorService rarelyExecutor = threadPool.executor(threadPoolNames.get(1));
    final Set<SearchRequest> requests = Collections.newSetFromMap(Collections.synchronizedMap(new IdentityHashMap<>()));
    TransportAction<SearchRequest, SearchResponse> searchAction = new TransportAction<SearchRequest, SearchResponse>(Settings.EMPTY, "action", threadPool, actionFilters, resolver, taskManager) {

        @Override
        protected void doExecute(SearchRequest request, ActionListener<SearchResponse> listener) {
            requests.add(request);
            int currentConcurrentSearches = counter.incrementAndGet();
            if (currentConcurrentSearches > maxAllowedConcurrentSearches) {
                errorHolder.set(new AssertionError("Current concurrent search [" + currentConcurrentSearches + "] is higher than is allowed [" + maxAllowedConcurrentSearches + "]"));
            }
            final ExecutorService executorService = rarely() ? rarelyExecutor : commonExecutor;
            executorService.execute(() -> {
                counter.decrementAndGet();
                listener.onResponse(new SearchResponse());
            });
        }
    };
    TransportMultiSearchAction action = new TransportMultiSearchAction(threadPool, actionFilters, transportService, clusterService, searchAction, resolver, 10);
    // Execute the multi search api and fail if we find an error after executing:
    try {
        /*
             * Allow for a large number of search requests in a single batch as previous implementations could stack overflow if the number
             * of requests in a single batch was large
             */
        int numSearchRequests = scaledRandomIntBetween(1, 8192);
        MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
        multiSearchRequest.maxConcurrentSearchRequests(maxAllowedConcurrentSearches);
        for (int i = 0; i < numSearchRequests; i++) {
            multiSearchRequest.add(new SearchRequest());
        }
        MultiSearchResponse response = action.execute(multiSearchRequest).actionGet();
        assertThat(response.getResponses().length, equalTo(numSearchRequests));
        assertThat(requests.size(), equalTo(numSearchRequests));
        assertThat(errorHolder.get(), nullValue());
    } finally {
        assertTrue(ESTestCase.terminate(threadPool));
    }
}
Also used : IdentityHashMap(java.util.IdentityHashMap) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) Settings(org.elasticsearch.common.settings.Settings) AtomicReference(java.util.concurrent.atomic.AtomicReference) ActionFilters(org.elasticsearch.action.support.ActionFilters) TransportAction(org.elasticsearch.action.support.TransportAction) TaskManager(org.elasticsearch.tasks.TaskManager) ClusterService(org.elasticsearch.cluster.service.ClusterService) ActionListener(org.elasticsearch.action.ActionListener) TransportService(org.elasticsearch.transport.TransportService) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver)

Example 29 with TransportService

use of org.elasticsearch.transport.TransportService in project elasticsearch by elastic.

the class TransportNodesActionTests method setUp.

@Before
public void setUp() throws Exception {
    super.setUp();
    transport = new CapturingTransport();
    clusterService = createClusterService(THREAD_POOL);
    transportService = new TransportService(clusterService.getSettings(), transport, THREAD_POOL, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null);
    transportService.start();
    transportService.acceptIncomingRequests();
    int numNodes = randomIntBetween(3, 10);
    DiscoveryNodes.Builder discoBuilder = DiscoveryNodes.builder();
    List<DiscoveryNode> discoveryNodes = new ArrayList<>();
    for (int i = 0; i < numNodes; i++) {
        Map<String, String> attributes = new HashMap<>();
        Set<DiscoveryNode.Role> roles = new HashSet<>(randomSubsetOf(Arrays.asList(DiscoveryNode.Role.values())));
        if (frequently()) {
            attributes.put("custom", randomBoolean() ? "match" : randomAsciiOfLengthBetween(3, 5));
        }
        final DiscoveryNode node = newNode(i, attributes, roles);
        discoBuilder = discoBuilder.add(node);
        discoveryNodes.add(node);
    }
    discoBuilder.localNodeId(randomFrom(discoveryNodes).getId());
    discoBuilder.masterNodeId(randomFrom(discoveryNodes).getId());
    ClusterState.Builder stateBuilder = ClusterState.builder(clusterService.getClusterName());
    stateBuilder.nodes(discoBuilder);
    ClusterState clusterState = stateBuilder.build();
    setState(clusterService, clusterState);
}
Also used : StreamOutput(org.elasticsearch.common.io.stream.StreamOutput) Arrays(java.util.Arrays) FailedNodeException(org.elasticsearch.action.FailedNodeException) BeforeClass(org.junit.BeforeClass) ClusterServiceUtils.createClusterService(org.elasticsearch.test.ClusterServiceUtils.createClusterService) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) Supplier(java.util.function.Supplier) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) ArrayList(java.util.ArrayList) AtomicReferenceArray(java.util.concurrent.atomic.AtomicReferenceArray) HashSet(java.util.HashSet) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Settings(org.elasticsearch.common.settings.Settings) After(org.junit.After) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) ESTestCase(org.elasticsearch.test.ESTestCase) TransportService(org.elasticsearch.transport.TransportService) Before(org.junit.Before) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) AfterClass(org.junit.AfterClass) ActionFilters(org.elasticsearch.action.support.ActionFilters) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) Set(java.util.Set) IOException(java.io.IOException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Version(org.elasticsearch.Version) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Collections(java.util.Collections) ClusterServiceUtils.setState(org.elasticsearch.test.ClusterServiceUtils.setState) TransportBroadcastByNodeActionTests(org.elasticsearch.action.support.broadcast.node.TransportBroadcastByNodeActionTests) Mockito.mock(org.mockito.Mockito.mock) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) HashMap(java.util.HashMap) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) ArrayList(java.util.ArrayList) TransportService(org.elasticsearch.transport.TransportService) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) HashSet(java.util.HashSet) Before(org.junit.Before)

Example 30 with TransportService

use of org.elasticsearch.transport.TransportService in project elasticsearch by elastic.

the class UnicastZenPingTests method testInvalidHosts.

public void testInvalidHosts() throws InterruptedException {
    final Logger logger = mock(Logger.class);
    final NetworkService networkService = new NetworkService(Settings.EMPTY, Collections.emptyList());
    final Transport transport = new MockTcpTransport(Settings.EMPTY, threadPool, BigArrays.NON_RECYCLING_INSTANCE, new NoneCircuitBreakerService(), new NamedWriteableRegistry(Collections.emptyList()), networkService, Version.CURRENT) {

        @Override
        public BoundTransportAddress boundAddress() {
            return new BoundTransportAddress(new TransportAddress[] { new TransportAddress(InetAddress.getLoopbackAddress(), 9300) }, new TransportAddress(InetAddress.getLoopbackAddress(), 9300));
        }
    };
    closeables.push(transport);
    final TransportService transportService = new TransportService(Settings.EMPTY, transport, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null);
    closeables.push(transportService);
    final List<DiscoveryNode> discoveryNodes = TestUnicastZenPing.resolveHostsLists(executorService, logger, Arrays.asList("127.0.0.1:9300:9300", "127.0.0.1:9301"), 1, transportService, "test_", TimeValue.timeValueSeconds(1));
    // only one of the two is valid and will be used
    assertThat(discoveryNodes, hasSize(1));
    assertThat(discoveryNodes.get(0).getAddress().getAddress(), equalTo("127.0.0.1"));
    assertThat(discoveryNodes.get(0).getAddress().getPort(), equalTo(9301));
    verify(logger).warn(eq("failed to resolve host [127.0.0.1:9300:9300]"), Matchers.any(ExecutionException.class));
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) TransportAddress(org.elasticsearch.common.transport.TransportAddress) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) NetworkService(org.elasticsearch.common.network.NetworkService) Logger(org.apache.logging.log4j.Logger) Transport(org.elasticsearch.transport.Transport) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) ExecutionException(java.util.concurrent.ExecutionException) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService)

Aggregations

TransportService (org.elasticsearch.transport.TransportService)42 Settings (org.elasticsearch.common.settings.Settings)25 ThreadPool (org.elasticsearch.threadpool.ThreadPool)21 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)19 ClusterState (org.elasticsearch.cluster.ClusterState)18 ClusterService (org.elasticsearch.cluster.service.ClusterService)17 Collections (java.util.Collections)16 IOException (java.io.IOException)15 CountDownLatch (java.util.concurrent.CountDownLatch)15 TimeUnit (java.util.concurrent.TimeUnit)15 Before (org.junit.Before)15 ActionFilters (org.elasticsearch.action.support.ActionFilters)14 ESTestCase (org.elasticsearch.test.ESTestCase)14 MockTransportService (org.elasticsearch.test.transport.MockTransportService)14 TestThreadPool (org.elasticsearch.threadpool.TestThreadPool)14 HashSet (java.util.HashSet)13 DiscoveryNodes (org.elasticsearch.cluster.node.DiscoveryNodes)13 IndexNameExpressionResolver (org.elasticsearch.cluster.metadata.IndexNameExpressionResolver)12 TransportAddress (org.elasticsearch.common.transport.TransportAddress)12 After (org.junit.After)12