(function () { const replSetName = 'rs0'; const replSetHost = 'box-mongodb:27017'; const config = { _id: replSetName, members: [ { _id: 0, host: replSetHost, }, ], }; function replicaSetIsReady() { try { const status = rs.status(); return status && status.ok === 1; } catch (error) { print('Replica set status unavailable:', error.message); return false; } } if (!replicaSetIsReady()) { print('Initializing replica set', JSON.stringify(config)); rs.initiate(config); let attempts = 0; while (attempts < 20) { let status; try { status = rs.status(); } catch (error) { print('Replica set not ready yet:', error.message); sleep(1000); attempts += 1; continue; } if (status && status.ok === 1 && status.myState === 1) { print('Replica set is PRIMARY'); break; } print('Waiting for PRIMARY (attempt', attempts + 1, ')'); sleep(1000); attempts += 1; } } else { print('Replica set already initialized'); } ['box_admin', 'box_stats'].forEach((dbName) => { const targetDb = db.getSiblingDB(dbName); const result = targetDb.runCommand({ ping: 1 }); print('Ensured database ' + dbName + ':', tojson(result)); }); })();