Search in sources :

Example 16 with TimeRange

use of org.graylog2.plugin.indexer.searches.timeranges.TimeRange in project graylog2-server by Graylog2.

the class SearchResourceTest method restrictTimeRangeReturnsLimitedTimeRange.

@Test
public void restrictTimeRangeReturnsLimitedTimeRange() {
    when(clusterConfigService.get(SearchesClusterConfig.class)).thenReturn(SearchesClusterConfig.createDefault().toBuilder().queryTimeRangeLimit(queryLimitPeriod).build());
    final DateTime from = new DateTime(2015, 1, 15, 12, 0, DateTimeZone.UTC);
    final DateTime to = from.plus(queryLimitPeriod.multipliedBy(2));
    final TimeRange timeRange = AbsoluteRange.create(from, to);
    final TimeRange restrictedTimeRange = searchResource.restrictTimeRange(timeRange);
    assertThat(restrictedTimeRange).isNotNull();
    assertThat(restrictedTimeRange.getFrom()).isEqualTo(to.minus(queryLimitPeriod));
    assertThat(restrictedTimeRange.getTo()).isEqualTo(to);
}
Also used : TimeRange(org.graylog2.plugin.indexer.searches.timeranges.TimeRange) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Example 17 with TimeRange

use of org.graylog2.plugin.indexer.searches.timeranges.TimeRange in project graylog2-server by Graylog2.

the class FieldContentValueAlertCondition method runCheck.

@Override
public CheckResult runCheck() {
    String filter = "streams:" + stream.getId();
    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("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;
    } catch (InvalidRangeFormatException e) {
        // lol same here
        LOG.error("Invalid timerange format.", e);
        return null;
    }
}
Also used : InvalidRangeFormatException(org.graylog2.indexer.InvalidRangeFormatException) 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 18 with TimeRange

use of org.graylog2.plugin.indexer.searches.timeranges.TimeRange in project graylog2-server by Graylog2.

the class FieldValueAlertCondition method runCheck.

@Override
public CheckResult runCheck() {
    try {
        final String filter = "streams:" + stream.getId();
        // TODO we don't support cardinality yet
        final FieldStatsResult fieldStatsResult = searches.fieldStats(field, "*", filter, RelativeRange.create(time * 60), false, true, false);
        if (fieldStatsResult.getCount() == 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.getMean();
                break;
            case MIN:
                result = fieldStatsResult.getMin();
                break;
            case MAX:
                result = fieldStatsResult.getMax();
                break;
            case SUM:
                result = fieldStatsResult.getSum();
                break;
            case STDDEV:
                result = fieldStatsResult.getStdDeviation();
                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.getSearchHits();
                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 (InvalidRangeFormatException e) {
        // lol same here
        LOG.error("Invalid timerange format.", e);
        return null;
    } catch (Searches.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 : InvalidRangeFormatException(org.graylog2.indexer.InvalidRangeFormatException) InvalidRangeParametersException(org.graylog2.plugin.indexer.searches.timeranges.InvalidRangeParametersException) ResultMessage(org.graylog2.indexer.results.ResultMessage) Message(org.graylog2.plugin.Message) Searches(org.graylog2.indexer.searches.Searches) ResultMessage(org.graylog2.indexer.results.ResultMessage) FieldStatsResult(org.graylog2.indexer.results.FieldStatsResult) MessageSummary(org.graylog2.plugin.MessageSummary)

Example 19 with TimeRange

use of org.graylog2.plugin.indexer.searches.timeranges.TimeRange 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 = "streams:" + stream.getId();
        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("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;
    } catch (InvalidRangeFormatException e) {
        // lol same here
        LOG.error("Invalid timerange format.", e);
        return null;
    }
}
Also used : InvalidRangeFormatException(org.graylog2.indexer.InvalidRangeFormatException) 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 20 with TimeRange

use of org.graylog2.plugin.indexer.searches.timeranges.TimeRange in project graylog2-server by Graylog2.

the class TimeRangeFactory method create.

public TimeRange create(final Map<String, Object> timerangeConfig) throws InvalidRangeParametersException {
    final String rangeType = Strings.isNullOrEmpty((String) timerangeConfig.get("type")) ? (String) timerangeConfig.get("range_type") : (String) timerangeConfig.get("type");
    if (Strings.isNullOrEmpty(rangeType)) {
        throw new InvalidRangeParametersException("range type not set");
    }
    switch(rangeType) {
        case "relative":
            return RelativeRange.create(Integer.parseInt(String.valueOf(timerangeConfig.get("range"))));
        case "keyword":
            return KeywordRange.create((String) timerangeConfig.get("keyword"));
        case "absolute":
            final String from = new DateTime(timerangeConfig.get("from"), DateTimeZone.UTC).toString();
            final String to = new DateTime(timerangeConfig.get("to"), DateTimeZone.UTC).toString();
            return AbsoluteRange.create(from, to);
        default:
            throw new InvalidRangeParametersException("range_type not recognized");
    }
}
Also used : InvalidRangeParametersException(org.graylog2.plugin.indexer.searches.timeranges.InvalidRangeParametersException) DateTime(org.joda.time.DateTime)

Aggregations

TimeRange (org.graylog2.plugin.indexer.searches.timeranges.TimeRange)21 DateTime (org.joda.time.DateTime)14 Test (org.junit.Test)10 Timed (com.codahale.metrics.annotation.Timed)8 ApiOperation (io.swagger.annotations.ApiOperation)8 ApiResponses (io.swagger.annotations.ApiResponses)8 Produces (javax.ws.rs.Produces)8 ZonedDateTime (java.time.ZonedDateTime)6 GET (javax.ws.rs.GET)6 SearchPhaseExecutionException (org.elasticsearch.action.search.SearchPhaseExecutionException)6 SearchRequest (org.elasticsearch.action.search.SearchRequest)6 SearchResponse (org.elasticsearch.action.search.SearchResponse)6 IndexRange (org.graylog2.indexer.ranges.IndexRange)6 InvalidRangeParametersException (org.graylog2.plugin.indexer.searches.timeranges.InvalidRangeParametersException)6 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)5 Filter (org.elasticsearch.search.aggregations.bucket.filter.Filter)5 FilterAggregationBuilder (org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder)5 MongoIndexRange (org.graylog2.indexer.ranges.MongoIndexRange)5 Sorting (org.graylog2.indexer.searches.Sorting)5 ScrollResult (org.graylog2.indexer.results.ScrollResult)4