Debian Codegraph @

examples/python/debug/asyncio_debug_server.py

raw
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
16 import argparse
17 import asyncio
18 import logging
19 import random
20
21 import grpc
22
23 helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
24 "helloworld.proto")
25
26 # TODO: Suppress until the macOS segfault fix rolled out
27 from grpc_channelz.v1 import channelz # pylint: disable=wrong-import-position
28
29 _LOGGER = logging.getLogger(__name__)
30 _LOGGER.setLevel(logging.INFO)
31
32 _RANDOM_FAILURE_RATE = 0.3
33
34
35 class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer):
36
37 def __init__(self, failure_rate):
38 self._failure_rate = failure_rate
39
40 async def SayHello(
41 self, request: helloworld_pb2.HelloRequest,
42 context: grpc.aio.ServicerContext) -> helloworld_pb2.HelloReply:
43 if random.random() < self._failure_rate:
44 context.abort(grpc.StatusCode.UNAVAILABLE,
45 'Randomly injected failure.')
46 return helloworld_pb2.HelloReply(message=f'Hello, {request.name}!')
47
48
49 def create_server(addr: str, failure_rate: float) -> grpc.aio.Server:
50 server = grpc.aio.server()
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
61 async def main() -> None:
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 await server.start()
78 await server.wait_for_termination()
79
80
81 if __name__ == '__main__':
82 logging.basicConfig(level=logging.INFO)
83 asyncio.get_event_loop().run_until_complete(main())