1# Copyright 2019 The gRPC Authors 2# 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 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 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.""" 15 16from __future__ import absolute_import 17from __future__ import division 18from __future__ import print_function 19 20import argparse 21import logging 22from concurrent import futures 23import random 24 25import grpc 26from grpc_channelz.v1 import channelz 27 28from examples import helloworld_pb2 29from examples import helloworld_pb2_grpc 30 31_LOGGER = logging.getLogger(__name__) 32_LOGGER.setLevel(logging.INFO) 33 34_RANDOM_FAILURE_RATE = 0.3 35 36 37class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer): 38 39 def __init__(self, failure_rate): 40 self._failure_rate = failure_rate 41 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) 47 48 49def create_server(addr, failure_rate): 50 server = grpc.server(futures.ThreadPoolExecutor()) 51 helloworld_pb2_grpc.add_GreeterServicer_to_server( 52 FaultInjectGreeter(failure_rate), server) 53 54 # Add Channelz Servicer to the gRPC server 55 channelz.add_channelz_servicer(server) 56 57 server.add_insecure_port(addr) 58 return server 59 60 61def main(): 62 parser = argparse.ArgumentParser() 63 parser.add_argument('--addr', 64 nargs=1, 65 type=str, 66 default='[::]:50051', 67 help='the address to listen on') 68 parser.add_argument( 69 '--failure_rate', 70 nargs=1, 71 type=float, 72 default=0.3, 73 help='a float indicates the percentage of failed message injections') 74 args = parser.parse_args() 75 76 server = create_server(addr=args.addr, failure_rate=args.failure_rate) 77 server.start() 78 server.wait_for_termination() 79 80 81if __name__ == '__main__': 82 logging.basicConfig(level=logging.INFO) 83 main() 84