44// MONGO_INITDB_REPLICA_HOST can be set to the resolvable hostname:port
55// used to advertise this member (e.g. "database:27017" in Kubernetes).
66const host = process . env . MONGO_INITDB_REPLICA_HOST || "localhost:27017" ;
7- const maxWaitMs = 60000 ;
7+ const maxWaitMs = 60 * 1000 ;
88const intervalMs = 1000 ;
99const start = Date . now ( ) ;
1010
11+ /** Ensure the primary host is correctly configured */
1112function ensurePrimaryHost ( forceReconfig ) {
1213 let conf ;
1314 try {
@@ -28,39 +29,53 @@ function ensurePrimaryHost(forceReconfig) {
2829 conf . members [ 0 ] . host = host ;
2930 conf . version = ( conf . version || 1 ) + 1 ;
3031 rs . reconfig ( conf , { force : forceReconfig } ) ;
31-
3232 return false ;
3333 }
3434
3535 return true ;
3636}
3737
38+ // Wait for replica set to be initialized.
39+ let replicaSetInitiated = false ;
40+ while ( Date . now ( ) - start < maxWaitMs ) {
41+ try {
42+ rs . initiate ( { _id : "rs0" , members : [ { _id : 0 , host : host } ] } ) ;
43+ print ( `Initialized replica set with host ${ host } ` ) ;
44+ replicaSetInitiated = true ;
45+ break ;
46+ } catch ( err ) {
47+ if ( String ( err ) . includes ( "already initialized" ) ) {
48+ print ( "Replica set already initialized" ) ;
49+ replicaSetInitiated = true ;
50+ break ;
51+ }
52+
53+ print ( `Replica set init deferred: ${ err } ` ) ;
54+ }
55+
56+ sleep ( intervalMs ) ;
57+ }
58+ if ( ! replicaSetInitiated ) {
59+ throw new Error ( `Replica set not initialized after ${ maxWaitMs } ms` ) ;
60+ }
61+
62+ // Wait for this member to be PRIMARY with the correct host.
3863while ( Date . now ( ) - start < maxWaitMs ) {
3964 try {
4065 if ( db . hello ( ) . isWritablePrimary ) {
4166 if ( ensurePrimaryHost ( false ) ) {
42- print ( " Replica set is PRIMARY with correct host" ) ;
67+ print ( ` Replica set is PRIMARY with correct host: ${ host } ` ) ;
4368 quit ( 0 ) ;
4469 }
4570 } else {
4671 ensurePrimaryHost ( true ) ;
4772 }
48- } catch ( error ) {
49- print ( `Host alignment deferred (${ error } )` ) ;
50- }
51-
52- try {
53- rs . initiate ( { _id : "rs0" , members : [ { _id : 0 , host : host } ] } ) ;
54- print ( `Initialized replica set with host ${ host } ` ) ;
55- } catch ( error ) {
56- if ( ! String ( error ) . includes ( "already initialized" ) ) {
57- print ( `Replica set init deferred (${ error } )` ) ;
58- }
73+ } catch ( err ) {
74+ print ( `Host alignment deferred: ${ err } ` ) ;
5975 }
6076
6177 sleep ( intervalMs ) ;
6278}
63-
6479throw new Error (
6580 `Replica set did not reach PRIMARY state with host ${ host } after ${ maxWaitMs } ms`
6681) ;
0 commit comments