|
| 1 | +import sys |
| 2 | +import time |
| 3 | + |
1 | 4 | from flask import Flask |
2 | 5 | from pymongo import MongoClient |
| 6 | +from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError |
3 | 7 | import os |
4 | 8 | import logging |
5 | 9 | from celery import Celery |
|
11 | 15 | __version__ = "1.1.2-beta.1" |
12 | 16 |
|
13 | 17 | MONGO_URI = os.getenv("MONGO_URI") |
| 18 | + |
| 19 | + |
| 20 | + |
| 21 | +def wait_for_mongodb_replicaset(logger, max_retries=120, retry_interval=5): |
| 22 | + """ |
| 23 | + Wait for MongoDB to be ready before starting the application. |
| 24 | + For replica sets, waits for PRIMARY to be elected. |
| 25 | + """ |
| 26 | + mongo_mode = os.getenv("MONGODB_MODE", "standalone").lower() |
| 27 | + if mongo_mode == "standalone": |
| 28 | + logger.info("MongoDB is in standalone mode, skipping ReplicaSet wait") |
| 29 | + return |
| 30 | + |
| 31 | + mongo_uri = os.getenv("MONGO_URI") |
| 32 | + |
| 33 | + if not mongo_uri: |
| 34 | + logger.warning("MONGO_URI not set, exiting application") |
| 35 | + sys.exit(1) |
| 36 | + |
| 37 | + logger.info(f"Waiting for MongoDB ReplicaSet to be ready and elect the primary...") |
| 38 | + |
| 39 | + for attempt in range(1, max_retries + 1): |
| 40 | + try: |
| 41 | + # Try to connect |
| 42 | + client = MongoClient( |
| 43 | + mongo_uri, serverSelectionTimeoutMS=5000, connectTimeoutMS=5000 |
| 44 | + ) |
| 45 | + |
| 46 | + # Execute a simple operation to verify PRIMARY exists |
| 47 | + client.admin.command("ping") |
| 48 | + |
| 49 | + # For replica sets, verify PRIMARY exists |
| 50 | + if "replicaSet=" in mongo_uri: |
| 51 | + if client.primary is None: |
| 52 | + raise Exception("No PRIMARY elected yet") |
| 53 | + logger.info(f"PRIMARY found: {client.primary}") |
| 54 | + |
| 55 | + client.close() |
| 56 | + logger.info("MongoDB is ready") |
| 57 | + return |
| 58 | + |
| 59 | + except (ServerSelectionTimeoutError, ConnectionFailure, Exception) as e: |
| 60 | + if attempt >= max_retries: |
| 61 | + logger.info( |
| 62 | + f"MongoDB not ready after {max_retries * retry_interval}s" |
| 63 | + ) |
| 64 | + logger.info(f" Error: {e}") |
| 65 | + sys.exit(1) |
| 66 | + |
| 67 | + if attempt % 6 == 0: # Print every 30 seconds |
| 68 | + logger.info( |
| 69 | + f" Still waiting... ({attempt}/{max_retries}) - {e.__class__.__name__}" |
| 70 | + ) |
| 71 | + |
| 72 | + time.sleep(retry_interval) |
| 73 | + |
| 74 | +wait_for_mongodb_replicaset(logging.getLogger()) |
14 | 75 | mongo_client = MongoClient(MONGO_URI) |
15 | 76 |
|
16 | 77 | VALUES_DIRECTORY = os.getenv("VALUES_DIRECTORY", "") |
|
0 commit comments