Java Code Examples for org.elasticsearch.common.transport.TransportAddress

The following examples show how to use org.elasticsearch.common.transport.TransportAddress. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: skywalking   Source File: TransportClientConfig.java    License: Apache License 2.0 6 votes vote down vote up
private TransportAddress[] parseEsHost()
    throws Exception {
    TransportAddress[] transportAddresses = null;
    if (!elasticsearchHost.isEmpty()) {
        String[] hostIp = elasticsearchHost.split(",");
        transportAddresses = new TransportAddress[hostIp.length];

        for (int i = 0; i < hostIp.length; ++i) {
            String[] hostIpItem = hostIp[i].split(":");
            String ip = hostIpItem[0].trim();
            String port = hostIpItem[1].trim();
            transportAddresses[i] = new TransportAddress(InetAddress.getByName(ip), PORT);
        }
    }
    return transportAddresses;
}
 
Example 2
Source Project: crate   Source File: PostgresNetty.java    License: Apache License 2.0 6 votes vote down vote up
private TransportAddress bindAddress(final InetAddress hostAddress) {
    PortsRange portsRange = new PortsRange(port);
    final AtomicReference<Exception> lastException = new AtomicReference<>();
    final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>();
    boolean success = portsRange.iterate(portNumber -> {
        try {
            Channel channel = bootstrap.bind(new InetSocketAddress(hostAddress, portNumber)).sync().channel();
            serverChannels.add(channel);
            boundSocket.set((InetSocketAddress) channel.localAddress());
        } catch (Exception e) {
            lastException.set(e);
            return false;
        }
        return true;
    });
    if (!success) {
        throw new BindPostgresException("Failed to bind to [" + port + "]", lastException.get());
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Bound psql to address {{}}", NetworkAddress.format(boundSocket.get()));
    }
    return new TransportAddress(boundSocket.get());
}
 
Example 3
Source Project: crate   Source File: TcpTransport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends back an error response to the caller via the given channel
 *
 * @param nodeVersion the caller node version
 * @param features    the caller features
 * @param channel     the channel to send the response to
 * @param error       the error to return
 * @param requestId   the request ID this response replies to
 * @param action      the action this response replies to
 */
public void sendErrorResponse(
        final Version nodeVersion,
        final Set<String> features,
        final TcpChannel channel,
        final Exception error,
        final long requestId,
        final String action) throws IOException {
    try (BytesStreamOutput stream = new BytesStreamOutput()) {
        stream.setVersion(nodeVersion);
        stream.setFeatures(features);
        RemoteTransportException tx = new RemoteTransportException(
            nodeName, new TransportAddress(channel.getLocalAddress()), action, error);
        ThreadContext.bwcWriteHeaders(stream);
        stream.writeException(tx);
        byte status = 0;
        status = TransportStatus.setResponse(status);
        status = TransportStatus.setError(status);
        final BytesReference bytes = stream.bytes();
        final BytesReference header = buildHeader(requestId, status, nodeVersion, bytes.length());
        CompositeBytesReference message = new CompositeBytesReference(header, bytes);
        SendListener onResponseSent = new SendListener(channel, null,
            () -> messageListener.onResponseSent(requestId, action, error), message.length());
        internalSendMessage(channel, message, onResponseSent);
    }
}
 
Example 4
Source Project: foxtrot   Source File: ElasticsearchConnection.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    logger.info("Starting ElasticSearch Client");
    Settings settings = Settings.builder()
            .put("cluster.name", config.getCluster())
            .put("client.transport.ignore_cluster_name", true)
            .build();

    TransportClient esClient = new CustomESTransportClient(settings);
    final int port = config.getPort() == null
        ? 9300
        : config.getPort();

    for(String host : config.getHosts()) {
        String[] tokenizedHosts = host.split(",");
        for(String tokenizedHost : tokenizedHosts) {
            esClient.addTransportAddress(new TransportAddress(InetAddress.getByName(tokenizedHost), port));
            logger.info("Added ElasticSearch Node : {}", host);
        }
    }
    client = esClient;
    logger.info("Started ElasticSearch Client");
}
 
Example 5
private String[] getIndexes() {

		Settings settings = Settings.builder().put("cluster.name", "cluster1").build();
		try (TransportClient client = new PreBuiltTransportClient(settings)) {
			client.addTransportAddress(
					new TransportAddress(InetAddress.getByName("localhost"), embeddedElastic.getTransportTcpPort()));

			return client.admin()
					.indices()
					.getIndex(new GetIndexRequest())
					.actionGet()
					.getIndices();
		} catch (UnknownHostException e) {
			throw new IllegalStateException(e);
		}

	}
 
Example 6
Source Project: flink   Source File: Elasticsearch2ApiCallBridge.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TransportClient createClient(Map<String, String> clientConfig) {
	Settings settings = Settings.settingsBuilder().put(clientConfig).build();

	TransportClient transportClient = TransportClient.builder().settings(settings).build();
	for (TransportAddress address : ElasticsearchUtils.convertInetSocketAddresses(transportAddresses)) {
		transportClient.addTransportAddress(address);
	}

	// verify that we actually are connected to a cluster
	if (transportClient.connectedNodes().isEmpty()) {

		// close the transportClient here
		IOUtils.closeQuietly(transportClient);

		throw new RuntimeException("Elasticsearch client is not connected to any Elasticsearch nodes!");
	}

	if (LOG.isInfoEnabled()) {
		LOG.info("Created Elasticsearch TransportClient with connected nodes {}", transportClient.connectedNodes());
	}

	return transportClient;
}
 
Example 7
Source Project: elasticshell   Source File: DefaultClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ShellNativeClient newTransportClient(String... addresses) {
    TransportAddress[] transportAddresses = new TransportAddress[addresses.length];
    for (int i = 0; i < addresses.length; i++) {
        String address = addresses[i];

        String[] splitAddress = address.split(":");
        String host = shellSettings.settings().get(ShellSettings.TRANSPORT_HOST);

        if (splitAddress.length>=1) {
            host = splitAddress[0];
        }

        int port = shellSettings.settings().getAsInt(ShellSettings.TRANSPORT_PORT, null);
        if (splitAddress.length>=2) {
            try {
                port = Integer.valueOf(splitAddress[1]);
            } catch(NumberFormatException e) {
                logger.warn("Unable to parse port [{}]", splitAddress[1], e);
            }
        }

        transportAddresses[i] = new InetSocketTransportAddress(host, port);
    }
    return newTransportClient(transportAddresses);
}
 
Example 8
Source Project: presto-connectors   Source File: Elasticsearch6Module.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Client get()
{
    try {
        Settings settings = Settings.builder().put("cluster.name", clusterName)
                .put("client.transport.sniff", true).build();

        TransportClient client = new PreBuiltTransportClient(settings);
        for (String ip : hosts.split(",")) {
            client.addTransportAddress(
                    new TransportAddress(InetAddress.getByName(ip.split(":")[0]),
                            Integer.parseInt(ip.split(":")[1])));
        }
        return client;
    }
    catch (IOException e) {
        throw new PrestoException(UNEXPECTED_ES_ERROR, "Failed to get connection to Elasticsearch", e);
    }
}
 
Example 9
Source Project: crate   Source File: SrvUnicastHostsProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<TransportAddress> getSeedAddresses(HostsResolver hostsResolver) {
    if (query == null) {
        LOGGER.error("DNS query must not be null. Please set '{}'", DISCOVERY_SRV_QUERY);
        return Collections.emptyList();
    }
    try {
        List<DnsRecord> records = lookupRecords();
        LOGGER.trace("Building dynamic unicast discovery nodes...");
        if (records == null || records.size() == 0) {
            LOGGER.debug("No nodes found");
        } else {
            List<TransportAddress> transportAddresses = parseRecords(records);
            LOGGER.info("Using dynamic nodes {}", transportAddresses);
            return transportAddresses;
        }
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        LOGGER.error("DNS lookup exception:", e);
    }
    return Collections.emptyList();
}
 
Example 10
private String[] getIndexes() {

		Settings settings = Settings.builder().put("cluster.name", "cluster1").build();
		try (TransportClient client = new PreBuiltTransportClient(settings)) {
			client.addTransportAddress(
					new TransportAddress(InetAddress.getByName("localhost"), embeddedElastic.getTransportTcpPort()));

			return client.admin()
					.indices()
					.getIndex(new GetIndexRequest())
					.actionGet()
					.getIndices();
		} catch (UnknownHostException e) {
			throw new IllegalStateException(e);
		}

	}
 
Example 11
@Override
@SuppressWarnings("squid:S2095")
public void setup() {
  final Settings.Builder settingsBuilder = Settings.builder();

  settingsBuilder.put("node.name", properties.getNodeName())
      .put("cluster.name", properties.getClusterName())
      .put("http.enabled", properties.isHttpEnabled());

  client = new PreBuiltTransportClient(settingsBuilder.build());
  try {
    client.addTransportAddress(new TransportAddress(InetAddress.getByName(properties.getHost()), properties.getPort()));
  } catch (UnknownHostException e) {
    log.error("Error connecting to the Elasticsearch cluster at {}:{}", properties.getHost(), properties.getPort(), e);
  }
}
 
Example 12
Source Project: crate   Source File: NodeStatsContextFieldResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws UnknownHostException {
    final OsService osService = mock(OsService.class);
    final OsStats osStats = mock(OsStats.class);
    final MonitorService monitorService = mock(MonitorService.class);

    when(monitorService.osService()).thenReturn(osService);
    when(osService.stats()).thenReturn(osStats);
    DiscoveryNode discoveryNode = newNode("node_name", "node_id");

    postgresAddress = new TransportAddress(Inet4Address.getLocalHost(), 5432);
    resolver = new NodeStatsContextFieldResolver(
        () -> discoveryNode,
        monitorService,
        () -> null,
        () -> new HttpStats(20L, 30L),
        mock(ThreadPool.class),
        new ExtendedNodeInfo(),
        () -> new ConnectionStats(2L, 4L),
        () -> postgresAddress,
        () -> 12L,
        () -> 1L
    );
}
 
Example 13
Source Project: elasticsearch-full   Source File: XPackBaseDemo.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    /**
     * 如果es集群安装了x-pack插件则以此种方式连接集群
     * 1. java客户端的方式是以tcp协议在9300端口上进行通信
     * 2. http客户端的方式是以http协议在9200端口上进行通信
     */
    Settings settings = Settings.builder(). put("xpack.security.user", "elastic:changeme").build();
    client = new PreBuiltXPackTransportClient(settings)
            .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9200));
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("elastic", "changeme"));
    restClient = RestClient.builder(new HttpHost("localhost",9200,"http"))
            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                }
            }).build();
}
 
Example 14
@Override
public void logFailedLogin(String effectiveUser, boolean securityadmin, String initiatingUser, TransportRequest request, Task task) {
    final String action = null;

    if(!checkTransportFilter(Category.FAILED_LOGIN, action, effectiveUser, request)) {
        return;
    }

    final TransportAddress remoteAddress = getRemoteAddress();
    final List<AuditMessage> msgs = RequestResolver.resolve(Category.FAILED_LOGIN, getOrigin(), action, null, effectiveUser, securityadmin, initiatingUser, remoteAddress, request, getThreadContextHeaders(), task, resolver, clusterService, settings, logRequestBody, resolveIndices, resolveBulkRequests, opendistrosecurityIndex, excludeSensitiveHeaders, null);

    for(AuditMessage msg: msgs) {
        save(msg);
    }
}
 
Example 15
Source Project: jstorm   Source File: EsConfig.java    License: Apache License 2.0 5 votes vote down vote up
List<TransportAddress> getTransportAddresses() throws UnknownHostException {
  List<TransportAddress> transportAddresses = Lists.newArrayList();
  for (String node : nodes) {
    String[] hostAndPort = node.split(DELIMITER);
    Preconditions.checkArgument(hostAndPort.length == 2,
        "Incorrect node format");
    String host = hostAndPort[0];
    int port = Integer.parseInt(hostAndPort[1]);
    InetSocketTransportAddress inetSocketTransportAddress = new InetSocketTransportAddress(
        InetAddress.getByName(host), port);
    transportAddresses.add(inetSocketTransportAddress);
  }
  return transportAddresses;
}
 
Example 16
Source Project: crate   Source File: TcpTransportTest.java    License: Apache License 2.0 5 votes vote down vote up
/** Test ipv4 host with port works */
public void testParseV4WithPort() throws Exception {
    TransportAddress[] addresses = TcpTransport.parse("127.0.0.1:2345", 1234);
    assertEquals(1, addresses.length);

    assertEquals("127.0.0.1", addresses[0].getAddress());
    assertEquals(2345, addresses[0].getPort());
}
 
Example 17
@Override
public void logMissingPrivileges(String privilege, TransportRequest request, Task task) {
    final String action = null;

    if(!checkTransportFilter(Category.MISSING_PRIVILEGES, privilege, getUser(), request)) {
        return;
    }

    final TransportAddress remoteAddress = getRemoteAddress();
    final List<AuditMessage> msgs = RequestResolver.resolve(Category.MISSING_PRIVILEGES, getOrigin(), action, privilege, getUser(), null, null, remoteAddress, request, getThreadContextHeaders(), task, resolver, clusterService, settings, logRequestBody, resolveIndices, resolveBulkRequests, opendistrosecurityIndex, excludeSensitiveHeaders, null);

    for(AuditMessage msg: msgs) {
        save(msg);
    }
}
 
Example 18
Source Project: skywalking   Source File: TransportAddressCache.java    License: Apache License 2.0 5 votes vote down vote up
private String format() {
    StringBuilder stringBuilder = new StringBuilder();
    for (TransportAddress node : transportAddresses) {
        stringBuilder.append(node.getAddress()).append(":").append(node.getPort()).append(";");
    }

    return stringBuilder.toString();
}
 
Example 19
Source Project: elasticsearch-helper   Source File: TransportClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the current registered transport addresses to use.
 * @return list of transport addresess
 */
public List<TransportAddress> transportAddresses() {
    List<TransportAddress> lstBuilder = new ArrayList<>();
    for (DiscoveryNode listedNode : listedNodes) {
        lstBuilder.add(listedNode.address());
    }
    return Collections.unmodifiableList(lstBuilder);
}
 
Example 20
Source Project: crate   Source File: ClusterFormationFailureHelperTests.java    License: Apache License 2.0 5 votes vote down vote up
public void testDescriptionBeforeBootstrapping() {
    final DiscoveryNode localNode = new DiscoveryNode("local", buildNewFakeTransportAddress(), Version.CURRENT);
    final ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT)
        .version(7L)
        .metaData(MetaData.builder().coordinationMetaData(CoordinationMetaData.builder().term(4L).build()))
        .nodes(DiscoveryNodes.builder().add(localNode).localNodeId(localNode.getId())).build();

    assertThat(new ClusterFormationState(Settings.EMPTY, clusterState, emptyList(), emptyList(), 1L).getDescription(),
        is("master not discovered yet, this node has not previously joined a bootstrapped (v4+) cluster, and " +
            "[cluster.initial_master_nodes] is empty on this node: have discovered []; " +
            "discovery will continue using [] from hosts providers and [" + localNode +
            "] from last-known cluster state; node term 1, last-accepted version 7 in term 4"));

    final TransportAddress otherAddress = buildNewFakeTransportAddress();
    assertThat(new ClusterFormationState(Settings.EMPTY, clusterState, singletonList(otherAddress), emptyList(), 2L).getDescription(),
        is("master not discovered yet, this node has not previously joined a bootstrapped (v4+) cluster, and " +
            "[cluster.initial_master_nodes] is empty on this node: have discovered []; " +
            "discovery will continue using [" + otherAddress + "] from hosts providers and [" + localNode +
            "] from last-known cluster state; node term 2, last-accepted version 7 in term 4"));

    final DiscoveryNode otherNode = new DiscoveryNode("other", buildNewFakeTransportAddress(), Version.CURRENT);
    assertThat(new ClusterFormationState(Settings.EMPTY, clusterState, emptyList(), singletonList(otherNode), 3L).getDescription(),
        is("master not discovered yet, this node has not previously joined a bootstrapped (v4+) cluster, and " +
            "[cluster.initial_master_nodes] is empty on this node: have discovered [" + otherNode + "]; " +
            "discovery will continue using [] from hosts providers and [" + localNode +
            "] from last-known cluster state; node term 3, last-accepted version 7 in term 4"));

    assertThat(new ClusterFormationState(Settings.builder().putList(INITIAL_MASTER_NODES_SETTING.getKey(), "other").build(),
            clusterState, emptyList(), emptyList(), 4L).getDescription(),
        is("master not discovered yet, this node has not previously joined a bootstrapped (v4+) cluster, and " +
            "this node must discover master-eligible nodes [other] to bootstrap a cluster: have discovered []; " +
            "discovery will continue using [] from hosts providers and [" + localNode +
            "] from last-known cluster state; node term 4, last-accepted version 7 in term 4"));
}
 
Example 21
Source Project: crate   Source File: AzureSeedHostsProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * We build the list of addresses from Azure Management API
 * List of addresses is cached.
 * The cache time can be controlled using `cloud.azure.refresh_interval` setting.
 */
@Override
public List<TransportAddress> getSeedAddresses(HostsResolver hostsResolver) {
    if (cache == null) {
        cache = new AddressCache(refreshInterval, Collections.emptyList());
    }
    return cache.getOrRefresh();
}
 
Example 22
Source Project: Flink-CEPplus   Source File: ElasticsearchSink.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@code ElasticsearchSink} that connects to the cluster using a {@link TransportClient}.
 *
 * @param userConfig The map of user settings that are used when constructing the {@link TransportClient} and {@link BulkProcessor}
 * @param transportAddresses The addresses of Elasticsearch nodes to which to connect using a {@link TransportClient}
 * @param elasticsearchSinkFunction This is used to generate multiple {@link ActionRequest} from the incoming element
 * @param failureHandler This is used to handle failed {@link ActionRequest}
 */
public ElasticsearchSink(
	Map<String, String> userConfig,
	List<TransportAddress> transportAddresses,
	ElasticsearchSinkFunction<T> elasticsearchSinkFunction,
	ActionRequestFailureHandler failureHandler) {

	super(new Elasticsearch1ApiCallBridge(transportAddresses), userConfig, elasticsearchSinkFunction, failureHandler);
}
 
Example 23
Source Project: Flink-CEPplus   Source File: ElasticsearchSinkITCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests that behaviour of the deprecated {@link IndexRequestBuilder} constructor works properly.
 */
@Test
public void testDeprecatedIndexRequestBuilderVariant() throws Exception {
	final String index = "index-req-builder-test-index";

	final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

	DataStreamSource<Tuple2<Integer, String>> source = env.addSource(new SourceSinkDataTestKit.TestDataSourceFunction());

	Map<String, String> userConfig = new HashMap<>();
	// This instructs the sink to emit after every element, otherwise they would be buffered
	userConfig.put(ElasticsearchSinkBase.CONFIG_KEY_BULK_FLUSH_MAX_ACTIONS, "1");
	userConfig.put("cluster.name", CLUSTER_NAME);
	userConfig.put("node.local", "true");

	List<TransportAddress> transports = new ArrayList<>();
	transports.add(new LocalTransportAddress("1"));

	source.addSink(new ElasticsearchSink<>(
		userConfig,
		transports,
		new TestIndexRequestBuilder(index))
	);

	env.execute("Elasticsearch Deprecated IndexRequestBuilder Bridge Test");

	// verify the results
	Client client = embeddedNodeEnv.getClient();
	SourceSinkDataTestKit.verifyProducedSinkData(client, index);

	client.close();
}
 
Example 24
Source Project: skywalking   Source File: TransportAddressCache.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized void removeDiscoveryNode(TransportAddress transportAddress) {
    List<TransportAddress> nodesBuilder = new ArrayList<TransportAddress>();

    for (TransportAddress otherNode : transportAddresses) {
        if (!otherNode.getAddress().equals(transportAddress.getAddress())) {
            nodesBuilder.add(otherNode);
        }
    }

    transportAddresses = nodesBuilder;
    transportAddressesStr = format();
}
 
Example 25
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
                          Object ret) throws Throwable {
    TransportClientEnhanceInfo transportClientEnhanceInfo = (TransportClientEnhanceInfo) objInst.getSkyWalkingDynamicField();
    TransportAddressCache transportAddressCache = transportClientEnhanceInfo.getTransportAddressCache();
    if (transportAddressCache == null) {
        transportAddressCache = new TransportAddressCache();
        transportClientEnhanceInfo.setTransportAddressCache(transportAddressCache);
    }
    transportAddressCache.addDiscoveryNode((TransportAddress[]) allArguments[0]);
    return ret;
}
 
Example 26
Source Project: crate   Source File: SrvUnicastHostsProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testParseRecords() {
    ByteBuf buf = Unpooled.buffer();
    buf.writeShort(0); // priority
    buf.writeShort(0); // weight
    buf.writeShort(993); // port
    encodeName("localhost.", buf);
    DnsRecord record = new DefaultDnsRawRecord("_myprotocol._tcp.crate.io.", DnsRecordType.SRV, 30, buf);

    List<TransportAddress> addresses = srvUnicastHostsProvider.parseRecords(Collections.singletonList(record));
    assertThat(addresses.get(0).getAddress(), is("127.0.0.1"));
    assertThat(addresses.get(0).getPort(), is(993));
}
 
Example 27
Source Project: Quicksql   Source File: EmbeddedElasticsearchNode.java    License: MIT License 5 votes vote down vote up
/**
 * Returns current address to connect to with HTTP client.
 *
 * @return hostname/port for HTTP connection
 */
public TransportAddress httpAddress() {
    Preconditions.checkState(isStarted, "node is not started");

    NodesInfoResponse response = client().admin().cluster().prepareNodesInfo()
        .execute().actionGet();
    if (response.getNodes().size() != 1) {
        throw new IllegalStateException("Expected single node but got "
            + response.getNodes().size());
    }
    NodeInfo node = response.getNodes().get(0);
    return node.getHttp().address().boundAddresses()[0];
}
 
Example 28
Source Project: deprecated-security-ssl   Source File: SSLTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTransportClientSSLFail() throws Exception {
    thrown.expect(NoNodeAvailableException.class);

    final Settings settings = Settings.builder().put("opendistro_security.ssl.transport.enabled", true)
            .put(SSLConfigConstants.OPENDISTRO_SECURITY_SSL_HTTP_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL)
            .put(SSLConfigConstants.OPENDISTRO_SECURITY_SSL_TRANSPORT_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL)
            .put(SSLConfigConstants.OPENDISTRO_SECURITY_SSL_TRANSPORT_KEYSTORE_ALIAS, "node-0")
            .put("opendistro_security.ssl.transport.keystore_filepath", getAbsoluteFilePathFromClassPath("node-0-keystore.jks"))
            .put("opendistro_security.ssl.transport.truststore_filepath", getAbsoluteFilePathFromClassPath("truststore.jks"))
            .put("opendistro_security.ssl.transport.enforce_hostname_verification", false)
            .put("opendistro_security.ssl.transport.resolve_hostname", false).build();

    startES(settings);

    final Settings tcSettings = Settings.builder().put("cluster.name", clustername)
            .put("path.home", getAbsoluteFilePathFromClassPath("node-0-keystore.jks").getParent())
            .put("opendistro_security.ssl.transport.keystore_filepath", getAbsoluteFilePathFromClassPath("node-0-keystore.jks"))
            .put("opendistro_security.ssl.transport.truststore_filepath", getAbsoluteFilePathFromClassPath("truststore_fail.jks"))
            .put("opendistro_security.ssl.transport.enforce_hostname_verification", false)
            .put("opendistro_security.ssl.transport.resolve_hostname", false).build();

    try (TransportClient tc = new TransportClientImpl(tcSettings, asCollection(OpenDistroSecuritySSLPlugin.class))) {
        tc.addTransportAddress(new TransportAddress(new InetSocketAddress(nodeHost, nodePort)));
        Assert.assertEquals(3, tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size());
    }
}
 
Example 29
@Test
public void testAutodiscover() throws IOException {
    startNode("2");
    Settings.Builder settingsBuilder = Settings.builder()
            .put("cluster.name", getClusterName())
            .put("path.home", System.getProperty("path.home"))
            .put("autodiscover", true);
    int i = 0;
    NodesInfoRequest nodesInfoRequest = new NodesInfoRequest().transport(true);
    NodesInfoResponse response = client("1").admin().cluster().nodesInfo(nodesInfoRequest).actionGet();
    for (NodeInfo nodeInfo : response) {
        TransportAddress ta = nodeInfo.getTransport().getAddress().publishAddress();
        if (ta instanceof InetSocketTransportAddress) {
            InetSocketTransportAddress address = (InetSocketTransportAddress) ta;
            settingsBuilder.put("host." + i++, address.address().getHostName() + ":" + address.address().getPort());
        }
    }
    final IngestTransportClient ingest = ClientBuilder.builder()
            .put(settingsBuilder.build())
            .setMetric(new LongAdderIngestMetric())
            .toIngestTransportClient();
    try {
        ingest.newIndex("test");
    } finally {
        ingest.shutdown();
    }
    if (ingest.hasThrowable()) {
        logger.error("error", ingest.getThrowable());
    }
    assertFalse(ingest.hasThrowable());
}
 
Example 30
Source Project: anomaly-detection   Source File: ClusterCreation.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a cluster state with 1 master node and a few data nodes
 * @param numDataNodes the number of data nodes
 * @return the cluster state
 */
public static ClusterState state(int numDataNodes) {
    DiscoveryNode masterNode = new DiscoveryNode(
        "foo0",
        "foo0",
        new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
        Collections.emptyMap(),
        Collections.singleton(MASTER_ROLE),
        Version.CURRENT
    );
    List<DiscoveryNode> allNodes = new ArrayList<>();
    allNodes.add(masterNode);
    for (int i = 1; i <= numDataNodes - 1; i++) {
        allNodes
            .add(
                new DiscoveryNode(
                    "foo" + i,
                    "foo" + i,
                    new TransportAddress(InetAddress.getLoopbackAddress(), 9300 + i),
                    Collections.emptyMap(),
                    Collections.singleton(DATA_ROLE),
                    Version.CURRENT
                )
            );
    }
    return state(new ClusterName("test"), masterNode, masterNode, allNodes);
}