|
17 | 17 |
|
18 | 18 | import os |
19 | 19 | import sys |
| 20 | +import time |
20 | 21 | import warnings |
21 | 22 |
|
22 | 23 | import pymongo |
@@ -49,18 +50,25 @@ def _split_host_port(host_port): |
49 | 50 | # When testing against a replica set, 'host' and 'port' need |
50 | 51 | # to represent the primary. |
51 | 52 | try: |
52 | | - _ismaster = pymongo.MongoClient(host, port).admin.command('ismaster') |
53 | | - # Master slave topologies don't use setName. The members also aren't |
54 | | - # aware of one another (e.g. ismaster doesn't have a 'hosts' field). |
55 | | - if 'setName' in _ismaster: |
56 | | - _primary = _ismaster['primary'] |
57 | | - host, port = _split_host_port(_primary) |
58 | | - _secondaries = set(_ismaster['hosts']) - set([_primary]) |
59 | | - for _idx, _host_port in enumerate(_secondaries): |
60 | | - _host, _port = _split_host_port(_host_port) |
61 | | - # Enumerate doesn't accept a start argument until python 2.6. |
62 | | - setattr(sys.modules[__name__], "host%d" % (_idx + 1,), _host) |
63 | | - setattr(sys.modules[__name__], "port%d" % (_idx + 1,), _port) |
| 53 | + # Try to find the primary for 10 seconds. |
| 54 | + for _ in range(10): |
| 55 | + _ismaster = pymongo.MongoClient(host, port).admin.command('ismaster') |
| 56 | + # Master slave topologies don't use setName. The members also aren't |
| 57 | + # aware of one another (e.g. ismaster doesn't have a 'hosts' field). |
| 58 | + if 'setName' in _ismaster: |
| 59 | + _primary = _ismaster.get('primary') |
| 60 | + # No primary (yet?) |
| 61 | + if _primary is None: |
| 62 | + time.sleep(1) |
| 63 | + continue |
| 64 | + host, port = _split_host_port(_primary) |
| 65 | + _secondaries = set(_ismaster['hosts']) - set([_primary]) |
| 66 | + for _idx, _host_port in enumerate(_secondaries): |
| 67 | + _host, _port = _split_host_port(_host_port) |
| 68 | + # Enumerate doesn't accept a start argument until python 2.6. |
| 69 | + setattr(sys.modules[__name__], "host%d" % (_idx + 1,), _host) |
| 70 | + setattr(sys.modules[__name__], "port%d" % (_idx + 1,), _port) |
| 71 | + break |
64 | 72 | except ConnectionFailure: |
65 | 73 | pass |
66 | 74 |
|
|
0 commit comments