Debian Codegraph @

test/cpp/end2end/xds/xds_ring_hash_end2end_test.cc

raw
1 // Copyright 2017 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
16 #include <string>
17 #include <vector>
18
19 #include <gmock/gmock.h>
20 #include <gtest/gtest.h>
21
22 #include "absl/strings/str_cat.h"
23 #include "absl/strings/str_format.h"
24
25 #include <grpc/event_engine/endpoint_config.h>
26
27 #include "src/core/ext/filters/client_channel/backup_poller.h"
28 #include "src/core/ext/filters/client_channel/lb_policy/xds/xds_channel_args.h"
29 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
30 #include "src/core/lib/address_utils/sockaddr_utils.h"
31 #include "src/core/lib/gprpp/env.h"
32 #include "src/proto/grpc/testing/xds/v3/aggregate_cluster.grpc.pb.h"
33 #include "src/proto/grpc/testing/xds/v3/cluster.grpc.pb.h"
34 #include "test/cpp/end2end/connection_attempt_injector.h"
35 #include "test/cpp/end2end/xds/xds_end2end_test_lib.h"
36
37 namespace grpc {
38 namespace testing {
39 namespace {
40
41 using ::envoy::config::cluster::v3::CustomClusterType;
42 using ::envoy::config::endpoint::v3::HealthStatus;
43 using ::envoy::extensions::clusters::aggregate::v3::ClusterConfig;
44
45 class RingHashTest : public XdsEnd2endTest {
46 protected:
47 void SetUp() override {
48 logical_dns_cluster_resolver_response_generator_ =
49 grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
50 InitClient();
51 SetUpChannel();
52 }
53
54 void SetUpChannel(ChannelArguments* args = nullptr) {
55 ChannelArguments local_args;
56 if (args == nullptr) args = &local_args;
57 args->SetPointerWithVtable(
58 GRPC_ARG_XDS_LOGICAL_DNS_CLUSTER_FAKE_RESOLVER_RESPONSE_GENERATOR,
59 logical_dns_cluster_resolver_response_generator_.get(),
60 &grpc_core::FakeResolverResponseGenerator::kChannelArgPointerVtable);
61 ResetStub(/*failover_timeout_ms=*/0, args);
62 }
63
64 grpc_core::ServerAddressList CreateAddressListFromPortList(
65 const std::vector<int>& ports) {
66 grpc_core::ServerAddressList addresses;
67 for (int port : ports) {
68 absl::StatusOr<grpc_core::URI> lb_uri = grpc_core::URI::Parse(
69 absl::StrCat(ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", port));
70 GPR_ASSERT(lb_uri.ok());
71 grpc_resolved_address address;
72 GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
73 addresses.emplace_back(address.addr, address.len,
74 grpc_core::ChannelArgs());
75 }
76 return addresses;
77 }
78
79 std::string CreateMetadataValueThatHashesToBackendPort(int port) {
80 return absl::StrCat(ipv6_only_ ? "[::1]" : "127.0.0.1", ":", port, "_0");
81 }
82
83 std::string CreateMetadataValueThatHashesToBackend(int index) {
84 return CreateMetadataValueThatHashesToBackendPort(backends_[index]->port());
85 }
86
87 grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
88 logical_dns_cluster_resolver_response_generator_;
89 };
90
91 // Run both with and without load reporting, just for test coverage.
92 INSTANTIATE_TEST_SUITE_P(
93 XdsTest, RingHashTest,
94 ::testing::Values(XdsTestType(), XdsTestType().set_enable_load_reporting()),
95 &XdsTestType::Name);
96
97 TEST_P(RingHashTest, AggregateClusterFallBackFromRingHashAtStartup) {
98 CreateAndStartBackends(2);
99 const char* kNewCluster1Name = "new_cluster_1";
100 const char* kNewEdsService1Name = "new_eds_service_name_1";
101 const char* kNewCluster2Name = "new_cluster_2";
102 const char* kNewEdsService2Name = "new_eds_service_name_2";
103 // Populate new EDS resources.
104 EdsResourceArgs args1({
105 {"locality0", {MakeNonExistantEndpoint(), MakeNonExistantEndpoint()}},
106 });
107 EdsResourceArgs args2({
108 {"locality0", CreateEndpointsForBackends()},
109 });
110 balancer_->ads_service()->SetEdsResource(
111 BuildEdsResource(args1, kNewEdsService1Name));
112 balancer_->ads_service()->SetEdsResource(
113 BuildEdsResource(args2, kNewEdsService2Name));
114 // Populate new CDS resources.
115 Cluster new_cluster1 = default_cluster_;
116 new_cluster1.set_name(kNewCluster1Name);
117 new_cluster1.mutable_eds_cluster_config()->set_service_name(
118 kNewEdsService1Name);
119 balancer_->ads_service()->SetCdsResource(new_cluster1);
120 Cluster new_cluster2 = default_cluster_;
121 new_cluster2.set_name(kNewCluster2Name);
122 new_cluster2.mutable_eds_cluster_config()->set_service_name(
123 kNewEdsService2Name);
124 balancer_->ads_service()->SetCdsResource(new_cluster2);
125 // Create Aggregate Cluster
126 auto cluster = default_cluster_;
127 cluster.set_lb_policy(Cluster::RING_HASH);
128 CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
129 custom_cluster->set_name("envoy.clusters.aggregate");
130 ClusterConfig cluster_config;
131 cluster_config.add_clusters(kNewCluster1Name);
132 cluster_config.add_clusters(kNewCluster2Name);
133 custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
134 balancer_->ads_service()->SetCdsResource(cluster);
135 // Set up route with channel id hashing
136 auto new_route_config = default_route_config_;
137 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
138 auto* hash_policy = route->mutable_route()->add_hash_policy();
139 hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
140 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
141 new_route_config);
142 // Verifying that we are using ring hash as only 1 endpoint is receiving all
143 // the traffic.
144 CheckRpcSendOk(DEBUG_LOCATION, 100, RpcOptions().set_timeout_ms(5000));
145 bool found = false;
146 for (size_t i = 0; i < backends_.size(); ++i) {
147 if (backends_[i]->backend_service()->request_count() > 0) {
148 EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
149 << "backend " << i;
150 EXPECT_FALSE(found) << "backend " << i;
151 found = true;
152 }
153 }
154 EXPECT_TRUE(found);
155 }
156
157 TEST_P(RingHashTest,
158 AggregateClusterFallBackFromRingHashToLogicalDnsAtStartup) {
159 CreateAndStartBackends(1);
160 const char* kEdsClusterName = "eds_cluster";
161 const char* kLogicalDNSClusterName = "logical_dns_cluster";
162 // Populate EDS resource.
163 EdsResourceArgs args({
164 {"locality0",
165 {MakeNonExistantEndpoint(), MakeNonExistantEndpoint()},
166 kDefaultLocalityWeight,
167 0},
168 {"locality1",
169 {MakeNonExistantEndpoint(), MakeNonExistantEndpoint()},
170 kDefaultLocalityWeight,
171 1},
172 });
173 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
174 // Populate new CDS resources.
175 Cluster eds_cluster = default_cluster_;
176 eds_cluster.set_name(kEdsClusterName);
177 balancer_->ads_service()->SetCdsResource(eds_cluster);
178 // Populate LOGICAL_DNS cluster.
179 auto logical_dns_cluster = default_cluster_;
180 logical_dns_cluster.set_name(kLogicalDNSClusterName);
181 logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
182 auto* address = logical_dns_cluster.mutable_load_assignment()
183 ->add_endpoints()
184 ->add_lb_endpoints()
185 ->mutable_endpoint()
186 ->mutable_address()
187 ->mutable_socket_address();
188 address->set_address(kServerName);
189 address->set_port_value(443);
190 balancer_->ads_service()->SetCdsResource(logical_dns_cluster);
191 // Create Aggregate Cluster
192 auto cluster = default_cluster_;
193 cluster.set_lb_policy(Cluster::RING_HASH);
194 CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
195 custom_cluster->set_name("envoy.clusters.aggregate");
196 ClusterConfig cluster_config;
197 cluster_config.add_clusters(kEdsClusterName);
198 cluster_config.add_clusters(kLogicalDNSClusterName);
199 custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
200 balancer_->ads_service()->SetCdsResource(cluster);
201 // Set up route with channel id hashing
202 auto new_route_config = default_route_config_;
203 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
204 auto* hash_policy = route->mutable_route()->add_hash_policy();
205 hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
206 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
207 new_route_config);
208 // Set Logical DNS result
209 {
210 grpc_core::ExecCtx exec_ctx;
211 grpc_core::Resolver::Result result;
212 result.addresses = CreateAddressListFromPortList(GetBackendPorts());
213 logical_dns_cluster_resolver_response_generator_->SetResponse(
214 std::move(result));
215 }
216 // Inject connection delay to make this act more realistically.
217 ConnectionAttemptInjector injector;
218 injector.SetDelay(grpc_core::Duration::Milliseconds(500) *
219 grpc_test_slowdown_factor());
220 // Send RPC. Need the timeout to be long enough to account for the
221 // subchannel connection delays.
222 CheckRpcSendOk(DEBUG_LOCATION, 1, RpcOptions().set_timeout_ms(5000));
223 }
224
225 TEST_P(RingHashTest,
226 AggregateClusterFallBackFromRingHashToLogicalDnsAtStartupNoFailedRpcs) {
227 CreateAndStartBackends(1);
228 const char* kEdsClusterName = "eds_cluster";
229 const char* kLogicalDNSClusterName = "logical_dns_cluster";
230 // Populate EDS resource.
231 EdsResourceArgs args({
232 {"locality0",
233 {MakeNonExistantEndpoint(), MakeNonExistantEndpoint()},
234 kDefaultLocalityWeight,
235 0},
236 {"locality1",
237 {MakeNonExistantEndpoint(), MakeNonExistantEndpoint()},
238 kDefaultLocalityWeight,
239 1},
240 });
241 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
242 // Populate new CDS resources.
243 Cluster eds_cluster = default_cluster_;
244 eds_cluster.set_name(kEdsClusterName);
245 balancer_->ads_service()->SetCdsResource(eds_cluster);
246 // Populate LOGICAL_DNS cluster.
247 auto logical_dns_cluster = default_cluster_;
248 logical_dns_cluster.set_name(kLogicalDNSClusterName);
249 logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
250 auto* address = logical_dns_cluster.mutable_load_assignment()
251 ->add_endpoints()
252 ->add_lb_endpoints()
253 ->mutable_endpoint()
254 ->mutable_address()
255 ->mutable_socket_address();
256 address->set_address(kServerName);
257 address->set_port_value(443);
258 balancer_->ads_service()->SetCdsResource(logical_dns_cluster);
259 // Create Aggregate Cluster
260 auto cluster = default_cluster_;
261 cluster.set_lb_policy(Cluster::RING_HASH);
262 CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
263 custom_cluster->set_name("envoy.clusters.aggregate");
264 ClusterConfig cluster_config;
265 cluster_config.add_clusters(kEdsClusterName);
266 cluster_config.add_clusters(kLogicalDNSClusterName);
267 custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
268 balancer_->ads_service()->SetCdsResource(cluster);
269 // Set up route with channel id hashing
270 auto new_route_config = default_route_config_;
271 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
272 auto* hash_policy = route->mutable_route()->add_hash_policy();
273 hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
274 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
275 new_route_config);
276 // Set Logical DNS result
277 {
278 grpc_core::ExecCtx exec_ctx;
279 grpc_core::Resolver::Result result;
280 result.addresses = CreateAddressListFromPortList(GetBackendPorts());
281 logical_dns_cluster_resolver_response_generator_->SetResponse(
282 std::move(result));
283 }
284 // Set up connection attempt injector.
285 ConnectionAttemptInjector injector;
286 auto hold = injector.AddHold(backends_[0]->port());
287 // Increase subchannel backoff time, so that subchannels stay in
288 // TRANSIENT_FAILURE for long enough to trigger potential problems.
289 ChannelArguments channel_args;
290 channel_args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS,
291 10000 * grpc_test_slowdown_factor());
292 SetUpChannel(&channel_args);
293 // Start an RPC in the background.
294 LongRunningRpc rpc;
295 rpc.StartRpc(stub_.get(), RpcOptions().set_timeout_ms(5000));
296 // Wait for connection attempt to the backend.
297 hold->Wait();
298 // Channel should report CONNECTING here, and any RPC should be queued.
299 EXPECT_EQ(channel_->GetState(false), GRPC_CHANNEL_CONNECTING);
300 // Start a second RPC at this point, which should be queued as well.
301 // This will fail if the priority policy fails to update the picker to
302 // point to the LOGICAL_DNS child; if it leaves it pointing to the EDS
303 // priority 1, then the RPC will fail, because all subchannels are in
304 // TRANSIENT_FAILURE.
305 // Note that sending only the first RPC does not catch this case,
306 // because if the priority policy fails to update the picker, then the
307 // pick for the first RPC will not be retried.
308 LongRunningRpc rpc2;
309 rpc2.StartRpc(stub_.get(), RpcOptions().set_timeout_ms(5000));
310 // Allow the connection attempt to complete.
311 hold->Resume();
312 // Now the RPCs should complete successfully.
313 gpr_log(GPR_INFO, "=== WAITING FOR FIRST RPC TO FINISH ===");
314 Status status = rpc.GetStatus();
315 gpr_log(GPR_INFO, "=== FIRST RPC FINISHED ===");
316 EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
317 << " message=" << status.error_message();
318 gpr_log(GPR_INFO, "=== WAITING FOR SECOND RPC TO FINISH ===");
319 status = rpc2.GetStatus();
320 gpr_log(GPR_INFO, "=== SECOND RPC FINISHED ===");
321 EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
322 << " message=" << status.error_message();
323 }
324
325 // Tests that ring hash policy that hashes using channel id ensures all RPCs
326 // to go 1 particular backend.
327 TEST_P(RingHashTest, ChannelIdHashing) {
328 CreateAndStartBackends(4);
329 auto cluster = default_cluster_;
330 cluster.set_lb_policy(Cluster::RING_HASH);
331 balancer_->ads_service()->SetCdsResource(cluster);
332 auto new_route_config = default_route_config_;
333 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
334 auto* hash_policy = route->mutable_route()->add_hash_policy();
335 hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
336 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
337 new_route_config);
338 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
339 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
340 CheckRpcSendOk(DEBUG_LOCATION, 100, RpcOptions().set_timeout_ms(5000));
341 bool found = false;
342 for (size_t i = 0; i < backends_.size(); ++i) {
343 if (backends_[i]->backend_service()->request_count() > 0) {
344 EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
345 << "backend " << i;
346 EXPECT_FALSE(found) << "backend " << i;
347 found = true;
348 }
349 }
350 EXPECT_TRUE(found);
351 }
352
353 // Tests that ring hash policy that hashes using a header value can spread
354 // RPCs across all the backends.
355 TEST_P(RingHashTest, HeaderHashing) {
356 CreateAndStartBackends(4);
357 auto cluster = default_cluster_;
358 cluster.set_lb_policy(Cluster::RING_HASH);
359 balancer_->ads_service()->SetCdsResource(cluster);
360 auto new_route_config = default_route_config_;
361 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
362 auto* hash_policy = route->mutable_route()->add_hash_policy();
363 hash_policy->mutable_header()->set_header_name("address_hash");
364 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
365 new_route_config);
366 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
367 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
368 // Note each type of RPC will contains a header value that will always be
369 // hashed to a specific backend as the header value matches the value used
370 // to create the entry in the ring.
371 std::vector<std::pair<std::string, std::string>> metadata = {
372 {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
373 std::vector<std::pair<std::string, std::string>> metadata1 = {
374 {"address_hash", CreateMetadataValueThatHashesToBackend(1)}};
375 std::vector<std::pair<std::string, std::string>> metadata2 = {
376 {"address_hash", CreateMetadataValueThatHashesToBackend(2)}};
377 std::vector<std::pair<std::string, std::string>> metadata3 = {
378 {"address_hash", CreateMetadataValueThatHashesToBackend(3)}};
379 const auto rpc_options =
380 RpcOptions().set_metadata(std::move(metadata)).set_timeout_ms(5000);
381 const auto rpc_options1 =
382 RpcOptions().set_metadata(std::move(metadata1)).set_timeout_ms(5000);
383 const auto rpc_options2 =
384 RpcOptions().set_metadata(std::move(metadata2)).set_timeout_ms(5000);
385 const auto rpc_options3 =
386 RpcOptions().set_metadata(std::move(metadata3)).set_timeout_ms(5000);
387 WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
388 WaitForBackendOptions(), rpc_options);
389 WaitForBackend(DEBUG_LOCATION, 1, /*check_status=*/nullptr,
390 WaitForBackendOptions(), rpc_options1);
391 WaitForBackend(DEBUG_LOCATION, 2, /*check_status=*/nullptr,
392 WaitForBackendOptions(), rpc_options2);
393 WaitForBackend(DEBUG_LOCATION, 3, /*check_status=*/nullptr,
394 WaitForBackendOptions(), rpc_options3);
395 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
396 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options1);
397 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options2);
398 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options3);
399 for (size_t i = 0; i < backends_.size(); ++i) {
400 EXPECT_EQ(100, backends_[i]->backend_service()->request_count());
401 }
402 }
403
404 // Tests that ring hash policy that hashes using a header value and regex
405 // rewrite to aggregate RPCs to 1 backend.
406 TEST_P(RingHashTest, HeaderHashingWithRegexRewrite) {
407 CreateAndStartBackends(4);
408 auto cluster = default_cluster_;
409 cluster.set_lb_policy(Cluster::RING_HASH);
410 balancer_->ads_service()->SetCdsResource(cluster);
411 auto new_route_config = default_route_config_;
412 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
413 auto* hash_policy = route->mutable_route()->add_hash_policy();
414 hash_policy->mutable_header()->set_header_name("address_hash");
415 hash_policy->mutable_header()
416 ->mutable_regex_rewrite()
417 ->mutable_pattern()
418 ->set_regex("[0-9]+");
419 hash_policy->mutable_header()->mutable_regex_rewrite()->set_substitution(
420 "foo");
421 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
422 new_route_config);
423 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
424 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
425 std::vector<std::pair<std::string, std::string>> metadata = {
426 {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
427 std::vector<std::pair<std::string, std::string>> metadata1 = {
428 {"address_hash", CreateMetadataValueThatHashesToBackend(1)}};
429 std::vector<std::pair<std::string, std::string>> metadata2 = {
430 {"address_hash", CreateMetadataValueThatHashesToBackend(2)}};
431 std::vector<std::pair<std::string, std::string>> metadata3 = {
432 {"address_hash", CreateMetadataValueThatHashesToBackend(3)}};
433 const auto rpc_options =
434 RpcOptions().set_metadata(std::move(metadata)).set_timeout_ms(5000);
435 const auto rpc_options1 =
436 RpcOptions().set_metadata(std::move(metadata1)).set_timeout_ms(5000);
437 const auto rpc_options2 =
438 RpcOptions().set_metadata(std::move(metadata2)).set_timeout_ms(5000);
439 const auto rpc_options3 =
440 RpcOptions().set_metadata(std::move(metadata3)).set_timeout_ms(5000);
441 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
442 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options1);
443 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options2);
444 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options3);
445 bool found = false;
446 for (size_t i = 0; i < backends_.size(); ++i) {
447 if (backends_[i]->backend_service()->request_count() > 0) {
448 EXPECT_EQ(backends_[i]->backend_service()->request_count(), 400)
449 << "backend " << i;
450 EXPECT_FALSE(found) << "backend " << i;
451 found = true;
452 }
453 }
454 EXPECT_TRUE(found);
455 }
456
457 // Tests that ring hash policy that hashes using a random value.
458 TEST_P(RingHashTest, NoHashPolicy) {
459 CreateAndStartBackends(2);
460 const double kDistribution50Percent = 0.5;
461 const double kErrorTolerance = 0.05;
462 const uint32_t kRpcTimeoutMs = 10000;
463 const size_t kNumRpcs =
464 ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
465 auto cluster = default_cluster_;
466 // Increasing min ring size for random distribution.
467 cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
468 100000);
469 cluster.set_lb_policy(Cluster::RING_HASH);
470 balancer_->ads_service()->SetCdsResource(cluster);
471 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
472 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
473 // TODO(donnadionne): remove extended timeout after ring creation
474 // optimization.
475 WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
476 WaitForBackendOptions().set_timeout_ms(kRpcTimeoutMs),
477 RpcOptions().set_timeout_ms(kRpcTimeoutMs));
478 CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs);
479 const int request_count_1 = backends_[0]->backend_service()->request_count();
480 const int request_count_2 = backends_[1]->backend_service()->request_count();
481 EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
482 ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
483 EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
484 ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
485 }
486
487 // Tests that we observe endpoint weights.
488 TEST_P(RingHashTest, EndpointWeights) {
489 CreateAndStartBackends(3);
490 const double kDistribution50Percent = 0.5;
491 const double kDistribution25Percent = 0.25;
492 const double kErrorTolerance = 0.05;
493 const uint32_t kRpcTimeoutMs = 10000;
494 const size_t kNumRpcs =
495 ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
496 auto cluster = default_cluster_;
497 // Increasing min ring size for random distribution.
498 cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
499 100000);
500 cluster.set_lb_policy(Cluster::RING_HASH);
501 balancer_->ads_service()->SetCdsResource(cluster);
502 // Endpoint 0 has weight 0, will be treated as weight 1.
503 // Endpoint 1 has weight 1.
504 // Endpoint 2 has weight 2.
505 EdsResourceArgs args(
506 {{"locality0",
507 {CreateEndpoint(0, ::envoy::config::endpoint::v3::HealthStatus::UNKNOWN,
508 0),
509 CreateEndpoint(1, ::envoy::config::endpoint::v3::HealthStatus::UNKNOWN,
510 1),
511 CreateEndpoint(2, ::envoy::config::endpoint::v3::HealthStatus::UNKNOWN,
512 2)}}});
513 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
514 // TODO(donnadionne): remove extended timeout after ring creation
515 // optimization.
516 WaitForAllBackends(DEBUG_LOCATION, 0, 3, /*check_status=*/nullptr,
517 WaitForBackendOptions().set_timeout_ms(kRpcTimeoutMs),
518 RpcOptions().set_timeout_ms(kRpcTimeoutMs));
519 CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs);
520 // Endpoint 2 should see 50% of traffic, and endpoints 0 and 1 should
521 // each see 25% of traffic.
522 const int request_count_0 = backends_[0]->backend_service()->request_count();
523 const int request_count_1 = backends_[1]->backend_service()->request_count();
524 const int request_count_2 = backends_[2]->backend_service()->request_count();
525 EXPECT_THAT(static_cast<double>(request_count_0) / kNumRpcs,
526 ::testing::DoubleNear(kDistribution25Percent, kErrorTolerance));
527 EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
528 ::testing::DoubleNear(kDistribution25Percent, kErrorTolerance));
529 EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
530 ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
531 }
532
533 // Test that ring hash policy evaluation will continue past the terminal
534 // policy if no results are produced yet.
535 TEST_P(RingHashTest, ContinuesPastTerminalPolicyThatDoesNotProduceResult) {
536 CreateAndStartBackends(2);
537 auto cluster = default_cluster_;
538 cluster.set_lb_policy(Cluster::RING_HASH);
539 balancer_->ads_service()->SetCdsResource(cluster);
540 auto new_route_config = default_route_config_;
541 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
542 auto* hash_policy = route->mutable_route()->add_hash_policy();
543 hash_policy->mutable_header()->set_header_name("header_not_present");
544 hash_policy->set_terminal(true);
545 auto* hash_policy2 = route->mutable_route()->add_hash_policy();
546 hash_policy2->mutable_header()->set_header_name("address_hash");
547 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
548 new_route_config);
549 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
550 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
551 std::vector<std::pair<std::string, std::string>> metadata = {
552 {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
553 const auto rpc_options =
554 RpcOptions().set_metadata(std::move(metadata)).set_timeout_ms(5000);
555 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
556 EXPECT_EQ(backends_[0]->backend_service()->request_count(), 100);
557 EXPECT_EQ(backends_[1]->backend_service()->request_count(), 0);
558 }
559
560 // Test random hash is used when header hashing specified a header field that
561 // the RPC did not have.
562 TEST_P(RingHashTest, HashOnHeaderThatIsNotPresent) {
563 CreateAndStartBackends(2);
564 const double kDistribution50Percent = 0.5;
565 const double kErrorTolerance = 0.05;
566 const uint32_t kRpcTimeoutMs = 10000;
567 const size_t kNumRpcs =
568 ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
569 auto cluster = default_cluster_;
570 // Increasing min ring size for random distribution.
571 cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
572 100000);
573 cluster.set_lb_policy(Cluster::RING_HASH);
574 balancer_->ads_service()->SetCdsResource(cluster);
575 auto new_route_config = default_route_config_;
576 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
577 auto* hash_policy = route->mutable_route()->add_hash_policy();
578 hash_policy->mutable_header()->set_header_name("header_not_present");
579 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
580 new_route_config);
581 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
582 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
583 std::vector<std::pair<std::string, std::string>> metadata = {
584 {"unmatched_header", absl::StrFormat("%" PRIu32, rand())},
585 };
586 const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
587 // TODO(donnadionne): remove extended timeout after ring creation
588 // optimization.
589 WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
590 WaitForBackendOptions().set_timeout_ms(kRpcTimeoutMs),
591 RpcOptions().set_timeout_ms(kRpcTimeoutMs));
592 CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs, rpc_options);
593 const int request_count_1 = backends_[0]->backend_service()->request_count();
594 const int request_count_2 = backends_[1]->backend_service()->request_count();
595 EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
596 ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
597 EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
598 ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
599 }
600
601 // Test random hash is used when only unsupported hash policies are
602 // configured.
603 TEST_P(RingHashTest, UnsupportedHashPolicyDefaultToRandomHashing) {
604 CreateAndStartBackends(2);
605 const double kDistribution50Percent = 0.5;
606 const double kErrorTolerance = 0.05;
607 const uint32_t kRpcTimeoutMs = 10000;
608 const size_t kNumRpcs =
609 ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
610 auto cluster = default_cluster_;
611 // Increasing min ring size for random distribution.
612 cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
613 100000);
614 cluster.set_lb_policy(Cluster::RING_HASH);
615 balancer_->ads_service()->SetCdsResource(cluster);
616 auto new_route_config = default_route_config_;
617 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
618 auto* hash_policy_unsupported_1 = route->mutable_route()->add_hash_policy();
619 hash_policy_unsupported_1->mutable_cookie()->set_name("cookie");
620 auto* hash_policy_unsupported_2 = route->mutable_route()->add_hash_policy();
621 hash_policy_unsupported_2->mutable_connection_properties()->set_source_ip(
622 true);
623 auto* hash_policy_unsupported_3 = route->mutable_route()->add_hash_policy();
624 hash_policy_unsupported_3->mutable_query_parameter()->set_name(
625 "query_parameter");
626 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
627 new_route_config);
628 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
629 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
630 // TODO(donnadionne): remove extended timeout after ring creation
631 // optimization.
632 WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
633 WaitForBackendOptions().set_timeout_ms(kRpcTimeoutMs),
634 RpcOptions().set_timeout_ms(kRpcTimeoutMs));
635 CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs);
636 const int request_count_1 = backends_[0]->backend_service()->request_count();
637 const int request_count_2 = backends_[1]->backend_service()->request_count();
638 EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
639 ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
640 EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
641 ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
642 }
643
644 // Tests that ring hash policy that hashes using a random value can spread
645 // RPCs across all the backends according to locality weight.
646 TEST_P(RingHashTest, RandomHashingDistributionAccordingToEndpointWeight) {
647 CreateAndStartBackends(2);
648 const size_t kWeight1 = 1;
649 const size_t kWeight2 = 2;
650 const size_t kWeightTotal = kWeight1 + kWeight2;
651 const double kWeight33Percent = static_cast<double>(kWeight1) / kWeightTotal;
652 const double kWeight66Percent = static_cast<double>(kWeight2) / kWeightTotal;
653 const double kErrorTolerance = 0.05;
654 const uint32_t kRpcTimeoutMs = 10000;
655 const size_t kNumRpcs =
656 ComputeIdealNumRpcs(kWeight33Percent, kErrorTolerance);
657 auto cluster = default_cluster_;
658 // Increasing min ring size for random distribution.
659 cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
660 100000);
661 cluster.set_lb_policy(Cluster::RING_HASH);
662 balancer_->ads_service()->SetCdsResource(cluster);
663 EdsResourceArgs args({{"locality0",
664 {CreateEndpoint(0, HealthStatus::UNKNOWN, 1),
665 CreateEndpoint(1, HealthStatus::UNKNOWN, 2)}}});
666 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
667 // TODO(donnadionne): remove extended timeout after ring creation
668 // optimization.
669 WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
670 WaitForBackendOptions().set_timeout_ms(kRpcTimeoutMs),
671 RpcOptions().set_timeout_ms(kRpcTimeoutMs));
672 CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs);
673 const int weight_33_request_count =
674 backends_[0]->backend_service()->request_count();
675 const int weight_66_request_count =
676 backends_[1]->backend_service()->request_count();
677 EXPECT_THAT(static_cast<double>(weight_33_request_count) / kNumRpcs,
678 ::testing::DoubleNear(kWeight33Percent, kErrorTolerance));
679 EXPECT_THAT(static_cast<double>(weight_66_request_count) / kNumRpcs,
680 ::testing::DoubleNear(kWeight66Percent, kErrorTolerance));
681 }
682
683 // Tests that ring hash policy that hashes using a random value can spread
684 // RPCs across all the backends according to locality weight.
685 TEST_P(RingHashTest,
686 RandomHashingDistributionAccordingToLocalityAndEndpointWeight) {
687 CreateAndStartBackends(2);
688 const size_t kWeight1 = 1 * 1;
689 const size_t kWeight2 = 2 * 2;
690 const size_t kWeightTotal = kWeight1 + kWeight2;
691 const double kWeight20Percent = static_cast<double>(kWeight1) / kWeightTotal;
692 const double kWeight80Percent = static_cast<double>(kWeight2) / kWeightTotal;
693 const double kErrorTolerance = 0.05;
694 const uint32_t kRpcTimeoutMs = 10000;
695 const size_t kNumRpcs =
696 ComputeIdealNumRpcs(kWeight20Percent, kErrorTolerance);
697 auto cluster = default_cluster_;
698 // Increasing min ring size for random distribution.
699 cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
700 100000);
701 cluster.set_lb_policy(Cluster::RING_HASH);
702 balancer_->ads_service()->SetCdsResource(cluster);
703 EdsResourceArgs args(
704 {{"locality0", {CreateEndpoint(0, HealthStatus::UNKNOWN, 1)}, 1},
705 {"locality1", {CreateEndpoint(1, HealthStatus::UNKNOWN, 2)}, 2}});
706 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
707 // TODO(donnadionne): remove extended timeout after ring creation
708 // optimization.
709 WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
710 WaitForBackendOptions().set_timeout_ms(kRpcTimeoutMs),
711 RpcOptions().set_timeout_ms(kRpcTimeoutMs));
712 CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs);
713 const int weight_20_request_count =
714 backends_[0]->backend_service()->request_count();
715 const int weight_80_request_count =
716 backends_[1]->backend_service()->request_count();
717 EXPECT_THAT(static_cast<double>(weight_20_request_count) / kNumRpcs,
718 ::testing::DoubleNear(kWeight20Percent, kErrorTolerance));
719 EXPECT_THAT(static_cast<double>(weight_80_request_count) / kNumRpcs,
720 ::testing::DoubleNear(kWeight80Percent, kErrorTolerance));
721 }
722
723 // Tests that ring hash policy that hashes using a fixed string ensures all
724 // RPCs to go 1 particular backend; and that subsequent hashing policies are
725 // ignored due to the setting of terminal.
726 TEST_P(RingHashTest, FixedHashingTerminalPolicy) {
727 CreateAndStartBackends(2);
728 auto cluster = default_cluster_;
729 cluster.set_lb_policy(Cluster::RING_HASH);
730 balancer_->ads_service()->SetCdsResource(cluster);
731 auto new_route_config = default_route_config_;
732 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
733 auto* hash_policy = route->mutable_route()->add_hash_policy();
734 hash_policy->mutable_header()->set_header_name("fixed_string");
735 hash_policy->set_terminal(true);
736 auto* hash_policy_to_be_ignored = route->mutable_route()->add_hash_policy();
737 hash_policy_to_be_ignored->mutable_header()->set_header_name("random_string");
738 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
739 new_route_config);
740 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
741 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
742 std::vector<std::pair<std::string, std::string>> metadata = {
743 {"fixed_string", "fixed_value"},
744 {"random_string", absl::StrFormat("%" PRIu32, rand())},
745 };
746 const auto rpc_options =
747 RpcOptions().set_metadata(std::move(metadata)).set_timeout_ms(5000);
748 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
749 bool found = false;
750 for (size_t i = 0; i < backends_.size(); ++i) {
751 if (backends_[i]->backend_service()->request_count() > 0) {
752 EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
753 << "backend " << i;
754 EXPECT_FALSE(found) << "backend " << i;
755 found = true;
756 }
757 }
758 EXPECT_TRUE(found);
759 }
760
761 // Test that the channel will go from idle to ready via connecting;
762 // (tho it is not possible to catch the connecting state before moving to
763 // ready)
764 TEST_P(RingHashTest, IdleToReady) {
765 CreateAndStartBackends(1);
766 auto cluster = default_cluster_;
767 cluster.set_lb_policy(Cluster::RING_HASH);
768 balancer_->ads_service()->SetCdsResource(cluster);
769 auto new_route_config = default_route_config_;
770 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
771 auto* hash_policy = route->mutable_route()->add_hash_policy();
772 hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
773 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
774 new_route_config);
775 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
776 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
777 EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
778 CheckRpcSendOk(DEBUG_LOCATION, 1, RpcOptions().set_timeout_ms(5000));
779 EXPECT_EQ(GRPC_CHANNEL_READY, channel_->GetState(false));
780 }
781
782 // Test that the channel will transition to READY once it starts
783 // connecting even if there are no RPCs being sent to the picker.
784 TEST_P(RingHashTest, ContinuesConnectingWithoutPicks) {
785 // Create EDS resource.
786 CreateAndStartBackends(1);
787 auto non_existant_endpoint = MakeNonExistantEndpoint();
788 EdsResourceArgs args(
789 {{"locality0", {non_existant_endpoint, CreateEndpoint(0)}}});
790 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
791 // Change CDS resource to use RING_HASH.
792 auto cluster = default_cluster_;
793 cluster.set_lb_policy(Cluster::RING_HASH);
794 balancer_->ads_service()->SetCdsResource(cluster);
795 // Add hash policy to RDS resource.
796 auto new_route_config = default_route_config_;
797 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
798 auto* hash_policy = route->mutable_route()->add_hash_policy();
799 hash_policy->mutable_header()->set_header_name("address_hash");
800 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
801 new_route_config);
802 // Start connection attempt injector and add a hold for the P0
803 // connection attempt.
804 ConnectionAttemptInjector injector;
805 auto hold = injector.AddHold(non_existant_endpoint.port);
806 // A long-running RPC, just used to send the RPC in another thread.
807 LongRunningRpc rpc;
808 std::vector<std::pair<std::string, std::string>> metadata = {
809 {"address_hash",
810 CreateMetadataValueThatHashesToBackendPort(non_existant_endpoint.port)}};
811 rpc.StartRpc(stub_.get(), RpcOptions().set_timeout_ms(0).set_metadata(
812 std::move(metadata)));
813 // Wait for the RPC to trigger the P0 connection attempt, then cancel it,
814 // and then allow the connection attempt to complete.
815 hold->Wait();
816 rpc.CancelRpc();
817 EXPECT_EQ(StatusCode::CANCELLED, rpc.GetStatus().error_code());
818 hold->Resume();
819 // Wait for channel to become connected without any pending RPC.
820 EXPECT_TRUE(channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(5)));
821 // Make sure the backend did not get any requests.
822 EXPECT_EQ(0UL, backends_[0]->backend_service()->request_count());
823 }
824
825 // Tests that when we trigger internal connection attempts without
826 // picks, we do so for only one subchannel at a time.
827 TEST_P(RingHashTest, ContinuesConnectingWithoutPicksOneSubchannelAtATime) {
828 // Create EDS resource.
829 CreateAndStartBackends(1);
830 auto non_existant_endpoint0 = MakeNonExistantEndpoint();
831 auto non_existant_endpoint1 = MakeNonExistantEndpoint();
832 auto non_existant_endpoint2 = MakeNonExistantEndpoint();
833 EdsResourceArgs args({{"locality0",
834 {non_existant_endpoint0, non_existant_endpoint1,
835 non_existant_endpoint2, CreateEndpoint(0)}}});
836 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
837 // Change CDS resource to use RING_HASH.
838 auto cluster = default_cluster_;
839 cluster.set_lb_policy(Cluster::RING_HASH);
840 balancer_->ads_service()->SetCdsResource(cluster);
841 // Add hash policy to RDS resource.
842 auto new_route_config = default_route_config_;
843 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
844 auto* hash_policy = route->mutable_route()->add_hash_policy();
845 hash_policy->mutable_header()->set_header_name("address_hash");
846 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
847 new_route_config);
848 // Start connection attempt injector.
849 ConnectionAttemptInjector injector;
850 auto hold_non_existant0 = injector.AddHold(non_existant_endpoint0.port);
851 auto hold_non_existant1 = injector.AddHold(non_existant_endpoint1.port);
852 auto hold_non_existant2 = injector.AddHold(non_existant_endpoint2.port);
853 auto hold_good = injector.AddHold(backends_[0]->port());
854 // A long-running RPC, just used to send the RPC in another thread.
855 LongRunningRpc rpc;
856 std::vector<std::pair<std::string, std::string>> metadata = {
857 {"address_hash", CreateMetadataValueThatHashesToBackendPort(
858 non_existant_endpoint0.port)}};
859 rpc.StartRpc(stub_.get(), RpcOptions().set_timeout_ms(0).set_metadata(
860 std::move(metadata)));
861 // Wait for the RPC to trigger a connection attempt to the first address,
862 // then cancel the RPC. No other connection attempts should be started yet.
863 hold_non_existant0->Wait();
864 rpc.CancelRpc();
865 EXPECT_FALSE(hold_non_existant1->IsStarted());
866 EXPECT_FALSE(hold_non_existant2->IsStarted());
867 EXPECT_FALSE(hold_good->IsStarted());
868 // Allow the connection attempt to the first address to resume and wait
869 // for the attempt for the second address. No other connection
870 // attempts should be started yet.
871 auto hold_non_existant0_again = injector.AddHold(non_existant_endpoint0.port);
872 hold_non_existant0->Resume();
873 hold_non_existant1->Wait();
874 EXPECT_FALSE(hold_non_existant0_again->IsStarted());
875 EXPECT_FALSE(hold_non_existant2->IsStarted());
876 EXPECT_FALSE(hold_good->IsStarted());
877 // Allow the connection attempt to the second address to resume and wait
878 // for the attempt for the third address. No other connection
879 // attempts should be started yet.
880 auto hold_non_existant1_again = injector.AddHold(non_existant_endpoint1.port);
881 hold_non_existant1->Resume();
882 hold_non_existant2->Wait();
883 EXPECT_FALSE(hold_non_existant0_again->IsStarted());
884 EXPECT_FALSE(hold_non_existant1_again->IsStarted());
885 EXPECT_FALSE(hold_good->IsStarted());
886 // Allow the connection attempt to the third address to resume and wait
887 // for the attempt for the final address. No other connection
888 // attempts should be started yet.
889 auto hold_non_existant2_again = injector.AddHold(non_existant_endpoint2.port);
890 hold_non_existant2->Resume();
891 hold_good->Wait();
892 EXPECT_FALSE(hold_non_existant0_again->IsStarted());
893 EXPECT_FALSE(hold_non_existant1_again->IsStarted());
894 EXPECT_FALSE(hold_non_existant2_again->IsStarted());
895 // Allow the final attempt to resume.
896 hold_good->Resume();
897 // Wait for channel to become connected without any pending RPC.
898 EXPECT_TRUE(channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(10)));
899 // No other connection attempts should have been started.
900 EXPECT_FALSE(hold_non_existant0_again->IsStarted());
901 EXPECT_FALSE(hold_non_existant1_again->IsStarted());
902 EXPECT_FALSE(hold_non_existant2_again->IsStarted());
903 // RPC should have been cancelled.
904 EXPECT_EQ(StatusCode::CANCELLED, rpc.GetStatus().error_code());
905 // Make sure the backend did not get any requests.
906 EXPECT_EQ(0UL, backends_[0]->backend_service()->request_count());
907 }
908
909 // Test that when the first pick is down leading to a transient failure, we
910 // will move on to the next ring hash entry.
911 TEST_P(RingHashTest, TransientFailureCheckNextOne) {
912 CreateAndStartBackends(1);
913 auto cluster = default_cluster_;
914 cluster.set_lb_policy(Cluster::RING_HASH);
915 balancer_->ads_service()->SetCdsResource(cluster);
916 auto new_route_config = default_route_config_;
917 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
918 auto* hash_policy = route->mutable_route()->add_hash_policy();
919 hash_policy->mutable_header()->set_header_name("address_hash");
920 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
921 new_route_config);
922 std::vector<EdsResourceArgs::Endpoint> endpoints;
923 const int unused_port = grpc_pick_unused_port_or_die();
924 endpoints.emplace_back(unused_port);
925 endpoints.emplace_back(backends_[0]->port());
926 EdsResourceArgs args({{"locality0", std::move(endpoints)}});
927 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
928 std::vector<std::pair<std::string, std::string>> metadata = {
929 {"address_hash",
930 CreateMetadataValueThatHashesToBackendPort(unused_port)}};
931 const auto rpc_options =
932 RpcOptions().set_metadata(std::move(metadata)).set_timeout_ms(5000);
933 WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
934 WaitForBackendOptions(), rpc_options);
935 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
936 }
937
938 // Test that when a backend goes down, we will move on to the next subchannel
939 // (with a lower priority). When the backend comes back up, traffic will move
940 // back.
941 TEST_P(RingHashTest, SwitchToLowerPrioirtyAndThenBack) {
942 CreateAndStartBackends(2);
943 auto cluster = default_cluster_;
944 cluster.set_lb_policy(Cluster::RING_HASH);
945 balancer_->ads_service()->SetCdsResource(cluster);
946 auto new_route_config = default_route_config_;
947 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
948 auto* hash_policy = route->mutable_route()->add_hash_policy();
949 hash_policy->mutable_header()->set_header_name("address_hash");
950 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
951 new_route_config);
952 EdsResourceArgs args({
953 {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
954 0},
955 {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
956 1},
957 });
958 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
959 std::vector<std::pair<std::string, std::string>> metadata = {
960 {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
961 const auto rpc_options =
962 RpcOptions().set_metadata(std::move(metadata)).set_timeout_ms(5000);
963 WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
964 WaitForBackendOptions(), rpc_options);
965 backends_[0]->StopListeningAndSendGoaways();
966 WaitForBackend(DEBUG_LOCATION, 1, /*check_status=*/nullptr,
967 WaitForBackendOptions(), rpc_options);
968 ShutdownBackend(0);
969 StartBackend(0);
970 WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
971 WaitForBackendOptions(), rpc_options);
972 CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
973 EXPECT_EQ(100, backends_[0]->backend_service()->request_count());
974 EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
975 }
976
977 // Test that when all backends are down, we will keep reattempting.
978 TEST_P(RingHashTest, ReattemptWhenAllEndpointsUnreachable) {
979 CreateAndStartBackends(1);
980 const uint32_t kConnectionTimeoutMilliseconds = 5000;
981 auto cluster = default_cluster_;
982 cluster.set_lb_policy(Cluster::RING_HASH);
983 balancer_->ads_service()->SetCdsResource(cluster);
984 auto new_route_config = default_route_config_;
985 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
986 auto* hash_policy = route->mutable_route()->add_hash_policy();
987 hash_policy->mutable_header()->set_header_name("address_hash");
988 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
989 new_route_config);
990 EdsResourceArgs args(
991 {{"locality0", {MakeNonExistantEndpoint(), CreateEndpoint(0)}}});
992 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
993 std::vector<std::pair<std::string, std::string>> metadata = {
994 {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
995 EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
996 ShutdownBackend(0);
997 CheckRpcSendFailure(
998 DEBUG_LOCATION, StatusCode::UNAVAILABLE,
999 "ring hash cannot find a connected subchannel; first failure: "
1000 "(UNKNOWN: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
1001 "Failed to connect to remote host: Connection refused|"
1002 "UNAVAILABLE: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
1003 "Failed to connect to remote host: FD shutdown)",
1004 RpcOptions().set_metadata(std::move(metadata)));
1005 StartBackend(0);
1006 // Ensure we are actively connecting without any traffic.
1007 EXPECT_TRUE(channel_->WaitForConnected(
1008 grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
1009 }
1010
1011 // Test that when all backends are down and then up, we may pick a TF backend
1012 // and we will then jump to ready backend.
1013 TEST_P(RingHashTest, TransientFailureSkipToAvailableReady) {
1014 CreateBackends(2);
1015 const uint32_t kConnectionTimeoutMilliseconds = 5000;
1016 auto cluster = default_cluster_;
1017 cluster.set_lb_policy(Cluster::RING_HASH);
1018 balancer_->ads_service()->SetCdsResource(cluster);
1019 auto new_route_config = default_route_config_;
1020 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
1021 auto* hash_policy = route->mutable_route()->add_hash_policy();
1022 hash_policy->mutable_header()->set_header_name("address_hash");
1023 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
1024 new_route_config);
1025 // Make sure we include some unused ports to fill the ring.
1026 EdsResourceArgs args({
1027 {"locality0",
1028 {CreateEndpoint(0), CreateEndpoint(1), MakeNonExistantEndpoint(),
1029 MakeNonExistantEndpoint()}},
1030 });
1031 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
1032 std::vector<std::pair<std::string, std::string>> metadata = {
1033 {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
1034 const auto rpc_options = RpcOptions()
1035 .set_metadata(std::move(metadata))
1036 .set_timeout_ms(kConnectionTimeoutMilliseconds);
1037 EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
1038 gpr_log(GPR_INFO, "=== SENDING FIRST RPC ===");
1039 CheckRpcSendFailure(
1040 DEBUG_LOCATION, StatusCode::UNAVAILABLE,
1041 "ring hash cannot find a connected subchannel; first failure: "
1042 "(UNKNOWN: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
1043 "Failed to connect to remote host: Connection refused|"
1044 "UNAVAILABLE: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
1045 "Failed to connect to remote host: FD shutdown)",
1046 rpc_options);
1047 gpr_log(GPR_INFO, "=== DONE WITH FIRST RPC ===");
1048 EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel_->GetState(false));
1049 // Bring up backend 0. The channel should become connected without
1050 // any picks, because in TF, we are always trying to connect to at
1051 // least one backend at all times.
1052 gpr_log(GPR_INFO, "=== STARTING BACKEND 0 ===");
1053 StartBackend(0);
1054 gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL TO BECOME READY ===");
1055 EXPECT_TRUE(channel_->WaitForConnected(
1056 grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
1057 // RPCs should go to backend 0.
1058 gpr_log(GPR_INFO, "=== WAITING FOR BACKEND 0 ===");
1059 WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
1060 WaitForBackendOptions(), rpc_options);
1061 EXPECT_EQ(GRPC_CHANNEL_READY, channel_->GetState(false));
1062 // Bring down backend 0 and bring up backend 1.
1063 // Note the RPC contains a header value that will always be hashed to
1064 // backend 0. So by purposely bringing down backend 0 and bringing up another
1065 // backend, this will ensure Picker's first choice of backend 0 will fail
1066 // and it will go through the remaining subchannels to find one in READY.
1067 // Since the the entries in the ring are pretty distributed and we have
1068 // unused ports to fill the ring, it is almost guaranteed that the Picker
1069 // will go through some non-READY entries and skip them as per design.
1070 gpr_log(GPR_INFO, "=== SHUTTING DOWN BACKEND 0 ===");
1071 ShutdownBackend(0);
1072 gpr_log(GPR_INFO, "=== WAITING FOR STATE CHANGE ===");
1073 EXPECT_TRUE(channel_->WaitForStateChange(
1074 GRPC_CHANNEL_READY,
1075 grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
1076 EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel_->GetState(false));
1077 gpr_log(GPR_INFO, "=== SENDING SECOND RPC ===");
1078 CheckRpcSendFailure(
1079 DEBUG_LOCATION, StatusCode::UNAVAILABLE,
1080 "ring hash cannot find a connected subchannel; first failure: "
1081 "(UNKNOWN: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
1082 "Failed to connect to remote host: Connection refused|"
1083 "UNAVAILABLE: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
1084 "Failed to connect to remote host: FD shutdown)",
1085 rpc_options);
1086 gpr_log(GPR_INFO, "=== STARTING BACKEND 1 ===");
1087 StartBackend(1);
1088 gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL TO BECOME READY ===");
1089 EXPECT_TRUE(channel_->WaitForConnected(
1090 grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
1091 gpr_log(GPR_INFO, "=== WAITING FOR BACKEND 1 ===");
1092 WaitForBackend(DEBUG_LOCATION, 1, /*check_status=*/nullptr,
1093 WaitForBackendOptions(), rpc_options);
1094 gpr_log(GPR_INFO, "=== DONE ===");
1095 }
1096
1097 // This tests a bug seen in the wild where ring_hash started with no
1098 // endpoints and reported TRANSIENT_FAILURE, then got an update with
1099 // endpoints and reported IDLE, but the picker update was squelched, so
1100 // it failed to ever get reconnected.
1101 TEST_P(RingHashTest, ReattemptWhenGoingFromTransientFailureToIdle) {
1102 CreateAndStartBackends(1);
1103 const uint32_t kConnectionTimeoutMilliseconds = 5000;
1104 auto cluster = default_cluster_;
1105 cluster.set_lb_policy(Cluster::RING_HASH);
1106 balancer_->ads_service()->SetCdsResource(cluster);
1107 auto new_route_config = default_route_config_;
1108 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
1109 new_route_config);
1110 // Send empty EDS update.
1111 EdsResourceArgs args(
1112 {{"locality0", std::vector<EdsResourceArgs::Endpoint>()}});
1113 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
1114 EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
1115 // Channel should fail RPCs and go into TRANSIENT_FAILURE.
1116 CheckRpcSendFailure(
1117 DEBUG_LOCATION, StatusCode::UNAVAILABLE,
1118 "empty address list: EDS resource eds_service_name contains empty "
1119 "localities: \\[\\{region=\"xds_default_locality_region\", "
1120 "zone=\"xds_default_locality_zone\", sub_zone=\"locality0\"\\}\\]",
1121 RpcOptions().set_timeout_ms(kConnectionTimeoutMilliseconds));
1122 EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel_->GetState(false));
1123 // Send EDS update with 1 backend.
1124 args = EdsResourceArgs({{"locality0", CreateEndpointsForBackends()}});
1125 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
1126 // A wait_for_ready RPC should succeed, and the channel should report READY.
1127 CheckRpcSendOk(DEBUG_LOCATION, 1,
1128 RpcOptions()
1129 .set_timeout_ms(kConnectionTimeoutMilliseconds)
1130 .set_wait_for_ready(true));
1131 EXPECT_EQ(GRPC_CHANNEL_READY, channel_->GetState(false));
1132 }
1133
1134 // Test unspported hash policy types are all ignored before a supported
1135 // policy.
1136 TEST_P(RingHashTest, UnsupportedHashPolicyUntilChannelIdHashing) {
1137 CreateAndStartBackends(2);
1138 auto cluster = default_cluster_;
1139 cluster.set_lb_policy(Cluster::RING_HASH);
1140 balancer_->ads_service()->SetCdsResource(cluster);
1141 auto new_route_config = default_route_config_;
1142 auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
1143 auto* hash_policy_unsupported_1 = route->mutable_route()->add_hash_policy();
1144 hash_policy_unsupported_1->mutable_cookie()->set_name("cookie");
1145 auto* hash_policy_unsupported_2 = route->mutable_route()->add_hash_policy();
1146 hash_policy_unsupported_2->mutable_connection_properties()->set_source_ip(
1147 true);
1148 auto* hash_policy_unsupported_3 = route->mutable_route()->add_hash_policy();
1149 hash_policy_unsupported_3->mutable_query_parameter()->set_name(
1150 "query_parameter");
1151 auto* hash_policy = route->mutable_route()->add_hash_policy();
1152 hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
1153 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
1154 new_route_config);
1155 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
1156 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
1157 CheckRpcSendOk(DEBUG_LOCATION, 100, RpcOptions().set_timeout_ms(5000));
1158 bool found = false;
1159 for (size_t i = 0; i < backends_.size(); ++i) {
1160 if (backends_[i]->backend_service()->request_count() > 0) {
1161 EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
1162 << "backend " << i;
1163 EXPECT_FALSE(found) << "backend " << i;
1164 found = true;
1165 }
1166 }
1167 EXPECT_TRUE(found);
1168 }
1169
1170 } // namespace
1171 } // namespace testing
1172 } // namespace grpc
1173
1174 int main(int argc, char** argv) {
1175 grpc::testing::TestEnvironment env(&argc, argv);
1176 ::testing::InitGoogleTest(&argc, argv);
1177 // Make the backup poller poll very frequently in order to pick up
1178 // updates from all the subchannels's FDs.
1179 GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
1180 #if TARGET_OS_IPHONE
1181 // Workaround Apple CFStream bug
1182 grpc_core::SetEnv("grpc_cfstream", "0");
1183 #endif
1184 grpc_init();
1185 grpc::testing::ConnectionAttemptInjector::Init();
1186 const auto result = RUN_ALL_TESTS();
1187 grpc_shutdown();
1188 return result;
1189 }