Python grpc.intercept_channel() Examples

The following are 10 code examples of grpc.intercept_channel(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module grpc , or try the search function .
Example #1
Source File: conftest.py    From gapic-generator-python with Apache License 2.0 6 votes vote down vote up
def intercepted_echo(use_mtls):
    # The interceptor adds 'showcase-trailer' client metadata. Showcase server
    # echos any metadata with key 'showcase-trailer', so the same metadata
    # should appear as trailing metadata in the response.
    interceptor = MetadataClientInterceptor("showcase-trailer", "intercepted")
    host = "localhost:7469"
    channel = (
        grpc.secure_channel(host, ssl_credentials)
        if use_mtls
        else grpc.insecure_channel(host)
    )
    intercept_channel = grpc.intercept_channel(channel, interceptor)
    transport = EchoClient.get_transport_class("grpc")(
        channel=intercept_channel
    )
    return EchoClient(transport=transport) 
Example #2
Source File: service_client.py    From snet-cli with MIT License 6 votes vote down vote up
def __init__(self,org_id,service_id, service_metadata,group, service_stub, payment_strategy,
                 options,mpe_contract,account,sdk_web3):
        self.org_id = org_id
        self.service_id = service_id
        self.options = options
        self.group = group
        self.service_metadata = service_metadata

        self.payment_strategy = payment_strategy
        self.expiry_threshold = self.group["payment"]["payment_expiration_threshold"]
        self._base_grpc_channel = self._get_grpc_channel()
        self.grpc_channel = grpc.intercept_channel(self._base_grpc_channel,
                                                   generic_client_interceptor.create(self._intercept_call))
        self.payment_channel_provider=PaymentChannelProvider(sdk_web3,self._generate_payment_channel_state_service_client(),mpe_contract)
        self.service = self._generate_grpc_stub(service_stub)
        self.payment_channels = []
        self.last_read_block = 0
        self.account=account
        self.sdk_web3=sdk_web3
        self.mpe_address=mpe_contract.contract.address 
Example #3
Source File: trace.py    From opencensus-python with Apache License 2.0 6 votes vote down vote up
def wrap_make_secure_channel(make_secure_channel_func, tracer=None):
    """Wrap the google.cloud._helpers.make_secure_channel."""
    def call(*args, **kwargs):
        channel = make_secure_channel_func(*args, **kwargs)

        try:
            host = kwargs.get('host')
            tracer_interceptor = OpenCensusClientInterceptor(tracer, host)
            intercepted_channel = grpc.intercept_channel(
                channel, tracer_interceptor)
            return intercepted_channel  # pragma: NO COVER
        except Exception:
            log.warning(
                'Failed to wrap secure channel, '
                'clientlibs grpc calls not traced.')
            return channel
    return call 
Example #4
Source File: trace.py    From opencensus-python with Apache License 2.0 6 votes vote down vote up
def wrap_insecure_channel(insecure_channel_func, tracer=None):
    """Wrap the grpc.insecure_channel."""
    def call(*args, **kwargs):
        channel = insecure_channel_func(*args, **kwargs)

        try:
            target = kwargs.get('target')
            tracer_interceptor = OpenCensusClientInterceptor(tracer, target)
            intercepted_channel = grpc.intercept_channel(
                channel, tracer_interceptor)
            return intercepted_channel  # pragma: NO COVER
        except Exception:
            log.warning(
                'Failed to wrap insecure channel, '
                'clientlibs grpc calls not traced.')
            return channel
    return call 
Example #5
Source File: trace.py    From opencensus-python with Apache License 2.0 6 votes vote down vote up
def wrap_create_channel(create_channel_func, tracer=None):
    """Wrap the google.api_core.grpc_helpers.create_channel."""
    def call(*args, **kwargs):
        channel = create_channel_func(*args, **kwargs)

        try:
            target = kwargs.get('target')
            tracer_interceptor = OpenCensusClientInterceptor(tracer, target)
            intercepted_channel = grpc.intercept_channel(
                channel, tracer_interceptor)
            return intercepted_channel  # pragma: NO COVER
        except Exception:
            log.warning(
                'Failed to wrap create_channel, '
                'clientlibs grpc calls not traced.')
            return channel
    return call 
Example #6
Source File: hello_world_client.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def main():
    exporter = stackdriver_exporter.StackdriverExporter()
    tracer = Tracer(exporter=exporter)
    tracer_interceptor = client_interceptor.OpenCensusClientInterceptor(
        tracer,
        host_port=HOST_PORT)
    channel = grpc.insecure_channel(HOST_PORT)
    channel = grpc.intercept_channel(channel, tracer_interceptor)
    stub = hello_world_pb2_grpc.GreeterStub(channel)
    response = stub.SayHello(hello_world_pb2.HelloRequest(name='you'))
    print("Message received: " + response.message) 
Example #7
Source File: test_client_interceptor.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def _intercepted_channel(self, tracer=None):
        return grpc.intercept_channel(
            self._channel,
            client_interceptor.OpenCensusClientInterceptor(tracer=tracer)) 
Example #8
Source File: grpc.py    From airflow with Apache License 2.0 4 votes vote down vote up
def get_conn(self):
        base_url = self.conn.host

        if self.conn.port:
            base_url = base_url + ":" + str(self.conn.port)

        auth_type = self._get_field("auth_type")

        if auth_type == "NO_AUTH":
            channel = grpc.insecure_channel(base_url)
        elif auth_type in {"SSL", "TLS"}:
            credential_file_name = self._get_field("credential_pem_file")
            creds = grpc.ssl_channel_credentials(open(credential_file_name).read())
            channel = grpc.secure_channel(base_url, creds)
        elif auth_type == "JWT_GOOGLE":
            credentials, _ = google_auth.default()
            jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials(
                credentials)
            channel = google_auth_transport_grpc.secure_authorized_channel(
                jwt_creds, None, base_url)
        elif auth_type == "OATH_GOOGLE":
            scopes = self._get_field("scopes").split(",")
            credentials, _ = google_auth.default(scopes=scopes)
            request = google_auth_transport_requests.Request()
            channel = google_auth_transport_grpc.secure_authorized_channel(
                credentials, request, base_url)
        elif auth_type == "CUSTOM":
            if not self.custom_connection_func:
                raise AirflowConfigException(
                    "Customized connection function not set, not able to establish a channel")
            channel = self.custom_connection_func(self.conn)
        else:
            raise AirflowConfigException(
                "auth_type not supported or not provided, channel cannot be established,\
                given value: %s" % str(auth_type))

        if self.interceptors:
            for interceptor in self.interceptors:
                channel = grpc.intercept_channel(channel,
                                                 interceptor)

        return channel 
Example #9
Source File: client.py    From google-ads-python with Apache License 2.0 4 votes vote down vote up
def get_service(self, name, version=_DEFAULT_VERSION, interceptors=None):
        """Returns a service client instance for the specified service_name.

        Args:
            name: a str indicating the name of the service for which a
                service client is being retrieved; e.g. you may specify
                "CampaignService" to retrieve a CampaignServiceClient instance.
            version: a str indicating the version of the Google Ads API to be
                used.
            interceptors: an optional list of interceptors to include in
                requests. NOTE: this parameter is not intended for non-Google
                use and is not officially supported.

        Returns:
            A service client instance associated with the given service_name.

        Raises:
            AttributeError: If the specified name doesn't exist.
        """
        api_module = self._get_api_services_by_version(version)
        interceptors = interceptors or []

        try:
            service_client = getattr(api_module,
                                     _SERVICE_CLIENT_TEMPLATE.format(name))
        except AttributeError:
            raise ValueError('Specified service {}" does not exist in Google '
                             'Ads API {}.'.format(name, version))

        try:
            service_transport_class = getattr(
                api_module, _SERVICE_GRPC_TRANSPORT_TEMPLATE.format(name))
        except AttributeError:
            raise ValueError('Grpc transport does not exist for the specified '
                             'service "{}".'.format(name))

        endpoint = (self.endpoint if self.endpoint
                    else service_client.SERVICE_ADDRESS)

        channel = service_transport_class.create_channel(
            address=endpoint,
            credentials=self.credentials,
            options=_GRPC_CHANNEL_OPTIONS)

        interceptors = interceptors + [
            MetadataInterceptor(self.developer_token, self.login_customer_id),
            LoggingInterceptor(_logger, version, endpoint),
            ExceptionInterceptor(version)]

        channel = grpc.intercept_channel(
            channel,
            *interceptors)

        service_transport = service_transport_class(channel=channel)

        return service_client(transport=service_transport) 
Example #10
Source File: client.py    From hangar-py with Apache License 2.0 4 votes vote down vote up
def _setup_client_channel_config(self):
        """get grpc client configuration from server and setup channel and stub for use.
        """
        tmp_insec_channel = grpc.insecure_channel(self.address)
        tmp_channel = grpc.intercept_channel(tmp_insec_channel, self.header_adder_int)
        tmp_stub = hangar_service_pb2_grpc.HangarServiceStub(tmp_channel)
        t_init, t_tot = time.time(), 0
        while t_tot < self.wait_ready_timeout:
            try:
                request = hangar_service_pb2.GetClientConfigRequest()
                response = tmp_stub.GetClientConfig(request)
                self.cfg['push_max_nbytes'] = int(response.config['push_max_nbytes'])
                self.cfg['optimization_target'] = response.config['optimization_target']

                enable_compression = response.config['enable_compression']
                if enable_compression == 'NoCompression':
                    compression_val = grpc.Compression.NoCompression
                elif enable_compression == 'Deflate':
                    compression_val = grpc.Compression.Deflate
                elif enable_compression == 'Gzip':
                    compression_val = grpc.Compression.Gzip
                else:
                    compression_val = grpc.Compression.NoCompression
                self.cfg['enable_compression'] = compression_val

            except grpc.RpcError as err:
                if not (err.code() == grpc.StatusCode.UNAVAILABLE) and (self.wait_ready is True):
                    logger.error(err)
                    raise err
            else:
                break
            time.sleep(0.05)
            t_tot = time.time() - t_init
        else:
            err = ConnectionError(f'Server did not connect after: {self.wait_ready_timeout} sec.')
            logger.error(err)
            raise err

        tmp_channel.close()
        tmp_insec_channel.close()
        configured_channel = grpc.insecure_channel(
            self.address,
            options=[
                ('grpc.optimization_target', self.cfg['optimization_target']),
                ("grpc.keepalive_time_ms", 1000 * 60 * 1),
                ("grpc.keepalive_timeout_ms", 1000 * 10),
                ("grpc.http2_min_sent_ping_interval_without_data_ms", 1000 * 10),
                ("grpc.http2_max_pings_without_data", 0),
                ("grpc.keepalive_permit_without_calls", 1),
            ],
            compression=self.cfg['enable_compression'])
        self.channel = grpc.intercept_channel(configured_channel, self.header_adder_int)
        self.stub = hangar_service_pb2_grpc.HangarServiceStub(self.channel)