Search in sources :

Example 21 with Messages

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

the class FormattedEmailAlertSenderTest method defaultBodyTemplateDoesNotShowBacklogIfBacklogIsEmpty.

@Test
public void defaultBodyTemplateDoesNotShowBacklogIfBacklogIsEmpty() throws Exception {
    FormattedEmailAlertSender emailAlertSender = new FormattedEmailAlertSender(new EmailConfiguration(), mockNotificationService, mockNodeId, templateEngine);
    Stream stream = mock(Stream.class);
    when(stream.getId()).thenReturn("123456");
    when(stream.getTitle()).thenReturn("Stream Title");
    AlertCondition alertCondition = mock(AlertCondition.class);
    AlertCondition.CheckResult checkResult = mock(AbstractAlertCondition.CheckResult.class);
    when(checkResult.getTriggeredAt()).thenReturn(new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC));
    when(checkResult.getTriggeredCondition()).thenReturn(alertCondition);
    String body = emailAlertSender.buildBody(stream, checkResult, Collections.<Message>emptyList());
    assertThat(body).contains("<No backlog>\n").doesNotContain("Last messages accounting for this alert:\n");
}
Also used : EmailConfiguration(org.graylog2.configuration.EmailConfiguration) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Example 22 with Messages

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

the class FormattedEmailAlertSenderTest method defaultBodyTemplateShowsBacklogIfBacklogIsNotEmpty.

@Test
public void defaultBodyTemplateShowsBacklogIfBacklogIsNotEmpty() throws Exception {
    FormattedEmailAlertSender emailAlertSender = new FormattedEmailAlertSender(new EmailConfiguration(), mockNotificationService, mockNodeId, templateEngine);
    Stream stream = mock(Stream.class);
    when(stream.getId()).thenReturn("123456");
    when(stream.getTitle()).thenReturn("Stream Title");
    AlertCondition alertCondition = mock(AlertCondition.class);
    AlertCondition.CheckResult checkResult = mock(AbstractAlertCondition.CheckResult.class);
    when(checkResult.getTriggeredAt()).thenReturn(new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC));
    when(checkResult.getTriggeredCondition()).thenReturn(alertCondition);
    Message message = new Message("Test", "source", new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC));
    String body = emailAlertSender.buildBody(stream, checkResult, Collections.singletonList(message));
    assertThat(body).doesNotContain("<No backlog>\n").containsSequence("Last messages accounting for this alert:\n", message.toString());
}
Also used : Message(org.graylog2.plugin.Message) EmailConfiguration(org.graylog2.configuration.EmailConfiguration) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Example 23 with Messages

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

the class DecoratorProcessorImpl method decorate.

@Override
public SearchResponse decorate(SearchResponse searchResponse, Optional<String> streamId) {
    try {
        final List<SearchResponseDecorator> searchResponseDecorators = streamId.isPresent() ? decoratorResolver.searchResponseDecoratorsForStream(streamId.get()) : decoratorResolver.searchResponseDecoratorsForGlobal();
        final Optional<SearchResponseDecorator> metaDecorator = searchResponseDecorators.stream().reduce((f, g) -> (v) -> g.apply(f.apply(v)));
        if (metaDecorator.isPresent()) {
            final Map<String, ResultMessageSummary> originalMessages = searchResponse.messages().stream().collect(Collectors.toMap(this::getMessageKey, Function.identity()));
            final SearchResponse newSearchResponse = metaDecorator.get().apply(searchResponse);
            final Set<String> newFields = extractFields(newSearchResponse.messages());
            final List<ResultMessageSummary> decoratedMessages = newSearchResponse.messages().stream().map(resultMessage -> {
                final ResultMessageSummary originalMessage = originalMessages.get(getMessageKey(resultMessage));
                if (originalMessage != null) {
                    return resultMessage.toBuilder().decorationStats(DecorationStats.create(originalMessage.message(), resultMessage.message())).build();
                }
                return resultMessage;
            }).collect(Collectors.toList());
            return newSearchResponse.toBuilder().messages(decoratedMessages).fields(newFields).decorationStats(this.getSearchDecoratorStats(decoratedMessages)).build();
        }
    } catch (Exception e) {
        LOG.error("Error decorating search response", e);
    }
    return searchResponse;
}
Also used : Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse) Set(java.util.Set) SearchResponseDecorator(org.graylog2.plugin.decorators.SearchResponseDecorator) SearchDecorationStats(org.graylog2.rest.resources.search.responses.SearchDecorationStats) DecorationStats(org.graylog2.rest.models.messages.responses.DecorationStats) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) Inject(javax.inject.Inject) HashSet(java.util.HashSet) List(java.util.List) Map(java.util.Map) Optional(java.util.Optional) Message(org.graylog2.plugin.Message) SearchResponseDecorator(org.graylog2.plugin.decorators.SearchResponseDecorator) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse)

Example 24 with Messages

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

the class FixDeflectorByMoveJob method doExecute.

public void doExecute(IndexSet indexSet) {
    if (!indexSet.getConfig().isWritable()) {
        LOG.debug("No need to fix deflector for non-writable index set <{}> ({})", indexSet.getConfig().id(), indexSet.getConfig().title());
        return;
    }
    if (indexSet.isUp() || !indices.exists(indexSet.getWriteIndexAlias())) {
        LOG.error("There is no index <{}>. No need to run this job. Aborting.", indexSet.getWriteIndexAlias());
        return;
    }
    LOG.info("Attempting to fix deflector with move strategy.");
    boolean wasProcessing = true;
    try {
        // Pause message processing and lock the pause.
        wasProcessing = serverStatus.isProcessing();
        serverStatus.pauseMessageProcessing();
        progress = 5;
        bufferSynchronizer.waitForEmptyBuffers();
        progress = 10;
        // Copy messages to new index.
        String newTarget = null;
        try {
            newTarget = indexSet.getNewestIndex();
            LOG.info("Starting to move <{}> to <{}>.", indexSet.getWriteIndexAlias(), newTarget);
            indices.move(indexSet.getWriteIndexAlias(), newTarget);
        } catch (Exception e) {
            LOG.error("Moving index failed. Rolling back.", e);
            if (newTarget != null) {
                indices.delete(newTarget);
            }
            throw new RuntimeException(e);
        }
        LOG.info("Done moving deflector index.");
        progress = 85;
        // Delete deflector index.
        LOG.info("Deleting <{}> index.", indexSet.getWriteIndexAlias());
        indices.delete(indexSet.getWriteIndexAlias());
        progress = 90;
        // Set up deflector.
        indexSet.setUp();
        progress = 95;
    } finally {
        // Start message processing again.
        serverStatus.unlockProcessingPause();
        if (wasProcessing) {
            serverStatus.resumeMessageProcessing();
        }
    }
    progress = 90;
    activityWriter.write(new Activity("Notification condition [" + Notification.Type.DEFLECTOR_EXISTS_AS_INDEX + "] " + "has been fixed.", this.getClass()));
    notificationService.fixed(Notification.Type.DEFLECTOR_EXISTS_AS_INDEX);
    progress = 100;
    LOG.info("Finished.");
}
Also used : Activity(org.graylog2.shared.system.activities.Activity)

Example 25 with Messages

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

the class Indices method getAllMessageFieldsForIndices.

public Map<String, Set<String>> getAllMessageFieldsForIndices(final String[] writeIndexWildcards) {
    final Map<String, Set<String>> fields = new HashMap<>();
    final ClusterStateRequest csr = new ClusterStateRequest().blocks(true).nodes(true).indices(writeIndexWildcards);
    final ClusterState cs = c.admin().cluster().state(csr).actionGet().getState();
    for (ObjectObjectCursor<String, IndexMetaData> m : cs.getMetaData().indices()) {
        try {
            MappingMetaData mmd = m.value.mapping(IndexMapping.TYPE_MESSAGE);
            if (mmd == null) {
                // There is no mapping if there are no messages in the index.
                continue;
            }
            @SuppressWarnings("unchecked") final Map<String, Object> mapping = (Map<String, Object>) mmd.getSourceAsMap().get("properties");
            if (mapping != null) {
                fields.put(m.key, mapping.keySet());
            }
        } catch (Exception e) {
            LOG.error("Error while trying to get fields of <" + m.index + ">", e);
        }
    }
    return fields;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexSet(org.graylog2.indexer.IndexSet) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashMap(java.util.HashMap) ClusterStateRequest(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) ElasticsearchException(org.elasticsearch.ElasticsearchException) IndexClosedException(org.elasticsearch.indices.IndexClosedException) IndexNotFoundException(org.graylog2.indexer.IndexNotFoundException) IOException(java.io.IOException) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) HashMap(java.util.HashMap)

Aggregations

Message (org.graylog2.plugin.Message)15 Timed (com.codahale.metrics.annotation.Timed)11 ApiOperation (io.swagger.annotations.ApiOperation)11 Produces (javax.ws.rs.Produces)10 ApiResponses (io.swagger.annotations.ApiResponses)9 Test (org.junit.Test)9 GET (javax.ws.rs.GET)8 Map (java.util.Map)6 SearchPhaseExecutionException (org.elasticsearch.action.search.SearchPhaseExecutionException)6 TimeRange (org.graylog2.plugin.indexer.searches.timeranges.TimeRange)6 MetricRegistry (com.codahale.metrics.MetricRegistry)5 IndexSet (org.graylog2.indexer.IndexSet)5 ResultMessage (org.graylog2.indexer.results.ResultMessage)5 Sorting (org.graylog2.indexer.searches.Sorting)5 Timer (com.codahale.metrics.Timer)4 ImmutableMap (com.google.common.collect.ImmutableMap)4 Stream (org.graylog2.plugin.streams.Stream)4 AccessDeniedException (java.nio.file.AccessDeniedException)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3