Package org.elasticsearch.index.service

Examples of org.elasticsearch.index.service.IndexService


        // check if aliases changed
        if (aliasesChanged(event)) {
            // go over and update aliases
            for (IndexMetaData indexMetaData : event.state().metaData()) {
                String index = indexMetaData.index();
                IndexService indexService = indicesService.indexService(index);
                if (indexService == null) {
                    // we only create / update here
                    continue;
                }
                IndexAliasesService indexAliasesService = indexService.aliasesService();
                processAliases(index, indexMetaData.aliases().values(), indexAliasesService);
                // go over and remove aliases
                for (IndexAlias indexAlias : indexAliasesService) {
                    if (!indexMetaData.aliases().containsKey(indexAlias.alias())) {
                        // we have it in our aliases, but not in the metadata, remove it
View Full Code Here


            return;
        }
        DiscoveryNodes nodes = event.state().nodes();

        for (final ShardRouting shardRouting : routingNode) {
            final IndexService indexService = indicesService.indexService(shardRouting.index());
            if (indexService == null) {
                // got deleted on us, ignore
                continue;
            }
            final IndexMetaData indexMetaData = event.state().metaData().index(shardRouting.index());
            if (indexMetaData == null) {
                // the index got deleted on the metadata, we will clean it later in the apply deleted method call
                continue;
            }

            final int shardId = shardRouting.id();

            if (!indexService.hasShard(shardId) && shardRouting.started()) {
                if (failedShards.containsKey(shardRouting.shardId())) {
                    if (nodes.masterNode() != null) {
                        shardStateAction.resendShardFailed(shardRouting, indexMetaData.getUUID(),
                                "master " + nodes.masterNode() + " marked shard as started, but shard has previous failed. resending shard failure.",
                                nodes.masterNode()
                        );
                    }
                } else {
                    // the master thinks we are started, but we don't have this shard at all, mark it as failed
                    logger.warn("[{}][{}] master [{}] marked shard as started, but shard has not been created, mark shard as failed", shardRouting.index(), shardId, nodes.masterNode());
                    failedShards.put(shardRouting.shardId(), new FailedShard(shardRouting.version()));
                    if (nodes.masterNode() != null) {
                        shardStateAction.shardFailed(shardRouting, indexMetaData.getUUID(),
                                "master " + nodes.masterNode() + " marked shard as started, but shard has not been created, mark shard as failed",
                                nodes.masterNode()
                        );
                    }
                }
                continue;
            }

            InternalIndexShard indexShard = (InternalIndexShard) indexService.shard(shardId);
            if (indexShard != null) {
                ShardRouting currentRoutingEntry = indexShard.routingEntry();
                // if the current and global routing are initializing, but are still not the same, its a different "shard" being allocated
                // for example: a shard that recovers from one node and now needs to recover to another node,
                //              or a replica allocated and then allocating a primary because the primary failed on another node
                boolean shardHasBeenRemoved = false;
                if (currentRoutingEntry.initializing() && shardRouting.initializing() && !currentRoutingEntry.equals(shardRouting)) {
                    logger.debug("[{}][{}] removing shard (different instance of it allocated on this node, current [{}], global [{}])", shardRouting.index(), shardRouting.id(), currentRoutingEntry, shardRouting);
                    // closing the shard will also cancel any ongoing recovery.
                    indexService.removeShard(shardRouting.id(), "removing shard (different instance of it allocated on this node)");
                    shardHasBeenRemoved = true;
                } else if (isPeerRecovery(shardRouting)) {
                    // check if there is an existing recovery going, and if so, and the source node is not the same, cancel the recovery to restart it
                    RecoveryState recoveryState = recoveryTarget.recoveryState(indexShard);
                    if (recoveryState != null && recoveryState.getStage() != RecoveryState.Stage.DONE) {
                        // we have an ongoing recovery, find the source based on current routing and compare them
                        DiscoveryNode sourceNode = findSourceNodeForPeerRecovery(routingTable, nodes, shardRouting);
                        if (!recoveryState.getSourceNode().equals(sourceNode)) {
                            logger.debug("[{}][{}] removing shard (recovery source changed), current [{}], global [{}])", shardRouting.index(), shardRouting.id(), currentRoutingEntry, shardRouting);
                            // closing the shard will also cancel any ongoing recovery.
                            indexService.removeShard(shardRouting.id(), "removing shard (recovery source node changed)");
                            shardHasBeenRemoved = true;
                        }
                    }
                }
                if (shardHasBeenRemoved == false && !shardRouting.equals(indexShard.routingEntry())) {
                    // if we happen to remove the shardRouting by id above we don't need to jump in here!
                    indexShard.routingEntry(shardRouting);
                    indexService.shardInjectorSafe(shardId).getInstance(IndexShardGatewayService.class).routingStateChanged();
                }
            }

            if (shardRouting.initializing()) {
                applyInitializingShard(routingTable, nodes, indexMetaData, routingTable.index(shardRouting.index()).shard(shardRouting.id()), shardRouting);
View Full Code Here

            iterator.remove();
        }
    }

    private void applyInitializingShard(final RoutingTable routingTable, final DiscoveryNodes nodes, final IndexMetaData indexMetaData, final IndexShardRoutingTable indexShardRouting, final ShardRouting shardRouting) throws ElasticsearchException {
        final IndexService indexService = indicesService.indexService(shardRouting.index());
        if (indexService == null) {
            // got deleted on us, ignore
            return;
        }
        final int shardId = shardRouting.id();

        if (indexService.hasShard(shardId)) {
            IndexShard indexShard = indexService.shardSafe(shardId);
            if (indexShard.state() == IndexShardState.STARTED || indexShard.state() == IndexShardState.POST_RECOVERY) {
                // the master thinks we are initializing, but we are already started or on POST_RECOVERY and waiting
                // for master to confirm a shard started message (either master failover, or a cluster event before
                // 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 {}",
                            indexShard.shardId(), indexShard.state(), nodes.masterNode());
                }
                if (nodes.masterNode() != null) {
                    shardStateAction.shardStarted(shardRouting, indexMetaData.getUUID(),
                            "master " + nodes.masterNode() + " marked shard as initializing, but shard state is [" + indexShard.state() + "], mark shard as started",
                            nodes.masterNode());
                }
                return;
            } else {
                if (indexShard.ignoreRecoveryAttempt()) {
                    logger.trace("ignoring recovery instruction for an existing shard {} (shard state: [{}])", indexShard.shardId(), indexShard.state());
                    return;
                }
            }
        }

        // if we're in peer recovery, try to find out the source node now so in case it fails, we will not create the index shard
        DiscoveryNode sourceNode = null;
        if (isPeerRecovery(shardRouting)) {
            sourceNode = findSourceNodeForPeerRecovery(routingTable, nodes, shardRouting);
            if (sourceNode == null) {
                logger.trace("ignoring initializing shard {} - no source node can be found.", shardRouting.shardId());
                return;
            }
        }

        // if there is no shard, create it
        if (!indexService.hasShard(shardId)) {
            if (failedShards.containsKey(shardRouting.shardId())) {
                if (nodes.masterNode() != null) {
                    shardStateAction.resendShardFailed(shardRouting, indexMetaData.getUUID(),
                            "master " + nodes.masterNode() + " marked shard as initializing, but shard is marked as failed, resend shard failure",
                            nodes.masterNode());
                }
                return;
            }
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug("[{}][{}] creating shard", shardRouting.index(), shardId);
                }
                InternalIndexShard indexShard = (InternalIndexShard) indexService.createShard(shardId);
                indexShard.routingEntry(shardRouting);
                indexShard.engine().addFailedEngineListener(failedEngineHandler);
            } catch (IndexShardAlreadyExistsException e) {
                // ignore this, the method call can happen several times
            } catch (Throwable e) {
                logger.warn("[{}][{}] failed to create shard", e, shardRouting.index(), shardRouting.id());
                try {
                    indexService.removeShard(shardId, "failed to create [" + ExceptionsHelper.detailedMessage(e) + "]");
                } catch (IndexShardMissingException e1) {
                    // ignore
                } catch (Throwable e1) {
                    logger.warn("[{}][{}] failed to remove shard after failed creation", e1, shardRouting.index(), shardRouting.id());
                }
                failedShards.put(shardRouting.shardId(), new FailedShard(shardRouting.version()));
                if (nodes.masterNode() != null) {
                    shardStateAction.shardFailed(shardRouting, indexMetaData.getUUID(), "Failed to create shard, message [" + detailedMessage(e) + "]",
                            nodes.masterNode()
                    );
                } else {
                    logger.debug("can't send shard failed for {} as there is no current master", shardRouting.shardId());
                }
                return;
            }
        }
        final InternalIndexShard indexShard = (InternalIndexShard) indexService.shardSafe(shardId);

        if (indexShard.ignoreRecoveryAttempt()) {
            // we are already recovering (we can get to this state since the cluster event can happen several
            // times while we recover)
            logger.trace("ignoring recovery instruction for shard {} (shard state: [{}])", indexShard.shardId(), indexShard.state());
            return;
        }

        if (isPeerRecovery(shardRouting)) {
            try {

                assert sourceNode != null : "peer recovery started but sourceNode is null";

                // we don't mark this one as relocated at the end.
                // For primaries: requests in any case are routed to both when its relocating and that way we handle
                //    the edge case where its mark as relocated, and we might need to roll it back...
                // For replicas: we are recovering a backup from a primary
                RecoveryState.Type type = shardRouting.primary() ? RecoveryState.Type.RELOCATION : RecoveryState.Type.REPLICA;
                recoveryTarget.startRecovery(indexShard, type, sourceNode, new PeerRecoveryListener(shardRouting, indexService, indexMetaData));
            } catch (Throwable e) {
                indexShard.engine().failEngine("corrupted preexisting index", e);
                handleRecoveryFailure(indexService, indexMetaData, shardRouting, true, e);
            }
        } else {
            // we are the first primary, recover from the gateway
            // if its post api allocation, the index should exists
            boolean indexShouldExists = indexShardRouting.primaryAllocatedPostApi();
            IndexShardGatewayService shardGatewayService = indexService.shardInjectorSafe(shardId).getInstance(IndexShardGatewayService.class);
            shardGatewayService.recover(indexShouldExists, new IndexShardGatewayService.RecoveryListener() {
                @Override
                public void onRecoveryDone() {
                    shardStateAction.shardStarted(shardRouting, indexMetaData.getUUID(), "after recovery from gateway");
                }
View Full Code Here

    }

    @Override
    protected PrimaryResponse<ShardDeleteByQueryResponse, ShardDeleteByQueryRequest> shardOperationOnPrimary(ClusterState clusterState, PrimaryOperationRequest shardRequest) {
        ShardDeleteByQueryRequest request = shardRequest.request;
        IndexService indexService = indicesService.indexServiceSafe(shardRequest.shardId.getIndex());
        IndexShard indexShard = indexService.shardSafe(shardRequest.shardId.id());

        SearchContext.setCurrent(new DefaultSearchContext(0, new ShardSearchLocalRequest(request.types(), request.nowInMillis()), null,
                indexShard.acquireSearcher(DELETE_BY_QUERY_API), indexService, indexShard, scriptService,
                pageCacheRecycler, bigArrays, threadPool.estimatedTimeInMillisCounter()));
        try {
View Full Code Here


    @Override
    protected void shardOperationOnReplica(ReplicaOperationRequest shardRequest) {
        ShardDeleteByQueryRequest request = shardRequest.request;
        IndexService indexService = indicesService.indexServiceSafe(shardRequest.shardId.getIndex());
        IndexShard indexShard = indexService.shardSafe(shardRequest.shardId.id());

        SearchContext.setCurrent(new DefaultSearchContext(0, new ShardSearchLocalRequest(request.types(), request.nowInMillis()), null,
                indexShard.acquireSearcher(DELETE_BY_QUERY_API, IndexShard.Mode.WRITE), indexService, indexShard, scriptService,
                pageCacheRecycler, bigArrays, threadPool.estimatedTimeInMillisCounter()));
        try {
View Full Code Here

        return indices.get(index);
    }

    @Override
    public IndexService indexServiceSafe(String index) throws IndexMissingException {
        IndexService indexService = indexService(index);
        if (indexService == null) {
            throw new IndexMissingException(new Index(index));
        }
        return indexService;
    }
View Full Code Here

            throw new IndexCreationException(index, e);
        }

        indicesInjectors.put(index.name(), indexInjector);

        IndexService indexService = indexInjector.getInstance(IndexService.class);

        indicesLifecycle.afterIndexCreated(indexService);

        indices = newMapBuilder(indices).put(index.name(), indexService).immutableMap();
View Full Code Here

    public void removeIndex(String index, String reason) throws ElasticsearchException {
        removeIndex(index, reason, null);
    }

    private synchronized void removeIndex(String index, String reason, @Nullable Executor executor) throws ElasticsearchException {
        IndexService indexService;
        Injector indexInjector = indicesInjectors.remove(index);
        if (indexInjector == null) {
            return;
        }

        logger.debug("[{}] closing ... (reason [{}])", index, reason);
        Map<String, IndexService> tmpMap = newHashMap(indices);
        indexService = tmpMap.remove(index);
        indices = ImmutableMap.copyOf(tmpMap);

        indicesLifecycle.beforeIndexClosed(indexService);

        for (Class<? extends CloseableIndexComponent> closeable : pluginsService.indexServices()) {
            indexInjector.getInstance(closeable).close();
        }

        logger.debug("[{}] closing index service", index, reason);
        ((InternalIndexService) indexService).close(reason, executor);

        logger.debug("[{}] closing index cache", index, reason);
        indexInjector.getInstance(IndexCache.class).close();
        logger.debug("[{}] clearing index field data", index, reason);
        indexInjector.getInstance(IndexFieldDataService.class).clear();
        logger.debug("[{}] closing analysis service", index, reason);
        indexInjector.getInstance(AnalysisService.class).close();
        logger.debug("[{}] closing index engine", index, reason);
        indexInjector.getInstance(IndexEngine.class).close();

        logger.debug("[{}] closing index gateway", index, reason);
        indexInjector.getInstance(IndexGateway.class).close();
        logger.debug("[{}] closing mapper service", index, reason);
        indexInjector.getInstance(MapperService.class).close();
        logger.debug("[{}] closing index query parser service", index, reason);
        indexInjector.getInstance(IndexQueryParserService.class).close();

        logger.debug("[{}] closing index service", index, reason);
        indexInjector.getInstance(IndexStore.class).close();

        Injectors.close(injector);

        logger.debug("[{}] closed... (reason [{}])", index, reason);
        indicesLifecycle.afterIndexClosed(indexService.index());
    }
View Full Code Here

    }

    @Override
    protected NodeStoreFilesMetaData nodeOperation(NodeRequest request) throws ElasticsearchException {
        if (request.unallocated) {
            IndexService indexService = indicesService.indexService(request.shardId.index().name());
            if (indexService == null) {
                return new NodeStoreFilesMetaData(clusterService.localNode(), null);
            }
            if (!indexService.hasShard(request.shardId.id())) {
                return new NodeStoreFilesMetaData(clusterService.localNode(), null);
            }
        }
        IndexMetaData metaData = clusterService.state().metaData().index(request.shardId.index().name());
        if (metaData == null) {
View Full Code Here

            throw new ElasticsearchException("Failed to list store metadata for shard [" + request.shardId + "]", e);
        }
    }

    private StoreFilesMetaData listStoreMetaData(ShardId shardId) throws IOException {
        IndexService indexService = indicesService.indexService(shardId.index().name());
        if (indexService != null) {
            InternalIndexShard indexShard = (InternalIndexShard) indexService.shard(shardId.id());
            if (indexShard != null) {
                final Store store = indexShard.store();
                store.incRef();
                try {
                    return new StoreFilesMetaData(true, shardId, store.getMetadataOrEmpty().asMap());
View Full Code Here

TOP

Related Classes of org.elasticsearch.index.service.IndexService

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.