    def ensure_connected
      # Don't run the reconnection login if we're already inside an
      # +ensure_connected+ block.
      return yield if Threaded.executing? :connection
      Threaded.begin :connection

      retry_on_failure = true

      begin
        connect unless connected?
        yield
      rescue Errors::ReplicaSetReconfigured
        # Someone else wrapped this in an #ensure_primary block, so let the
        # reconfiguration exception bubble up.
        raise
      rescue Errors::OperationFailure, Errors::AuthenticationFailure, Errors::QueryFailure
        # These exceptions are "expected" in the normal course of events, and
        # don't necessitate disconnecting.
        raise
      rescue Errors::ConnectionFailure
        disconnect

        if retry_on_failure
          # Maybe there was a hiccup -- try reconnecting one more time
          retry_on_failure = false
          retry
        else
          # Nope, we failed to connect twice. Flag the node as down and re-raise
          # the exception.
          down!
          raise
        end
      rescue
        # Looks like we got an unexpected error, so we'll clean up the connection
        # and re-raise the exception.
        disconnect
        raise $!.extend(Errors::SocketError)
      end
    ensure
      Threaded.end :connection
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.