|
1 | 1 | import enum |
2 | 2 | import json |
| 3 | +import logging |
3 | 4 | import pathlib |
4 | 5 | import random |
5 | 6 | from functools import lru_cache |
|
13 | 14 | from django.db.models import Manager, Model |
14 | 15 | from django.db.utils import OperationalError |
15 | 16 |
|
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
16 | 19 | UNKNOWN = "unknown" |
17 | 20 | VERSIONS_INFO_FILE_LOCATION = ".versions.json" |
18 | 21 |
|
@@ -138,34 +141,38 @@ def using_database_replica( |
138 | 141 | local_replicas = [name for name in connections if name.startswith(replica_prefix)] |
139 | 142 |
|
140 | 143 | if not local_replicas: |
| 144 | + logger.info("No replicas set up.") |
141 | 145 | return manager |
142 | 146 |
|
143 | 147 | chosen_replica = None |
144 | 148 |
|
145 | 149 | if settings.REPLICA_READ_STRATEGY == ReplicaReadStrategy.SEQUENTIAL: |
146 | 150 | _sequential_replica_manager.setdefault(replica_prefix, cycle(local_replicas)) |
147 | | - for attempt in range(len(local_replicas)): |
| 151 | + for _ in range(len(local_replicas)): |
148 | 152 | attempted_replica = next(_sequential_replica_manager[replica_prefix]) |
149 | 153 | try: |
150 | 154 | connections[attempted_replica].ensure_connection() |
151 | 155 | chosen_replica = attempted_replica |
152 | 156 | break |
153 | 157 | except OperationalError: |
| 158 | + logger.warning(f"Replica '{attempted_replica}' is not available.") |
154 | 159 | continue |
155 | 160 |
|
156 | 161 | if settings.REPLICA_READ_STRATEGY == ReplicaReadStrategy.DISTRIBUTED: |
157 | | - for attempt in range(len(local_replicas)): |
| 162 | + for _ in range(len(local_replicas)): |
158 | 163 | attempted_replica = random.choice(local_replicas) |
159 | 164 | try: |
160 | 165 | connections[attempted_replica].ensure_connection() |
161 | 166 | chosen_replica = attempted_replica |
162 | 167 | break |
163 | 168 | except OperationalError: |
| 169 | + logger.warning(f"Replica '{attempted_replica}' is not available.") |
164 | 170 | local_replicas.remove(attempted_replica) |
165 | 171 | continue |
166 | 172 |
|
167 | 173 | if not chosen_replica: |
168 | 174 | if replica_prefix == "replica_": |
| 175 | + logger.warning("Falling back to cross-region replicas, if any.") |
169 | 176 | return using_database_replica(manager, "cross_region_replica_") |
170 | 177 | raise OperationalError("No available replicas") |
171 | 178 |
|
|
0 commit comments