debug_server.py 2.6 KB

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