Debian Codegraph @

examples/python/wait_for_ready/asyncio_wait_for_ready_example.py

raw
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 example of utilizing wait-for-ready flag."""
15
16 import asyncio
17 from contextlib import contextmanager
18 import logging
19 import socket
20 from typing import Iterable
21
22 import grpc
23
24 helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
25 "helloworld.proto")
26
27 _LOGGER = logging.getLogger(__name__)
28 _LOGGER.setLevel(logging.INFO)
29
30
31 @contextmanager
32 def get_free_loopback_tcp_port() -> Iterable[str]:
33 if socket.has_ipv6:
34 tcp_socket = socket.socket(socket.AF_INET6)
35 else:
36 tcp_socket = socket.socket(socket.AF_INET)
37 tcp_socket.bind(('', 0))
38 address_tuple = tcp_socket.getsockname()
39 yield f"localhost:{address_tuple[1]}"
40 tcp_socket.close()
41
42
43 class Greeter(helloworld_pb2_grpc.GreeterServicer):
44
45 async def SayHello(self, request: helloworld_pb2.HelloRequest,
46 unused_context) -> helloworld_pb2.HelloReply:
47 return helloworld_pb2.HelloReply(message=f'Hello, {request.name}!')
48
49
50 def create_server(server_address: str):
51 server = grpc.aio.server()
52 helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
53 bound_port = server.add_insecure_port(server_address)
54 assert bound_port == int(server_address.split(':')[-1])
55 return server
56
57
58 async def process(stub: helloworld_pb2_grpc.GreeterStub,
59 wait_for_ready: bool = None) -> None:
60 try:
61 response = await stub.SayHello(helloworld_pb2.HelloRequest(name='you'),
62 wait_for_ready=wait_for_ready)
63 message = response.message
64 except grpc.aio.AioRpcError as rpc_error:
65 assert rpc_error.code() == grpc.StatusCode.UNAVAILABLE
66 assert not wait_for_ready
67 message = rpc_error
68 else:
69 assert wait_for_ready
70 _LOGGER.info("Wait-for-ready %s, client received: %s",
71 "enabled" if wait_for_ready else "disabled", message)
72
73
74 async def main() -> None:
75 # Pick a random free port
76 with get_free_loopback_tcp_port() as server_address:
77 # Create gRPC channel
78 channel = grpc.aio.insecure_channel(server_address)
79 stub = helloworld_pb2_grpc.GreeterStub(channel)
80
81 # Fire an RPC without wait_for_ready
82 fail_fast_task = asyncio.get_event_loop().create_task(
83 process(stub, wait_for_ready=False))
84 # Fire an RPC with wait_for_ready
85 wait_for_ready_task = asyncio.get_event_loop().create_task(
86 process(stub, wait_for_ready=True))
87
88 # Wait for the channel entering TRANSIENT FAILURE state.
89 state = channel.get_state()
90 while state != grpc.ChannelConnectivity.TRANSIENT_FAILURE:
91 await channel.wait_for_state_change(state)
92 state = channel.get_state()
93
94 # Start the server to handle the RPC
95 server = create_server(server_address)
96 await server.start()
97
98 # Expected to fail with StatusCode.UNAVAILABLE.
99 await fail_fast_task
100 # Expected to success.
101 await wait_for_ready_task
102
103 await server.stop(None)
104 await channel.close()
105
106
107 if __name__ == '__main__':
108 logging.basicConfig(level=logging.INFO)
109 asyncio.get_event_loop().run_until_complete(main())