Connect to Mongo and return a new Connection. Can raise ConnectionFailure. Note that the pool does not keep a reference to the socket -- you must call checkin() when you're done with it.
(self, handler: Optional[_MongoClientErrorHandler] = None)
| 1003 | error._add_error_label("RetryableError") |
| 1004 | |
| 1005 | def connect(self, handler: Optional[_MongoClientErrorHandler] = None) -> Connection: |
| 1006 | """Connect to Mongo and return a new Connection. |
| 1007 | |
| 1008 | Can raise ConnectionFailure. |
| 1009 | |
| 1010 | Note that the pool does not keep a reference to the socket -- you |
| 1011 | must call checkin() when you're done with it. |
| 1012 | """ |
| 1013 | with self.lock: |
| 1014 | conn_id = self.next_connection_id |
| 1015 | self.next_connection_id += 1 |
| 1016 | # Use a temporary context so that interrupt_connections can cancel creating the socket. |
| 1017 | tmp_context = _CancellationContext() |
| 1018 | self.active_contexts.add(tmp_context) |
| 1019 | |
| 1020 | listeners = self.opts._event_listeners |
| 1021 | if self.enabled_for_cmap: |
| 1022 | assert listeners is not None |
| 1023 | listeners.publish_connection_created(self.address, conn_id) |
| 1024 | if self.enabled_for_logging and _CONNECTION_LOGGER.isEnabledFor(logging.DEBUG): |
| 1025 | _debug_log( |
| 1026 | _CONNECTION_LOGGER, |
| 1027 | message=_ConnectionStatusMessage.CONN_CREATED, |
| 1028 | clientId=self._client_id, |
| 1029 | serverHost=self.address[0], |
| 1030 | serverPort=self.address[1], |
| 1031 | driverConnectionId=conn_id, |
| 1032 | ) |
| 1033 | |
| 1034 | try: |
| 1035 | networking_interface = _configured_socket_interface(self.address, self.opts) |
| 1036 | # Catch KeyboardInterrupt, CancelledError, etc. and cleanup. |
| 1037 | except BaseException as error: |
| 1038 | with self.lock: |
| 1039 | self.active_contexts.discard(tmp_context) |
| 1040 | if self.enabled_for_cmap: |
| 1041 | assert listeners is not None |
| 1042 | listeners.publish_connection_closed( |
| 1043 | self.address, conn_id, ConnectionClosedReason.ERROR |
| 1044 | ) |
| 1045 | if self.enabled_for_logging and _CONNECTION_LOGGER.isEnabledFor(logging.DEBUG): |
| 1046 | _debug_log( |
| 1047 | _CONNECTION_LOGGER, |
| 1048 | message=_ConnectionStatusMessage.CONN_CLOSED, |
| 1049 | clientId=self._client_id, |
| 1050 | serverHost=self.address[0], |
| 1051 | serverPort=self.address[1], |
| 1052 | driverConnectionId=conn_id, |
| 1053 | reason=_verbose_connection_error_reason(ConnectionClosedReason.ERROR), |
| 1054 | error=ConnectionClosedReason.ERROR, |
| 1055 | ) |
| 1056 | self._handle_connection_error(error) |
| 1057 | if isinstance(error, (IOError, OSError, *SSLErrors)): |
| 1058 | details = _get_timeout_details(self.opts) |
| 1059 | _raise_connection_failure(self.address, error, timeout_details=details) |
| 1060 | raise |
| 1061 | |
| 1062 | conn = Connection(networking_interface, self, self.address, conn_id, self.is_sdam) # type: ignore[arg-type] |
no test coverage detected