Search in sources :

Example 21 with RestHighLevelClient

use of org.elasticsearch.client.RestHighLevelClient in project metron by apache.

the class ElasticsearchUpdateDaoTest method setup.

@BeforeEach
public void setup() {
    accessConfig = new AccessConfig();
    retrieveLatestDao = mock(ElasticsearchRetrieveLatestDao.class);
    RestHighLevelClient highLevel = mock(RestHighLevelClient.class);
    ElasticsearchClient client = new ElasticsearchClient(mock(RestClient.class), highLevel);
    updateDao = new ElasticsearchUpdateDao(client, accessConfig, retrieveLatestDao);
}
Also used : RestClient(org.elasticsearch.client.RestClient) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) AccessConfig(org.apache.metron.indexing.dao.AccessConfig) ElasticsearchClient(org.apache.metron.elasticsearch.client.ElasticsearchClient) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 22 with RestHighLevelClient

use of org.elasticsearch.client.RestHighLevelClient in project ranger by apache.

the class ElasticSearchAuditDestination method newClient.

private RestHighLevelClient newClient() {
    try {
        if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password) && password.contains("keytab") && new File(password).exists()) {
            subject = CredentialsProviderUtil.login(user, password);
        }
        RestClientBuilder restClientBuilder = getRestClientBuilder(hosts, protocol, user, password, port);
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Initialized client");
        }
        boolean exits = false;
        try {
            exits = restHighLevelClient.indices().open(new OpenIndexRequest(this.index), RequestOptions.DEFAULT).isShardsAcknowledged();
        } catch (Exception e) {
            LOG.warn("Error validating index " + this.index);
        }
        if (exits) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Index exists");
            }
        } else {
            LOG.info("Index does not exist");
        }
        return restHighLevelClient;
    } catch (Throwable t) {
        lastLoggedAt.updateAndGet(lastLoggedAt -> {
            long now = System.currentTimeMillis();
            long elapsed = now - lastLoggedAt;
            if (elapsed > TimeUnit.MINUTES.toMillis(1)) {
                LOG.error("Can't connect to ElasticSearch server: " + connectionString(), t);
                return now;
            } else {
                return lastLoggedAt;
            }
        });
        return null;
    }
}
Also used : RestClient(org.elasticsearch.client.RestClient) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) Arrays(java.util.Arrays) StringUtils(org.apache.commons.lang.StringUtils) RegistryBuilder(org.apache.http.config.RegistryBuilder) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) AuthSchemes(org.apache.http.client.config.AuthSchemes) OpenIndexRequest(org.elasticsearch.action.admin.indices.open.OpenIndexRequest) ArrayList(java.util.ArrayList) IndexRequest(org.elasticsearch.action.index.IndexRequest) KerberosCredentialsProvider(org.apache.ranger.authorization.credutils.kerberos.KerberosCredentialsProvider) Locale(java.util.Locale) Map(java.util.Map) Lookup(org.apache.http.config.Lookup) RequestOptions(org.elasticsearch.client.RequestOptions) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory) AuthzAuditEvent(org.apache.ranger.audit.model.AuthzAuditEvent) PrivilegedActionException(java.security.PrivilegedActionException) Properties(java.util.Properties) Logger(org.slf4j.Logger) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) Collection(java.util.Collection) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) File(java.io.File) Subject(javax.security.auth.Subject) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) MiscUtil(org.apache.ranger.audit.provider.MiscUtil) CredentialsProviderUtil(org.apache.ranger.authorization.credutils.CredentialsProviderUtil) AuditEventBase(org.apache.ranger.audit.model.AuditEventBase) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpHost(org.apache.http.HttpHost) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) OpenIndexRequest(org.elasticsearch.action.admin.indices.open.OpenIndexRequest) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) File(java.io.File) PrivilegedActionException(java.security.PrivilegedActionException)

Example 23 with RestHighLevelClient

use of org.elasticsearch.client.RestHighLevelClient in project datashare by ICIJ.

the class ElasticsearchConfiguration method createESClient.

public static RestHighLevelClient createESClient(final PropertiesProvider propertiesProvider) {
    System.setProperty("es.set.netty.runtime.available.processors", "false");
    try {
        URL indexUrl = new URL(propertiesProvider.get(INDEX_ADDRESS_PROP).orElse(DEFAULT_ADDRESS));
        HttpHost httpHost = create(format("%s://%s:%d", indexUrl.getProtocol(), indexUrl.getHost(), indexUrl.getPort()));
        RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback = httpClientBuilder -> httpClientBuilder;
        if (indexUrl.getUserInfo() != null) {
            String[] userInfo = indexUrl.getUserInfo().split(":");
            LOGGER.info("using credentials from url (user={})", userInfo[0]);
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userInfo[0], userInfo[1]));
            httpClientConfigCallback = httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHost).setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(5000).setSocketTimeout(60000)).setHttpClientConfigCallback(httpClientConfigCallback));
        String clusterName = propertiesProvider.get(CLUSTER_PROP).orElse(ES_CLUSTER_NAME);
        return client;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
Also used : RestClient(org.elasticsearch.client.RestClient) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) URLDecoder(java.net.URLDecoder) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) WriteRequest(org.elasticsearch.action.support.WriteRequest) Settings(org.elasticsearch.common.settings.Settings) RequestOptions(org.elasticsearch.client.RequestOptions) HttpHost.create(org.apache.http.HttpHost.create) Logger(org.slf4j.Logger) CreateIndexRequest(org.elasticsearch.client.indices.CreateIndexRequest) PropertiesProvider(org.icij.datashare.PropertiesProvider) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) String.format(java.lang.String.format) ByteStreams.toByteArray(com.google.common.io.ByteStreams.toByteArray) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) JSON(org.elasticsearch.common.xcontent.XContentType.JSON) AuthScope(org.apache.http.auth.AuthScope) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpHost(org.apache.http.HttpHost) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GetIndexRequest(org.elasticsearch.client.indices.GetIndexRequest) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) MalformedURLException(java.net.MalformedURLException) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) URL(java.net.URL) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.http.HttpHost)

Example 24 with RestHighLevelClient

use of org.elasticsearch.client.RestHighLevelClient in project datashare by ICIJ.

the class ElasticsearchConfigurationTest method test_create_client_with_user_pass.

@Test
public void test_create_client_with_user_pass() throws Exception {
    RestHighLevelClient esClient = ElasticsearchConfiguration.createESClient(new PropertiesProvider(new HashMap<String, String>() {

        {
            put("elasticsearchAddress", "http://user:pass@elasticsearch:9200");
        }
    }));
    Response response = esClient.getLowLevelClient().performRequest(new Request("GET", TEST_INDEX));
    assertThat(EntityUtils.toString(response.getEntity())).contains("settings");
}
Also used : PropertiesProvider(org.icij.datashare.PropertiesProvider) Response(org.elasticsearch.client.Response) HashMap(java.util.HashMap) Request(org.elasticsearch.client.Request) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) Test(org.junit.Test)

Example 25 with RestHighLevelClient

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

the class RestWriterVariant method getTestClient.

@Override
public TestClient getTestClient(Config config) throws IOException {
    final ElasticsearchRestWriter restWriter = new ElasticsearchRestWriter(config);
    final RestHighLevelClient highLevelClient = restWriter.getRestHighLevelClient();
    return new TestClient() {

        @Override
        public GetResponse get(GetRequest getRequest) throws IOException {
            return highLevelClient.get(getRequest);
        }

        @Override
        public void recreateIndex(String indexName) throws IOException {
            RestClient restClient = restWriter.getRestLowLevelClient();
            try {
                restClient.performRequest("DELETE", "/" + indexName);
            } catch (Exception e) {
            // ok since index may not exist
            }
            String indexSettings = "{\"settings\" : {\"index\":{\"number_of_shards\":1,\"number_of_replicas\":1}}}";
            HttpEntity entity = new StringEntity(indexSettings, ContentType.APPLICATION_JSON);
            Response putResponse = restClient.performRequest("PUT", "/" + indexName, Collections.emptyMap(), entity);
            Assert.assertEquals(putResponse.getStatusLine().getStatusCode(), 200, "Recreate index succeeded");
        }

        @Override
        public void close() throws IOException {
            restWriter.close();
        }
    };
}
Also used : GetResponse(org.elasticsearch.action.get.GetResponse) Response(org.elasticsearch.client.Response) StringEntity(org.apache.http.entity.StringEntity) HttpEntity(org.apache.http.HttpEntity) GetRequest(org.elasticsearch.action.get.GetRequest) RestClient(org.elasticsearch.client.RestClient) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) IOException(java.io.IOException)

Aggregations

RestHighLevelClient (org.elasticsearch.client.RestHighLevelClient)61 HttpHost (org.apache.http.HttpHost)23 RestClientBuilder (org.elasticsearch.client.RestClientBuilder)21 IOException (java.io.IOException)14 RestClient (org.elasticsearch.client.RestClient)13 HashMap (java.util.HashMap)10 IndexRequest (org.elasticsearch.action.index.IndexRequest)8 RequestOptions (org.elasticsearch.client.RequestOptions)7 Test (org.junit.jupiter.api.Test)7 CredentialsProvider (org.apache.http.client.CredentialsProvider)6 SearchRequest (org.elasticsearch.action.search.SearchRequest)6 SearchResponse (org.elasticsearch.action.search.SearchResponse)6 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 List (java.util.List)5 Map (java.util.Map)5 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)5 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)5 DeleteIndexRequest (org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest)5 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)5