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