Search in sources :

Example 26 with Releasable

use of org.elasticsearch.common.lease.Releasable in project elasticsearch by elastic.

the class IndexShardOperationsLockTests method testAllOperationsInvoked.

public void testAllOperationsInvoked() throws InterruptedException, TimeoutException, ExecutionException {
    int numThreads = 10;
    List<PlainActionFuture<Releasable>> futures = new ArrayList<>();
    List<Thread> operationThreads = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(numThreads / 2);
    for (int i = 0; i < numThreads; i++) {
        PlainActionFuture<Releasable> future = new PlainActionFuture<Releasable>() {

            @Override
            public void onResponse(Releasable releasable) {
                releasable.close();
                super.onResponse(releasable);
            }
        };
        Thread thread = new Thread() {

            public void run() {
                latch.countDown();
                block.acquire(future, ThreadPool.Names.GENERIC, true);
            }
        };
        futures.add(future);
        operationThreads.add(thread);
    }
    CountDownLatch blockFinished = new CountDownLatch(1);
    threadPool.generic().execute(() -> {
        try {
            latch.await();
            blockAndWait().close();
            blockFinished.countDown();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    for (Thread thread : operationThreads) {
        thread.start();
    }
    for (PlainActionFuture<Releasable> future : futures) {
        assertNotNull(future.get(1, TimeUnit.MINUTES));
    }
    for (Thread thread : operationThreads) {
        thread.join();
    }
    blockFinished.await();
}
Also used : PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) ArrayList(java.util.ArrayList) Releasable(org.elasticsearch.common.lease.Releasable) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 27 with Releasable

use of org.elasticsearch.common.lease.Releasable in project elasticsearch by elastic.

the class ReleasablesTests method testReleaseOnce.

public void testReleaseOnce() {
    AtomicInteger count = new AtomicInteger(0);
    Releasable releasable = Releasables.releaseOnce(count::incrementAndGet, count::incrementAndGet);
    assertEquals(0, count.get());
    releasable.close();
    assertEquals(2, count.get());
    releasable.close();
    assertEquals(2, count.get());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Releasable(org.elasticsearch.common.lease.Releasable)

Example 28 with Releasable

use of org.elasticsearch.common.lease.Releasable in project elasticsearch by elastic.

the class TribeIT method testOnConflictPrefer.

public void testOnConflictPrefer() throws Exception {
    final String preference = randomFrom(cluster1, cluster2).getClusterName();
    Settings additionalSettings = Settings.builder().put("tribe.on_conflict", "prefer_" + preference).build();
    try (Releasable tribeNode = startTribeNode(ALL, additionalSettings)) {
        assertAcked(cluster1.client().admin().indices().prepareCreate("test1"));
        assertAcked(cluster1.client().admin().indices().prepareCreate("shared"));
        ensureGreen(cluster1.client());
        assertAcked(cluster2.client().admin().indices().prepareCreate("test2"));
        assertAcked(cluster2.client().admin().indices().prepareCreate("shared"));
        ensureGreen(cluster2.client());
        // Wait for the tribe node to connect to the two remote clusters
        assertNodes(ALL);
        // Wait for the tribe node to retrieve the indices into its cluster state
        assertIndicesExist(client(), "test1", "test2", "shared");
        ClusterState clusterState = client().admin().cluster().prepareState().get().getState();
        assertThat(clusterState.getMetaData().hasIndex("test1"), is(true));
        assertThat(clusterState.getMetaData().index("test1").getSettings().get("tribe.name"), equalTo(cluster1.getClusterName()));
        assertThat(clusterState.getMetaData().hasIndex("test2"), is(true));
        assertThat(clusterState.getMetaData().index("test2").getSettings().get("tribe.name"), equalTo(cluster2.getClusterName()));
        assertThat(clusterState.getMetaData().hasIndex("shared"), is(true));
        assertThat(clusterState.getMetaData().index("shared").getSettings().get("tribe.name"), equalTo(preference));
    }
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) Releasable(org.elasticsearch.common.lease.Releasable) Matchers.containsString(org.hamcrest.Matchers.containsString) Settings(org.elasticsearch.common.settings.Settings) DiscoverySettings(org.elasticsearch.discovery.DiscoverySettings)

Example 29 with Releasable

use of org.elasticsearch.common.lease.Releasable in project elasticsearch by elastic.

the class RecoverySourceHandlerTests method testWaitForClusterStateOnPrimaryRelocation.

public void testWaitForClusterStateOnPrimaryRelocation() throws IOException, InterruptedException {
    final RecoverySettings recoverySettings = new RecoverySettings(Settings.EMPTY, service);
    final boolean attemptSequenceNumberBasedRecovery = randomBoolean();
    final boolean isTranslogReadyForSequenceNumberBasedRecovery = attemptSequenceNumberBasedRecovery && randomBoolean();
    final StartRecoveryRequest request = new StartRecoveryRequest(shardId, new DiscoveryNode("b", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT), new DiscoveryNode("b", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT), null, true, randomNonNegativeLong(), attemptSequenceNumberBasedRecovery ? randomNonNegativeLong() : SequenceNumbersService.UNASSIGNED_SEQ_NO);
    final AtomicBoolean phase1Called = new AtomicBoolean();
    final AtomicBoolean prepareTargetForTranslogCalled = new AtomicBoolean();
    final AtomicBoolean phase2Called = new AtomicBoolean();
    final AtomicBoolean ensureClusterStateVersionCalled = new AtomicBoolean();
    final AtomicBoolean recoveriesDelayed = new AtomicBoolean();
    final AtomicBoolean relocated = new AtomicBoolean();
    final IndexShard shard = mock(IndexShard.class);
    when(shard.seqNoStats()).thenReturn(mock(SeqNoStats.class));
    when(shard.segmentStats(anyBoolean())).thenReturn(mock(SegmentsStats.class));
    final Translog.View translogView = mock(Translog.View.class);
    when(shard.acquireTranslogView()).thenReturn(translogView);
    when(shard.state()).then(i -> relocated.get() ? IndexShardState.RELOCATED : IndexShardState.STARTED);
    doAnswer(i -> {
        relocated.set(true);
        assertTrue(recoveriesDelayed.get());
        return null;
    }).when(shard).relocated(any(String.class));
    final Supplier<Long> currentClusterStateVersionSupplier = () -> {
        assertFalse(ensureClusterStateVersionCalled.get());
        assertTrue(recoveriesDelayed.get());
        ensureClusterStateVersionCalled.set(true);
        return 0L;
    };
    final Function<String, Releasable> delayNewRecoveries = s -> {
        assertThat(phase1Called.get(), equalTo(!isTranslogReadyForSequenceNumberBasedRecovery));
        assertTrue(prepareTargetForTranslogCalled.get());
        assertTrue(phase2Called.get());
        assertFalse(recoveriesDelayed.get());
        recoveriesDelayed.set(true);
        return () -> {
            assertTrue(recoveriesDelayed.get());
            recoveriesDelayed.set(false);
        };
    };
    final RecoverySourceHandler handler = new RecoverySourceHandler(shard, mock(RecoveryTargetHandler.class), request, currentClusterStateVersionSupplier, delayNewRecoveries, recoverySettings.getChunkSize().bytesAsInt(), Settings.EMPTY) {

        @Override
        boolean isTranslogReadyForSequenceNumberBasedRecovery(final Translog.View translogView) {
            return isTranslogReadyForSequenceNumberBasedRecovery;
        }

        @Override
        public void phase1(final IndexCommit snapshot, final Translog.View translogView) {
            phase1Called.set(true);
        }

        @Override
        void prepareTargetForTranslog(final int totalTranslogOps, final long maxUnsafeAutoIdTimestamp) throws IOException {
            prepareTargetForTranslogCalled.set(true);
        }

        @Override
        void phase2(long startingSeqNo, Translog.Snapshot snapshot) throws IOException {
            phase2Called.set(true);
        }
    };
    handler.recoverToTarget();
    assertTrue(ensureClusterStateVersionCalled.get());
    // phase1 should only be attempted if we are not doing a sequence-number-based recovery
    assertThat(phase1Called.get(), equalTo(!isTranslogReadyForSequenceNumberBasedRecovery));
    assertTrue(prepareTargetForTranslogCalled.get());
    assertTrue(phase2Called.get());
    assertTrue(relocated.get());
    assertFalse(recoveriesDelayed.get());
}
Also used : 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) IndexShard(org.elasticsearch.index.shard.IndexShard) SegmentsStats(org.elasticsearch.index.engine.SegmentsStats) IndexCommit(org.apache.lucene.index.IndexCommit) Translog(org.elasticsearch.index.translog.Translog) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SeqNoStats(org.elasticsearch.index.seqno.SeqNoStats) Releasable(org.elasticsearch.common.lease.Releasable)

Example 30 with Releasable

use of org.elasticsearch.common.lease.Releasable in project elasticsearch by elastic.

the class SyncedFlushSingleNodeTests method testSyncFailsIfOperationIsInFlight.

public void testSyncFailsIfOperationIsInFlight() throws InterruptedException, ExecutionException {
    createIndex("test");
    client().prepareIndex("test", "test", "1").setSource("{}", XContentType.JSON).get();
    IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test"));
    IndexShard shard = test.getShardOrNull(0);
    SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class);
    final ShardId shardId = shard.shardId();
    PlainActionFuture<Releasable> fut = new PlainActionFuture<>();
    shard.acquirePrimaryOperationLock(fut, ThreadPool.Names.INDEX);
    try (Releasable operationLock = fut.get()) {
        SyncedFlushUtil.LatchedListener<ShardsSyncedFlushResult> listener = new SyncedFlushUtil.LatchedListener<>();
        flushService.attemptSyncedFlush(shardId, listener);
        listener.latch.await();
        assertNull(listener.error);
        ShardsSyncedFlushResult syncedFlushResult = listener.result;
        assertNotNull(syncedFlushResult);
        assertEquals(0, syncedFlushResult.successfulShards());
        assertNotEquals(0, syncedFlushResult.totalShards());
        assertEquals("[1] ongoing operations on primary", syncedFlushResult.failureReason());
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) IndexService(org.elasticsearch.index.IndexService) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) IndexShard(org.elasticsearch.index.shard.IndexShard) IndicesService(org.elasticsearch.indices.IndicesService) Releasable(org.elasticsearch.common.lease.Releasable)

Aggregations

Releasable (org.elasticsearch.common.lease.Releasable)38 PlainActionFuture (org.elasticsearch.action.support.PlainActionFuture)7 IndexShard (org.elasticsearch.index.shard.IndexShard)7 ClusterState (org.elasticsearch.cluster.ClusterState)6 IOException (java.io.IOException)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 ElasticsearchException (org.elasticsearch.ElasticsearchException)5 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)5 TestShardRouting (org.elasticsearch.cluster.routing.TestShardRouting)5 Settings (org.elasticsearch.common.settings.Settings)5 ExecutionException (java.util.concurrent.ExecutionException)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 BytesReference (org.elasticsearch.common.bytes.BytesReference)4 ArrayList (java.util.ArrayList)3 ActionListener (org.elasticsearch.action.ActionListener)3 ClusterBlockException (org.elasticsearch.cluster.block.ClusterBlockException)3 AbstractRunnable (org.elasticsearch.common.util.concurrent.AbstractRunnable)3 DiscoverySettings (org.elasticsearch.discovery.DiscoverySettings)3 ShardId (org.elasticsearch.index.shard.ShardId)3 List (java.util.List)2