Search in sources :

Example 16 with ShardId

use of org.elasticsearch.index.shard.ShardId in project elasticsearch by elastic.

the class ShardCoreKeyMapTests method testBasics.

public void testBasics() throws IOException {
    Directory dir1 = newDirectory();
    RandomIndexWriter w1 = new RandomIndexWriter(random(), dir1);
    w1.addDocument(new Document());
    Directory dir2 = newDirectory();
    RandomIndexWriter w2 = new RandomIndexWriter(random(), dir2);
    w2.addDocument(new Document());
    Directory dir3 = newDirectory();
    RandomIndexWriter w3 = new RandomIndexWriter(random(), dir3);
    w3.addDocument(new Document());
    ShardId shardId1 = new ShardId("index1", "_na_", 1);
    ShardId shardId2 = new ShardId("index1", "_na_", 3);
    ShardId shardId3 = new ShardId("index2", "_na_", 2);
    ElasticsearchDirectoryReader reader1 = ElasticsearchDirectoryReader.wrap(w1.getReader(), shardId1);
    ElasticsearchDirectoryReader reader2 = ElasticsearchDirectoryReader.wrap(w2.getReader(), shardId2);
    ElasticsearchDirectoryReader reader3 = ElasticsearchDirectoryReader.wrap(w3.getReader(), shardId3);
    ShardCoreKeyMap map = new ShardCoreKeyMap();
    for (DirectoryReader reader : Arrays.asList(reader1, reader2, reader3)) {
        for (LeafReaderContext ctx : reader.leaves()) {
            map.add(ctx.reader());
        }
    }
    assertEquals(3, map.size());
    // Adding them back is a no-op
    for (LeafReaderContext ctx : reader1.leaves()) {
        map.add(ctx.reader());
    }
    assertEquals(3, map.size());
    for (LeafReaderContext ctx : reader2.leaves()) {
        assertEquals(shardId2, map.getShardId(ctx.reader().getCoreCacheKey()));
    }
    w1.addDocument(new Document());
    ElasticsearchDirectoryReader newReader1 = ElasticsearchDirectoryReader.wrap(w1.getReader(), shardId1);
    reader1.close();
    reader1 = newReader1;
    // same for reader2, but with a force merge to trigger evictions
    w2.addDocument(new Document());
    w2.forceMerge(1);
    ElasticsearchDirectoryReader newReader2 = ElasticsearchDirectoryReader.wrap(w2.getReader(), shardId2);
    reader2.close();
    reader2 = newReader2;
    for (DirectoryReader reader : Arrays.asList(reader1, reader2, reader3)) {
        for (LeafReaderContext ctx : reader.leaves()) {
            map.add(ctx.reader());
        }
    }
    final Set<Object> index1Keys = new HashSet<>();
    for (DirectoryReader reader : Arrays.asList(reader1, reader2)) {
        for (LeafReaderContext ctx : reader.leaves()) {
            index1Keys.add(ctx.reader().getCoreCacheKey());
        }
    }
    index1Keys.removeAll(map.getCoreKeysForIndex("index1"));
    assertEquals(Collections.emptySet(), index1Keys);
    reader1.close();
    w1.close();
    reader2.close();
    w2.close();
    reader3.close();
    w3.close();
    assertEquals(0, map.size());
    dir1.close();
    dir2.close();
    dir3.close();
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) ElasticsearchDirectoryReader(org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader) DirectoryReader(org.apache.lucene.index.DirectoryReader) ElasticsearchDirectoryReader(org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) Document(org.apache.lucene.document.Document) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter) Directory(org.apache.lucene.store.Directory) HashSet(java.util.HashSet)

Example 17 with ShardId

use of org.elasticsearch.index.shard.ShardId in project elasticsearch by elastic.

the class VersionsTests method testNestedDocuments.

public void testNestedDocuments() throws IOException {
    Directory dir = newDirectory();
    IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER));
    List<Document> docs = new ArrayList<>();
    for (int i = 0; i < 4; ++i) {
        // Nested
        Document doc = new Document();
        doc.add(new Field(UidFieldMapper.NAME, "1", UidFieldMapper.Defaults.NESTED_FIELD_TYPE));
        docs.add(doc);
    }
    // Root
    Document doc = new Document();
    doc.add(new Field(UidFieldMapper.NAME, "1", UidFieldMapper.Defaults.FIELD_TYPE));
    NumericDocValuesField version = new NumericDocValuesField(VersionFieldMapper.NAME, 5L);
    doc.add(version);
    docs.add(doc);
    writer.updateDocuments(new Term(UidFieldMapper.NAME, "1"), docs);
    DirectoryReader directoryReader = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(writer), new ShardId("foo", "_na_", 1));
    assertThat(Versions.loadVersion(directoryReader, new Term(UidFieldMapper.NAME, "1")), equalTo(5L));
    assertThat(Versions.loadDocIdAndVersion(directoryReader, new Term(UidFieldMapper.NAME, "1")).version, equalTo(5L));
    version.setLongValue(6L);
    writer.updateDocuments(new Term(UidFieldMapper.NAME, "1"), docs);
    version.setLongValue(7L);
    writer.updateDocuments(new Term(UidFieldMapper.NAME, "1"), docs);
    directoryReader = reopen(directoryReader);
    assertThat(Versions.loadVersion(directoryReader, new Term(UidFieldMapper.NAME, "1")), equalTo(7L));
    assertThat(Versions.loadDocIdAndVersion(directoryReader, new Term(UidFieldMapper.NAME, "1")).version, equalTo(7L));
    writer.deleteDocuments(new Term(UidFieldMapper.NAME, "1"));
    directoryReader = reopen(directoryReader);
    assertThat(Versions.loadVersion(directoryReader, new Term(UidFieldMapper.NAME, "1")), equalTo(Versions.NOT_FOUND));
    assertThat(Versions.loadDocIdAndVersion(directoryReader, new Term(UidFieldMapper.NAME, "1")), nullValue());
    directoryReader.close();
    writer.close();
    dir.close();
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) Field(org.apache.lucene.document.Field) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) IndexWriter(org.apache.lucene.index.IndexWriter) DirectoryReader(org.apache.lucene.index.DirectoryReader) ElasticsearchDirectoryReader(org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader) ArrayList(java.util.ArrayList) Term(org.apache.lucene.index.Term) Document(org.apache.lucene.document.Document) Directory(org.apache.lucene.store.Directory) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig)

Example 18 with ShardId

use of org.elasticsearch.index.shard.ShardId in project elasticsearch by elastic.

the class IndexFolderUpgraderTests method writeIndex.

private void writeIndex(NodeEnvironment nodeEnv, IndexSettings indexSettings, int numIdxFiles, int numTranslogFiles) throws IOException {
    NodeEnvironment.NodePath[] nodePaths = nodeEnv.nodePaths();
    Path[] oldIndexPaths = new Path[nodePaths.length];
    for (int i = 0; i < nodePaths.length; i++) {
        oldIndexPaths[i] = nodePaths[i].indicesPath.resolve(indexSettings.getIndex().getName());
    }
    IndexMetaData.FORMAT.write(indexSettings.getIndexMetaData(), oldIndexPaths);
    for (int id = 0; id < indexSettings.getNumberOfShards(); id++) {
        Path oldIndexPath = randomFrom(oldIndexPaths);
        ShardId shardId = new ShardId(indexSettings.getIndex(), id);
        if (indexSettings.hasCustomDataPath()) {
            Path customIndexPath = nodeEnv.resolveBaseCustomLocation(indexSettings).resolve(indexSettings.getIndex().getName());
            writeShard(shardId, customIndexPath, numIdxFiles, numTranslogFiles);
        } else {
            writeShard(shardId, oldIndexPath, numIdxFiles, numTranslogFiles);
        }
        ShardStateMetaData state = new ShardStateMetaData(true, indexSettings.getUUID(), AllocationId.newInitializing());
        ShardStateMetaData.FORMAT.write(state, oldIndexPath.resolve(String.valueOf(shardId.getId())));
    }
}
Also used : Path(java.nio.file.Path) ShardPath(org.elasticsearch.index.shard.ShardPath) ShardId(org.elasticsearch.index.shard.ShardId) ShardStateMetaData(org.elasticsearch.index.shard.ShardStateMetaData)

Example 19 with ShardId

use of org.elasticsearch.index.shard.ShardId 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 20 with ShardId

use of org.elasticsearch.index.shard.ShardId 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)

Aggregations

ShardId (org.elasticsearch.index.shard.ShardId)293 ClusterState (org.elasticsearch.cluster.ClusterState)60 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)60 Index (org.elasticsearch.index.Index)59 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)45 ArrayList (java.util.ArrayList)42 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)41 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)37 HashMap (java.util.HashMap)36 IOException (java.io.IOException)31 UnassignedInfo (org.elasticsearch.cluster.routing.UnassignedInfo)30 Document (org.apache.lucene.document.Document)28 DirectoryReader (org.apache.lucene.index.DirectoryReader)28 Directory (org.apache.lucene.store.Directory)28 PlainActionFuture (org.elasticsearch.action.support.PlainActionFuture)28 Path (java.nio.file.Path)26 Settings (org.elasticsearch.common.settings.Settings)26 IndexWriter (org.apache.lucene.index.IndexWriter)24 ElasticsearchDirectoryReader (org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader)24 IndexShard (org.elasticsearch.index.shard.IndexShard)24