Search in sources :

Example 11 with RestClientBuilder

use of org.elasticsearch.client.RestClientBuilder in project incubator-gobblin by apache.

the class ElasticsearchRestWriter method buildRestClient.

// TODO: Support pass through of configuration (e.g. timeouts etc) of rest client from above
private static RestClient buildRestClient(List<InetSocketTransportAddress> hosts, int threadCount, boolean sslEnabled, String keyStoreType, String keyStoreFilePassword, String identityFilepath, String trustStoreType, String trustStoreFilePassword, String cacertsFilepath) throws Exception {
    HttpHost[] httpHosts = new HttpHost[hosts.size()];
    String scheme = sslEnabled ? "https" : "http";
    for (int h = 0; h < httpHosts.length; h++) {
        InetSocketTransportAddress host = hosts.get(h);
        httpHosts[h] = new HttpHost(host.getAddress(), host.getPort(), scheme);
    }
    RestClientBuilder builder = RestClient.builder(httpHosts);
    if (sslEnabled) {
        log.info("ssl configuration: trustStoreType = {}, cacertsFilePath = {}", trustStoreType, cacertsFilepath);
        KeyStore truststore = KeyStore.getInstance(trustStoreType);
        FileInputStream trustInputStream = new FileInputStream(cacertsFilepath);
        try {
            truststore.load(trustInputStream, trustStoreFilePassword.toCharArray());
        } finally {
            trustInputStream.close();
        }
        SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(truststore, null);
        log.info("ssl key configuration: keyStoreType = {}, keyFilePath = {}", keyStoreType, identityFilepath);
        KeyStore keystore = KeyStore.getInstance(keyStoreType);
        FileInputStream keyInputStream = new FileInputStream(identityFilepath);
        try {
            keystore.load(keyInputStream, keyStoreFilePassword.toCharArray());
        } finally {
            keyInputStream.close();
        }
        sslBuilder.loadKeyMaterial(keystore, keyStoreFilePassword.toCharArray());
        final SSLContext sslContext = sslBuilder.build();
        builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build()));
    } else {
        builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build()));
    }
    // Configure timeouts
    builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectionRequestTimeout(// Important, otherwise the client has spurious timeouts
    0));
    return builder.build();
}
Also used : RestClient(org.elasticsearch.client.RestClient) SSLContext(javax.net.ssl.SSLContext) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) ConfigUtils(org.apache.gobblin.util.ConfigUtils) Batch(org.apache.gobblin.writer.Batch) Future(java.util.concurrent.Future) SSLContexts(org.apache.http.ssl.SSLContexts) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) Nullable(javax.annotation.Nullable) WriteResponse(org.apache.gobblin.writer.WriteResponse) WriteCallback(org.apache.gobblin.writer.WriteCallback) Pair(org.apache.commons.math3.util.Pair) Config(com.typesafe.config.Config) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) IOException(java.io.IOException) KeyStore(java.security.KeyStore) PasswordManager(org.apache.gobblin.password.PasswordManager) FileInputStream(java.io.FileInputStream) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Paths(java.nio.file.Paths) VisibleForTesting(com.google.common.annotations.VisibleForTesting) HttpHost(org.apache.http.HttpHost) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) BatchAsyncDataWriter(org.apache.gobblin.writer.BatchAsyncDataWriter) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HttpHost(org.apache.http.HttpHost) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) SSLContext(javax.net.ssl.SSLContext) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) KeyStore(java.security.KeyStore) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) FileInputStream(java.io.FileInputStream)

Example 12 with RestClientBuilder

use of org.elasticsearch.client.RestClientBuilder in project thingsboard by thingsboard.

the class ElasticsearchAuditLogSink method init.

@PostConstruct
public void init() {
    try {
        log.trace("Adding elastic rest endpoint... host [{}], port [{}], scheme name [{}]", host, port, schemeName);
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, schemeName));
        if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)) {
            log.trace("...using username [{}] and password ***", userName);
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        }
        this.restClient = builder.build();
    } catch (Exception e) {
        log.error("Sink init failed!", e);
        throw new RuntimeException(e.getMessage(), e);
    }
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) PostConstruct(javax.annotation.PostConstruct)

Example 13 with RestClientBuilder

use of org.elasticsearch.client.RestClientBuilder in project elasticsearch by elastic.

the class ESRestTestCase method buildClient.

protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException {
    RestClientBuilder builder = RestClient.builder(hosts);
    String keystorePath = settings.get(TRUSTSTORE_PATH);
    if (keystorePath != null) {
        final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
        if (keystorePass == null) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
        }
        Path path = PathUtils.get(keystorePath);
        if (!Files.exists(path)) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keystorePass.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
            SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext);
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy));
        } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException | CertificateException e) {
            throw new RuntimeException("Error setting up ssl", e);
        }
    }
    try (ThreadContext threadContext = new ThreadContext(settings)) {
        Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
        int i = 0;
        for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
            defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
        }
        builder.setDefaultHeaders(defaultHeaders);
    }
    return builder.build();
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) SSLIOSessionStrategy(org.apache.http.nio.conn.ssl.SSLIOSessionStrategy) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) BasicHeader(org.apache.http.message.BasicHeader)

Example 14 with RestClientBuilder

use of org.elasticsearch.client.RestClientBuilder in project elasticsearch by elastic.

the class ESIntegTestCase method createRestClient.

protected static RestClient createRestClient(RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback, String protocol) {
    final NodesInfoResponse nodeInfos = client().admin().cluster().prepareNodesInfo().get();
    final List<NodeInfo> nodes = nodeInfos.getNodes();
    assertFalse(nodeInfos.hasFailures());
    List<HttpHost> hosts = new ArrayList<>();
    for (NodeInfo node : nodes) {
        if (node.getHttp() != null) {
            TransportAddress publishAddress = node.getHttp().address().publishAddress();
            InetSocketAddress address = publishAddress.address();
            hosts.add(new HttpHost(NetworkAddress.format(address.getAddress()), address.getPort(), protocol));
        }
    }
    RestClientBuilder builder = RestClient.builder(hosts.toArray(new HttpHost[hosts.size()]));
    if (httpClientConfigCallback != null) {
        builder.setHttpClientConfigCallback(httpClientConfigCallback);
    }
    return builder.build();
}
Also used : NodesInfoResponse(org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse) NodeInfo(org.elasticsearch.action.admin.cluster.node.info.NodeInfo) HttpHost(org.apache.http.HttpHost) TransportAddress(org.elasticsearch.common.transport.TransportAddress) InetSocketAddress(java.net.InetSocketAddress) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) RestClientBuilder(org.elasticsearch.client.RestClientBuilder)

Example 15 with RestClientBuilder

use of org.elasticsearch.client.RestClientBuilder in project nifi by apache.

the class ElasticSearchClientServiceImpl method setupClient.

private void setupClient(ConfigurationContext context) throws MalformedURLException, InitializationException {
    final String hosts = context.getProperty(HTTP_HOSTS).evaluateAttributeExpressions().getValue();
    String[] hostsSplit = hosts.split(",[\\s]*");
    this.url = hostsSplit[0];
    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    final String username = context.getProperty(USERNAME).evaluateAttributeExpressions().getValue();
    final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue();
    final Integer connectTimeout = context.getProperty(CONNECT_TIMEOUT).asInteger();
    final Integer readTimeout = context.getProperty(SOCKET_TIMEOUT).asInteger();
    final Integer retryTimeout = context.getProperty(RETRY_TIMEOUT).asInteger();
    HttpHost[] hh = new HttpHost[hostsSplit.length];
    for (int x = 0; x < hh.length; x++) {
        URL u = new URL(hostsSplit[x]);
        hh[x] = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
    }
    final SSLContext sslContext;
    try {
        sslContext = (sslService != null && sslService.isKeyStoreConfigured() && sslService.isTrustStoreConfigured()) ? buildSslContext(sslService) : null;
    } catch (IOException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | KeyManagementException e) {
        getLogger().error("Error building up SSL Context from the supplied configuration.", e);
        throw new InitializationException(e);
    }
    RestClientBuilder builder = RestClient.builder(hh).setHttpClientConfigCallback(httpClientBuilder -> {
        if (sslContext != null) {
            httpClientBuilder = httpClientBuilder.setSSLContext(sslContext);
        }
        if (username != null && password != null) {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
            httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }
        return httpClientBuilder;
    }).setRequestConfigCallback(requestConfigBuilder -> {
        requestConfigBuilder.setConnectTimeout(connectTimeout);
        requestConfigBuilder.setSocketTimeout(readTimeout);
        return requestConfigBuilder;
    }).setMaxRetryTimeoutMillis(retryTimeout);
    this.client = builder.build();
}
Also used : RestClient(org.elasticsearch.client.RestClient) SSLContext(javax.net.ssl.SSLContext) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) ConfigurationContext(org.apache.nifi.controller.ConfigurationContext) InitializationException(org.apache.nifi.reporting.InitializationException) URL(java.net.URL) HashMap(java.util.HashMap) KeyStoreException(java.security.KeyStoreException) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ArrayList(java.util.ArrayList) SecureRandom(java.security.SecureRandom) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) Charset(java.nio.charset.Charset) UnrecoverableKeyException(java.security.UnrecoverableKeyException) Map(java.util.Map) AbstractControllerService(org.apache.nifi.controller.AbstractControllerService) NStringEntity(org.apache.http.nio.entity.NStringEntity) OnEnabled(org.apache.nifi.annotation.lifecycle.OnEnabled) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) MalformedURLException(java.net.MalformedURLException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) SSLContextService(org.apache.nifi.ssl.SSLContextService) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) IOException(java.io.IOException) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) AuthScope(org.apache.http.auth.AuthScope) Response(org.elasticsearch.client.Response) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpHost(org.apache.http.HttpHost) Collections(java.util.Collections) OnDisabled(org.apache.nifi.annotation.lifecycle.OnDisabled) InputStream(java.io.InputStream) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) InitializationException(org.apache.nifi.reporting.InitializationException) URL(java.net.URL) KeyManagementException(java.security.KeyManagementException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) UnrecoverableKeyException(java.security.UnrecoverableKeyException) HttpHost(org.apache.http.HttpHost) SSLContextService(org.apache.nifi.ssl.SSLContextService)

Aggregations

RestClientBuilder (org.elasticsearch.client.RestClientBuilder)34 HttpHost (org.apache.http.HttpHost)27 RestHighLevelClient (org.elasticsearch.client.RestHighLevelClient)23 RestClient (org.elasticsearch.client.RestClient)15 IOException (java.io.IOException)11 CredentialsProvider (org.apache.http.client.CredentialsProvider)11 ArrayList (java.util.ArrayList)7 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)7 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)7 File (java.io.File)6 List (java.util.List)6 Locale (java.util.Locale)6 KeyStore (java.security.KeyStore)5 Map (java.util.Map)5 StringUtils (org.apache.commons.lang.StringUtils)5 AuthSchemeProvider (org.apache.http.auth.AuthSchemeProvider)5 AuthSchemes (org.apache.http.client.config.AuthSchemes)5 Lookup (org.apache.http.config.Lookup)5 RegistryBuilder (org.apache.http.config.RegistryBuilder)5 SPNegoSchemeFactory (org.apache.http.impl.auth.SPNegoSchemeFactory)5