Example #1
0
    def __post_init__(self):
        if not self.tls_ca_cert and self.tls_ca_cert_path:
            with open(self.tls_ca_cert_path, 'rb') as inf:
                self.tls_ca_cert = inf.read()
        if not self.client_cert and self.client_cert_path:
            with open(self.client_cert_path, 'rb') as inf:
                self.client_cert = inf.read()
        if not self.client_key and self.client_key_path:
            with open(self.client_key_path, 'rb') as inf:
                self.client_key = inf.read()

        opts = [
            ("grpc.ssl_target_name_override", self.ssl_target_name)
        ] if self.ssl_target_name else []

        # pylint: disable=attribute-defined-outside-init
        # Create GRPC channel
        if self.tls_ca_cert:
            # Add client credentials if available
            if self.client_cert and self.client_key:
                creds = aiogrpc.ssl_channel_credentials(
                    self.tls_ca_cert,
                    private_key=self.client_key,
                    certificate_chain=self.client_cert
                )
            else:
                creds = aiogrpc.ssl_channel_credentials(self.tls_ca_cert)
            # Create secure channel
            self._grpc_channel = aiogrpc.secure_channel(
                self.endpoint, creds, opts
            )
        else:
            # Create insecure channel if no cert
            self._grpc_channel = aiogrpc.insecure_channel(self.endpoint, opts)
Example #2
0
    def _create_grpc_channel(self, endpoint, ssl=False,
                             ca_cert=None, cert_key=None, cert_cert=None, default_ca=False, options=None,
                             *, loop=None, executor=None):
        credentials = None
        if not ssl:
            channel = aiogrpc.insecure_channel(endpoint, options=options, loop=loop, executor=executor,
                                               standalone_pool_for_streaming=True)
        else:
            if default_ca:
                ca_cert = None
            else:
                if ca_cert is None:
                    logger.warning("Certificate authority is not specified. Empty CA will be used. To use system CA set"
                                   " `default_ca=True`")
                    ca_cert = ''

            # to ensure ssl connect , set grpc env
            # os.environ['GRPC_SSL_CIPHER_SUITES'] = 'ECDHE-ECDSA-AES256-GCM-SHA384'

            credentials = aiogrpc.ssl_channel_credentials(ca_cert, cert_key, cert_cert)
            channel = aiogrpc.secure_channel(endpoint, credentials, options=options,
                                             loop=loop, executor=executor,
                                             standalone_pool_for_streaming=True)

        # Save parameters for auto-recreate
        self._credentials = credentials
        self._options = options
        self._loop = channel._loop
        self._executor = executor
        return channel
Example #3
0
 def _recreate_grpc_channel(self, endpoint):
     self._call_credentials = None
     self._metadata = None
     if self._credentials:
         channel = aiogrpc.secure_channel(endpoint, self._credentials, options=self._options,
                                          loop=self._loop, executor=self._executor,
                                          standalone_pool_for_streaming=True)
     else:
         channel = aiogrpc.insecure_channel(endpoint, options=self._options, loop=self._loop,
                                            executor=self._executor, standalone_pool_for_streaming=True)
     return channel
    def _connect_backend(self):
        """
        Initializes the connection to the running backend
        """
        if self.secure:
            # For now just allow insecure connections
            raise NotImplementedError()

        #: gRPC channel
        self._channel = aiogrpc.insecure_channel(
            "{}:{}".format(self.host, self.port)
        )
    async def _connect_backend(self):
        """
        Initializes the connection to the running backend
        """

        #: gRPC channel
        self._channel = aiogrpc.insecure_channel("{}:{}".format(
            self.host, self.port))

        print("Waiting for mavsdk_server to be ready...")
        await aiogrpc.channel_ready_future(self._channel)
        print("Connected to mavsdk_server!")
Example #6
0
def create_grpc_channel(target,
                        cert_file=None,
                        client_key=None,
                        client_cert=None,
                        opts=None):
    """Construct a grpc channel.

    Args:
        target: server address include host:port
        cert_file: ssl/tls root cert file for the connection
        opts: grpc channel options
                grpc.default_authority: default authority
                grpc.ssl_target_name_override: ssl target name override

    Returns:
        grpc channel

    """

    root_cert = None

    if cert_file:
        if isinstance(cert_file, bytes):
            root_cert = cert_file
        else:
            with open(cert_file, 'rb') as f:
                root_cert = f.read()

    if client_key:
        if not isinstance(client_key, bytes):
            with open(client_key, 'rb') as f:
                client_key = f.read()

    if client_cert:
        if not isinstance(client_cert, bytes):
            with open(client_cert, 'rb') as f:
                client_cert = f.read()

    if root_cert is None:
        return aiogrpc.insecure_channel(target, opts)
    else:
        if client_cert and client_key:
            creds = aiogrpc. \
                ssl_channel_credentials(root_cert,
                                        private_key=client_key,
                                        certificate_chain=client_cert)
        else:
            creds = aiogrpc.ssl_channel_credentials(root_cert)

        return aiogrpc.secure_channel(target, creds, opts)
Example #7
0
    def __init__(self, file):
        self.c = c = u.config
        self.p = p = c["processes"][file]

        u.delfile(f'.logs/{file}.txt')
        self.logger = u.log = u.setLogger(p.get("loggers")).classFilter(
            self, "main")

        h = c["exchange"]
        channel = insecure_channel('%s:%s' % (h["host"], h["port"]))
        self._stub = ExchangeServiceStub(channel)
        self.connections = {}
        self.slowdown = 0
        self.rtt = c["rtt"]  # round-trip time
Example #8
0
    def __init__(self, broker='192.168.4.239:50052', *args, **kwargs):

        self.broker = broker
        self.channel = grpc.insecure_channel(self.broker)
        self.async_channel = insecure_channel(self.broker)
        self._event_thread = Thread(target=self.event_notify, name='EVENT')
        self._callback_thread = Thread(target=self.callback, name='CALLBACK')
        self._quotation_thread = Thread(target=self.quotation,
                                        name='Quotation')
        self._callback_thread_alive = True
        self._quotation_thread_alive = True
        self._callback_queue = queue.Queue()
        self._event_loop = asyncio.get_event_loop()
        self._sub_code = []
        self._res = queue.Queue(maxsize=100)
Example #9
0
    async def member_healthy(self, members=None):

        if not members:
            members = await self.member_list()
            members = [m.clientURLs for m in members]

        health_members = []
        unhealth_members = []
        for m in members:

            m = [u.rpartition("//")[2] for u in m]
            m = [u for u in m if u]
            if m:
                server_endpoint = ipv4_endpoints(m)

                if self._credentials:
                    channel = aiogrpc.secure_channel(
                        server_endpoint,
                        self._credentials,
                        options=self._options,
                        loop=self._loop,
                        executor=self._executor,
                        standalone_pool_for_streaming=True)
                else:
                    channel = aiogrpc.insecure_channel(
                        server_endpoint,
                        options=self._options,
                        loop=self._loop,
                        executor=self._executor,
                        standalone_pool_for_streaming=True)
                try:
                    maintenance = Maintenance(channel=channel,
                                              timeout=2,
                                              username=self.username,
                                              password=self.password)
                    try:
                        await maintenance.status()
                    except grpc.RpcError:
                        unhealth_members.append(m)
                    else:
                        health_members.append(m)
                finally:
                    await channel.close()
            else:
                unhealth_members.append(m)

        return health_members, unhealth_members
    async def _connect_backend(self):
        """
        Initializes the connection to the running backend
        """

        #: gRPC channel
        self._channel = aiogrpc.insecure_channel(
            "{}:{}".format(self.host, self.port),
            standalone_pool_for_streaming=True
        )

        logger = logging.getLogger(__name__)
        logger.addHandler(logging.NullHandler())  # Avoid errors when user has not configured logging

        logger.debug("Waiting for mavsdk_server to be ready...")
        await aiogrpc.channel_ready_future(self._channel)
        logger.debug("Connected to mavsdk_server!")
Example #11
0
 async def testBalancing(self):
     s1 = create_server(['127.0.0.1:9902'])
     s2 = create_server(['127.0.0.1:9903'])
     self.channel = aiogrpc.insecure_channel(
         'ipv4:///127.0.0.1:9902,127.0.0.1:9903', loop=self.loop)
     self.stub = TestServiceStub(self.channel)
     s1.start()
     try:
         result = await self.stub.NormalMethod(StandardRequest(name='test1')
                                               )
         self.assertEqual(result.message, 'test1')
     finally:
         s1.stop(None)
     s2.start()
     try:
         result = await self.stub.NormalMethod(StandardRequest(name='test1')
                                               )
         self.assertEqual(result.message, 'test1')
     finally:
         s1.stop(None)
Example #12
0
    def __init__(self,
                 host='localhost',
                 port=2379,
                 ca_cert=None,
                 cert_key=None,
                 cert_cert=None,
                 timeout=None,
                 user=None,
                 password=None):

        self._url = '{host}:{port}'.format(host=host, port=port)

        cert_params = [c is not None for c in (cert_cert, cert_key)]
        if ca_cert is not None:
            if all(cert_params):
                credentials = self._get_secure_creds(ca_cert, cert_key,
                                                     cert_cert)
                self.uses_secure_channel = True
                self.channel = aiogrpc.secure_channel(self._url, credentials)
            elif any(cert_params):
                # some of the cert parameters are set
                raise ValueError(
                    'to use a secure channel ca_cert is required by itself, '
                    'or cert_cert and cert_key must both be specified.')
            else:
                credentials = self._get_secure_creds(ca_cert, None, None)
                self.uses_secure_channel = True
                self.channel = aiogrpc.secure_channel(self._url, credentials)
        else:
            self.uses_secure_channel = False
            self.channel = aiogrpc.insecure_channel(self._url)

        self.timeout = timeout
        self.call_credentials = None
        self._user = user
        self._password = password
Example #13
0
 def setUp(self):
     self.loop = asyncio.get_event_loop()
     self.channel = aiogrpc.insecure_channel('ipv4:///127.0.0.1:9901',
                                             loop=self.loop)
     self.stub = TestServiceStub(self.channel)
Example #14
0
 def _connect(self):
     # connect to wavemq agent
     wavemq_channel = insecure_channel(self._cfg['wavemq'])
     self._cl = WAVEMQStub(wavemq_channel)
Example #15
0
 def __init__(self, host, port):
     grpc_uri = f"ipv4:///{host}:{port}"
     rpc_channel = insecure_channel(grpc_uri)
     self.stub = InternalServerStub(rpc_channel)
Example #16
0
async def query():
    async with insecure_channel(url) as conn:
        client = SquareServiceStub(channel=conn)
        response = await client.sumSquare(
            AsyncIterWrapper(Message(message=i) for i in range(12)))
        print(response.message)
Example #17
0
 async def testAsyncCtxManager(self):
     async with aiogrpc.insecure_channel('ipv4:///127.0.0.1:9901',
                                         loop=self.loop) as _channel:
         await aiogrpc.channel_ready_future(_channel)
Example #18
0
async def query():
    async with insecure_channel(url) as conn:
        client = SquareServiceStub(channel=conn)
        async for response in client.streamrangeSquare(
                AsyncIterWrapper(Message(message=i) for i in range(12))):
            print(response.message)
Example #19
0
async def query():
    async with insecure_channel(url) as conn:
        client = SquareServiceStub(channel=conn)
        result = await client.square(Message(message=12.3))
        print(result)
Example #20
0
from aiogrpc import insecure_channel
import asyncio

import stock_hq_pb2
import stock_hq_pb2_grpc

channel = insecure_channel('ipv4:///192.168.4.239:50052')
stub = stock_hq_pb2_grpc.StockHQServiceStub(channel)


async def test_call():
    return await stub.QA_fetch_get(
        stock_hq_pb2.Query(code='601801', type='1min'))


response = test_call()
print(response.code, response.open, response.high, response.low,
      response.close)

#
#async def test_call_stream():
#    async for v in mystub.my_stream_method(...):
#       ...
Example #21
0
 async def __aenter__(self):
   self._channel = insecure_channel(self.endpoint)
   self._stub = prediction_service_pb2.beta_create_PredictionService_stub(self._channel)
   return self
Example #22
0
async def query():
    async with insecure_channel(url) as conn:
        client = SquareServiceStub(channel=conn)
        async for response in client.rangeSquare(Message(message=12)):
            print(response.message)