52 lines
No EOL
1.6 KiB
Bash
52 lines
No EOL
1.6 KiB
Bash
#!/bin/bash
|
|
# Move to the script's directory
|
|
cd "$(dirname "$0")"
|
|
|
|
# 1. ROBUST ENV SOURCING (Same logic as MinIO/Keepalived)
|
|
ENV_PATH="/docker/mongo/.env"
|
|
if [ -f "$ENV_PATH" ]; then
|
|
while read -r line || [ -n "$line" ]; do
|
|
[[ "$line" =~ ^#.*$ ]] && continue
|
|
[[ -z "$line" ]] && continue
|
|
export "${line//\"/}"
|
|
done < "$ENV_PATH"
|
|
else
|
|
echo "ERROR: .env file not found!"
|
|
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 (${KOMODO_DB_HOSTNAME}) to be ready..."
|
|
MAX_RETRIES=10
|
|
COUNT=0
|
|
until docker exec "$KOMODO_DB_HOSTNAME" 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
|
|
|
|
# 3. CHECK-THEN-INITIATE LOGIC
|
|
# Ask the DB if it is already part of a replica set
|
|
IS_INIT=$(docker exec -t "$KOMODO_DB_HOSTNAME" mongosh --quiet --eval "rs.status().ok" 2>/dev/null)
|
|
|
|
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..."
|
|
|
|
# Use your defined PRI/SEC variables for the members
|
|
docker exec -t "$KOMODO_DB_HOSTNAME" mongosh --eval "
|
|
rs.initiate({
|
|
_id: 'rs${LXC_NUM}',
|
|
members: [
|
|
{ _id: 0, host: '${KOMODO_DB_PRI}:27017' },
|
|
{ _id: 1, host: '${KOMODO_DB_SEC}:27017' }
|
|
]
|
|
})"
|
|
|
|
echo "🚀 Initialization command sent! Transitioning to Primary..."
|
|
fi |