Search in sources :

Example 6 with Cluster

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

the class IndexRotationThreadTest method testDoNotPerformRotation.

@Test
public void testDoNotPerformRotation() throws NoTargetIndexException {
    final Provider<RotationStrategy> provider = new RotationStrategyProvider();
    final IndexRotationThread rotationThread = new IndexRotationThread(notificationService, indices, indexSetRegistry, cluster, new NullActivityWriter(), nodeId, ImmutableMap.<String, Provider<RotationStrategy>>builder().put("strategy", provider).build());
    when(indexSetConfig.rotationStrategyClass()).thenReturn("strategy");
    rotationThread.checkForRotation(indexSet);
    verify(indexSet, never()).cycle();
}
Also used : NullActivityWriter(org.graylog2.shared.system.activities.NullActivityWriter) RotationStrategy(org.graylog2.plugin.indexer.rotation.RotationStrategy) Test(org.junit.Test)

Example 7 with Cluster

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

the class Indices method areReopened.

public Map<String, Boolean> areReopened(Collection<String> indices) {
    final ClusterStateResponse clusterState = c.admin().cluster().prepareState().all().get();
    final ImmutableOpenMap<String, IndexMetaData> indicesMetaData = clusterState.getState().getMetaData().getIndices();
    return indices.stream().collect(Collectors.toMap(index -> index, index -> checkForReopened(indicesMetaData.get(index))));
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) GetAliasesResponse(org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse) SortBuilders(org.elasticsearch.search.sort.SortBuilders) DateTimeZone(org.joda.time.DateTimeZone) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) LoggerFactory(org.slf4j.LoggerFactory) IndexStats(org.elasticsearch.action.admin.indices.stats.IndexStats) IndexClosedException(org.elasticsearch.indices.IndexClosedException) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) ClusterState(org.elasticsearch.cluster.ClusterState) IndicesStatsRequest(org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest) Settings(org.elasticsearch.common.settings.Settings) WriteConsistencyLevel(org.elasticsearch.action.WriteConsistencyLevel) PutIndexTemplateRequest(org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest) Map(java.util.Map) SearchResponse(org.elasticsearch.action.search.SearchResponse) IndexRangeStats(org.graylog2.indexer.searches.IndexRangeStats) IndexSet(org.graylog2.indexer.IndexSet) IndexMapping(org.graylog2.indexer.IndexMapping) Max(org.elasticsearch.search.aggregations.metrics.max.Max) Collectors.toSet(java.util.stream.Collectors.toSet) SearchHit(org.elasticsearch.search.SearchHit) SearchType(org.elasticsearch.action.search.SearchType) ImmutableSet(com.google.common.collect.ImmutableSet) Min(org.elasticsearch.search.aggregations.metrics.min.Min) ImmutableMap(com.google.common.collect.ImmutableMap) Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms) GetAliasesRequest(org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest) Collection(java.util.Collection) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) AliasMetaData(org.elasticsearch.cluster.metadata.AliasMetaData) Set(java.util.Set) FilterAggregationBuilder(org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) DeleteIndexTemplateRequest(org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest) Filter(org.elasticsearch.search.aggregations.bucket.filter.Filter) List(java.util.List) AuditActor(org.graylog2.audit.AuditActor) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ClusterStateRequest(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest) Optional(java.util.Optional) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) HashMap(java.util.HashMap) SearchRequest(org.elasticsearch.action.search.SearchRequest) Singleton(javax.inject.Singleton) ActionFuture(org.elasticsearch.action.ActionFuture) OpenIndexRequest(org.elasticsearch.action.admin.indices.open.OpenIndexRequest) UpdateSettingsRequest(org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest) ForceMergeRequest(org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest) XContentHelper(org.elasticsearch.common.xcontent.XContentHelper) Inject(javax.inject.Inject) IndicesStatsResponse(org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse) GetIndexRequestBuilder(org.elasticsearch.action.admin.indices.get.GetIndexRequestBuilder) ImmutableList(com.google.common.collect.ImmutableList) NodeId(org.graylog2.plugin.system.NodeId) ShardStats(org.elasticsearch.action.admin.indices.stats.ShardStats) CreateIndexRequest(org.elasticsearch.action.admin.indices.create.CreateIndexRequest) TimeValue(org.elasticsearch.common.unit.TimeValue) ES_INDEX_CREATE(org.graylog2.audit.AuditEventTypes.ES_INDEX_CREATE) GetIndexResponse(org.elasticsearch.action.admin.indices.get.GetIndexResponse) Duration(com.github.joschi.jadconfig.util.Duration) Messages(org.graylog2.indexer.messages.Messages) AuditEventSender(org.graylog2.audit.AuditEventSender) Nullable(javax.annotation.Nullable) DeleteIndexRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest) Logger(org.slf4j.Logger) QueryBuilders.matchAllQuery(org.elasticsearch.index.query.QueryBuilders.matchAllQuery) GetIndexRequest(org.elasticsearch.action.admin.indices.get.GetIndexRequest) IndexNotFoundException(org.graylog2.indexer.IndexNotFoundException) Client(org.elasticsearch.client.Client) DateTime(org.joda.time.DateTime) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) AggregationBuilders(org.elasticsearch.search.aggregations.AggregationBuilders) IOException(java.io.IOException) Maps(com.google.common.collect.Maps) IndicesAdminClient(org.elasticsearch.client.IndicesAdminClient) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) TimeUnit(java.util.concurrent.TimeUnit) CloseIndexRequest(org.elasticsearch.action.admin.indices.close.CloseIndexRequest) IndicesExistsResponse(org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse) FlushRequest(org.elasticsearch.action.admin.indices.flush.FlushRequest) DocsStats(org.elasticsearch.index.shard.DocsStats) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SortParseElement(org.elasticsearch.search.sort.SortParseElement) UnmodifiableIterator(com.google.common.collect.UnmodifiableIterator) ClusterHealthStatus(org.elasticsearch.cluster.health.ClusterHealthStatus) Collections(java.util.Collections) IndicesExistsRequest(org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 8 with Cluster

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

the class CountsTest method setUp.

@Before
public void setUp() throws Exception {
    final Map<String, Object> settings = ImmutableMap.of("number_of_shards", 1, "index.number_of_replicas", 0);
    final CreateIndexResponse createIndexResponse1 = client.admin().indices().prepareCreate(INDEX_NAME_1).setSettings(settings).setTimeout(TimeValue.timeValueSeconds(10L)).execute().get();
    assumeTrue(createIndexResponse1.isAcknowledged());
    final CreateIndexResponse createIndexResponse2 = client.admin().indices().prepareCreate(INDEX_NAME_2).setSettings(settings).setTimeout(TimeValue.timeValueSeconds(10L)).execute().get();
    assumeTrue(createIndexResponse2.isAcknowledged());
    final ClusterHealthResponse clusterHealthResponse1 = client.admin().cluster().prepareHealth(INDEX_NAME_1).setWaitForGreenStatus().execute().get();
    assumeTrue(clusterHealthResponse1.getStatus() == ClusterHealthStatus.GREEN);
    final ClusterHealthResponse clusterHealthResponse2 = client.admin().cluster().prepareHealth(INDEX_NAME_2).setWaitForGreenStatus().execute().get();
    assumeTrue(clusterHealthResponse2.getStatus() == ClusterHealthStatus.GREEN);
    counts = new Counts(client, indexSetRegistry);
    indexSetConfig1 = IndexSetConfig.builder().id("id-1").title("title-1").indexPrefix("index_set_1_counts_test").shards(1).replicas(0).rotationStrategyClass(MessageCountRotationStrategy.class.getCanonicalName()).rotationStrategy(MessageCountRotationStrategyConfig.createDefault()).retentionStrategyClass(DeletionRetentionStrategy.class.getCanonicalName()).retentionStrategy(DeletionRetentionStrategyConfig.createDefault()).creationDate(ZonedDateTime.of(2016, 10, 12, 0, 0, 0, 0, ZoneOffset.UTC)).indexAnalyzer("standard").indexTemplateName("template-1").indexOptimizationMaxNumSegments(1).indexOptimizationDisabled(false).build();
    indexSetConfig2 = IndexSetConfig.builder().id("id-2").title("title-2").indexPrefix("index_set_2_counts_test").shards(1).replicas(0).rotationStrategyClass(MessageCountRotationStrategy.class.getCanonicalName()).rotationStrategy(MessageCountRotationStrategyConfig.createDefault()).retentionStrategyClass(DeletionRetentionStrategy.class.getCanonicalName()).retentionStrategy(DeletionRetentionStrategyConfig.createDefault()).creationDate(ZonedDateTime.of(2016, 10, 13, 0, 0, 0, 0, ZoneOffset.UTC)).indexAnalyzer("standard").indexTemplateName("template-2").indexOptimizationMaxNumSegments(1).indexOptimizationDisabled(false).build();
    when(indexSetRegistry.getManagedIndices()).thenReturn(new String[] { INDEX_NAME_1, INDEX_NAME_2 });
    when(indexSetRegistry.get(indexSetConfig1.id())).thenReturn(Optional.of(indexSet1));
    when(indexSetRegistry.get(indexSetConfig2.id())).thenReturn(Optional.of(indexSet2));
    when(indexSet1.getManagedIndices()).thenReturn(new String[] { INDEX_NAME_1 });
    when(indexSet2.getManagedIndices()).thenReturn(new String[] { INDEX_NAME_2 });
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) MessageCountRotationStrategy(org.graylog2.indexer.rotation.strategies.MessageCountRotationStrategy) DeletionRetentionStrategy(org.graylog2.indexer.retention.strategies.DeletionRetentionStrategy) CreateIndexResponse(org.elasticsearch.action.admin.indices.create.CreateIndexResponse) Before(org.junit.Before)

Example 9 with Cluster

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

the class ClusterResource method nodes.

@GET
@Timed
@Path("/nodes")
@ApiOperation(value = "List all active nodes in this cluster.")
public NodeSummaryList nodes() {
    final Map<String, Node> nodes = nodeService.allActive(Node.Type.SERVER);
    final List<NodeSummary> nodeList = new ArrayList<>(nodes.size());
    for (Node node : nodes.values()) {
        nodeList.add(nodeSummary(node));
    }
    return NodeSummaryList.create(nodeList);
}
Also used : NodeSummary(org.graylog2.rest.models.system.cluster.responses.NodeSummary) Node(org.graylog2.cluster.Node) ArrayList(java.util.ArrayList) Path(javax.ws.rs.Path) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 10 with Cluster

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

the class IndexerSetupService method startUp.

@Override
protected void startUp() throws Exception {
    Tools.silenceUncaughtExceptionsInThisThread();
    LOG.debug("Starting indexer");
    node.start();
    final Client client = node.client();
    try {
        /* try to determine the cluster health. if this times out we could not connect and try to determine if there's
                   anything listening at all. if that happens this usually has these reasons:
                    1. cluster.name is different
                    2. network.publish_host is not reachable
                    3. wrong address configured
                    4. multicast in use but broken in this environment
                   we handle a red cluster state differently because if we can get that result it means the cluster itself
                   is reachable, which is a completely different problem from not being able to join at all.
                 */
        final ClusterHealthRequest atLeastRed = client.admin().cluster().prepareHealth().setWaitForStatus(ClusterHealthStatus.RED).request();
        final ClusterHealthResponse health = client.admin().cluster().health(atLeastRed).actionGet(configuration.getClusterDiscoveryTimeout(), MILLISECONDS);
        // we don't get here if we couldn't join the cluster. just check for red cluster state
        if (ClusterHealthStatus.RED.equals(health.getStatus())) {
            final Notification notification = notificationService.buildNow().addSeverity(Notification.Severity.URGENT).addType(Notification.Type.ES_CLUSTER_RED);
            notificationService.publishIfFirst(notification);
            LOG.warn("The Elasticsearch cluster state is RED which means shards are unassigned.");
            LOG.info("This usually indicates a crashed and corrupt cluster and needs to be investigated. Graylog will write into the local disk journal.");
            LOG.info("See {} for details.", DocsHelper.PAGE_ES_CONFIGURATION);
        }
        if (ClusterHealthStatus.GREEN.equals(health.getStatus())) {
            notificationService.fixed(Notification.Type.ES_CLUSTER_RED);
        }
        notificationService.fixed(Notification.Type.ES_UNAVAILABLE);
    } catch (ElasticsearchTimeoutException e) {
        final String hosts = node.settings().get("discovery.zen.ping.unicast.hosts");
        if (!isNullOrEmpty(hosts)) {
            final Iterable<String> hostList = Splitter.on(',').omitEmptyStrings().trimResults().split(hosts);
            for (String host : hostList) {
                final URI esUri = URI.create("http://" + HostAndPort.fromString(host).getHostText() + ":9200/");
                LOG.info("Checking Elasticsearch HTTP API at {}", esUri);
                // Try the HTTP API endpoint
                final Request request = new Request.Builder().get().url(esUri.resolve("/_nodes").toString()).build();
                try (final Response response = httpClient.newCall(request).execute()) {
                    if (response.isSuccessful()) {
                        final JsonNode resultTree = objectMapper.readTree(response.body().byteStream());
                        final JsonNode nodesList = resultTree.get("nodes");
                        if (!configuration.isDisableVersionCheck()) {
                            final Iterator<String> nodes = nodesList.fieldNames();
                            while (nodes.hasNext()) {
                                final String id = nodes.next();
                                final Version clusterVersion = Version.fromString(nodesList.get(id).get("version").textValue());
                                checkClusterVersion(clusterVersion);
                            }
                        }
                        final String clusterName = resultTree.get("cluster_name").textValue();
                        checkClusterName(clusterName);
                    } else {
                        LOG.error("Could not connect to Elasticsearch at " + esUri + ". Is it running?");
                    }
                } catch (IOException ioException) {
                    LOG.error("Could not connect to Elasticsearch: {}", ioException.getMessage());
                }
            }
        }
        final Notification notification = notificationService.buildNow().addSeverity(Notification.Severity.URGENT).addType(Notification.Type.ES_UNAVAILABLE);
        notificationService.publishIfFirst(notification);
        LOG.warn("Could not connect to Elasticsearch");
        LOG.info("If you're using multicast, check that it is working in your network and that Elasticsearch is accessible. Also check that the cluster name setting is correct.");
        LOG.info("See {} for details.", DocsHelper.PAGE_ES_CONFIGURATION);
    }
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Request(okhttp3.Request) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) URI(java.net.URI) Notification(org.graylog2.notifications.Notification) Response(okhttp3.Response) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) Version(org.elasticsearch.Version) Iterator(java.util.Iterator) Client(org.elasticsearch.client.Client) OkHttpClient(okhttp3.OkHttpClient)

Aggregations

IndexSet (org.graylog2.indexer.IndexSet)5 IOException (java.io.IOException)4 ClusterHealthResponse (org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse)4 Notification (org.graylog2.notifications.Notification)4 Test (org.junit.Test)4 Timed (com.codahale.metrics.annotation.Timed)3 ApiOperation (io.swagger.annotations.ApiOperation)3 Map (java.util.Map)3 Set (java.util.Set)3 Path (javax.ws.rs.Path)3 IndexSetConfig (org.graylog2.indexer.indexset.IndexSetConfig)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 HashMap (java.util.HashMap)2 Collectors (java.util.stream.Collectors)2 Collectors.toSet (java.util.stream.Collectors.toSet)2 Inject (javax.inject.Inject)2 GET (javax.ws.rs.GET)2 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)2 ElasticsearchException (org.elasticsearch.ElasticsearchException)2