Search in sources :

Example 96 with IndexService

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

the class IndicesService method verifyIndexMetadata.

/**
     * This method verifies that the given {@code metaData} holds sane values to create an {@link IndexService}.
     * This method tries to update the meta data of the created {@link IndexService} if the given {@code metaDataUpdate} is different from the given {@code metaData}.
     * This method will throw an exception if the creation or the update fails.
     * The created {@link IndexService} will not be registered and will be closed immediately.
     */
public synchronized void verifyIndexMetadata(IndexMetaData metaData, IndexMetaData metaDataUpdate) throws IOException {
    final List<Closeable> closeables = new ArrayList<>();
    try {
        IndicesFieldDataCache indicesFieldDataCache = new IndicesFieldDataCache(settings, new IndexFieldDataCache.Listener() {
        });
        closeables.add(indicesFieldDataCache);
        IndicesQueryCache indicesQueryCache = new IndicesQueryCache(settings);
        closeables.add(indicesQueryCache);
        // this will also fail if some plugin fails etc. which is nice since we can verify that early
        final IndexService service = createIndexService("metadata verification", metaData, indicesQueryCache, indicesFieldDataCache, emptyList(), s -> {
        });
        closeables.add(() -> service.close("metadata verification", false));
        service.mapperService().merge(metaData, MapperService.MergeReason.MAPPING_RECOVERY, true);
        if (metaData.equals(metaDataUpdate) == false) {
            service.updateMetaData(metaDataUpdate);
        }
    } finally {
        IOUtils.close(closeables);
    }
}
Also used : IndexFieldDataCache(org.elasticsearch.index.fielddata.IndexFieldDataCache) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) IndexService(org.elasticsearch.index.IndexService) Closeable(java.io.Closeable) CollectionUtils.arrayAsArrayList(org.elasticsearch.common.util.CollectionUtils.arrayAsArrayList) ArrayList(java.util.ArrayList)

Example 97 with IndexService

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

the class IndicesService method createIndex.

/**
     * Creates a new {@link IndexService} for the given metadata.
     * @param indexMetaData the index metadata to create the index for
     * @param builtInListeners a list of built-in lifecycle {@link IndexEventListener} that should should be used along side with the per-index listeners
     * @throws ResourceAlreadyExistsException if the index already exists.
     */
@Override
public synchronized IndexService createIndex(IndexMetaData indexMetaData, List<IndexEventListener> builtInListeners, Consumer<ShardId> globalCheckpointSyncer) throws IOException {
    ensureChangesAllowed();
    if (indexMetaData.getIndexUUID().equals(IndexMetaData.INDEX_UUID_NA_VALUE)) {
        throw new IllegalArgumentException("index must have a real UUID found value: [" + indexMetaData.getIndexUUID() + "]");
    }
    final Index index = indexMetaData.getIndex();
    if (hasIndex(index)) {
        throw new ResourceAlreadyExistsException(index);
    }
    List<IndexEventListener> finalListeners = new ArrayList<>(builtInListeners);
    final IndexEventListener onStoreClose = new IndexEventListener() {

        @Override
        public void onStoreClosed(ShardId shardId) {
            indicesQueryCache.onClose(shardId);
        }
    };
    finalListeners.add(onStoreClose);
    finalListeners.add(oldShardsStats);
    final IndexService indexService = createIndexService("create index", indexMetaData, indicesQueryCache, indicesFieldDataCache, finalListeners, globalCheckpointSyncer, indexingMemoryController);
    boolean success = false;
    try {
        indexService.getIndexEventListener().afterIndexCreated(indexService);
        indices = newMapBuilder(indices).put(index.getUUID(), indexService).immutableMap();
        success = true;
        return indexService;
    } finally {
        if (success == false) {
            indexService.close("plugins_failed", true);
        }
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) IndexService(org.elasticsearch.index.IndexService) CollectionUtils.arrayAsArrayList(org.elasticsearch.common.util.CollectionUtils.arrayAsArrayList) ArrayList(java.util.ArrayList) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) Index(org.elasticsearch.index.Index)

Example 98 with IndexService

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

the class IndicesClusterStateService method createIndices.

private void createIndices(final ClusterState state) {
    // we only create indices for shards that are allocated
    RoutingNode localRoutingNode = state.getRoutingNodes().node(state.nodes().getLocalNodeId());
    if (localRoutingNode == null) {
        return;
    }
    // create map of indices to create with shards to fail if index creation fails
    final Map<Index, List<ShardRouting>> indicesToCreate = new HashMap<>();
    for (ShardRouting shardRouting : localRoutingNode) {
        if (failedShardsCache.containsKey(shardRouting.shardId()) == false) {
            final Index index = shardRouting.index();
            if (indicesService.indexService(index) == null) {
                indicesToCreate.computeIfAbsent(index, k -> new ArrayList<>()).add(shardRouting);
            }
        }
    }
    for (Map.Entry<Index, List<ShardRouting>> entry : indicesToCreate.entrySet()) {
        final Index index = entry.getKey();
        final IndexMetaData indexMetaData = state.metaData().index(index);
        logger.debug("[{}] creating index", index);
        AllocatedIndex<? extends Shard> indexService = null;
        try {
            indexService = indicesService.createIndex(indexMetaData, buildInIndexListener, globalCheckpointSyncer);
            if (indexService.updateMapping(indexMetaData) && sendRefreshMapping) {
                nodeMappingRefreshAction.nodeMappingRefresh(state.nodes().getMasterNode(), new NodeMappingRefreshAction.NodeMappingRefreshRequest(indexMetaData.getIndex().getName(), indexMetaData.getIndexUUID(), state.nodes().getLocalNodeId()));
            }
        } catch (Exception e) {
            final String failShardReason;
            if (indexService == null) {
                failShardReason = "failed to create index";
            } else {
                failShardReason = "failed to update mapping for index";
                indicesService.removeIndex(index, FAILURE, "removing index (mapping update failed)");
            }
            for (ShardRouting shardRouting : entry.getValue()) {
                sendFailShard(shardRouting, failShardReason, e, state);
            }
        }
    }
}
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) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Index(org.elasticsearch.index.Index) NodeMappingRefreshAction(org.elasticsearch.cluster.action.index.NodeMappingRefreshAction) 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) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) List(java.util.List) ArrayList(java.util.ArrayList) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Map(java.util.Map) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 99 with IndexService

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

the class SyncedFlushService method performSyncedFlush.

private ShardSyncedFlushResponse performSyncedFlush(ShardSyncedFlushRequest request) {
    IndexService indexService = indicesService.indexServiceSafe(request.shardId().getIndex());
    IndexShard indexShard = indexService.getShard(request.shardId().id());
    logger.trace("{} performing sync flush. sync id [{}], expected commit id {}", request.shardId(), request.syncId(), request.expectedCommitId());
    Engine.SyncedFlushResult result = indexShard.syncFlush(request.syncId(), request.expectedCommitId());
    logger.trace("{} sync flush done. sync id [{}], result [{}]", request.shardId(), request.syncId(), result);
    switch(result) {
        case SUCCESS:
            return new ShardSyncedFlushResponse();
        case COMMIT_MISMATCH:
            return new ShardSyncedFlushResponse("commit has changed");
        case PENDING_OPERATIONS:
            return new ShardSyncedFlushResponse("pending operations");
        default:
            throw new ElasticsearchException("unknown synced flush result [" + result + "]");
    }
}
Also used : IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) ElasticsearchException(org.elasticsearch.ElasticsearchException) Engine(org.elasticsearch.index.engine.Engine)

Example 100 with IndexService

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

the class PeerRecoverySourceService method recover.

private RecoveryResponse recover(final StartRecoveryRequest request) throws IOException {
    final IndexService indexService = indicesService.indexServiceSafe(request.shardId().getIndex());
    final IndexShard shard = indexService.getShard(request.shardId().id());
    // starting recovery from that our (the source) shard state is marking the shard to be in recovery mode as well, otherwise
    // the index operations will not be routed to it properly
    RoutingNode node = clusterService.state().getRoutingNodes().node(request.targetNode().getId());
    if (node == null) {
        logger.debug("delaying recovery of {} as source node {} is unknown", request.shardId(), request.targetNode());
        throw new DelayRecoveryException("source node does not have the node [" + request.targetNode() + "] in its state yet..");
    }
    ShardRouting routingEntry = shard.routingEntry();
    if (request.isPrimaryRelocation() && (routingEntry.relocating() == false || routingEntry.relocatingNodeId().equals(request.targetNode().getId()) == false)) {
        logger.debug("delaying recovery of {} as source shard is not marked yet as relocating to {}", request.shardId(), request.targetNode());
        throw new DelayRecoveryException("source shard is not marked yet as relocating to [" + request.targetNode() + "]");
    }
    ShardRouting targetShardRouting = node.getByShardId(request.shardId());
    if (targetShardRouting == null) {
        logger.debug("delaying recovery of {} as it is not listed as assigned to target node {}", request.shardId(), request.targetNode());
        throw new DelayRecoveryException("source node does not have the shard listed in its state as allocated on the node");
    }
    if (!targetShardRouting.initializing()) {
        logger.debug("delaying recovery of {} as it is not listed as initializing on the target node {}. known shards state is [{}]", request.shardId(), request.targetNode(), targetShardRouting.state());
        throw new DelayRecoveryException("source node has the state of the target shard to be [" + targetShardRouting.state() + "], expecting to be [initializing]");
    }
    RecoverySourceHandler handler = ongoingRecoveries.addNewRecovery(request, targetShardRouting.allocationId().getId(), shard);
    logger.trace("[{}][{}] starting recovery to {}", request.shardId().getIndex().getName(), request.shardId().id(), request.targetNode());
    try {
        return handler.recoverToTarget();
    } finally {
        ongoingRecoveries.remove(shard, handler);
    }
}
Also used : RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Aggregations

IndexService (org.elasticsearch.index.IndexService)173 IndexShard (org.elasticsearch.index.shard.IndexShard)53 CompressedXContent (org.elasticsearch.common.compress.CompressedXContent)49 IndicesService (org.elasticsearch.indices.IndicesService)38 DocumentMapper (org.elasticsearch.index.mapper.DocumentMapper)30 Settings (org.elasticsearch.common.settings.Settings)25 ShardId (org.elasticsearch.index.shard.ShardId)24 Index (org.elasticsearch.index.Index)20 QueryShardContext (org.elasticsearch.index.query.QueryShardContext)17 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)16 IOException (java.io.IOException)15 HashMap (java.util.HashMap)15 ArrayList (java.util.ArrayList)14 ClusterState (org.elasticsearch.cluster.ClusterState)13 Map (java.util.Map)12 ClusterService (org.elasticsearch.cluster.service.ClusterService)12 ElasticsearchException (org.elasticsearch.ElasticsearchException)11 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)11 ParsedDocument (org.elasticsearch.index.mapper.ParsedDocument)11 List (java.util.List)10