Search in sources :

Example 71 with Indices

use of org.graylog2.indexer.indices.Indices in project graylog2-server by Graylog2.

the class ClusterAdapterES7 method clusterHealth.

private Optional<ClusterHealthResponse> clusterHealth(Collection<String> indices) {
    final String[] indicesAry = indices.toArray(new String[0]);
    if (!indices.isEmpty() && !indicesExist(indicesAry)) {
        return Optional.empty();
    }
    final ClusterHealthRequest request = new ClusterHealthRequest(indicesAry).timeout(TimeValue.timeValueSeconds(Ints.saturatedCast(requestTimeout.toSeconds()))).indicesOptions(IndicesOptions.lenientExpand());
    try {
        return Optional.of(client.execute((c, requestOptions) -> c.cluster().health(request, requestOptions)));
    } catch (ElasticsearchException e) {
        if (LOG.isDebugEnabled()) {
            LOG.error("{} ({})", e.getMessage(), Optional.ofNullable(e.getCause()).map(Throwable::getMessage).orElse("n/a"), e);
        } else {
            LOG.error("{} ({})", e.getMessage(), Optional.ofNullable(e.getCause()).map(Throwable::getMessage).orElse("n/a"));
        }
        return Optional.empty();
    }
}
Also used : ClusterHealthResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterGetSettingsRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.settings.ClusterGetSettingsRequest) NodesStats(org.graylog2.system.stats.elasticsearch.NodesStats) LoggerFactory(org.slf4j.LoggerFactory) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) ClusterGetSettingsResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.settings.ClusterGetSettingsResponse) ClusterHealthStatus(org.graylog.shaded.elasticsearch7.org.elasticsearch.cluster.health.ClusterHealthStatus) HealthStatus(org.graylog2.indexer.indices.HealthStatus) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) ClusterStats(org.graylog2.system.stats.elasticsearch.ClusterStats) TimeValue(org.graylog.shaded.elasticsearch7.org.elasticsearch.common.unit.TimeValue) Locale(java.util.Locale) IndicesOptions(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.support.IndicesOptions) ClusterHealth(org.graylog2.rest.models.system.indexer.responses.ClusterHealth) JsonNode(com.fasterxml.jackson.databind.JsonNode) Duration(com.github.joschi.jadconfig.util.Duration) Named(javax.inject.Named) JsonNodeType(com.fasterxml.jackson.databind.node.JsonNodeType) ClusterAllocationDiskSettingsFactory(org.graylog2.indexer.cluster.health.ClusterAllocationDiskSettingsFactory) GetIndexRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.indices.GetIndexRequest) Logger(org.slf4j.Logger) CatApi(org.graylog.storage.elasticsearch7.cat.CatApi) Collection(java.util.Collection) Request(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.Request) PendingTasksStats(org.graylog2.indexer.cluster.PendingTasksStats) IndicesStats(org.graylog2.system.stats.elasticsearch.IndicesStats) Set(java.util.Set) ClusterAllocationDiskSettings(org.graylog2.indexer.cluster.health.ClusterAllocationDiskSettings) NodeFileDescriptorStats(org.graylog2.indexer.cluster.health.NodeFileDescriptorStats) Ints(com.google.common.primitives.Ints) ClusterHealthRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) Collectors(java.util.stream.Collectors) ShardStats(org.graylog2.system.stats.elasticsearch.ShardStats) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) List(java.util.List) NodeDiskUsageStats(org.graylog2.indexer.cluster.health.NodeDiskUsageStats) Optional(java.util.Optional) ClusterAdapter(org.graylog2.indexer.cluster.ClusterAdapter) NodeResponse(org.graylog.storage.elasticsearch7.cat.NodeResponse) ClusterHealthRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) ElasticsearchException(org.graylog2.indexer.ElasticsearchException)

Example 72 with Indices

use of org.graylog2.indexer.indices.Indices in project graylog2-server by Graylog2.

the class IndicesAdapterES7 method indexRangeStatsOfIndex.

@Override
public IndexRangeStats indexRangeStatsOfIndex(String index) {
    final FilterAggregationBuilder builder = AggregationBuilders.filter("agg", QueryBuilders.existsQuery(Message.FIELD_TIMESTAMP)).subAggregation(AggregationBuilders.min("ts_min").field(Message.FIELD_TIMESTAMP)).subAggregation(AggregationBuilders.max("ts_max").field(Message.FIELD_TIMESTAMP)).subAggregation(AggregationBuilders.terms("streams").size(Integer.MAX_VALUE).field(Message.FIELD_STREAMS));
    final SearchSourceBuilder query = SearchSourceBuilder.searchSource().aggregation(builder).size(0);
    final SearchRequest request = new SearchRequest().source(query).indices(index).searchType(SearchType.DFS_QUERY_THEN_FETCH).indicesOptions(IndicesOptions.lenientExpandOpen());
    final SearchResponse result = client.execute((c, requestOptions) -> c.search(request, requestOptions), "Couldn't build index range of index " + index);
    if (result.getTotalShards() == 0 || result.getAggregations() == null) {
        throw new IndexNotFoundException("Couldn't build index range of index " + index + " because it doesn't exist.");
    }
    final Filter f = result.getAggregations().get("agg");
    if (f == null) {
        throw new IndexNotFoundException("Couldn't build index range of index " + index + " because it doesn't exist.");
    } else if (f.getDocCount() == 0L) {
        LOG.debug("No documents with attribute \"timestamp\" found in index <{}>", index);
        return IndexRangeStats.EMPTY;
    }
    final Min minAgg = f.getAggregations().get("ts_min");
    final long minUnixTime = new Double(minAgg.getValue()).longValue();
    final DateTime min = new DateTime(minUnixTime, DateTimeZone.UTC);
    final Max maxAgg = f.getAggregations().get("ts_max");
    final long maxUnixTime = new Double(maxAgg.getValue()).longValue();
    final DateTime max = new DateTime(maxUnixTime, DateTimeZone.UTC);
    // make sure we return an empty list, so we can differentiate between old indices that don't have this information
    // and newer ones that simply have no streams.
    final Terms streams = f.getAggregations().get("streams");
    final List<String> streamIds = streams.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(toList());
    return IndexRangeStats.create(min, max, streamIds);
}
Also used : SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) FilterAggregationBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) Max(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.metrics.Max) Terms(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.terms.Terms) DateTime(org.joda.time.DateTime) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse) Min(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.metrics.Min) Filter(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.filter.Filter) MultiBucketsAggregation(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation) IndexNotFoundException(org.graylog2.indexer.IndexNotFoundException)

Example 73 with Indices

use of org.graylog2.indexer.indices.Indices in project graylog2-server by Graylog2.

the class MoreSearchAdapterES7 method eventSearch.

@Override
public MoreSearch.Result eventSearch(String queryString, TimeRange timerange, Set<String> affectedIndices, Sorting sorting, int page, int perPage, Set<String> eventStreams, String filterString, Set<String> forbiddenSourceStreams) {
    final QueryBuilder query = (queryString.isEmpty() || queryString.equals("*")) ? matchAllQuery() : queryStringQuery(queryString).allowLeadingWildcard(allowLeadingWildcard);
    final BoolQueryBuilder filter = boolQuery().filter(query).filter(termsQuery(EventDto.FIELD_STREAMS, eventStreams)).filter(requireNonNull(TimeRangeQueryFactory.create(timerange)));
    if (!isNullOrEmpty(filterString)) {
        filter.filter(queryStringQuery(filterString));
    }
    if (!forbiddenSourceStreams.isEmpty()) {
        // If an event has any stream in "source_streams" that the calling search user is not allowed to access,
        // the event must not be in the search result.
        filter.filter(boolQuery().mustNot(termsQuery(EventDto.FIELD_SOURCE_STREAMS, forbiddenSourceStreams)));
    }
    final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(filter).from((page - 1) * perPage).size(perPage).sort(sorting.getField(), sortOrderMapper.fromSorting(sorting)).trackTotalHits(true);
    final Set<String> indices = affectedIndices.isEmpty() ? Collections.singleton("") : affectedIndices;
    final SearchRequest searchRequest = new SearchRequest(indices.toArray(new String[0])).source(searchSourceBuilder).indicesOptions(INDICES_OPTIONS);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Query:\n{}", searchSourceBuilder.toString(new ToXContent.MapParams(Collections.singletonMap("pretty", "true"))));
        LOG.debug("Execute search: {}", searchRequest.toString());
    }
    final SearchResponse searchResult = client.search(searchRequest, "Unable to perform search query");
    final List<ResultMessage> hits = Streams.stream(searchResult.getHits()).map(ResultMessageFactory::fromSearchHit).collect(Collectors.toList());
    final long total = searchResult.getHits().getTotalHits().value;
    return MoreSearch.Result.builder().results(hits).resultsCount(total).duration(searchResult.getTook().getMillis()).usedIndexNames(affectedIndices).executedQuery(searchSourceBuilder.toString()).build();
}
Also used : SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) BoolQueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.BoolQueryBuilder) QueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.BoolQueryBuilder) ResultMessage(org.graylog2.indexer.results.ResultMessage) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse)

Example 74 with Indices

use of org.graylog2.indexer.indices.Indices in project graylog2-server by Graylog2.

the class ElasticsearchBackend method doRun.

@Override
public QueryResult doRun(SearchJob job, Query query, ESGeneratedQueryContext queryContext) {
    if (query.searchTypes().isEmpty()) {
        return QueryResult.builder().query(query).searchTypes(Collections.emptyMap()).errors(new HashSet<>(queryContext.errors())).build();
    }
    LOG.debug("Running query {} for job {}", query.id(), job.getId());
    final HashMap<String, SearchType.Result> resultsMap = Maps.newHashMap();
    final Set<String> affectedIndices = indexLookup.indexNamesForStreamsInTimeRange(query.usedStreamIds(), query.timerange());
    final Map<String, SearchSourceBuilder> searchTypeQueries = queryContext.searchTypeQueries();
    final List<String> searchTypeIds = new ArrayList<>(searchTypeQueries.keySet());
    final List<SearchRequest> searches = searchTypeIds.stream().map(searchTypeId -> {
        final Set<String> affectedIndicesForSearchType = query.searchTypes().stream().filter(s -> s.id().equalsIgnoreCase(searchTypeId)).findFirst().flatMap(searchType -> {
            if (searchType.effectiveStreams().isEmpty() && !query.globalOverride().flatMap(GlobalOverride::timerange).isPresent() && !searchType.timerange().isPresent()) {
                return Optional.empty();
            }
            final Set<String> usedStreamIds = searchType.effectiveStreams().isEmpty() ? query.usedStreamIds() : searchType.effectiveStreams();
            return Optional.of(indexLookup.indexNamesForStreamsInTimeRange(usedStreamIds, query.effectiveTimeRange(searchType)));
        }).orElse(affectedIndices);
        Set<String> indices = affectedIndicesForSearchType.isEmpty() ? Collections.singleton("") : affectedIndicesForSearchType;
        return new SearchRequest().source(searchTypeQueries.get(searchTypeId)).indices(indices.toArray(new String[0])).indicesOptions(IndicesOptions.fromOptions(false, false, true, false));
    }).collect(Collectors.toList());
    final List<MultiSearchResponse.Item> results = client.msearch(searches, "Unable to perform search query: ");
    for (SearchType searchType : query.searchTypes()) {
        final String searchTypeId = searchType.id();
        final Provider<ESSearchTypeHandler<? extends SearchType>> handlerProvider = elasticsearchSearchTypeHandlers.get(searchType.type());
        if (handlerProvider == null) {
            LOG.error("Unknown search type '{}', cannot convert query result.", searchType.type());
            // no need to add another error here, as the query generation code will have added the error about the missing handler already
            continue;
        }
        if (isSearchTypeWithError(queryContext, searchTypeId)) {
            LOG.error("Failed search type '{}', cannot convert query result, skipping.", searchType.type());
            // no need to add another error here, as the query generation code will have added the error about the missing handler already
            continue;
        }
        // we create a new instance because some search type handlers might need to track information between generating the query and
        // processing its result, such as aggregations, which depend on the name and type
        final ESSearchTypeHandler<? extends SearchType> handler = handlerProvider.get();
        final int searchTypeIndex = searchTypeIds.indexOf(searchTypeId);
        final MultiSearchResponse.Item multiSearchResponse = results.get(searchTypeIndex);
        if (multiSearchResponse.isFailure()) {
            ElasticsearchException e = new ElasticsearchException("Search type returned error: ", multiSearchResponse.getFailure());
            queryContext.addError(SearchTypeErrorParser.parse(query, searchTypeId, e));
        } else if (checkForFailedShards(multiSearchResponse).isPresent()) {
            ElasticsearchException e = checkForFailedShards(multiSearchResponse).get();
            queryContext.addError(SearchTypeErrorParser.parse(query, searchTypeId, e));
        } else {
            final SearchType.Result searchTypeResult = handler.extractResult(job, query, searchType, multiSearchResponse.getResponse(), queryContext);
            if (searchTypeResult != null) {
                resultsMap.put(searchTypeId, searchTypeResult);
            }
        }
    }
    LOG.debug("Query {} ran for job {}", query.id(), job.getId());
    return QueryResult.builder().query(query).searchTypes(resultsMap).errors(new HashSet<>(queryContext.errors())).build();
}
Also used : ESSearchTypeHandler(org.graylog.storage.elasticsearch7.views.searchtypes.ESSearchTypeHandler) AndFilter(org.graylog.plugins.views.search.filter.AndFilter) ElasticsearchClient(org.graylog.storage.elasticsearch7.ElasticsearchClient) Arrays(java.util.Arrays) BackendQuery(org.graylog.plugins.views.search.engine.BackendQuery) QueryBackend(org.graylog.plugins.views.search.engine.QueryBackend) Provider(javax.inject.Provider) LoggerFactory(org.slf4j.LoggerFactory) FieldTypeException(org.graylog2.indexer.FieldTypeException) MultiSearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse) StreamFilter(org.graylog.plugins.views.search.filter.StreamFilter) Map(java.util.Map) IndicesOptions(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.support.IndicesOptions) SearchConfig(org.graylog.plugins.views.search.engine.SearchConfig) Set(java.util.Set) Collectors(java.util.stream.Collectors) BoolQueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.BoolQueryBuilder) Objects(java.util.Objects) List(java.util.List) Filter(org.graylog.plugins.views.search.Filter) Optional(java.util.Optional) SearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse) Query(org.graylog.plugins.views.search.Query) SearchTypeErrorParser(org.graylog.plugins.views.search.errors.SearchTypeErrorParser) HashMap(java.util.HashMap) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) ShardOperationFailedException(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.ShardOperationFailedException) ArrayList(java.util.ArrayList) GlobalOverride(org.graylog.plugins.views.search.GlobalOverride) Inject(javax.inject.Inject) HashSet(java.util.HashSet) OrFilter(org.graylog.plugins.views.search.filter.OrFilter) SearchType(org.graylog.plugins.views.search.SearchType) QueryStringFilter(org.graylog.plugins.views.search.filter.QueryStringFilter) SearchTypeError(org.graylog.plugins.views.search.errors.SearchTypeError) QueryResult(org.graylog.plugins.views.search.QueryResult) TimeRangeQueryFactory(org.graylog.storage.elasticsearch7.TimeRangeQueryFactory) SearchJob(org.graylog.plugins.views.search.SearchJob) QueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) Logger(org.slf4j.Logger) SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) Maps(com.google.common.collect.Maps) QueryStringDecorators(org.graylog.plugins.views.search.elasticsearch.QueryStringDecorators) Named(com.google.inject.name.Named) IndexLookup(org.graylog.plugins.views.search.elasticsearch.IndexLookup) QueryBuilders(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryBuilders) Message(org.graylog2.plugin.Message) Collections(java.util.Collections) SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) QueryResult(org.graylog.plugins.views.search.QueryResult) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) GlobalOverride(org.graylog.plugins.views.search.GlobalOverride) MultiSearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse) ESSearchTypeHandler(org.graylog.storage.elasticsearch7.views.searchtypes.ESSearchTypeHandler) SearchType(org.graylog.plugins.views.search.SearchType) HashSet(java.util.HashSet) GlobalOverride(org.graylog.plugins.views.search.GlobalOverride)

Example 75 with Indices

use of org.graylog2.indexer.indices.Indices in project graylog2-server by Graylog2.

the class SearchesAdapterES7 method search.

@Override
public SearchResult search(Set<String> indices, Set<IndexRange> indexRanges, SearchesConfig config) {
    final SearchSourceBuilder searchSourceBuilder = searchRequestFactory.create(config);
    if (indexRanges.isEmpty()) {
        return SearchResult.empty(config.query(), searchSourceBuilder.toString());
    }
    final SearchRequest searchRequest = new SearchRequest(indices.toArray(new String[0])).source(searchSourceBuilder);
    final SearchResponse searchResult = client.search(searchRequest, "Unable to perform search query");
    final List<ResultMessage> resultMessages = extractResultMessages(searchResult);
    final long totalResults = searchResult.getHits().getTotalHits().value;
    final long tookMs = searchResult.getTook().getMillis();
    final String builtQuery = searchSourceBuilder.toString();
    return new SearchResult(resultMessages, totalResults, indexRanges, config.query(), builtQuery, tookMs);
}
Also used : SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) SearchResult(org.graylog2.indexer.results.SearchResult) ResultMessage(org.graylog2.indexer.results.ResultMessage) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse)

Aggregations

IndexSet (org.graylog2.indexer.IndexSet)20 IndexRange (org.graylog2.indexer.ranges.IndexRange)19 Set (java.util.Set)18 Test (org.junit.Test)18 DateTime (org.joda.time.DateTime)17 Map (java.util.Map)16 Collectors (java.util.stream.Collectors)15 List (java.util.List)14 TimeRange (org.graylog2.plugin.indexer.searches.timeranges.TimeRange)14 ZonedDateTime (java.time.ZonedDateTime)13 Inject (javax.inject.Inject)13 JsonNode (com.fasterxml.jackson.databind.JsonNode)11 ImmutableMap (com.google.common.collect.ImmutableMap)11 HashMap (java.util.HashMap)11 Indices (org.graylog2.indexer.indices.Indices)11 MongoIndexRange (org.graylog2.indexer.ranges.MongoIndexRange)11 Logger (org.slf4j.Logger)11 LoggerFactory (org.slf4j.LoggerFactory)11 Optional (java.util.Optional)10 ImmutableSet (com.google.common.collect.ImmutableSet)9