Search in sources :

Example 11 with Transport

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

the class FetchSearchPhase method innerRun.

private void innerRun() throws IOException {
    final int numShards = context.getNumShards();
    final boolean isScrollSearch = context.getRequest().scroll() != null;
    ScoreDoc[] sortedShardDocs = searchPhaseController.sortDocs(isScrollSearch, queryResults);
    String scrollId = isScrollSearch ? TransportSearchHelper.buildScrollId(queryResults) : null;
    List<AtomicArray.Entry<QuerySearchResultProvider>> queryResultsAsList = queryResults.asList();
    final SearchPhaseController.ReducedQueryPhase reducedQueryPhase = resultConsumer.reduce();
    final boolean queryAndFetchOptimization = queryResults.length() == 1;
    final Runnable finishPhase = () -> moveToNextPhase(searchPhaseController, sortedShardDocs, scrollId, reducedQueryPhase, queryAndFetchOptimization ? queryResults : fetchResults);
    if (queryAndFetchOptimization) {
        assert queryResults.get(0) == null || queryResults.get(0).fetchResult() != null;
        // query AND fetch optimization
        finishPhase.run();
    } else {
        final IntArrayList[] docIdsToLoad = searchPhaseController.fillDocIdsToLoad(numShards, sortedShardDocs);
        if (sortedShardDocs.length == 0) {
            // no docs to fetch -- sidestep everything and return
            queryResultsAsList.stream().map(e -> e.value.queryResult()).forEach(// we have to release contexts here to free up resources
            this::releaseIrrelevantSearchContext);
            finishPhase.run();
        } else {
            final ScoreDoc[] lastEmittedDocPerShard = isScrollSearch ? searchPhaseController.getLastEmittedDocPerShard(reducedQueryPhase, sortedShardDocs, numShards) : null;
            final CountedCollector<FetchSearchResult> counter = new CountedCollector<>(fetchResults::set, // we count down every shard in the result no matter if we got any results or not
            docIdsToLoad.length, finishPhase, context);
            for (int i = 0; i < docIdsToLoad.length; i++) {
                IntArrayList entry = docIdsToLoad[i];
                QuerySearchResultProvider queryResult = queryResults.get(i);
                if (entry == null) {
                    // no results for this shard ID
                    if (queryResult != null) {
                        // if we got some hits from this shard we have to release the context there
                        // we do this as we go since it will free up resources and passing on the request on the
                        // transport layer is cheap.
                        releaseIrrelevantSearchContext(queryResult.queryResult());
                    }
                    // in any case we count down this result since we don't talk to this shard anymore
                    counter.countDown();
                } else {
                    Transport.Connection connection = context.getConnection(queryResult.shardTarget().getNodeId());
                    ShardFetchSearchRequest fetchSearchRequest = createFetchRequest(queryResult.queryResult().id(), i, entry, lastEmittedDocPerShard);
                    executeFetch(i, queryResult.shardTarget(), counter, fetchSearchRequest, queryResult.queryResult(), connection);
                }
            }
        }
    }
}
Also used : SearchShardTarget(org.elasticsearch.search.SearchShardTarget) InternalSearchResponse(org.elasticsearch.search.internal.InternalSearchResponse) Transport(org.elasticsearch.transport.Transport) ScoreDoc(org.apache.lucene.search.ScoreDoc) AtomicArray(org.elasticsearch.common.util.concurrent.AtomicArray) IOException(java.io.IOException) ShardFetchSearchRequest(org.elasticsearch.search.fetch.ShardFetchSearchRequest) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Function(java.util.function.Function) QuerySearchResultProvider(org.elasticsearch.search.query.QuerySearchResultProvider) List(java.util.List) Logger(org.apache.logging.log4j.Logger) FetchSearchResult(org.elasticsearch.search.fetch.FetchSearchResult) QuerySearchResult(org.elasticsearch.search.query.QuerySearchResult) Supplier(org.apache.logging.log4j.util.Supplier) IntArrayList(com.carrotsearch.hppc.IntArrayList) ActionRunnable(org.elasticsearch.action.ActionRunnable) ActionListener(org.elasticsearch.action.ActionListener) QuerySearchResultProvider(org.elasticsearch.search.query.QuerySearchResultProvider) FetchSearchResult(org.elasticsearch.search.fetch.FetchSearchResult) ScoreDoc(org.apache.lucene.search.ScoreDoc) ShardFetchSearchRequest(org.elasticsearch.search.fetch.ShardFetchSearchRequest) ActionRunnable(org.elasticsearch.action.ActionRunnable) IntArrayList(com.carrotsearch.hppc.IntArrayList) Transport(org.elasticsearch.transport.Transport)

Example 12 with Transport

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

the class TransportClient method buildTemplate.

private static ClientTemplate buildTemplate(Settings providedSettings, Settings defaultSettings, Collection<Class<? extends Plugin>> plugins, HostFailureListener failureListner) {
    if (Node.NODE_NAME_SETTING.exists(providedSettings) == false) {
        providedSettings = Settings.builder().put(providedSettings).put(Node.NODE_NAME_SETTING.getKey(), "_client_").build();
    }
    final PluginsService pluginsService = newPluginService(providedSettings, plugins);
    final Settings settings = Settings.builder().put(defaultSettings).put(pluginsService.updatedSettings()).build();
    final List<Closeable> resourcesToClose = new ArrayList<>();
    final ThreadPool threadPool = new ThreadPool(settings);
    resourcesToClose.add(() -> ThreadPool.terminate(threadPool, 10, TimeUnit.SECONDS));
    final NetworkService networkService = new NetworkService(settings, Collections.emptyList());
    try {
        final List<Setting<?>> additionalSettings = new ArrayList<>();
        final List<String> additionalSettingsFilter = new ArrayList<>();
        additionalSettings.addAll(pluginsService.getPluginSettings());
        additionalSettingsFilter.addAll(pluginsService.getPluginSettingsFilter());
        for (final ExecutorBuilder<?> builder : threadPool.builders()) {
            additionalSettings.addAll(builder.getRegisteredSettings());
        }
        SettingsModule settingsModule = new SettingsModule(settings, additionalSettings, additionalSettingsFilter);
        SearchModule searchModule = new SearchModule(settings, true, pluginsService.filterPlugins(SearchPlugin.class));
        List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
        entries.addAll(NetworkModule.getNamedWriteables());
        entries.addAll(searchModule.getNamedWriteables());
        entries.addAll(ClusterModule.getNamedWriteables());
        entries.addAll(pluginsService.filterPlugins(Plugin.class).stream().flatMap(p -> p.getNamedWriteables().stream()).collect(Collectors.toList()));
        NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(entries);
        NamedXContentRegistry xContentRegistry = new NamedXContentRegistry(Stream.of(searchModule.getNamedXContents().stream(), pluginsService.filterPlugins(Plugin.class).stream().flatMap(p -> p.getNamedXContent().stream())).flatMap(Function.identity()).collect(toList()));
        ModulesBuilder modules = new ModulesBuilder();
        // plugin modules must be added here, before others or we can get crazy injection errors...
        for (Module pluginModule : pluginsService.createGuiceModules()) {
            modules.add(pluginModule);
        }
        modules.add(b -> b.bind(ThreadPool.class).toInstance(threadPool));
        ActionModule actionModule = new ActionModule(true, settings, null, settingsModule.getIndexScopedSettings(), settingsModule.getClusterSettings(), settingsModule.getSettingsFilter(), threadPool, pluginsService.filterPlugins(ActionPlugin.class), null, null);
        modules.add(actionModule);
        CircuitBreakerService circuitBreakerService = Node.createCircuitBreakerService(settingsModule.getSettings(), settingsModule.getClusterSettings());
        resourcesToClose.add(circuitBreakerService);
        BigArrays bigArrays = new BigArrays(settings, circuitBreakerService);
        resourcesToClose.add(bigArrays);
        modules.add(settingsModule);
        NetworkModule networkModule = new NetworkModule(settings, true, pluginsService.filterPlugins(NetworkPlugin.class), threadPool, bigArrays, circuitBreakerService, namedWriteableRegistry, xContentRegistry, networkService, null);
        final Transport transport = networkModule.getTransportSupplier().get();
        final TransportService transportService = new TransportService(settings, transport, threadPool, networkModule.getTransportInterceptor(), boundTransportAddress -> DiscoveryNode.createLocal(settings, new TransportAddress(TransportAddress.META_ADDRESS, 0), UUIDs.randomBase64UUID()), null);
        modules.add((b -> {
            b.bind(BigArrays.class).toInstance(bigArrays);
            b.bind(PluginsService.class).toInstance(pluginsService);
            b.bind(CircuitBreakerService.class).toInstance(circuitBreakerService);
            b.bind(NamedWriteableRegistry.class).toInstance(namedWriteableRegistry);
            b.bind(Transport.class).toInstance(transport);
            b.bind(TransportService.class).toInstance(transportService);
            b.bind(NetworkService.class).toInstance(networkService);
        }));
        Injector injector = modules.createInjector();
        final TransportClientNodesService nodesService = new TransportClientNodesService(settings, transportService, threadPool, failureListner == null ? (t, e) -> {
        } : failureListner);
        final TransportProxyClient proxy = new TransportProxyClient(settings, transportService, nodesService, actionModule.getActions().values().stream().map(x -> x.getAction()).collect(Collectors.toList()));
        List<LifecycleComponent> pluginLifecycleComponents = new ArrayList<>();
        pluginLifecycleComponents.addAll(pluginsService.getGuiceServiceClasses().stream().map(injector::getInstance).collect(Collectors.toList()));
        resourcesToClose.addAll(pluginLifecycleComponents);
        transportService.start();
        transportService.acceptIncomingRequests();
        ClientTemplate transportClient = new ClientTemplate(injector, pluginLifecycleComponents, nodesService, proxy, namedWriteableRegistry);
        resourcesToClose.clear();
        return transportClient;
    } finally {
        IOUtils.closeWhileHandlingException(resourcesToClose);
    }
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) Arrays(java.util.Arrays) Injector(org.elasticsearch.common.inject.Injector) NetworkModule(org.elasticsearch.common.network.NetworkModule) BigArrays(org.elasticsearch.common.util.BigArrays) Settings(org.elasticsearch.common.settings.Settings) TimeValue.timeValueSeconds(org.elasticsearch.common.unit.TimeValue.timeValueSeconds) ThreadPool(org.elasticsearch.threadpool.ThreadPool) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) ActionRequest(org.elasticsearch.action.ActionRequest) PluginsService(org.elasticsearch.plugins.PluginsService) Transport(org.elasticsearch.transport.Transport) Setting(org.elasticsearch.common.settings.Setting) Collection(java.util.Collection) UUIDs(org.elasticsearch.common.UUIDs) ClusterModule(org.elasticsearch.cluster.ClusterModule) Collectors(java.util.stream.Collectors) AbstractClient(org.elasticsearch.client.support.AbstractClient) List(java.util.List) Stream(java.util.stream.Stream) TransportAddress(org.elasticsearch.common.transport.TransportAddress) SearchPlugin(org.elasticsearch.plugins.SearchPlugin) Module(org.elasticsearch.common.inject.Module) InternalSettingsPreparer(org.elasticsearch.node.InternalSettingsPreparer) Function(java.util.function.Function) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) ArrayList(java.util.ArrayList) ActionModule(org.elasticsearch.action.ActionModule) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NetworkService(org.elasticsearch.common.network.NetworkService) SettingsModule(org.elasticsearch.common.settings.SettingsModule) NetworkPlugin(org.elasticsearch.plugins.NetworkPlugin) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) TcpTransport(org.elasticsearch.transport.TcpTransport) TimeValue(org.elasticsearch.common.unit.TimeValue) Node(org.elasticsearch.node.Node) ExecutorBuilder(org.elasticsearch.threadpool.ExecutorBuilder) TransportService(org.elasticsearch.transport.TransportService) ActionRequestBuilder(org.elasticsearch.action.ActionRequestBuilder) SearchModule(org.elasticsearch.search.SearchModule) ActionPlugin(org.elasticsearch.plugins.ActionPlugin) ActionResponse(org.elasticsearch.action.ActionResponse) IOUtils(org.apache.lucene.util.IOUtils) Plugin(org.elasticsearch.plugins.Plugin) Action(org.elasticsearch.action.Action) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) LifecycleComponent(org.elasticsearch.common.component.LifecycleComponent) Closeable(java.io.Closeable) ModulesBuilder(org.elasticsearch.common.inject.ModulesBuilder) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) NetworkPlugin(org.elasticsearch.plugins.NetworkPlugin) TransportAddress(org.elasticsearch.common.transport.TransportAddress) Closeable(java.io.Closeable) ActionModule(org.elasticsearch.action.ActionModule) ArrayList(java.util.ArrayList) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ActionPlugin(org.elasticsearch.plugins.ActionPlugin) LifecycleComponent(org.elasticsearch.common.component.LifecycleComponent) Injector(org.elasticsearch.common.inject.Injector) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) Settings(org.elasticsearch.common.settings.Settings) PluginsService(org.elasticsearch.plugins.PluginsService) Setting(org.elasticsearch.common.settings.Setting) SearchPlugin(org.elasticsearch.plugins.SearchPlugin) BigArrays(org.elasticsearch.common.util.BigArrays) TransportService(org.elasticsearch.transport.TransportService) SettingsModule(org.elasticsearch.common.settings.SettingsModule) NetworkService(org.elasticsearch.common.network.NetworkService) SearchModule(org.elasticsearch.search.SearchModule) ModulesBuilder(org.elasticsearch.common.inject.ModulesBuilder) NetworkModule(org.elasticsearch.common.network.NetworkModule) ClusterModule(org.elasticsearch.cluster.ClusterModule) Module(org.elasticsearch.common.inject.Module) ActionModule(org.elasticsearch.action.ActionModule) SettingsModule(org.elasticsearch.common.settings.SettingsModule) SearchModule(org.elasticsearch.search.SearchModule) Transport(org.elasticsearch.transport.Transport) TcpTransport(org.elasticsearch.transport.TcpTransport) NetworkModule(org.elasticsearch.common.network.NetworkModule)

Example 13 with Transport

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

the class NetworkModuleTests method testDefaultKeys.

public void testDefaultKeys() {
    Settings settings = Settings.builder().put(NetworkModule.HTTP_DEFAULT_TYPE_SETTING.getKey(), "default_custom").put(NetworkModule.TRANSPORT_DEFAULT_TYPE_SETTING.getKey(), "default_custom").build();
    Supplier<HttpServerTransport> custom = FakeHttpTransport::new;
    Supplier<HttpServerTransport> def = FakeHttpTransport::new;
    Supplier<Transport> customTransport = () -> null;
    NetworkModule module = newNetworkModule(settings, false, new NetworkPlugin() {

        @Override
        public Map<String, Supplier<Transport>> getTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays, CircuitBreakerService circuitBreakerService, NamedWriteableRegistry namedWriteableRegistry, NetworkService networkService) {
            return Collections.singletonMap("default_custom", customTransport);
        }

        @Override
        public Map<String, Supplier<HttpServerTransport>> getHttpTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays, CircuitBreakerService circuitBreakerService, NamedWriteableRegistry namedWriteableRegistry, NamedXContentRegistry xContentRegistry, NetworkService networkService, HttpServerTransport.Dispatcher requestDispatcher) {
            Map<String, Supplier<HttpServerTransport>> supplierMap = new HashMap<>();
            supplierMap.put("custom", custom);
            supplierMap.put("default_custom", def);
            return supplierMap;
        }
    });
    assertSame(def, module.getHttpServerTransportSupplier());
    assertSame(customTransport, module.getTransportSupplier());
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) NetworkPlugin(org.elasticsearch.plugins.NetworkPlugin) ThreadPool(org.elasticsearch.threadpool.ThreadPool) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) BigArrays(org.elasticsearch.common.util.BigArrays) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) Transport(org.elasticsearch.transport.Transport) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) HashMap(java.util.HashMap) Map(java.util.Map) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Settings(org.elasticsearch.common.settings.Settings)

Example 14 with Transport

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

the class UnicastZenPingTests method testSimplePings.

public void testSimplePings() throws IOException, InterruptedException, ExecutionException {
    // use ephemeral ports
    final Settings settings = Settings.builder().put("cluster.name", "test").put(TransportSettings.PORT.getKey(), 0).build();
    final Settings settingsMismatch = Settings.builder().put(settings).put("cluster.name", "mismatch").put(TransportSettings.PORT.getKey(), 0).build();
    NetworkService networkService = new NetworkService(settings, Collections.emptyList());
    final BiFunction<Settings, Version, Transport> supplier = (s, v) -> new MockTcpTransport(s, threadPool, BigArrays.NON_RECYCLING_INSTANCE, new NoneCircuitBreakerService(), new NamedWriteableRegistry(Collections.emptyList()), networkService, v) {

        @Override
        public void connectToNode(DiscoveryNode node, ConnectionProfile connectionProfile, CheckedBiConsumer<Connection, ConnectionProfile, IOException> connectionValidator) throws ConnectTransportException {
            throw new AssertionError("zen pings should never connect to node (got [" + node + "])");
        }
    };
    NetworkHandle handleA = startServices(settings, threadPool, "UZP_A", Version.CURRENT, supplier);
    closeables.push(handleA.transportService);
    NetworkHandle handleB = startServices(settings, threadPool, "UZP_B", Version.CURRENT, supplier);
    closeables.push(handleB.transportService);
    NetworkHandle handleC = startServices(settingsMismatch, threadPool, "UZP_C", Version.CURRENT, supplier);
    closeables.push(handleC.transportService);
    final Version versionD;
    if (randomBoolean()) {
        versionD = VersionUtils.randomVersionBetween(random(), Version.CURRENT.minimumCompatibilityVersion(), Version.CURRENT);
    } else {
        versionD = Version.CURRENT;
    }
    logger.info("UZP_D version set to [{}]", versionD);
    NetworkHandle handleD = startServices(settingsMismatch, threadPool, "UZP_D", versionD, supplier);
    closeables.push(handleD.transportService);
    final ClusterState state = ClusterState.builder(new ClusterName("test")).version(randomNonNegativeLong()).build();
    final ClusterState stateMismatch = ClusterState.builder(new ClusterName("mismatch")).version(randomNonNegativeLong()).build();
    Settings hostsSettings = Settings.builder().putArray("discovery.zen.ping.unicast.hosts", NetworkAddress.format(new InetSocketAddress(handleA.address.address().getAddress(), handleA.address.address().getPort())), NetworkAddress.format(new InetSocketAddress(handleB.address.address().getAddress(), handleB.address.address().getPort())), NetworkAddress.format(new InetSocketAddress(handleC.address.address().getAddress(), handleC.address.address().getPort())), NetworkAddress.format(new InetSocketAddress(handleD.address.address().getAddress(), handleD.address.address().getPort()))).put("cluster.name", "test").build();
    Settings hostsSettingsMismatch = Settings.builder().put(hostsSettings).put(settingsMismatch).build();
    TestUnicastZenPing zenPingA = new TestUnicastZenPing(hostsSettings, threadPool, handleA, EMPTY_HOSTS_PROVIDER);
    zenPingA.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleA.node).localNodeId("UZP_A").build();
        }

        @Override
        public ClusterState clusterState() {
            return ClusterState.builder(state).blocks(ClusterBlocks.builder().addGlobalBlock(STATE_NOT_RECOVERED_BLOCK)).build();
        }
    });
    closeables.push(zenPingA);
    TestUnicastZenPing zenPingB = new TestUnicastZenPing(hostsSettings, threadPool, handleB, EMPTY_HOSTS_PROVIDER);
    zenPingB.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleB.node).localNodeId("UZP_B").build();
        }

        @Override
        public ClusterState clusterState() {
            return state;
        }
    });
    closeables.push(zenPingB);
    TestUnicastZenPing zenPingC = new TestUnicastZenPing(hostsSettingsMismatch, threadPool, handleC, EMPTY_HOSTS_PROVIDER) {

        @Override
        protected Version getVersion() {
            return versionD;
        }
    };
    zenPingC.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleC.node).localNodeId("UZP_C").build();
        }

        @Override
        public ClusterState clusterState() {
            return stateMismatch;
        }
    });
    closeables.push(zenPingC);
    TestUnicastZenPing zenPingD = new TestUnicastZenPing(hostsSettingsMismatch, threadPool, handleD, EMPTY_HOSTS_PROVIDER);
    zenPingD.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleD.node).localNodeId("UZP_D").build();
        }

        @Override
        public ClusterState clusterState() {
            return stateMismatch;
        }
    });
    closeables.push(zenPingD);
    logger.info("ping from UZP_A");
    Collection<ZenPing.PingResponse> pingResponses = zenPingA.pingAndWait().toList();
    assertThat(pingResponses.size(), equalTo(1));
    ZenPing.PingResponse ping = pingResponses.iterator().next();
    assertThat(ping.node().getId(), equalTo("UZP_B"));
    assertThat(ping.getClusterStateVersion(), equalTo(state.version()));
    assertPingCount(handleA, handleB, 3);
    // mismatch, shouldn't ping
    assertPingCount(handleA, handleC, 0);
    // mismatch, shouldn't ping
    assertPingCount(handleA, handleD, 0);
    // ping again, this time from B,
    logger.info("ping from UZP_B");
    pingResponses = zenPingB.pingAndWait().toList();
    assertThat(pingResponses.size(), equalTo(1));
    ping = pingResponses.iterator().next();
    assertThat(ping.node().getId(), equalTo("UZP_A"));
    assertThat(ping.getClusterStateVersion(), equalTo(ElectMasterService.MasterCandidate.UNRECOVERED_CLUSTER_VERSION));
    assertPingCount(handleB, handleA, 3);
    // mismatch, shouldn't ping
    assertPingCount(handleB, handleC, 0);
    // mismatch, shouldn't ping
    assertPingCount(handleB, handleD, 0);
    logger.info("ping from UZP_C");
    pingResponses = zenPingC.pingAndWait().toList();
    assertThat(pingResponses.size(), equalTo(1));
    assertPingCount(handleC, handleA, 0);
    assertPingCount(handleC, handleB, 0);
    assertPingCount(handleC, handleD, 3);
    logger.info("ping from UZP_D");
    pingResponses = zenPingD.pingAndWait().toList();
    assertThat(pingResponses.size(), equalTo(1));
    assertPingCount(handleD, handleA, 0);
    assertPingCount(handleD, handleB, 0);
    assertPingCount(handleD, handleC, 3);
}
Also used : Arrays(java.util.Arrays) BigArrays(org.elasticsearch.common.util.BigArrays) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) BiFunction(java.util.function.BiFunction) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) InetAddress(java.net.InetAddress) STATE_NOT_RECOVERED_BLOCK(org.elasticsearch.gateway.GatewayService.STATE_NOT_RECOVERED_BLOCK) ClusterState(org.elasticsearch.cluster.ClusterState) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Matchers.eq(org.mockito.Matchers.eq) After(org.junit.After) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) Role(org.elasticsearch.cluster.node.DiscoveryNode.Role) ThreadFactory(java.util.concurrent.ThreadFactory) EnumSet(java.util.EnumSet) Transport(org.elasticsearch.transport.Transport) Collection(java.util.Collection) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Version(org.elasticsearch.Version) TransportAddress(org.elasticsearch.common.transport.TransportAddress) TransportConnectionListener(org.elasticsearch.transport.TransportConnectionListener) TransportSettings(org.elasticsearch.transport.TransportSettings) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) TransportRequestOptions(org.elasticsearch.transport.TransportRequestOptions) TransportException(org.elasticsearch.transport.TransportException) NetworkAddress(org.elasticsearch.common.network.NetworkAddress) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) Matchers(org.mockito.Matchers) HashMap(java.util.HashMap) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) CheckedBiConsumer(org.elasticsearch.common.CheckedBiConsumer) Stack(java.util.Stack) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NetworkService(org.elasticsearch.common.network.NetworkService) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) TimeValue(org.elasticsearch.common.unit.TimeValue) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ESTestCase(org.elasticsearch.test.ESTestCase) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ConnectionProfile(org.elasticsearch.transport.ConnectionProfile) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) Matchers.empty(org.hamcrest.Matchers.empty) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) Collections.emptySet(java.util.Collections.emptySet) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) VersionUtils(org.elasticsearch.test.VersionUtils) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Closeable(java.io.Closeable) Collections(java.util.Collections) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) CheckedBiConsumer(org.elasticsearch.common.CheckedBiConsumer) InetSocketAddress(java.net.InetSocketAddress) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Version(org.elasticsearch.Version) ClusterName(org.elasticsearch.cluster.ClusterName) Settings(org.elasticsearch.common.settings.Settings) TransportSettings(org.elasticsearch.transport.TransportSettings) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) ClusterState(org.elasticsearch.cluster.ClusterState) ConnectionProfile(org.elasticsearch.transport.ConnectionProfile) NetworkService(org.elasticsearch.common.network.NetworkService) Transport(org.elasticsearch.transport.Transport) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService)

Example 15 with Transport

use of org.elasticsearch.transport.Transport 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

Transport (org.elasticsearch.transport.Transport)22 NamedWriteableRegistry (org.elasticsearch.common.io.stream.NamedWriteableRegistry)18 NetworkService (org.elasticsearch.common.network.NetworkService)15 Settings (org.elasticsearch.common.settings.Settings)14 NoneCircuitBreakerService (org.elasticsearch.indices.breaker.NoneCircuitBreakerService)14 ThreadPool (org.elasticsearch.threadpool.ThreadPool)14 TransportService (org.elasticsearch.transport.TransportService)14 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)13 TransportAddress (org.elasticsearch.common.transport.TransportAddress)13 TestThreadPool (org.elasticsearch.threadpool.TestThreadPool)13 MockTcpTransport (org.elasticsearch.transport.MockTcpTransport)13 BigArrays (org.elasticsearch.common.util.BigArrays)12 MockTransportService (org.elasticsearch.test.transport.MockTransportService)12 Collections (java.util.Collections)11 Logger (org.apache.logging.log4j.Logger)11 BoundTransportAddress (org.elasticsearch.common.transport.BoundTransportAddress)11 UnknownHostException (java.net.UnknownHostException)10 List (java.util.List)10 Map (java.util.Map)10 TimeUnit (java.util.concurrent.TimeUnit)10