Ejemplo n.º 1
0
def make_server_description(server, hosts):
    """Make ServerDescription from server info from JSON file."""
    server_type = server['type']
    if server_type == "Unknown":
        return ServerDescription(clean_node(server['address']), IsMaster({}))

    ismaster_response = {'ok': True, 'hosts': hosts}
    if server_type != "Standalone" and server_type != "Mongos":
        ismaster_response['setName'] = "rs"

    if server_type == "RSPrimary":
        ismaster_response['ismaster'] = True
    elif server_type == "RSSecondary":
        ismaster_response['secondary'] = True
    elif server_type == "Mongos":
        ismaster_response['msg'] = 'isdbgrid'

    ismaster_response['lastWrite'] = {
        'lastWriteDate': make_last_write_date(server)
    }

    for field in 'maxWireVersion', 'tags', 'idleWritePeriodMillis':
        if field in server:
            ismaster_response[field] = server[field]

    # Sets _last_update_time to now.
    sd = ServerDescription(clean_node(server['address']),
                           IsMaster(ismaster_response),
                           round_trip_time=server['avg_rtt_ms'])

    sd._last_update_time = server['lastUpdateTime'] / 1000.0  # ms to sec.
    return sd
Ejemplo n.º 2
0
    def run_scenario(self, scenario_def):
        topology = create_topology(scenario_def)

        # Update mock operation_count state:
        for mock in scenario_def['mocked_topology_state']:
            address = clean_node(mock['address'])
            server = topology.get_server_by_address(address)
            server.pool.operation_count = mock['operation_count']

        pref = ReadPreference.NEAREST
        counts = dict(
            (address, 0)
            for address in topology._description.server_descriptions())

        # Number of times to repeat server selection
        iterations = scenario_def['iterations']
        for _ in range(iterations):
            server = topology.select_server(pref, server_selection_timeout=0)
            counts[server.description.address] += 1

        # Verify expected_frequencies
        outcome = scenario_def['outcome']
        tolerance = outcome['tolerance']
        expected_frequencies = outcome['expected_frequencies']
        for host_str, freq in expected_frequencies.items():
            address = clean_node(host_str)
            actual_freq = float(counts[address]) / iterations
            if freq == 0:
                # Should be exactly 0.
                self.assertEqual(actual_freq, 0)
            else:
                # Should be within 'tolerance'.
                self.assertAlmostEqual(actual_freq, freq, delta=tolerance)
def make_server_description(server, hosts):
    """Make a ServerDescription from server info in a JSON test."""
    server_type = server['type']
    if server_type == "Unknown":
        return ServerDescription(clean_node(server['address']), IsMaster({}))

    ismaster_response = {'ok': True, 'hosts': hosts}
    if server_type != "Standalone" and server_type != "Mongos":
        ismaster_response['setName'] = "rs"

    if server_type == "RSPrimary":
        ismaster_response['ismaster'] = True
    elif server_type == "RSSecondary":
        ismaster_response['secondary'] = True
    elif server_type == "Mongos":
        ismaster_response['msg'] = 'isdbgrid'

    ismaster_response['lastWrite'] = {
        'lastWriteDate': make_last_write_date(server)
    }

    for field in 'maxWireVersion', 'tags', 'idleWritePeriodMillis':
        if field in server:
            ismaster_response[field] = server[field]

    # Sets _last_update_time to now.
    sd = ServerDescription(clean_node(server['address']),
                           IsMaster(ismaster_response),
                           round_trip_time=server['avg_rtt_ms'] / 1000.0)

    if 'lastUpdateTime' in server:
        sd._last_update_time = server['lastUpdateTime'] / 1000.0  # ms to sec.

    return sd
Ejemplo n.º 4
0
def get_addresses(server_list):
    seeds = []
    hosts = []
    for server in server_list:
        seeds.append(clean_node(server['address']))
        hosts.append(server['address'])
    return seeds, hosts
def get_addresses(server_list):
    seeds = []
    hosts = []
    for server in server_list:
        seeds.append(clean_node(server['address']))
        hosts.append(server['address'])
    return seeds, hosts
    def _run_scenario(self):
        class NoopMonitor(Monitor):
            """Override the _run method to do nothing."""
            def _run(self):
                time.sleep(0.05)

        m = single_client(h=scenario_def['uri'],
                          p=27017,
                          event_listeners=[self.all_listener],
                          _monitor_class=NoopMonitor)
        topology = m._get_topology()

        try:
            for phase in scenario_def['phases']:
                for (source, response) in phase['responses']:
                    source_address = clean_node(source)
                    topology.on_change(
                        ServerDescription(address=source_address,
                                          ismaster=IsMaster(response),
                                          round_trip_time=0))

                expected_results = phase['outcome']['events']
                expected_len = len(expected_results)
                wait_until(
                    lambda: len(self.all_listener.results) >= expected_len,
                    "publish all events",
                    timeout=15)

                # Wait some time to catch possible lagging extra events.
                time.sleep(0.5)

                i = 0
                while i < expected_len:
                    result = self.all_listener.results[i] if len(
                        self.all_listener.results) > i else None
                    # The order of ServerOpening/ClosedEvents doesn't matter
                    if isinstance(result, (monitoring.ServerOpeningEvent,
                                           monitoring.ServerClosedEvent)):
                        i, passed, message = compare_multiple_events(
                            i, expected_results, self.all_listener.results)
                        self.assertTrue(passed, message)
                    else:
                        self.assertTrue(
                            *compare_events(expected_results[i], result))
                        i += 1

                # Assert no extra events.
                extra_events = self.all_listener.results[expected_len:]
                if extra_events:
                    self.fail('Extra events %r' % (extra_events, ))

                self.all_listener.reset()
        finally:
            m.close()
Ejemplo n.º 7
0
def make_server_description(server, hosts):
    """Make a ServerDescription from server info in a JSON test."""
    server_type = server['type']
    if server_type in ("Unknown", "PossiblePrimary"):
        return ServerDescription(clean_node(server['address']), Hello({}))

    hello_response = {'ok': True, 'hosts': hosts}
    if server_type not in ("Standalone", "Mongos", "RSGhost"):
        hello_response['setName'] = "rs"

    if server_type == "RSPrimary":
        hello_response[HelloCompat.LEGACY_CMD] = True
    elif server_type == "RSSecondary":
        hello_response['secondary'] = True
    elif server_type == "Mongos":
        hello_response['msg'] = 'isdbgrid'
    elif server_type == "RSGhost":
        hello_response['isreplicaset'] = True
    elif server_type == "RSArbiter":
        hello_response['arbiterOnly'] = True

    hello_response['lastWrite'] = {
        'lastWriteDate': make_last_write_date(server)
    }

    for field in 'maxWireVersion', 'tags', 'idleWritePeriodMillis':
        if field in server:
            hello_response[field] = server[field]

    hello_response.setdefault('maxWireVersion', 6)

    # Sets _last_update_time to now.
    sd = ServerDescription(clean_node(server['address']),
                           Hello(hello_response),
                           round_trip_time=server['avg_rtt_ms'] / 1000.0)

    if 'lastUpdateTime' in server:
        sd._last_update_time = server['lastUpdateTime'] / 1000.0  # ms to sec.

    return sd
Ejemplo n.º 8
0
def make_server_description(server, hosts):
    """Make ServerDescription from server info from JSON file."""
    ismaster_response = {}
    ismaster_response['tags'] = server['tags']
    ismaster_response['ok'] = True
    ismaster_response['hosts'] = hosts

    server_type = server['type']

    if server_type != "Standalone" and server_type != "Mongos":
        ismaster_response['setName'] = True
    if server_type == "RSPrimary":
        ismaster_response['ismaster'] = True
    elif server_type == "RSSecondary":
        ismaster_response['secondary'] = True
    elif server_type == "Mongos":
        ismaster_response['msg'] = 'isdbgrid'

    return ServerDescription(clean_node(server['address']),
                             IsMaster(ismaster_response),
                             round_trip_time=server['avg_rtt_ms'])
def make_server_description(server, hosts):
    """Make ServerDescription from server info from JSON file."""
    ismaster_response = {}
    ismaster_response['tags'] = server['tags']
    ismaster_response['ok'] = True
    ismaster_response['hosts'] = hosts

    server_type = server['type']

    if server_type != "Standalone" and server_type != "Mongos":
        ismaster_response['setName'] = True
    if server_type == "RSPrimary":
        ismaster_response['ismaster'] = True
    elif server_type == "RSSecondary":
        ismaster_response['secondary'] = True
    elif server_type == "Mongos":
        ismaster_response['msg'] = 'isdbgrid'

    return ServerDescription(clean_node(server['address']),
                             IsMaster(ismaster_response),
                             round_trip_time=server['avg_rtt_ms'])
Ejemplo n.º 10
0
 def me(self):
     me = self._doc.get('me')
     if me:
         return common.clean_node(me)
Ejemplo n.º 11
0
 def me(self) -> Optional[Tuple[str, int]]:
     me = self._doc.get("me")
     if me:
         return common.clean_node(me)
     return None
Ejemplo n.º 12
0
 def me(self):
     me = self._doc.get('me')
     if me:
         return common.clean_node(me)