Search in sources :

Example 1 with ResultMessage

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

the class MessageResource method search.

@GET
@Path("/{index}/{messageId}")
@Timed
@ApiOperation(value = "Get a single message.")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Specified index does not exist."), @ApiResponse(code = 404, message = "Message does not exist.") })
public ResultMessage search(@ApiParam(name = "index", value = "The index this message is stored in.", required = true) @PathParam("index") String index, @ApiParam(name = "messageId", required = true) @PathParam("messageId") String messageId) {
    checkPermission(RestPermissions.MESSAGES_READ, messageId);
    try {
        final ResultMessage resultMessage = messages.get(messageId, index);
        final Message message = resultMessage.getMessage();
        checkMessageReadPermission(message);
        return resultMessage;
    } catch (IndexNotFoundException e) {
        final String msg = "Index " + e.getIndex() + " does not exist.";
        LOG.error(msg, e);
        throw new NotFoundException(msg, e);
    } catch (DocumentNotFoundException e) {
        final String msg = "Message " + messageId + " does not exist in index " + index;
        LOG.error(msg, e);
        throw new NotFoundException(msg, e);
    }
}
Also used : ResultMessage(org.graylog2.indexer.results.ResultMessage) RawMessage(org.graylog2.plugin.journal.RawMessage) Message(org.graylog2.plugin.Message) DocumentNotFoundException(org.graylog2.indexer.messages.DocumentNotFoundException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) NotFoundException(javax.ws.rs.NotFoundException) DocumentNotFoundException(org.graylog2.indexer.messages.DocumentNotFoundException) ResultMessage(org.graylog2.indexer.results.ResultMessage) Path(javax.ws.rs.Path) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 2 with ResultMessage

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

the class ScrollChunkWriter method writeTo.

@Override
public void writeTo(ScrollResult.ScrollChunk scrollChunk, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("[{}] Writing chunk {}", Thread.currentThread().getId(), scrollChunk.getChunkNumber());
    }
    final CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));
    final List<String> fields = scrollChunk.getFields();
    final int numberOfFields = fields.size();
    if (scrollChunk.isFirstChunk()) {
        // write field headers only on first chunk
        csvWriter.writeNext(fields.toArray(new String[numberOfFields]));
    }
    // write result set in same order as the header row
    final String[] fieldValues = new String[numberOfFields];
    for (ResultMessage message : scrollChunk.getMessages()) {
        int idx = 0;
        // first collect all values from the current message
        for (String fieldName : fields) {
            final Object val = message.getMessage().getField(fieldName);
            if (val == null) {
                fieldValues[idx] = null;
            } else {
                String stringVal = val.toString();
                fieldValues[idx] = stringVal.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
            }
            idx++;
        }
        // write the complete line, some fields might not be present in the message, so there might be null values
        csvWriter.writeNext(fieldValues);
    }
    if (csvWriter.checkError()) {
        LOG.error("Encountered unspecified error when writing message result as CSV, result is likely malformed.");
    }
    csvWriter.close();
}
Also used : CSVWriter(au.com.bytecode.opencsv.CSVWriter) OutputStreamWriter(java.io.OutputStreamWriter) ResultMessage(org.graylog2.indexer.results.ResultMessage)

Example 3 with ResultMessage

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

the class SearchResult method extractFields.

private Set<String> extractFields(List<ResultMessage> hits) {
    Set<String> filteredFields = Sets.newHashSet();
    Set<String> allFields = Sets.newHashSet();
    Iterator<ResultMessage> i = hits.iterator();
    while (i.hasNext()) {
        final Message message = i.next().getMessage();
        allFields.addAll(message.getFieldNames());
        for (String field : message.getFieldNames()) {
            if (!Message.RESERVED_FIELDS.contains(field)) {
                filteredFields.add(field);
            }
        }
    }
    // TODO: This is super awkward. First we do not include RESERVED_FIELDS, then we add some back...
    if (allFields.contains("message")) {
        filteredFields.add("message");
    }
    if (allFields.contains("source")) {
        filteredFields.add("source");
    }
    filteredFields.remove("streams");
    filteredFields.remove("full_message");
    return filteredFields;
}
Also used : Message(org.graylog2.plugin.Message)

Example 4 with ResultMessage

use of org.graylog2.indexer.results.ResultMessage 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 5 with ResultMessage

use of org.graylog2.indexer.results.ResultMessage 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)

Aggregations

Message (org.graylog2.plugin.Message)8 ResultMessage (org.graylog2.indexer.results.ResultMessage)7 NotFoundException (javax.ws.rs.NotFoundException)3 IndexNotFoundException (org.elasticsearch.index.IndexNotFoundException)3 InvalidRangeFormatException (org.graylog2.indexer.InvalidRangeFormatException)3 DocumentNotFoundException (org.graylog2.indexer.messages.DocumentNotFoundException)3 MessageSummary (org.graylog2.plugin.MessageSummary)3 InvalidRangeParametersException (org.graylog2.plugin.indexer.searches.timeranges.InvalidRangeParametersException)3 RawMessage (org.graylog2.plugin.journal.RawMessage)3 Timed (com.codahale.metrics.annotation.Timed)2 ApiOperation (io.swagger.annotations.ApiOperation)2 ApiResponses (io.swagger.annotations.ApiResponses)2 Path (javax.ws.rs.Path)2 SearchResult (org.graylog2.indexer.results.SearchResult)2 Sorting (org.graylog2.indexer.searches.Sorting)2 Configuration (org.graylog2.plugin.configuration.Configuration)2 CSVWriter (au.com.bytecode.opencsv.CSVWriter)1 UUID (com.eaio.uuid.UUID)1 OutputStreamWriter (java.io.OutputStreamWriter)1 InetSocketAddress (java.net.InetSocketAddress)1