1 # Copyright 2019 The gRPC Authors
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """The Python example of utilizing Channelz feature."""
16 from __future__ import absolute_import
17 from __future__ import division
18 from __future__ import print_function
22 from concurrent import futures
26 from grpc_channelz.v1 import channelz
28 from examples import helloworld_pb2
29 from examples import helloworld_pb2_grpc
31 _LOGGER = logging.getLogger(__name__)
32 _LOGGER.setLevel(logging.INFO)
34 _RANDOM_FAILURE_RATE = 0.3
37 class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer):
39 def __init__(self, failure_rate):
40 self._failure_rate = failure_rate
42 def SayHello(self, request, context):
43 if random.random() < self._failure_rate:
44 context.abort(grpc.StatusCode.UNAVAILABLE,
45 'Randomly injected failure.')
46 return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
49 def create_server(addr, failure_rate):
50 server = grpc.server(futures.ThreadPoolExecutor())
51 helloworld_pb2_grpc.add_GreeterServicer_to_server(
52 FaultInjectGreeter(failure_rate), server)
54 # Add Channelz Servicer to the gRPC server
55 channelz.add_channelz_servicer(server)
57 server.add_insecure_port(addr)
62 parser = argparse.ArgumentParser()
63 parser.add_argument('--addr',
67 help='the address to listen on')
73 help='a float indicates the percentage of failed message injections')
74 args = parser.parse_args()
76 server = create_server(addr=args.addr, failure_rate=args.failure_rate)
78 server.wait_for_termination()
81 if __name__ == '__main__':
82 logging.basicConfig(level=logging.INFO)