Search in sources :

Example 31 with ShardRouting

use of org.elasticsearch.cluster.routing.ShardRouting in project elasticsearch by elastic.

the class AbstractIndicesClusterStateServiceTestCase method assertClusterStateMatchesNodeState.

/**
     * Checks if cluster state matches internal state of IndicesClusterStateService instance
     *
     * @param state cluster state used for matching
     */
public void assertClusterStateMatchesNodeState(ClusterState state, IndicesClusterStateService indicesClusterStateService) {
    MockIndicesService indicesService = (MockIndicesService) indicesClusterStateService.indicesService;
    ConcurrentMap<ShardId, ShardRouting> failedShardsCache = indicesClusterStateService.failedShardsCache;
    RoutingNode localRoutingNode = state.getRoutingNodes().node(state.getNodes().getLocalNodeId());
    if (localRoutingNode != null) {
        if (enableRandomFailures == false) {
            assertThat("failed shard cache should be empty", failedShardsCache.values(), empty());
        }
        // check that all shards in local routing nodes have been allocated
        for (ShardRouting shardRouting : localRoutingNode) {
            Index index = shardRouting.index();
            IndexMetaData indexMetaData = state.metaData().getIndexSafe(index);
            MockIndexShard shard = indicesService.getShardOrNull(shardRouting.shardId());
            ShardRouting failedShard = failedShardsCache.get(shardRouting.shardId());
            if (enableRandomFailures) {
                if (shard == null && failedShard == null) {
                    fail("Shard with id " + shardRouting + " expected but missing in indicesService and failedShardsCache");
                }
                if (failedShard != null && failedShard.isSameAllocation(shardRouting) == false) {
                    fail("Shard cache has not been properly cleaned for " + failedShard);
                }
            } else {
                if (shard == null) {
                    fail("Shard with id " + shardRouting + " expected but missing in indicesService");
                }
            }
            if (shard != null) {
                AllocatedIndex<? extends Shard> indexService = indicesService.indexService(index);
                assertTrue("Index " + index + " expected but missing in indicesService", indexService != null);
                // index metadata has been updated
                assertThat(indexService.getIndexSettings().getIndexMetaData(), equalTo(indexMetaData));
                // shard has been created
                if (enableRandomFailures == false || failedShard == null) {
                    assertTrue("Shard with id " + shardRouting + " expected but missing in indexService", shard != null);
                    // shard has latest shard routing
                    assertThat(shard.routingEntry(), equalTo(shardRouting));
                }
                if (shard.routingEntry().primary() && shard.routingEntry().active()) {
                    IndexShardRoutingTable shardRoutingTable = state.routingTable().shardRoutingTable(shard.shardId());
                    Set<String> activeIds = shardRoutingTable.activeShards().stream().map(r -> r.allocationId().getId()).collect(Collectors.toSet());
                    Set<String> initializingIds = shardRoutingTable.getAllInitializingShards().stream().map(r -> r.allocationId().getId()).collect(Collectors.toSet());
                    assertThat(shard.routingEntry() + " isn't updated with active aIDs", shard.activeAllocationIds, equalTo(activeIds));
                    assertThat(shard.routingEntry() + " isn't updated with init aIDs", shard.initializingAllocationIds, equalTo(initializingIds));
                }
            }
        }
    }
    // all other shards / indices have been cleaned up
    for (AllocatedIndex<? extends Shard> indexService : indicesService) {
        assertTrue(state.metaData().getIndexSafe(indexService.index()) != null);
        boolean shardsFound = false;
        for (Shard shard : indexService) {
            shardsFound = true;
            ShardRouting persistedShardRouting = shard.routingEntry();
            ShardRouting shardRouting = localRoutingNode.getByShardId(persistedShardRouting.shardId());
            if (shardRouting == null) {
                fail("Shard with id " + persistedShardRouting + " locally exists but missing in routing table");
            }
            if (shardRouting.equals(persistedShardRouting) == false) {
                fail("Local shard " + persistedShardRouting + " has stale routing" + shardRouting);
            }
        }
        if (shardsFound == false) {
            if (enableRandomFailures) {
                // check if we have shards of that index in failedShardsCache
                // if yes, we might not have cleaned the index as failedShardsCache can be populated by another thread
                assertFalse(failedShardsCache.keySet().stream().noneMatch(shardId -> shardId.getIndex().equals(indexService.index())));
            } else {
                fail("index service for index " + indexService.index() + " has no shards");
            }
        }
    }
}
Also used : ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) ShardId(org.elasticsearch.index.shard.ShardId) Callback(org.elasticsearch.common.util.Callback) Shard(org.elasticsearch.indices.cluster.IndicesClusterStateService.Shard) Nullable(org.elasticsearch.common.Nullable) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) ConcurrentMap(java.util.concurrent.ConcurrentMap) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) TimeValue(org.elasticsearch.common.unit.TimeValue) Map(java.util.Map) IndexSettings(org.elasticsearch.index.IndexSettings) IndicesService(org.elasticsearch.indices.IndicesService) ESTestCase(org.elasticsearch.test.ESTestCase) Before(org.junit.Before) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.empty(org.hamcrest.Matchers.empty) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) IndexShardState(org.elasticsearch.index.shard.IndexShardState) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) Iterator(java.util.Iterator) AllocatedIndex(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndex) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) Set(java.util.Set) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IOException(java.io.IOException) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) Collectors(java.util.stream.Collectors) MapBuilder.newMapBuilder(org.elasticsearch.common.collect.MapBuilder.newMapBuilder) Consumer(java.util.function.Consumer) List(java.util.List) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) AllocatedIndices(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) Index(org.elasticsearch.index.Index) AllocatedIndex(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndex) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ShardId(org.elasticsearch.index.shard.ShardId) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Shard(org.elasticsearch.indices.cluster.IndicesClusterStateService.Shard) IndexShard(org.elasticsearch.index.shard.IndexShard)

Example 32 with ShardRouting

use of org.elasticsearch.cluster.routing.ShardRouting in project elasticsearch by elastic.

the class SyncedFlushSingleNodeTests method testFailAfterIntermediateCommit.

public void testFailAfterIntermediateCommit() throws InterruptedException {
    createIndex("test");
    client().prepareIndex("test", "test", "1").setSource("{}", XContentType.JSON).get();
    IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test"));
    IndexShard shard = test.getShardOrNull(0);
    SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class);
    final ShardId shardId = shard.shardId();
    final ClusterState state = getInstanceFromNode(ClusterService.class).state();
    final IndexShardRoutingTable shardRoutingTable = flushService.getShardRoutingTable(shardId, state);
    final List<ShardRouting> activeShards = shardRoutingTable.activeShards();
    assertEquals("exactly one active shard", 1, activeShards.size());
    Map<String, Engine.CommitId> commitIds = SyncedFlushUtil.sendPreSyncRequests(flushService, activeShards, state, shardId);
    assertEquals("exactly one commit id", 1, commitIds.size());
    if (randomBoolean()) {
        client().prepareIndex("test", "test", "2").setSource("{}", XContentType.JSON).get();
    }
    client().admin().indices().prepareFlush("test").setForce(true).get();
    String syncId = UUIDs.base64UUID();
    final SyncedFlushUtil.LatchedListener<ShardsSyncedFlushResult> listener = new SyncedFlushUtil.LatchedListener();
    flushService.sendSyncRequests(syncId, activeShards, state, commitIds, shardId, shardRoutingTable.size(), listener);
    listener.latch.await();
    assertNull(listener.error);
    ShardsSyncedFlushResult syncedFlushResult = listener.result;
    assertNotNull(syncedFlushResult);
    assertEquals(0, syncedFlushResult.successfulShards());
    assertEquals(1, syncedFlushResult.totalShards());
    assertEquals(syncId, syncedFlushResult.syncId());
    assertNotNull(syncedFlushResult.shardResponses().get(activeShards.get(0)));
    assertFalse(syncedFlushResult.shardResponses().get(activeShards.get(0)).success());
    assertEquals("commit has changed", syncedFlushResult.shardResponses().get(activeShards.get(0)).failureReason());
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IndicesService(org.elasticsearch.indices.IndicesService) ShardId(org.elasticsearch.index.shard.ShardId) ClusterService(org.elasticsearch.cluster.service.ClusterService) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 33 with ShardRouting

use of org.elasticsearch.cluster.routing.ShardRouting in project elasticsearch by elastic.

the class SyncedFlushSingleNodeTests method testFailWhenCommitIsMissing.

public void testFailWhenCommitIsMissing() throws InterruptedException {
    createIndex("test");
    client().prepareIndex("test", "test", "1").setSource("{}", XContentType.JSON).get();
    IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test"));
    IndexShard shard = test.getShardOrNull(0);
    SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class);
    final ShardId shardId = shard.shardId();
    final ClusterState state = getInstanceFromNode(ClusterService.class).state();
    final IndexShardRoutingTable shardRoutingTable = flushService.getShardRoutingTable(shardId, state);
    final List<ShardRouting> activeShards = shardRoutingTable.activeShards();
    assertEquals("exactly one active shard", 1, activeShards.size());
    Map<String, Engine.CommitId> commitIds = SyncedFlushUtil.sendPreSyncRequests(flushService, activeShards, state, shardId);
    assertEquals("exactly one commit id", 1, commitIds.size());
    // wipe it...
    commitIds.clear();
    String syncId = UUIDs.base64UUID();
    SyncedFlushUtil.LatchedListener<ShardsSyncedFlushResult> listener = new SyncedFlushUtil.LatchedListener();
    flushService.sendSyncRequests(syncId, activeShards, state, commitIds, shardId, shardRoutingTable.size(), listener);
    listener.latch.await();
    assertNull(listener.error);
    ShardsSyncedFlushResult syncedFlushResult = listener.result;
    assertNotNull(syncedFlushResult);
    assertEquals(0, syncedFlushResult.successfulShards());
    assertEquals(1, syncedFlushResult.totalShards());
    assertEquals(syncId, syncedFlushResult.syncId());
    assertNotNull(syncedFlushResult.shardResponses().get(activeShards.get(0)));
    assertFalse(syncedFlushResult.shardResponses().get(activeShards.get(0)).success());
    assertEquals("no commit id from pre-sync flush", syncedFlushResult.shardResponses().get(activeShards.get(0)).failureReason());
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IndicesService(org.elasticsearch.indices.IndicesService) ShardId(org.elasticsearch.index.shard.ShardId) ClusterService(org.elasticsearch.cluster.service.ClusterService) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 34 with ShardRouting

use of org.elasticsearch.cluster.routing.ShardRouting in project elasticsearch by elastic.

the class RestIndicesActionTests method randomIndicesStatsResponse.

private IndicesStatsResponse randomIndicesStatsResponse(final Index[] indices) {
    List<ShardStats> shardStats = new ArrayList<>();
    for (final Index index : indices) {
        for (int i = 0; i < 2; i++) {
            ShardId shardId = new ShardId(index, i);
            Path path = createTempDir().resolve("indices").resolve(index.getUUID()).resolve(String.valueOf(i));
            ShardRouting shardRouting = ShardRouting.newUnassigned(shardId, i == 0, i == 0 ? StoreRecoverySource.EMPTY_STORE_INSTANCE : PeerRecoverySource.INSTANCE, new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, null));
            shardRouting = shardRouting.initialize("node-0", null, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE);
            shardRouting = shardRouting.moveToStarted();
            CommonStats stats = new CommonStats();
            stats.fieldData = new FieldDataStats();
            stats.queryCache = new QueryCacheStats();
            stats.docs = new DocsStats();
            stats.store = new StoreStats();
            stats.indexing = new IndexingStats();
            stats.search = new SearchStats();
            stats.segments = new SegmentsStats();
            stats.merge = new MergeStats();
            stats.refresh = new RefreshStats();
            stats.completion = new CompletionStats();
            stats.requestCache = new RequestCacheStats();
            stats.get = new GetStats();
            stats.flush = new FlushStats();
            stats.warmer = new WarmerStats();
            shardStats.add(new ShardStats(shardRouting, new ShardPath(false, path, path, shardId), stats, null, null));
        }
    }
    return IndicesStatsTests.newIndicesStatsResponse(shardStats.toArray(new ShardStats[shardStats.size()]), shardStats.size(), shardStats.size(), 0, emptyList());
}
Also used : StoreStats(org.elasticsearch.index.store.StoreStats) UnassignedInfo(org.elasticsearch.cluster.routing.UnassignedInfo) RefreshStats(org.elasticsearch.index.refresh.RefreshStats) ArrayList(java.util.ArrayList) Index(org.elasticsearch.index.Index) GetStats(org.elasticsearch.index.get.GetStats) SegmentsStats(org.elasticsearch.index.engine.SegmentsStats) ShardId(org.elasticsearch.index.shard.ShardId) CommonStats(org.elasticsearch.action.admin.indices.stats.CommonStats) FlushStats(org.elasticsearch.index.flush.FlushStats) ShardPath(org.elasticsearch.index.shard.ShardPath) QueryCacheStats(org.elasticsearch.index.cache.query.QueryCacheStats) DocsStats(org.elasticsearch.index.shard.DocsStats) FieldDataStats(org.elasticsearch.index.fielddata.FieldDataStats) ShardStats(org.elasticsearch.action.admin.indices.stats.ShardStats) Path(java.nio.file.Path) ShardPath(org.elasticsearch.index.shard.ShardPath) IndexingStats(org.elasticsearch.index.shard.IndexingStats) WarmerStats(org.elasticsearch.index.warmer.WarmerStats) SearchStats(org.elasticsearch.index.search.stats.SearchStats) MergeStats(org.elasticsearch.index.merge.MergeStats) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) RequestCacheStats(org.elasticsearch.index.cache.request.RequestCacheStats) CompletionStats(org.elasticsearch.search.suggest.completion.CompletionStats)

Example 35 with ShardRouting

use of org.elasticsearch.cluster.routing.ShardRouting in project elasticsearch by elastic.

the class SyncedFlushResponse method toXContent.

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(Fields._SHARDS);
    shardCounts.toXContent(builder, params);
    builder.endObject();
    for (Map.Entry<String, List<ShardsSyncedFlushResult>> indexEntry : shardsResultPerIndex.entrySet()) {
        List<ShardsSyncedFlushResult> indexResult = indexEntry.getValue();
        builder.startObject(indexEntry.getKey());
        ShardCounts indexShardCounts = calculateShardCounts(indexResult);
        indexShardCounts.toXContent(builder, params);
        if (indexShardCounts.failed > 0) {
            builder.startArray(Fields.FAILURES);
            for (ShardsSyncedFlushResult shardResults : indexResult) {
                if (shardResults.failed()) {
                    builder.startObject();
                    builder.field(Fields.SHARD, shardResults.shardId().id());
                    builder.field(Fields.REASON, shardResults.failureReason());
                    builder.endObject();
                    continue;
                }
                Map<ShardRouting, SyncedFlushService.ShardSyncedFlushResponse> failedShards = shardResults.failedShards();
                for (Map.Entry<ShardRouting, SyncedFlushService.ShardSyncedFlushResponse> shardEntry : failedShards.entrySet()) {
                    builder.startObject();
                    builder.field(Fields.SHARD, shardResults.shardId().id());
                    builder.field(Fields.REASON, shardEntry.getValue().failureReason());
                    builder.field(Fields.ROUTING, shardEntry.getKey());
                    builder.endObject();
                }
            }
            builder.endArray();
        }
        builder.endObject();
    }
    return builder;
}
Also used : ShardsSyncedFlushResult(org.elasticsearch.indices.flush.ShardsSyncedFlushResult) ArrayList(java.util.ArrayList) List(java.util.List) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) HashMap(java.util.HashMap) Map(java.util.Map) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap)

Aggregations

ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)372 ClusterState (org.elasticsearch.cluster.ClusterState)162 ShardId (org.elasticsearch.index.shard.ShardId)104 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)92 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)79 RoutingNode (org.elasticsearch.cluster.routing.RoutingNode)75 TestShardRouting (org.elasticsearch.cluster.routing.TestShardRouting)75 RoutingTable (org.elasticsearch.cluster.routing.RoutingTable)74 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)71 Index (org.elasticsearch.index.Index)50 HashSet (java.util.HashSet)49 UnassignedInfo (org.elasticsearch.cluster.routing.UnassignedInfo)49 ArrayList (java.util.ArrayList)48 IndexShard (org.elasticsearch.index.shard.IndexShard)48 Settings (org.elasticsearch.common.settings.Settings)46 MetaData (org.elasticsearch.cluster.metadata.MetaData)45 IndexRoutingTable (org.elasticsearch.cluster.routing.IndexRoutingTable)44 IOException (java.io.IOException)43 HashMap (java.util.HashMap)41 RoutingNodes (org.elasticsearch.cluster.routing.RoutingNodes)41