Search in sources :

Example 16 with ClusterStateUpdateTask

use of org.opensearch.cluster.ClusterStateUpdateTask in project OpenSearch by opensearch-project.

the class BlobStoreRepository method executeConsistentStateUpdate.

@Override
public void executeConsistentStateUpdate(Function<RepositoryData, ClusterStateUpdateTask> createUpdateTask, String source, Consumer<Exception> onFailure) {
    final RepositoryMetadata repositoryMetadataStart = metadata;
    getRepositoryData(ActionListener.wrap(repositoryData -> {
        final ClusterStateUpdateTask updateTask = createUpdateTask.apply(repositoryData);
        clusterService.submitStateUpdateTask(source, new ClusterStateUpdateTask(updateTask.priority()) {

            private boolean executedTask = false;

            @Override
            public ClusterState execute(ClusterState currentState) throws Exception {
                // to change in any form.
                if (repositoryMetadataStart.equals(getRepoMetadata(currentState))) {
                    executedTask = true;
                    return updateTask.execute(currentState);
                }
                return currentState;
            }

            @Override
            public void onFailure(String source, Exception e) {
                if (executedTask) {
                    updateTask.onFailure(source, e);
                } else {
                    onFailure.accept(e);
                }
            }

            @Override
            public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
                if (executedTask) {
                    updateTask.clusterStateProcessed(source, oldState, newState);
                } else {
                    executeConsistentStateUpdate(createUpdateTask, source, onFailure);
                }
            }

            @Override
            public TimeValue timeout() {
                return updateTask.timeout();
            }
        });
    }, onFailure));
}
Also used : Metadata(org.opensearch.cluster.metadata.Metadata) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AllocationService(org.opensearch.cluster.routing.allocation.AllocationService) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) AbortedSnapshotException(org.opensearch.snapshots.AbortedSnapshotException) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Map(java.util.Map) Lucene(org.opensearch.common.lucene.Lucene) ActionListener(org.opensearch.action.ActionListener) IOContext(org.apache.lucene.store.IOContext) Repository(org.opensearch.repositories.Repository) TimeValue(org.opensearch.common.unit.TimeValue) ExceptionsHelper(org.opensearch.ExceptionsHelper) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) BlobStoreIndexShardSnapshot(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshot) BlockingQueue(java.util.concurrent.BlockingQueue) AbstractLifecycleComponent(org.opensearch.common.component.AbstractLifecycleComponent) Logger(org.apache.logging.log4j.Logger) RepositoryOperation(org.opensearch.repositories.RepositoryOperation) Stream(java.util.stream.Stream) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) BytesArray(org.opensearch.common.bytes.BytesArray) BlobStoreIndexShardSnapshots(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshots) FsBlobContainer(org.opensearch.common.blobstore.fs.FsBlobContainer) StepListener(org.opensearch.action.StepListener) XContentType(org.opensearch.common.xcontent.XContentType) IndexCommit(org.apache.lucene.index.IndexCommit) ThreadPool(org.opensearch.threadpool.ThreadPool) BlobContainer(org.opensearch.common.blobstore.BlobContainer) Releasable(org.opensearch.common.lease.Releasable) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ClusterState(org.opensearch.cluster.ClusterState) SnapshotMissingException(org.opensearch.snapshots.SnapshotMissingException) Numbers(org.opensearch.common.Numbers) SlicedInputStream(org.opensearch.index.snapshots.blobstore.SlicedInputStream) SnapshotException(org.opensearch.snapshots.SnapshotException) Streams(org.opensearch.common.io.Streams) CompressorFactory(org.opensearch.common.compress.CompressorFactory) RepositoryVerificationException(org.opensearch.repositories.RepositoryVerificationException) RepositoryCleanupInProgress(org.opensearch.cluster.RepositoryCleanupInProgress) InputStreamIndexInput(org.opensearch.common.lucene.store.InputStreamIndexInput) LongStream(java.util.stream.LongStream) IndexInput(org.apache.lucene.store.IndexInput) SetOnce(org.apache.lucene.util.SetOnce) RepositoriesMetadata(org.opensearch.cluster.metadata.RepositoriesMetadata) Executor(java.util.concurrent.Executor) SnapshotInfo(org.opensearch.snapshots.SnapshotInfo) RepositoryMetadata(org.opensearch.cluster.metadata.RepositoryMetadata) IOException(java.io.IOException) IndexShardSnapshotFailedException(org.opensearch.index.snapshots.IndexShardSnapshotFailedException) NotXContentException(org.opensearch.common.compress.NotXContentException) AtomicLong(java.util.concurrent.atomic.AtomicLong) RepositoryCleanupResult(org.opensearch.repositories.RepositoryCleanupResult) BlobPath(org.opensearch.common.blobstore.BlobPath) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) CounterMetric(org.opensearch.common.metrics.CounterMetric) ShardGenerations(org.opensearch.repositories.ShardGenerations) NoSuchFileException(java.nio.file.NoSuchFileException) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) SnapshotCreationException(org.opensearch.snapshots.SnapshotCreationException) ByteSizeUnit(org.opensearch.common.unit.ByteSizeUnit) SnapshotFiles(org.opensearch.index.snapshots.blobstore.SnapshotFiles) SnapshotsService(org.opensearch.snapshots.SnapshotsService) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) XContentParser(org.opensearch.common.xcontent.XContentParser) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MapperService(org.opensearch.index.mapper.MapperService) IndexId(org.opensearch.repositories.IndexId) XContentFactory(org.opensearch.common.xcontent.XContentFactory) RepositoryStats(org.opensearch.repositories.RepositoryStats) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) RecoverySettings(org.opensearch.indices.recovery.RecoverySettings) RepositoryException(org.opensearch.repositories.RepositoryException) FileInfo.canonicalName(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshot.FileInfo.canonicalName) BytesRef(org.apache.lucene.util.BytesRef) SnapshotId(org.opensearch.snapshots.SnapshotId) Collection(java.util.Collection) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Store(org.opensearch.index.store.Store) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) Tuple(org.opensearch.common.collect.Tuple) BlobStore(org.opensearch.common.blobstore.BlobStore) List(java.util.List) Optional(java.util.Optional) BytesReference(org.opensearch.common.bytes.BytesReference) RateLimitingInputStream(org.opensearch.index.snapshots.blobstore.RateLimitingInputStream) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ActionRunnable(org.opensearch.action.ActionRunnable) SnapshotsInProgress(org.opensearch.cluster.SnapshotsInProgress) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) SnapshotDeletionsInProgress(org.opensearch.cluster.SnapshotDeletionsInProgress) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) FilterInputStream(java.io.FilterInputStream) IndexShardSnapshotStatus(org.opensearch.index.snapshots.IndexShardSnapshotStatus) IndexMetaDataGenerations(org.opensearch.repositories.IndexMetaDataGenerations) UUIDs(org.opensearch.common.UUIDs) StoreFileMetadata(org.opensearch.index.store.StoreFileMetadata) IndexOutput(org.apache.lucene.store.IndexOutput) IndexShardRestoreFailedException(org.opensearch.index.snapshots.IndexShardRestoreFailedException) RepositoryData(org.opensearch.repositories.RepositoryData) Setting(org.opensearch.common.settings.Setting) RepositoryShardId(org.opensearch.repositories.RepositoryShardId) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) DeleteResult(org.opensearch.common.blobstore.DeleteResult) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) RateLimiter(org.apache.lucene.store.RateLimiter) InputStream(java.io.InputStream) ClusterState(org.opensearch.cluster.ClusterState) RepositoryMetadata(org.opensearch.cluster.metadata.RepositoryMetadata) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) AbortedSnapshotException(org.opensearch.snapshots.AbortedSnapshotException) SnapshotMissingException(org.opensearch.snapshots.SnapshotMissingException) SnapshotException(org.opensearch.snapshots.SnapshotException) RepositoryVerificationException(org.opensearch.repositories.RepositoryVerificationException) IOException(java.io.IOException) IndexShardSnapshotFailedException(org.opensearch.index.snapshots.IndexShardSnapshotFailedException) NotXContentException(org.opensearch.common.compress.NotXContentException) NoSuchFileException(java.nio.file.NoSuchFileException) SnapshotCreationException(org.opensearch.snapshots.SnapshotCreationException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) RepositoryException(org.opensearch.repositories.RepositoryException) IndexShardRestoreFailedException(org.opensearch.index.snapshots.IndexShardRestoreFailedException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException)

Example 17 with ClusterStateUpdateTask

use of org.opensearch.cluster.ClusterStateUpdateTask in project OpenSearch by opensearch-project.

the class BatchedRerouteServiceTests method testBatchesReroutesTogetherAtPriorityOfHighestSubmittedReroute.

public void testBatchesReroutesTogetherAtPriorityOfHighestSubmittedReroute() throws BrokenBarrierException, InterruptedException {
    final CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
    clusterService.submitStateUpdateTask("block master service", new ClusterStateUpdateTask() {

        @Override
        public ClusterState execute(ClusterState currentState) throws Exception {
            // notify test that we are blocked
            cyclicBarrier.await();
            // wait to be unblocked by test
            cyclicBarrier.await();
            return currentState;
        }

        @Override
        public void onFailure(String source, Exception e) {
            throw new AssertionError(source, e);
        }
    });
    // wait for master thread to be blocked
    cyclicBarrier.await();
    final AtomicBoolean rerouteExecuted = new AtomicBoolean();
    final BatchedRerouteService batchedRerouteService = new BatchedRerouteService(clusterService, (s, r) -> {
        // only called once
        assertTrue(rerouteExecuted.compareAndSet(false, true));
        return s;
    });
    final int iterations = scaledRandomIntBetween(1, 100);
    final CountDownLatch tasksSubmittedCountDown = new CountDownLatch(iterations);
    final CountDownLatch tasksCompletedCountDown = new CountDownLatch(iterations);
    final List<Runnable> actions = new ArrayList<>(iterations);
    final Function<Priority, Runnable> rerouteFromPriority = priority -> () -> {
        final AtomicBoolean alreadyRun = new AtomicBoolean();
        batchedRerouteService.reroute("reroute at " + priority, priority, ActionListener.wrap(() -> {
            assertTrue(alreadyRun.compareAndSet(false, true));
            tasksCompletedCountDown.countDown();
        }));
        tasksSubmittedCountDown.countDown();
    };
    // ensure at least one URGENT priority reroute
    actions.add(rerouteFromPriority.apply(Priority.URGENT));
    for (int i = 1; i < iterations; i++) {
        final int iteration = i;
        if (randomBoolean()) {
            actions.add(rerouteFromPriority.apply(randomFrom(Priority.LOW, Priority.NORMAL, Priority.HIGH, Priority.URGENT)));
        } else {
            final Priority priority = randomFrom(Priority.NORMAL, Priority.HIGH, Priority.URGENT, Priority.IMMEDIATE);
            final boolean submittedConcurrentlyWithReroute = randomBoolean();
            if (submittedConcurrentlyWithReroute == false) {
                // this task might be submitted later
                tasksSubmittedCountDown.countDown();
            }
            actions.add(() -> {
                clusterService.submitStateUpdateTask("other task " + iteration + " at " + priority, new ClusterStateUpdateTask(priority) {

                    @Override
                    public ClusterState execute(ClusterState currentState) {
                        switch(priority) {
                            case IMMEDIATE:
                                if (submittedConcurrentlyWithReroute) {
                                    assertFalse("should have rerouted after " + priority + " priority task", rerouteExecuted.get());
                                }
                                // else this task might be submitted too late to precede the reroute
                                break;
                            case URGENT:
                                // may run either before or after reroute
                                break;
                            case HIGH:
                            case NORMAL:
                                assertTrue("should have rerouted before " + priority + " priority task", rerouteExecuted.get());
                                break;
                            default:
                                fail("unexpected priority: " + priority);
                                break;
                        }
                        return currentState;
                    }

                    @Override
                    public void onFailure(String source, Exception e) {
                        throw new AssertionError(source, e);
                    }

                    @Override
                    public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
                        tasksCompletedCountDown.countDown();
                    }
                });
                if (submittedConcurrentlyWithReroute) {
                    tasksSubmittedCountDown.countDown();
                }
            });
        }
    }
    Randomness.shuffle(actions);
    actions.forEach(threadPool.generic()::execute);
    assertTrue(tasksSubmittedCountDown.await(10, TimeUnit.SECONDS));
    // allow master thread to continue;
    cyclicBarrier.await();
    // wait for reroute to complete
    assertTrue(tasksCompletedCountDown.await(10, TimeUnit.SECONDS));
    // see above for assertion that it's only called once
    assertTrue(rerouteExecuted.get());
}
Also used : DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) ThreadPool(org.opensearch.threadpool.ThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Priority(org.opensearch.common.Priority) OpenSearchException(org.opensearch.OpenSearchException) Function(java.util.function.Function) ArrayList(java.util.ArrayList) ClusterState(org.opensearch.cluster.ClusterState) After(org.junit.After) Matchers.lessThan(org.hamcrest.Matchers.lessThan) ActionListener(org.opensearch.action.ActionListener) EnumSet(java.util.EnumSet) Before(org.junit.Before) CyclicBarrier(java.util.concurrent.CyclicBarrier) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) FailedToCommitClusterStateException(org.opensearch.cluster.coordination.FailedToCommitClusterStateException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) Randomness(org.opensearch.common.Randomness) ClusterService(org.opensearch.cluster.service.ClusterService) ClusterServiceUtils(org.opensearch.test.ClusterServiceUtils) ClusterState(org.opensearch.cluster.ClusterState) Priority(org.opensearch.common.Priority) ArrayList(java.util.ArrayList) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) CountDownLatch(java.util.concurrent.CountDownLatch) OpenSearchException(org.opensearch.OpenSearchException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) FailedToCommitClusterStateException(org.opensearch.cluster.coordination.FailedToCommitClusterStateException) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 18 with ClusterStateUpdateTask

use of org.opensearch.cluster.ClusterStateUpdateTask in project OpenSearch by opensearch-project.

the class DelayedAllocationServiceTests method testDelayedUnassignedScheduleReroute.

public void testDelayedUnassignedScheduleReroute() throws Exception {
    TimeValue delaySetting = timeValueMillis(100);
    Metadata metadata = Metadata.builder().put(IndexMetadata.builder("test").settings(settings(Version.CURRENT).put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), delaySetting)).numberOfShards(1).numberOfReplicas(1)).build();
    ClusterState clusterState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY)).metadata(metadata).routingTable(RoutingTable.builder().addAsNew(metadata.index("test")).build()).build();
    clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().add(newNode("node1")).add(newNode("node2")).localNodeId("node1").masterNodeId("node1")).build();
    final long baseTimestampNanos = System.nanoTime();
    allocationService.setNanoTimeOverride(baseTimestampNanos);
    clusterState = allocationService.reroute(clusterState, "reroute");
    // starting primaries
    clusterState = startInitializingShardsAndReroute(allocationService, clusterState);
    // starting replicas
    clusterState = startInitializingShardsAndReroute(allocationService, clusterState);
    assertFalse("no shards should be unassigned", clusterState.getRoutingNodes().unassigned().size() > 0);
    String nodeId = null;
    final List<ShardRouting> allShards = clusterState.getRoutingTable().allShards("test");
    // we need to find the node with the replica otherwise we will not reroute
    for (ShardRouting shardRouting : allShards) {
        if (shardRouting.primary() == false) {
            nodeId = shardRouting.currentNodeId();
            break;
        }
    }
    assertNotNull(nodeId);
    // remove node that has replica and reroute
    clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).remove(nodeId)).build();
    clusterState = allocationService.disassociateDeadNodes(clusterState, true, "reroute");
    ClusterState stateWithDelayedShard = clusterState;
    // make sure the replica is marked as delayed (i.e. not reallocated)
    assertEquals(1, UnassignedInfo.getNumberOfDelayedUnassigned(stateWithDelayedShard));
    ShardRouting delayedShard = stateWithDelayedShard.getRoutingNodes().unassigned().iterator().next();
    assertEquals(baseTimestampNanos, delayedShard.unassignedInfo().getUnassignedTimeInNanos());
    // mock ClusterService.submitStateUpdateTask() method
    CountDownLatch latch = new CountDownLatch(1);
    AtomicReference<ClusterStateUpdateTask> clusterStateUpdateTask = new AtomicReference<>();
    doAnswer(invocationOnMock -> {
        clusterStateUpdateTask.set((ClusterStateUpdateTask) invocationOnMock.getArguments()[1]);
        latch.countDown();
        return null;
    }).when(clusterService).submitStateUpdateTask(eq(CLUSTER_UPDATE_TASK_SOURCE), any(ClusterStateUpdateTask.class));
    assertNull(delayedAllocationService.delayedRerouteTask.get());
    long delayUntilClusterChangeEvent = TimeValue.timeValueNanos(randomInt((int) delaySetting.nanos() - 1)).nanos();
    long clusterChangeEventTimestampNanos = baseTimestampNanos + delayUntilClusterChangeEvent;
    delayedAllocationService.setNanoTimeOverride(clusterChangeEventTimestampNanos);
    delayedAllocationService.clusterChanged(new ClusterChangedEvent("fake node left", stateWithDelayedShard, clusterState));
    // check that delayed reroute task was created and registered with the proper settings
    DelayedAllocationService.DelayedRerouteTask delayedRerouteTask = delayedAllocationService.delayedRerouteTask.get();
    assertNotNull(delayedRerouteTask);
    assertFalse(delayedRerouteTask.cancelScheduling.get());
    assertThat(delayedRerouteTask.baseTimestampNanos, equalTo(clusterChangeEventTimestampNanos));
    assertThat(delayedRerouteTask.nextDelay.nanos(), equalTo(delaySetting.nanos() - (clusterChangeEventTimestampNanos - baseTimestampNanos)));
    // check that submitStateUpdateTask() was invoked on the cluster service mock
    assertTrue(latch.await(30, TimeUnit.SECONDS));
    verify(clusterService).submitStateUpdateTask(eq(CLUSTER_UPDATE_TASK_SOURCE), eq(clusterStateUpdateTask.get()));
    // advance the time on the allocation service to a timestamp that happened after the delayed scheduling
    long nanoTimeForReroute = clusterChangeEventTimestampNanos + delaySetting.nanos() + timeValueMillis(randomInt(200)).nanos();
    allocationService.setNanoTimeOverride(nanoTimeForReroute);
    // apply cluster state
    ClusterState stateWithRemovedDelay = clusterStateUpdateTask.get().execute(stateWithDelayedShard);
    // check that shard is not delayed anymore
    assertEquals(0, UnassignedInfo.getNumberOfDelayedUnassigned(stateWithRemovedDelay));
    // check that task is now removed
    assertNull(delayedAllocationService.delayedRerouteTask.get());
    // simulate calling listener (cluster change event)
    delayedAllocationService.setNanoTimeOverride(nanoTimeForReroute + timeValueMillis(randomInt(200)).nanos());
    delayedAllocationService.clusterChanged(new ClusterChangedEvent(CLUSTER_UPDATE_TASK_SOURCE, stateWithRemovedDelay, stateWithDelayedShard));
    // check that no new task is scheduled
    assertNull(delayedAllocationService.delayedRerouteTask.get());
    // check that no further cluster state update was submitted
    verifyNoMoreInteractions(clusterService);
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) AtomicReference(java.util.concurrent.atomic.AtomicReference) ClusterChangedEvent(org.opensearch.cluster.ClusterChangedEvent) CountDownLatch(java.util.concurrent.CountDownLatch) TimeValue(org.opensearch.common.unit.TimeValue)

Example 19 with ClusterStateUpdateTask

use of org.opensearch.cluster.ClusterStateUpdateTask in project OpenSearch by opensearch-project.

the class MasterServiceTests method testMasterAwareExecution.

public void testMasterAwareExecution() throws Exception {
    final MasterService nonMaster = createMasterService(false);
    final boolean[] taskFailed = { false };
    final CountDownLatch latch1 = new CountDownLatch(1);
    nonMaster.submitStateUpdateTask("test", new ClusterStateUpdateTask() {

        @Override
        public ClusterState execute(ClusterState currentState) {
            latch1.countDown();
            return currentState;
        }

        @Override
        public void onFailure(String source, Exception e) {
            taskFailed[0] = true;
            latch1.countDown();
        }
    });
    latch1.await();
    assertTrue("cluster state update task was executed on a non-master", taskFailed[0]);
    final CountDownLatch latch2 = new CountDownLatch(1);
    nonMaster.submitStateUpdateTask("test", new LocalClusterUpdateTask() {

        @Override
        public ClusterTasksResult<LocalClusterUpdateTask> execute(ClusterState currentState) {
            taskFailed[0] = false;
            latch2.countDown();
            return unchanged();
        }

        @Override
        public void onFailure(String source, Exception e) {
            taskFailed[0] = true;
            latch2.countDown();
        }
    });
    latch2.await();
    assertFalse("non-master cluster state update task was not executed", taskFailed[0]);
    nonMaster.close();
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) LocalClusterUpdateTask(org.opensearch.cluster.LocalClusterUpdateTask) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) AckedClusterStateUpdateTask(org.opensearch.cluster.AckedClusterStateUpdateTask) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) OpenSearchException(org.opensearch.OpenSearchException) FailedToCommitClusterStateException(org.opensearch.cluster.coordination.FailedToCommitClusterStateException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException)

Example 20 with ClusterStateUpdateTask

use of org.opensearch.cluster.ClusterStateUpdateTask in project OpenSearch by opensearch-project.

the class PersistentTasksClusterServiceTests method createRecheckTestClusterService.

private ClusterService createRecheckTestClusterService(ClusterState initialState, boolean shouldSimulateFailure) {
    AtomicBoolean testFailureNextTime = new AtomicBoolean(shouldSimulateFailure);
    AtomicReference<ClusterState> state = new AtomicReference<>(initialState);
    ClusterService recheckTestClusterService = mock(ClusterService.class);
    when(recheckTestClusterService.getClusterSettings()).thenReturn(clusterService.getClusterSettings());
    doAnswer(invocationOnMock -> state.get().getNodes().getLocalNode()).when(recheckTestClusterService).localNode();
    doAnswer(invocationOnMock -> state.get()).when(recheckTestClusterService).state();
    doAnswer(invocationOnMock -> {
        @SuppressWarnings("unchecked") ClusterStateUpdateTask task = (ClusterStateUpdateTask) invocationOnMock.getArguments()[1];
        ClusterState before = state.get();
        ClusterState after = task.execute(before);
        if (testFailureNextTime.compareAndSet(true, false)) {
            task.onFailure("testing failure", new RuntimeException("foo"));
        } else {
            state.set(after);
            task.clusterStateProcessed("test", before, after);
        }
        return null;
    }).when(recheckTestClusterService).submitStateUpdateTask(anyString(), any(ClusterStateUpdateTask.class));
    return recheckTestClusterService;
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClusterState(org.opensearch.cluster.ClusterState) ClusterServiceUtils.createClusterService(org.opensearch.test.ClusterServiceUtils.createClusterService) ClusterService(org.opensearch.cluster.service.ClusterService) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Aggregations

ClusterStateUpdateTask (org.opensearch.cluster.ClusterStateUpdateTask)44 ClusterState (org.opensearch.cluster.ClusterState)43 IOException (java.io.IOException)21 ClusterService (org.opensearch.cluster.service.ClusterService)21 TimeValue (org.opensearch.common.unit.TimeValue)20 ActionListener (org.opensearch.action.ActionListener)18 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)17 ArrayList (java.util.ArrayList)16 List (java.util.List)16 Set (java.util.Set)15 ThreadPool (org.opensearch.threadpool.ThreadPool)14 HashSet (java.util.HashSet)13 Map (java.util.Map)13 ClusterBlockException (org.opensearch.cluster.block.ClusterBlockException)13 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)13 Metadata (org.opensearch.cluster.metadata.Metadata)13 Collections (java.util.Collections)12 Collectors (java.util.stream.Collectors)12 LogManager (org.apache.logging.log4j.LogManager)12 Logger (org.apache.logging.log4j.Logger)12