1# Copyright 2020 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 AsyncIO example of utilizing Channelz feature.""" 15 16import argparse 17import asyncio 18import logging 19import random 20 21import grpc 22 23helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( 24 "helloworld.proto" 25) 26 27# TODO: Suppress until the macOS segfault fix rolled out 28from grpc_channelz.v1 import channelz # pylint: disable=wrong-import-position 29 30_LOGGER = logging.getLogger(__name__) 31_LOGGER.setLevel(logging.INFO) 32 33_RANDOM_FAILURE_RATE = 0.3 34 35 36class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer): 37 def __init__(self, failure_rate): 38 self._failure_rate = failure_rate 39 40 async def SayHello( 41 self, 42 request: helloworld_pb2.HelloRequest, 43 context: grpc.aio.ServicerContext, 44 ) -> helloworld_pb2.HelloReply: 45 if random.random() < self._failure_rate: 46 context.abort( 47 grpc.StatusCode.UNAVAILABLE, "Randomly injected failure." 48 ) 49 return helloworld_pb2.HelloReply(message=f"Hello, {request.name}!") 50 51 52def create_server(addr: str, failure_rate: float) -> grpc.aio.Server: 53 server = grpc.aio.server() 54 helloworld_pb2_grpc.add_GreeterServicer_to_server( 55 FaultInjectGreeter(failure_rate), server 56 ) 57 58 # Add Channelz Servicer to the gRPC server 59 channelz.add_channelz_servicer(server) 60 61 server.add_insecure_port(addr) 62 return server 63 64 65async def main() -> None: 66 parser = argparse.ArgumentParser() 67 parser.add_argument( 68 "--addr", 69 nargs=1, 70 type=str, 71 default="[::]:50051", 72 help="the address to listen on", 73 ) 74 parser.add_argument( 75 "--failure_rate", 76 nargs=1, 77 type=float, 78 default=0.3, 79 help="a float indicates the percentage of failed message injections", 80 ) 81 args = parser.parse_args() 82 83 server = create_server(addr=args.addr, failure_rate=args.failure_rate) 84 await server.start() 85 await server.wait_for_termination() 86 87 88if __name__ == "__main__": 89 logging.basicConfig(level=logging.INFO) 90 asyncio.get_event_loop().run_until_complete(main()) 91