Skip to content

Commit c35732d

Browse files
Fix race condition in InternalTestCluster.getMasterName()
Prevents assertion errors when the master node is null after obtaining the cluster state in the second call. See PRs 127213 and 127891 for details about recent changes to this method, and where the code used in this commit was proposed.
1 parent bccd6f2 commit c35732d

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags.Flag;
2929
import org.elasticsearch.action.support.DestructiveOperations;
3030
import org.elasticsearch.action.support.RefCountingRunnable;
31+
import org.elasticsearch.action.support.SubscribableListener;
3132
import org.elasticsearch.action.support.replication.TransportReplicationAction;
3233
import org.elasticsearch.client.internal.Client;
3334
import org.elasticsearch.cluster.ClusterName;
@@ -2038,13 +2039,12 @@ public String getMasterName(@Nullable String viaNode) {
20382039
throw new AssertionError("Unable to get master name, no node found");
20392040
}
20402041
try {
2041-
ClusterServiceUtils.awaitClusterState(logger, state -> state.nodes().getMasterNode() != null, clusterService(viaNode));
2042-
final ClusterState state = client(viaNode).admin().cluster().prepareState(TEST_REQUEST_TIMEOUT).setLocal(true).get().getState();
2043-
final DiscoveryNode masterNode = state.nodes().getMasterNode();
2044-
if (masterNode == null) {
2045-
throw new AssertionError("Master is not stable but the method expects a stable master node");
2046-
}
2047-
return masterNode.getName();
2042+
final var masterNameListener = new SubscribableListener<String>();
2043+
return safeAwait(ClusterServiceUtils.addTemporaryStateListener(clusterService(viaNode), cs -> {
2044+
Optional.ofNullable(cs.nodes().getMasterNode())
2045+
.ifPresent(masterNode -> masterNameListener.onResponse(masterNode.getName()));
2046+
return masterNameListener.isDone();
2047+
}).andThen(masterNameListener::addListener));
20482048
} catch (Exception e) {
20492049
logger.warn("Can't fetch cluster state", e);
20502050
throw new RuntimeException("Can't get master node " + e.getMessage(), e);

0 commit comments

Comments
 (0)