Debian Codegraph @

tools/run_tests/xds_k8s_test_driver/bin/run_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 """Channelz debugging tool for xDS test client/server.
15
16 This is intended as a debugging / local development helper and not executed
17 as a part of interop test suites.
18
19 Typical usage examples:
20
21 # Show channel and server socket pair
22 python -m bin.run_channelz --flagfile=config/local-dev.cfg
23
24 # Evaluate setup for different security configurations
25 python -m bin.run_channelz --flagfile=config/local-dev.cfg --security=tls
26 python -m bin.run_channelz --flagfile=config/local-dev.cfg --security=mtls_error
27
28 # More information and usage options
29 python -m bin.run_channelz --helpfull
30 """
31 import hashlib
32 import logging
33
34 from absl import app
35 from absl import flags
36
37 from framework import xds_flags
38 from framework import xds_k8s_flags
39 from framework.infrastructure import k8s
40 from framework.rpc import grpc_channelz
41 from framework.test_app import client_app
42 from framework.test_app import server_app
43
44 logger = logging.getLogger(__name__)
45 # Flags
46 _SERVER_RPC_HOST = flags.DEFINE_string('server_rpc_host',
47 default='127.0.0.1',
48 help='Server RPC host')
49 _CLIENT_RPC_HOST = flags.DEFINE_string('client_rpc_host',
50 default='127.0.0.1',
51 help='Client RPC host')
52 _SECURITY = flags.DEFINE_enum('security',
53 default=None,
54 enum_values=[
55 'mtls', 'tls', 'plaintext', 'mtls_error',
56 'server_authz_error'
57 ],
58 help='Show info for a security setup')
59 flags.adopt_module_key_flags(xds_flags)
60 flags.adopt_module_key_flags(xds_k8s_flags)
61 # Running outside of a test suite, so require explicit resource_suffix.
62 flags.mark_flag_as_required("resource_suffix")
63
64 # Type aliases
65 _Channel = grpc_channelz.Channel
66 _Socket = grpc_channelz.Socket
67 _ChannelState = grpc_channelz.ChannelState
68 _XdsTestServer = server_app.XdsTestServer
69 _XdsTestClient = client_app.XdsTestClient
70
71
72 def debug_cert(cert):
73 if not cert:
74 return '<missing>'
75 sha1 = hashlib.sha1(cert)
76 return f'sha1={sha1.hexdigest()}, len={len(cert)}'
77
78
79 def debug_sock_tls(tls):
80 return (f'local: {debug_cert(tls.local_certificate)}\n'
81 f'remote: {debug_cert(tls.remote_certificate)}')
82
83
84 def get_deployment_pods(k8s_ns, deployment_name):
85 deployment = k8s_ns.get_deployment(deployment_name)
86 return k8s_ns.list_deployment_pods(deployment)
87
88
89 def debug_security_setup_negative(test_client):
90 """Debug negative cases: mTLS Error, Server AuthZ error
91
92 1) mTLS Error: Server expects client mTLS cert,
93 but client configured only for TLS.
94 2) AuthZ error: Client does not authorize server because of mismatched
95 SAN name.
96 """
97 # Client side.
98 client_correct_setup = True
99 channel: _Channel = test_client.wait_for_server_channel_state(
100 state=_ChannelState.TRANSIENT_FAILURE)
101 try:
102 subchannel, *subchannels = list(
103 test_client.channelz.list_channel_subchannels(channel))
104 except ValueError:
105 print("Client setup fail: subchannel not found. "
106 "Common causes: test client didn't connect to TD; "
107 "test client exhausted retries, and closed all subchannels.")
108 return
109
110 # Client must have exactly one subchannel.
111 logger.debug('Found subchannel, %s', subchannel)
112 if subchannels:
113 client_correct_setup = False
114 print(f'Unexpected subchannels {subchannels}')
115 subchannel_state: _ChannelState = subchannel.data.state.state
116 if subchannel_state is not _ChannelState.TRANSIENT_FAILURE:
117 client_correct_setup = False
118 print('Subchannel expected to be in '
119 'TRANSIENT_FAILURE, same as its channel')
120
121 # Client subchannel must have no sockets.
122 sockets = list(test_client.channelz.list_subchannels_sockets(subchannel))
123 if sockets:
124 client_correct_setup = False
125 print(f'Unexpected subchannel sockets {sockets}')
126
127 # Results.
128 if client_correct_setup:
129 print('Client setup pass: the channel '
130 'to the server has exactly one subchannel '
131 'in TRANSIENT_FAILURE, and no sockets')
132
133
134 def debug_security_setup_positive(test_client, test_server):
135 """Debug positive cases: mTLS, TLS, Plaintext."""
136 test_client.wait_for_active_server_channel()
137 client_sock: _Socket = test_client.get_active_server_channel_socket()
138 server_sock: _Socket = test_server.get_server_socket_matching_client(
139 client_sock)
140
141 server_tls = server_sock.security.tls
142 client_tls = client_sock.security.tls
143
144 print(f'\nServer certs:\n{debug_sock_tls(server_tls)}')
145 print(f'\nClient certs:\n{debug_sock_tls(client_tls)}')
146 print()
147
148 if server_tls.local_certificate:
149 eq = server_tls.local_certificate == client_tls.remote_certificate
150 print(f'(TLS) Server local matches client remote: {eq}')
151 else:
152 print('(TLS) Not detected')
153
154 if server_tls.remote_certificate:
155 eq = server_tls.remote_certificate == client_tls.local_certificate
156 print(f'(mTLS) Server remote matches client local: {eq}')
157 else:
158 print('(mTLS) Not detected')
159
160
161 def debug_basic_setup(test_client, test_server):
162 """Show channel and server socket pair"""
163 test_client.wait_for_active_server_channel()
164 client_sock: _Socket = test_client.get_active_server_channel_socket()
165 server_sock: _Socket = test_server.get_server_socket_matching_client(
166 client_sock)
167
168 print(f'Client socket:\n{client_sock}\n')
169 print(f'Matching server:\n{server_sock}\n')
170
171
172 def main(argv):
173 if len(argv) > 1:
174 raise app.UsageError('Too many command-line arguments.')
175
176 # Must be called before KubernetesApiManager or GcpApiManager init.
177 xds_flags.set_socket_default_timeout_from_flag()
178
179 k8s_api_manager = k8s.KubernetesApiManager(xds_k8s_flags.KUBE_CONTEXT.value)
180
181 # Resource names.
182 resource_prefix: str = xds_flags.RESOURCE_PREFIX.value
183
184 # Server
185 server_name = xds_flags.SERVER_NAME.value
186 server_namespace = resource_prefix
187 server_k8s_ns = k8s.KubernetesNamespace(k8s_api_manager, server_namespace)
188 server_pod = get_deployment_pods(server_k8s_ns, server_name)[0]
189 test_server: _XdsTestServer = _XdsTestServer(
190 ip=server_pod.status.pod_ip,
191 rpc_port=xds_flags.SERVER_PORT.value,
192 hostname=server_pod.metadata.name,
193 xds_host=xds_flags.SERVER_XDS_HOST.value,
194 xds_port=xds_flags.SERVER_XDS_PORT.value,
195 rpc_host=_SERVER_RPC_HOST.value)
196
197 # Client
198 client_name = xds_flags.CLIENT_NAME.value
199 client_namespace = resource_prefix
200 client_k8s_ns = k8s.KubernetesNamespace(k8s_api_manager, client_namespace)
201 client_pod = get_deployment_pods(client_k8s_ns, client_name)[0]
202 test_client: _XdsTestClient = _XdsTestClient(
203 ip=client_pod.status.pod_ip,
204 rpc_port=xds_flags.CLIENT_PORT.value,
205 server_target=test_server.xds_uri,
206 hostname=client_pod.metadata.name,
207 rpc_host=_CLIENT_RPC_HOST.value)
208
209 if _SECURITY.value in ('mtls', 'tls', 'plaintext'):
210 debug_security_setup_positive(test_client, test_server)
211 elif _SECURITY.value == ('mtls_error', 'server_authz_error'):
212 debug_security_setup_negative(test_client)
213 else:
214 debug_basic_setup(test_client, test_server)
215
216 test_client.close()
217 test_server.close()
218
219
220 if __name__ == '__main__':
221 app.run(main)