Search in sources :

Example 26 with IndexFormatTooOldException

use of org.apache.lucene.index.IndexFormatTooOldException in project elasticsearch by elastic.

the class StoreTests method testVerifyingIndexOutput.

public void testVerifyingIndexOutput() throws IOException {
    Directory dir = newDirectory();
    IndexOutput output = dir.createOutput("foo.bar", IOContext.DEFAULT);
    int iters = scaledRandomIntBetween(10, 100);
    for (int i = 0; i < iters; i++) {
        BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
        output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
    }
    CodecUtil.writeFooter(output);
    output.close();
    IndexInput indexInput = dir.openInput("foo.bar", IOContext.DEFAULT);
    String checksum = Store.digestToString(CodecUtil.retrieveChecksum(indexInput));
    indexInput.seek(0);
    BytesRef ref = new BytesRef(scaledRandomIntBetween(1, 1024));
    long length = indexInput.length();
    IndexOutput verifyingOutput = new Store.LuceneVerifyingIndexOutput(new StoreFileMetaData("foo1.bar", length, checksum), dir.createOutput("foo1.bar", IOContext.DEFAULT));
    while (length > 0) {
        if (random().nextInt(10) == 0) {
            verifyingOutput.writeByte(indexInput.readByte());
            length--;
        } else {
            int min = (int) Math.min(length, ref.bytes.length);
            indexInput.readBytes(ref.bytes, ref.offset, min);
            verifyingOutput.writeBytes(ref.bytes, ref.offset, min);
            length -= min;
        }
    }
    Store.verify(verifyingOutput);
    try {
        appendRandomData(verifyingOutput);
        fail("should be a corrupted index");
    } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
    // ok
    }
    try {
        Store.verify(verifyingOutput);
        fail("should be a corrupted index");
    } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
    // ok
    }
    IOUtils.close(indexInput, verifyingOutput, dir);
}
Also used : CorruptIndexException(org.apache.lucene.index.CorruptIndexException) IndexOutput(org.apache.lucene.store.IndexOutput) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) ChecksumIndexInput(org.apache.lucene.store.ChecksumIndexInput) IndexInput(org.apache.lucene.store.IndexInput) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) BytesRef(org.apache.lucene.util.BytesRef) Directory(org.apache.lucene.store.Directory) RAMDirectory(org.apache.lucene.store.RAMDirectory)

Example 27 with IndexFormatTooOldException

use of org.apache.lucene.index.IndexFormatTooOldException in project elasticsearch by elastic.

the class StoreTests method testVerifyingIndexOutputOnEmptyFile.

public void testVerifyingIndexOutputOnEmptyFile() throws IOException {
    Directory dir = newDirectory();
    IndexOutput verifyingOutput = new Store.LuceneVerifyingIndexOutput(new StoreFileMetaData("foo.bar", 0, Store.digestToString(0)), dir.createOutput("foo1.bar", IOContext.DEFAULT));
    try {
        Store.verify(verifyingOutput);
        fail("should be a corrupted index");
    } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
    // ok
    }
    IOUtils.close(verifyingOutput, dir);
}
Also used : IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) IndexOutput(org.apache.lucene.store.IndexOutput) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) Directory(org.apache.lucene.store.Directory) RAMDirectory(org.apache.lucene.store.RAMDirectory)

Example 28 with IndexFormatTooOldException

use of org.apache.lucene.index.IndexFormatTooOldException in project elasticsearch by elastic.

the class ExceptionSerializationTests method testWriteThrowable.

public void testWriteThrowable() throws IOException {
    final QueryShardException queryShardException = new QueryShardException(new Index("foo", "_na_"), "foobar", null);
    final UnknownException unknownException = new UnknownException("this exception is unknown", queryShardException);
    final Exception[] causes = new Exception[] { new IllegalStateException("foobar"), new IllegalArgumentException("alalaal"), new NullPointerException("boom"), new EOFException("dadada"), new ElasticsearchSecurityException("nono!"), new NumberFormatException("not a number"), new CorruptIndexException("baaaam booom", "this is my resource"), new IndexFormatTooNewException("tooo new", 1, 2, 3), new IndexFormatTooOldException("tooo new", 1, 2, 3), new IndexFormatTooOldException("tooo new", "very old version"), new ArrayIndexOutOfBoundsException("booom"), new StringIndexOutOfBoundsException("booom"), new FileNotFoundException("booom"), new NoSuchFileException("booom"), new AlreadyClosedException("closed!!", new NullPointerException()), new LockObtainFailedException("can't lock directory", new NullPointerException()), unknownException };
    for (final Exception cause : causes) {
        ElasticsearchException ex = new ElasticsearchException("topLevel", cause);
        ElasticsearchException deserialized = serialize(ex);
        assertEquals(deserialized.getMessage(), ex.getMessage());
        assertTrue("Expected: " + deserialized.getCause().getMessage() + " to contain: " + ex.getCause().getClass().getName() + " but it didn't", deserialized.getCause().getMessage().contains(ex.getCause().getMessage()));
        if (ex.getCause().getClass() != UnknownException.class) {
            // unknown exception is not directly mapped
            assertEquals(deserialized.getCause().getClass(), ex.getCause().getClass());
        } else {
            assertEquals(deserialized.getCause().getClass(), NotSerializableExceptionWrapper.class);
        }
        assertArrayEquals(deserialized.getStackTrace(), ex.getStackTrace());
        assertTrue(deserialized.getStackTrace().length > 1);
        assertVersionSerializable(VersionUtils.randomVersion(random()), cause);
        assertVersionSerializable(VersionUtils.randomVersion(random()), ex);
        assertVersionSerializable(VersionUtils.randomVersion(random()), deserialized);
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) NoSuchFileException(java.nio.file.NoSuchFileException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) Index(org.elasticsearch.index.Index) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) IllegalShardRoutingStateException(org.elasticsearch.cluster.routing.IllegalShardRoutingStateException) ActionTransportException(org.elasticsearch.transport.ActionTransportException) SearchContextMissingException(org.elasticsearch.search.SearchContextMissingException) SnapshotException(org.elasticsearch.snapshots.SnapshotException) AccessDeniedException(java.nio.file.AccessDeniedException) SearchException(org.elasticsearch.search.SearchException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) RecoverFilesRecoveryException(org.elasticsearch.indices.recovery.RecoverFilesRecoveryException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) NotDirectoryException(java.nio.file.NotDirectoryException) DirectoryNotEmptyException(java.nio.file.DirectoryNotEmptyException) IOException(java.io.IOException) IndexTemplateMissingException(org.elasticsearch.indices.IndexTemplateMissingException) NoSuchFileException(java.nio.file.NoSuchFileException) FailedNodeException(org.elasticsearch.action.FailedNodeException) SearchParseException(org.elasticsearch.search.SearchParseException) URISyntaxException(java.net.URISyntaxException) AliasesNotFoundException(org.elasticsearch.rest.action.admin.indices.AliasesNotFoundException) RecoveryEngineException(org.elasticsearch.index.engine.RecoveryEngineException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) TimestampParsingException(org.elasticsearch.action.TimestampParsingException) RoutingMissingException(org.elasticsearch.action.RoutingMissingException) RepositoryException(org.elasticsearch.repositories.RepositoryException) AlreadyExpiredException(org.elasticsearch.index.AlreadyExpiredException) InvalidIndexTemplateException(org.elasticsearch.indices.InvalidIndexTemplateException) QueryShardException(org.elasticsearch.index.query.QueryShardException) FileSystemException(java.nio.file.FileSystemException) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) EOFException(java.io.EOFException) FileNotFoundException(java.io.FileNotFoundException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) ActionNotFoundTransportException(org.elasticsearch.transport.ActionNotFoundTransportException) ParsingException(org.elasticsearch.common.ParsingException) FileSystemLoopException(java.nio.file.FileSystemLoopException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) AtomicMoveNotSupportedException(java.nio.file.AtomicMoveNotSupportedException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) EOFException(java.io.EOFException) QueryShardException(org.elasticsearch.index.query.QueryShardException) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException)

Example 29 with IndexFormatTooOldException

use of org.apache.lucene.index.IndexFormatTooOldException in project crate by crate.

the class RecoverySourceHandler method phase1.

/**
 * Perform phase1 of the recovery operations. Once this {@link IndexCommit}
 * snapshot has been performed no commit operations (files being fsync'd)
 * are effectively allowed on this index until all recovery phases are done
 * <p>
 * Phase1 examines the segment files on the target node and copies over the
 * segments that are missing. Only segments that have the same size and
 * checksum can be reused
 */
void phase1(IndexCommit snapshot, long startingSeqNo, IntSupplier translogOps, ActionListener<SendFileResult> listener) {
    cancellableThreads.checkForCancel();
    final Store store = shard.store();
    try {
        final StopWatch stopWatch = new StopWatch().start();
        final Store.MetadataSnapshot recoverySourceMetadata;
        try {
            recoverySourceMetadata = store.getMetadata(snapshot);
        } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
            shard.failShard("recovery", ex);
            throw ex;
        }
        for (String name : snapshot.getFileNames()) {
            final StoreFileMetadata md = recoverySourceMetadata.get(name);
            if (md == null) {
                logger.info("Snapshot differs from actual index for file: {} meta: {}", name, recoverySourceMetadata.asMap());
                throw new CorruptIndexException("Snapshot differs from actual index - maybe index was removed metadata has " + recoverySourceMetadata.asMap().size() + " files", name);
            }
        }
        if (canSkipPhase1(recoverySourceMetadata, request.metadataSnapshot()) == false) {
            final List<String> phase1FileNames = new ArrayList<>();
            final List<Long> phase1FileSizes = new ArrayList<>();
            final List<String> phase1ExistingFileNames = new ArrayList<>();
            final List<Long> phase1ExistingFileSizes = new ArrayList<>();
            // Total size of segment files that are recovered
            long totalSizeInBytes = 0;
            // Total size of segment files that were able to be re-used
            long existingTotalSizeInBytes = 0;
            // Generate a "diff" of all the identical, different, and missing
            // segment files on the target node, using the existing files on
            // the source node
            final Store.RecoveryDiff diff = recoverySourceMetadata.recoveryDiff(request.metadataSnapshot());
            for (StoreFileMetadata md : diff.identical) {
                phase1ExistingFileNames.add(md.name());
                phase1ExistingFileSizes.add(md.length());
                existingTotalSizeInBytes += md.length();
                if (logger.isTraceEnabled()) {
                    logger.trace("recovery [phase1]: not recovering [{}], exist in local store and has checksum [{}]," + " size [{}]", md.name(), md.checksum(), md.length());
                }
                totalSizeInBytes += md.length();
            }
            List<StoreFileMetadata> phase1Files = new ArrayList<>(diff.different.size() + diff.missing.size());
            phase1Files.addAll(diff.different);
            phase1Files.addAll(diff.missing);
            for (StoreFileMetadata md : phase1Files) {
                if (request.metadataSnapshot().asMap().containsKey(md.name())) {
                    logger.trace("recovery [phase1]: recovering [{}], exists in local store, but is different: remote [{}], local [{}]", md.name(), request.metadataSnapshot().asMap().get(md.name()), md);
                } else {
                    logger.trace("recovery [phase1]: recovering [{}], does not exist in remote", md.name());
                }
                phase1FileNames.add(md.name());
                phase1FileSizes.add(md.length());
                totalSizeInBytes += md.length();
            }
            logger.trace("recovery [phase1]: recovering_files [{}] with total_size [{}], reusing_files [{}] with total_size [{}]", phase1FileNames.size(), new ByteSizeValue(totalSizeInBytes), phase1ExistingFileNames.size(), new ByteSizeValue(existingTotalSizeInBytes));
            final StepListener<Void> sendFileInfoStep = new StepListener<>();
            final StepListener<Void> sendFilesStep = new StepListener<>();
            final StepListener<RetentionLease> createRetentionLeaseStep = new StepListener<>();
            final StepListener<Void> cleanFilesStep = new StepListener<>();
            cancellableThreads.checkForCancel();
            recoveryTarget.receiveFileInfo(phase1FileNames, phase1FileSizes, phase1ExistingFileNames, phase1ExistingFileSizes, translogOps.getAsInt(), sendFileInfoStep);
            sendFileInfoStep.whenComplete(r -> sendFiles(store, phase1Files.toArray(new StoreFileMetadata[0]), translogOps, sendFilesStep), listener::onFailure);
            sendFilesStep.whenComplete(r -> createRetentionLease(startingSeqNo, createRetentionLeaseStep), listener::onFailure);
            createRetentionLeaseStep.whenComplete(retentionLease -> {
                final long lastKnownGlobalCheckpoint = shard.getLastKnownGlobalCheckpoint();
                assert retentionLease == null || retentionLease.retainingSequenceNumber() - 1 <= lastKnownGlobalCheckpoint : retentionLease + " vs " + lastKnownGlobalCheckpoint;
                // Establishes new empty translog on the replica with global checkpoint set to lastKnownGlobalCheckpoint. We want
                // the commit we just copied to be a safe commit on the replica, so why not set the global checkpoint on the replica
                // to the max seqno of this commit? Because (in rare corner cases) this commit might not be a safe commit here on
                // the primary, and in these cases the max seqno would be too high to be valid as a global checkpoint.
                cleanFiles(store, recoverySourceMetadata, translogOps, lastKnownGlobalCheckpoint, cleanFilesStep);
            }, listener::onFailure);
            final long totalSize = totalSizeInBytes;
            final long existingTotalSize = existingTotalSizeInBytes;
            cleanFilesStep.whenComplete(r -> {
                final TimeValue took = stopWatch.totalTime();
                logger.trace("recovery [phase1]: took [{}]", took);
                listener.onResponse(new SendFileResult(phase1FileNames, phase1FileSizes, totalSize, phase1ExistingFileNames, phase1ExistingFileSizes, existingTotalSize, took));
            }, listener::onFailure);
        } else {
            logger.trace("skipping [phase1] since source and target have identical sync id [{}]", recoverySourceMetadata.getSyncId());
            // but we must still create a retention lease
            final StepListener<RetentionLease> createRetentionLeaseStep = new StepListener<>();
            createRetentionLease(startingSeqNo, createRetentionLeaseStep);
            createRetentionLeaseStep.whenComplete(retentionLease -> {
                final TimeValue took = stopWatch.totalTime();
                logger.trace("recovery [phase1]: took [{}]", took);
                listener.onResponse(new SendFileResult(Collections.emptyList(), Collections.emptyList(), 0L, Collections.emptyList(), Collections.emptyList(), 0L, took));
            }, listener::onFailure);
        }
    } catch (Exception e) {
        throw new RecoverFilesRecoveryException(request.shardId(), 0, new ByteSizeValue(0L), e);
    }
}
Also used : CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) Store(org.elasticsearch.index.store.Store) StoreFileMetadata(org.elasticsearch.index.store.StoreFileMetadata) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) TimeValue(io.crate.common.unit.TimeValue) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) RecoveryEngineException(org.elasticsearch.index.engine.RecoveryEngineException) RetentionLeaseNotFoundException(org.elasticsearch.index.seqno.RetentionLeaseNotFoundException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) IndexShardClosedException(org.elasticsearch.index.shard.IndexShardClosedException) IndexShardRelocatedException(org.elasticsearch.index.shard.IndexShardRelocatedException) IOException(java.io.IOException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) StopWatch(org.elasticsearch.common.StopWatch) RetentionLease(org.elasticsearch.index.seqno.RetentionLease) AtomicLong(java.util.concurrent.atomic.AtomicLong) StepListener(org.elasticsearch.action.StepListener) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException)

Example 30 with IndexFormatTooOldException

use of org.apache.lucene.index.IndexFormatTooOldException in project crate by crate.

the class TranslogHeader method read.

/**
 * Read a translog header from the given path and file channel
 */
static TranslogHeader read(final String translogUUID, final Path path, final FileChannel channel) throws IOException {
    try {
        // This input is intentionally not closed because closing it will close the FileChannel.
        final BufferedChecksumStreamInput in = new BufferedChecksumStreamInput(new InputStreamStreamInput(java.nio.channels.Channels.newInputStream(channel), channel.size()), path.toString());
        final int version;
        try {
            version = CodecUtil.checkHeader(new InputStreamDataInput(in), TRANSLOG_CODEC, VERSION_CHECKSUMS, VERSION_PRIMARY_TERM);
        } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException e) {
            tryReportOldVersionError(path, channel);
            throw new TranslogCorruptedException(path.toString(), "translog header corrupted", e);
        }
        if (version == VERSION_CHECKSUMS) {
            throw new IllegalStateException("pre-2.0 translog found [" + path + "]");
        }
        // Read the translogUUID
        final int uuidLen = in.readInt();
        if (uuidLen > channel.size()) {
            throw new TranslogCorruptedException(path.toString(), "UUID length can't be larger than the translog");
        }
        if (uuidLen <= 0) {
            throw new TranslogCorruptedException(path.toString(), "UUID length must be positive");
        }
        final BytesRef uuid = new BytesRef(uuidLen);
        uuid.length = uuidLen;
        in.read(uuid.bytes, uuid.offset, uuid.length);
        // Read the primary term
        final long primaryTerm;
        if (version == VERSION_PRIMARY_TERM) {
            primaryTerm = in.readLong();
        } else {
            // This can be dropped with 5.0 as BWC with older versions is not required anymore
            assert version == VERSION_CHECKPOINTS : "Unknown header version [" + version + "]";
            primaryTerm = UNASSIGNED_PRIMARY_TERM;
        }
        // Verify the checksum (can be always verified on >= 5.0 as version must be primary term based without BWC)
        if (version >= VERSION_PRIMARY_TERM) {
            Translog.verifyChecksum(in);
        }
        assert primaryTerm >= 0 : "Primary term must be non-negative [" + primaryTerm + "]; translog path [" + path + "]";
        final int headerSizeInBytes = headerSizeInBytes(version, uuid.length);
        assert channel.position() == headerSizeInBytes : "Header is not fully read; header size [" + headerSizeInBytes + "], position [" + channel.position() + "]";
        // verify UUID only after checksum, to ensure that UUID is not corrupted
        final BytesRef expectedUUID = new BytesRef(translogUUID);
        if (uuid.bytesEquals(expectedUUID) == false) {
            throw new TranslogCorruptedException(path.toString(), "expected shard UUID " + expectedUUID + " but got: " + uuid + " this translog file belongs to a different translog");
        }
        return new TranslogHeader(translogUUID, primaryTerm, headerSizeInBytes);
    } catch (EOFException e) {
        throw new TranslogCorruptedException(path.toString(), "translog header truncated", e);
    }
}
Also used : CorruptIndexException(org.apache.lucene.index.CorruptIndexException) InputStreamDataInput(org.apache.lucene.store.InputStreamDataInput) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) EOFException(java.io.EOFException) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) BytesRef(org.apache.lucene.util.BytesRef) InputStreamStreamInput(org.elasticsearch.common.io.stream.InputStreamStreamInput)

Aggregations

IndexFormatTooOldException (org.apache.lucene.index.IndexFormatTooOldException)31 CorruptIndexException (org.apache.lucene.index.CorruptIndexException)29 IndexFormatTooNewException (org.apache.lucene.index.IndexFormatTooNewException)29 Directory (org.apache.lucene.store.Directory)14 IndexInput (org.apache.lucene.store.IndexInput)12 IndexOutput (org.apache.lucene.store.IndexOutput)12 IOException (java.io.IOException)11 RAMDirectory (org.apache.lucene.store.RAMDirectory)11 BytesRef (org.apache.lucene.util.BytesRef)8 NoSuchFileException (java.nio.file.NoSuchFileException)6 Store (org.elasticsearch.index.store.Store)6 EOFException (java.io.EOFException)5 ChecksumIndexInput (org.apache.lucene.store.ChecksumIndexInput)5 FilterDirectory (org.apache.lucene.store.FilterDirectory)5 NIOFSDirectory (org.apache.lucene.store.NIOFSDirectory)5 FileNotFoundException (java.io.FileNotFoundException)4 AccessDeniedException (java.nio.file.AccessDeniedException)4 AtomicMoveNotSupportedException (java.nio.file.AtomicMoveNotSupportedException)4 DirectoryNotEmptyException (java.nio.file.DirectoryNotEmptyException)4 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)4