def test_verify_vhost_maximum_connections(self):
        addr = "%s/$management" % self.address()
        timeout = 5

        # two connections should be ok
        denied = False
        try:
            bc1 = SyncRequestResponse(BlockingConnection(addr,
                                                         timeout=timeout))
            bc2 = SyncRequestResponse(BlockingConnection(addr,
                                                         timeout=timeout))
        except ConnectionException:
            denied = True
        except Timeout:
            denied = True

        self.assertFalse(denied)  # assert connections were opened

        # third connection should be denied
        denied = False
        try:
            bc3 = SyncRequestResponse(BlockingConnection(addr,
                                                         timeout=timeout))
        except ConnectionException:
            denied = True
        except Timeout:
            denied = True

        self.assertTrue(
            denied)  # assert if connection that should not open did open

        bc1.connection.close()
        bc2.connection.close()
Ejemplo n.º 2
0
    def __init__(self, router_host, router_port, cert_dir):
        self.router_host = router_host
        self.router_port = router_port
        self.cert_dir = cert_dir
        ssl_domain = None
        allowed_mechs = []
        sasl_enabled = False

        if self.cert_dir != None:
            ssl_domain = SSLDomain(SSLDomain.MODE_CLIENT)
            ssl_domain.set_trusted_ca_db(
                str(os.path.join(self.cert_dir, 'ca.crt')))
            ssl_domain.set_credentials(
                str(os.path.join(self.cert_dir, "tls.crt")),
                str(os.path.join(self.cert_dir, "tls.key")), None)
            ssl_domain.set_peer_authentication(SSLDomain.VERIFY_PEER)
            allowed_mechs = str("EXTERNAL")
            sasl_enabled = True

        self.client = SyncRequestResponse(
            BlockingConnection("amqps://" + self.router_host + ":" +
                               str(self.router_port),
                               30,
                               None,
                               ssl_domain,
                               allowed_mechs=allowed_mechs,
                               sasl_enabled=sasl_enabled), "$management")
Ejemplo n.º 3
0
 def __init__(self, connection):
     """
     Create a management client proxy using the given connection.
     """
     self.name = self.identity = u'self'
     self.type = u'org.amqp.management' # AMQP management node type
     self.url = connection.url
     self.client = SyncRequestResponse(connection, self.url.path)
    def test_link_route_lookup_not_found(self):
        """
        verify correct handling of lookup misses
        """
        bc = BlockingConnection(self.INT_A.edge_listener, timeout=TIMEOUT)
        srr = SyncRequestResponse(bc, self.QD_TERMINUS_ADDRESS_LOOKUP)

        rsp = self._check_response(srr.call(self._lookup_request("not.found.address", True)))
        self.assertEqual(self.QCM_ADDR_LOOKUP_NOT_FOUND, rsp[0])
Ejemplo n.º 5
0
    def query(
            self,
            entity_type: str = 'org.apache.qpid.dispatch.router.node') -> list:
        """
        Queries the related router instance, retrieving information for
        the provided Entity Type. The result is an array of a named tuple,
        whose fields are the attribute names returned by the router.
        In example, if querying entity type: org.apache.qpid.dispatch.allocator,
        the results can be accessed as: result.typeName, result.typeSize, ...
        same names returned by the router.
        :param entity_type:
        :return:
        """
        # Scheme to use
        scheme: str = 'amqp'
        if self._connection_options['ssl_domain']:
            scheme = 'amqps'

        # URL to test
        url: Url = Url('%s://%s:%s/$management' %
                       (scheme, self.host, self.port))
        self._logger.info('Querying router at: %s://%s:%s/$management' %
                          (scheme, self.host, self.port))

        # Proton connection
        self._logger.debug('Connection options: %s' % self._connection_options)
        connection: BlockingConnection = BlockingConnection(
            url, **self._connection_options)

        # Proton sync client
        client: SyncRequestResponse = SyncRequestResponse(connection, url.path)

        # Request message object
        request: proton.Message = proton.Message()
        request.properties = {
            u'operation': u'QUERY',
            u'entityType': u'%s' % entity_type,
        }
        request.body = {u'attributeNames': []}

        # Sending the request
        response: client.call = client.call(request)

        # Closing connection
        client.connection.close()

        # Namedtuple that represents the query response from the router
        # so fields can be read based on their attribute names.
        RouterQueryResults = namedtuple(
            'RouterQueryResults',
            response.body['attributeNames'])  # type: ignore
        records: list = []

        for record in response.body['results']:
            records.append(RouterQueryResults(*record))

        return records
Ejemplo n.º 6
0
 def _invalid_request_test(self, msg, disposition=Disposition.REJECTED):
     bc = BlockingConnection(self.INT_A.edge_listener, timeout=TIMEOUT)
     srr = SyncRequestResponse(bc, self.QD_TERMINUS_ADDRESS_LOOKUP)
     # @TODO(kgiusti) - self.assertRaises does not work here:
     try:
         srr.call(msg)
         self.assertTrue(False)
     except SendException as exc:
         self.assertEqual(disposition, exc.state)
     bc.close()
 def test_link_route_lookup_no_dest(self):
     """
     verify correct handling of matches to mobile addresses
     """
     bc = BlockingConnection(self.INT_A.edge_listener, timeout=TIMEOUT)
     srr = SyncRequestResponse(bc, self.QD_TERMINUS_ADDRESS_LOOKUP)
     rsp = self._check_response(srr.call(self._lookup_request("org.apache.A.nope", True)))
     self.assertEqual(self.QCM_ADDR_LOOKUP_OK, rsp[0])
     self.assertEqual(True, rsp[1])
     self.assertEqual(False, rsp[2])
     bc.close()
Ejemplo n.º 8
0
 def test_connection_properties(self):
     ensureCanTestExtendedSASL()
     server = ConnPropertiesServer(Url(host="127.0.0.1", port=free_tcp_port()), timeout=self.timeout)
     server.start()
     server.wait()
     connection = BlockingConnection(server.url, timeout=self.timeout, properties=CONNECTION_PROPERTIES, offered_capabilities=OFFERED_CAPABILITIES, desired_capabilities=DESIRED_CAPABILITIES)
     client = SyncRequestResponse(connection)
     client.connection.close()
     server.join(timeout=self.timeout)
     self.assertEquals(server.properties_received, True)
     self.assertEquals(server.offered_capabilities_received, True)
     self.assertEquals(server.desired_capabilities_received, True)
Ejemplo n.º 9
0
 def test_allowed_mechs_anonymous(self):
     # All this test does it make sure that if we pass allowed_mechs to BlockingConnection, it is actually used.
     server = ConnPropertiesServer(Url(host="127.0.0.1", port=free_tcp_port()), timeout=self.timeout)
     server.start()
     server.wait()
     # An ANONYMOUS allowed_mechs will work, anonymous connections are allowed by ConnPropertiesServer
     connection = BlockingConnection(server.url, timeout=self.timeout, properties=CONNECTION_PROPERTIES, offered_capabilities=OFFERED_CAPABILITIES, desired_capabilities=DESIRED_CAPABILITIES, allowed_mechs=ANONYMOUS)
     client = SyncRequestResponse(connection)
     client.connection.close()
     server.join(timeout=self.timeout)
     self.assertEquals(server.properties_received, True)
     self.assertEquals(server.offered_capabilities_received, True)
     self.assertEquals(server.desired_capabilities_received, True)
    def test_connection_properties(self):
        connection = BlockingConnection(self.router.addresses[0],
                                        timeout=60,
                                        properties=CONNECTION_PROPERTIES)
        client = SyncRequestResponse(connection)

        node = Node.connect(self.router.addresses[0])

        results = node.query(type='org.apache.qpid.dispatch.connection', attribute_names=[u'properties']).results

        self.assertEqual(results[0][0][u'connection'], u'properties')
        self.assertEqual(results[0][0][u'int_property'], 6451)

        client.connection.close()
Ejemplo n.º 11
0
    def __init__(self, connection, locales=None):
        """
        Create a management node proxy using the given connection.
        @param locales: Default list of locales for management operations.
        @param connection: a L{BlockingConnection} to the management agent.
        """
        self.name = self.identity = u'self'
        self.type = u'org.amqp.management'  # AMQP management node type
        self.locales = locales

        self.locales = locales
        self.url = connection.url
        self.client = SyncRequestResponse(connection, self.url.path)
        self.reply_to = self.client.reply_to
Ejemplo n.º 12
0
    def test_link_route_lookup_not_link_route(self):
        """
        verify correct handling of matches to mobile addresses
        """
        addr = "not.a.linkroute"
        client = AsyncTestReceiver(self.INT_A.listener, addr)
        self.INT_A.wait_address(addr)

        bc = BlockingConnection(self.INT_A.edge_listener, timeout=TIMEOUT)
        srr = SyncRequestResponse(bc, self.QD_TERMINUS_ADDRESS_LOOKUP)

        rsp = self._check_response(srr.call(self._lookup_request(addr, True)))
        # self.assertEqual(self.QCM_ADDR_LOOKUP_OK, rsp[0])
        self.assertEqual(False, rsp[1])
        bc.close()
        client.stop()
    def test_sync_request_response_blocking_connection_no_object_leaks(self):
        with test_broker() as tb:
            sockname = tb.get_acceptor_sockname()
            url = "{0}:{1}".format(*sockname)
            opts = namedtuple('Opts', ['address', 'timeout'])(address=url, timeout=3)

            with no_fd_leaks(self):
                client = SyncRequestResponse(
                    BlockingConnection(url, opts.timeout, allowed_mechs="ANONYMOUS"), "somequeue")
                try:
                    request = "One Two Three Four"
                    response = client.call(Message(body=request))
                finally:
                    client.connection.close()

        gc.collect()
Ejemplo n.º 14
0
 def get_metrics(self):
     client = SyncRequestResponse(BlockingConnection("127.0.0.1:5672", 30),
                                  "$management")
     try:
         properties = {}
         properties["entityType"] = "org.apache.qpid.dispatch.connection"
         properties["operation"] = "QUERY"
         properties["name"] = "self"
         message = Message(body=None, properties=properties)
         response = client.call(message)
         return response
     except:
         e = sys.exc_info()[0]
         print("Error querying router for metrics: %s" % e)
         return None
     finally:
         client.connection.close()
Ejemplo n.º 15
0
    def test_request_response(self):
        ensureCanTestExtendedSASL()
        def test(name, address="x"):
            for i in range(5):
                body="%s%s" % (name, i)
                response = client.call(Message(address=address, body=body))
                self.assertEquals(response.address, client.reply_to)
                self.assertEquals(response.body, body)

        server = EchoServer(Url(host="127.0.0.1", port=free_tcp_port()), self.timeout)
        server.start()
        server.wait()
        connection = BlockingConnection(server.url, timeout=self.timeout)
        client = SyncRequestResponse(connection)
        try:
            test("foo")         # Simple request/resposne
        finally:
            client.connection.close()
        server.join(timeout=self.timeout)
Ejemplo n.º 16
0
    def test_link_route_lookup_ok(self):
        """
        verify a link route address can be looked up successfully for both
        locally attached and remotely attached containers
        """

        # fire up a fake broker attached to the router local to the edge router
        # wait until both in and out addresses are ready
        fb = FakeBroker(self.INT_A.broker_connector,
                        container_id='FakeBrokerA')
        self.INT_A.wait_address("org.apache.A", containers=1, count=2)

        # create a fake edge and lookup the target address
        bc = BlockingConnection(self.INT_A.edge_listener, timeout=TIMEOUT)
        srr = SyncRequestResponse(bc, self.QD_TERMINUS_ADDRESS_LOOKUP)

        for direction in [True, False]:
            # True = direction inbound (receiver) False = direction outbound (sender)
            rsp = self._check_response(
                srr.call(self._lookup_request("org.apache.A.foo", direction)))
            self.assertEqual(self.QCM_ADDR_LOOKUP_OK, rsp[0])
            self.assertTrue(rsp[1])
            self.assertTrue(rsp[2])

        # shutdown fake router
        fb.join()

        # now fire up a fake broker attached to the remote router
        fb = FakeBroker(self.INT_B.broker_connector,
                        container_id='FakeBrokerB')
        self.INT_A.wait_address("org.apache.B", remotes=1, count=2)

        for direction in [True, False]:
            rsp = self._check_response(
                srr.call(self._lookup_request("org.apache.B.foo", direction)))
            self.assertEqual(self.QCM_ADDR_LOOKUP_OK, rsp[0])
            self.assertTrue(rsp[1])
            self.assertTrue(rsp[2])

        fb.join()
        bc.close()
Ejemplo n.º 17
0
    def __init__(self, router_address, timeout, router_id=None, edge_id=None):
        """
        @param router_address: the network address of the router to manage.
        @param timeout: raise an error if a management operation blocks longer
        than timeout seconds.
        @param router_id: identity of remote router.  Use this if the router to
        be managed is not the router at router_address.  This can be used to
        access a remote router using a local router as a proxy.
        @param edge_id: like router_id except remote is an edge router.

        Note that router_id and edge_id are mutually exclusive
        """
        assert (not (edge_id and router_id))
        self._conn = BlockingConnection(router_address, timeout=timeout)
        if router_id:
            self._mgmt_address = u'_topo/0/%s/$management' % router_id
        elif edge_id:
            self._mgmt_address = u'_edge/%s/$management' % edge_id
        else:
            self._mgmt_address = u'$management'
        self._client = SyncRequestResponse(self._conn, self._mgmt_address)
 def collect_metric(self, entityType):
     try:
         client = SyncRequestResponse(
             BlockingConnection("127.0.0.1:5672", 30), "$management")
         try:
             properties = {}
             properties["entityType"] = entityType
             properties["operation"] = "QUERY"
             properties["name"] = "self"
             message = Message(body=None, properties=properties)
             response = client.call(message)
             if response == None:
                 return response
             else:
                 return RouterResponse(response)
         finally:
             client.connection.close()
     except:
         e = sys.exc_info()[0]
         print("Error querying router for metrics: %s" % e)
         return None
Ejemplo n.º 19
0
    def collect(self):
        collector_map = self.create_collector_map()
        fetcher_map = self.create_entity_map(collector_map)
        connection = None
        print("Collecting metrics")

        try:
            connection = BlockingConnection("amqps://" + self.router_host +
                                            ":" + str(self.router_port),
                                            30,
                                            None,
                                            self.ssl_domain,
                                            allowed_mechs=self.allowed_mechs,
                                            sasl_enabled=self.sasl_enabled,
                                            container_id="router-metrics")
            client = SyncRequestResponse(connection, "$management")
            for fetcher in fetcher_map:
                response = fetcher(client)
                if response != None:
                    for collector in fetcher_map[fetcher]:
                        for entity in response.get_results():
                            if response.contains(entity, collector.filter):
                                labels = []
                                for l in collector.labels:
                                    label_idx = response.get_index(l)
                                    if label_idx != None and entity[
                                            label_idx] != None:
                                        labels.append(entity[label_idx])
                                    else:
                                        labels.append("")
                                value = entity[response.get_index(
                                    collector.name)]
                                collector.add(labels, int(value))
        finally:
            if connection != None:
                connection.close()

        for collector in collector_map.itervalues():
            yield collector.metric()
Ejemplo n.º 20
0
parser = optparse.OptionParser(
    usage="usage: %prog [options]",
    description="Send requests to the supplied address and print responses.")
parser.add_option("-a",
                  "--address",
                  default="localhost:5672/examples",
                  help="address to which messages are sent (default %default)")
parser.add_option("-t",
                  "--timeout",
                  type="float",
                  default=5,
                  help="Give up after this time out (default %default)")
opts, args = parser.parse_args()

url = Url(opts.address)
client = SyncRequestResponse(BlockingConnection(url, timeout=opts.timeout),
                             url.path)

try:
    REQUESTS = [
        "Twas brillig, and the slithy toves",
        "Did gire and gymble in the wabe.", "All mimsy were the borogroves,",
        "And the mome raths outgrabe."
    ]
    for request in REQUESTS:
        response = client.call(Message(body=request))
        print "%s => %s" % (request, response.body)
finally:
    client.connection.close()
Ejemplo n.º 21
0
 def set_client(self, url_path):
     if url_path:
         self.url.path = u'%s' % url_path
         self.client = SyncRequestResponse(self.connection, self.url.path)