Search in sources :

Example 1 with Searches

use of org.graylog2.indexer.searches.Searches in project graylog2-server by Graylog2.

the class SearchesTest method setUp.

@Before
public void setUp() throws Exception {
    when(indexRangeService.find(any(DateTime.class), any(DateTime.class))).thenReturn(INDEX_RANGES);
    metricRegistry = new MetricRegistry();
    searches = new Searches(new Configuration(), indexRangeService, client, metricRegistry, streamService, mock(Indices.class));
}
Also used : Configuration(org.graylog2.Configuration) MetricRegistry(com.codahale.metrics.MetricRegistry) ZonedDateTime(java.time.ZonedDateTime) DateTime(org.joda.time.DateTime) Before(org.junit.Before)

Example 2 with Searches

use of org.graylog2.indexer.searches.Searches in project graylog2-server by Graylog2.

the class V20190304102700_MigrateMessageListStructure method findSearchTypIds.

private List<String> findSearchTypIds(String stateId, String searchId, List<String> widgetMappingSearchTypeIds) {
    final BasicDBObject dbQuery = new BasicDBObject();
    dbQuery.put("_id", new ObjectId(searchId));
    final FindIterable<Document> searches = this.searchCollections.find(dbQuery);
    /* There can be only one search with matching id */
    assert this.searchCollections.count(dbQuery) == 1;
    final Document search = searches.first();
    final List<String> searchTypeId = new ArrayList<>();
    @SuppressWarnings("unchecked") final List<Document> queries = (ArrayList) search.get("queries");
    for (final Document query : queries) {
        if (query.getString("id").equals(stateId)) {
            @SuppressWarnings("unchecked") final List<Document> searchTypes = (ArrayList) query.get("search_types");
            searchTypeId.addAll(searchTypes.stream().map(searchType -> searchType.getString("id")).filter(search_id -> !widgetMappingSearchTypeIds.contains(search_id)).collect(Collectors.toList()));
        }
    }
    return searchTypeId;
}
Also used : Document(org.bson.Document) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Logger(org.slf4j.Logger) MongoCollection(com.mongodb.client.MongoCollection) ZonedDateTime(java.time.ZonedDateTime) BasicDBObject(com.mongodb.BasicDBObject) LoggerFactory(org.slf4j.LoggerFactory) WithBeanGetter(org.graylog.autovalue.WithBeanGetter) JsonAutoDetect(com.fasterxml.jackson.annotation.JsonAutoDetect) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) List(java.util.List) ClusterConfigService(org.graylog2.plugin.cluster.ClusterConfigService) FindIterable(com.mongodb.client.FindIterable) Map(java.util.Map) JsonCreator(com.fasterxml.jackson.annotation.JsonCreator) AutoValue(com.google.auto.value.AutoValue) ObjectId(org.bson.types.ObjectId) Optional(java.util.Optional) Migration(org.graylog2.migrations.Migration) MongoConnection(org.graylog2.database.MongoConnection) Comparator(java.util.Comparator) BasicDBObject(com.mongodb.BasicDBObject) ObjectId(org.bson.types.ObjectId) ArrayList(java.util.ArrayList) Document(org.bson.Document)

Example 3 with Searches

use of org.graylog2.indexer.searches.Searches in project graylog2-server by Graylog2.

the class V20151210140600_ElasticsearchConfigMigration method upgrade.

// Migrate old Elasticsearch config settings to new ClusterConfig based ones.
@Override
public void upgrade() {
    // All default rotation strategy settings.
    final MessageCountRotationStrategyConfig messageCountRotationStrategyConfig = clusterConfigService.get(MessageCountRotationStrategyConfig.class);
    final SizeBasedRotationStrategyConfig sizeBasedRotationStrategyConfig = clusterConfigService.get(SizeBasedRotationStrategyConfig.class);
    final TimeBasedRotationStrategyConfig timeBasedRotationStrategyConfig = clusterConfigService.get(TimeBasedRotationStrategyConfig.class);
    if (messageCountRotationStrategyConfig == null) {
        final MessageCountRotationStrategyConfig countConfig = MessageCountRotationStrategyConfig.create(elasticsearchConfiguration.getMaxDocsPerIndex());
        clusterConfigService.write(countConfig);
        LOG.info("Migrated \"{}\" setting: {}", "elasticsearch_max_docs_per_index", countConfig);
    }
    if (sizeBasedRotationStrategyConfig == null) {
        final SizeBasedRotationStrategyConfig sizeConfig = SizeBasedRotationStrategyConfig.create(elasticsearchConfiguration.getMaxSizePerIndex());
        clusterConfigService.write(sizeConfig);
        LOG.info("Migrated \"{}\" setting: {}", "elasticsearch_max_size_per_index", sizeConfig);
    }
    if (timeBasedRotationStrategyConfig == null) {
        final TimeBasedRotationStrategyConfig timeConfig = TimeBasedRotationStrategyConfig.create(elasticsearchConfiguration.getMaxTimePerIndex(), elasticsearchConfiguration.getMaxWriteIndexAge());
        clusterConfigService.write(timeConfig);
        LOG.info("Migrated \"{}\" setting: {}", "elasticsearch_max_time_per_index", timeConfig);
    }
    // All default retention strategy settings
    final ClosingRetentionStrategyConfig closingRetentionStrategyConfig = clusterConfigService.get(ClosingRetentionStrategyConfig.class);
    final DeletionRetentionStrategyConfig deletionRetentionStrategyConfig = clusterConfigService.get(DeletionRetentionStrategyConfig.class);
    if (closingRetentionStrategyConfig == null) {
        final ClosingRetentionStrategyConfig closingConfig = ClosingRetentionStrategyConfig.create(elasticsearchConfiguration.getMaxNumberOfIndices());
        clusterConfigService.write(closingConfig);
        LOG.info("Migrated \"{}\" setting: {}", "elasticsearch_max_number_of_indices", closingConfig);
    }
    if (deletionRetentionStrategyConfig == null) {
        final DeletionRetentionStrategyConfig deletionConfig = DeletionRetentionStrategyConfig.create(elasticsearchConfiguration.getMaxNumberOfIndices());
        clusterConfigService.write(deletionConfig);
        LOG.info("Migrated \"{}\" setting: {}", "elasticsearch_max_number_of_indices", deletionConfig);
    }
    // Selected rotation and retention strategies.
    final IndexManagementConfig indexManagementConfig = clusterConfigService.get(IndexManagementConfig.class);
    if (indexManagementConfig == null) {
        final Class<? extends RotationStrategy> rotationStrategyClass;
        switch(elasticsearchConfiguration.getRotationStrategy()) {
            case "size":
                rotationStrategyClass = SizeBasedRotationStrategy.class;
                break;
            case "time":
                rotationStrategyClass = TimeBasedRotationStrategy.class;
                break;
            case "count":
                rotationStrategyClass = MessageCountRotationStrategy.class;
                break;
            default:
                LOG.warn("Unknown retention strategy \"{}\"", elasticsearchConfiguration.getRotationStrategy());
                rotationStrategyClass = MessageCountRotationStrategy.class;
        }
        final Class<? extends RetentionStrategy> retentionStrategyClass;
        switch(elasticsearchConfiguration.getRetentionStrategy()) {
            case "close":
                retentionStrategyClass = ClosingRetentionStrategy.class;
                break;
            case "delete":
                retentionStrategyClass = DeletionRetentionStrategy.class;
                break;
            default:
                LOG.warn("Unknown retention strategy \"{}\"", elasticsearchConfiguration.getRetentionStrategy());
                retentionStrategyClass = DeletionRetentionStrategy.class;
        }
        final IndexManagementConfig config = IndexManagementConfig.create(rotationStrategyClass.getCanonicalName(), retentionStrategyClass.getCanonicalName());
        clusterConfigService.write(config);
        LOG.info("Migrated \"{}\" and \"{}\" setting: {}", "rotation_strategy", "retention_strategy", config);
    }
    final SearchesClusterConfig searchesClusterConfig = clusterConfigService.get(SearchesClusterConfig.class);
    if (searchesClusterConfig == null) {
        final SearchesClusterConfig config = SearchesClusterConfig.createDefault();
        LOG.info("Creating searches cluster config: {}", config);
        clusterConfigService.write(config);
    }
}
Also used : TimeBasedRotationStrategyConfig(org.graylog2.indexer.rotation.strategies.TimeBasedRotationStrategyConfig) MessageCountRotationStrategyConfig(org.graylog2.indexer.rotation.strategies.MessageCountRotationStrategyConfig) SearchesClusterConfig(org.graylog2.indexer.searches.SearchesClusterConfig) ClosingRetentionStrategyConfig(org.graylog2.indexer.retention.strategies.ClosingRetentionStrategyConfig) SizeBasedRotationStrategyConfig(org.graylog2.indexer.rotation.strategies.SizeBasedRotationStrategyConfig) DeletionRetentionStrategyConfig(org.graylog2.indexer.retention.strategies.DeletionRetentionStrategyConfig) IndexManagementConfig(org.graylog2.indexer.management.IndexManagementConfig)

Example 4 with Searches

use of org.graylog2.indexer.searches.Searches in project graylog2-server by Graylog2.

the class ViewsResource method validateIntegrity.

private void validateIntegrity(ViewDTO dto, SearchUser searchUser) {
    final Search search = searchDomain.getForUser(dto.searchId(), searchUser).orElseThrow(() -> new BadRequestException("Search " + dto.searchId() + " not available"));
    final Set<String> searchQueries = search.queries().stream().map(Query::id).collect(Collectors.toSet());
    final Set<String> stateQueries = dto.state().keySet();
    if (!searchQueries.containsAll(stateQueries)) {
        final Sets.SetView<String> diff = Sets.difference(searchQueries, stateQueries);
        throw new BadRequestException("Search queries do not correspond to view/state queries, missing query IDs: " + diff);
    }
    final Set<String> searchTypes = search.queries().stream().flatMap(q -> q.searchTypes().stream()).map(SearchType::id).collect(Collectors.toSet());
    final Set<String> stateTypes = dto.state().values().stream().flatMap(v -> v.widgetMapping().values().stream()).flatMap(Collection::stream).collect(Collectors.toSet());
    if (!searchTypes.containsAll(stateTypes)) {
        final Sets.SetView<String> diff = Sets.difference(searchTypes, stateTypes);
        throw new BadRequestException("Search types do not correspond to view/search types, missing searches: " + diff);
    }
    final Set<String> widgetIds = dto.state().values().stream().flatMap(v -> v.widgets().stream()).map(WidgetDTO::id).collect(Collectors.toSet());
    final Set<String> widgetPositions = dto.state().values().stream().flatMap(v -> v.widgetPositions().keySet().stream()).collect(Collectors.toSet());
    if (!widgetPositions.containsAll(widgetIds)) {
        final Sets.SetView<String> diff = Sets.difference(widgetPositions, widgetIds);
        throw new BadRequestException("Widget positions don't correspond to widgets, missing widget possitions: " + diff);
    }
}
Also used : Produces(javax.ws.rs.Produces) ViewsAuditEventTypes(org.graylog.plugins.views.audit.ViewsAuditEventTypes) UserContext(org.graylog.security.UserContext) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) WidgetDTO(org.graylog.plugins.views.search.views.WidgetDTO) ViewDTO(org.graylog.plugins.views.search.views.ViewDTO) NotEmpty(javax.validation.constraints.NotEmpty) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) PaginatedList(org.graylog2.database.PaginatedList) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) SearchQueryField(org.graylog2.search.SearchQueryField) Locale(java.util.Locale) Map(java.util.Map) PluginRestResource(org.graylog2.plugin.rest.PluginRestResource) DefaultValue(javax.ws.rs.DefaultValue) BadRequestException(javax.ws.rs.BadRequestException) ENGLISH(java.util.Locale.ENGLISH) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) ClusterEventBus(org.graylog2.events.ClusterEventBus) SearchUser(org.graylog.plugins.views.search.permissions.SearchUser) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) PathParam(javax.ws.rs.PathParam) Query(org.graylog.plugins.views.search.Query) SearchQueryParser(org.graylog2.search.SearchQueryParser) GET(javax.ws.rs.GET) ViewResolver(org.graylog.plugins.views.search.views.ViewResolver) SearchDomain(org.graylog.plugins.views.search.SearchDomain) Inject(javax.inject.Inject) ViewResolverDecoder(org.graylog.plugins.views.search.views.ViewResolverDecoder) SearchType(org.graylog.plugins.views.search.SearchType) AuditEvent(org.graylog2.audit.jersey.AuditEvent) Api(io.swagger.annotations.Api) Search(org.graylog.plugins.views.search.Search) SearchQuery(org.graylog2.search.SearchQuery) DashboardDeletedEvent(org.graylog2.dashboards.events.DashboardDeletedEvent) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) ForbiddenException(javax.ws.rs.ForbiddenException) RestResource(org.graylog2.shared.rest.resources.RestResource) ValidationException(org.graylog2.plugin.database.ValidationException) ViewService(org.graylog.plugins.views.search.views.ViewService) PUT(javax.ws.rs.PUT) PaginatedResponse(org.graylog2.rest.models.PaginatedResponse) User(org.graylog2.plugin.database.users.User) Sets(com.google.common.collect.Sets) Search(org.graylog.plugins.views.search.Search) BadRequestException(javax.ws.rs.BadRequestException)

Example 5 with Searches

use of org.graylog2.indexer.searches.Searches in project graylog2-server by Graylog2.

the class FieldContentValueAlertConditionTest method testCorrectUsageOfRelativeRange.

@Test
public void testCorrectUsageOfRelativeRange() throws Exception {
    final Stream stream = mock(Stream.class);
    final Searches searches = mock(Searches.class);
    final Configuration configuration = mock(Configuration.class);
    final SearchResult searchResult = mock(SearchResult.class);
    final int alertCheckInterval = 42;
    final RelativeRange relativeRange = RelativeRange.create(alertCheckInterval);
    when(stream.getId()).thenReturn("stream-id");
    when(configuration.getAlertCheckInterval()).thenReturn(alertCheckInterval);
    when(searches.search(anyString(), anyString(), eq(relativeRange), anyInt(), anyInt(), any(Sorting.class))).thenReturn(searchResult);
    final FieldContentValueAlertCondition alertCondition = new FieldContentValueAlertCondition(searches, configuration, stream, null, DateTime.now(DateTimeZone.UTC), "mockuser", ImmutableMap.<String, Object>of("field", "test", "value", "test"), "Field Content Value Test COndition");
    final AbstractAlertCondition.CheckResult result = alertCondition.runCheck();
}
Also used : Searches(org.graylog2.indexer.searches.Searches) Configuration(org.graylog2.Configuration) RelativeRange(org.graylog2.plugin.indexer.searches.timeranges.RelativeRange) Stream(org.graylog2.plugin.streams.Stream) SearchResult(org.graylog2.indexer.results.SearchResult) AbstractAlertCondition(org.graylog2.alerts.AbstractAlertCondition) Sorting(org.graylog2.indexer.searches.Sorting) Test(org.junit.Test) AlertConditionTest(org.graylog2.alerts.AlertConditionTest)

Aggregations

ZonedDateTime (java.time.ZonedDateTime)15 DateTime (org.joda.time.DateTime)15 Test (org.junit.Test)15 ElasticsearchBaseTest (org.graylog.testing.elasticsearch.ElasticsearchBaseTest)13 AbsoluteRange (org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange)7 HashSet (java.util.HashSet)4 Map (java.util.Map)4 Collectors (java.util.stream.Collectors)4 Inject (javax.inject.Inject)4 CountResult (org.graylog2.indexer.results.CountResult)4 SearchResult (org.graylog2.indexer.results.SearchResult)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Optional (java.util.Optional)3 Set (java.util.Set)3 FieldStatsResult (org.graylog2.indexer.results.FieldStatsResult)3 Maps (com.google.common.collect.Maps)2 Named (com.google.inject.name.Named)2 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2