Search in sources :

Example 1 with IndexOutputOutputStream

use of org.elasticsearch.common.lucene.store.IndexOutputOutputStream in project elasticsearch by elastic.

the class ChecksumBlobStoreFormat method writeBlob.

/**
     * Writes blob in atomic manner without resolving the blobName using using {@link #blobName} method.
     * <p>
     * The blob will be compressed and checksum will be written if required.
     *
     * @param obj           object to be serialized
     * @param blobContainer blob container
     * @param blobName          blob name
     */
protected void writeBlob(T obj, BlobContainer blobContainer, String blobName) throws IOException {
    BytesReference bytes = write(obj);
    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
        final String resourceDesc = "ChecksumBlobStoreFormat.writeBlob(blob=\"" + blobName + "\")";
        try (OutputStreamIndexOutput indexOutput = new OutputStreamIndexOutput(resourceDesc, blobName, byteArrayOutputStream, BUFFER_SIZE)) {
            CodecUtil.writeHeader(indexOutput, codec, VERSION);
            try (OutputStream indexOutputOutputStream = new IndexOutputOutputStream(indexOutput) {

                @Override
                public void close() throws IOException {
                // this is important since some of the XContentBuilders write bytes on close.
                // in order to write the footer we need to prevent closing the actual index input.
                }
            }) {
                bytes.writeTo(indexOutputOutputStream);
            }
            CodecUtil.writeFooter(indexOutput);
        }
        BytesArray bytesArray = new BytesArray(byteArrayOutputStream.toByteArray());
        try (InputStream stream = bytesArray.streamInput()) {
            blobContainer.writeBlob(blobName, stream, bytesArray.length());
        }
    }
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) BytesArray(org.elasticsearch.common.bytes.BytesArray) OutputStreamIndexOutput(org.apache.lucene.store.OutputStreamIndexOutput) IndexOutputOutputStream(org.elasticsearch.common.lucene.store.IndexOutputOutputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) IndexOutputOutputStream(org.elasticsearch.common.lucene.store.IndexOutputOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 2 with IndexOutputOutputStream

use of org.elasticsearch.common.lucene.store.IndexOutputOutputStream in project crate by crate.

the class MetadataStateFormat method writeStateToFirstLocation.

private void writeStateToFirstLocation(final T state, Path stateLocation, Directory stateDir, String tmpFileName) throws WriteStateException {
    try {
        deleteFileIfExists(stateLocation, stateDir, tmpFileName);
        try (IndexOutput out = stateDir.createOutput(tmpFileName, IOContext.DEFAULT)) {
            CodecUtil.writeHeader(out, STATE_FILE_CODEC, STATE_FILE_VERSION);
            out.writeInt(FORMAT.index());
            try (XContentBuilder builder = newXContentBuilder(FORMAT, new IndexOutputOutputStream(out) {

                @Override
                public void close() {
                // this is important since some of the XContentBuilders write bytes on close.
                // in order to write the footer we need to prevent closing the actual index input.
                }
            })) {
                builder.startObject();
                toXContent(builder, state);
                builder.endObject();
            }
            CodecUtil.writeFooter(out);
        }
        stateDir.sync(Collections.singleton(tmpFileName));
    } catch (Exception e) {
        throw new WriteStateException(false, "failed to write state to the first location tmp file " + stateLocation.resolve(tmpFileName), e);
    }
}
Also used : IndexOutputOutputStream(org.elasticsearch.common.lucene.store.IndexOutputOutputStream) IndexOutput(org.apache.lucene.store.IndexOutput) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) NoSuchFileException(java.nio.file.NoSuchFileException) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) IOException(java.io.IOException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) FileNotFoundException(java.io.FileNotFoundException)

Example 3 with IndexOutputOutputStream

use of org.elasticsearch.common.lucene.store.IndexOutputOutputStream in project crate by crate.

the class RecoverySourceHandlerTests method generateFiles.

private List<StoreFileMetadata> generateFiles(Store store, int numFiles, IntSupplier fileSizeSupplier) throws IOException {
    List<StoreFileMetadata> files = new ArrayList<>();
    for (int i = 0; i < numFiles; i++) {
        byte[] buffer = randomByteArrayOfLength(fileSizeSupplier.getAsInt());
        CRC32 digest = new CRC32();
        digest.update(buffer, 0, buffer.length);
        StoreFileMetadata md = new StoreFileMetadata("test-" + i, buffer.length + 8, Store.digestToString(digest.getValue()), org.apache.lucene.util.Version.LATEST);
        try (OutputStream out = new IndexOutputOutputStream(store.createVerifyingOutput(md.name(), md, IOContext.DEFAULT))) {
            out.write(buffer);
            out.write(Numbers.longToBytes(digest.getValue()));
        }
        store.directory().sync(Collections.singleton(md.name()));
        files.add(md);
    }
    return files;
}
Also used : CRC32(java.util.zip.CRC32) IndexOutputOutputStream(org.elasticsearch.common.lucene.store.IndexOutputOutputStream) IndexOutputOutputStream(org.elasticsearch.common.lucene.store.IndexOutputOutputStream) OutputStream(java.io.OutputStream) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) StoreFileMetadata(org.elasticsearch.index.store.StoreFileMetadata)

Example 4 with IndexOutputOutputStream

use of org.elasticsearch.common.lucene.store.IndexOutputOutputStream in project elasticsearch by elastic.

the class RecoverySourceHandlerTests method testHandleCorruptedIndexOnSendSendFiles.

public void testHandleCorruptedIndexOnSendSendFiles() throws Throwable {
    Settings settings = Settings.builder().put("indices.recovery.concurrent_streams", 1).put("indices.recovery.concurrent_small_file_streams", 1).build();
    final RecoverySettings recoverySettings = new RecoverySettings(settings, service);
    final StartRecoveryRequest request = new StartRecoveryRequest(shardId, new DiscoveryNode("b", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT), new DiscoveryNode("b", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT), null, randomBoolean(), randomNonNegativeLong(), randomBoolean() ? SequenceNumbersService.UNASSIGNED_SEQ_NO : 0L);
    Path tempDir = createTempDir();
    Store store = newStore(tempDir, false);
    AtomicBoolean failedEngine = new AtomicBoolean(false);
    RecoverySourceHandler handler = new RecoverySourceHandler(null, null, request, () -> 0L, e -> () -> {
    }, recoverySettings.getChunkSize().bytesAsInt(), Settings.EMPTY) {

        @Override
        protected void failEngine(IOException cause) {
            assertFalse(failedEngine.get());
            failedEngine.set(true);
        }
    };
    Directory dir = store.directory();
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir, newIndexWriterConfig());
    int numDocs = randomIntBetween(10, 100);
    for (int i = 0; i < numDocs; i++) {
        Document document = new Document();
        document.add(new StringField("id", Integer.toString(i), Field.Store.YES));
        document.add(newField("field", randomUnicodeOfCodepointLengthBetween(1, 10), TextField.TYPE_STORED));
        writer.addDocument(document);
    }
    writer.commit();
    writer.close();
    Store.MetadataSnapshot metadata = store.getMetadata(null);
    List<StoreFileMetaData> metas = new ArrayList<>();
    for (StoreFileMetaData md : metadata) {
        metas.add(md);
    }
    CorruptionUtils.corruptFile(random(), FileSystemUtils.files(tempDir, (p) -> (p.getFileName().toString().equals("write.lock") || p.getFileName().toString().startsWith("extra")) == false));
    Store targetStore = newStore(createTempDir(), false);
    try {
        handler.sendFiles(store, metas.toArray(new StoreFileMetaData[0]), (md) -> {
            try {
                return new IndexOutputOutputStream(targetStore.createVerifyingOutput(md.name(), md, IOContext.DEFAULT)) {

                    @Override
                    public void close() throws IOException {
                        super.close();
                        // sync otherwise MDW will mess with it
                        store.directory().sync(Collections.singleton(md.name()));
                    }
                };
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        fail("corrupted index");
    } catch (IOException ex) {
        assertNotNull(ExceptionsHelper.unwrapCorruption(ex));
    }
    assertTrue(failedEngine.get());
    IOUtils.close(store, targetStore);
}
Also used : Path(java.nio.file.Path) ShardId(org.elasticsearch.index.shard.ShardId) Versions(org.elasticsearch.common.lucene.uid.Versions) Arrays(java.util.Arrays) IndexSettingsModule(org.elasticsearch.test.IndexSettingsModule) Term(org.apache.lucene.index.Term) ParseContext(org.elasticsearch.index.mapper.ParseContext) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) SeqNoStats(org.elasticsearch.index.seqno.SeqNoStats) Document(org.apache.lucene.document.Document) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) Settings(org.elasticsearch.common.settings.Settings) Directory(org.apache.lucene.store.Directory) Mockito.doAnswer(org.mockito.Mockito.doAnswer) UidFieldMapper(org.elasticsearch.index.mapper.UidFieldMapper) IOContext(org.apache.lucene.store.IOContext) Path(java.nio.file.Path) Releasable(org.elasticsearch.common.lease.Releasable) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) DirectoryReader(org.apache.lucene.index.DirectoryReader) BytesReference(org.elasticsearch.common.bytes.BytesReference) Engine(org.elasticsearch.index.engine.Engine) Matchers.any(org.mockito.Matchers.any) SeqNoFieldMapper(org.elasticsearch.index.mapper.SeqNoFieldMapper) List(java.util.List) Version(org.elasticsearch.Version) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexOutputOutputStream(org.elasticsearch.common.lucene.store.IndexOutputOutputStream) IndexReader(org.apache.lucene.index.IndexReader) Mockito.mock(org.mockito.Mockito.mock) IndexCommit(org.apache.lucene.index.IndexCommit) XContentType(org.elasticsearch.common.xcontent.XContentType) StringField(org.apache.lucene.document.StringField) IndexShardRelocatedException(org.elasticsearch.index.shard.IndexShardRelocatedException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SegmentsStats(org.elasticsearch.index.engine.SegmentsStats) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) BaseDirectoryWrapper(org.apache.lucene.store.BaseDirectoryWrapper) StoreFileMetaData(org.elasticsearch.index.store.StoreFileMetaData) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) SequenceNumbersService(org.elasticsearch.index.seqno.SequenceNumbersService) Store(org.elasticsearch.index.store.Store) IndexSettings(org.elasticsearch.index.IndexSettings) Mapping(org.elasticsearch.index.mapper.Mapping) ESTestCase(org.elasticsearch.test.ESTestCase) Collections.emptyMap(java.util.Collections.emptyMap) FileSystemUtils(org.elasticsearch.common.io.FileSystemUtils) IndexShardState(org.elasticsearch.index.shard.IndexShardState) CorruptionUtils(org.elasticsearch.test.CorruptionUtils) Uid(org.elasticsearch.index.mapper.Uid) Collections.emptySet(java.util.Collections.emptySet) IndexShard(org.elasticsearch.index.shard.IndexShard) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) Mockito.when(org.mockito.Mockito.when) DirectoryService(org.elasticsearch.index.store.DirectoryService) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) Field(org.apache.lucene.document.Field) Translog(org.elasticsearch.index.translog.Translog) TextField(org.apache.lucene.document.TextField) DummyShardLock(org.elasticsearch.test.DummyShardLock) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter) Collections(java.util.Collections) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) IndexOutputOutputStream(org.elasticsearch.common.lucene.store.IndexOutputOutputStream) ArrayList(java.util.ArrayList) Store(org.elasticsearch.index.store.Store) IOException(java.io.IOException) Document(org.apache.lucene.document.Document) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StoreFileMetaData(org.elasticsearch.index.store.StoreFileMetaData) StringField(org.apache.lucene.document.StringField) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter) Directory(org.apache.lucene.store.Directory)

Example 5 with IndexOutputOutputStream

use of org.elasticsearch.common.lucene.store.IndexOutputOutputStream in project elasticsearch by elastic.

the class RecoverySourceHandlerTests method testSendFiles.

public void testSendFiles() throws Throwable {
    Settings settings = Settings.builder().put("indices.recovery.concurrent_streams", 1).put("indices.recovery.concurrent_small_file_streams", 1).build();
    final RecoverySettings recoverySettings = new RecoverySettings(settings, service);
    final StartRecoveryRequest request = new StartRecoveryRequest(shardId, new DiscoveryNode("b", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT), new DiscoveryNode("b", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT), null, randomBoolean(), randomNonNegativeLong(), randomBoolean() ? SequenceNumbersService.UNASSIGNED_SEQ_NO : randomNonNegativeLong());
    Store store = newStore(createTempDir());
    RecoverySourceHandler handler = new RecoverySourceHandler(null, null, request, () -> 0L, e -> () -> {
    }, recoverySettings.getChunkSize().bytesAsInt(), Settings.EMPTY);
    Directory dir = store.directory();
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir, newIndexWriterConfig());
    int numDocs = randomIntBetween(10, 100);
    for (int i = 0; i < numDocs; i++) {
        Document document = new Document();
        document.add(new StringField("id", Integer.toString(i), Field.Store.YES));
        document.add(newField("field", randomUnicodeOfCodepointLengthBetween(1, 10), TextField.TYPE_STORED));
        writer.addDocument(document);
    }
    writer.commit();
    writer.close();
    Store.MetadataSnapshot metadata = store.getMetadata(null);
    List<StoreFileMetaData> metas = new ArrayList<>();
    for (StoreFileMetaData md : metadata) {
        metas.add(md);
    }
    Store targetStore = newStore(createTempDir());
    handler.sendFiles(store, metas.toArray(new StoreFileMetaData[0]), (md) -> {
        try {
            return new IndexOutputOutputStream(targetStore.createVerifyingOutput(md.name(), md, IOContext.DEFAULT)) {

                @Override
                public void close() throws IOException {
                    super.close();
                    // sync otherwise MDW will mess with it
                    targetStore.directory().sync(Collections.singleton(md.name()));
                }
            };
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
    Store.MetadataSnapshot targetStoreMetadata = targetStore.getMetadata(null);
    Store.RecoveryDiff recoveryDiff = targetStoreMetadata.recoveryDiff(metadata);
    assertEquals(metas.size(), recoveryDiff.identical.size());
    assertEquals(0, recoveryDiff.different.size());
    assertEquals(0, recoveryDiff.missing.size());
    IndexReader reader = DirectoryReader.open(targetStore.directory());
    assertEquals(numDocs, reader.maxDoc());
    IOUtils.close(reader, store, targetStore);
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) IndexOutputOutputStream(org.elasticsearch.common.lucene.store.IndexOutputOutputStream) ArrayList(java.util.ArrayList) Store(org.elasticsearch.index.store.Store) IOException(java.io.IOException) Document(org.apache.lucene.document.Document) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) StoreFileMetaData(org.elasticsearch.index.store.StoreFileMetaData) StringField(org.apache.lucene.document.StringField) IndexReader(org.apache.lucene.index.IndexReader) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter) Directory(org.apache.lucene.store.Directory)

Aggregations

IndexOutputOutputStream (org.elasticsearch.common.lucene.store.IndexOutputOutputStream)7 IOException (java.io.IOException)4 OutputStream (java.io.OutputStream)3 ArrayList (java.util.ArrayList)3 OutputStreamIndexOutput (org.apache.lucene.store.OutputStreamIndexOutput)3 BytesArray (org.elasticsearch.common.bytes.BytesArray)3 BytesReference (org.elasticsearch.common.bytes.BytesReference)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 Path (java.nio.file.Path)2 Document (org.apache.lucene.document.Document)2 StringField (org.apache.lucene.document.StringField)2 CorruptIndexException (org.apache.lucene.index.CorruptIndexException)2 IndexReader (org.apache.lucene.index.IndexReader)2 RandomIndexWriter (org.apache.lucene.index.RandomIndexWriter)2 Directory (org.apache.lucene.store.Directory)2 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)2 ClusterSettings (org.elasticsearch.common.settings.ClusterSettings)2 Settings (org.elasticsearch.common.settings.Settings)2 IndexSettings (org.elasticsearch.index.IndexSettings)2 ParsedDocument (org.elasticsearch.index.mapper.ParsedDocument)2