Search in sources :

Example 51 with BytesArray

use of org.elasticsearch.common.bytes.BytesArray in project elasticsearch by elastic.

the class InternalEngineTests method testRecoverFromForeignTranslog.

public void testRecoverFromForeignTranslog() throws IOException {
    final int numDocs = randomIntBetween(1, 10);
    for (int i = 0; i < numDocs; i++) {
        ParsedDocument doc = testParsedDocument(Integer.toString(i), "test", null, testDocument(), new BytesArray("{}"), null);
        Engine.Index firstIndexRequest = new Engine.Index(newUid(doc), doc, SequenceNumbersService.UNASSIGNED_SEQ_NO, 0, Versions.MATCH_DELETED, VersionType.INTERNAL, PRIMARY, System.nanoTime(), -1, false);
        Engine.IndexResult index = engine.index(firstIndexRequest);
        assertThat(index.getVersion(), equalTo(1L));
    }
    engine.refresh("test");
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), randomIntBetween(numDocs, numDocs + 10));
        assertThat(topDocs.totalHits, equalTo(numDocs));
    }
    Translog.TranslogGeneration generation = engine.getTranslog().getGeneration();
    engine.close();
    Translog translog = new Translog(new TranslogConfig(shardId, createTempDir(), INDEX_SETTINGS, BigArrays.NON_RECYCLING_INSTANCE), null, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
    translog.add(new Translog.Index("test", "SomeBogusId", "{}".getBytes(Charset.forName("UTF-8"))));
    assertEquals(generation.translogFileGeneration, translog.currentFileGeneration());
    translog.close();
    EngineConfig config = engine.config();
    /* create a TranslogConfig that has been created with a different UUID */
    TranslogConfig translogConfig = new TranslogConfig(shardId, translog.location(), config.getIndexSettings(), BigArrays.NON_RECYCLING_INSTANCE);
    EngineConfig brokenConfig = new EngineConfig(EngineConfig.OpenMode.OPEN_INDEX_AND_TRANSLOG, shardId, threadPool, config.getIndexSettings(), null, store, createSnapshotDeletionPolicy(), newMergePolicy(), config.getAnalyzer(), config.getSimilarity(), new CodecService(null, logger), config.getEventListener(), config.getTranslogRecoveryPerformer(), IndexSearcher.getDefaultQueryCache(), IndexSearcher.getDefaultQueryCachingPolicy(), translogConfig, TimeValue.timeValueMinutes(5), config.getRefreshListeners(), IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP);
    try {
        InternalEngine internalEngine = new InternalEngine(brokenConfig);
        fail("translog belongs to a different engine");
    } catch (EngineCreationFailureException ex) {
    }
    // and recover again!
    engine = createEngine(store, primaryTranslogDir);
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), randomIntBetween(numDocs, numDocs + 10));
        assertThat(topDocs.totalHits, equalTo(numDocs));
    }
}
Also used : Searcher(org.elasticsearch.index.engine.Engine.Searcher) BytesArray(org.elasticsearch.common.bytes.BytesArray) TranslogConfig(org.elasticsearch.index.translog.TranslogConfig) Index(org.elasticsearch.index.Index) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) LongPoint(org.apache.lucene.document.LongPoint) Translog(org.elasticsearch.index.translog.Translog) TopDocs(org.apache.lucene.search.TopDocs) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) CodecService(org.elasticsearch.index.codec.CodecService)

Example 52 with BytesArray

use of org.elasticsearch.common.bytes.BytesArray in project elasticsearch by elastic.

the class InternalEngineTests method testTranslogReplay.

public void testTranslogReplay() throws IOException {
    final int numDocs = randomIntBetween(1, 10);
    for (int i = 0; i < numDocs; i++) {
        ParsedDocument doc = testParsedDocument(Integer.toString(i), "test", null, testDocument(), new BytesArray("{}"), null);
        Engine.Index firstIndexRequest = new Engine.Index(newUid(doc), doc, SequenceNumbersService.UNASSIGNED_SEQ_NO, 0, Versions.MATCH_DELETED, VersionType.INTERNAL, PRIMARY, System.nanoTime(), -1, false);
        Engine.IndexResult indexResult = engine.index(firstIndexRequest);
        assertThat(indexResult.getVersion(), equalTo(1L));
    }
    engine.refresh("test");
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), randomIntBetween(numDocs, numDocs + 10));
        assertThat(topDocs.totalHits, equalTo(numDocs));
    }
    TranslogHandler parser = (TranslogHandler) engine.config().getTranslogRecoveryPerformer();
    parser.mappingUpdate = dynamicUpdate();
    engine.close();
    // we need to reuse the engine config unless the parser.mappingModified won't work
    engine = new InternalEngine(copy(engine.config(), EngineConfig.OpenMode.OPEN_INDEX_AND_TRANSLOG));
    engine.recoverFromTranslog();
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), randomIntBetween(numDocs, numDocs + 10));
        assertThat(topDocs.totalHits, equalTo(numDocs));
    }
    parser = (TranslogHandler) engine.config().getTranslogRecoveryPerformer();
    assertEquals(numDocs, parser.recoveredOps.get());
    if (parser.mappingUpdate != null) {
        assertEquals(1, parser.getRecoveredTypes().size());
        assertTrue(parser.getRecoveredTypes().containsKey("test"));
    } else {
        assertEquals(0, parser.getRecoveredTypes().size());
    }
    engine.close();
    engine = createEngine(store, primaryTranslogDir);
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), randomIntBetween(numDocs, numDocs + 10));
        assertThat(topDocs.totalHits, equalTo(numDocs));
    }
    parser = (TranslogHandler) engine.config().getTranslogRecoveryPerformer();
    assertEquals(0, parser.recoveredOps.get());
    final boolean flush = randomBoolean();
    int randomId = randomIntBetween(numDocs + 1, numDocs + 10);
    ParsedDocument doc = testParsedDocument(Integer.toString(randomId), "test", null, testDocument(), new BytesArray("{}"), null);
    Engine.Index firstIndexRequest = new Engine.Index(newUid(doc), doc, SequenceNumbersService.UNASSIGNED_SEQ_NO, 0, 1, VersionType.EXTERNAL, PRIMARY, System.nanoTime(), -1, false);
    Engine.IndexResult indexResult = engine.index(firstIndexRequest);
    assertThat(indexResult.getVersion(), equalTo(1L));
    if (flush) {
        engine.flush();
    }
    doc = testParsedDocument(Integer.toString(randomId), "test", null, testDocument(), new BytesArray("{}"), null);
    Engine.Index idxRequest = new Engine.Index(newUid(doc), doc, SequenceNumbersService.UNASSIGNED_SEQ_NO, 0, 2, VersionType.EXTERNAL, PRIMARY, System.nanoTime(), -1, false);
    Engine.IndexResult result = engine.index(idxRequest);
    engine.refresh("test");
    assertThat(result.getVersion(), equalTo(2L));
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), numDocs + 1);
        assertThat(topDocs.totalHits, equalTo(numDocs + 1));
    }
    engine.close();
    engine = createEngine(store, primaryTranslogDir);
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), numDocs + 1);
        assertThat(topDocs.totalHits, equalTo(numDocs + 1));
    }
    parser = (TranslogHandler) engine.config().getTranslogRecoveryPerformer();
    assertEquals(flush ? 1 : 2, parser.recoveredOps.get());
    engine.delete(new Engine.Delete("test", Integer.toString(randomId), newUid(doc)));
    if (randomBoolean()) {
        engine.refresh("test");
    } else {
        engine.close();
        engine = createEngine(store, primaryTranslogDir);
    }
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), numDocs);
        assertThat(topDocs.totalHits, equalTo(numDocs));
    }
}
Also used : Searcher(org.elasticsearch.index.engine.Engine.Searcher) BytesArray(org.elasticsearch.common.bytes.BytesArray) Index(org.elasticsearch.index.Index) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) LongPoint(org.apache.lucene.document.LongPoint) TopDocs(org.apache.lucene.search.TopDocs) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument)

Example 53 with BytesArray

use of org.elasticsearch.common.bytes.BytesArray in project elasticsearch by elastic.

the class InternalEngineTests method testAppendConcurrently.

public void testAppendConcurrently() throws InterruptedException, IOException {
    Thread[] thread = new Thread[randomIntBetween(3, 5)];
    int numDocs = randomIntBetween(1000, 10000);
    assertEquals(0, engine.getNumVersionLookups());
    assertEquals(0, engine.getNumIndexVersionsLookups());
    List<Engine.Index> docs = new ArrayList<>();
    for (int i = 0; i < numDocs; i++) {
        final ParsedDocument doc = testParsedDocument(Integer.toString(i), "test", null, testDocumentWithTextField(), new BytesArray("{}".getBytes(Charset.defaultCharset())), null);
        Engine.Index index = randomAppendOnly(doc, false, i);
        docs.add(index);
    }
    Collections.shuffle(docs, random());
    CountDownLatch startGun = new CountDownLatch(thread.length);
    AtomicInteger offset = new AtomicInteger(-1);
    for (int i = 0; i < thread.length; i++) {
        thread[i] = new Thread() {

            @Override
            public void run() {
                startGun.countDown();
                try {
                    startGun.await();
                } catch (InterruptedException e) {
                    throw new AssertionError(e);
                }
                int docOffset;
                while ((docOffset = offset.incrementAndGet()) < docs.size()) {
                    try {
                        engine.index(docs.get(docOffset));
                    } catch (IOException e) {
                        throw new AssertionError(e);
                    }
                }
            }
        };
        thread[i].start();
    }
    for (int i = 0; i < thread.length; i++) {
        thread[i].join();
    }
    engine.refresh("test");
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), 10);
        assertEquals(docs.size(), topDocs.totalHits);
    }
    assertEquals(0, engine.getNumVersionLookups());
    assertEquals(0, engine.getNumIndexVersionsLookups());
    assertFalse(engine.indexWriterHasDeletions());
}
Also used : Searcher(org.elasticsearch.index.engine.Engine.Searcher) BytesArray(org.elasticsearch.common.bytes.BytesArray) ArrayList(java.util.ArrayList) Index(org.elasticsearch.index.Index) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) LongPoint(org.apache.lucene.document.LongPoint) TopDocs(org.apache.lucene.search.TopDocs) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 54 with BytesArray

use of org.elasticsearch.common.bytes.BytesArray in project elasticsearch by elastic.

the class InternalEngineTests method testRetryWithAutogeneratedIdsAndWrongOrderWorksAndNoDuplicateDocs.

public void testRetryWithAutogeneratedIdsAndWrongOrderWorksAndNoDuplicateDocs() throws IOException {
    final ParsedDocument doc = testParsedDocument("1", "test", null, testDocumentWithTextField(), new BytesArray("{}".getBytes(Charset.defaultCharset())), null);
    boolean isRetry = true;
    long autoGeneratedIdTimestamp = 0;
    Engine.Index firstIndexRequest = new Engine.Index(newUid(doc), doc, SequenceNumbersService.UNASSIGNED_SEQ_NO, 0, Versions.MATCH_ANY, VersionType.INTERNAL, PRIMARY, System.nanoTime(), autoGeneratedIdTimestamp, isRetry);
    Engine.IndexResult result = engine.index(firstIndexRequest);
    assertThat(result.getVersion(), equalTo(1L));
    Engine.Index firstIndexRequestReplica = new Engine.Index(newUid(doc), doc, result.getSeqNo(), firstIndexRequest.primaryTerm(), result.getVersion(), firstIndexRequest.versionType().versionTypeForReplicationAndRecovery(), REPLICA, System.nanoTime(), autoGeneratedIdTimestamp, isRetry);
    Engine.IndexResult indexReplicaResult = replicaEngine.index(firstIndexRequestReplica);
    assertThat(indexReplicaResult.getVersion(), equalTo(1L));
    isRetry = false;
    Engine.Index secondIndexRequest = new Engine.Index(newUid(doc), doc, SequenceNumbersService.UNASSIGNED_SEQ_NO, 0, Versions.MATCH_ANY, VersionType.INTERNAL, PRIMARY, System.nanoTime(), autoGeneratedIdTimestamp, isRetry);
    Engine.IndexResult indexResult = engine.index(secondIndexRequest);
    assertTrue(indexResult.isCreated());
    engine.refresh("test");
    try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), 10);
        assertEquals(1, topDocs.totalHits);
    }
    Engine.Index secondIndexRequestReplica = new Engine.Index(newUid(doc), doc, result.getSeqNo(), secondIndexRequest.primaryTerm(), result.getVersion(), firstIndexRequest.versionType().versionTypeForReplicationAndRecovery(), REPLICA, System.nanoTime(), autoGeneratedIdTimestamp, isRetry);
    replicaEngine.index(secondIndexRequestReplica);
    replicaEngine.refresh("test");
    try (Engine.Searcher searcher = replicaEngine.acquireSearcher("test")) {
        TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), 10);
        assertEquals(1, topDocs.totalHits);
    }
}
Also used : Searcher(org.elasticsearch.index.engine.Engine.Searcher) TopDocs(org.apache.lucene.search.TopDocs) BytesArray(org.elasticsearch.common.bytes.BytesArray) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) Index(org.elasticsearch.index.Index) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery)

Example 55 with BytesArray

use of org.elasticsearch.common.bytes.BytesArray in project elasticsearch by elastic.

the class DocumentMapperMergeTests method testConcurrentMergeTest.

public void testConcurrentMergeTest() throws Throwable {
    final MapperService mapperService = createIndex("test").mapperService();
    mapperService.merge("test", new CompressedXContent("{\"test\":{}}"), MapperService.MergeReason.MAPPING_UPDATE, false);
    final DocumentMapper documentMapper = mapperService.documentMapper("test");
    DocumentFieldMappers dfm = documentMapper.mappers();
    try {
        assertNotNull(dfm.indexAnalyzer().tokenStream("non_existing_field", "foo"));
        fail();
    } catch (IllegalArgumentException e) {
    // ok that's expected
    }
    final AtomicBoolean stopped = new AtomicBoolean(false);
    final CyclicBarrier barrier = new CyclicBarrier(2);
    final AtomicReference<String> lastIntroducedFieldName = new AtomicReference<>();
    final AtomicReference<Exception> error = new AtomicReference<>();
    final Thread updater = new Thread() {

        @Override
        public void run() {
            try {
                barrier.await();
                for (int i = 0; i < 200 && stopped.get() == false; i++) {
                    final String fieldName = Integer.toString(i);
                    ParsedDocument doc = documentMapper.parse("test", "test", fieldName, new BytesArray("{ \"" + fieldName + "\" : \"test\" }"));
                    Mapping update = doc.dynamicMappingsUpdate();
                    assert update != null;
                    lastIntroducedFieldName.set(fieldName);
                    mapperService.merge("test", new CompressedXContent(update.toString()), MapperService.MergeReason.MAPPING_UPDATE, false);
                }
            } catch (Exception e) {
                error.set(e);
            } finally {
                stopped.set(true);
            }
        }
    };
    updater.start();
    try {
        barrier.await();
        while (stopped.get() == false) {
            final String fieldName = lastIntroducedFieldName.get();
            final BytesReference source = new BytesArray("{ \"" + fieldName + "\" : \"test\" }");
            ParsedDocument parsedDoc = documentMapper.parse("test", "test", "random", source);
            if (parsedDoc.dynamicMappingsUpdate() != null) {
                // not in the mapping yet, try again
                continue;
            }
            dfm = documentMapper.mappers();
            assertNotNull(dfm.indexAnalyzer().tokenStream(fieldName, "foo"));
        }
    } finally {
        stopped.set(true);
        updater.join();
    }
    if (error.get() != null) {
        throw error.get();
    }
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) BytesArray(org.elasticsearch.common.bytes.BytesArray) DocumentFieldMappers(org.elasticsearch.index.mapper.DocumentFieldMappers) DocumentMapper(org.elasticsearch.index.mapper.DocumentMapper) AtomicReference(java.util.concurrent.atomic.AtomicReference) Mapping(org.elasticsearch.index.mapper.Mapping) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) CompressedXContent(org.elasticsearch.common.compress.CompressedXContent) MapperService(org.elasticsearch.index.mapper.MapperService)

Aggregations

BytesArray (org.elasticsearch.common.bytes.BytesArray)203 BytesReference (org.elasticsearch.common.bytes.BytesReference)36 Matchers.containsString (org.hamcrest.Matchers.containsString)31 IOException (java.io.IOException)29 StreamInput (org.elasticsearch.common.io.stream.StreamInput)24 ParsedDocument (org.elasticsearch.index.mapper.ParsedDocument)24 BytesStreamOutput (org.elasticsearch.common.io.stream.BytesStreamOutput)21 HashMap (java.util.HashMap)17 BytesRef (org.apache.lucene.util.BytesRef)17 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)14 CompressedXContent (org.elasticsearch.common.compress.CompressedXContent)14 FakeRestRequest (org.elasticsearch.test.rest.FakeRestRequest)13 ArrayList (java.util.ArrayList)12 TopDocs (org.apache.lucene.search.TopDocs)12 SearchResponse (org.elasticsearch.action.search.SearchResponse)12 Document (org.elasticsearch.index.mapper.ParseContext.Document)12 Index (org.elasticsearch.index.Index)11 Map (java.util.Map)10 IndexableField (org.apache.lucene.index.IndexableField)10 IndexService (org.elasticsearch.index.IndexService)10