Search in sources :

Example 1 with IndexService

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

the class SyncedFlushService method performInFlightOps.

private InFlightOpsResponse performInFlightOps(InFlightOpsRequest request) {
    IndexService indexService = indicesService.indexServiceSafe(request.shardId().getIndex());
    IndexShard indexShard = indexService.getShard(request.shardId().id());
    if (indexShard.routingEntry().primary() == false) {
        throw new IllegalStateException("[" + request.shardId() + "] expected a primary shard");
    }
    int opCount = indexShard.getActiveOperationsCount();
    logger.trace("{} in flight operations sampled at [{}]", request.shardId(), opCount);
    return new InFlightOpsResponse(opCount);
}
Also used : IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard)

Example 2 with IndexService

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

the class TransportNodesListShardStoreMetaData method listStoreMetaData.

private StoreFilesMetaData listStoreMetaData(ShardId shardId) throws IOException {
    logger.trace("listing store meta data for {}", shardId);
    long startTimeNS = System.nanoTime();
    boolean exists = false;
    try {
        IndexService indexService = indicesService.indexService(shardId.getIndex());
        if (indexService != null) {
            IndexShard indexShard = indexService.getShardOrNull(shardId.id());
            if (indexShard != null) {
                exists = true;
                return new StoreFilesMetaData(shardId, indexShard.snapshotStoreMetadata());
            }
        }
        // try and see if we an list unallocated
        IndexMetaData metaData = clusterService.state().metaData().index(shardId.getIndex());
        if (metaData == null) {
            // we may send this requests while processing the cluster state that recovered the index
            // sometimes the request comes in before the local node processed that cluster state
            // in such cases we can load it from disk
            metaData = IndexMetaData.FORMAT.loadLatestState(logger, NamedXContentRegistry.EMPTY, nodeEnv.indexPaths(shardId.getIndex()));
        }
        if (metaData == null) {
            logger.trace("{} node doesn't have meta data for the requests index, responding with empty", shardId);
            return new StoreFilesMetaData(shardId, Store.MetadataSnapshot.EMPTY);
        }
        final IndexSettings indexSettings = indexService != null ? indexService.getIndexSettings() : new IndexSettings(metaData, settings);
        final ShardPath shardPath = ShardPath.loadShardPath(logger, nodeEnv, shardId, indexSettings);
        if (shardPath == null) {
            return new StoreFilesMetaData(shardId, Store.MetadataSnapshot.EMPTY);
        }
        //    reuse local resources.
        return new StoreFilesMetaData(shardId, Store.readMetadataSnapshot(shardPath.resolveIndex(), shardId, nodeEnv::shardLock, logger));
    } finally {
        TimeValue took = new TimeValue(System.nanoTime() - startTimeNS, TimeUnit.NANOSECONDS);
        if (exists) {
            logger.debug("{} loaded store meta data (took [{}])", shardId, took);
        } else {
            logger.trace("{} didn't find any store meta data to load (took [{}])", shardId, took);
        }
    }
}
Also used : IndexService(org.elasticsearch.index.IndexService) ShardPath(org.elasticsearch.index.shard.ShardPath) IndexShard(org.elasticsearch.index.shard.IndexShard) IndexSettings(org.elasticsearch.index.IndexSettings) TimeValue(org.elasticsearch.common.unit.TimeValue) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 3 with IndexService

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

the class SyncedFlushSingleNodeTests method testModificationPreventsFlushing.

public void testModificationPreventsFlushing() 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());
    client().prepareIndex("test", "test", "2").setSource("{}", XContentType.JSON).get();
    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("pending operations", syncedFlushResult.shardResponses().get(activeShards.get(0)).failureReason());
    // pull another commit and make sure we can't sync-flush with the old one
    SyncedFlushUtil.sendPreSyncRequests(flushService, activeShards, state, shardId);
    listener = new SyncedFlushUtil.LatchedListener();
    flushService.sendSyncRequests(syncId, activeShards, state, commitIds, shardId, shardRoutingTable.size(), listener);
    listener.latch.await();
    assertNull(listener.error);
    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 4 with IndexService

use of org.elasticsearch.index.IndexService 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 5 with IndexService

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

the class RecoveryStatusTests method testRenameTempFiles.

public void testRenameTempFiles() throws IOException {
    IndexService service = createIndex("foo");
    IndexShard indexShard = service.getShardOrNull(0);
    DiscoveryNode node = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
    RecoveryTarget status = new RecoveryTarget(indexShard, node, new PeerRecoveryTargetService.RecoveryListener() {

        @Override
        public void onRecoveryDone(RecoveryState state) {
        }

        @Override
        public void onRecoveryFailure(RecoveryState state, RecoveryFailedException e, boolean sendShardFailure) {
        }
    }, version -> {
    });
    try (IndexOutput indexOutput = status.openAndPutIndexOutput("foo.bar", new StoreFileMetaData("foo.bar", 8 + CodecUtil.footerLength(), "9z51nw"), status.store())) {
        indexOutput.writeInt(1);
        IndexOutput openIndexOutput = status.getOpenIndexOutput("foo.bar");
        assertSame(openIndexOutput, indexOutput);
        openIndexOutput.writeInt(1);
        CodecUtil.writeFooter(indexOutput);
    }
    try {
        status.openAndPutIndexOutput("foo.bar", new StoreFileMetaData("foo.bar", 8 + CodecUtil.footerLength(), "9z51nw"), status.store());
        fail("file foo.bar is already opened and registered");
    } catch (IllegalStateException ex) {
        assertEquals("output for file [foo.bar] has already been created", ex.getMessage());
    // all well = it's already registered
    }
    status.removeOpenIndexOutputs("foo.bar");
    Set<String> strings = Sets.newHashSet(status.store().directory().listAll());
    String expectedFile = null;
    for (String file : strings) {
        if (Pattern.compile("recovery[.][\\w-]+[.]foo[.]bar").matcher(file).matches()) {
            expectedFile = file;
            break;
        }
    }
    assertNotNull(expectedFile);
    // we have to close it here otherwise rename fails since the write.lock is held by the engine
    indexShard.close("foo", false);
    status.renameAllTempFiles();
    strings = Sets.newHashSet(status.store().directory().listAll());
    assertTrue(strings.toString(), strings.contains("foo.bar"));
    assertFalse(strings.toString(), strings.contains(expectedFile));
    // we must fail the recovery because marking it as done will try to move the shard to POST_RECOVERY, which will fail because it's started
    status.fail(new RecoveryFailedException(status.state(), "end of test. OK.", null), false);
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IndexOutput(org.apache.lucene.store.IndexOutput) StoreFileMetaData(org.elasticsearch.index.store.StoreFileMetaData)

Aggregations

IndexService (org.elasticsearch.index.IndexService)212 IndexShard (org.elasticsearch.index.shard.IndexShard)77 IndicesService (org.elasticsearch.indices.IndicesService)56 CompressedXContent (org.elasticsearch.common.compress.CompressedXContent)50 ShardId (org.elasticsearch.index.shard.ShardId)38 Index (org.elasticsearch.index.Index)36 DocumentMapper (org.elasticsearch.index.mapper.DocumentMapper)33 Settings (org.elasticsearch.common.settings.Settings)31 IOException (java.io.IOException)22 ArrayList (java.util.ArrayList)22 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)22 HashMap (java.util.HashMap)21 Map (java.util.Map)19 ClusterService (org.elasticsearch.cluster.service.ClusterService)19 QueryShardContext (org.elasticsearch.index.query.QueryShardContext)18 ElasticsearchException (org.elasticsearch.ElasticsearchException)17 ClusterState (org.elasticsearch.cluster.ClusterState)16 List (java.util.List)14 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)13 IndexSettings (org.elasticsearch.index.IndexSettings)13