Search in sources :

Example 61 with Messages

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

the class V20191203120602_MigrateSavedSearchesToViews method migrateSavedSearch.

private Map.Entry<View, Search> migrateSavedSearch(SavedSearch savedSearch) {
    final String histogramId = randomUUIDProvider.get();
    final String messageListId = randomUUIDProvider.get();
    final Set<ViewWidget> widgets = ImmutableSet.of(AggregationWidget.create(histogramId), savedSearch.query().toMessagesWidget(messageListId));
    final Map<String, Set<String>> widgetMapping = new HashMap<>(widgets.size());
    final Set<SearchType> searchTypes = widgets.stream().flatMap(widget -> {
        final Set<SearchType> widgetSearchTypes = widget.toSearchTypes(randomUUIDProvider);
        widgetMapping.put(widget.id(), widgetSearchTypes.stream().map(SearchType::id).collect(Collectors.toSet()));
        return widgetSearchTypes.stream();
    }).collect(Collectors.toSet());
    final Query.Builder queryBuilder = Query.builder().id(randomUUIDProvider.get()).timerange(savedSearch.query().toTimeRange()).query(savedSearch.query().query()).searchTypes(searchTypes);
    final Query query = savedSearch.query().streamId().map(queryBuilder::streamId).orElse(queryBuilder).build();
    final Search newSearch = Search.create(randomObjectIdProvider.get(), Collections.singleton(query), savedSearch.creatorUserId(), savedSearch.createdAt());
    final Titles titles = Titles.ofWidgetTitles(ImmutableMap.of(histogramId, "Message Count", messageListId, "All Messages"));
    final Map<String, ViewWidgetPosition> widgetPositions = ImmutableMap.of(histogramId, ViewWidgetPosition.builder().col(Position.fromInt(1)).row(Position.fromInt(1)).height(Position.fromInt(2)).width(Position.infinity()).build(), messageListId, ViewWidgetPosition.builder().col(Position.fromInt(1)).row(Position.fromInt(3)).height(Position.fromInt(6)).width(Position.infinity()).build());
    final ViewState viewState = ViewState.create(titles, widgets, widgetMapping, widgetPositions);
    final View newView = View.create(randomObjectIdProvider.get(), "Saved Search: " + savedSearch.title(), "This Search was migrated automatically from the \"" + savedSearch.title() + "\" saved search.", "", newSearch.id(), Collections.singletonMap(query.id(), viewState), Optional.of(savedSearch.creatorUserId()), savedSearch.createdAt());
    return new AbstractMap.SimpleEntry<>(newView, newSearch);
}
Also used : ViewService(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.ViewService) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) ZonedDateTime(java.time.ZonedDateTime) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) ViewWidgetPosition(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.ViewWidgetPosition) ViewState(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.ViewState) Inject(javax.inject.Inject) ClusterConfigService(org.graylog2.plugin.cluster.ClusterConfigService) Map(java.util.Map) Migration(org.graylog2.migrations.Migration) RandomObjectIdProvider(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.RandomObjectIdProvider) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) SearchType(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.search.SearchType) View(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.View) SavedSearch(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.savedsearch.SavedSearch) Query(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.search.Query) Set(java.util.Set) ViewWidget(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.ViewWidget) Collectors(java.util.stream.Collectors) SavedSearchService(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.savedsearch.SavedSearchService) Search(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.search.Search) AbstractMap(java.util.AbstractMap) RandomUUIDProvider(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.RandomUUIDProvider) JsonCreator(com.fasterxml.jackson.annotation.JsonCreator) AutoValue(com.google.auto.value.AutoValue) Position(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.Position) Optional(java.util.Optional) AggregationWidget(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.AggregationWidget) Titles(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.Titles) Collections(java.util.Collections) SearchService(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.search.SearchService) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) Query(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.search.Query) HashMap(java.util.HashMap) ViewState(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.ViewState) View(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.View) Titles(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.Titles) ViewWidget(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.ViewWidget) ViewWidgetPosition(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.view.ViewWidgetPosition) SavedSearch(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.savedsearch.SavedSearch) Search(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.search.Search) SearchType(org.graylog.plugins.views.migrations.V20191203120602_MigrateSavedSearchesToViewsSupport.search.SearchType)

Example 62 with Messages

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

the class MessagesResource method retrieve.

@ApiOperation(value = "Export messages as CSV", notes = "Use this endpoint, if you want to configure export parameters freely instead of relying on an existing Search")
@POST
@Produces(MoreMediaTypes.TEXT_CSV)
@NoAuditEvent("Has custom audit events")
public ChunkedOutput<SimpleMessageChunk> retrieve(@ApiParam @Valid MessagesRequest rawrequest, @Context SearchUser searchUser) {
    final MessagesRequest request = fillInIfNecessary(rawrequest, searchUser);
    final ValidationRequest.Builder validationReq = ValidationRequest.builder();
    Optional.ofNullable(rawrequest.queryString()).ifPresent(validationReq::query);
    Optional.ofNullable(rawrequest.timeRange()).ifPresent(validationReq::timerange);
    Optional.ofNullable(rawrequest.streams()).ifPresent(validationReq::streams);
    final ValidationResponse validationResponse = queryValidationService.validate(validationReq.build());
    if (validationResponse.status().equals(ValidationStatus.ERROR)) {
        validationResponse.explanations().stream().findFirst().map(ValidationMessage::errorMessage).ifPresent(message -> {
            throw new BadRequestException("Request validation failed: " + message);
        });
    }
    executionGuard.checkUserIsPermittedToSeeStreams(request.streams(), searchUser::canReadStream);
    ExportMessagesCommand command = commandFactory.buildFromRequest(request);
    return asyncRunner.apply(chunkConsumer -> exporter().export(command, chunkConsumer));
}
Also used : ValidationResponse(org.graylog.plugins.views.search.validation.ValidationResponse) ValidationRequest(org.graylog.plugins.views.search.validation.ValidationRequest) MessagesRequest(org.graylog.plugins.views.search.export.MessagesRequest) BadRequestException(javax.ws.rs.BadRequestException) ExportMessagesCommand(org.graylog.plugins.views.search.export.ExportMessagesCommand) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 63 with Messages

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

the class CmdLineTool method run.

@Override
public void run() {
    final Level logLevel = setupLogger();
    if (isDumpDefaultConfig()) {
        dumpDefaultConfigAndExit();
    }
    // This is holding all our metrics.
    MetricRegistry metricRegistry = MetricRegistryFactory.create();
    featureFlags = getFeatureFlags(metricRegistry);
    installConfigRepositories();
    installCommandConfig();
    beforeStart();
    beforeStart(parseAndGetTLSConfiguration(), parseAndGetPathConfiguration(configFile));
    processConfiguration(jadConfig);
    coreConfigInjector = setupCoreConfigInjector();
    final Set<Plugin> plugins = loadPlugins(getPluginPath(configFile), chainingClassLoader);
    installPluginConfig(plugins);
    processConfiguration(jadConfig);
    if (isDumpConfig()) {
        dumpCurrentConfigAndExit();
    }
    if (!validateConfiguration()) {
        LOG.error("Validating configuration file failed - exiting.");
        System.exit(1);
    }
    final List<String> arguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
    LOG.info("Running with JVM arguments: {}", Joiner.on(' ').join(arguments));
    beforeInjectorCreation(plugins);
    injector = setupInjector(new NamedConfigParametersModule(jadConfig.getConfigurationBeans()), new PluginBindings(plugins), binder -> binder.bind(MetricRegistry.class).toInstance(metricRegistry));
    if (injector == null) {
        LOG.error("Injector could not be created, exiting! (Please include the previous error messages in bug " + "reports.)");
        System.exit(1);
    }
    addInstrumentedAppender(metricRegistry, logLevel);
    // Report metrics via JMX.
    final JmxReporter reporter = JmxReporter.forRegistry(metricRegistry).build();
    reporter.start();
    startCommand();
}
Also used : NamedConfigParametersModule(com.github.joschi.jadconfig.guice.NamedConfigParametersModule) Option(com.github.rvesse.airline.annotations.Option) Module(com.google.inject.Module) Plugin(org.graylog2.plugin.Plugin) Arrays(java.util.Arrays) ParameterException(com.github.joschi.jadconfig.ParameterException) NodeIdPersistenceException(org.graylog2.plugin.system.NodeIdPersistenceException) FeatureFlagsFactory(org.graylog2.featureflag.FeatureFlagsFactory) GuiceInjectorHolder(org.graylog2.shared.bindings.GuiceInjectorHolder) RepositoryException(com.github.joschi.jadconfig.RepositoryException) LoggerContext(org.apache.logging.log4j.core.LoggerContext) Tools(org.graylog2.plugin.Tools) LoggerFactory(org.slf4j.LoggerFactory) Level(org.apache.logging.log4j.Level) Security(java.security.Security) InstrumentedAppender(com.codahale.metrics.log4j2.InstrumentedAppender) Message(com.google.inject.spi.Message) PluginLoaderConfig(org.graylog2.plugin.PluginLoaderConfig) Map(java.util.Map) UnsupportedSearchException(org.graylog2.storage.UnsupportedSearchException) Version(org.graylog2.plugin.Version) PropertiesRepository(com.github.joschi.jadconfig.repositories.PropertiesRepository) Command(com.github.rvesse.airline.annotations.Command) ChainingClassLoader(org.graylog2.shared.plugins.ChainingClassLoader) Path(java.nio.file.Path) TLSProtocolsConfiguration(org.graylog2.configuration.TLSProtocolsConfiguration) ExceptionUtils(org.graylog2.shared.utilities.ExceptionUtils) Slf4JLoggerFactory(io.netty.util.internal.logging.Slf4JLoggerFactory) ImmutableSet(com.google.common.collect.ImmutableSet) JodaTimeConverterFactory(com.github.joschi.jadconfig.jodatime.JodaTimeConverterFactory) Collection(java.util.Collection) Set(java.util.Set) ServerStatus(org.graylog2.plugin.ServerStatus) SearchVersion(org.graylog2.storage.SearchVersion) ValidationException(com.github.joschi.jadconfig.ValidationException) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Stage(com.google.inject.Stage) List(java.util.List) Stream(java.util.stream.Stream) Configuration(org.graylog2.Configuration) DocsHelper(org.graylog2.plugin.DocsHelper) PluginBindings(org.graylog2.shared.bindings.PluginBindings) PathConfiguration(org.graylog2.configuration.PathConfiguration) PluginMetaData(org.graylog2.plugin.PluginMetaData) ElasticsearchProbeException(org.graylog2.storage.versionprobe.ElasticsearchProbeException) UI(org.graylog2.shared.UI) AccessDeniedException(java.nio.file.AccessDeniedException) GuavaConverterFactory(com.github.joschi.jadconfig.guava.GuavaConverterFactory) Joiner(com.google.common.base.Joiner) EnvironmentRepository(com.github.joschi.jadconfig.repositories.EnvironmentRepository) Strings.nullToEmpty(com.google.common.base.Strings.nullToEmpty) Strings(joptsimple.internal.Strings) HashSet(java.util.HashSet) JmxReporter(com.codahale.metrics.jmx.JmxReporter) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Binder(com.google.inject.Binder) SystemPropertiesRepository(com.github.joschi.jadconfig.repositories.SystemPropertiesRepository) JadConfig(com.github.joschi.jadconfig.JadConfig) ManagementFactory(java.lang.management.ManagementFactory) NamedConfigParametersModule(com.github.joschi.jadconfig.guice.NamedConfigParametersModule) MigrateCmd(org.graylog2.bootstrap.commands.MigrateCmd) FeatureFlags(org.graylog2.featureflag.FeatureFlags) MetricRegistry(com.codahale.metrics.MetricRegistry) Logger(org.slf4j.Logger) Names(com.google.inject.name.Names) PluginLoader(org.graylog2.shared.plugins.PluginLoader) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Injector(com.google.inject.Injector) CreationException(com.google.inject.CreationException) Repository(com.github.joschi.jadconfig.Repository) Guice(com.google.inject.Guice) MetricRegistryFactory(org.graylog2.shared.metrics.MetricRegistryFactory) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) PluginBindings(org.graylog2.shared.bindings.PluginBindings) MetricRegistry(com.codahale.metrics.MetricRegistry) Level(org.apache.logging.log4j.Level) JmxReporter(com.codahale.metrics.jmx.JmxReporter) Plugin(org.graylog2.plugin.Plugin)

Example 64 with Messages

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

the class DecoratorProcessorImpl method decorate.

@Override
public SearchResponse decorate(SearchResponse searchResponse, List<SearchResponseDecorator> searchResponseDecorators) {
    try {
        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 65 with Messages

use of org.graylog2.indexer.messages.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(EnumSet.of(PROCESS, OUTPUT));
        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)

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