Search in sources :

Example 6 with IndicesFieldDataCache

use of org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache in project elasticsearch by elastic.

the class RandomExceptionCircuitBreakerIT method testBreakerWithRandomExceptions.

public void testBreakerWithRandomExceptions() throws IOException, InterruptedException, ExecutionException {
    for (NodeStats node : client().admin().cluster().prepareNodesStats().clear().setBreaker(true).execute().actionGet().getNodes()) {
        assertThat("Breaker is not set to 0", node.getBreaker().getStats(CircuitBreaker.FIELDDATA).getEstimated(), equalTo(0L));
    }
    String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties").startObject("test-str").field("type", "keyword").field("doc_values", randomBoolean()).endObject().startObject("test-num").field("type", randomFrom(Arrays.asList("float", "long", "double", "short", "integer"))).endObject().endObject().endObject().endObject().string();
    final double topLevelRate;
    final double lowLevelRate;
    if (frequently()) {
        if (randomBoolean()) {
            if (randomBoolean()) {
                lowLevelRate = 1.0 / between(2, 10);
                topLevelRate = 0.0d;
            } else {
                topLevelRate = 1.0 / between(2, 10);
                lowLevelRate = 0.0d;
            }
        } else {
            lowLevelRate = 1.0 / between(2, 10);
            topLevelRate = 1.0 / between(2, 10);
        }
    } else {
        // rarely no exception
        topLevelRate = 0d;
        lowLevelRate = 0d;
    }
    Settings.Builder settings = Settings.builder().put(indexSettings()).put(EXCEPTION_TOP_LEVEL_RATIO_KEY, topLevelRate).put(EXCEPTION_LOW_LEVEL_RATIO_KEY, lowLevelRate).put(MockEngineSupport.WRAP_READER_RATIO.getKey(), 1.0d);
    logger.info("creating index: [test] using settings: [{}]", settings.build().getAsMap());
    CreateIndexResponse response = client().admin().indices().prepareCreate("test").setSettings(settings).addMapping("type", mapping, XContentType.JSON).execute().actionGet();
    final int numDocs;
    if (response.isShardsAcked() == false) {
        /* some seeds just won't let you create the index at all and we enter a ping-pong mode
             * trying one node after another etc. that is ok but we need to make sure we don't wait
             * forever when indexing documents so we set numDocs = 1 and expect all shards to fail
             * when we search below.*/
        if (response.isAcknowledged()) {
            logger.info("Index creation timed out waiting for primaries to start - only index one doc and expect searches to fail");
        } else {
            logger.info("Index creation failed - only index one doc and expect searches to fail");
        }
        numDocs = 1;
    } else {
        numDocs = between(10, 100);
    }
    for (int i = 0; i < numDocs; i++) {
        try {
            client().prepareIndex("test", "type", "" + i).setTimeout(TimeValue.timeValueSeconds(1)).setSource("test-str", randomUnicodeOfLengthBetween(5, 25), "test-num", i).get();
        } catch (ElasticsearchException ex) {
        }
    }
    logger.info("Start Refresh");
    // don't assert on failures here
    RefreshResponse refreshResponse = client().admin().indices().prepareRefresh("test").execute().get();
    final boolean refreshFailed = refreshResponse.getShardFailures().length != 0 || refreshResponse.getFailedShards() != 0;
    logger.info("Refresh failed: [{}] numShardsFailed: [{}], shardFailuresLength: [{}], successfulShards: [{}], totalShards: [{}] ", refreshFailed, refreshResponse.getFailedShards(), refreshResponse.getShardFailures().length, refreshResponse.getSuccessfulShards(), refreshResponse.getTotalShards());
    final int numSearches = scaledRandomIntBetween(50, 150);
    NodesStatsResponse resp = client().admin().cluster().prepareNodesStats().clear().setBreaker(true).execute().actionGet();
    for (NodeStats stats : resp.getNodes()) {
        assertThat("Breaker is set to 0", stats.getBreaker().getStats(CircuitBreaker.FIELDDATA).getEstimated(), equalTo(0L));
    }
    for (int i = 0; i < numSearches; i++) {
        SearchRequestBuilder searchRequestBuilder = client().prepareSearch().setQuery(QueryBuilders.matchAllQuery());
        if (random().nextBoolean()) {
            searchRequestBuilder.addSort("test-str", SortOrder.ASC);
        }
        searchRequestBuilder.addSort("test-num", SortOrder.ASC);
        boolean success = false;
        try {
            // Sort by the string and numeric fields, to load them into field data
            searchRequestBuilder.get();
            success = true;
        } catch (SearchPhaseExecutionException ex) {
            logger.info("expected SearchPhaseException: [{}]", ex.getMessage());
        }
        if (frequently()) {
            // Now, clear the cache and check that the circuit breaker has been
            // successfully set back to zero. If there is a bug in the circuit
            // breaker adjustment code, it should show up here by the breaker
            // estimate being either positive or negative.
            // make sure all shards are there - there could be shards that are still starting up.
            ensureGreen("test");
            assertAllSuccessful(client().admin().indices().prepareClearCache("test").setFieldDataCache(true).execute().actionGet());
            // Since .cleanUp() is no longer called on cache clear, we need to call it on each node manually
            for (String node : internalCluster().getNodeNames()) {
                final IndicesFieldDataCache fdCache = internalCluster().getInstance(IndicesService.class, node).getIndicesFieldDataCache();
                // Clean up the cache, ensuring that entries' listeners have been called
                fdCache.getCache().refresh();
            }
            NodesStatsResponse nodeStats = client().admin().cluster().prepareNodesStats().clear().setBreaker(true).execute().actionGet();
            for (NodeStats stats : nodeStats.getNodes()) {
                assertThat("Breaker reset to 0 last search success: " + success + " mapping: " + mapping, stats.getBreaker().getStats(CircuitBreaker.FIELDDATA).getEstimated(), equalTo(0L));
            }
        }
    }
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) IndicesService(org.elasticsearch.indices.IndicesService) ElasticsearchException(org.elasticsearch.ElasticsearchException) NodesStatsResponse(org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse) NodeStats(org.elasticsearch.action.admin.cluster.node.stats.NodeStats) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) RefreshResponse(org.elasticsearch.action.admin.indices.refresh.RefreshResponse) CreateIndexResponse(org.elasticsearch.action.admin.indices.create.CreateIndexResponse) Settings(org.elasticsearch.common.settings.Settings)

Example 7 with IndicesFieldDataCache

use of org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache in project elasticsearch by elastic.

the class IndexShardTestCase method newShard.

/**
     * creates a new initializing shard.
     *
     * @param routing              shard routing to use
     * @param shardPath            path to use for shard data
     * @param indexMetaData        indexMetaData for the shard, including any mapping
     * @param indexSearcherWrapper an optional wrapper to be used during searchers
     * @param listeners            an optional set of listeners to add to the shard
     */
protected IndexShard newShard(ShardRouting routing, ShardPath shardPath, IndexMetaData indexMetaData, @Nullable IndexSearcherWrapper indexSearcherWrapper, Runnable globalCheckpointSyncer, @Nullable EngineFactory engineFactory, IndexingOperationListener... listeners) throws IOException {
    final Settings nodeSettings = Settings.builder().put("node.name", routing.currentNodeId()).build();
    final IndexSettings indexSettings = new IndexSettings(indexMetaData, nodeSettings);
    final IndexShard indexShard;
    final Store store = createStore(indexSettings, shardPath);
    boolean success = false;
    try {
        IndexCache indexCache = new IndexCache(indexSettings, new DisabledQueryCache(indexSettings), null);
        MapperService mapperService = MapperTestUtils.newMapperService(xContentRegistry(), createTempDir(), indexSettings.getSettings());
        mapperService.merge(indexMetaData, MapperService.MergeReason.MAPPING_RECOVERY, true);
        SimilarityService similarityService = new SimilarityService(indexSettings, Collections.emptyMap());
        final IndexEventListener indexEventListener = new IndexEventListener() {
        };
        final Engine.Warmer warmer = searcher -> {
        };
        IndicesFieldDataCache indicesFieldDataCache = new IndicesFieldDataCache(nodeSettings, new IndexFieldDataCache.Listener() {
        });
        IndexFieldDataService indexFieldDataService = new IndexFieldDataService(indexSettings, indicesFieldDataCache, new NoneCircuitBreakerService(), mapperService);
        indexShard = new IndexShard(routing, indexSettings, shardPath, store, indexCache, mapperService, similarityService, indexFieldDataService, engineFactory, indexEventListener, indexSearcherWrapper, threadPool, BigArrays.NON_RECYCLING_INSTANCE, warmer, globalCheckpointSyncer, Collections.emptyList(), Arrays.asList(listeners));
        success = true;
    } finally {
        if (success == false) {
            IOUtils.close(store);
        }
    }
    return indexShard;
}
Also used : IndexNotFoundException(org.apache.lucene.index.IndexNotFoundException) Versions(org.elasticsearch.common.lucene.uid.Versions) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) Arrays(java.util.Arrays) Nullable(org.elasticsearch.common.Nullable) BigArrays(org.elasticsearch.common.util.BigArrays) BiFunction(java.util.function.BiFunction) VersionType(org.elasticsearch.index.VersionType) Document(org.apache.lucene.document.Document) IndexRequest(org.elasticsearch.action.index.IndexRequest) Settings(org.elasticsearch.common.settings.Settings) ShardRoutingHelper(org.elasticsearch.cluster.routing.ShardRoutingHelper) Directory(org.apache.lucene.store.Directory) ThreadPool(org.elasticsearch.threadpool.ThreadPool) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) UidFieldMapper(org.elasticsearch.index.mapper.UidFieldMapper) EnumSet(java.util.EnumSet) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) Set(java.util.Set) MapperTestUtils(org.elasticsearch.index.MapperTestUtils) Engine(org.elasticsearch.index.engine.Engine) SimilarityService(org.elasticsearch.index.similarity.SimilarityService) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) MapperService(org.elasticsearch.index.mapper.MapperService) Version(org.elasticsearch.Version) Matchers.contains(org.hamcrest.Matchers.contains) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) LeafReader(org.apache.lucene.index.LeafReader) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) StartRecoveryRequest(org.elasticsearch.indices.recovery.StartRecoveryRequest) XContentType(org.elasticsearch.common.xcontent.XContentType) IndexFieldDataService(org.elasticsearch.index.fielddata.IndexFieldDataService) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) DisabledQueryCache(org.elasticsearch.index.cache.query.DisabledQueryCache) BytesArray(org.elasticsearch.common.bytes.BytesArray) RecoverySourceHandler(org.elasticsearch.indices.recovery.RecoverySourceHandler) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) IndexCache(org.elasticsearch.index.cache.IndexCache) SequenceNumbersService(org.elasticsearch.index.seqno.SequenceNumbersService) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) Store(org.elasticsearch.index.store.Store) IndexSettings(org.elasticsearch.index.IndexSettings) Node(org.elasticsearch.node.Node) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ESTestCase(org.elasticsearch.test.ESTestCase) Bits(org.apache.lucene.util.Bits) SourceToParse(org.elasticsearch.index.mapper.SourceToParse) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) IndexFieldDataCache(org.elasticsearch.index.fielddata.IndexFieldDataCache) Uid(org.elasticsearch.index.mapper.Uid) RecoveryTarget(org.elasticsearch.indices.recovery.RecoveryTarget) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) DirectoryService(org.elasticsearch.index.store.DirectoryService) EngineFactory(org.elasticsearch.index.engine.EngineFactory) TimeUnit(java.util.concurrent.TimeUnit) FlushRequest(org.elasticsearch.action.admin.indices.flush.FlushRequest) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) DummyShardLock(org.elasticsearch.test.DummyShardLock) Collections(java.util.Collections) IndexSettings(org.elasticsearch.index.IndexSettings) Store(org.elasticsearch.index.store.Store) IndexFieldDataCache(org.elasticsearch.index.fielddata.IndexFieldDataCache) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) IndexFieldDataService(org.elasticsearch.index.fielddata.IndexFieldDataService) IndexCache(org.elasticsearch.index.cache.IndexCache) SimilarityService(org.elasticsearch.index.similarity.SimilarityService) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) DisabledQueryCache(org.elasticsearch.index.cache.query.DisabledQueryCache) MapperService(org.elasticsearch.index.mapper.MapperService) Engine(org.elasticsearch.index.engine.Engine) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService)

Aggregations

IndicesFieldDataCache (org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache)7 IndexSettings (org.elasticsearch.index.IndexSettings)3 IndexFieldDataService (org.elasticsearch.index.fielddata.IndexFieldDataService)3 IOException (java.io.IOException)2 ElasticsearchException (org.elasticsearch.ElasticsearchException)2 NodeStats (org.elasticsearch.action.admin.cluster.node.stats.NodeStats)2 Settings (org.elasticsearch.common.settings.Settings)2 IndexFieldDataCache (org.elasticsearch.index.fielddata.IndexFieldDataCache)2 IndicesService (org.elasticsearch.indices.IndicesService)2 Closeable (java.io.Closeable)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 EnumSet (java.util.EnumSet)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeUnit (java.util.concurrent.TimeUnit)1 BiFunction (java.util.function.BiFunction)1 Document (org.apache.lucene.document.Document)1