<commit_before># Copyright 2009-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License.  You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.  See the License for the specific language governing
# permissions and limitations under the License.

"""Internal class to monitor a topology of one or more servers."""

import random
import threading
import time

from bson.py3compat import itervalues
from pymongo import common
from pymongo.topology_description import (updated_topology_description,
                                          TOPOLOGY_TYPE,
                                          TopologyDescription)
from pymongo.errors import AutoReconnect
from pymongo.server import Server
from pymongo.server_selectors import (arbiter_server_selector,
                                      secondary_server_selector,
                                      writable_server_selector)


class Topology(object):
    """Monitor a topology of one or more servers."""
    def __init__(self, topology_settings):
        self._settings = topology_settings
        topology_description = TopologyDescription(
            topology_settings.get_topology_type(),
            topology_settings.get_server_descriptions(),
            topology_settings.set_name)

        self._description = topology_description
        self._opened = False
        self._lock = threading.Lock()
        self._condition = self._settings.condition_class(self._lock)
        self._servers = {}

    def open(self):
        """Start monitoring, or restart after a fork.

        No effect if called multiple times.
        """
        with self._lock:
            self._ensure_opened()

    def select_servers(self, selector, server_wait_time=None):
        """Return a list of Servers matching selector, or time out.

        :Parameters:
          - `selector`: function that takes a list of Servers and returns
            a subset of them.
          - `server_wait_time` (optional): maximum seconds to wait. If not
            provided, the default value common.SERVER_WAIT_TIME is used.

        Raises exc:`AutoReconnect` after `server_wait_time` if no
        matching servers are found.
        """
        if server_wait_time is None:
            wait_time = common.SERVER_WAIT_TIME
        else:
            wait_time = server_wait_time

        with self._lock:
            self._description.check_compatible()

            # TODO: use monotonic time if available.
            now = time.time()
            end_time = now + wait_time
            server_descriptions = self._apply_selector(selector)

            while not server_descriptions:
                # No suitable servers.
                if wait_time == 0 or now > end_time:
                    # TODO: more error diagnostics. E.g., if state is
                    # ReplicaSet but every server is Unknown, and the host
                    # list is non-empty, and doesn't intersect with
                    # settings.seeds, the set is probably configured with
                    # internal hostnames or IPs and we're connecting from
                    # outside. Or if we're a replica set and
                    # server_descriptions is empty, we have the wrong
                    # set_name. Include TopologyDescription's str() in
                    # exception msg.
                    raise AutoReconnect("No suitable servers available")<commit_msg>Note that Topology.select_server() calls open() if needed.<commit_after># Copyright 2009-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License.  You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.  See the License for the specific language governing
# permissions and limitations under the License.

"""Internal class to monitor a topology of one or more servers."""

import random
import threading
import time

from bson.py3compat import itervalues
from pymongo import common
from pymongo.topology_description import (updated_topology_description,
                                          TOPOLOGY_TYPE,
                                          TopologyDescription)
from pymongo.errors import AutoReconnect
from pymongo.server import Server
from pymongo.server_selectors import (arbiter_server_selector,
                                      secondary_server_selector,
                                      writable_server_selector)


class Topology(object):
    """Monitor a topology of one or more servers."""
    def __init__(self, topology_settings):
        self._settings = topology_settings
        topology_description = TopologyDescription(
            topology_settings.get_topology_type(),
            topology_settings.get_server_descriptions(),
            topology_settings.set_name)

        self._description = topology_description
        self._opened = False
        self._lock = threading.Lock()
        self._condition = self._settings.condition_class(self._lock)
        self._servers = {}

    def open(self):
        """Start monitoring, or restart after a fork.

        No effect if called multiple times.
        """
        with self._lock:
            self._ensure_opened()

    def select_servers(self, selector, server_wait_time=None):
        """Return a list of Servers matching selector, or time out.

        :Parameters:
          - `selector`: function that takes a list of Servers and returns
            a subset of them.
          - `server_wait_time` (optional): maximum seconds to wait. If not
            provided, the default value common.SERVER_WAIT_TIME is used.

        Calls self.open() if needed.

        Raises exc:`AutoReconnect` after `server_wait_time` if no
        matching servers are found.
        """
        if server_wait_time is None:
            wait_time = common.SERVER_WAIT_TIME
        else:
            wait_time = server_wait_time

        with self._lock:
            self._description.check_compatible()

            # TODO: use monotonic time if available.
            now = time.time()
            end_time = now + wait_time
            server_descriptions = self._apply_selector(selector)

            while not server_descriptions:
                # No suitable servers.
                if wait_time == 0 or now > end_time:
                    # TODO: more error diagnostics. E.g., if state is
                    # ReplicaSet but every server is Unknown, and the host
                    # list is non-empty, and doesn't intersect with
                    # settings.seeds, the set is probably configured with
                    # internal hostnames or IPs and we're connecting from
                    # outside. Or if we're a replica set and
                    # server_descriptions is empty, we have the wrong
                    # set_name. Include TopologyDescription's str() in
                    # exception msg.
                    raise AutoReconnect("No suitable servers available")
{'fraction_non_alphanumeric': 0.061798494652053344, 'fraction_numerical': 0.0036973458338835337, 'mean_word_length': 2.1245874587458746, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6095237', 'n_tokens_mistral': 1876, 'n_tokens_neox': 1770, 'n_words': 673}