xref: /aosp_15_r20/external/grpc-grpc/examples/python/debug/debug_server.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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
21from concurrent import futures
22import logging
23import random
24
25import grpc
26
27helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
28    "helloworld.proto"
29)
30
31# TODO: Suppress until the macOS segfault fix rolled out
32from grpc_channelz.v1 import channelz  # pylint: disable=wrong-import-position
33
34_LOGGER = logging.getLogger(__name__)
35_LOGGER.setLevel(logging.INFO)
36
37_RANDOM_FAILURE_RATE = 0.3
38
39
40class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer):
41    def __init__(self, failure_rate):
42        self._failure_rate = failure_rate
43
44    def SayHello(self, request, context):
45        if random.random() < self._failure_rate:
46            context.abort(
47                grpc.StatusCode.UNAVAILABLE, "Randomly injected failure."
48            )
49        return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name)
50
51
52def create_server(addr, failure_rate):
53    server = grpc.server(futures.ThreadPoolExecutor())
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
65def main():
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    server.start()
85    server.wait_for_termination()
86
87
88if __name__ == "__main__":
89    logging.basicConfig(level=logging.INFO)
90    main()
91