Search in sources :

Example 86 with IndexService

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

the class MetaDataIndexAliasesService method innerExecute.

ClusterState innerExecute(ClusterState currentState, Iterable<AliasAction> actions) {
    List<Index> indicesToClose = new ArrayList<>();
    Map<String, IndexService> indices = new HashMap<>();
    try {
        boolean changed = false;
        // Gather all the indexes that must be removed first so:
        // 1. We don't cause error when attempting to replace an index with a alias of the same name.
        // 2. We don't allow removal of aliases from indexes that we're just going to delete anyway. That'd be silly.
        Set<Index> indicesToDelete = new HashSet<>();
        for (AliasAction action : actions) {
            if (action.removeIndex()) {
                IndexMetaData index = currentState.metaData().getIndices().get(action.getIndex());
                if (index == null) {
                    throw new IndexNotFoundException(action.getIndex());
                }
                indicesToDelete.add(index.getIndex());
                changed = true;
            }
        }
        // Remove the indexes if there are any to remove
        if (changed) {
            currentState = deleteIndexService.deleteIndices(currentState, indicesToDelete);
        }
        MetaData.Builder metadata = MetaData.builder(currentState.metaData());
        // Run the remaining alias actions
        for (AliasAction action : actions) {
            if (action.removeIndex()) {
                // Handled above
                continue;
            }
            IndexMetaData index = metadata.get(action.getIndex());
            if (index == null) {
                throw new IndexNotFoundException(action.getIndex());
            }
            NewAliasValidator newAliasValidator = (alias, indexRouting, filter) -> {
                /* It is important that we look up the index using the metadata builder we are modifying so we can remove an
                     * index and replace it with an alias. */
                Function<String, IndexMetaData> indexLookup = name -> metadata.get(name);
                aliasValidator.validateAlias(alias, action.getIndex(), indexRouting, indexLookup);
                if (Strings.hasLength(filter)) {
                    IndexService indexService = indices.get(index.getIndex());
                    if (indexService == null) {
                        indexService = indicesService.indexService(index.getIndex());
                        if (indexService == null) {
                            // temporarily create the index and add mappings so we can parse the filter
                            try {
                                indexService = indicesService.createIndex(index, emptyList(), shardId -> {
                                });
                                indicesToClose.add(index.getIndex());
                            } catch (IOException e) {
                                throw new ElasticsearchException("Failed to create temporary index for parsing the alias", e);
                            }
                            indexService.mapperService().merge(index, MapperService.MergeReason.MAPPING_RECOVERY, false);
                        }
                        indices.put(action.getIndex(), indexService);
                    }
                    // the context is only used for validation so it's fine to pass fake values for the shard id and the current
                    // timestamp
                    aliasValidator.validateAliasFilter(alias, filter, indexService.newQueryShardContext(0, null, () -> 0L), xContentRegistry);
                }
            };
            changed |= action.apply(newAliasValidator, metadata, index);
        }
        if (changed) {
            ClusterState updatedState = ClusterState.builder(currentState).metaData(metadata).build();
            // i.e. remove and add the same alias to the same index
            if (!updatedState.metaData().equalsAliases(currentState.metaData())) {
                return updatedState;
            }
        }
        return currentState;
    } finally {
        for (Index index : indicesToClose) {
            indicesService.removeIndex(index, NO_LONGER_ASSIGNED, "created for alias processing");
        }
    }
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) AckedClusterStateUpdateTask(org.elasticsearch.cluster.AckedClusterStateUpdateTask) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) Function(java.util.function.Function) Strings(org.elasticsearch.common.Strings) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Map(java.util.Map) IndicesService(org.elasticsearch.indices.IndicesService) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Priority(org.elasticsearch.common.Priority) AbstractComponent(org.elasticsearch.common.component.AbstractComponent) Collections.emptyList(java.util.Collections.emptyList) IndexService(org.elasticsearch.index.IndexService) Set(java.util.Set) IOException(java.io.IOException) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) MapperService(org.elasticsearch.index.mapper.MapperService) List(java.util.List) IndicesAliasesClusterStateUpdateRequest(org.elasticsearch.action.admin.indices.alias.IndicesAliasesClusterStateUpdateRequest) ClusterStateUpdateResponse(org.elasticsearch.cluster.ack.ClusterStateUpdateResponse) NO_LONGER_ASSIGNED(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.NO_LONGER_ASSIGNED) ActionListener(org.elasticsearch.action.ActionListener) NewAliasValidator(org.elasticsearch.cluster.metadata.AliasAction.NewAliasValidator) ClusterState(org.elasticsearch.cluster.ClusterState) HashMap(java.util.HashMap) IndexService(org.elasticsearch.index.IndexService) ArrayList(java.util.ArrayList) Index(org.elasticsearch.index.Index) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) NewAliasValidator(org.elasticsearch.cluster.metadata.AliasAction.NewAliasValidator) Function(java.util.function.Function) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) HashSet(java.util.HashSet)

Example 87 with IndexService

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

the class SearchService method createSearchContext.

public DefaultSearchContext createSearchContext(ShardSearchRequest request, TimeValue timeout, @Nullable Engine.Searcher searcher) throws IOException {
    IndexService indexService = indicesService.indexServiceSafe(request.shardId().getIndex());
    IndexShard indexShard = indexService.getShard(request.shardId().getId());
    SearchShardTarget shardTarget = new SearchShardTarget(clusterService.localNode().getId(), indexShard.shardId());
    Engine.Searcher engineSearcher = searcher == null ? indexShard.acquireSearcher("search") : searcher;
    final DefaultSearchContext searchContext = new DefaultSearchContext(idGenerator.incrementAndGet(), request, shardTarget, engineSearcher, indexService, indexShard, bigArrays, threadPool.estimatedTimeInMillisCounter(), timeout, fetchPhase);
    boolean success = false;
    try {
        // we clone the query shard context here just for rewriting otherwise we
        // might end up with incorrect state since we are using now() or script services
        // during rewrite and normalized / evaluate templates etc.
        request.rewrite(new QueryShardContext(searchContext.getQueryShardContext()));
        assert searchContext.getQueryShardContext().isCachable();
        success = true;
    } finally {
        if (success == false) {
            IOUtils.closeWhileHandlingException(searchContext);
        }
    }
    return searchContext;
}
Also used : IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) Engine(org.elasticsearch.index.engine.Engine)

Example 88 with IndexService

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

the class TransportUpgradeStatusAction method shardOperation.

@Override
protected ShardUpgradeStatus shardOperation(UpgradeStatusRequest request, ShardRouting shardRouting) {
    IndexService indexService = indicesService.indexServiceSafe(shardRouting.shardId().getIndex());
    IndexShard indexShard = indexService.getShard(shardRouting.shardId().id());
    List<Segment> segments = indexShard.segments(false);
    long total_bytes = 0;
    long to_upgrade_bytes = 0;
    long to_upgrade_bytes_ancient = 0;
    for (Segment seg : segments) {
        total_bytes += seg.sizeInBytes;
        if (seg.version.major != Version.CURRENT.luceneVersion.major) {
            to_upgrade_bytes_ancient += seg.sizeInBytes;
            to_upgrade_bytes += seg.sizeInBytes;
        } else if (seg.version.minor != Version.CURRENT.luceneVersion.minor) {
            // TODO: this comparison is bogus! it would cause us to upgrade even with the same format
            // instead, we should check if the codec has changed
            to_upgrade_bytes += seg.sizeInBytes;
        }
    }
    return new ShardUpgradeStatus(indexShard.routingEntry(), total_bytes, to_upgrade_bytes, to_upgrade_bytes_ancient);
}
Also used : IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) Segment(org.elasticsearch.index.engine.Segment)

Example 89 with IndexService

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

the class IndicesService method removeIndex.

@Override
public void removeIndex(final Index index, final IndexRemovalReason reason, final String extraInfo) {
    final String indexName = index.getName();
    try {
        final IndexService indexService;
        final IndexEventListener listener;
        synchronized (this) {
            if (hasIndex(index) == false) {
                return;
            }
            logger.debug("[{}] closing ... (reason [{}])", indexName, reason);
            Map<String, IndexService> newIndices = new HashMap<>(indices);
            indexService = newIndices.remove(index.getUUID());
            assert indexService != null : "IndexService is null for index: " + index;
            indices = unmodifiableMap(newIndices);
            listener = indexService.getIndexEventListener();
        }
        listener.beforeIndexRemoved(indexService, reason);
        logger.debug("{} closing index service (reason [{}][{}])", index, reason, extraInfo);
        indexService.close(extraInfo, reason == IndexRemovalReason.DELETED);
        logger.debug("{} closed... (reason [{}][{}])", index, reason, extraInfo);
        final IndexSettings indexSettings = indexService.getIndexSettings();
        listener.afterIndexRemoved(indexService.index(), indexSettings, reason);
        if (reason == IndexRemovalReason.DELETED) {
            // now we are done - try to wipe data on disk if possible
            deleteIndexStore(extraInfo, indexService.index(), indexSettings);
        }
    } catch (Exception e) {
        logger.warn((Supplier<?>) () -> new ParameterizedMessage("failed to remove index {} ([{}][{}])", index, reason, extraInfo), e);
    }
}
Also used : IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) IndexService(org.elasticsearch.index.IndexService) HashMap(java.util.HashMap) IndexSettings(org.elasticsearch.index.IndexSettings) Supplier(java.util.function.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException)

Example 90 with IndexService

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

the class IndicesService method stats.

public NodeIndicesStats stats(boolean includePrevious, CommonStatsFlags flags) {
    CommonStats oldStats = new CommonStats(flags);
    if (includePrevious) {
        Flag[] setFlags = flags.getFlags();
        for (Flag flag : setFlags) {
            switch(flag) {
                case Get:
                    oldStats.get.add(oldShardsStats.getStats);
                    break;
                case Indexing:
                    oldStats.indexing.add(oldShardsStats.indexingStats);
                    break;
                case Search:
                    oldStats.search.add(oldShardsStats.searchStats);
                    break;
                case Merge:
                    oldStats.merge.add(oldShardsStats.mergeStats);
                    break;
                case Refresh:
                    oldStats.refresh.add(oldShardsStats.refreshStats);
                    break;
                case Recovery:
                    oldStats.recoveryStats.add(oldShardsStats.recoveryStats);
                    break;
                case Flush:
                    oldStats.flush.add(oldShardsStats.flushStats);
                    break;
            }
        }
    }
    Map<Index, List<IndexShardStats>> statsByShard = new HashMap<>();
    for (IndexService indexService : this) {
        for (IndexShard indexShard : indexService) {
            try {
                if (indexShard.routingEntry() == null) {
                    continue;
                }
                IndexShardStats indexShardStats = new IndexShardStats(indexShard.shardId(), new ShardStats[] { new ShardStats(indexShard.routingEntry(), indexShard.shardPath(), new CommonStats(indicesQueryCache, indexShard, flags), indexShard.commitStats(), indexShard.seqNoStats()) });
                if (!statsByShard.containsKey(indexService.index())) {
                    statsByShard.put(indexService.index(), arrayAsArrayList(indexShardStats));
                } else {
                    statsByShard.get(indexService.index()).add(indexShardStats);
                }
            } catch (IllegalIndexShardStateException e) {
                // we can safely ignore illegal state on ones that are closing for example
                logger.trace((Supplier<?>) () -> new ParameterizedMessage("{} ignoring shard stats", indexShard.shardId()), e);
            }
        }
    }
    return new NodeIndicesStats(oldStats, statsByShard);
}
Also used : IndexShardStats(org.elasticsearch.action.admin.indices.stats.IndexShardStats) ShardStats(org.elasticsearch.action.admin.indices.stats.ShardStats) HashMap(java.util.HashMap) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) Index(org.elasticsearch.index.Index) IndexShardStats(org.elasticsearch.action.admin.indices.stats.IndexShardStats) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) Flag(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags.Flag) CommonStats(org.elasticsearch.action.admin.indices.stats.CommonStats) CollectionUtils.arrayAsArrayList(org.elasticsearch.common.util.CollectionUtils.arrayAsArrayList) ArrayList(java.util.ArrayList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) Supplier(java.util.function.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage)

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