Debian Codegraph @

tools/run_tests/xds_k8s_test_driver/framework/rpc/grpc_channelz.py

raw
1 # Copyright 2020 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 """
15 This contains helpers for gRPC services defined in
16 https://github.com/grpc/grpc-proto/blob/master/grpc/channelz/v1/channelz.proto
17 """
18 import ipaddress
19 import logging
20 from typing import Iterator, Optional
21
22 import grpc
23 from grpc_channelz.v1 import channelz_pb2
24 from grpc_channelz.v1 import channelz_pb2_grpc
25
26 import framework.rpc
27
28 logger = logging.getLogger(__name__)
29
30 # Type aliases
31 # Channel
32 Channel = channelz_pb2.Channel
33 ChannelConnectivityState = channelz_pb2.ChannelConnectivityState
34 ChannelState = ChannelConnectivityState.State # pylint: disable=no-member
35 _GetTopChannelsRequest = channelz_pb2.GetTopChannelsRequest
36 _GetTopChannelsResponse = channelz_pb2.GetTopChannelsResponse
37 # Subchannel
38 Subchannel = channelz_pb2.Subchannel
39 _GetSubchannelRequest = channelz_pb2.GetSubchannelRequest
40 _GetSubchannelResponse = channelz_pb2.GetSubchannelResponse
41 # Server
42 Server = channelz_pb2.Server
43 _GetServersRequest = channelz_pb2.GetServersRequest
44 _GetServersResponse = channelz_pb2.GetServersResponse
45 # Sockets
46 Socket = channelz_pb2.Socket
47 SocketRef = channelz_pb2.SocketRef
48 _GetSocketRequest = channelz_pb2.GetSocketRequest
49 _GetSocketResponse = channelz_pb2.GetSocketResponse
50 Address = channelz_pb2.Address
51 Security = channelz_pb2.Security
52 # Server Sockets
53 _GetServerSocketsRequest = channelz_pb2.GetServerSocketsRequest
54 _GetServerSocketsResponse = channelz_pb2.GetServerSocketsResponse
55
56
57 class ChannelzServiceClient(framework.rpc.grpc.GrpcClientHelper):
58 stub: channelz_pb2_grpc.ChannelzStub
59
60 def __init__(self,
61 channel: grpc.Channel,
62 *,
63 log_target: Optional[str] = ''):
64 super().__init__(channel,
65 channelz_pb2_grpc.ChannelzStub,
66 log_target=log_target)
67
68 @staticmethod
69 def is_sock_tcpip_address(address: Address):
70 return address.WhichOneof('address') == 'tcpip_address'
71
72 @staticmethod
73 def is_ipv4(tcpip_address: Address.TcpIpAddress):
74 # According to proto, tcpip_address.ip_address is either IPv4 or IPv6.
75 # Correspondingly, it's either 4 bytes or 16 bytes in length.
76 return len(tcpip_address.ip_address) == 4
77
78 @classmethod
79 def sock_address_to_str(cls, address: Address):
80 if cls.is_sock_tcpip_address(address):
81 tcpip_address: Address.TcpIpAddress = address.tcpip_address
82 if cls.is_ipv4(tcpip_address):
83 ip = ipaddress.IPv4Address(tcpip_address.ip_address)
84 else:
85 ip = ipaddress.IPv6Address(tcpip_address.ip_address)
86 return f'{ip}:{tcpip_address.port}'
87 else:
88 raise NotImplementedError('Only tcpip_address implemented')
89
90 @classmethod
91 def sock_addresses_pretty(cls, socket: Socket):
92 return (f'local={cls.sock_address_to_str(socket.local)}, '
93 f'remote={cls.sock_address_to_str(socket.remote)}')
94
95 @staticmethod
96 def find_server_socket_matching_client(server_sockets: Iterator[Socket],
97 client_socket: Socket) -> Socket:
98 for server_socket in server_sockets:
99 if server_socket.remote == client_socket.local:
100 return server_socket
101 return None
102
103 def find_channels_for_target(self, target: str,
104 **kwargs) -> Iterator[Channel]:
105 return (channel for channel in self.list_channels(**kwargs)
106 if channel.data.target == target)
107
108 def find_server_listening_on_port(self, port: int,
109 **kwargs) -> Optional[Server]:
110 for server in self.list_servers(**kwargs):
111 listen_socket_ref: SocketRef
112 for listen_socket_ref in server.listen_socket:
113 listen_socket = self.get_socket(listen_socket_ref.socket_id,
114 **kwargs)
115 listen_address: Address = listen_socket.local
116 if (self.is_sock_tcpip_address(listen_address) and
117 listen_address.tcpip_address.port == port):
118 return server
119 return None
120
121 def list_channels(self, **kwargs) -> Iterator[Channel]:
122 """
123 Iterate over all pages of all root channels.
124
125 Root channels are those which application has directly created.
126 This does not include subchannels nor non-top level channels.
127 """
128 start: int = -1
129 response: Optional[_GetTopChannelsResponse] = None
130 while start < 0 or not response.end:
131 # From proto: To request subsequent pages, the client generates this
132 # value by adding 1 to the highest seen result ID.
133 start += 1
134 response = self.call_unary_with_deadline(
135 rpc='GetTopChannels',
136 req=_GetTopChannelsRequest(start_channel_id=start),
137 **kwargs)
138 for channel in response.channel:
139 start = max(start, channel.ref.channel_id)
140 yield channel
141
142 def list_servers(self, **kwargs) -> Iterator[Server]:
143 """Iterate over all pages of all servers that exist in the process."""
144 start: int = -1
145 response: Optional[_GetServersResponse] = None
146 while start < 0 or not response.end:
147 # From proto: To request subsequent pages, the client generates this
148 # value by adding 1 to the highest seen result ID.
149 start += 1
150 response = self.call_unary_with_deadline(
151 rpc='GetServers',
152 req=_GetServersRequest(start_server_id=start),
153 **kwargs)
154 for server in response.server:
155 start = max(start, server.ref.server_id)
156 yield server
157
158 def list_server_sockets(self, server: Server, **kwargs) -> Iterator[Socket]:
159 """List all server sockets that exist in server process.
160
161 Iterating over the results will resolve additional pages automatically.
162 """
163 start: int = -1
164 response: Optional[_GetServerSocketsResponse] = None
165 while start < 0 or not response.end:
166 # From proto: To request subsequent pages, the client generates this
167 # value by adding 1 to the highest seen result ID.
168 start += 1
169 response = self.call_unary_with_deadline(
170 rpc='GetServerSockets',
171 req=_GetServerSocketsRequest(server_id=server.ref.server_id,
172 start_socket_id=start),
173 **kwargs)
174 socket_ref: SocketRef
175 for socket_ref in response.socket_ref:
176 start = max(start, socket_ref.socket_id)
177 # Yield actual socket
178 yield self.get_socket(socket_ref.socket_id, **kwargs)
179
180 def list_channel_sockets(self, channel: Channel,
181 **kwargs) -> Iterator[Socket]:
182 """List all sockets of all subchannels of a given channel."""
183 for subchannel in self.list_channel_subchannels(channel, **kwargs):
184 yield from self.list_subchannels_sockets(subchannel, **kwargs)
185
186 def list_channel_subchannels(self, channel: Channel,
187 **kwargs) -> Iterator[Subchannel]:
188 """List all subchannels of a given channel."""
189 for subchannel_ref in channel.subchannel_ref:
190 yield self.get_subchannel(subchannel_ref.subchannel_id, **kwargs)
191
192 def list_subchannels_sockets(self, subchannel: Subchannel,
193 **kwargs) -> Iterator[Socket]:
194 """List all sockets of a given subchannel."""
195 for socket_ref in subchannel.socket_ref:
196 yield self.get_socket(socket_ref.socket_id, **kwargs)
197
198 def get_subchannel(self, subchannel_id, **kwargs) -> Subchannel:
199 """Return a single Subchannel, otherwise raises RpcError."""
200 response: _GetSubchannelResponse = self.call_unary_with_deadline(
201 rpc='GetSubchannel',
202 req=_GetSubchannelRequest(subchannel_id=subchannel_id),
203 **kwargs)
204 return response.subchannel
205
206 def get_socket(self, socket_id, **kwargs) -> Socket:
207 """Return a single Socket, otherwise raises RpcError."""
208 response: _GetSocketResponse = self.call_unary_with_deadline(
209 rpc='GetSocket',
210 req=_GetSocketRequest(socket_id=socket_id),
211 **kwargs)
212 return response.socket