Search in sources :

Example 11 with Index

use of org.elasticsearch.index.Index 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 12 with Index

use of org.elasticsearch.index.Index 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 13 with Index

use of org.elasticsearch.index.Index in project elasticsearch by elastic.

the class RestRecoveryActionTests method testRestRecoveryAction.

public void testRestRecoveryAction() {
    final Settings settings = Settings.EMPTY;
    final RestController restController = new RestController(settings, Collections.emptySet(), null, null, null);
    final RestRecoveryAction action = new RestRecoveryAction(settings, restController);
    final int totalShards = randomIntBetween(1, 32);
    final int successfulShards = Math.max(0, totalShards - randomIntBetween(1, 2));
    final int failedShards = totalShards - successfulShards;
    final boolean detailed = randomBoolean();
    final Map<String, List<RecoveryState>> shardRecoveryStates = new HashMap<>();
    final List<RecoveryState> recoveryStates = new ArrayList<>();
    for (int i = 0; i < successfulShards; i++) {
        final RecoveryState state = mock(RecoveryState.class);
        when(state.getShardId()).thenReturn(new ShardId(new Index("index", "_na_"), i));
        final RecoveryState.Timer timer = mock(RecoveryState.Timer.class);
        when(timer.time()).thenReturn((long) randomIntBetween(1000000, 10 * 1000000));
        when(state.getTimer()).thenReturn(timer);
        when(state.getRecoverySource()).thenReturn(TestShardRouting.randomRecoverySource());
        when(state.getStage()).thenReturn(randomFrom(RecoveryState.Stage.values()));
        final DiscoveryNode sourceNode = randomBoolean() ? mock(DiscoveryNode.class) : null;
        if (sourceNode != null) {
            when(sourceNode.getHostName()).thenReturn(randomAsciiOfLength(8));
        }
        when(state.getSourceNode()).thenReturn(sourceNode);
        final DiscoveryNode targetNode = mock(DiscoveryNode.class);
        when(targetNode.getHostName()).thenReturn(randomAsciiOfLength(8));
        when(state.getTargetNode()).thenReturn(targetNode);
        RecoveryState.Index index = mock(RecoveryState.Index.class);
        final int totalRecoveredFiles = randomIntBetween(1, 64);
        when(index.totalRecoverFiles()).thenReturn(totalRecoveredFiles);
        final int recoveredFileCount = randomIntBetween(0, totalRecoveredFiles);
        when(index.recoveredFileCount()).thenReturn(recoveredFileCount);
        when(index.recoveredFilesPercent()).thenReturn((100f * recoveredFileCount) / totalRecoveredFiles);
        when(index.totalFileCount()).thenReturn(randomIntBetween(totalRecoveredFiles, 2 * totalRecoveredFiles));
        final int totalRecoveredBytes = randomIntBetween(1, 1 << 24);
        when(index.totalRecoverBytes()).thenReturn((long) totalRecoveredBytes);
        final int recoveredBytes = randomIntBetween(0, totalRecoveredBytes);
        when(index.recoveredBytes()).thenReturn((long) recoveredBytes);
        when(index.recoveredBytesPercent()).thenReturn((100f * recoveredBytes) / totalRecoveredBytes);
        when(index.totalRecoverBytes()).thenReturn((long) randomIntBetween(totalRecoveredBytes, 2 * totalRecoveredBytes));
        when(state.getIndex()).thenReturn(index);
        final RecoveryState.Translog translog = mock(RecoveryState.Translog.class);
        final int translogOps = randomIntBetween(0, 1 << 18);
        when(translog.totalOperations()).thenReturn(translogOps);
        final int translogOpsRecovered = randomIntBetween(0, translogOps);
        when(translog.recoveredOperations()).thenReturn(translogOpsRecovered);
        when(translog.recoveredPercent()).thenReturn(translogOps == 0 ? 100f : (100f * translogOpsRecovered / translogOps));
        when(state.getTranslog()).thenReturn(translog);
        recoveryStates.add(state);
    }
    final List<RecoveryState> shuffle = new ArrayList<>(recoveryStates);
    Randomness.shuffle(shuffle);
    shardRecoveryStates.put("index", shuffle);
    final List<ShardOperationFailedException> shardFailures = new ArrayList<>();
    final RecoveryResponse response = new RecoveryResponse(totalShards, successfulShards, failedShards, detailed, shardRecoveryStates, shardFailures);
    final Table table = action.buildRecoveryTable(null, response);
    assertNotNull(table);
    List<Table.Cell> headers = table.getHeaders();
    assertThat(headers.get(0).value, equalTo("index"));
    assertThat(headers.get(1).value, equalTo("shard"));
    assertThat(headers.get(2).value, equalTo("time"));
    assertThat(headers.get(3).value, equalTo("type"));
    assertThat(headers.get(4).value, equalTo("stage"));
    assertThat(headers.get(5).value, equalTo("source_host"));
    assertThat(headers.get(6).value, equalTo("source_node"));
    assertThat(headers.get(7).value, equalTo("target_host"));
    assertThat(headers.get(8).value, equalTo("target_node"));
    assertThat(headers.get(9).value, equalTo("repository"));
    assertThat(headers.get(10).value, equalTo("snapshot"));
    assertThat(headers.get(11).value, equalTo("files"));
    assertThat(headers.get(12).value, equalTo("files_recovered"));
    assertThat(headers.get(13).value, equalTo("files_percent"));
    assertThat(headers.get(14).value, equalTo("files_total"));
    assertThat(headers.get(15).value, equalTo("bytes"));
    assertThat(headers.get(16).value, equalTo("bytes_recovered"));
    assertThat(headers.get(17).value, equalTo("bytes_percent"));
    assertThat(headers.get(18).value, equalTo("bytes_total"));
    assertThat(headers.get(19).value, equalTo("translog_ops"));
    assertThat(headers.get(20).value, equalTo("translog_ops_recovered"));
    assertThat(headers.get(21).value, equalTo("translog_ops_percent"));
    assertThat(table.getRows().size(), equalTo(successfulShards));
    for (int i = 0; i < successfulShards; i++) {
        final RecoveryState state = recoveryStates.get(i);
        List<Table.Cell> cells = table.getRows().get(i);
        assertThat(cells.get(0).value, equalTo("index"));
        assertThat(cells.get(1).value, equalTo(i));
        assertThat(cells.get(2).value, equalTo(new TimeValue(state.getTimer().time())));
        assertThat(cells.get(3).value, equalTo(state.getRecoverySource().getType().name().toLowerCase(Locale.ROOT)));
        assertThat(cells.get(4).value, equalTo(state.getStage().name().toLowerCase(Locale.ROOT)));
        assertThat(cells.get(5).value, equalTo(state.getSourceNode() == null ? "n/a" : state.getSourceNode().getHostName()));
        assertThat(cells.get(6).value, equalTo(state.getSourceNode() == null ? "n/a" : state.getSourceNode().getName()));
        assertThat(cells.get(7).value, equalTo(state.getTargetNode().getHostName()));
        assertThat(cells.get(8).value, equalTo(state.getTargetNode().getName()));
        assertThat(cells.get(9).value, equalTo(state.getRecoverySource() == null || state.getRecoverySource().getType() != RecoverySource.Type.SNAPSHOT ? "n/a" : ((SnapshotRecoverySource) state.getRecoverySource()).snapshot().getRepository()));
        assertThat(cells.get(10).value, equalTo(state.getRecoverySource() == null || state.getRecoverySource().getType() != RecoverySource.Type.SNAPSHOT ? "n/a" : ((SnapshotRecoverySource) state.getRecoverySource()).snapshot().getSnapshotId().getName()));
        assertThat(cells.get(11).value, equalTo(state.getIndex().totalRecoverFiles()));
        assertThat(cells.get(12).value, equalTo(state.getIndex().recoveredFileCount()));
        assertThat(cells.get(13).value, equalTo(percent(state.getIndex().recoveredFilesPercent())));
        assertThat(cells.get(14).value, equalTo(state.getIndex().totalFileCount()));
        assertThat(cells.get(15).value, equalTo(state.getIndex().totalRecoverBytes()));
        assertThat(cells.get(16).value, equalTo(state.getIndex().recoveredBytes()));
        assertThat(cells.get(17).value, equalTo(percent(state.getIndex().recoveredBytesPercent())));
        assertThat(cells.get(18).value, equalTo(state.getIndex().totalBytes()));
        assertThat(cells.get(19).value, equalTo(state.getTranslog().totalOperations()));
        assertThat(cells.get(20).value, equalTo(state.getTranslog().recoveredOperations()));
        assertThat(cells.get(21).value, equalTo(percent(state.getTranslog().recoveredPercent())));
    }
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) RestController(org.elasticsearch.rest.RestController) Index(org.elasticsearch.index.Index) RecoveryResponse(org.elasticsearch.action.admin.indices.recovery.RecoveryResponse) ShardId(org.elasticsearch.index.shard.ShardId) ArrayList(java.util.ArrayList) List(java.util.List) ShardOperationFailedException(org.elasticsearch.action.ShardOperationFailedException) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) Settings(org.elasticsearch.common.settings.Settings) TimeValue(org.elasticsearch.common.unit.TimeValue) Table(org.elasticsearch.common.Table) SnapshotRecoverySource(org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource)

Example 14 with Index

use of org.elasticsearch.index.Index in project elasticsearch by elastic.

the class TransportCloseIndexAction method masterOperation.

@Override
protected void masterOperation(final CloseIndexRequest request, final ClusterState state, final ActionListener<CloseIndexResponse> listener) {
    final Index[] concreteIndices = indexNameExpressionResolver.concreteIndices(state, request);
    CloseIndexClusterStateUpdateRequest updateRequest = new CloseIndexClusterStateUpdateRequest().ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout()).indices(concreteIndices);
    indexStateService.closeIndex(updateRequest, new ActionListener<ClusterStateUpdateResponse>() {

        @Override
        public void onResponse(ClusterStateUpdateResponse response) {
            listener.onResponse(new CloseIndexResponse(response.isAcknowledged()));
        }

        @Override
        public void onFailure(Exception t) {
            logger.debug((Supplier<?>) () -> new ParameterizedMessage("failed to close indices [{}]", (Object) concreteIndices), t);
            listener.onFailure(t);
        }
    });
}
Also used : Index(org.elasticsearch.index.Index) Supplier(org.apache.logging.log4j.util.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ClusterStateUpdateResponse(org.elasticsearch.cluster.ack.ClusterStateUpdateResponse) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException)

Example 15 with Index

use of org.elasticsearch.index.Index in project elasticsearch by elastic.

the class TransportDeleteIndexAction method masterOperation.

@Override
protected void masterOperation(final DeleteIndexRequest request, final ClusterState state, final ActionListener<DeleteIndexResponse> listener) {
    final Set<Index> concreteIndices = new HashSet<>(Arrays.asList(indexNameExpressionResolver.concreteIndices(state, request)));
    if (concreteIndices.isEmpty()) {
        listener.onResponse(new DeleteIndexResponse(true));
        return;
    }
    DeleteIndexClusterStateUpdateRequest deleteRequest = new DeleteIndexClusterStateUpdateRequest().ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout()).indices(concreteIndices.toArray(new Index[concreteIndices.size()]));
    deleteIndexService.deleteIndices(deleteRequest, new ActionListener<ClusterStateUpdateResponse>() {

        @Override
        public void onResponse(ClusterStateUpdateResponse response) {
            listener.onResponse(new DeleteIndexResponse(response.isAcknowledged()));
        }

        @Override
        public void onFailure(Exception t) {
            logger.debug((Supplier<?>) () -> new ParameterizedMessage("failed to delete indices [{}]", concreteIndices), t);
            listener.onFailure(t);
        }
    });
}
Also used : Index(org.elasticsearch.index.Index) Supplier(org.apache.logging.log4j.util.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ClusterStateUpdateResponse(org.elasticsearch.cluster.ack.ClusterStateUpdateResponse) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) HashSet(java.util.HashSet)

Aggregations

Index (org.elasticsearch.index.Index)366 ShardId (org.elasticsearch.index.shard.ShardId)108 Settings (org.elasticsearch.common.settings.Settings)95 ClusterState (org.elasticsearch.cluster.ClusterState)88 ArrayList (java.util.ArrayList)79 IOException (java.io.IOException)74 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)65 IndexMetadata (org.elasticsearch.cluster.metadata.IndexMetadata)65 HashMap (java.util.HashMap)61 Map (java.util.Map)61 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)59 List (java.util.List)56 HashSet (java.util.HashSet)50 Path (java.nio.file.Path)45 IndexSettings (org.elasticsearch.index.IndexSettings)44 IndexService (org.elasticsearch.index.IndexService)43 Set (java.util.Set)40 Metadata (org.elasticsearch.cluster.metadata.Metadata)39 ClusterService (org.elasticsearch.cluster.service.ClusterService)39 ActionListener (org.elasticsearch.action.ActionListener)35