Search in sources :

Example 1 with InternalEngineFactory

use of org.elasticsearch.index.engine.InternalEngineFactory in project crate by crate.

the class BlobStoreRepositoryRestoreTests method testRestoreSnapshotWithExistingFiles.

/**
 * Restoring a snapshot that contains multiple files must succeed even when
 * some files already exist in the shard's store.
 */
public void testRestoreSnapshotWithExistingFiles() throws IOException {
    final IndexId indexId = new IndexId(randomAlphaOfLength(10), UUIDs.randomBase64UUID());
    final ShardId shardId = new ShardId(indexId.getName(), indexId.getId(), 0);
    IndexShard shard = newShard(shardId, true);
    try {
        // index documents in the shards
        final int numDocs = scaledRandomIntBetween(1, 500);
        recoverShardFromStore(shard);
        for (int i = 0; i < numDocs; i++) {
            indexDoc(shard, Integer.toString(i));
            if (rarely()) {
                flushShard(shard, false);
            }
        }
        assertDocCount(shard, numDocs);
        // snapshot the shard
        final Repository repository = createRepository();
        final Snapshot snapshot = new Snapshot(repository.getMetadata().name(), new SnapshotId(randomAlphaOfLength(10), "_uuid"));
        snapshotShard(shard, snapshot, repository);
        // capture current store files
        final Store.MetadataSnapshot storeFiles = shard.snapshotStoreMetadata();
        assertFalse(storeFiles.asMap().isEmpty());
        // close the shard
        closeShards(shard);
        // delete some random files in the store
        List<String> deletedFiles = randomSubsetOf(randomIntBetween(1, storeFiles.size() - 1), storeFiles.asMap().keySet());
        for (String deletedFile : deletedFiles) {
            Files.delete(shard.shardPath().resolveIndex().resolve(deletedFile));
        }
        // build a new shard using the same store directory as the closed shard
        ShardRouting shardRouting = ShardRoutingHelper.initWithSameId(shard.routingEntry(), RecoverySource.ExistingStoreRecoverySource.INSTANCE);
        shard = newShard(shardRouting, shard.shardPath(), shard.indexSettings().getIndexMetadata(), null, new InternalEngineFactory(), () -> {
        }, RetentionLeaseSyncer.EMPTY, EMPTY_EVENT_LISTENER);
        // restore the shard
        recoverShardFromSnapshot(shard, snapshot, repository);
        // check that the shard is not corrupted
        TestUtil.checkIndex(shard.store().directory());
        // check that all files have been restored
        final Directory directory = shard.store().directory();
        final List<String> directoryFiles = Arrays.asList(directory.listAll());
        for (StoreFileMetadata storeFile : storeFiles) {
            String fileName = storeFile.name();
            assertTrue("File [" + fileName + "] does not exist in store directory", directoryFiles.contains(fileName));
            assertEquals(storeFile.length(), shard.store().directory().fileLength(fileName));
        }
    } finally {
        if (shard != null && shard.state() != IndexShardState.CLOSED) {
            try {
                shard.close("test", false);
            } finally {
                IOUtils.close(shard.store());
            }
        }
    }
}
Also used : IndexId(org.elasticsearch.repositories.IndexId) IndexShard(org.elasticsearch.index.shard.IndexShard) Store(org.elasticsearch.index.store.Store) Matchers.containsString(org.hamcrest.Matchers.containsString) StoreFileMetadata(org.elasticsearch.index.store.StoreFileMetadata) ShardId(org.elasticsearch.index.shard.ShardId) Snapshot(org.elasticsearch.snapshots.Snapshot) SnapshotId(org.elasticsearch.snapshots.SnapshotId) Repository(org.elasticsearch.repositories.Repository) FsRepository(org.elasticsearch.repositories.fs.FsRepository) InternalEngineFactory(org.elasticsearch.index.engine.InternalEngineFactory) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Directory(org.apache.lucene.store.Directory)

Example 2 with InternalEngineFactory

use of org.elasticsearch.index.engine.InternalEngineFactory in project crate by crate.

the class IndexShardRetentionLeaseTests method runExpirationTest.

private void runExpirationTest(final boolean primary) throws IOException {
    final long retentionLeaseMillis = randomLongBetween(1, TimeValue.timeValueHours(12).millis());
    final Settings settings = Settings.builder().put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true).put(IndexSettings.INDEX_SOFT_DELETES_RETENTION_LEASE_PERIOD_SETTING.getKey(), TimeValue.timeValueMillis(retentionLeaseMillis).getStringRep()).build();
    // current time is mocked through the thread pool
    final IndexShard indexShard = newStartedShard(primary, settings, new InternalEngineFactory());
    final long primaryTerm = indexShard.getOperationPrimaryTerm();
    try {
        final long[] retainingSequenceNumbers = new long[1];
        retainingSequenceNumbers[0] = randomLongBetween(0, Long.MAX_VALUE);
        final long initialVersion;
        if (primary) {
            initialVersion = 2;
            indexShard.addRetentionLease("0", retainingSequenceNumbers[0], "test-0", ActionListener.wrap(() -> {
            }));
        } else {
            initialVersion = 3;
            final RetentionLeases retentionLeases = new RetentionLeases(primaryTerm, initialVersion, Arrays.asList(peerRecoveryRetentionLease(indexShard), new RetentionLease("0", retainingSequenceNumbers[0], currentTimeMillis.get(), "test-0")));
            indexShard.updateRetentionLeasesOnReplica(retentionLeases);
        }
        {
            final RetentionLeases retentionLeases = indexShard.getEngine().config().retentionLeasesSupplier().get();
            assertThat(retentionLeases.version(), equalTo(initialVersion));
            assertThat(retentionLeases.leases(), hasSize(2));
            final RetentionLease retentionLease = retentionLeases.get("0");
            assertThat(retentionLease.timestamp(), equalTo(currentTimeMillis.get()));
            assertRetentionLeases(indexShard, 1, retainingSequenceNumbers, primaryTerm, initialVersion, primary, false);
        }
        // renew the lease
        currentTimeMillis.set(currentTimeMillis.get() + randomLongBetween(0, 1024));
        retainingSequenceNumbers[0] = randomLongBetween(retainingSequenceNumbers[0], Long.MAX_VALUE);
        if (primary) {
            indexShard.renewRetentionLease("0", retainingSequenceNumbers[0], "test-0");
        } else {
            final RetentionLeases retentionLeases = new RetentionLeases(primaryTerm, initialVersion + 1, Arrays.asList(peerRecoveryRetentionLease(indexShard), new RetentionLease("0", retainingSequenceNumbers[0], currentTimeMillis.get(), "test-0")));
            indexShard.updateRetentionLeasesOnReplica(retentionLeases);
        }
        {
            final RetentionLeases retentionLeases = indexShard.getEngine().config().retentionLeasesSupplier().get();
            assertThat(retentionLeases.version(), equalTo(initialVersion + 1));
            assertThat(retentionLeases.leases(), hasSize(2));
            final RetentionLease retentionLease = retentionLeases.get("0");
            assertThat(retentionLease.timestamp(), equalTo(currentTimeMillis.get()));
            assertRetentionLeases(indexShard, 1, retainingSequenceNumbers, primaryTerm, initialVersion + 1, primary, false);
        }
        // now force the lease to expire
        currentTimeMillis.set(currentTimeMillis.get() + randomLongBetween(retentionLeaseMillis, Long.MAX_VALUE - currentTimeMillis.get()));
        if (primary) {
            assertRetentionLeases(indexShard, 1, retainingSequenceNumbers, primaryTerm, initialVersion + 1, true, false);
            assertRetentionLeases(indexShard, 0, new long[0], primaryTerm, initialVersion + 2, true, true);
        } else {
            assertRetentionLeases(indexShard, 1, retainingSequenceNumbers, primaryTerm, initialVersion + 1, false, false);
        }
    } finally {
        closeShards(indexShard);
    }
}
Also used : RetentionLease(org.elasticsearch.index.seqno.RetentionLease) InternalEngineFactory(org.elasticsearch.index.engine.InternalEngineFactory) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) RetentionLeases(org.elasticsearch.index.seqno.RetentionLeases)

Example 3 with InternalEngineFactory

use of org.elasticsearch.index.engine.InternalEngineFactory in project crate by crate.

the class IndicesService method getEngineFactory.

private EngineFactory getEngineFactory(final IndexSettings idxSettings) {
    final IndexMetadata indexMetadata = idxSettings.getIndexMetadata();
    if (indexMetadata != null && indexMetadata.getState() == IndexMetadata.State.CLOSE) {
        // NoOpEngine takes precedence as long as the index is closed
        return NoOpEngine::new;
    }
    final List<Optional<EngineFactory>> engineFactories = engineFactoryProviders.stream().map(engineFactoryProvider -> engineFactoryProvider.apply(idxSettings)).filter(maybe -> Objects.requireNonNull(maybe).isPresent()).collect(Collectors.toList());
    if (engineFactories.isEmpty()) {
        return new InternalEngineFactory();
    } else if (engineFactories.size() == 1) {
        assert engineFactories.get(0).isPresent();
        return engineFactories.get(0).get();
    } else {
        final String message = String.format(Locale.ROOT, "multiple engine factories provided for %s: %s", idxSettings.getIndex(), engineFactories.stream().map(t -> {
            assert t.isPresent();
            return "[" + t.get().getClass().getName() + "]";
        }).collect(Collectors.joining(",")));
        throw new IllegalStateException(message);
    }
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) ShardId(org.elasticsearch.index.shard.ShardId) NoOpEngine(org.elasticsearch.index.engine.NoOpEngine) BigArrays(org.elasticsearch.common.util.BigArrays) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) MetadataStateFormat(org.elasticsearch.gateway.MetadataStateFormat) MapperRegistry(org.elasticsearch.indices.mapper.MapperRegistry) Sets(io.crate.common.collections.Sets) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) IndexStorePlugin(org.elasticsearch.plugins.IndexStorePlugin) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) InternalEngineFactory(org.elasticsearch.index.engine.InternalEngineFactory) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) PluginsService(org.elasticsearch.plugins.PluginsService) Setting(org.elasticsearch.common.settings.Setting) AbstractRefCounted(org.elasticsearch.common.util.concurrent.AbstractRefCounted) Collections.emptyList(java.util.Collections.emptyList) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) AnalysisRegistry(org.elasticsearch.index.analysis.AnalysisRegistry) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Iterables(io.crate.common.collections.Iterables) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) CountDownLatch(java.util.concurrent.CountDownLatch) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) MapperService(org.elasticsearch.index.mapper.MapperService) List(java.util.List) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) Logger(org.apache.logging.log4j.Logger) IndicesClusterStateService(org.elasticsearch.indices.cluster.IndicesClusterStateService) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) RetentionLeaseSyncer(org.elasticsearch.index.seqno.RetentionLeaseSyncer) TimeValue(io.crate.common.unit.TimeValue) Optional(java.util.Optional) EsExecutors.daemonThreadFactory(org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory) IndexingOperationListener(org.elasticsearch.index.shard.IndexingOperationListener) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) MapBuilder.newMapBuilder(io.crate.common.collections.MapBuilder.newMapBuilder) XContentType(org.elasticsearch.common.xcontent.XContentType) HashMap(java.util.HashMap) MetaStateService(org.elasticsearch.gateway.MetaStateService) Index(org.elasticsearch.index.Index) IndexModule(org.elasticsearch.index.IndexModule) EsThreadPoolExecutor(org.elasticsearch.common.util.concurrent.EsThreadPoolExecutor) Function(java.util.function.Function) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ArrayList(java.util.ArrayList) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) IndexSettings(org.elasticsearch.index.IndexSettings) Node(org.elasticsearch.node.Node) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) Collections.emptyMap(java.util.Collections.emptyMap) FileSystemUtils(org.elasticsearch.common.io.FileSystemUtils) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) AbstractIndexComponent(org.elasticsearch.index.AbstractIndexComponent) Iterator(java.util.Iterator) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) Files(java.nio.file.Files) IndexCreationContext(org.elasticsearch.index.IndexService.IndexCreationContext) Client(org.elasticsearch.client.Client) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IOUtils(io.crate.common.io.IOUtils) IOException(java.io.IOException) ShardLock(org.elasticsearch.env.ShardLock) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) AbstractLifecycleComponent(org.elasticsearch.common.component.AbstractLifecycleComponent) EngineFactory(org.elasticsearch.index.engine.EngineFactory) IndexScopedSettings(org.elasticsearch.common.settings.IndexScopedSettings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CollectionUtil(org.apache.lucene.util.CollectionUtil) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) Closeable(java.io.Closeable) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) LogManager(org.apache.logging.log4j.LogManager) Optional(java.util.Optional) InternalEngineFactory(org.elasticsearch.index.engine.InternalEngineFactory) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata)

Example 4 with InternalEngineFactory

use of org.elasticsearch.index.engine.InternalEngineFactory in project crate by crate.

the class TransportReplicationAllPermitsAcquisitionTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    globalBlock = randomBoolean();
    RestStatus restStatus = randomFrom(RestStatus.values());
    block = new ClusterBlock(randomIntBetween(1, 10), randomAlphaOfLength(5), false, true, false, restStatus, ClusterBlockLevel.ALL);
    clusterService = createClusterService(threadPool);
    final ClusterState.Builder state = ClusterState.builder(clusterService.state());
    Set<DiscoveryNodeRole> roles = new HashSet<>(DiscoveryNodeRole.BUILT_IN_ROLES);
    DiscoveryNode node1 = new DiscoveryNode("_name1", "_node1", buildNewFakeTransportAddress(), emptyMap(), roles, Version.CURRENT);
    DiscoveryNode node2 = new DiscoveryNode("_name2", "_node2", buildNewFakeTransportAddress(), emptyMap(), roles, Version.CURRENT);
    state.nodes(DiscoveryNodes.builder().add(node1).add(node2).localNodeId(node1.getId()).masterNodeId(node1.getId()));
    shardId = new ShardId("index", UUID.randomUUID().toString(), 0);
    ShardRouting shardRouting = newShardRouting(shardId, node1.getId(), true, ShardRoutingState.INITIALIZING, RecoverySource.EmptyStoreRecoverySource.INSTANCE);
    Settings indexSettings = Settings.builder().put(SETTING_VERSION_CREATED, Version.CURRENT).put(SETTING_INDEX_UUID, shardId.getIndex().getUUID()).put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 1).put(SETTING_CREATION_DATE, System.currentTimeMillis()).build();
    primary = newStartedShard(p -> newShard(shardRouting, indexSettings, new InternalEngineFactory()), true);
    for (int i = 0; i < 10; i++) {
        final String id = Integer.toString(i);
        indexDoc(primary, id, "{\"value\":" + id + "}");
    }
    IndexMetadata indexMetadata = IndexMetadata.builder(shardId.getIndexName()).settings(indexSettings).primaryTerm(shardId.id(), primary.getOperationPrimaryTerm()).putMapping("default", "{ \"properties\": { \"value\":  { \"type\": \"short\"}}}").build();
    state.metadata(Metadata.builder().put(indexMetadata, false).generateClusterUuidIfNeeded());
    replica = newShard(primary.shardId(), false, node2.getId(), indexMetadata, null);
    recoverReplica(replica, primary, true);
    IndexRoutingTable.Builder routing = IndexRoutingTable.builder(indexMetadata.getIndex());
    routing.addIndexShard(new IndexShardRoutingTable.Builder(shardId).addShard(primary.routingEntry()).build());
    state.routingTable(RoutingTable.builder().add(routing.build()).build());
    setState(clusterService, state.build());
    final Settings transportSettings = Settings.builder().put("node.name", node1.getId()).build();
    MockTransport transport = new MockTransport() {

        @Override
        protected void onSendRequest(long requestId, String action, TransportRequest request, DiscoveryNode node) {
            assertThat(action, allOf(startsWith("cluster:admin/test/"), endsWith("[r]")));
            assertThat(node, equalTo(node2));
            // node2 doesn't really exist, but we are performing some trickery in mockIndicesService() to pretend that node1 holds both
            // the primary and the replica, so redirect the request back to node1.
            transportService.sendRequest(transportService.getLocalNode(), action, request, new TransportResponseHandler<TransportReplicationAction.ReplicaResponse>() {

                @Override
                public ReplicaResponse read(StreamInput in) throws IOException {
                    return new ReplicaResponse(in);
                }

                @SuppressWarnings("unchecked")
                private TransportResponseHandler<TransportReplicationAction.ReplicaResponse> getResponseHandler() {
                    return (TransportResponseHandler<TransportReplicationAction.ReplicaResponse>) getResponseHandlers().onResponseReceived(requestId, TransportMessageListener.NOOP_LISTENER);
                }

                @Override
                public void handleResponse(TransportReplicationAction.ReplicaResponse response) {
                    getResponseHandler().handleResponse(response);
                }

                @Override
                public void handleException(TransportException exp) {
                    getResponseHandler().handleException(exp);
                }

                @Override
                public String executor() {
                    return ThreadPool.Names.SAME;
                }
            });
        }
    };
    transportService = transport.createTransportService(transportSettings, threadPool, bta -> node1, null);
    transportService.start();
    transportService.acceptIncomingRequests();
    shardStateAction = new ShardStateAction(clusterService, transportService, null, null);
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) TransportRequest(org.elasticsearch.transport.TransportRequest) SETTING_VERSION_CREATED(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_VERSION_CREATED) ClusterServiceUtils.createClusterService(org.elasticsearch.test.ClusterServiceUtils.createClusterService) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) ClusterState(org.elasticsearch.cluster.ClusterState) TransportMessageListener(org.elasticsearch.transport.TransportMessageListener) Settings(org.elasticsearch.common.settings.Settings) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) After(org.junit.After) Matchers.nullValue(org.hamcrest.Matchers.nullValue) ThreadPool(org.elasticsearch.threadpool.ThreadPool) InternalEngineFactory(org.elasticsearch.index.engine.InternalEngineFactory) Releasable(org.elasticsearch.common.lease.Releasable) CyclicBarrier(java.util.concurrent.CyclicBarrier) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Matchers.allOf(org.hamcrest.Matchers.allOf) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) Set(java.util.Set) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) UUID(java.util.UUID) Matchers.startsWith(org.hamcrest.Matchers.startsWith) Objects(java.util.Objects) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) List(java.util.List) Version(org.elasticsearch.Version) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) RestStatus(org.elasticsearch.rest.RestStatus) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TimeValue(io.crate.common.unit.TimeValue) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) DiscoveryNodeRole(org.elasticsearch.cluster.node.DiscoveryNodeRole) SETTING_INDEX_UUID(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_INDEX_UUID) TransportException(org.elasticsearch.transport.TransportException) Matchers.endsWith(org.hamcrest.Matchers.endsWith) Mockito.mock(org.mockito.Mockito.mock) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) SETTING_NUMBER_OF_SHARDS(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS) TransportChannel(org.elasticsearch.transport.TransportChannel) ClusterService(org.elasticsearch.cluster.service.ClusterService) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) ArrayList(java.util.ArrayList) TestShardRouting.newShardRouting(org.elasticsearch.cluster.routing.TestShardRouting.newShardRouting) HashSet(java.util.HashSet) Metadata(org.elasticsearch.cluster.metadata.Metadata) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) SETTING_NUMBER_OF_REPLICAS(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS) ReplicaResponse(org.elasticsearch.action.support.replication.TransportReplicationAction.ReplicaResponse) TransportResponse(org.elasticsearch.transport.TransportResponse) IndicesService(org.elasticsearch.indices.IndicesService) TransportService(org.elasticsearch.transport.TransportService) ClusterBlockLevel(org.elasticsearch.cluster.block.ClusterBlockLevel) Before(org.junit.Before) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) SetOnce(org.apache.lucene.util.SetOnce) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) MockTransport(org.elasticsearch.test.transport.MockTransport) Test(org.junit.Test) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) SETTING_CREATION_DATE(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_CREATION_DATE) Mockito.when(org.mockito.Mockito.when) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) IndexShardTestCase(org.elasticsearch.index.shard.IndexShardTestCase) Matchers.hasItem(org.hamcrest.Matchers.hasItem) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) StreamInput(org.elasticsearch.common.io.stream.StreamInput) ClusterServiceUtils.setState(org.elasticsearch.test.ClusterServiceUtils.setState) ActionListener(org.elasticsearch.action.ActionListener) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) DiscoveryNodeRole(org.elasticsearch.cluster.node.DiscoveryNodeRole) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) ShardId(org.elasticsearch.index.shard.ShardId) InternalEngineFactory(org.elasticsearch.index.engine.InternalEngineFactory) MockTransport(org.elasticsearch.test.transport.MockTransport) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Settings(org.elasticsearch.common.settings.Settings) HashSet(java.util.HashSet) ClusterState(org.elasticsearch.cluster.ClusterState) TransportRequest(org.elasticsearch.transport.TransportRequest) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) IOException(java.io.IOException) TransportException(org.elasticsearch.transport.TransportException) RestStatus(org.elasticsearch.rest.RestStatus) StreamInput(org.elasticsearch.common.io.stream.StreamInput) ReplicaResponse(org.elasticsearch.action.support.replication.TransportReplicationAction.ReplicaResponse) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) TestShardRouting.newShardRouting(org.elasticsearch.cluster.routing.TestShardRouting.newShardRouting) ReplicaResponse(org.elasticsearch.action.support.replication.TransportReplicationAction.ReplicaResponse) Before(org.junit.Before)

Example 5 with InternalEngineFactory

use of org.elasticsearch.index.engine.InternalEngineFactory in project crate by crate.

the class IndexShardRetentionLeaseTests method testPersistence.

public void testPersistence() throws IOException {
    final Settings settings = Settings.builder().put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true).put(IndexSettings.INDEX_SOFT_DELETES_RETENTION_LEASE_PERIOD_SETTING.getKey(), Long.MAX_VALUE, TimeUnit.NANOSECONDS).build();
    final IndexShard indexShard = newStartedShard(true, settings, new InternalEngineFactory());
    try {
        final int length = randomIntBetween(0, 8);
        final long[] minimumRetainingSequenceNumbers = new long[length];
        for (int i = 0; i < length; i++) {
            minimumRetainingSequenceNumbers[i] = randomLongBetween(SequenceNumbers.NO_OPS_PERFORMED, Long.MAX_VALUE);
            currentTimeMillis.set(TimeUnit.NANOSECONDS.toMillis(randomNonNegativeLong()));
            indexShard.addRetentionLease(Integer.toString(i), minimumRetainingSequenceNumbers[i], "test-" + i, ActionListener.wrap(() -> {
            }));
        }
        currentTimeMillis.set(TimeUnit.NANOSECONDS.toMillis(Long.MAX_VALUE));
        // force the retention leases to persist
        indexShard.persistRetentionLeases();
        // the written retention leases should equal our current retention leases
        final RetentionLeases retentionLeases = indexShard.getEngine().config().retentionLeasesSupplier().get();
        final RetentionLeases writtenRetentionLeases = indexShard.loadRetentionLeases();
        assertThat(writtenRetentionLeases.version(), equalTo(1L + length));
        assertThat(writtenRetentionLeases.leases(), contains(retentionLeases.leases().toArray(new RetentionLease[0])));
        // when we recover, we should recover the retention leases
        final IndexShard recoveredShard = reinitShard(indexShard, ShardRoutingHelper.initWithSameId(indexShard.routingEntry(), RecoverySource.ExistingStoreRecoverySource.INSTANCE));
        try {
            recoverShardFromStore(recoveredShard);
            final RetentionLeases recoveredRetentionLeases = recoveredShard.getEngine().config().retentionLeasesSupplier().get();
            assertThat(recoveredRetentionLeases.version(), equalTo(1L + length));
            assertThat(recoveredRetentionLeases.leases(), contains(retentionLeases.leases().toArray(new RetentionLease[0])));
        } finally {
            closeShards(recoveredShard);
        }
        // we should not recover retention leases when force-allocating a stale primary
        final IndexShard forceRecoveredShard = reinitShard(indexShard, ShardRoutingHelper.initWithSameId(indexShard.routingEntry(), RecoverySource.ExistingStoreRecoverySource.FORCE_STALE_PRIMARY_INSTANCE));
        try {
            recoverShardFromStore(forceRecoveredShard);
            final RetentionLeases recoveredRetentionLeases = forceRecoveredShard.getEngine().config().retentionLeasesSupplier().get();
            assertThat(recoveredRetentionLeases.leases(), hasSize(1));
            assertThat(recoveredRetentionLeases.leases().iterator().next().id(), equalTo(ReplicationTracker.getPeerRecoveryRetentionLeaseId(indexShard.routingEntry())));
            assertThat(recoveredRetentionLeases.version(), equalTo(1L));
        } finally {
            closeShards(forceRecoveredShard);
        }
    } finally {
        closeShards(indexShard);
    }
}
Also used : InternalEngineFactory(org.elasticsearch.index.engine.InternalEngineFactory) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) RetentionLeases(org.elasticsearch.index.seqno.RetentionLeases)

Aggregations

InternalEngineFactory (org.elasticsearch.index.engine.InternalEngineFactory)5 Settings (org.elasticsearch.common.settings.Settings)4 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)3 IndexSettings (org.elasticsearch.index.IndexSettings)3 IndexShard (org.elasticsearch.index.shard.IndexShard)3 ShardId (org.elasticsearch.index.shard.ShardId)3 TimeValue (io.crate.common.unit.TimeValue)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Collections.emptyMap (java.util.Collections.emptyMap)2 List (java.util.List)2 Objects (java.util.Objects)2 Set (java.util.Set)2 TimeUnit (java.util.concurrent.TimeUnit)2 ClusterState (org.elasticsearch.cluster.ClusterState)2 IndexMetadata (org.elasticsearch.cluster.metadata.IndexMetadata)2 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)2 RecoverySource (org.elasticsearch.cluster.routing.RecoverySource)2 IndexService (org.elasticsearch.index.IndexService)2 ThreadPool (org.elasticsearch.threadpool.ThreadPool)2