Search in sources :

Example 6 with ElasticsearchException

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

the class JestUtils method checkForFailedShards.

public static Optional<ElasticsearchException> checkForFailedShards(JestResult result) {
    // unwrap shard failure due to non-numeric mapping. this happens when searching across index sets
    // if at least one of the index sets comes back with a result, the overall result will have the aggregation
    // but not considered failed entirely. however, if one shard has the error, we will refuse to respond
    // otherwise we would be showing empty graphs for non-numeric fields.
    final JsonNode shards = result.getJsonObject().path("_shards");
    final double failedShards = shards.path("failed").asDouble();
    if (failedShards > 0) {
        final List<String> errors = StreamSupport.stream(shards.path("failures").spliterator(), false).map(failure -> failure.path("reason").path("reason").asText()).filter(s -> !s.isEmpty()).collect(Collectors.toList());
        final List<String> nonNumericFieldErrors = errors.stream().filter(error -> error.startsWith("Expected numeric type on field")).collect(Collectors.toList());
        if (!nonNumericFieldErrors.isEmpty()) {
            return Optional.of(new FieldTypeException("Unable to perform search query: ", deduplicateErrors(nonNumericFieldErrors)));
        }
        return Optional.of(new ElasticsearchException("Unable to perform search query: ", deduplicateErrors(errors)));
    }
    return Optional.empty();
}
Also used : IndexNotFoundException(org.graylog2.indexer.IndexNotFoundException) MasterNotDiscoveredException(org.graylog2.indexer.MasterNotDiscoveredException) QueryParsingException(org.graylog2.indexer.QueryParsingException) JestHttpClient(io.searchbox.client.http.JestHttpClient) IOException(java.io.IOException) JestResult(io.searchbox.client.JestResult) RequestConfig(org.apache.http.client.config.RequestConfig) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) Supplier(java.util.function.Supplier) Collectors(java.util.stream.Collectors) FieldTypeException(org.graylog2.indexer.FieldTypeException) ArrayList(java.util.ArrayList) JestClient(io.searchbox.client.JestClient) List(java.util.List) Action(io.searchbox.action.Action) Matcher(java.util.regex.Matcher) Optional(java.util.Optional) JsonNode(com.fasterxml.jackson.databind.JsonNode) StreamSupport(java.util.stream.StreamSupport) InvalidWriteTargetException(org.graylog2.indexer.InvalidWriteTargetException) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) FieldTypeException(org.graylog2.indexer.FieldTypeException) JsonNode(com.fasterxml.jackson.databind.JsonNode) ElasticsearchException(org.graylog2.indexer.ElasticsearchException)

Example 7 with ElasticsearchException

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

the class JestUtils method specificException.

public static ElasticsearchException specificException(Supplier<String> errorMessage, JsonNode errorNode) {
    final JsonNode rootCauses = errorNode.path("root_cause");
    final List<String> reasons = new ArrayList<>(rootCauses.size());
    for (JsonNode rootCause : rootCauses) {
        final JsonNode reason = rootCause.path("reason");
        if (reason.isTextual()) {
            reasons.add(reason.asText());
        }
        final JsonNode type = rootCause.path("type");
        if (!type.isTextual()) {
            continue;
        }
        switch(type.asText()) {
            case "master_not_discovered_exception":
                return new MasterNotDiscoveredException();
            case "cluster_block_exception":
                if (reason.asText().contains("no master")) {
                    return new MasterNotDiscoveredException();
                }
            case "query_parsing_exception":
                return buildQueryParsingException(errorMessage, rootCause, reasons);
            case "index_not_found_exception":
                final String indexName = rootCause.path("resource.id").asText();
                return IndexNotFoundException.create(errorMessage.get(), indexName);
            case "illegal_argument_exception":
                final String reasonText = reason.asText();
                if (reasonText.startsWith("Expected numeric type on field")) {
                    return buildFieldTypeException(errorMessage, reasonText);
                }
                if (reasonText.startsWith("no write index is defined for alias")) {
                    final Matcher matcher = invalidWriteTarget.matcher(reasonText);
                    if (matcher.find()) {
                        final String target = matcher.group("target");
                        return InvalidWriteTargetException.create(target);
                    }
                }
                break;
        }
    }
    if (reasons.isEmpty()) {
        return new ElasticsearchException(errorMessage.get(), Collections.singletonList(errorNode.toString()));
    }
    return new ElasticsearchException(errorMessage.get(), deduplicateErrors(reasons));
}
Also used : Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) MasterNotDiscoveredException(org.graylog2.indexer.MasterNotDiscoveredException)

Example 8 with ElasticsearchException

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

the class MultiSearch method wrap.

public SearchResult wrap(Search search, Supplier<String> errorMessage) {
    final io.searchbox.core.MultiSearch multiSearch = new io.searchbox.core.MultiSearch.Builder(search).build();
    final MultiSearchResult multiSearchResult = JestUtils.execute(jestClient, multiSearch, errorMessage);
    final List<MultiSearchResult.MultiSearchResponse> responses = multiSearchResult.getResponses();
    if (responses.size() != 1) {
        throw new ElasticsearchException("Expected exactly 1 search result, but got " + responses.size());
    }
    final MultiSearchResult.MultiSearchResponse response = responses.get(0);
    if (response.isError) {
        throw JestUtils.specificException(errorMessage, response.error);
    }
    final Optional<ElasticsearchException> elasticsearchException = checkForFailedShards(response.searchResult);
    elasticsearchException.ifPresent(e -> {
        throw e;
    });
    return response.searchResult;
}
Also used : MultiSearchResult(io.searchbox.core.MultiSearchResult) ElasticsearchException(org.graylog2.indexer.ElasticsearchException)

Example 9 with ElasticsearchException

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

the class IndicesAdapterES6 method updateIndexMapping.

@Override
public void updateIndexMapping(@Nonnull String indexName, @Nonnull String mappingType, @Nonnull Map<String, Object> mapping) {
    final PutMapping request = new PutMapping.Builder(indexName, mappingType, mapping).build();
    final JestResult jestResult;
    try {
        jestResult = jestClient.execute(request);
    } catch (IOException e) {
        throw new ElasticsearchException("Couldn't update index mapping " + indexName + "/" + mappingType, e);
    }
    if (!jestResult.isSucceeded()) {
        throw new ElasticsearchException(jestResult.getErrorMessage());
    }
}
Also used : PutMapping(io.searchbox.indices.mapping.PutMapping) IOException(java.io.IOException) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) JestResult(io.searchbox.client.JestResult)

Example 10 with ElasticsearchException

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

the class IndicesAdapterES6 method move.

@Override
public void move(String source, String target, Consumer<IndexMoveResult> resultCallback) {
    // TODO: This method should use the Re-index API: https://www.elastic.co/guide/en/elasticsearch/reference/5.3/docs-reindex.html
    final String query = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery()).size(350).sort(SortBuilders.fieldSort(FieldSortBuilder.DOC_FIELD_NAME)).toString();
    final Search request = new Search.Builder(query).setParameter(Parameters.SCROLL, "10s").addIndex(source).build();
    final SearchResult searchResult = JestUtils.execute(jestClient, request, () -> "Couldn't process search query response");
    final String scrollId = searchResult.getJsonObject().path("_scroll_id").asText(null);
    if (scrollId == null) {
        throw new ElasticsearchException("Couldn't find scroll ID in search query response");
    }
    while (true) {
        final SearchScroll scrollRequest = new SearchScroll.Builder(scrollId, "1m").build();
        final JestResult scrollResult = JestUtils.execute(jestClient, scrollRequest, () -> "Couldn't process result of scroll query");
        final JsonNode scrollHits = scrollResult.getJsonObject().path("hits").path("hits");
        // No more hits.
        if (scrollHits.size() == 0) {
            break;
        }
        final Bulk.Builder bulkRequestBuilder = new Bulk.Builder();
        for (JsonNode jsonElement : scrollHits) {
            Optional.ofNullable(jsonElement.path("_source")).map(sourceJson -> objectMapper.<Map<String, Object>>convertValue(sourceJson, TypeReferences.MAP_STRING_OBJECT)).ifPresent(doc -> {
                final String id = (String) doc.remove("_id");
                if (!Strings.isNullOrEmpty(id)) {
                    bulkRequestBuilder.addAction(indexingHelper.prepareIndexRequest(target, doc, id));
                }
            });
        }
        final BulkResult bulkResult = JestUtils.execute(jestClient, bulkRequestBuilder.build(), () -> "Couldn't bulk index messages into index " + target);
        final boolean hasFailedItems = !bulkResult.getFailedItems().isEmpty();
        final IndexMoveResult result = IndexMoveResult.create(bulkResult.getItems().size(), bulkResult.getJsonObject().path("took").asLong(), hasFailedItems);
        resultCallback.accept(result);
    }
}
Also used : TermsAggregation(io.searchbox.core.search.aggregation.TermsAggregation) DateTimeZone(org.joda.time.DateTimeZone) Arrays(java.util.Arrays) PutTemplate(io.searchbox.indices.template.PutTemplate) LoggerFactory(org.slf4j.LoggerFactory) ModifyAliases(io.searchbox.indices.aliases.ModifyAliases) RequestConfig(org.apache.http.client.config.RequestConfig) TypeReferences(org.graylog2.jackson.TypeReferences) UpdateSettings(io.searchbox.indices.settings.UpdateSettings) FieldSortBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.FieldSortBuilder) MaxAggregation(io.searchbox.core.search.aggregation.MaxAggregation) IndicesAdapter(org.graylog2.indexer.indices.IndicesAdapter) HealthStatus(org.graylog2.indexer.indices.HealthStatus) JestUtils(org.graylog.storage.elasticsearch6.jest.JestUtils) Indices(org.graylog2.indexer.indices.Indices) Locale(java.util.Locale) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) IndexRangeStats(org.graylog2.indexer.searches.IndexRangeStats) Bulk(io.searchbox.core.Bulk) Cat(io.searchbox.core.Cat) IndexMapping(org.graylog2.indexer.IndexMapping) FilterAggregation(io.searchbox.core.search.aggregation.FilterAggregation) QueryBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders) SearchSourceBuilder.searchSource(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder.searchSource) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) Health(io.searchbox.cluster.Health) AddAliasMapping(io.searchbox.indices.aliases.AddAliasMapping) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) GetAliases(io.searchbox.indices.aliases.GetAliases) RemoveAliasMapping(io.searchbox.indices.aliases.RemoveAliasMapping) PutMapping(io.searchbox.indices.mapping.PutMapping) DeleteIndex(io.searchbox.indices.DeleteIndex) Stats(io.searchbox.indices.Stats) List(java.util.List) Parameters(io.searchbox.params.Parameters) OpenIndex(io.searchbox.indices.OpenIndex) AggregationBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.AggregationBuilders) IndexMoveResult(org.graylog2.indexer.indices.IndexMoveResult) Optional(java.util.Optional) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResult(io.searchbox.core.SearchResult) FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) HashMap(java.util.HashMap) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) SearchType(io.searchbox.params.SearchType) Iterators(com.google.common.collect.Iterators) JestClient(io.searchbox.client.JestClient) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) SortBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.SortBuilders) ImmutableList(com.google.common.collect.ImmutableList) Flush(io.searchbox.indices.Flush) DeleteTemplate(io.searchbox.indices.template.DeleteTemplate) IndexStatistics(org.graylog2.indexer.indices.stats.IndexStatistics) Duration(com.github.joschi.jadconfig.util.Duration) StreamSupport(java.util.stream.StreamSupport) Nonnull(javax.annotation.Nonnull) GetSettings(io.searchbox.indices.settings.GetSettings) Logger(org.slf4j.Logger) MinAggregation(io.searchbox.core.search.aggregation.MinAggregation) Iterator(java.util.Iterator) IndexSettings(org.graylog2.indexer.indices.IndexSettings) IndexNotFoundException(org.graylog2.indexer.IndexNotFoundException) SearchScroll(io.searchbox.core.SearchScroll) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Search(io.searchbox.core.Search) AliasMapping(io.searchbox.indices.aliases.AliasMapping) DateTime(org.joda.time.DateTime) ForceMerge(io.searchbox.indices.ForceMerge) GetSingleAlias(org.graylog.storage.elasticsearch6.indices.GetSingleAlias) IOException(java.io.IOException) JestResult(io.searchbox.client.JestResult) Ints(com.google.common.primitives.Ints) CreateIndex(io.searchbox.indices.CreateIndex) BulkResult(io.searchbox.core.BulkResult) Consumer(java.util.function.Consumer) URLEncoder(java.net.URLEncoder) Collectors.toList(java.util.stream.Collectors.toList) CatResult(io.searchbox.core.CatResult) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) CloseIndex(io.searchbox.indices.CloseIndex) GetTemplate(io.searchbox.indices.template.GetTemplate) Message(org.graylog2.plugin.Message) Collections(java.util.Collections) State(io.searchbox.cluster.State) FieldSortBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.FieldSortBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) SearchResult(io.searchbox.core.SearchResult) JsonNode(com.fasterxml.jackson.databind.JsonNode) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) IndexMoveResult(org.graylog2.indexer.indices.IndexMoveResult) Bulk(io.searchbox.core.Bulk) BulkResult(io.searchbox.core.BulkResult) SearchScroll(io.searchbox.core.SearchScroll) Search(io.searchbox.core.Search) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) JestResult(io.searchbox.client.JestResult)

Aggregations

ElasticsearchException (org.graylog2.indexer.ElasticsearchException)17 JestResult (io.searchbox.client.JestResult)8 List (java.util.List)7 Collectors (java.util.stream.Collectors)7 Inject (javax.inject.Inject)7 ArrayList (java.util.ArrayList)6 Collections (java.util.Collections)6 Map (java.util.Map)6 Optional (java.util.Optional)6 Set (java.util.Set)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 Arrays (java.util.Arrays)5 HashMap (java.util.HashMap)5 IOException (java.io.IOException)4 Message (org.graylog2.plugin.Message)4 IndicesOptions (org.graylog.shaded.elasticsearch7.org.elasticsearch.action.support.IndicesOptions)3 Test (org.junit.Test)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2