|
| 1 | +// Ensure a single-node replica set is initialized and advertising the |
| 2 | +// expected host for this environment. |
| 3 | +// |
| 4 | +// MONGO_INITDB_REPLICA_HOST can be set to the resolvable hostname:port |
| 5 | +// used to advertise this member (e.g. "database:27017" in Kubernetes). |
| 6 | +const host = process.env.MONGO_INITDB_REPLICA_HOST || "localhost:27017"; |
| 7 | +const maxWaitMs = 60 * 1000; |
| 8 | +const intervalMs = 1000; |
| 9 | +const start = Date.now(); |
| 10 | + |
| 11 | +/** Ensure the primary host is correctly configured */ |
| 12 | +function ensurePrimaryHost(forceReconfig) { |
| 13 | + let conf; |
| 14 | + try { |
| 15 | + conf = rs.conf(); |
| 16 | + } catch (error) { |
| 17 | + conf = db.getSiblingDB("local").system.replset.findOne(); |
| 18 | + if (!forceReconfig || !conf) { |
| 19 | + throw error; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + if (!conf.members?.length) { |
| 24 | + throw new Error("Replica set config has no members"); |
| 25 | + } |
| 26 | + |
| 27 | + if (conf.members[0].host !== host) { |
| 28 | + print(`Updating replica set member host to ${host}`); |
| 29 | + conf.members[0].host = host; |
| 30 | + conf.version = (conf.version || 1) + 1; |
| 31 | + rs.reconfig(conf, { force: forceReconfig }); |
| 32 | + return false; |
| 33 | + } |
| 34 | + |
| 35 | + return true; |
| 36 | +} |
| 37 | + |
| 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. |
| 63 | +while (Date.now() - start < maxWaitMs) { |
| 64 | + try { |
| 65 | + if (db.hello().isWritablePrimary) { |
| 66 | + if (ensurePrimaryHost(false)) { |
| 67 | + print(`Replica set is PRIMARY with correct host: ${host}`); |
| 68 | + quit(0); |
| 69 | + } |
| 70 | + } else { |
| 71 | + ensurePrimaryHost(true); |
| 72 | + } |
| 73 | + } catch (err) { |
| 74 | + print(`Host alignment deferred: ${err}`); |
| 75 | + } |
| 76 | + |
| 77 | + sleep(intervalMs); |
| 78 | +} |
| 79 | +throw new Error( |
| 80 | + `Replica set did not reach PRIMARY state with host ${host} after ${maxWaitMs}ms` |
| 81 | +); |
0 commit comments