Search in sources :

Example 41 with IndexSet

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

the class V20161116172200_CreateDefaultStreamMigration method createDefaultStream.

private void createDefaultStream() {
    final IndexSet indexSet = indexSetRegistry.getDefault();
    final ObjectId id = new ObjectId(Stream.DEFAULT_STREAM_ID);
    final Map<String, Object> fields = ImmutableMap.<String, Object>builder().put(StreamImpl.FIELD_TITLE, "All messages").put(StreamImpl.FIELD_DESCRIPTION, "Stream containing all messages").put(StreamImpl.FIELD_DISABLED, false).put(StreamImpl.FIELD_CREATED_AT, DateTime.now(DateTimeZone.UTC)).put(StreamImpl.FIELD_CREATOR_USER_ID, "local:admin").put(StreamImpl.FIELD_MATCHING_TYPE, StreamImpl.MatchingType.DEFAULT.name()).put(StreamImpl.FIELD_REMOVE_MATCHES_FROM_DEFAULT_STREAM, false).put(StreamImpl.FIELD_DEFAULT_STREAM, true).put(StreamImpl.FIELD_INDEX_SET_ID, indexSet.getConfig().id()).build();
    final Stream stream = new StreamImpl(id, fields, Collections.emptyList(), Collections.emptySet(), indexSet);
    try {
        streamService.save(stream);
        LOG.info("Successfully created default stream: {}", stream.getTitle());
    } catch (ValidationException e) {
        LOG.error("Couldn't create default stream! This is a bug!");
    }
    clusterEventBus.post(StreamsChangedEvent.create(stream.getId()));
}
Also used : ValidationException(org.graylog2.plugin.database.ValidationException) ObjectId(org.bson.types.ObjectId) StreamImpl(org.graylog2.streams.StreamImpl) Stream(org.graylog2.plugin.streams.Stream) IndexSet(org.graylog2.indexer.IndexSet)

Example 42 with IndexSet

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

the class V20161130141500_DefaultStreamRecalcIndexRanges method upgrade.

@Override
public void upgrade() {
    IndexSet indexSet;
    try {
        indexSet = indexSetRegistry.getDefault();
    } catch (IllegalStateException e) {
        // Try to find the default index set manually if the index set registry cannot find it.
        // This is needed if you run this migration with a 2.2.0-beta.2 state before commit 460cac6af.
        final IndexSetConfig indexSetConfig = indexSetService.findOne(DBQuery.is("default", true)).orElseThrow(() -> new IllegalStateException("No default index set configured! This is a bug!"));
        indexSet = indexSetFactory.create(indexSetConfig);
    }
    final IndexSet defaultIndexSet = indexSet;
    if (!cluster.isConnected()) {
        LOG.info("Cluster not connected yet, delaying migration until it is reachable.");
        while (true) {
            try {
                cluster.waitForConnectedAndDeflectorHealthy();
                break;
            } catch (InterruptedException | TimeoutException e) {
                LOG.warn("Interrupted or timed out waiting for Elasticsearch cluster, checking again.");
            }
        }
    }
    final Set<String> indexRangesWithoutStreams = indexRangeService.findAll().stream().filter(indexRange -> defaultIndexSet.isManagedIndex(indexRange.indexName())).filter(indexRange -> indexRange.streamIds() == null).map(IndexRange::indexName).collect(Collectors.toSet());
    if (indexRangesWithoutStreams.size() == 0) {
        // all ranges have a stream list, even if it is empty, nothing more to do
        return;
    }
    final String currentWriteTarget;
    try {
        currentWriteTarget = defaultIndexSet.getActiveWriteIndex();
    } catch (TooManyAliasesException e) {
        LOG.error("Multiple write targets found for write alias. Cannot continue to assign streams to older indices", e);
        return;
    }
    for (String indexName : defaultIndexSet.getManagedIndices()) {
        if (indexName.equals(currentWriteTarget)) {
            // do not recalculate for current write target
            continue;
        }
        if (!indexRangesWithoutStreams.contains(indexName)) {
            // already computed streams for this index
            continue;
        }
        LOG.info("Recalculating streams in index {}", indexName);
        final CreateNewSingleIndexRangeJob createNewSingleIndexRangeJob = rebuildIndexRangeJobFactory.create(indexSetRegistry.getAll(), indexName);
        createNewSingleIndexRangeJob.execute();
    }
}
Also used : CreateNewSingleIndexRangeJob(org.graylog2.indexer.ranges.CreateNewSingleIndexRangeJob) IndexRangeService(org.graylog2.indexer.ranges.IndexRangeService) Logger(org.slf4j.Logger) Cluster(org.graylog2.indexer.cluster.Cluster) IndexSetConfig(org.graylog2.indexer.indexset.IndexSetConfig) ZonedDateTime(java.time.ZonedDateTime) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) TimeoutException(java.util.concurrent.TimeoutException) DBQuery(org.mongojack.DBQuery) Collectors(java.util.stream.Collectors) IndexRange(org.graylog2.indexer.ranges.IndexRange) Inject(javax.inject.Inject) IndexSetService(org.graylog2.indexer.indexset.IndexSetService) MongoIndexSet(org.graylog2.indexer.MongoIndexSet) IndexSet(org.graylog2.indexer.IndexSet) TooManyAliasesException(org.graylog2.indexer.indices.TooManyAliasesException) IndexSetRegistry(org.graylog2.indexer.IndexSetRegistry) CreateNewSingleIndexRangeJob(org.graylog2.indexer.ranges.CreateNewSingleIndexRangeJob) IndexSetConfig(org.graylog2.indexer.indexset.IndexSetConfig) TooManyAliasesException(org.graylog2.indexer.indices.TooManyAliasesException) MongoIndexSet(org.graylog2.indexer.MongoIndexSet) IndexSet(org.graylog2.indexer.IndexSet) TimeoutException(java.util.concurrent.TimeoutException)

Example 43 with IndexSet

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

the class IndexRangesMigrationPeriodical method doRun.

@Override
public void doRun() {
    final MongoIndexRangesMigrationComplete migrationComplete = clusterConfigService.get(MongoIndexRangesMigrationComplete.class);
    if (migrationComplete != null && migrationComplete.complete) {
        LOG.debug("Migration of index ranges (pre Graylog 1.2.2) already complete. Skipping migration process.");
        return;
    }
    while (!cluster.isConnected() || !cluster.isHealthy()) {
        Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
    }
    final Set<String> indexNames = ImmutableSet.copyOf(indexSetRegistry.getManagedIndices());
    // Migrate old MongoDB index ranges
    final SortedSet<IndexRange> mongoIndexRanges = legacyMongoIndexRangeService.findAll();
    for (IndexRange indexRange : mongoIndexRanges) {
        if (indexNames.contains(indexRange.indexName())) {
            LOG.info("Migrating index range from MongoDB: {}", indexRange);
            indexRangeService.save(indexRange);
        } else {
            LOG.info("Removing stale index range from MongoDB: {}", indexRange);
        }
        legacyMongoIndexRangeService.delete(indexRange.indexName());
    }
    // Check whether all index ranges have been migrated
    final int numberOfIndices = indexNames.size();
    final SortedSet<IndexRange> allIndexRanges = indexRangeService.findAll();
    final int numberOfIndexRanges = allIndexRanges.size();
    if (numberOfIndices > numberOfIndexRanges) {
        LOG.info("There are more indices ({}) than there are index ranges ({}). Notifying administrator.", numberOfIndices, numberOfIndexRanges);
        // remove all present index names so we can display the index sets that need manual fixing
        final Set<String> extraIndices = Sets.newHashSet(indexNames);
        allIndexRanges.forEach(indexRange -> extraIndices.remove(indexRange.indexName()));
        final Set<String> affectedIndexSetNames = extraIndices.stream().map(indexSetRegistry::getForIndex).filter(Optional::isPresent).map(Optional::get).map(IndexSet::getConfig).map(IndexSetConfig::title).collect(Collectors.toSet());
        final Notification notification = notificationService.buildNow().addSeverity(Notification.Severity.URGENT).addType(Notification.Type.INDEX_RANGES_RECALCULATION).addDetail("indices", numberOfIndices).addDetail("index_ranges", numberOfIndexRanges).addDetail("index_sets", affectedIndexSetNames.isEmpty() ? null : Joiner.on(", ").join(affectedIndexSetNames));
        notificationService.publishIfFirst(notification);
    }
    clusterConfigService.write(new MongoIndexRangesMigrationComplete(true));
}
Also used : IndexRange(org.graylog2.indexer.ranges.IndexRange) Optional(java.util.Optional) IndexSet(org.graylog2.indexer.IndexSet) Notification(org.graylog2.notifications.Notification)

Example 44 with IndexSet

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

the class IndexRotationThread method checkAndRepair.

protected void checkAndRepair(IndexSet indexSet) {
    if (!indexSet.isUp()) {
        if (indices.exists(indexSet.getWriteIndexAlias())) {
            // Publish a notification if there is an *index* called graylog2_deflector
            Notification notification = notificationService.buildNow().addType(Notification.Type.DEFLECTOR_EXISTS_AS_INDEX).addSeverity(Notification.Severity.URGENT);
            final boolean published = notificationService.publishIfFirst(notification);
            if (published) {
                LOG.warn("There is an index called [" + indexSet.getWriteIndexAlias() + "]. Cannot fix this automatically and published a notification.");
            }
        } else {
            indexSet.setUp();
        }
    } else {
        try {
            String currentTarget;
            try {
                currentTarget = indexSet.getActiveWriteIndex();
            } catch (TooManyAliasesException e) {
                // If we get this exception, there are multiple indices which have the deflector alias set.
                // We try to cleanup the alias and try again. This should not happen, but might under certain
                // circumstances.
                indexSet.cleanupAliases(e.getIndices());
                try {
                    currentTarget = indexSet.getActiveWriteIndex();
                } catch (TooManyAliasesException e1) {
                    throw new IllegalStateException(e1);
                }
            }
            String shouldBeTarget = indexSet.getNewestIndex();
            if (!shouldBeTarget.equals(currentTarget)) {
                String msg = "Deflector is pointing to [" + currentTarget + "], not the newest one: [" + shouldBeTarget + "]. Re-pointing.";
                LOG.warn(msg);
                activityWriter.write(new Activity(msg, IndexRotationThread.class));
                if (ClusterHealthStatus.RED == indices.waitForRecovery(shouldBeTarget)) {
                    LOG.error("New target index for deflector didn't get healthy within timeout. Skipping deflector update.");
                } else {
                    indexSet.pointTo(shouldBeTarget, currentTarget);
                }
            }
        } catch (NoTargetIndexException e) {
            LOG.warn("Deflector is not up. Not trying to point to another index.");
        }
    }
}
Also used : NoTargetIndexException(org.graylog2.indexer.NoTargetIndexException) Activity(org.graylog2.shared.system.activities.Activity) TooManyAliasesException(org.graylog2.indexer.indices.TooManyAliasesException) Notification(org.graylog2.notifications.Notification)

Example 45 with IndexSet

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

the class IndexRotationThread method checkForRotation.

protected void checkForRotation(IndexSet indexSet) {
    final IndexSetConfig config = indexSet.getConfig();
    final Provider<RotationStrategy> rotationStrategyProvider = rotationStrategyMap.get(config.rotationStrategyClass());
    if (rotationStrategyProvider == null) {
        LOG.warn("Rotation strategy \"{}\" not found, not running index rotation!", config.rotationStrategyClass());
        rotationProblemNotification("Index Rotation Problem!", "Index rotation strategy " + config.rotationStrategyClass() + " not found! Please fix your index rotation configuration!");
        return;
    }
    final RotationStrategy rotationStrategy = rotationStrategyProvider.get();
    if (rotationStrategy == null) {
        LOG.warn("No rotation strategy found, not running index rotation!");
        return;
    }
    rotationStrategy.rotate(indexSet);
}
Also used : IndexSetConfig(org.graylog2.indexer.indexset.IndexSetConfig) RotationStrategy(org.graylog2.plugin.indexer.rotation.RotationStrategy)

Aggregations

IndexSet (org.graylog2.indexer.IndexSet)31 Test (org.junit.Test)26 IndexSetConfig (org.graylog2.indexer.indexset.IndexSetConfig)22 Timed (com.codahale.metrics.annotation.Timed)13 ApiOperation (io.swagger.annotations.ApiOperation)13 Path (javax.ws.rs.Path)12 AuditEvent (org.graylog2.audit.jersey.AuditEvent)11 ApiResponses (io.swagger.annotations.ApiResponses)10 Map (java.util.Map)9 POST (javax.ws.rs.POST)9 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)9 BadRequestException (javax.ws.rs.BadRequestException)8 NotFoundException (javax.ws.rs.NotFoundException)8 Produces (javax.ws.rs.Produces)8 DefaultIndexSetConfig (org.graylog2.indexer.indexset.DefaultIndexSetConfig)8 Set (java.util.Set)7 Collectors (java.util.stream.Collectors)7 Inject (javax.inject.Inject)7 IndexSetRegistry (org.graylog2.indexer.IndexSetRegistry)7 Api (io.swagger.annotations.Api)6