Search in sources :

Example 1 with Index

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

the class MockSearchServiceTests method testAssertNoInFlightContext.

public void testAssertNoInFlightContext() {
    final long nowInMillis = randomNonNegativeLong();
    SearchContext s = new TestSearchContext(new QueryShardContext(0, new IndexSettings(EMPTY_INDEX_METADATA, Settings.EMPTY), null, null, null, null, null, xContentRegistry(), null, null, () -> nowInMillis)) {

        @Override
        public SearchShardTarget shardTarget() {
            return new SearchShardTarget("node", new Index("idx", "ignored"), 0);
        }

        @Override
        public SearchType searchType() {
            return SearchType.DEFAULT;
        }

        @Override
        public Query query() {
            return Queries.newMatchAllQuery();
        }
    };
    MockSearchService.addActiveContext(s);
    try {
        Throwable e = expectThrows(AssertionError.class, () -> MockSearchService.assertNoInFlightContext());
        assertEquals("There are still [1] in-flight contexts. The first one's creation site is listed as the cause of this exception.", e.getMessage());
        e = e.getCause();
        // The next line with throw an exception if the date looks wrong
        assertEquals("[node][idx][0] query=[*:*]", e.getMessage());
        assertEquals(MockSearchService.class.getName(), e.getStackTrace()[0].getClassName());
        assertEquals(MockSearchServiceTests.class.getName(), e.getStackTrace()[1].getClassName());
    } finally {
        MockSearchService.removeActiveContext(s);
    }
}
Also used : TestSearchContext(org.elasticsearch.test.TestSearchContext) IndexSettings(org.elasticsearch.index.IndexSettings) SearchContext(org.elasticsearch.search.internal.SearchContext) TestSearchContext(org.elasticsearch.test.TestSearchContext) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) Index(org.elasticsearch.index.Index)

Example 2 with Index

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

the class IndexFolderUpgrader method upgrade.

/**
     * Renames <code>indexFolderName</code> index folders found in node paths and custom path
     * iff {@link #needsUpgrade(Index, String)} is true.
     * Index folder in custom paths are renamed first followed by index folders in each node path.
     */
void upgrade(final String indexFolderName) throws IOException {
    for (NodeEnvironment.NodePath nodePath : nodeEnv.nodePaths()) {
        final Path indexFolderPath = nodePath.indicesPath.resolve(indexFolderName);
        final IndexMetaData indexMetaData = IndexMetaData.FORMAT.loadLatestState(logger, NamedXContentRegistry.EMPTY, indexFolderPath);
        if (indexMetaData != null) {
            final Index index = indexMetaData.getIndex();
            if (needsUpgrade(index, indexFolderName)) {
                logger.info("{} upgrading [{}] to new naming convention", index, indexFolderPath);
                final IndexSettings indexSettings = new IndexSettings(indexMetaData, settings);
                if (indexSettings.hasCustomDataPath()) {
                    // we rename index folder in custom path before renaming them in any node path
                    // to have the index state under a not-yet-upgraded index folder, which we use to
                    // continue renaming after a incomplete upgrade.
                    final Path customLocationSource = nodeEnv.resolveBaseCustomLocation(indexSettings).resolve(indexFolderName);
                    final Path customLocationTarget = customLocationSource.resolveSibling(index.getUUID());
                    // in a node path, which needs upgrading, it is a no-op for subsequent node paths
                    if (// might not exist if no data was written for this index
                    Files.exists(customLocationSource) && Files.exists(customLocationTarget) == false) {
                        upgrade(index, customLocationSource, customLocationTarget);
                    } else {
                        logger.info("[{}] no upgrade needed - already upgraded", customLocationTarget);
                    }
                }
                upgrade(index, indexFolderPath, indexFolderPath.resolveSibling(index.getUUID()));
            } else {
                logger.debug("[{}] no upgrade needed - already upgraded", indexFolderPath);
            }
        } else {
            logger.warn("[{}] no index state found - ignoring", indexFolderPath);
        }
    }
}
Also used : Path(java.nio.file.Path) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) IndexSettings(org.elasticsearch.index.IndexSettings) Index(org.elasticsearch.index.Index) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 3 with Index

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

the class ShardSearchRequest method parseAliasFilter.

/**
     * Returns the filter associated with listed filtering aliases.
     * <p>
     * The list of filtering aliases should be obtained by calling MetaData.filteringAliases.
     * Returns <tt>null</tt> if no filtering is required.</p>
     */
static QueryBuilder parseAliasFilter(CheckedFunction<byte[], QueryBuilder, IOException> filterParser, IndexMetaData metaData, String... aliasNames) {
    if (aliasNames == null || aliasNames.length == 0) {
        return null;
    }
    Index index = metaData.getIndex();
    ImmutableOpenMap<String, AliasMetaData> aliases = metaData.getAliases();
    Function<AliasMetaData, QueryBuilder> parserFunction = (alias) -> {
        if (alias.filter() == null) {
            return null;
        }
        try {
            return filterParser.apply(alias.filter().uncompressed());
        } catch (IOException ex) {
            throw new AliasFilterParsingException(index, alias.getAlias(), "Invalid alias filter", ex);
        }
    };
    if (aliasNames.length == 1) {
        AliasMetaData alias = aliases.get(aliasNames[0]);
        if (alias == null) {
            // This shouldn't happen unless alias disappeared after filteringAliases was called.
            throw new InvalidAliasNameException(index, aliasNames[0], "Unknown alias name was passed to alias Filter");
        }
        return parserFunction.apply(alias);
    } else {
        // we need to bench here a bit, to see maybe it makes sense to use OrFilter
        BoolQueryBuilder combined = new BoolQueryBuilder();
        for (String aliasName : aliasNames) {
            AliasMetaData alias = aliases.get(aliasName);
            if (alias == null) {
                // This shouldn't happen unless alias disappeared after filteringAliases was called.
                throw new InvalidAliasNameException(index, aliasNames[0], "Unknown alias name was passed to alias Filter");
            }
            QueryBuilder parsedFilter = parserFunction.apply(alias);
            if (parsedFilter != null) {
                combined.should(parsedFilter);
            } else {
                // The filter might be null only if filter was removed after filteringAliases was called
                return null;
            }
        }
        return combined;
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) SearchType(org.elasticsearch.action.search.SearchType) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) AliasMetaData(org.elasticsearch.cluster.metadata.AliasMetaData) Scroll(org.elasticsearch.search.Scroll) IOException(java.io.IOException) Index(org.elasticsearch.index.Index) BytesReference(org.elasticsearch.common.bytes.BytesReference) Function(java.util.function.Function) CheckedFunction(org.elasticsearch.common.CheckedFunction) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) AliasFilterParsingException(org.elasticsearch.indices.AliasFilterParsingException) InvalidAliasNameException(org.elasticsearch.indices.InvalidAliasNameException) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) AliasMetaData(org.elasticsearch.cluster.metadata.AliasMetaData) AliasFilterParsingException(org.elasticsearch.indices.AliasFilterParsingException) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) Index(org.elasticsearch.index.Index) IOException(java.io.IOException) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) InvalidAliasNameException(org.elasticsearch.indices.InvalidAliasNameException)

Example 4 with Index

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

the class TransportReplicationActionTests method mockIndicesService.

final IndicesService mockIndicesService(ClusterService clusterService) {
    final IndicesService indicesService = mock(IndicesService.class);
    when(indicesService.indexServiceSafe(any(Index.class))).then(invocation -> {
        Index index = (Index) invocation.getArguments()[0];
        final ClusterState state = clusterService.state();
        final IndexMetaData indexSafe = state.metaData().getIndexSafe(index);
        return mockIndexService(indexSafe, clusterService);
    });
    when(indicesService.indexService(any(Index.class))).then(invocation -> {
        Index index = (Index) invocation.getArguments()[0];
        final ClusterState state = clusterService.state();
        if (state.metaData().hasIndex(index.getName())) {
            final IndexMetaData indexSafe = state.metaData().getIndexSafe(index);
            return mockIndexService(clusterService.state().metaData().getIndexSafe(index), clusterService);
        } else {
            return null;
        }
    });
    return indicesService;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndicesService(org.elasticsearch.indices.IndicesService) Index(org.elasticsearch.index.Index) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 5 with Index

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

the class OperationRoutingTests method testThatOnlyNodesSupportNodeIds.

public void testThatOnlyNodesSupportNodeIds() throws InterruptedException, IOException {
    TestThreadPool threadPool = null;
    ClusterService clusterService = null;
    try {
        threadPool = new TestThreadPool("testThatOnlyNodesSupportNodeIds");
        clusterService = ClusterServiceUtils.createClusterService(threadPool);
        final String indexName = "test";
        ClusterServiceUtils.setState(clusterService, ClusterStateCreationUtils.stateWithActivePrimary(indexName, true, randomInt(8)));
        final Index index = clusterService.state().metaData().index(indexName).getIndex();
        final List<ShardRouting> shards = clusterService.state().getRoutingNodes().assignedShards(new ShardId(index, 0));
        final int count = randomIntBetween(1, shards.size());
        int position = 0;
        final List<String> nodes = new ArrayList<>();
        final List<ShardRouting> expected = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            if (randomBoolean() && !shards.get(position).initializing()) {
                nodes.add(shards.get(position).currentNodeId());
                expected.add(shards.get(position));
                position++;
            } else {
                nodes.add("missing_" + i);
            }
        }
        if (expected.size() > 0) {
            final ShardIterator it = new OperationRouting(Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)).getShards(clusterService.state(), indexName, 0, "_only_nodes:" + String.join(",", nodes));
            final List<ShardRouting> only = new ArrayList<>();
            ShardRouting shard;
            while ((shard = it.nextOrNull()) != null) {
                only.add(shard);
            }
            assertThat(new HashSet<>(only), equalTo(new HashSet<>(expected)));
        } else {
            final ClusterService cs = clusterService;
            final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new OperationRouting(Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)).getShards(cs.state(), indexName, 0, "_only_nodes:" + String.join(",", nodes)));
            if (nodes.size() == 1) {
                assertThat(e, hasToString(containsString("no data nodes with criteria [" + String.join(",", nodes) + "] found for shard: [test][0]")));
            } else {
                assertThat(e, hasToString(containsString("no data nodes with criterion [" + String.join(",", nodes) + "] found for shard: [test][0]")));
            }
        }
    } finally {
        IOUtils.close(clusterService);
        terminate(threadPool);
    }
}
Also used : ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) ArrayList(java.util.ArrayList) Index(org.elasticsearch.index.Index) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) HasToString.hasToString(org.hamcrest.object.HasToString.hasToString) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) ShardId(org.elasticsearch.index.shard.ShardId) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashSet(java.util.HashSet)

Aggregations

Index (org.elasticsearch.index.Index)366 ShardId (org.elasticsearch.index.shard.ShardId)108 Settings (org.elasticsearch.common.settings.Settings)95 ClusterState (org.elasticsearch.cluster.ClusterState)88 ArrayList (java.util.ArrayList)79 IOException (java.io.IOException)74 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)65 IndexMetadata (org.elasticsearch.cluster.metadata.IndexMetadata)65 HashMap (java.util.HashMap)61 Map (java.util.Map)61 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)59 List (java.util.List)56 HashSet (java.util.HashSet)50 Path (java.nio.file.Path)45 IndexSettings (org.elasticsearch.index.IndexSettings)44 IndexService (org.elasticsearch.index.IndexService)43 Set (java.util.Set)40 Metadata (org.elasticsearch.cluster.metadata.Metadata)39 ClusterService (org.elasticsearch.cluster.service.ClusterService)39 ActionListener (org.elasticsearch.action.ActionListener)35