Search in sources :

Example 86 with Messages

use of org.graylog2.plugin.Messages in project graylog2-server by Graylog2.

the class MoreSearchAdapterES6 method scrollEvents.

@Override
public void scrollEvents(String queryString, TimeRange timeRange, Set<String> affectedIndices, Set<String> streams, String scrollTime, int batchSize, ScrollEventsCallback resultCallback) throws EventProcessorException {
    final QueryBuilder query = (queryString.trim().isEmpty() || queryString.trim().equals("*")) ? matchAllQuery() : queryStringQuery(queryString).allowLeadingWildcard(allowLeadingWildcard);
    final BoolQueryBuilder filter = boolQuery().filter(query).filter(requireNonNull(TimeRangeQueryFactory.create(timeRange)));
    // Filtering with an empty streams list doesn't work and would return zero results
    if (!streams.isEmpty()) {
        filter.filter(termsQuery(Message.FIELD_STREAMS, streams));
    }
    final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(filter).size(batchSize);
    final Search.Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()).addType(IndexMapping.TYPE_MESSAGE).addIndex(affectedIndices.isEmpty() ? Collections.singleton("") : affectedIndices).addSort(new Sort("timestamp", Sort.Sorting.ASC)).allowNoIndices(false).ignoreUnavailable(false).setParameter(Parameters.SCROLL, scrollTime);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Query:\n{}", searchSourceBuilder.toString(new ToXContent.MapParams(Collections.singletonMap("pretty", "true"))));
        LOG.debug("Execute search: {}", searchBuilder.build().toString());
    }
    final ScrollResult scrollResult = scroll.scroll(searchBuilder.build(), () -> "Unable to scroll indices.", searchSourceBuilder.toString(), scrollTime, Collections.emptyList());
    final AtomicBoolean continueScrolling = new AtomicBoolean(true);
    final Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        ScrollResult.ScrollChunk scrollChunk = scrollResult.nextChunk();
        while (continueScrolling.get() && scrollChunk != null) {
            final List<ResultMessage> messages = scrollChunk.getMessages();
            LOG.debug("Passing <{}> messages to callback", messages.size());
            resultCallback.accept(Collections.unmodifiableList(messages), continueScrolling);
            // Stop if the resultCallback told us to stop
            if (!continueScrolling.get()) {
                break;
            }
            scrollChunk = scrollResult.nextChunk();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        try {
            // Tell Elasticsearch that we are done with the scroll so it can release resources as soon as possible
            // instead of waiting for the scroll timeout to kick in.
            scrollResult.cancel();
        } catch (Exception ignored) {
        }
        LOG.debug("Scrolling done - took {} ms", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
    }
}
Also used : QueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) Stopwatch(com.google.common.base.Stopwatch) UncheckedIOException(java.io.UncheckedIOException) QueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) ResultMessage(org.graylog2.indexer.results.ResultMessage) EventProcessorException(org.graylog.events.processor.EventProcessorException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) ScrollResult(org.graylog2.indexer.results.ScrollResult) Search(io.searchbox.core.Search) MoreSearch(org.graylog.events.search.MoreSearch) Sort(io.searchbox.core.search.sort.Sort)

Example 87 with Messages

use of org.graylog2.plugin.Messages in project graylog2-server by Graylog2.

the class ESMessageList method doExtractResult.

@Override
public SearchType.Result doExtractResult(SearchJob job, Query query, MessageList searchType, SearchResult result, MetricAggregation aggregations, ESGeneratedQueryContext queryContext) {
    // noinspection unchecked
    final List<ResultMessageSummary> messages = result.getHits(Map.class, false).stream().map(hit -> ResultMessage.parseFromSource(hit.id, hit.index, (Map<String, Object>) hit.source, hit.highlight)).map((resultMessage) -> ResultMessageSummary.create(resultMessage.highlightRanges, resultMessage.getMessage().getFields(), resultMessage.getIndex())).collect(Collectors.toList());
    final String undecoratedQueryString = query.query().queryString();
    final String queryString = this.esQueryDecorators.decorate(undecoratedQueryString, job, query);
    final DateTime from = query.effectiveTimeRange(searchType).getFrom();
    final DateTime to = query.effectiveTimeRange(searchType).getTo();
    final SearchResponse searchResponse = SearchResponse.create(undecoratedQueryString, queryString, Collections.emptySet(), messages, Collections.emptySet(), 0, result.getTotal(), from, to);
    final SearchResponse decoratedSearchResponse = decoratorProcessor.decorateSearchResponse(searchResponse, searchType.decorators());
    final MessageList.Result.Builder resultBuilder = MessageList.Result.result(searchType.id()).messages(decoratedSearchResponse.messages()).effectiveTimerange(AbsoluteRange.create(from, to)).totalResults(decoratedSearchResponse.totalResults());
    return searchType.name().map(resultBuilder::name).orElse(resultBuilder).build();
}
Also used : ESGeneratedQueryContext(org.graylog.storage.elasticsearch6.views.ESGeneratedQueryContext) Query(org.graylog.plugins.views.search.Query) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse) FieldSortBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.FieldSortBuilder) SortOrder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.SortOrder) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) Inject(javax.inject.Inject) SortBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.SortBuilders) ResultMessage(org.graylog2.indexer.results.ResultMessage) SearchType(org.graylog.plugins.views.search.SearchType) Sort(org.graylog.plugins.views.search.searchtypes.Sort) Map(java.util.Map) AbsoluteRange(org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange) MessageList(org.graylog.plugins.views.search.searchtypes.MessageList) LegacyDecoratorProcessor(org.graylog.plugins.views.search.LegacyDecoratorProcessor) QueryBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders) HighlightBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder) SearchJob(org.graylog.plugins.views.search.SearchJob) DateTime(org.joda.time.DateTime) QueryStringQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryStringQueryBuilder) Set(java.util.Set) Collectors(java.util.stream.Collectors) List(java.util.List) QueryStringDecorators(org.graylog.plugins.views.search.elasticsearch.QueryStringDecorators) MetricAggregation(io.searchbox.core.search.aggregation.MetricAggregation) Optional(java.util.Optional) Named(com.google.inject.name.Named) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Message(org.graylog2.plugin.Message) Collections(java.util.Collections) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResult(io.searchbox.core.SearchResult) Map(java.util.Map) DateTime(org.joda.time.DateTime) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse) SearchResult(io.searchbox.core.SearchResult)

Example 88 with Messages

use of org.graylog2.plugin.Messages in project graylog2-server by Graylog2.

the class ESMessageList method doExtractResult.

@Override
public SearchType.Result doExtractResult(SearchJob job, Query query, MessageList searchType, org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse result, Aggregations aggregations, ESGeneratedQueryContext queryContext) {
    final List<ResultMessageSummary> messages = StreamSupport.stream(result.getHits().spliterator(), false).map(ESMessageList::resultMessageFromSearchHit).map((resultMessage) -> ResultMessageSummary.create(resultMessage.highlightRanges, resultMessage.getMessage().getFields(), resultMessage.getIndex())).collect(Collectors.toList());
    final String undecoratedQueryString = query.query().queryString();
    final String queryString = this.esQueryDecorators.decorate(undecoratedQueryString, job, query);
    final DateTime from = query.effectiveTimeRange(searchType).getFrom();
    final DateTime to = query.effectiveTimeRange(searchType).getTo();
    final SearchResponse searchResponse = SearchResponse.create(undecoratedQueryString, queryString, Collections.emptySet(), messages, Collections.emptySet(), 0, result.getHits().getTotalHits().value, from, to);
    final SearchResponse decoratedSearchResponse = decoratorProcessor.decorateSearchResponse(searchResponse, searchType.decorators());
    final MessageList.Result.Builder resultBuilder = MessageList.Result.result(searchType.id()).messages(decoratedSearchResponse.messages()).effectiveTimerange(AbsoluteRange.create(from, to)).totalResults(decoratedSearchResponse.totalResults());
    return searchType.name().map(resultBuilder::name).orElse(resultBuilder).build();
}
Also used : Arrays(java.util.Arrays) Query(org.graylog.plugins.views.search.Query) Text(org.graylog.shaded.elasticsearch7.org.elasticsearch.common.text.Text) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) Inject(javax.inject.Inject) ResultMessage(org.graylog2.indexer.results.ResultMessage) SearchType(org.graylog.plugins.views.search.SearchType) Sort(org.graylog.plugins.views.search.searchtypes.Sort) Map(java.util.Map) ESGeneratedQueryContext(org.graylog.storage.elasticsearch7.views.ESGeneratedQueryContext) AbsoluteRange(org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange) StreamSupport(java.util.stream.StreamSupport) MessageList(org.graylog.plugins.views.search.searchtypes.MessageList) QueryStringQueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryStringQueryBuilder) LegacyDecoratorProcessor(org.graylog.plugins.views.search.LegacyDecoratorProcessor) SortBuilders(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.sort.SortBuilders) FieldSortBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.sort.FieldSortBuilder) SearchJob(org.graylog.plugins.views.search.SearchJob) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) DateTime(org.joda.time.DateTime) Set(java.util.Set) Collectors(java.util.stream.Collectors) SortOrder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.sort.SortOrder) Aggregations(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.Aggregations) HighlightBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder) List(java.util.List) QueryStringDecorators(org.graylog.plugins.views.search.elasticsearch.QueryStringDecorators) SearchHit(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.SearchHit) Optional(java.util.Optional) Named(com.google.inject.name.Named) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) VisibleForTesting(com.google.common.annotations.VisibleForTesting) HighlightField(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.fetch.subphase.highlight.HighlightField) QueryBuilders(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryBuilders) Message(org.graylog2.plugin.Message) Collections(java.util.Collections) DateTime(org.joda.time.DateTime) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse)

Example 89 with Messages

use of org.graylog2.plugin.Messages in project graylog2-server by Graylog2.

the class MoreSearchAdapterES7 method scrollEvents.

@Override
public void scrollEvents(String queryString, TimeRange timeRange, Set<String> affectedIndices, Set<String> streams, String scrollTime, int batchSize, ScrollEventsCallback resultCallback) throws EventProcessorException {
    final ScrollCommand scrollCommand = buildScrollCommand(queryString, timeRange, affectedIndices, streams, batchSize);
    final ScrollResult scrollResult = scroll.scroll(scrollCommand);
    final AtomicBoolean continueScrolling = new AtomicBoolean(true);
    final Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        ScrollResult.ScrollChunk scrollChunk = scrollResult.nextChunk();
        while (continueScrolling.get() && scrollChunk != null) {
            final List<ResultMessage> messages = scrollChunk.getMessages();
            LOG.debug("Passing <{}> messages to callback", messages.size());
            resultCallback.accept(Collections.unmodifiableList(messages), continueScrolling);
            // Stop if the resultCallback told us to stop
            if (!continueScrolling.get()) {
                break;
            }
            scrollChunk = scrollResult.nextChunk();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        try {
            // Tell Elasticsearch that we are done with the scroll so it can release resources as soon as possible
            // instead of waiting for the scroll timeout to kick in.
            scrollResult.cancel();
        } catch (Exception ignored) {
        }
        LOG.debug("Scrolling done - took {} ms", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ScrollResult(org.graylog2.indexer.results.ScrollResult) ScrollCommand(org.graylog2.indexer.searches.ScrollCommand) Stopwatch(com.google.common.base.Stopwatch) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) ResultMessage(org.graylog2.indexer.results.ResultMessage) EventProcessorException(org.graylog.events.processor.EventProcessorException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException)

Example 90 with Messages

use of org.graylog2.plugin.Messages in project graylog2-server by Graylog2.

the class EventBacklogService method getMessagesForEvent.

public ImmutableList<MessageSummary> getMessagesForEvent(EventDto eventDto, long backlogSize) throws NotFoundException {
    if (backlogSize <= 0) {
        return ImmutableList.of();
    }
    final EventProcessor.Factory factory = eventProcessorFactories.get(eventDto.eventDefinitionType());
    if (factory == null) {
        throw new NotFoundException("Couldn't find event processor factory for type " + eventDto.eventDefinitionType());
    }
    final EventDefinition eventDefinition = eventDefinitionService.get(eventDto.eventDefinitionId()).orElseThrow(() -> new NotFoundException("Could not find event definintion <" + eventDto.eventDefinitionId() + ">"));
    final EventProcessor eventProcessor = factory.create(eventDefinition);
    final ImmutableList.Builder<MessageSummary> backlogBuilder = ImmutableList.builder();
    try {
        eventProcessor.sourceMessagesForEvent(Event.fromDto(eventDto), backlogBuilder::addAll, backlogSize);
    } catch (EventProcessorException e) {
        // TODO return this error, so it can be included in the notification message?
        LOG.error("Failed to query backlog messages for Event {}", eventDto.id(), e);
    }
    return backlogBuilder.build();
}
Also used : EventProcessorException(org.graylog.events.processor.EventProcessorException) ImmutableList(com.google.common.collect.ImmutableList) EventProcessor(org.graylog.events.processor.EventProcessor) NotFoundException(org.graylog2.database.NotFoundException) EventDefinition(org.graylog.events.processor.EventDefinition) MessageSummary(org.graylog2.plugin.MessageSummary)

Aggregations

Message (org.graylog2.plugin.Message)41 Test (org.junit.Test)31 DateTime (org.joda.time.DateTime)17 Map (java.util.Map)15 ApiOperation (io.swagger.annotations.ApiOperation)14 Produces (javax.ws.rs.Produces)14 Timed (com.codahale.metrics.annotation.Timed)13 ApiResponses (io.swagger.annotations.ApiResponses)12 Messages (org.graylog2.plugin.Messages)12 List (java.util.List)11 GET (javax.ws.rs.GET)11 AbsoluteRange (org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange)11 ResultMessage (org.graylog2.indexer.results.ResultMessage)10 TimeRange (org.graylog2.plugin.indexer.searches.timeranges.TimeRange)10 ArrayList (java.util.ArrayList)9 Collectors (java.util.stream.Collectors)9 ResultMessageSummary (org.graylog2.rest.models.messages.responses.ResultMessageSummary)9 ImmutableMap (com.google.common.collect.ImmutableMap)8 IOException (java.io.IOException)8 Inject (javax.inject.Inject)8