Search in sources :

Example 36 with RestHighLevelClient

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

the class ElasticSearchAccessAuditsService method searchXAccessAudits.

public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) {
    RestHighLevelClient client = elasticSearchMgr.getClient();
    final boolean hiveQueryVisibility = PropertiesUtil.getBooleanProperty("ranger.audit.hive.query.visibility", true);
    if (client == null) {
        LOGGER.warn("ElasticSearch client is null, so not running the query.");
        throw restErrorUtil.createRESTException("Error connecting to search engine", MessageEnums.ERROR_SYSTEM);
    }
    List<VXAccessAudit> xAccessAuditList = new ArrayList<VXAccessAudit>();
    Map<String, Object> paramList = searchCriteria.getParamList();
    updateUserExclusion(paramList);
    SearchResponse response;
    try {
        response = elasticSearchUtil.searchResources(searchCriteria, searchFields, sortFields, client, elasticSearchMgr.index);
    } catch (IOException e) {
        LOGGER.warn(String.format("ElasticSearch query failed: %s", e.getMessage()));
        throw restErrorUtil.createRESTException("Error querying search engine", MessageEnums.ERROR_SYSTEM);
    }
    MultiGetItemResponse[] docs;
    try {
        docs = elasticSearchUtil.fetch(client, elasticSearchMgr.index, response.getHits().getHits());
    } catch (IOException e) {
        LOGGER.warn(String.format("ElasticSearch fetch failed: %s", e.getMessage()));
        throw restErrorUtil.createRESTException("Error querying search engine", MessageEnums.ERROR_SYSTEM);
    }
    for (int i = 0; i < docs.length; i++) {
        // NOPMD - This for loop can be replaced by a foreach loop
        MultiGetItemResponse doc = docs[i];
        VXAccessAudit vXAccessAudit = populateViewBean(doc.getResponse());
        if (vXAccessAudit != null) {
            String serviceType = vXAccessAudit.getServiceType();
            boolean isHive = "hive".equalsIgnoreCase(serviceType);
            if (!hiveQueryVisibility && isHive) {
                vXAccessAudit.setRequestData(null);
            } else if (isHive) {
                String accessType = vXAccessAudit.getAccessType();
                if ("grant".equalsIgnoreCase(accessType) || "revoke".equalsIgnoreCase(accessType)) {
                    String requestData = vXAccessAudit.getRequestData();
                    if (requestData != null) {
                        try {
                            vXAccessAudit.setRequestData(java.net.URLDecoder.decode(requestData, "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            LOGGER.warn("Error while encoding request data: " + requestData, e);
                        }
                    } else {
                        LOGGER.warn("Error in request data of audit from elasticSearch. AuditData: " + vXAccessAudit.toString());
                    }
                }
            }
        }
        xAccessAuditList.add(vXAccessAudit);
    }
    VXAccessAuditList returnList = new VXAccessAuditList();
    returnList.setPageSize(searchCriteria.getMaxRows());
    returnList.setResultSize(response.getHits().getHits().length);
    returnList.setTotalCount(response.getHits().getTotalHits().value);
    returnList.setStartIndex(searchCriteria.getStartIndex());
    returnList.setVXAccessAudits(xAccessAuditList);
    return returnList;
}
Also used : MultiGetItemResponse(org.elasticsearch.action.get.MultiGetItemResponse) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) IOException(java.io.IOException) VXAccessAuditList(org.apache.ranger.view.VXAccessAuditList) SearchResponse(org.elasticsearch.action.search.SearchResponse) VXAccessAudit(org.apache.ranger.view.VXAccessAudit)

Example 37 with RestHighLevelClient

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

the class ElasticSearchUtil method searchResources.

public SearchResponse searchResources(SearchCriteria searchCriteria, List<SearchField> searchFields, List<SortField> sortFields, RestHighLevelClient client, String index) throws IOException {
    // See Also: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-query-builders.html
    QueryAccumulator queryAccumulator = new QueryAccumulator(searchCriteria);
    if (searchCriteria.getParamList() != null) {
        searchFields.stream().forEach(queryAccumulator::addQuery);
        // hashmap for each field name
        if (queryAccumulator.fromDate != null || queryAccumulator.toDate != null) {
            queryAccumulator.queries.add(setDateRange(queryAccumulator.dateFieldName, queryAccumulator.fromDate, queryAccumulator.toDate));
        }
    }
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    queryAccumulator.queries.stream().filter(x -> x != null).forEach(boolQueryBuilder::must);
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    setSortClause(searchCriteria, sortFields, searchSourceBuilder);
    searchSourceBuilder.from(searchCriteria.getStartIndex());
    searchSourceBuilder.size(searchCriteria.getMaxRows());
    searchSourceBuilder.fetchSource(true);
    SearchRequest query = new SearchRequest();
    query.indices(index);
    query.source(searchSourceBuilder.query(boolQueryBuilder));
    return client.search(query, RequestOptions.DEFAULT);
}
Also used : java.util(java.util) LoggerFactory(org.slf4j.LoggerFactory) LocalDateTime(java.time.LocalDateTime) MultiGetRequest(org.elasticsearch.action.get.MultiGetRequest) Autowired(org.springframework.beans.factory.annotation.Autowired) SimpleDateFormat(java.text.SimpleDateFormat) SearchRequest(org.elasticsearch.action.search.SearchRequest) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) SearchResponse(org.elasticsearch.action.search.SearchResponse) RequestOptions(org.elasticsearch.client.RequestOptions) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) SearchHit(org.elasticsearch.search.SearchHit) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) org.apache.ranger.common(org.apache.ranger.common) Logger(org.slf4j.Logger) RangeQueryBuilder(org.elasticsearch.index.query.RangeQueryBuilder) IOException(java.io.IOException) MultiGetItemResponse(org.elasticsearch.action.get.MultiGetItemResponse) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) ZoneId(java.time.ZoneId) Component(org.springframework.stereotype.Component) DateTimeFormatter(java.time.format.DateTimeFormatter) SortOrder(org.elasticsearch.search.sort.SortOrder) ClientUtils(org.apache.solr.client.solrj.util.ClientUtils) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) SearchRequest(org.elasticsearch.action.search.SearchRequest) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder)

Example 38 with RestHighLevelClient

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

the class ElasticSearchMgr method connect.

synchronized void connect() {
    if (client == null) {
        synchronized (ElasticSearchAuditDestination.class) {
            if (client == null) {
                String urls = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_URLS);
                String protocol = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PROTOCOL, "http");
                user = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_USER, "");
                password = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PWRD, "");
                int port = Integer.parseInt(PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PORT));
                this.index = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_INDEX, "ranger_audits");
                String parameterString = String.format(Locale.ROOT, "User:%s, %s://%s:%s/%s", user, protocol, urls, port, index);
                logger.info("Initializing ElasticSearch " + parameterString);
                if (urls != null) {
                    urls = urls.trim();
                }
                if (StringUtils.isBlank(urls) || "NONE".equalsIgnoreCase(urls.trim())) {
                    logger.info(String.format("Clearing URI config value: %s", urls));
                    urls = null;
                }
                try {
                    if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password) && password.contains("keytab") && new File(password).exists()) {
                        subject = CredentialsProviderUtil.login(user, password);
                    }
                    RestClientBuilder restClientBuilder = getRestClientBuilder(urls, protocol, user, password, port);
                    client = new RestHighLevelClient(restClientBuilder);
                } catch (Throwable t) {
                    logger.error("Can't connect to ElasticSearch: " + parameterString, t);
                }
            }
        }
    }
}
Also used : ElasticSearchAuditDestination(org.apache.ranger.audit.destination.ElasticSearchAuditDestination) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) File(java.io.File)

Example 39 with RestHighLevelClient

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

the class ElasticSearchAuditDestination method log.

@Override
public boolean log(Collection<AuditEventBase> events) {
    boolean ret = false;
    try {
        logStatusIfRequired();
        addTotalCount(events.size());
        RestHighLevelClient client = getClient();
        if (null == client) {
            // ElasticSearch is still not initialized. So need return error
            addDeferredCount(events.size());
            return ret;
        }
        ArrayList<AuditEventBase> eventList = new ArrayList<>(events);
        BulkRequest bulkRequest = new BulkRequest();
        try {
            for (AuditEventBase event : eventList) {
                AuthzAuditEvent authzEvent = (AuthzAuditEvent) event;
                String id = authzEvent.getEventId();
                Map<String, Object> doc = toDoc(authzEvent);
                bulkRequest.add(new IndexRequest(index).id(id).source(doc));
            }
        } catch (Exception ex) {
            addFailedCount(eventList.size());
            logFailedEvent(eventList, ex);
        }
        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        if (response.status().getStatus() >= 400) {
            addFailedCount(eventList.size());
            logFailedEvent(eventList, "HTTP " + response.status().getStatus());
        } else {
            BulkItemResponse[] items = response.getItems();
            for (int i = 0; i < items.length; i++) {
                AuditEventBase itemRequest = eventList.get(i);
                BulkItemResponse itemResponse = items[i];
                if (itemResponse.isFailed()) {
                    addFailedCount(1);
                    logFailedEvent(Arrays.asList(itemRequest), itemResponse.getFailureMessage());
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(String.format("Indexed %s", itemRequest.getEventKey()));
                    }
                    addSuccessCount(1);
                    ret = true;
                }
            }
        }
    } catch (Throwable t) {
        addDeferredCount(events.size());
        logError("Error sending message to ElasticSearch", t);
    }
    return ret;
}
Also used : AuditEventBase(org.apache.ranger.audit.model.AuditEventBase) ArrayList(java.util.ArrayList) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) OpenIndexRequest(org.elasticsearch.action.admin.indices.open.OpenIndexRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) PrivilegedActionException(java.security.PrivilegedActionException) AuthzAuditEvent(org.apache.ranger.audit.model.AuthzAuditEvent) BulkRequest(org.elasticsearch.action.bulk.BulkRequest)

Example 40 with RestHighLevelClient

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

the class ElasticSearchIndexBootStrapper method createClient.

private void createClient() {
    try {
        RestClientBuilder restClientBuilder = getRestClientBuilder(hosts, protocol, user, password, port);
        client = new RestHighLevelClient(restClientBuilder);
    } catch (Throwable t) {
        lastLoggedAt.updateAndGet(lastLoggedAt -> {
            long now = System.currentTimeMillis();
            long elapsed = now - lastLoggedAt;
            if (elapsed > TimeUnit.MINUTES.toMillis(1)) {
                LOG.severe("Can't connect to ElasticSearch server: " + connectionString() + t);
                return now;
            } else {
                return lastLoggedAt;
            }
        });
    }
}
Also used : RestClient(org.elasticsearch.client.RestClient) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) StringUtils(org.apache.commons.lang.StringUtils) RegistryBuilder(org.apache.http.config.RegistryBuilder) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) XContentType(org.elasticsearch.common.xcontent.XContentType) AuthSchemes(org.apache.http.client.config.AuthSchemes) OpenIndexRequest(org.elasticsearch.action.admin.indices.open.OpenIndexRequest) Settings(org.elasticsearch.common.settings.Settings) KerberosCredentialsProvider(org.apache.ranger.authorization.credutils.kerberos.KerberosCredentialsProvider) Locale(java.util.Locale) CredentialReader(org.apache.ranger.credentialapi.CredentialReader) TimeValue(org.elasticsearch.common.unit.TimeValue) Lookup(org.apache.http.config.Lookup) RequestOptions(org.elasticsearch.client.RequestOptions) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory) Path(java.nio.file.Path) CreateIndexRequest(org.elasticsearch.client.indices.CreateIndexRequest) Files(java.nio.file.Files) IOException(java.io.IOException) KeyStore(java.security.KeyStore) Logger(java.util.logging.Logger) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Paths(java.nio.file.Paths) CredentialsProviderUtil(org.apache.ranger.authorization.credutils.CredentialsProviderUtil) CreateIndexResponse(org.elasticsearch.client.indices.CreateIndexResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpHost(org.apache.http.HttpHost) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient)

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