2121
2222import org .apache .lucene .util .IOUtils ;
2323import org .elasticsearch .Version ;
24+ import org .elasticsearch .cluster .ClusterState ;
25+ import org .elasticsearch .cluster .ClusterStateObserver ;
2426import org .elasticsearch .cluster .node .DiscoveryNode ;
2527import org .elasticsearch .cluster .node .DiscoveryNodes ;
2628import org .elasticsearch .cluster .service .ClusterService ;
2729import org .elasticsearch .common .settings .Settings ;
30+ import org .elasticsearch .common .unit .TimeValue ;
31+ import org .elasticsearch .common .util .concurrent .ThreadContext ;
2832import org .elasticsearch .test .ESTestCase ;
2933import org .elasticsearch .test .transport .MockTransportService ;
3034import org .elasticsearch .threadpool .TestThreadPool ;
3135import org .elasticsearch .threadpool .ThreadPool ;
3236
3337import java .io .Closeable ;
3438import java .util .Stack ;
39+ import java .util .concurrent .CountDownLatch ;
3540
3641import static org .elasticsearch .test .ClusterServiceUtils .createClusterService ;
3742import static org .hamcrest .Matchers .equalTo ;
@@ -54,6 +59,34 @@ public void testInitialJoin() throws Exception {
5459 final SingleNodeDiscovery discovery =
5560 new SingleNodeDiscovery (Settings .EMPTY , clusterService );
5661 discovery .startInitialJoin ();
62+
63+ // we are racing against the initial join which is asynchronous so we use an observer
64+ final ClusterState state = clusterService .state ();
65+ final ThreadContext threadContext = threadPool .getThreadContext ();
66+ final ClusterStateObserver observer =
67+ new ClusterStateObserver (state , clusterService , null , logger , threadContext );
68+ if (state .nodes ().getMasterNodeId () == null ) {
69+ final CountDownLatch latch = new CountDownLatch (1 );
70+ observer .waitForNextChange (new ClusterStateObserver .Listener () {
71+ @ Override
72+ public void onNewClusterState (ClusterState state ) {
73+ latch .countDown ();
74+ }
75+
76+ @ Override
77+ public void onClusterServiceClose () {
78+ latch .countDown ();
79+ }
80+
81+ @ Override
82+ public void onTimeout (TimeValue timeout ) {
83+ assert false ;
84+ }
85+ }, s -> s .nodes ().getMasterNodeId () != null );
86+
87+ latch .await ();
88+ }
89+
5790 final DiscoveryNodes nodes = clusterService .state ().nodes ();
5891 assertThat (nodes .getSize (), equalTo (1 ));
5992 assertThat (nodes .getMasterNode ().getId (), equalTo (node .getId ()));
0 commit comments