async_greeter_server_with_graceful_shutdown.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright 2021 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 graceful shutdown example for the asyncio Greeter server."""
  15. import asyncio
  16. import logging
  17. import grpc
  18. import helloworld_pb2
  19. import helloworld_pb2_grpc
  20. # Coroutines to be invoked when the event loop is shutting down.
  21. _cleanup_coroutines = []
  22. class Greeter(helloworld_pb2_grpc.GreeterServicer):
  23. async def SayHello(
  24. self, request: helloworld_pb2.HelloRequest,
  25. context: grpc.aio.ServicerContext) -> helloworld_pb2.HelloReply:
  26. logging.info('Received request, sleeping for 4 seconds...')
  27. await asyncio.sleep(4)
  28. logging.info('Sleep completed, responding')
  29. return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
  30. async def serve() -> None:
  31. server = grpc.aio.server()
  32. helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
  33. listen_addr = '[::]:50051'
  34. server.add_insecure_port(listen_addr)
  35. logging.info("Starting server on %s", listen_addr)
  36. await server.start()
  37. async def server_graceful_shutdown():
  38. logging.info("Starting graceful shutdown...")
  39. # Shuts down the server with 0 seconds of grace period. During the
  40. # grace period, the server won't accept new connections and allow
  41. # existing RPCs to continue within the grace period.
  42. await server.stop(5)
  43. _cleanup_coroutines.append(server_graceful_shutdown())
  44. await server.wait_for_termination()
  45. if __name__ == '__main__':
  46. logging.basicConfig(level=logging.INFO)
  47. loop = asyncio.get_event_loop()
  48. try:
  49. loop.run_until_complete(serve())
  50. finally:
  51. loop.run_until_complete(*_cleanup_coroutines)
  52. loop.close()