asyncio_debug_server.py 2.6 KB

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