Search in sources :

Example 86 with IndexNotFoundException

use of org.elasticsearch.index.IndexNotFoundException in project crate by crate.

the class ShardCollectSource method getIterators.

private List<CompletableFuture<BatchIterator<Row>>> getIterators(CollectTask collectTask, RoutedCollectPhase collectPhase, boolean requiresScroll, Map<String, IntIndexedContainer> indexShards) {
    Metadata metadata = clusterService.state().metadata();
    List<CompletableFuture<BatchIterator<Row>>> iterators = new ArrayList<>();
    for (Map.Entry<String, IntIndexedContainer> entry : indexShards.entrySet()) {
        String indexName = entry.getKey();
        IndexMetadata indexMD = metadata.index(indexName);
        if (indexMD == null) {
            if (IndexParts.isPartitioned(indexName)) {
                continue;
            }
            throw new IndexNotFoundException(indexName);
        }
        Index index = indexMD.getIndex();
        try {
            indicesService.indexServiceSafe(index);
        } catch (IndexNotFoundException e) {
            if (IndexParts.isPartitioned(indexName)) {
                continue;
            }
            throw e;
        }
        for (IntCursor shardCursor : entry.getValue()) {
            ShardId shardId = new ShardId(index, shardCursor.value);
            try {
                ShardCollectorProvider shardCollectorProvider = getCollectorProviderSafe(shardId);
                CompletableFuture<BatchIterator<Row>> iterator = shardCollectorProvider.getFutureIterator(collectPhase, requiresScroll, collectTask);
                iterators.add(iterator);
            } catch (ShardNotFoundException | IllegalIndexShardStateException e) {
                // and the reader required in the fetchPhase would be missing.
                if (Symbols.containsColumn(collectPhase.toCollect(), DocSysColumns.FETCHID)) {
                    throw e;
                }
                iterators.add(remoteCollectorFactory.createCollector(shardId, collectPhase, collectTask, shardCollectorProviderFactory));
            } catch (IndexNotFoundException e) {
                // Prevent wrapping this to not break retry-detection
                throw e;
            } catch (Throwable t) {
                Exceptions.rethrowRuntimeException(t);
            }
        }
    }
    return iterators;
}
Also used : IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Metadata(org.elasticsearch.cluster.metadata.Metadata) ArrayList(java.util.ArrayList) IntIndexedContainer(com.carrotsearch.hppc.IntIndexedContainer) Index(org.elasticsearch.index.Index) InMemoryBatchIterator(io.crate.data.InMemoryBatchIterator) CompositeBatchIterator(io.crate.data.CompositeBatchIterator) BatchIterator(io.crate.data.BatchIterator) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) ShardId(org.elasticsearch.index.shard.ShardId) CompletableFuture(java.util.concurrent.CompletableFuture) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) IntCursor(com.carrotsearch.hppc.cursors.IntCursor) ShardCollectorProvider(io.crate.execution.engine.collect.ShardCollectorProvider) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Row(io.crate.data.Row) SentinelRow(io.crate.data.SentinelRow) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 87 with IndexNotFoundException

use of org.elasticsearch.index.IndexNotFoundException in project crate by crate.

the class DocTableInfoBuilder method docIndexMetadata.

private DocIndexMetadata docIndexMetadata() {
    DocIndexMetadata docIndexMetadata;
    String templateName = PartitionName.templateName(ident.schema(), ident.name());
    if (metadata.getTemplates().containsKey(templateName)) {
        docIndexMetadata = buildDocIndexMetadataFromTemplate(ident.indexNameOrAlias(), templateName);
        // We need all concrete indices, regardless of their state, for operations such as reopening.
        concreteIndices = indexNameExpressionResolver.concreteIndexNames(state, IndicesOptions.lenientExpandOpen(), ident.indexNameOrAlias());
        // We need all concrete open indices, as closed indices must not appear in the routing.
        concreteOpenIndices = indexNameExpressionResolver.concreteIndexNames(state, IndicesOptions.fromOptions(true, true, true, false, IndicesOptions.strictExpandOpenAndForbidClosed()), ident.indexNameOrAlias());
    } else {
        try {
            concreteIndices = indexNameExpressionResolver.concreteIndexNames(state, IndicesOptions.strictExpandOpen(), ident.indexNameOrAlias());
            concreteOpenIndices = concreteIndices;
            if (concreteIndices.length == 0) {
                // no matching index found
                throw new RelationUnknown(ident);
            }
            docIndexMetadata = buildDocIndexMetadata(concreteIndices[0]);
        } catch (IndexNotFoundException ex) {
            throw new RelationUnknown(ident.fqn(), ex);
        }
    }
    return docIndexMetadata;
}
Also used : RelationUnknown(io.crate.exceptions.RelationUnknown) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException)

Example 88 with IndexNotFoundException

use of org.elasticsearch.index.IndexNotFoundException in project crate by crate.

the class RetryOnFailureResultReceiverTest method testRetryIsInvokedOnIndexNotFoundException.

@Test
public void testRetryIsInvokedOnIndexNotFoundException() throws Exception {
    AtomicInteger numRetries = new AtomicInteger(0);
    BaseResultReceiver resultReceiver = new BaseResultReceiver();
    ClusterState initialState = clusterService.state();
    RetryOnFailureResultReceiver retryOnFailureResultReceiver = new RetryOnFailureResultReceiver(clusterService, initialState, indexName -> true, resultReceiver, UUID.randomUUID(), (newJobId, receiver) -> numRetries.incrementAndGet());
    // Must have a different cluster state then the initial state to trigger a retry
    clusterService.submitStateUpdateTask("dummy", new DummyUpdate());
    assertBusy(() -> assertThat(initialState, Matchers.not(sameInstance(clusterService.state()))));
    retryOnFailureResultReceiver.fail(new IndexNotFoundException("t1"));
    assertThat(numRetries.get(), is(1));
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BaseResultReceiver(io.crate.action.sql.BaseResultReceiver) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Test(org.junit.Test) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest)

Example 89 with IndexNotFoundException

use of org.elasticsearch.index.IndexNotFoundException in project crate by crate.

the class DropTablePlan method executeOrFail.

@Override
public void executeOrFail(DependencyCarrier dependencies, PlannerContext plannerContext, RowConsumer consumer, Row params, SubQueryResults subQueryResults) {
    TableInfo table = dropTable.table();
    DropTableRequest request;
    if (table == null) {
        if (dropTable.maybeCorrupt()) {
            // setting isPartitioned=true should be safe.
            // It will delete a template if it exists, and if there is no template it shouldn't do any harm
            request = new DropTableRequest(dropTable.tableName(), true);
        } else {
            // no-op, table is already gone
            assert dropTable.dropIfExists() : "If table is null, IF EXISTS flag must have been present";
            consumer.accept(InMemoryBatchIterator.of(ROW_ZERO, SENTINEL), null);
            return;
        }
    } else {
        boolean isPartitioned = table instanceof DocTableInfo && ((DocTableInfo) table).isPartitioned();
        request = new DropTableRequest(table.ident(), isPartitioned);
    }
    dependencies.transportDropTableAction().execute(request, new ActionListener<>() {

        @Override
        public void onResponse(AcknowledgedResponse response) {
            if (!response.isAcknowledged() && LOGGER.isWarnEnabled()) {
                if (LOGGER.isWarnEnabled()) {
                    LOGGER.warn("Dropping table {} was not acknowledged. This could lead to inconsistent state.", dropTable.tableName());
                }
            }
            consumer.accept(InMemoryBatchIterator.of(ROW_ONE, SENTINEL), null);
        }

        @Override
        public void onFailure(Exception e) {
            if (dropTable.dropIfExists() && e instanceof IndexNotFoundException) {
                consumer.accept(InMemoryBatchIterator.of(ROW_ZERO, SENTINEL), null);
            } else {
                consumer.accept(null, e);
            }
        }
    });
}
Also used : DocTableInfo(io.crate.metadata.doc.DocTableInfo) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) DocTableInfo(io.crate.metadata.doc.DocTableInfo) TableInfo(io.crate.metadata.table.TableInfo) DropTableRequest(io.crate.execution.ddl.tables.DropTableRequest) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException)

Example 90 with IndexNotFoundException

use of org.elasticsearch.index.IndexNotFoundException in project crate by crate.

the class IndexShard method startRecovery.

public void startRecovery(RecoveryState recoveryState, PeerRecoveryTargetService recoveryTargetService, PeerRecoveryTargetService.RecoveryListener recoveryListener, RepositoriesService repositoriesService, Consumer<MappingMetadata> mappingUpdateConsumer, IndicesService indicesService) {
    // }
    assert recoveryState.getRecoverySource().equals(shardRouting.recoverySource());
    switch(recoveryState.getRecoverySource().getType()) {
        case EMPTY_STORE:
        case EXISTING_STORE:
            executeRecovery("from store", recoveryState, recoveryListener, this::recoverFromStore);
            break;
        case PEER:
            try {
                markAsRecovering("from " + recoveryState.getSourceNode(), recoveryState);
                recoveryTargetService.startRecovery(this, recoveryState.getSourceNode(), recoveryListener);
            } catch (Exception e) {
                failShard("corrupted preexisting index", e);
                recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true);
            }
            break;
        case SNAPSHOT:
            final String repo = ((SnapshotRecoverySource) recoveryState.getRecoverySource()).snapshot().getRepository();
            executeRecovery("from snapshot", recoveryState, recoveryListener, l -> restoreFromRepository(repositoriesService.repository(repo), l));
            break;
        case LOCAL_SHARDS:
            final IndexMetadata indexMetadata = indexSettings().getIndexMetadata();
            final Index resizeSourceIndex = indexMetadata.getResizeSourceIndex();
            final List<IndexShard> startedShards = new ArrayList<>();
            final IndexService sourceIndexService = indicesService.indexService(resizeSourceIndex);
            final Set<ShardId> requiredShards;
            final int numShards;
            if (sourceIndexService != null) {
                requiredShards = IndexMetadata.selectRecoverFromShards(shardId().id(), sourceIndexService.getMetadata(), indexMetadata.getNumberOfShards());
                for (IndexShard shard : sourceIndexService) {
                    if (shard.state() == IndexShardState.STARTED && requiredShards.contains(shard.shardId())) {
                        startedShards.add(shard);
                    }
                }
                numShards = requiredShards.size();
            } else {
                numShards = -1;
                requiredShards = Collections.emptySet();
            }
            if (numShards == startedShards.size()) {
                assert requiredShards.isEmpty() == false;
                executeRecovery("from local shards", recoveryState, recoveryListener, l -> recoverFromLocalShards(mappingUpdateConsumer, startedShards.stream().filter((s) -> requiredShards.contains(s.shardId())).collect(Collectors.toList()), l));
            } else {
                final RuntimeException e;
                if (numShards == -1) {
                    e = new IndexNotFoundException(resizeSourceIndex);
                } else {
                    e = new IllegalStateException("not all required shards of index " + resizeSourceIndex + " are started yet, expected " + numShards + " found " + startedShards.size() + " can't recover shard " + shardId());
                }
                throw e;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown recovery source " + recoveryState.getRecoverySource());
    }
}
Also used : Query(org.apache.lucene.search.Query) UpgradeRequest(org.elasticsearch.action.admin.indices.upgrade.post.UpgradeRequest) LongSupplier(java.util.function.LongSupplier) BigArrays(org.elasticsearch.common.util.BigArrays) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Term(org.apache.lucene.index.Term) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) RecoveryStats(org.elasticsearch.index.recovery.RecoveryStats) ReferenceManager(org.apache.lucene.search.ReferenceManager) SeqNoStats(org.elasticsearch.index.seqno.SeqNoStats) UsageTrackingQueryCachingPolicy(org.apache.lucene.search.UsageTrackingQueryCachingPolicy) EngineConfig(org.elasticsearch.index.engine.EngineConfig) WriteStateException(org.elasticsearch.gateway.WriteStateException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Map(java.util.Map) ObjectLongMap(com.carrotsearch.hppc.ObjectLongMap) QueryCachingPolicy(org.apache.lucene.search.QueryCachingPolicy) CheckedRunnable(org.elasticsearch.common.CheckedRunnable) EnumSet(java.util.EnumSet) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) Set(java.util.Set) StandardCharsets(java.nio.charset.StandardCharsets) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) Booleans(io.crate.common.Booleans) CountDownLatch(java.util.concurrent.CountDownLatch) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) Exceptions(io.crate.exceptions.Exceptions) Logger(org.apache.logging.log4j.Logger) RestStatus(org.elasticsearch.rest.RestStatus) ReplicationTracker(org.elasticsearch.index.seqno.ReplicationTracker) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ThreadInterruptedException(org.apache.lucene.util.ThreadInterruptedException) IndexCommit(org.apache.lucene.index.IndexCommit) StoreStats(org.elasticsearch.index.store.StoreStats) Tuple(io.crate.common.collections.Tuple) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) IndexModule(org.elasticsearch.index.IndexModule) CodecService(org.elasticsearch.index.codec.CodecService) ArrayList(java.util.ArrayList) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) XContentHelper(org.elasticsearch.common.xcontent.XContentHelper) RetentionLease(org.elasticsearch.index.seqno.RetentionLease) RetentionLeases(org.elasticsearch.index.seqno.RetentionLeases) IndexCache(org.elasticsearch.index.cache.IndexCache) Store(org.elasticsearch.index.store.Store) BiConsumer(java.util.function.BiConsumer) StreamSupport(java.util.stream.StreamSupport) IndicesService(org.elasticsearch.indices.IndicesService) TranslogConfig(org.elasticsearch.index.translog.TranslogConfig) Nullable(javax.annotation.Nullable) EngineException(org.elasticsearch.index.engine.EngineException) SourceToParse(org.elasticsearch.index.mapper.SourceToParse) AsyncIOProcessor(org.elasticsearch.common.util.concurrent.AsyncIOProcessor) SequenceNumbers(org.elasticsearch.index.seqno.SequenceNumbers) SetOnce(org.apache.lucene.util.SetOnce) IdFieldMapper(org.elasticsearch.index.mapper.IdFieldMapper) IndexService(org.elasticsearch.index.IndexService) IOUtils(io.crate.common.io.IOUtils) IOException(java.io.IOException) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) Segment(org.elasticsearch.index.engine.Segment) AtomicLong(java.util.concurrent.atomic.AtomicLong) ReplicationResponse(org.elasticsearch.action.support.replication.ReplicationResponse) CounterMetric(org.elasticsearch.common.metrics.CounterMetric) ActionListener(org.elasticsearch.action.ActionListener) ElasticsearchException(org.elasticsearch.ElasticsearchException) SafeCommitInfo(org.elasticsearch.index.engine.SafeCommitInfo) TimeoutException(java.util.concurrent.TimeoutException) SnapshotRecoverySource(org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource) VersionType(org.elasticsearch.index.VersionType) StoreFileMetadata(org.elasticsearch.index.store.StoreFileMetadata) Settings(org.elasticsearch.common.settings.Settings) ResyncTask(org.elasticsearch.index.shard.PrimaryReplicaSyncer.ResyncTask) Locale(java.util.Locale) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ActionRunnable(org.elasticsearch.action.ActionRunnable) Releasable(org.elasticsearch.common.lease.Releasable) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) RefreshFailedEngineException(org.elasticsearch.index.engine.RefreshFailedEngineException) CheckIndex(org.apache.lucene.index.CheckIndex) UNASSIGNED_SEQ_NO(org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) Collectors(java.util.stream.Collectors) SegmentInfos(org.apache.lucene.index.SegmentInfos) ReadOnlyEngine(org.elasticsearch.index.engine.ReadOnlyEngine) Engine(org.elasticsearch.index.engine.Engine) Objects(java.util.Objects) MapperService(org.elasticsearch.index.mapper.MapperService) TranslogStats(org.elasticsearch.index.translog.TranslogStats) List(java.util.List) Version(org.elasticsearch.Version) MeanMetric(org.elasticsearch.common.metrics.MeanMetric) RetentionLeaseStats(org.elasticsearch.index.seqno.RetentionLeaseStats) MappingMetadata(org.elasticsearch.cluster.metadata.MappingMetadata) IndicesClusterStateService(org.elasticsearch.indices.cluster.IndicesClusterStateService) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) RetentionLeaseSyncer(org.elasticsearch.index.seqno.RetentionLeaseSyncer) TimeValue(io.crate.common.unit.TimeValue) Optional(java.util.Optional) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) CommitStats(org.elasticsearch.index.engine.CommitStats) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CheckedConsumer(org.elasticsearch.common.CheckedConsumer) Index(org.elasticsearch.index.Index) Lucene(org.elasticsearch.common.lucene.Lucene) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) HashSet(java.util.HashSet) ForceMergeRequest(org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest) RootObjectMapper(org.elasticsearch.index.mapper.RootObjectMapper) MetadataSnapshot(org.elasticsearch.index.store.Store.MetadataSnapshot) IndexSettings(org.elasticsearch.index.IndexSettings) Mapping(org.elasticsearch.index.mapper.Mapping) DocumentMapper(org.elasticsearch.index.mapper.DocumentMapper) PrintStream(java.io.PrintStream) Repository(org.elasticsearch.repositories.Repository) Uid(org.elasticsearch.index.mapper.Uid) RecoveryTarget(org.elasticsearch.indices.recovery.RecoveryTarget) EngineFactory(org.elasticsearch.index.engine.EngineFactory) IndexingMemoryController(org.elasticsearch.indices.IndexingMemoryController) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) FlushRequest(org.elasticsearch.action.admin.indices.flush.FlushRequest) Closeable(java.io.Closeable) Assertions(org.elasticsearch.Assertions) Translog(org.elasticsearch.index.translog.Translog) Collections(java.util.Collections) RunOnce(org.elasticsearch.common.util.concurrent.RunOnce) IndexService(org.elasticsearch.index.IndexService) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CheckIndex(org.apache.lucene.index.CheckIndex) Index(org.elasticsearch.index.Index) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) WriteStateException(org.elasticsearch.gateway.WriteStateException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) ThreadInterruptedException(org.apache.lucene.util.ThreadInterruptedException) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) EngineException(org.elasticsearch.index.engine.EngineException) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) TimeoutException(java.util.concurrent.TimeoutException) RefreshFailedEngineException(org.elasticsearch.index.engine.RefreshFailedEngineException) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata)

Aggregations

IndexNotFoundException (org.elasticsearch.index.IndexNotFoundException)92 ClusterState (org.elasticsearch.cluster.ClusterState)22 ShardNotFoundException (org.elasticsearch.index.shard.ShardNotFoundException)21 ShardId (org.elasticsearch.index.shard.ShardId)19 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)16 Index (org.elasticsearch.index.Index)16 Map (java.util.Map)15 ArrayList (java.util.ArrayList)14 IOException (java.io.IOException)13 IndexMetadata (org.elasticsearch.cluster.metadata.IndexMetadata)12 List (java.util.List)11 IndicesOptions (org.elasticsearch.action.support.IndicesOptions)11 ClusterName (org.elasticsearch.cluster.ClusterName)9 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)9 Settings (org.elasticsearch.common.settings.Settings)9 Matchers.containsString (org.hamcrest.Matchers.containsString)9 HashMap (java.util.HashMap)8 Nullable (javax.annotation.Nullable)8 RoutingNode (org.elasticsearch.cluster.routing.RoutingNode)8 RoutingNodes (org.elasticsearch.cluster.routing.RoutingNodes)8