Search in sources :

Example 1 with MessageSummary

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

the class FieldValueAlertCondition method runCheck.

@Override
public CheckResult runCheck() {
    try {
        final String filter = buildQueryFilter(stream.getId(), query);
        // TODO we don't support cardinality yet
        final FieldStatsResult fieldStatsResult = searches.fieldStats(field, "*", filter, RelativeRange.create(time * 60), false, true, false);
        if (fieldStatsResult.count() == 0) {
            LOG.debug("Alert check <{}> did not match any messages. Returning not triggered.", type);
            return new NegativeCheckResult();
        }
        final double result;
        switch(type) {
            case MEAN:
                result = fieldStatsResult.mean();
                break;
            case MIN:
                result = fieldStatsResult.min();
                break;
            case MAX:
                result = fieldStatsResult.max();
                break;
            case SUM:
                result = fieldStatsResult.sum();
                break;
            case STDDEV:
                result = fieldStatsResult.stdDeviation();
                break;
            default:
                LOG.error("No such field value check type: [{}]. Returning not triggered.", type);
                return new NegativeCheckResult();
        }
        LOG.debug("Alert check <{}> result: [{}]", id, result);
        if (Double.isInfinite(result)) {
            // This happens when there are no ES results/docs.
            LOG.debug("Infinite value. Returning not triggered.");
            return new NegativeCheckResult();
        }
        final boolean triggered;
        switch(thresholdType) {
            case HIGHER:
                triggered = result > threshold.doubleValue();
                break;
            case LOWER:
                triggered = result < threshold.doubleValue();
                break;
            default:
                triggered = false;
        }
        if (triggered) {
            final String resultDescription = "Field " + field + " had a " + type + " of " + decimalFormat.format(result) + " in the last " + time + " minutes with trigger condition " + thresholdType + " than " + decimalFormat.format(threshold) + ". " + "(Current grace time: " + grace + " minutes)";
            final List<MessageSummary> summaries;
            if (getBacklog() > 0) {
                final List<ResultMessage> searchResult = fieldStatsResult.searchHits();
                summaries = Lists.newArrayListWithCapacity(searchResult.size());
                for (ResultMessage resultMessage : searchResult) {
                    final Message msg = resultMessage.getMessage();
                    summaries.add(new MessageSummary(resultMessage.getIndex(), msg));
                }
            } else {
                summaries = Collections.emptyList();
            }
            return new CheckResult(true, this, resultDescription, Tools.nowUTC(), summaries);
        } else {
            return new NegativeCheckResult();
        }
    } catch (InvalidRangeParametersException e) {
        // cannot happen lol
        LOG.error("Invalid timerange.", e);
        return null;
    } catch (FieldTypeException e) {
        LOG.debug("Field [{}] seems not to have a numerical type or doesn't even exist at all. Returning not triggered.", field, e);
        return new NegativeCheckResult();
    }
}
Also used : InvalidRangeParametersException(org.graylog2.plugin.indexer.searches.timeranges.InvalidRangeParametersException) ResultMessage(org.graylog2.indexer.results.ResultMessage) Message(org.graylog2.plugin.Message) ResultMessage(org.graylog2.indexer.results.ResultMessage) FieldStatsResult(org.graylog2.indexer.results.FieldStatsResult) FieldTypeException(org.graylog2.indexer.FieldTypeException) MessageSummary(org.graylog2.plugin.MessageSummary)

Example 2 with MessageSummary

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

the class FieldContentValueAlertCondition method runCheck.

@Override
public CheckResult runCheck() {
    String filter = buildQueryFilter(stream.getId(), query);
    String query = field + ":\"" + value + "\"";
    Integer backlogSize = getBacklog();
    boolean backlogEnabled = false;
    int searchLimit = 1;
    if (backlogSize != null && backlogSize > 0) {
        backlogEnabled = true;
        searchLimit = backlogSize;
    }
    try {
        SearchResult result = searches.search(query, filter, RelativeRange.create(configuration.getAlertCheckInterval()), searchLimit, 0, new Sorting(Message.FIELD_TIMESTAMP, Sorting.Direction.DESC));
        final List<MessageSummary> summaries;
        if (backlogEnabled) {
            summaries = Lists.newArrayListWithCapacity(result.getResults().size());
            for (ResultMessage resultMessage : result.getResults()) {
                final Message msg = resultMessage.getMessage();
                summaries.add(new MessageSummary(resultMessage.getIndex(), msg));
            }
        } else {
            summaries = Collections.emptyList();
        }
        final long count = result.getTotalResults();
        final String resultDescription = "Stream received messages matching <" + query + "> " + "(Current grace time: " + grace + " minutes)";
        if (count > 0) {
            LOG.debug("Alert check <{}> found [{}] messages.", id, count);
            return new CheckResult(true, this, resultDescription, Tools.nowUTC(), summaries);
        } else {
            LOG.debug("Alert check <{}> returned no results.", id);
            return new NegativeCheckResult();
        }
    } catch (InvalidRangeParametersException e) {
        // cannot happen lol
        LOG.error("Invalid timerange.", e);
        return null;
    }
}
Also used : InvalidRangeParametersException(org.graylog2.plugin.indexer.searches.timeranges.InvalidRangeParametersException) ResultMessage(org.graylog2.indexer.results.ResultMessage) Message(org.graylog2.plugin.Message) SearchResult(org.graylog2.indexer.results.SearchResult) ResultMessage(org.graylog2.indexer.results.ResultMessage) Sorting(org.graylog2.indexer.searches.Sorting) MessageSummary(org.graylog2.plugin.MessageSummary)

Example 3 with MessageSummary

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

the class MessageCountAlertCondition method runCheck.

@Override
public CheckResult runCheck() {
    try {
        // Create an absolute range from the relative range to make sure it doesn't change during the two
        // search requests. (count and find messages)
        // This is needed because the RelativeRange computes the range from NOW on every invocation of getFrom() and
        // getTo().
        // See: https://github.com/Graylog2/graylog2-server/issues/2382
        final RelativeRange relativeRange = RelativeRange.create(time * 60);
        final AbsoluteRange range = AbsoluteRange.create(relativeRange.getFrom(), relativeRange.getTo());
        final String filter = buildQueryFilter(stream.getId(), query);
        final CountResult result = searches.count("*", range, filter);
        final long count = result.count();
        LOG.debug("Alert check <{}> result: [{}]", id, count);
        final boolean triggered;
        switch(thresholdType) {
            case MORE:
                triggered = count > threshold;
                break;
            case LESS:
                triggered = count < threshold;
                break;
            default:
                triggered = false;
        }
        if (triggered) {
            final List<MessageSummary> summaries = Lists.newArrayList();
            if (getBacklog() > 0) {
                final SearchResult backlogResult = searches.search("*", filter, range, getBacklog(), 0, new Sorting(Message.FIELD_TIMESTAMP, Sorting.Direction.DESC));
                for (ResultMessage resultMessage : backlogResult.getResults()) {
                    final Message msg = resultMessage.getMessage();
                    summaries.add(new MessageSummary(resultMessage.getIndex(), msg));
                }
            }
            final String resultDescription = "Stream had " + count + " messages in the last " + time + " minutes with trigger condition " + thresholdType.toString().toLowerCase(Locale.ENGLISH) + " than " + threshold + " messages. " + "(Current grace time: " + grace + " minutes)";
            return new CheckResult(true, this, resultDescription, Tools.nowUTC(), summaries);
        } else {
            return new NegativeCheckResult();
        }
    } catch (InvalidRangeParametersException e) {
        // cannot happen lol
        LOG.error("Invalid timerange.", e);
        return null;
    }
}
Also used : InvalidRangeParametersException(org.graylog2.plugin.indexer.searches.timeranges.InvalidRangeParametersException) ResultMessage(org.graylog2.indexer.results.ResultMessage) Message(org.graylog2.plugin.Message) AbsoluteRange(org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange) SearchResult(org.graylog2.indexer.results.SearchResult) CountResult(org.graylog2.indexer.results.CountResult) ResultMessage(org.graylog2.indexer.results.ResultMessage) Sorting(org.graylog2.indexer.searches.Sorting) RelativeRange(org.graylog2.plugin.indexer.searches.timeranges.RelativeRange) MessageSummary(org.graylog2.plugin.MessageSummary)

Example 4 with MessageSummary

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

the class LegacyAlarmCallbackEventNotification method execute.

@Override
public void execute(EventNotificationContext ctx) throws PermanentEventNotificationException {
    final LegacyAlarmCallbackEventNotificationConfig config = (LegacyAlarmCallbackEventNotificationConfig) ctx.notificationConfig();
    final ImmutableList<MessageSummary> messagesForEvent = notificationCallbackService.getBacklogForEvent(ctx);
    final Optional<EventDefinitionDto> optionalEventDefinition = ctx.eventDefinition();
    if (!optionalEventDefinition.isPresent()) {
        final String msg = String.format(Locale.ROOT, "Unable to find definition for event <%s>", ctx.event().id());
        LOG.error(msg);
        throw new PermanentEventNotificationException(msg);
    }
    try {
        alarmCallbackSender.send(config, optionalEventDefinition.get(), ctx.event(), messagesForEvent);
    } catch (Exception e) {
        // TODO: Is there a case where we want to retry? (and are able to detect when to do it)
        throw new PermanentEventNotificationException("Couldn't send legacy notification - legacy notifications cannot be retried!", e);
    }
}
Also used : EventDefinitionDto(org.graylog.events.processor.EventDefinitionDto) PermanentEventNotificationException(org.graylog.events.notifications.PermanentEventNotificationException) MessageSummary(org.graylog2.plugin.MessageSummary) PermanentEventNotificationException(org.graylog.events.notifications.PermanentEventNotificationException)

Example 5 with MessageSummary

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

the class AggregationEventProcessor method sourceMessagesForEvent.

@Override
public void sourceMessagesForEvent(Event event, Consumer<List<MessageSummary>> messageConsumer, long limit) throws EventProcessorException {
    if (config.series().isEmpty()) {
        if (limit <= 0) {
            return;
        }
        final EventOriginContext.ESEventOriginContext esContext = EventOriginContext.parseESContext(event.getOriginContext()).orElseThrow(() -> new EventProcessorException("Failed to parse origin context", false, eventDefinition));
        try {
            final ResultMessage message;
            message = messages.get(esContext.messageId(), esContext.indexName());
            messageConsumer.accept(Lists.newArrayList(new MessageSummary(message.getIndex(), message.getMessage())));
        } catch (IOException e) {
            throw new EventProcessorException("Failed to query origin context message", false, eventDefinition, e);
        }
    } else {
        final AtomicLong msgCount = new AtomicLong(0L);
        final MoreSearch.ScrollCallback callback = (messages, continueScrolling) -> {
            final List<MessageSummary> summaries = Lists.newArrayList();
            for (final ResultMessage resultMessage : messages) {
                if (msgCount.incrementAndGet() > limit) {
                    continueScrolling.set(false);
                    break;
                }
                final Message msg = resultMessage.getMessage();
                summaries.add(new MessageSummary(resultMessage.getIndex(), msg));
            }
            messageConsumer.accept(summaries);
        };
        ElasticsearchQueryString scrollQueryString = ElasticsearchQueryString.of(config.query());
        scrollQueryString = scrollQueryString.concatenate(groupByQueryString(event));
        LOG.debug("scrollQueryString: {}", scrollQueryString);
        final TimeRange timeRange = AbsoluteRange.create(event.getTimerangeStart(), event.getTimerangeEnd());
        moreSearch.scrollQuery(scrollQueryString.queryString(), config.streams(), config.queryParameters(), timeRange, Math.min(500, Ints.saturatedCast(limit)), callback);
    }
}
Also used : EventProcessorException(org.graylog.events.processor.EventProcessorException) MoreSearch(org.graylog.events.search.MoreSearch) LoggerFactory(org.slf4j.LoggerFactory) EventOriginContext(org.graylog.events.event.EventOriginContext) MessageSummary(org.graylog2.plugin.MessageSummary) EventConsumer(org.graylog.events.processor.EventConsumer) Assisted(com.google.inject.assistedinject.Assisted) EventProcessor(org.graylog.events.processor.EventProcessor) ResultMessage(org.graylog2.indexer.results.ResultMessage) Locale(java.util.Locale) Map(java.util.Map) Event(org.graylog.events.event.Event) AbsoluteRange(org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange) EventDefinition(org.graylog.events.processor.EventDefinition) EventProcessorException(org.graylog.events.processor.EventProcessorException) TimeRange(org.graylog2.plugin.indexer.searches.timeranges.TimeRange) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Persisted(org.graylog2.plugin.database.Persisted) Set(java.util.Set) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) MoreSearch(org.graylog.events.search.MoreSearch) EventFactory(org.graylog.events.event.EventFactory) ParameterExpansionError(org.graylog.plugins.views.search.errors.ParameterExpansionError) List(java.util.List) Stream(org.graylog2.plugin.streams.Stream) StreamService(org.graylog2.streams.StreamService) Strings(org.apache.logging.log4j.util.Strings) Optional(java.util.Optional) MoreSearch.luceneEscape(org.graylog.events.search.MoreSearch.luceneEscape) HashMap(java.util.HashMap) SearchException(org.graylog.plugins.views.search.errors.SearchException) ElasticsearchQueryString(org.graylog.plugins.views.search.elasticsearch.ElasticsearchQueryString) Inject(javax.inject.Inject) DBEventProcessorStateService(org.graylog.events.processor.DBEventProcessorStateService) BooleanNumberConditionsVisitor(org.graylog.events.conditions.BooleanNumberConditionsVisitor) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Messages(org.graylog2.indexer.messages.Messages) EventProcessorParameters(org.graylog.events.processor.EventProcessorParameters) Logger(org.slf4j.Logger) EventWithContext(org.graylog.events.event.EventWithContext) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) Maps(com.google.common.collect.Maps) Ints(com.google.common.primitives.Ints) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) EventProcessorDependencyCheck(org.graylog.events.processor.EventProcessorDependencyCheck) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Message(org.graylog2.plugin.Message) EventProcessorPreconditionException(org.graylog.events.processor.EventProcessorPreconditionException) ResultMessage(org.graylog2.indexer.results.ResultMessage) Message(org.graylog2.plugin.Message) ElasticsearchQueryString(org.graylog.plugins.views.search.elasticsearch.ElasticsearchQueryString) IOException(java.io.IOException) ResultMessage(org.graylog2.indexer.results.ResultMessage) TimeRange(org.graylog2.plugin.indexer.searches.timeranges.TimeRange) AtomicLong(java.util.concurrent.atomic.AtomicLong) EventOriginContext(org.graylog.events.event.EventOriginContext) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) MessageSummary(org.graylog2.plugin.MessageSummary)

Aggregations

MessageSummary (org.graylog2.plugin.MessageSummary)11 Message (org.graylog2.plugin.Message)6 ResultMessage (org.graylog2.indexer.results.ResultMessage)4 Stream (org.graylog2.plugin.streams.Stream)4 PermanentEventNotificationException (org.graylog.events.notifications.PermanentEventNotificationException)3 AbstractAlertCondition (org.graylog2.alerts.AbstractAlertCondition)3 AlertCondition (org.graylog2.plugin.alarms.AlertCondition)3 InvalidRangeParametersException (org.graylog2.plugin.indexer.searches.timeranges.InvalidRangeParametersException)3 DateTime (org.joda.time.DateTime)3 ImmutableList (com.google.common.collect.ImmutableList)2 IOException (java.io.IOException)2 DummyAlertCondition (org.graylog2.alerts.types.DummyAlertCondition)2 SearchResult (org.graylog2.indexer.results.SearchResult)2 Sorting (org.graylog2.indexer.searches.Sorting)2 Configuration (org.graylog2.plugin.configuration.Configuration)2 AbsoluteRange (org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange)2 Test (org.junit.Test)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1