diff --git a/lxc1/p2-apps/mongo/mongo_init.sh b/lxc1/p2-apps/mongo/mongo_init.sh index 9498d18..a2a8276 100644 --- a/lxc1/p2-apps/mongo/mongo_init.sh +++ b/lxc1/p2-apps/mongo/mongo_init.sh @@ -15,38 +15,35 @@ else exit 1 fi -# 2. WAIT FOR MONGO TO BE READY -# We need the container to be up before we can run mongosh commands -echo "⏳ Waiting for MongoDB container (${mongo-db$KOMODO_NODE_ID}) to be ready..." -MAX_RETRIES=10 -COUNT=0 -until docker exec "mongo-db$KOMODO_NODE_ID" mongosh --quiet --eval "db.adminCommand('ping')" &>/dev/null; do - ((COUNT++)) - if [ $COUNT -ge $MAX_RETRIES ]; then - echo "❌ Timeout: MongoDB container is not responding." - exit 1 - fi - sleep 2 -done +STATUS_JSON=$(docker exec -t "mongo-db${KOMODO_NODE_ID}" mongosh --quiet --eval "rs.status()" 2>/dev/null) +IS_INIT=$(echo "$STATUS_JSON" | grep -c "ok: 1") -# 3. CHECK-THEN-INITIATE LOGIC -# Ask the DB if it is already part of a replica set -IS_INIT=$(docker exec -t "mongo-db$KOMODO_NODE_ID" mongosh --quiet --eval "rs.status().ok" 2>/dev/null) +if [ "$IS_INIT" -gt 0 ]; then + echo "✅ MongoDB is already part of a replica set. Nothing to do." + exit 0 +fi -if [ "$IS_INIT" == "1" ]; then - echo "✅ MongoDB Replica Set 'rs${LXC_NUM}' is already initialized. Skipping." -else - echo "⚠️ Replica Set not found. Initializing 'rs${LXC_NUM}' now..." +if [ "$KOMODO_NODE_ID" == "1" ]; then + echo "👑 Node 1 detected. Initiating as Primary for 'rs${LXC_NUM}'..." - # Use your defined PRI/SEC variables for the members - docker exec -t "mongo-db$KOMODO_NODE_ID" mongosh --eval " + # Initiate with just self to guarantee Primary status + docker exec -t "mongo-db1" mongosh --eval " rs.initiate({ _id: 'rs${LXC_NUM}', - members: [ - { _id: 0, host: 'mongo-db1:27017' }, - { _id: 1, host: 'mongo-db2:27017' } - ] + members: [{ _id: 0, host: 'mongo-db1:27017' }] })" - echo "🚀 Initialization command sent! Transitioning to Primary..." + echo "⏳ Waiting for election..." + sleep 5 + + # Pre-authorize the partner + docker exec -t "mongo-db1" mongosh --eval "rs.add('mongo-db2:27017')" + echo "🚀 Node 1 is now Primary and waiting for Node 2." + +else + echo "🏃 Node 2 detected. Attempting to handshake with Node 1..." + + # Node 2 doesn't initiate. It just waits for Node 1 to be ready. + # Node 1 already ran rs.add('mongo-db2'), so Node 2 just needs to be up. + echo "🤝 Node 2 is online. Synchronization should start automatically via Node 1's config." fi \ No newline at end of file