Debian Codegraph @

tools/run_tests/xds_k8s_test_driver/tests/affinity_test.py

raw
1 # Copyright 2021 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 import logging
15 import time
16 from typing import List
17
18 from absl import flags
19 from absl.testing import absltest
20 from google.protobuf import json_format
21
22 from framework import xds_k8s_flags
23 from framework import xds_k8s_testcase
24 from framework import xds_url_map_testcase
25 from framework.helpers import skips
26 from framework.rpc import grpc_channelz
27
28 logger = logging.getLogger(__name__)
29 flags.adopt_module_key_flags(xds_k8s_testcase)
30
31 # Type aliases
32 _XdsTestServer = xds_k8s_testcase.XdsTestServer
33 _XdsTestClient = xds_k8s_testcase.XdsTestClient
34 _ChannelzChannelState = grpc_channelz.ChannelState
35 _Lang = skips.Lang
36
37 # Testing consts
38 _TEST_AFFINITY_METADATA_KEY = 'xds_md'
39 _TD_PROPAGATE_CHECK_INTERVAL_SEC = 10
40 _TD_PROPAGATE_TIMEOUT = 600
41 _REPLICA_COUNT = 3
42 _RPC_COUNT = 100
43
44
45 class AffinityTest(xds_k8s_testcase.RegularXdsKubernetesTestCase):
46
47 @classmethod
48 def setUpClass(cls):
49 super().setUpClass()
50 # Force the python client to use the reference server image (Java)
51 # because the python server doesn't yet support set_not_serving RPC.
52 # TODO(https://github.com/grpc/grpc/issues/30635): Remove when resolved.
53 if cls.lang_spec.client_lang == _Lang.PYTHON:
54 cls.server_image = xds_k8s_flags.SERVER_IMAGE_CANONICAL.value
55
56 @staticmethod
57 def is_supported(config: skips.TestConfig) -> bool:
58 if config.client_lang in _Lang.CPP | _Lang.JAVA:
59 return config.version_gte('v1.40.x')
60 elif config.client_lang == _Lang.GO:
61 return config.version_gte('v1.41.x')
62 elif config.client_lang == _Lang.PYTHON:
63 # TODO(https://github.com/grpc/grpc/issues/27430): supported after
64 # the issue is fixed.
65 return False
66 elif config.client_lang == _Lang.NODE:
67 return False
68 return True
69
70 def test_affinity(self) -> None: # pylint: disable=too-many-statements
71
72 with self.subTest('00_create_health_check'):
73 self.td.create_health_check()
74
75 with self.subTest('01_create_backend_services'):
76 self.td.create_backend_service(
77 affinity_header=_TEST_AFFINITY_METADATA_KEY)
78
79 with self.subTest('02_create_url_map'):
80 self.td.create_url_map(self.server_xds_host, self.server_xds_port)
81
82 with self.subTest('03_create_target_proxy'):
83 self.td.create_target_proxy()
84
85 with self.subTest('04_create_forwarding_rule'):
86 self.td.create_forwarding_rule(self.server_xds_port)
87
88 test_servers: List[_XdsTestServer]
89 with self.subTest('05_start_test_servers'):
90 test_servers = self.startTestServers(replica_count=_REPLICA_COUNT)
91
92 with self.subTest('06_add_server_backends_to_backend_services'):
93 self.setupServerBackends()
94
95 test_client: _XdsTestClient
96 with self.subTest('07_start_test_client'):
97 test_client = self.startTestClient(test_servers[0],
98 rpc='EmptyCall',
99 metadata='EmptyCall:%s:123' %
100 _TEST_AFFINITY_METADATA_KEY)
101 # Validate the number of received endpoints and affinity configs.
102 config = test_client.csds.fetch_client_status(
103 log_level=logging.INFO)
104 self.assertIsNotNone(config)
105 json_config = json_format.MessageToDict(config)
106 parsed = xds_url_map_testcase.DumpedXdsConfig(json_config)
107 logging.info('Client received CSDS response: %s', parsed)
108 self.assertLen(parsed.endpoints, _REPLICA_COUNT)
109 self.assertEqual(
110 parsed.rds['virtualHosts'][0]['routes'][0]['route']
111 ['hashPolicy'][0]['header']['headerName'],
112 _TEST_AFFINITY_METADATA_KEY)
113 self.assertEqual(parsed.cds[0]['lbPolicy'], 'RING_HASH')
114
115 with self.subTest('08_test_client_xds_config_exists'):
116 self.assertXdsConfigExists(test_client)
117
118 with self.subTest('09_test_server_received_rpcs_from_test_client'):
119 self.assertSuccessfulRpcs(test_client)
120
121 with self.subTest('10_first_100_affinity_rpcs_pick_same_backend'):
122 rpc_stats = self.getClientRpcStats(test_client, _RPC_COUNT)
123 json_lb_stats = json_format.MessageToDict(rpc_stats)
124 rpc_distribution = xds_url_map_testcase.RpcDistributionStats(
125 json_lb_stats)
126 self.assertEqual(1, rpc_distribution.num_peers)
127 self.assertLen(
128 test_client.find_subchannels_with_state(
129 _ChannelzChannelState.READY),
130 1,
131 )
132 self.assertLen(
133 test_client.find_subchannels_with_state(
134 _ChannelzChannelState.IDLE),
135 2,
136 )
137 # Remember the backend inuse, and turn it down later.
138 first_backend_inuse = list(
139 rpc_distribution.raw['rpcsByPeer'].keys())[0]
140
141 with self.subTest('11_turn_down_server_in_use'):
142 for server in test_servers:
143 if server.hostname == first_backend_inuse:
144 server.set_not_serving()
145
146 with self.subTest('12_wait_for_unhealth_status_propagation'):
147 deadline = time.time() + _TD_PROPAGATE_TIMEOUT
148 parsed = None
149 try:
150 while time.time() < deadline:
151 config = test_client.csds.fetch_client_status(
152 log_level=logging.INFO)
153 self.assertIsNotNone(config)
154 json_config = json_format.MessageToDict(config)
155 parsed = xds_url_map_testcase.DumpedXdsConfig(json_config)
156 if len(parsed.endpoints) == _REPLICA_COUNT - 1:
157 break
158 logging.info(
159 'CSDS got unexpected endpoints, will retry after %d seconds',
160 _TD_PROPAGATE_CHECK_INTERVAL_SEC)
161 time.sleep(_TD_PROPAGATE_CHECK_INTERVAL_SEC)
162 else:
163 self.fail(
164 'unhealthy status did not propagate after 600 seconds')
165 finally:
166 logging.info('Client received CSDS response: %s', parsed)
167
168 with self.subTest('12_next_100_affinity_rpcs_pick_different_backend'):
169 rpc_stats = self.getClientRpcStats(test_client, _RPC_COUNT)
170 json_lb_stats = json_format.MessageToDict(rpc_stats)
171 rpc_distribution = xds_url_map_testcase.RpcDistributionStats(
172 json_lb_stats)
173 self.assertEqual(1, rpc_distribution.num_peers)
174 new_backend_inuse = list(
175 rpc_distribution.raw['rpcsByPeer'].keys())[0]
176 self.assertNotEqual(new_backend_inuse, first_backend_inuse)
177
178
179 if __name__ == '__main__':
180 absltest.main(failfast=True)