Search in sources :

Example 1 with IndexShardState

use of org.elasticsearch.index.shard.IndexShardState in project crate by crate.

the class IndicesClusterStateService method updateShard.

private void updateShard(DiscoveryNodes nodes, ShardRouting shardRouting, Shard shard, RoutingTable routingTable, ClusterState clusterState) {
    final ShardRouting currentRoutingEntry = shard.routingEntry();
    assert currentRoutingEntry.isSameAllocation(shardRouting) : "local shard has a different allocation id but wasn't cleaned by removeShards. " + "cluster state: " + shardRouting + " local: " + currentRoutingEntry;
    final long primaryTerm;
    try {
        final IndexMetadata indexMetadata = clusterState.metadata().index(shard.shardId().getIndex());
        primaryTerm = indexMetadata.primaryTerm(shard.shardId().id());
        final Set<String> inSyncIds = indexMetadata.inSyncAllocationIds(shard.shardId().id());
        final IndexShardRoutingTable indexShardRoutingTable = routingTable.shardRoutingTable(shardRouting.shardId());
        shard.updateShardState(shardRouting, primaryTerm, primaryReplicaSyncer::resync, clusterState.version(), inSyncIds, indexShardRoutingTable);
    } catch (Exception e) {
        failAndRemoveShard(shardRouting, true, "failed updating shard routing entry", e, clusterState);
        return;
    }
    final IndexShardState state = shard.state();
    if (shardRouting.initializing() && (state == IndexShardState.STARTED || state == IndexShardState.POST_RECOVERY)) {
        // we managed to tell the master we started), mark us as started
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("{} master marked shard as initializing, but shard has state [{}], resending shard started to {}", shardRouting.shardId(), state, nodes.getMasterNode());
        }
        if (nodes.getMasterNode() != null) {
            shardStateAction.shardStarted(shardRouting, primaryTerm, "master " + nodes.getMasterNode() + " marked shard as initializing, but shard state is [" + state + "], mark shard as started", SHARD_STATE_ACTION_LISTENER, clusterState);
        }
    }
}
Also used : IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) IndexShardState(org.elasticsearch.index.shard.IndexShardState) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) IndexShardClosedException(org.elasticsearch.index.shard.IndexShardClosedException) IndexShardRelocatedException(org.elasticsearch.index.shard.IndexShardRelocatedException) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) IOException(java.io.IOException)

Example 2 with IndexShardState

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

the class IndicesClusterStateService method updateShard.

private void updateShard(DiscoveryNodes nodes, ShardRouting shardRouting, Shard shard, RoutingTable routingTable, ClusterState clusterState) {
    final ShardRouting currentRoutingEntry = shard.routingEntry();
    assert currentRoutingEntry.isSameAllocation(shardRouting) : "local shard has a different allocation id but wasn't cleaning by removeShards. " + "cluster state: " + shardRouting + " local: " + currentRoutingEntry;
    try {
        shard.updateRoutingEntry(shardRouting);
        if (shardRouting.primary()) {
            IndexShardRoutingTable indexShardRoutingTable = routingTable.shardRoutingTable(shardRouting.shardId());
            Set<String> activeIds = indexShardRoutingTable.activeShards().stream().filter(sr -> nodes.get(sr.currentNodeId()).getVersion().onOrAfter(Version.V_6_0_0_alpha1_UNRELEASED)).map(r -> r.allocationId().getId()).collect(Collectors.toSet());
            Set<String> initializingIds = indexShardRoutingTable.getAllInitializingShards().stream().filter(sr -> nodes.get(sr.currentNodeId()).getVersion().onOrAfter(Version.V_6_0_0_alpha1_UNRELEASED)).map(r -> r.allocationId().getId()).collect(Collectors.toSet());
            shard.updateAllocationIdsFromMaster(activeIds, initializingIds);
        }
    } catch (Exception e) {
        failAndRemoveShard(shardRouting, true, "failed updating shard routing entry", e, clusterState);
        return;
    }
    final IndexShardState state = shard.state();
    if (shardRouting.initializing() && (state == IndexShardState.STARTED || state == IndexShardState.POST_RECOVERY)) {
        // we managed to tell the master we started), mark us as started
        if (logger.isTraceEnabled()) {
            logger.trace("{} master marked shard as initializing, but shard has state [{}], resending shard started to {}", shardRouting.shardId(), state, nodes.getMasterNode());
        }
        if (nodes.getMasterNode() != null) {
            shardStateAction.shardStarted(shardRouting, "master " + nodes.getMasterNode() + " marked shard as initializing, but shard state is [" + state + "], mark shard as started", SHARD_STATE_ACTION_LISTENER, clusterState);
        }
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) Arrays(java.util.Arrays) CLOSED(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.CLOSED) Nullable(org.elasticsearch.common.Nullable) FAILURE(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.FAILURE) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) SearchService(org.elasticsearch.search.SearchService) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) Type(org.elasticsearch.cluster.routing.RecoverySource.Type) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) Map(java.util.Map) SyncedFlushService(org.elasticsearch.indices.flush.SyncedFlushService) ThreadPool(org.elasticsearch.threadpool.ThreadPool) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) Set(java.util.Set) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) ClusterChangedEvent(org.elasticsearch.cluster.ClusterChangedEvent) Collectors(java.util.stream.Collectors) NodeMappingRefreshAction(org.elasticsearch.cluster.action.index.NodeMappingRefreshAction) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) SnapshotShardsService(org.elasticsearch.snapshots.SnapshotShardsService) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Version(org.elasticsearch.Version) IndexComponent(org.elasticsearch.index.IndexComponent) Supplier(org.apache.logging.log4j.util.Supplier) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) NO_LONGER_ASSIGNED(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.NO_LONGER_ASSIGNED) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Callback(org.elasticsearch.common.util.Callback) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) ClusterService(org.elasticsearch.cluster.service.ClusterService) IndexShardRelocatedException(org.elasticsearch.index.shard.IndexShardRelocatedException) PeerRecoverySourceService(org.elasticsearch.indices.recovery.PeerRecoverySourceService) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) GlobalCheckpointSyncAction(org.elasticsearch.index.seqno.GlobalCheckpointSyncAction) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) TimeValue(org.elasticsearch.common.unit.TimeValue) IndexSettings(org.elasticsearch.index.IndexSettings) IndicesService(org.elasticsearch.indices.IndicesService) ClusterStateApplier(org.elasticsearch.cluster.ClusterStateApplier) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) IndexShardState(org.elasticsearch.index.shard.IndexShardState) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) Iterator(java.util.Iterator) DELETED(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.DELETED) IndexService(org.elasticsearch.index.IndexService) GlobalCheckpointTracker(org.elasticsearch.index.seqno.GlobalCheckpointTracker) IndexShard(org.elasticsearch.index.shard.IndexShard) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) IOException(java.io.IOException) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) AbstractLifecycleComponent(org.elasticsearch.common.component.AbstractLifecycleComponent) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) GatewayService(org.elasticsearch.gateway.GatewayService) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) IndexShardState(org.elasticsearch.index.shard.IndexShardState) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) IndexShardRelocatedException(org.elasticsearch.index.shard.IndexShardRelocatedException) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) IOException(java.io.IOException)

Example 3 with IndexShardState

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

the class RelocationIT method testRelocationWhileRefreshing.

@TestLogging("org.elasticsearch.action.bulk:TRACE,org.elasticsearch.action.search:TRACE")
public void testRelocationWhileRefreshing() throws Exception {
    int numberOfRelocations = scaledRandomIntBetween(1, rarely() ? 10 : 4);
    int numberOfReplicas = randomBoolean() ? 0 : 1;
    int numberOfNodes = numberOfReplicas == 0 ? 2 : 3;
    logger.info("testRelocationWhileIndexingRandom(numRelocations={}, numberOfReplicas={}, numberOfNodes={})", numberOfRelocations, numberOfReplicas, numberOfNodes);
    String[] nodes = new String[numberOfNodes];
    logger.info("--> starting [node_0] ...");
    nodes[0] = internalCluster().startNode();
    logger.info("--> creating test index ...");
    prepareCreate("test", Settings.builder().put("index.number_of_shards", 1).put("index.number_of_replicas", numberOfReplicas).put("index.refresh_interval", // we want to control refreshes c
    -1)).get();
    for (int i = 1; i < numberOfNodes; i++) {
        logger.info("--> starting [node_{}] ...", i);
        nodes[i] = internalCluster().startNode();
        if (i != numberOfNodes - 1) {
            ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForNodes(Integer.toString(i + 1)).setWaitForGreenStatus().execute().actionGet();
            assertThat(healthResponse.isTimedOut(), equalTo(false));
        }
    }
    final Semaphore postRecoveryShards = new Semaphore(0);
    final IndexEventListener listener = new IndexEventListener() {

        @Override
        public void indexShardStateChanged(IndexShard indexShard, @Nullable IndexShardState previousState, IndexShardState currentState, @Nullable String reason) {
            if (currentState == IndexShardState.POST_RECOVERY) {
                postRecoveryShards.release();
            }
        }
    };
    for (MockIndexEventListener.TestEventListener eventListener : internalCluster().getInstances(MockIndexEventListener.TestEventListener.class)) {
        eventListener.setNewDelegate(listener);
    }
    logger.info("--> starting relocations...");
    // if we have replicas shift those
    int nodeShiftBased = numberOfReplicas;
    for (int i = 0; i < numberOfRelocations; i++) {
        int fromNode = (i % 2);
        int toNode = fromNode == 0 ? 1 : 0;
        fromNode += nodeShiftBased;
        toNode += nodeShiftBased;
        List<IndexRequestBuilder> builders1 = new ArrayList<>();
        for (int numDocs = randomIntBetween(10, 30); numDocs > 0; numDocs--) {
            builders1.add(client().prepareIndex("test", "type").setSource("{}", XContentType.JSON));
        }
        List<IndexRequestBuilder> builders2 = new ArrayList<>();
        for (int numDocs = randomIntBetween(10, 30); numDocs > 0; numDocs--) {
            builders2.add(client().prepareIndex("test", "type").setSource("{}", XContentType.JSON));
        }
        logger.info("--> START relocate the shard from {} to {}", nodes[fromNode], nodes[toNode]);
        client().admin().cluster().prepareReroute().add(new MoveAllocationCommand("test", 0, nodes[fromNode], nodes[toNode])).get();
        logger.debug("--> index [{}] documents", builders1.size());
        indexRandom(false, true, builders1);
        // wait for shard to reach post recovery
        postRecoveryShards.acquire(1);
        logger.debug("--> index [{}] documents", builders2.size());
        indexRandom(true, true, builders2);
        // verify cluster was finished.
        assertFalse(client().admin().cluster().prepareHealth().setWaitForNoRelocatingShards(true).setWaitForEvents(Priority.LANGUID).setTimeout("30s").get().isTimedOut());
        logger.info("--> DONE relocate the shard from {} to {}", fromNode, toNode);
        logger.debug("--> verifying all searches return the same number of docs");
        long expectedCount = -1;
        for (Client client : clients()) {
            SearchResponse response = client.prepareSearch("test").setPreference("_local").setSize(0).get();
            assertNoFailures(response);
            if (expectedCount < 0) {
                expectedCount = response.getHits().getTotalHits();
            } else {
                assertEquals(expectedCount, response.getHits().getTotalHits());
            }
        }
    }
}
Also used : MockIndexEventListener(org.elasticsearch.test.MockIndexEventListener) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) IndexShard(org.elasticsearch.index.shard.IndexShard) ArrayList(java.util.ArrayList) MoveAllocationCommand(org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand) Semaphore(java.util.concurrent.Semaphore) SearchResponse(org.elasticsearch.action.search.SearchResponse) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) MockIndexEventListener(org.elasticsearch.test.MockIndexEventListener) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) Client(org.elasticsearch.client.Client) IndexShardState(org.elasticsearch.index.shard.IndexShardState) Nullable(org.elasticsearch.common.Nullable) TestLogging(org.elasticsearch.test.junit.annotations.TestLogging)

Example 4 with IndexShardState

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

the class ExceptionSerializationTests method testIllegalIndexShardStateException.

public void testIllegalIndexShardStateException() throws IOException {
    ShardId id = new ShardId("foo", "_na_", 1);
    IndexShardState state = randomFrom(IndexShardState.values());
    IllegalIndexShardStateException ex = serialize(new IllegalIndexShardStateException(id, state, "come back later buddy"));
    assertEquals(id, ex.getShardId());
    assertEquals("CurrentState[" + state.name() + "] come back later buddy", ex.getMessage());
    assertEquals(state, ex.currentState());
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) IndexShardState(org.elasticsearch.index.shard.IndexShardState)

Example 5 with IndexShardState

use of org.elasticsearch.index.shard.IndexShardState in project crate by crate.

the class SnapshotShardsService method snapshot.

/**
 * Creates shard snapshot
 *
 * @param snapshot       snapshot
 * @param snapshotStatus snapshot status
 */
private void snapshot(final ShardId shardId, final Snapshot snapshot, final IndexId indexId, final IndexShardSnapshotStatus snapshotStatus, boolean writeShardGens, ActionListener<String> listener) {
    try {
        final IndexShard indexShard = indicesService.indexServiceSafe(shardId.getIndex()).getShardOrNull(shardId.id());
        if (indexShard.routingEntry().primary() == false) {
            throw new IndexShardSnapshotFailedException(shardId, "snapshot should be performed only on primary");
        }
        if (indexShard.routingEntry().relocating()) {
            // do not snapshot when in the process of relocation of primaries so we won't get conflicts
            throw new IndexShardSnapshotFailedException(shardId, "cannot snapshot while relocating");
        }
        final IndexShardState indexShardState = indexShard.state();
        if (indexShardState == IndexShardState.CREATED || indexShardState == IndexShardState.RECOVERING) {
            // shard has just been created, or still recovering
            throw new IndexShardSnapshotFailedException(shardId, "shard didn't fully recover yet");
        }
        final Repository repository = repositoriesService.repository(snapshot.getRepository());
        Engine.IndexCommitRef snapshotRef = null;
        try {
            // we flush first to make sure we get the latest writes snapshotted
            snapshotRef = indexShard.acquireLastIndexCommit(true);
            repository.snapshotShard(indexShard.store(), indexShard.mapperService(), snapshot.getSnapshotId(), indexId, snapshotRef.getIndexCommit(), snapshotStatus, writeShardGens, ActionListener.runBefore(listener, snapshotRef::close));
        } catch (Exception e) {
            IOUtils.close(snapshotRef);
            throw e;
        }
    } catch (Exception e) {
        listener.onFailure(e);
    }
}
Also used : Repository(org.elasticsearch.repositories.Repository) IndexShard(org.elasticsearch.index.shard.IndexShard) IndexShardSnapshotFailedException(org.elasticsearch.index.snapshots.IndexShardSnapshotFailedException) IndexShardState(org.elasticsearch.index.shard.IndexShardState) Engine(org.elasticsearch.index.engine.Engine) IndexShardSnapshotFailedException(org.elasticsearch.index.snapshots.IndexShardSnapshotFailedException) TransportException(org.elasticsearch.transport.TransportException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) IOException(java.io.IOException)

Aggregations

IndexShardState (org.elasticsearch.index.shard.IndexShardState)5 IOException (java.io.IOException)3 IndexShard (org.elasticsearch.index.shard.IndexShard)3 ArrayList (java.util.ArrayList)2 ResourceAlreadyExistsException (org.elasticsearch.ResourceAlreadyExistsException)2 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)2 Nullable (org.elasticsearch.common.Nullable)2 IndexEventListener (org.elasticsearch.index.shard.IndexEventListener)2 ShardId (org.elasticsearch.index.shard.ShardId)2 Arrays (java.util.Arrays)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1 Semaphore (java.util.concurrent.Semaphore)1 TimeUnit (java.util.concurrent.TimeUnit)1 Consumer (java.util.function.Consumer)1