Ensure that the client's connection pool has socket connections to all members of a replica set. Raises ConfigurationError when called with a non-replica set client. Depending on the use-case, the caller may need to clear any event listeners that are configured on the client.
(client: MongoClient)
| 89 | |
| 90 | |
| 91 | def ensure_all_connected(client: MongoClient) -> None: |
| 92 | """Ensure that the client's connection pool has socket connections to all |
| 93 | members of a replica set. Raises ConfigurationError when called with a |
| 94 | non-replica set client. |
| 95 | |
| 96 | Depending on the use-case, the caller may need to clear any event listeners |
| 97 | that are configured on the client. |
| 98 | """ |
| 99 | hello: dict = client.admin.command(HelloCompat.LEGACY_CMD) |
| 100 | if "setName" not in hello: |
| 101 | raise ConfigurationError("cluster is not a replica set") |
| 102 | |
| 103 | target_host_list = set(hello["hosts"] + hello.get("passives", [])) |
| 104 | connected_host_list = {hello["me"]} |
| 105 | |
| 106 | # Run hello until we have connected to each host at least once. |
| 107 | def discover(): |
| 108 | i = 0 |
| 109 | while i < 100 and connected_host_list != target_host_list: |
| 110 | hello: dict = client.admin.command( |
| 111 | HelloCompat.LEGACY_CMD, read_preference=ReadPreference.SECONDARY |
| 112 | ) |
| 113 | connected_host_list.update([hello["me"]]) |
| 114 | i += 1 |
| 115 | return connected_host_list |
| 116 | |
| 117 | try: |
| 118 | |
| 119 | def predicate(): |
| 120 | return target_host_list == discover() |
| 121 | |
| 122 | wait_until(predicate, "connected to all hosts") |
| 123 | except AssertionError as exc: |
| 124 | raise AssertionError( |
| 125 | f"{exc}, {connected_host_list} != {target_host_list}, {client.topology_description}" |
| 126 | ) |
| 127 | |
| 128 | |
| 129 | def assertRaisesExactly(cls, fn, *args, **kwargs): |