Search in sources :

Example 76 with IndexMetadata

use of org.elasticsearch.cluster.metadata.IndexMetadata in project elasticsearch by elastic.

the class NodeJoinControllerTests method testElectionBasedOnConflictingNodes.

/**
     * Tests tha node can become a master, even though the last cluster state it knows contains
     * nodes that conflict with the joins it got and needs to become a master
     */
public void testElectionBasedOnConflictingNodes() throws InterruptedException, ExecutionException {
    final DiscoveryNode masterNode = clusterService.localNode();
    final DiscoveryNode otherNode = new DiscoveryNode("other_node", buildNewFakeTransportAddress(), emptyMap(), EnumSet.allOf(DiscoveryNode.Role.class), Version.CURRENT);
    // simulate master going down with stale nodes in it's cluster state (for example when min master nodes is set to 2)
    // also add some shards to that node
    DiscoveryNodes.Builder discoBuilder = DiscoveryNodes.builder(clusterService.state().nodes());
    discoBuilder.masterNodeId(null);
    discoBuilder.add(otherNode);
    ClusterState.Builder stateBuilder = ClusterState.builder(clusterService.state()).nodes(discoBuilder);
    if (randomBoolean()) {
        IndexMetaData indexMetaData = IndexMetaData.builder("test").settings(Settings.builder().put(SETTING_VERSION_CREATED, Version.CURRENT).put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 1).put(SETTING_CREATION_DATE, System.currentTimeMillis())).build();
        IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(indexMetaData.getIndex());
        RoutingTable.Builder routing = new RoutingTable.Builder();
        routing.addAsNew(indexMetaData);
        final ShardId shardId = new ShardId("test", "_na_", 0);
        IndexShardRoutingTable.Builder indexShardRoutingBuilder = new IndexShardRoutingTable.Builder(shardId);
        final DiscoveryNode primaryNode = randomBoolean() ? masterNode : otherNode;
        final DiscoveryNode replicaNode = primaryNode.equals(masterNode) ? otherNode : masterNode;
        final boolean primaryStarted = randomBoolean();
        indexShardRoutingBuilder.addShard(TestShardRouting.newShardRouting("test", 0, primaryNode.getId(), null, true, primaryStarted ? ShardRoutingState.STARTED : ShardRoutingState.INITIALIZING, primaryStarted ? null : new UnassignedInfo(UnassignedInfo.Reason.INDEX_REOPENED, "getting there")));
        if (primaryStarted) {
            boolean replicaStared = randomBoolean();
            indexShardRoutingBuilder.addShard(TestShardRouting.newShardRouting("test", 0, replicaNode.getId(), null, false, replicaStared ? ShardRoutingState.STARTED : ShardRoutingState.INITIALIZING, replicaStared ? null : new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, "getting there")));
        } else {
            indexShardRoutingBuilder.addShard(TestShardRouting.newShardRouting("test", 0, null, null, false, ShardRoutingState.UNASSIGNED, new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, "life sucks")));
        }
        indexRoutingTableBuilder.addIndexShard(indexShardRoutingBuilder.build());
        IndexRoutingTable indexRoutingTable = indexRoutingTableBuilder.build();
        IndexMetaData updatedIndexMetaData = updateActiveAllocations(indexRoutingTable, indexMetaData);
        stateBuilder.metaData(MetaData.builder().put(updatedIndexMetaData, false).generateClusterUuidIfNeeded()).routingTable(RoutingTable.builder().add(indexRoutingTable).build());
    }
    setState(clusterService, stateBuilder.build());
    // conflict on node id or address
    final DiscoveryNode conflictingNode = randomBoolean() ? new DiscoveryNode(otherNode.getId(), randomBoolean() ? otherNode.getAddress() : buildNewFakeTransportAddress(), otherNode.getAttributes(), otherNode.getRoles(), Version.CURRENT) : new DiscoveryNode("conflicting_address_node", otherNode.getAddress(), otherNode.getAttributes(), otherNode.getRoles(), Version.CURRENT);
    nodeJoinController.startElectionContext();
    final SimpleFuture joinFuture = joinNodeAsync(conflictingNode);
    final CountDownLatch elected = new CountDownLatch(1);
    nodeJoinController.waitToBeElectedAsMaster(1, TimeValue.timeValueHours(5), new NodeJoinController.ElectionCallback() {

        @Override
        public void onElectedAsMaster(ClusterState state) {
            elected.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            logger.error("failed to be elected as master", t);
            throw new AssertionError("failed to be elected as master", t);
        }
    });
    elected.await();
    // throw any exception
    joinFuture.get();
    final ClusterState finalState = clusterService.state();
    final DiscoveryNodes finalNodes = finalState.nodes();
    assertTrue(finalNodes.isLocalNodeElectedMaster());
    assertThat(finalNodes.getLocalNode(), equalTo(masterNode));
    assertThat(finalNodes.getSize(), equalTo(2));
    assertThat(finalNodes.get(conflictingNode.getId()), equalTo(conflictingNode));
    List<ShardRouting> activeShardsOnRestartedNode = StreamSupport.stream(finalState.getRoutingNodes().node(conflictingNode.getId()).spliterator(), false).filter(ShardRouting::active).collect(Collectors.toList());
    assertThat(activeShardsOnRestartedNode, empty());
}
Also used : IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) UnassignedInfo(org.elasticsearch.cluster.routing.UnassignedInfo) ShardId(org.elasticsearch.index.shard.ShardId) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) ClusterState(org.elasticsearch.cluster.ClusterState) CountDownLatch(java.util.concurrent.CountDownLatch) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 77 with IndexMetadata

use of org.elasticsearch.cluster.metadata.IndexMetadata in project elasticsearch by elastic.

the class ZenDiscoveryUnitTests method testValidateOnUnsupportedIndexVersionCreated.

public void testValidateOnUnsupportedIndexVersionCreated() throws Exception {
    final int iters = randomIntBetween(3, 10);
    for (int i = 0; i < iters; i++) {
        ClusterState.Builder stateBuilder = ClusterState.builder(ClusterName.DEFAULT);
        final DiscoveryNode otherNode = new DiscoveryNode("other_node", buildNewFakeTransportAddress(), emptyMap(), EnumSet.allOf(DiscoveryNode.Role.class), Version.CURRENT);
        MembershipAction.ValidateJoinRequestRequestHandler request = new MembershipAction.ValidateJoinRequestRequestHandler();
        final boolean incompatible = randomBoolean();
        IndexMetaData indexMetaData = IndexMetaData.builder("test").settings(Settings.builder().put(SETTING_VERSION_CREATED, incompatible ? VersionUtils.getPreviousVersion(Version.CURRENT.minimumIndexCompatibilityVersion()) : VersionUtils.randomVersionBetween(random(), Version.CURRENT.minimumIndexCompatibilityVersion(), Version.CURRENT)).put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 0).put(SETTING_CREATION_DATE, System.currentTimeMillis())).state(IndexMetaData.State.OPEN).build();
        IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(indexMetaData.getIndex());
        RoutingTable.Builder routing = new RoutingTable.Builder();
        routing.addAsNew(indexMetaData);
        final ShardId shardId = new ShardId("test", "_na_", 0);
        IndexShardRoutingTable.Builder indexShardRoutingBuilder = new IndexShardRoutingTable.Builder(shardId);
        final DiscoveryNode primaryNode = otherNode;
        indexShardRoutingBuilder.addShard(TestShardRouting.newShardRouting("test", 0, primaryNode.getId(), null, true, ShardRoutingState.INITIALIZING, new UnassignedInfo(UnassignedInfo.Reason.INDEX_REOPENED, "getting there")));
        indexRoutingTableBuilder.addIndexShard(indexShardRoutingBuilder.build());
        IndexRoutingTable indexRoutingTable = indexRoutingTableBuilder.build();
        IndexMetaData updatedIndexMetaData = updateActiveAllocations(indexRoutingTable, indexMetaData);
        stateBuilder.metaData(MetaData.builder().put(updatedIndexMetaData, false).generateClusterUuidIfNeeded()).routingTable(RoutingTable.builder().add(indexRoutingTable).build());
        if (incompatible) {
            IllegalStateException ex = expectThrows(IllegalStateException.class, () -> request.messageReceived(new MembershipAction.ValidateJoinRequest(stateBuilder.build()), null));
            assertEquals("index [test] version not supported: " + VersionUtils.getPreviousVersion(Version.CURRENT.minimumCompatibilityVersion()) + " minimum compatible index version is: " + Version.CURRENT.minimumCompatibilityVersion(), ex.getMessage());
        } else {
            AtomicBoolean sendResponse = new AtomicBoolean(false);
            request.messageReceived(new MembershipAction.ValidateJoinRequest(stateBuilder.build()), new TransportChannel() {

                @Override
                public String action() {
                    return null;
                }

                @Override
                public String getProfileName() {
                    return null;
                }

                @Override
                public long getRequestId() {
                    return 0;
                }

                @Override
                public String getChannelType() {
                    return null;
                }

                @Override
                public void sendResponse(TransportResponse response) throws IOException {
                    sendResponse.set(true);
                }

                @Override
                public void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException {
                }

                @Override
                public void sendResponse(Exception exception) throws IOException {
                }
            });
            assertTrue(sendResponse.get());
        }
    }
}
Also used : IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) UnassignedInfo(org.elasticsearch.cluster.routing.UnassignedInfo) Matchers.containsString(org.hamcrest.Matchers.containsString) TransportResponse(org.elasticsearch.transport.TransportResponse) ShardId(org.elasticsearch.index.shard.ShardId) TransportChannel(org.elasticsearch.transport.TransportChannel) ClusterState(org.elasticsearch.cluster.ClusterState) ZenDiscovery.shouldIgnoreOrRejectNewClusterState(org.elasticsearch.discovery.zen.ZenDiscovery.shouldIgnoreOrRejectNewClusterState) IOException(java.io.IOException) IOException(java.io.IOException) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Role(org.elasticsearch.cluster.node.DiscoveryNode.Role) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) TransportResponseOptions(org.elasticsearch.transport.TransportResponseOptions)

Example 78 with IndexMetadata

use of org.elasticsearch.cluster.metadata.IndexMetadata in project elasticsearch by elastic.

the class IndexServiceTests method testRescheduleAsyncFsync.

public void testRescheduleAsyncFsync() throws Exception {
    Settings settings = Settings.builder().put(IndexSettings.INDEX_TRANSLOG_SYNC_INTERVAL_SETTING.getKey(), // very often :)
    "100ms").put(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING.getKey(), Translog.Durability.REQUEST).build();
    IndexService indexService = createIndex("test", settings);
    ensureGreen("test");
    assertNull(indexService.getFsyncTask());
    IndexMetaData metaData = IndexMetaData.builder(indexService.getMetaData()).settings(Settings.builder().put(indexService.getMetaData().getSettings()).put(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING.getKey(), Translog.Durability.ASYNC)).build();
    indexService.updateMetaData(metaData);
    assertNotNull(indexService.getFsyncTask());
    assertTrue(indexService.getRefreshTask().mustReschedule());
    client().prepareIndex("test", "test", "1").setSource("{\"foo\": \"bar\"}", XContentType.JSON).get();
    IndexShard shard = indexService.getShard(0);
    assertBusy(() -> {
        assertFalse(shard.getTranslog().syncNeeded());
    });
    metaData = IndexMetaData.builder(indexService.getMetaData()).settings(Settings.builder().put(indexService.getMetaData().getSettings()).put(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING.getKey(), Translog.Durability.REQUEST)).build();
    indexService.updateMetaData(metaData);
    assertNull(indexService.getFsyncTask());
    metaData = IndexMetaData.builder(indexService.getMetaData()).settings(Settings.builder().put(indexService.getMetaData().getSettings()).put(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING.getKey(), Translog.Durability.ASYNC)).build();
    indexService.updateMetaData(metaData);
    assertNotNull(indexService.getFsyncTask());
}
Also used : IndexShard(org.elasticsearch.index.shard.IndexShard) Settings(org.elasticsearch.common.settings.Settings) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 79 with IndexMetadata

use of org.elasticsearch.cluster.metadata.IndexMetadata in project elasticsearch by elastic.

the class IndexServiceTests method testRefreshActuallyWorks.

public void testRefreshActuallyWorks() throws Exception {
    IndexService indexService = createIndex("test", Settings.EMPTY);
    ensureGreen("test");
    IndexService.AsyncRefreshTask refreshTask = indexService.getRefreshTask();
    assertEquals(1000, refreshTask.getInterval().millis());
    assertTrue(indexService.getRefreshTask().mustReschedule());
    // now disable
    IndexMetaData metaData = IndexMetaData.builder(indexService.getMetaData()).settings(Settings.builder().put(indexService.getMetaData().getSettings()).put(IndexSettings.INDEX_REFRESH_INTERVAL_SETTING.getKey(), -1)).build();
    indexService.updateMetaData(metaData);
    client().prepareIndex("test", "test", "1").setSource("{\"foo\": \"bar\"}", XContentType.JSON).get();
    IndexShard shard = indexService.getShard(0);
    try (Engine.Searcher searcher = shard.acquireSearcher("test")) {
        TopDocs search = searcher.searcher().search(new MatchAllDocsQuery(), 10);
        assertEquals(0, search.totalHits);
    }
    // refresh every millisecond
    metaData = IndexMetaData.builder(indexService.getMetaData()).settings(Settings.builder().put(indexService.getMetaData().getSettings()).put(IndexSettings.INDEX_REFRESH_INTERVAL_SETTING.getKey(), "1ms")).build();
    indexService.updateMetaData(metaData);
    assertBusy(() -> {
        try (Engine.Searcher searcher = shard.acquireSearcher("test")) {
            TopDocs search = searcher.searcher().search(new MatchAllDocsQuery(), 10);
            assertEquals(1, search.totalHits);
        } catch (IOException e) {
            fail(e.getMessage());
        }
    });
}
Also used : TopDocs(org.apache.lucene.search.TopDocs) IndexShard(org.elasticsearch.index.shard.IndexShard) IOException(java.io.IOException) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) Engine(org.elasticsearch.index.engine.Engine) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 80 with IndexMetadata

use of org.elasticsearch.cluster.metadata.IndexMetadata in project elasticsearch by elastic.

the class RecoveryFromGatewayIT method assertAndCapturePrimaryTerms.

private Map<String, long[]> assertAndCapturePrimaryTerms(Map<String, long[]> previousTerms) {
    if (previousTerms == null) {
        previousTerms = new HashMap<>();
    }
    final Map<String, long[]> result = new HashMap<>();
    final ClusterState state = client().admin().cluster().prepareState().get().getState();
    for (ObjectCursor<IndexMetaData> cursor : state.metaData().indices().values()) {
        final IndexMetaData indexMetaData = cursor.value;
        final String index = indexMetaData.getIndex().getName();
        final long[] previous = previousTerms.get(index);
        final long[] current = IntStream.range(0, indexMetaData.getNumberOfShards()).mapToLong(indexMetaData::primaryTerm).toArray();
        if (previous == null) {
            result.put(index, current);
        } else {
            assertThat("number of terms changed for index [" + index + "]", current.length, equalTo(previous.length));
            for (int shard = 0; shard < current.length; shard++) {
                assertThat("primary term didn't increase for [" + index + "][" + shard + "]", current[shard], greaterThan(previous[shard]));
            }
            result.put(index, current);
        }
    }
    return result;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) HashMap(java.util.HashMap) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Aggregations

IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)253 IndexMetadata (org.elasticsearch.cluster.metadata.IndexMetadata)194 ClusterState (org.elasticsearch.cluster.ClusterState)124 Settings (org.elasticsearch.common.settings.Settings)104 Index (org.elasticsearch.index.Index)100 Test (org.junit.Test)90 ShardId (org.elasticsearch.index.shard.ShardId)71 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)68 IOException (java.io.IOException)65 Metadata (org.elasticsearch.cluster.metadata.Metadata)62 IndexSettings (org.elasticsearch.index.IndexSettings)62 RoutingTable (org.elasticsearch.cluster.routing.RoutingTable)60 MetaData (org.elasticsearch.cluster.metadata.MetaData)58 HashSet (java.util.HashSet)56 HashMap (java.util.HashMap)54 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)54 Map (java.util.Map)50 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)49 ArrayList (java.util.ArrayList)47 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)44