Debian Codegraph @

test/cpp/end2end/client_lb_end2end_test.cc

raw
1 // Copyright 2016 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 #include <algorithm>
16 #include <deque>
17 #include <memory>
18 #include <mutex>
19 #include <random>
20 #include <set>
21 #include <string>
22 #include <thread>
23
24 #include <gmock/gmock.h>
25 #include <gtest/gtest.h>
26
27 #include "absl/memory/memory.h"
28 #include "absl/strings/str_cat.h"
29 #include "absl/strings/str_format.h"
30 #include "absl/strings/str_join.h"
31 #include "absl/strings/string_view.h"
32
33 #include <grpc/event_engine/endpoint_config.h>
34 #include <grpc/grpc.h>
35 #include <grpc/support/alloc.h>
36 #include <grpc/support/atm.h>
37 #include <grpc/support/log.h>
38 #include <grpc/support/time.h>
39 #include <grpcpp/channel.h>
40 #include <grpcpp/client_context.h>
41 #include <grpcpp/create_channel.h>
42 #include <grpcpp/ext/call_metric_recorder.h>
43 #include <grpcpp/ext/orca_service.h>
44 #include <grpcpp/health_check_service_interface.h>
45 #include <grpcpp/impl/codegen/sync.h>
46 #include <grpcpp/server.h>
47 #include <grpcpp/server_builder.h>
48
49 #include "src/core/ext/filters/client_channel/backup_poller.h"
50 #include "src/core/ext/filters/client_channel/config_selector.h"
51 #include "src/core/ext/filters/client_channel/global_subchannel_pool.h"
52 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
53 #include "src/core/lib/address_utils/parse_address.h"
54 #include "src/core/lib/address_utils/sockaddr_utils.h"
55 #include "src/core/lib/backoff/backoff.h"
56 #include "src/core/lib/channel/channel_args.h"
57 #include "src/core/lib/gprpp/debug_location.h"
58 #include "src/core/lib/gprpp/env.h"
59 #include "src/core/lib/gprpp/ref_counted_ptr.h"
60 #include "src/core/lib/gprpp/time.h"
61 #include "src/core/lib/iomgr/tcp_client.h"
62 #include "src/core/lib/resolver/server_address.h"
63 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
64 #include "src/core/lib/service_config/service_config.h"
65 #include "src/core/lib/service_config/service_config_impl.h"
66 #include "src/core/lib/surface/server.h"
67 #include "src/core/lib/transport/connectivity_state.h"
68 #include "src/cpp/client/secure_credentials.h"
69 #include "src/cpp/server/secure_server_credentials.h"
70 #include "src/proto/grpc/testing/echo.grpc.pb.h"
71 #include "src/proto/grpc/testing/xds/v3/orca_load_report.pb.h"
72 #include "test/core/util/port.h"
73 #include "test/core/util/resolve_localhost_ip46.h"
74 #include "test/core/util/test_config.h"
75 #include "test/core/util/test_lb_policies.h"
76 #include "test/cpp/end2end/connection_attempt_injector.h"
77 #include "test/cpp/end2end/test_service_impl.h"
78
79 namespace grpc {
80 namespace testing {
81 namespace {
82
83 constexpr char kRequestMessage[] = "Live long and prosper.";
84
85 // Subclass of TestServiceImpl that increments a request counter for
86 // every call to the Echo RPC.
87 class MyTestServiceImpl : public TestServiceImpl {
88 public:
89 Status Echo(ServerContext* context, const EchoRequest* request,
90 EchoResponse* response) override {
91 {
92 grpc_core::MutexLock lock(&mu_);
93 ++request_count_;
94 }
95 AddClient(context->peer());
96 if (request->has_param() && request->param().has_backend_metrics()) {
97 load_report_ = request->param().backend_metrics();
98 auto* recorder = context->ExperimentalGetCallMetricRecorder();
99 EXPECT_NE(recorder, nullptr);
100 recorder->RecordCpuUtilizationMetric(load_report_.cpu_utilization())
101 .RecordMemoryUtilizationMetric(load_report_.mem_utilization());
102 for (const auto& p : load_report_.request_cost()) {
103 recorder->RecordRequestCostMetric(p.first, p.second);
104 }
105 for (const auto& p : load_report_.utilization()) {
106 recorder->RecordUtilizationMetric(p.first, p.second);
107 }
108 }
109 return TestServiceImpl::Echo(context, request, response);
110 }
111
112 int request_count() {
113 grpc_core::MutexLock lock(&mu_);
114 return request_count_;
115 }
116
117 void ResetCounters() {
118 grpc_core::MutexLock lock(&mu_);
119 request_count_ = 0;
120 }
121
122 std::set<std::string> clients() {
123 grpc_core::MutexLock lock(&clients_mu_);
124 return clients_;
125 }
126
127 private:
128 void AddClient(const std::string& client) {
129 grpc_core::MutexLock lock(&clients_mu_);
130 clients_.insert(client);
131 }
132
133 grpc_core::Mutex mu_;
134 int request_count_ = 0;
135 grpc_core::Mutex clients_mu_;
136 std::set<std::string> clients_;
137 // For strings storage.
138 xds::data::orca::v3::OrcaLoadReport load_report_;
139 };
140
141 class FakeResolverResponseGeneratorWrapper {
142 public:
143 explicit FakeResolverResponseGeneratorWrapper(bool ipv6_only)
144 : ipv6_only_(ipv6_only),
145 response_generator_(grpc_core::MakeRefCounted<
146 grpc_core::FakeResolverResponseGenerator>()) {}
147
148 FakeResolverResponseGeneratorWrapper(
149 FakeResolverResponseGeneratorWrapper&& other) noexcept {
150 ipv6_only_ = other.ipv6_only_;
151 response_generator_ = std::move(other.response_generator_);
152 }
153
154 void SetNextResolution(
155 const std::vector<int>& ports, const char* service_config_json = nullptr,
156 const char* attribute_key = nullptr,
157 std::unique_ptr<grpc_core::ServerAddress::AttributeInterface> attribute =
158 nullptr,
159 const grpc_core::ChannelArgs& per_address_args =
160 grpc_core::ChannelArgs()) {
161 grpc_core::ExecCtx exec_ctx;
162 response_generator_->SetResponse(
163 BuildFakeResults(ipv6_only_, ports, service_config_json, attribute_key,
164 std::move(attribute), per_address_args));
165 }
166
167 void SetNextResolutionUponError(const std::vector<int>& ports) {
168 grpc_core::ExecCtx exec_ctx;
169 response_generator_->SetReresolutionResponse(
170 BuildFakeResults(ipv6_only_, ports));
171 }
172
173 void SetFailureOnReresolution() {
174 grpc_core::ExecCtx exec_ctx;
175 response_generator_->SetFailureOnReresolution();
176 }
177
178 void SetResponse(grpc_core::Resolver::Result result) {
179 grpc_core::ExecCtx exec_ctx;
180 response_generator_->SetResponse(std::move(result));
181 }
182
183 grpc_core::FakeResolverResponseGenerator* Get() const {
184 return response_generator_.get();
185 }
186
187 private:
188 static grpc_core::Resolver::Result BuildFakeResults(
189 bool ipv6_only, const std::vector<int>& ports,
190 const char* service_config_json = nullptr,
191 const char* attribute_key = nullptr,
192 std::unique_ptr<grpc_core::ServerAddress::AttributeInterface> attribute =
193 nullptr,
194 const grpc_core::ChannelArgs& per_address_args =
195 grpc_core::ChannelArgs()) {
196 grpc_core::Resolver::Result result;
197 result.addresses = grpc_core::ServerAddressList();
198 for (const int& port : ports) {
199 absl::StatusOr<grpc_core::URI> lb_uri = grpc_core::URI::Parse(
200 absl::StrCat(ipv6_only ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", port));
201 GPR_ASSERT(lb_uri.ok());
202 grpc_resolved_address address;
203 GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
204 std::map<const char*,
205 std::unique_ptr<grpc_core::ServerAddress::AttributeInterface>>
206 attributes;
207 if (attribute != nullptr) {
208 attributes[attribute_key] = attribute->Copy();
209 }
210 result.addresses->emplace_back(address.addr, address.len,
211 per_address_args, std::move(attributes));
212 }
213 if (result.addresses->empty()) {
214 result.resolution_note = "fake resolver empty address list";
215 }
216 if (service_config_json != nullptr) {
217 result.service_config = grpc_core::ServiceConfigImpl::Create(
218 grpc_core::ChannelArgs(), service_config_json);
219 GPR_ASSERT(result.service_config.ok());
220 }
221 return result;
222 }
223
224 bool ipv6_only_ = false;
225 grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
226 response_generator_;
227 };
228
229 class ClientLbEnd2endTest : public ::testing::Test {
230 protected:
231 ClientLbEnd2endTest()
232 : server_host_("localhost"),
233 creds_(new SecureChannelCredentials(
234 grpc_fake_transport_security_credentials_create())) {}
235
236 static void SetUpTestCase() {
237 // Make the backup poller poll very frequently in order to pick up
238 // updates from all the subchannels's FDs.
239 GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
240 #if TARGET_OS_IPHONE
241 // Workaround Apple CFStream bug
242 grpc_core::SetEnv("grpc_cfstream", "0");
243 #endif
244 }
245
246 void SetUp() override {
247 grpc_init();
248 bool localhost_resolves_to_ipv4 = false;
249 bool localhost_resolves_to_ipv6 = false;
250 grpc_core::LocalhostResolves(&localhost_resolves_to_ipv4,
251 &localhost_resolves_to_ipv6);
252 ipv6_only_ = !localhost_resolves_to_ipv4 && localhost_resolves_to_ipv6;
253 }
254
255 void TearDown() override {
256 for (size_t i = 0; i < servers_.size(); ++i) {
257 servers_[i]->Shutdown();
258 }
259 servers_.clear();
260 creds_.reset();
261 grpc_shutdown();
262 }
263
264 void CreateServers(size_t num_servers,
265 std::vector<int> ports = std::vector<int>()) {
266 servers_.clear();
267 for (size_t i = 0; i < num_servers; ++i) {
268 int port = 0;
269 if (ports.size() == num_servers) port = ports[i];
270 servers_.emplace_back(new ServerData(port));
271 }
272 }
273
274 void StartServer(size_t index) { servers_[index]->Start(server_host_); }
275
276 void StartServers(size_t num_servers,
277 std::vector<int> ports = std::vector<int>()) {
278 CreateServers(num_servers, std::move(ports));
279 for (size_t i = 0; i < num_servers; ++i) {
280 StartServer(i);
281 }
282 }
283
284 std::vector<int> GetServersPorts(size_t start_index = 0,
285 size_t stop_index = 0) {
286 if (stop_index == 0) stop_index = servers_.size();
287 std::vector<int> ports;
288 for (size_t i = start_index; i < stop_index; ++i) {
289 ports.push_back(servers_[i]->port_);
290 }
291 return ports;
292 }
293
294 FakeResolverResponseGeneratorWrapper BuildResolverResponseGenerator() {
295 return FakeResolverResponseGeneratorWrapper(ipv6_only_);
296 }
297
298 std::unique_ptr<grpc::testing::EchoTestService::Stub> BuildStub(
299 const std::shared_ptr<Channel>& channel) {
300 return grpc::testing::EchoTestService::NewStub(channel);
301 }
302
303 std::shared_ptr<Channel> BuildChannel(
304 const std::string& lb_policy_name,
305 const FakeResolverResponseGeneratorWrapper& response_generator,
306 ChannelArguments args = ChannelArguments()) {
307 if (!lb_policy_name.empty()) {
308 args.SetLoadBalancingPolicyName(lb_policy_name);
309 } // else, default to pick first
310 args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
311 response_generator.Get());
312 return grpc::CreateCustomChannel("fake:default.example.com", creds_, args);
313 }
314
315 Status SendRpc(
316 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
317 EchoResponse* response = nullptr, int timeout_ms = 1000,
318 bool wait_for_ready = false, EchoRequest* request = nullptr) {
319 EchoResponse local_response;
320 if (response == nullptr) response = &local_response;
321 EchoRequest local_request;
322 if (request == nullptr) request = &local_request;
323 request->set_message(kRequestMessage);
324 request->mutable_param()->set_echo_metadata(true);
325 ClientContext context;
326 context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
327 if (wait_for_ready) context.set_wait_for_ready(true);
328 context.AddMetadata("foo", "1");
329 context.AddMetadata("bar", "2");
330 context.AddMetadata("baz", "3");
331 return stub->Echo(&context, *request, response);
332 }
333
334 void CheckRpcSendOk(
335 const grpc_core::DebugLocation& location,
336 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
337 bool wait_for_ready = false,
338 xds::data::orca::v3::OrcaLoadReport* load_report = nullptr,
339 int timeout_ms = 2000) {
340 EchoResponse response;
341 EchoRequest request;
342 EchoRequest* request_ptr = nullptr;
343 if (load_report != nullptr) {
344 request_ptr = &request;
345 auto params = request.mutable_param();
346 auto backend_metrics = params->mutable_backend_metrics();
347 *backend_metrics = *load_report;
348 }
349 Status status =
350 SendRpc(stub, &response, timeout_ms, wait_for_ready, request_ptr);
351 ASSERT_TRUE(status.ok())
352 << "From " << location.file() << ":" << location.line()
353 << "\nError: " << status.error_message() << " "
354 << status.error_details();
355 ASSERT_EQ(response.message(), kRequestMessage)
356 << "From " << location.file() << ":" << location.line();
357 }
358
359 void CheckRpcSendFailure(
360 const grpc_core::DebugLocation& location,
361 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
362 StatusCode expected_status, absl::string_view expected_message_regex) {
363 Status status = SendRpc(stub);
364 EXPECT_FALSE(status.ok());
365 EXPECT_EQ(expected_status, status.error_code())
366 << location.file() << ":" << location.line();
367 EXPECT_THAT(status.error_message(),
368 ::testing::MatchesRegex(expected_message_regex))
369 << location.file() << ":" << location.line();
370 }
371
372 void SendRpcsUntil(
373 const grpc_core::DebugLocation& debug_location,
374 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
375 std::function<bool(const Status&)> continue_predicate,
376 int timeout_ms = 15000) {
377 absl::Time deadline = absl::InfiniteFuture();
378 if (timeout_ms != 0) {
379 deadline = absl::Now() +
380 (absl::Milliseconds(timeout_ms) * grpc_test_slowdown_factor());
381 }
382 while (true) {
383 Status status = SendRpc(stub);
384 if (!continue_predicate(status)) return;
385 EXPECT_LE(absl::Now(), deadline)
386 << debug_location.file() << ":" << debug_location.line();
387 if (absl::Now() >= deadline) break;
388 }
389 }
390
391 struct ServerData {
392 const int port_;
393 std::unique_ptr<Server> server_;
394 MyTestServiceImpl service_;
395 experimental::OrcaService orca_service_;
396 std::unique_ptr<std::thread> thread_;
397
398 grpc_core::Mutex mu_;
399 grpc_core::CondVar cond_;
400 bool server_ready_ ABSL_GUARDED_BY(mu_) = false;
401 bool started_ ABSL_GUARDED_BY(mu_) = false;
402
403 explicit ServerData(int port = 0)
404 : port_(port > 0 ? port : grpc_pick_unused_port_or_die()),
405 orca_service_(experimental::OrcaService::Options()) {}
406
407 void Start(const std::string& server_host) {
408 gpr_log(GPR_INFO, "starting server on port %d", port_);
409 grpc_core::MutexLock lock(&mu_);
410 started_ = true;
411 thread_ = std::make_unique<std::thread>(
412 std::bind(&ServerData::Serve, this, server_host));
413 while (!server_ready_) {
414 cond_.Wait(&mu_);
415 }
416 server_ready_ = false;
417 gpr_log(GPR_INFO, "server startup complete");
418 }
419
420 void Serve(const std::string& server_host) {
421 std::ostringstream server_address;
422 server_address << server_host << ":" << port_;
423 ServerBuilder builder;
424 experimental::EnableCallMetricRecording(&builder);
425 std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
426 grpc_fake_transport_security_server_credentials_create()));
427 builder.AddListeningPort(server_address.str(), std::move(creds));
428 builder.RegisterService(&service_);
429 builder.RegisterService(&orca_service_);
430 server_ = builder.BuildAndStart();
431 grpc_core::MutexLock lock(&mu_);
432 server_ready_ = true;
433 cond_.Signal();
434 }
435
436 void Shutdown() {
437 grpc_core::MutexLock lock(&mu_);
438 if (!started_) return;
439 server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
440 thread_->join();
441 started_ = false;
442 }
443
444 void StopListeningAndSendGoaways() {
445 grpc_core::ExecCtx exec_ctx;
446 auto* server = grpc_core::Server::FromC(server_->c_server());
447 server->StopListening();
448 server->SendGoaways();
449 }
450
451 void SetServingStatus(const std::string& service, bool serving) {
452 server_->GetHealthCheckService()->SetServingStatus(service, serving);
453 }
454 };
455
456 void ResetCounters() {
457 for (const auto& server : servers_) server->service_.ResetCounters();
458 }
459
460 bool SeenAllServers(size_t start_index = 0, size_t stop_index = 0) {
461 if (stop_index == 0) stop_index = servers_.size();
462 for (size_t i = start_index; i < stop_index; ++i) {
463 if (servers_[i]->service_.request_count() == 0) return false;
464 }
465 return true;
466 }
467
468 // If status_check is null, all RPCs must succeed.
469 // If status_check is non-null, it will be called for all non-OK RPCs.
470 void WaitForServers(
471 const grpc_core::DebugLocation& location,
472 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
473 size_t start_index = 0, size_t stop_index = 0,
474 std::function<void(const Status&)> status_check = nullptr,
475 absl::Duration timeout = absl::Seconds(30)) {
476 if (stop_index == 0) stop_index = servers_.size();
477 auto deadline = absl::Now() + (timeout * grpc_test_slowdown_factor());
478 gpr_log(GPR_INFO,
479 "========= WAITING FOR BACKENDS [%" PRIuPTR ", %" PRIuPTR
480 ") ==========",
481 start_index, stop_index);
482 while (!SeenAllServers(start_index, stop_index)) {
483 Status status = SendRpc(stub);
484 if (status_check != nullptr) {
485 if (!status.ok()) status_check(status);
486 } else {
487 EXPECT_TRUE(status.ok())
488 << " code=" << status.error_code() << " message=\""
489 << status.error_message() << "\" at " << location.file() << ":"
490 << location.line();
491 }
492 EXPECT_LE(absl::Now(), deadline)
493 << " at " << location.file() << ":" << location.line();
494 if (absl::Now() >= deadline) break;
495 }
496 ResetCounters();
497 }
498
499 void WaitForServer(
500 const grpc_core::DebugLocation& location,
501 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
502 size_t server_index,
503 std::function<void(const Status&)> status_check = nullptr) {
504 WaitForServers(location, stub, server_index, server_index + 1,
505 status_check);
506 }
507
508 bool WaitForChannelState(
509 Channel* channel,
510 const std::function<bool(grpc_connectivity_state)>& predicate,
511 bool try_to_connect = false, int timeout_seconds = 5) {
512 const gpr_timespec deadline =
513 grpc_timeout_seconds_to_deadline(timeout_seconds);
514 while (true) {
515 grpc_connectivity_state state = channel->GetState(try_to_connect);
516 if (predicate(state)) break;
517 if (!channel->WaitForStateChange(state, deadline)) return false;
518 }
519 return true;
520 }
521
522 bool WaitForChannelNotReady(Channel* channel, int timeout_seconds = 5) {
523 auto predicate = [](grpc_connectivity_state state) {
524 return state != GRPC_CHANNEL_READY;
525 };
526 return WaitForChannelState(channel, predicate, false, timeout_seconds);
527 }
528
529 bool WaitForChannelReady(Channel* channel, int timeout_seconds = 5) {
530 auto predicate = [](grpc_connectivity_state state) {
531 return state == GRPC_CHANNEL_READY;
532 };
533 return WaitForChannelState(channel, predicate, true, timeout_seconds);
534 }
535
536 // Updates \a connection_order by appending to it the index of the newly
537 // connected server. Must be called after every single RPC.
538 void UpdateConnectionOrder(
539 const std::vector<std::unique_ptr<ServerData>>& servers,
540 std::vector<int>* connection_order) {
541 for (size_t i = 0; i < servers.size(); ++i) {
542 if (servers[i]->service_.request_count() == 1) {
543 // Was the server index known? If not, update connection_order.
544 const auto it =
545 std::find(connection_order->begin(), connection_order->end(), i);
546 if (it == connection_order->end()) {
547 connection_order->push_back(i);
548 return;
549 }
550 }
551 }
552 }
553
554 static std::string MakeConnectionFailureRegex(absl::string_view prefix) {
555 return absl::StrCat(
556 prefix,
557 "; last error: (UNKNOWN: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
558 "Failed to connect to remote host: Connection refused|"
559 "UNAVAILABLE: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
560 "Failed to connect to remote host: FD shutdown|"
561 "UNAVAILABLE: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
562 "(Socket closed|Connection reset by peer))");
563 }
564
565 const std::string server_host_;
566 std::vector<std::unique_ptr<ServerData>> servers_;
567 std::shared_ptr<ChannelCredentials> creds_;
568 bool ipv6_only_ = false;
569 };
570
571 TEST_F(ClientLbEnd2endTest, ChannelStateConnectingWhenResolving) {
572 const int kNumServers = 3;
573 StartServers(kNumServers);
574 auto response_generator = BuildResolverResponseGenerator();
575 auto channel = BuildChannel("", response_generator);
576 auto stub = BuildStub(channel);
577 // Initial state should be IDLE.
578 EXPECT_EQ(channel->GetState(false /* try_to_connect */), GRPC_CHANNEL_IDLE);
579 // Tell the channel to try to connect.
580 // Note that this call also returns IDLE, since the state change has
581 // not yet occurred; it just gets triggered by this call.
582 EXPECT_EQ(channel->GetState(true /* try_to_connect */), GRPC_CHANNEL_IDLE);
583 // Now that the channel is trying to connect, we should be in state
584 // CONNECTING.
585 EXPECT_EQ(channel->GetState(false /* try_to_connect */),
586 GRPC_CHANNEL_CONNECTING);
587 // Return a resolver result, which allows the connection attempt to proceed.
588 response_generator.SetNextResolution(GetServersPorts());
589 // We should eventually transition into state READY.
590 EXPECT_TRUE(WaitForChannelReady(channel.get()));
591 }
592
593 TEST_F(ClientLbEnd2endTest, ChannelIdleness) {
594 // Start server.
595 const int kNumServers = 1;
596 StartServers(kNumServers);
597 // Set max idle time and build the channel.
598 ChannelArguments args;
599 args.SetInt(GRPC_ARG_CLIENT_IDLE_TIMEOUT_MS,
600 1000 * grpc_test_slowdown_factor());
601 auto response_generator = BuildResolverResponseGenerator();
602 auto channel = BuildChannel("", response_generator, args);
603 auto stub = BuildStub(channel);
604 // The initial channel state should be IDLE.
605 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
606 // After sending RPC, channel state should be READY.
607 gpr_log(GPR_INFO, "*** SENDING RPC, CHANNEL SHOULD CONNECT ***");
608 response_generator.SetNextResolution(GetServersPorts());
609 CheckRpcSendOk(DEBUG_LOCATION, stub);
610 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
611 // After a period time not using the channel, the channel state should switch
612 // to IDLE.
613 gpr_log(GPR_INFO, "*** WAITING FOR CHANNEL TO GO IDLE ***");
614 gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(1200));
615 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
616 // Sending a new RPC should awake the IDLE channel.
617 gpr_log(GPR_INFO, "*** SENDING ANOTHER RPC, CHANNEL SHOULD RECONNECT ***");
618 response_generator.SetNextResolution(GetServersPorts());
619 CheckRpcSendOk(DEBUG_LOCATION, stub);
620 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
621 }
622
623 TEST_F(ClientLbEnd2endTest, AuthorityOverrideOnChannel) {
624 StartServers(1);
625 // Set authority via channel arg.
626 auto response_generator = BuildResolverResponseGenerator();
627 ChannelArguments args;
628 args.SetString(GRPC_ARG_DEFAULT_AUTHORITY, "foo.example.com");
629 auto channel = BuildChannel("", response_generator, args);
630 auto stub = BuildStub(channel);
631 response_generator.SetNextResolution(GetServersPorts());
632 // Send an RPC.
633 EchoRequest request;
634 request.mutable_param()->set_echo_host_from_authority_header(true);
635 EchoResponse response;
636 Status status = SendRpc(stub, &response, /*timeout_ms=*/1000,
637 /*wait_for_ready=*/false, &request);
638 EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
639 << " message=" << status.error_message();
640 // Check that the right authority was seen by the server.
641 EXPECT_EQ("foo.example.com", response.param().host());
642 }
643
644 TEST_F(ClientLbEnd2endTest, AuthorityOverrideFromResolver) {
645 StartServers(1);
646 auto response_generator = BuildResolverResponseGenerator();
647 auto channel = BuildChannel("", response_generator);
648 auto stub = BuildStub(channel);
649 // Inject resolver result that sets the per-address authority to a
650 // different value.
651 response_generator.SetNextResolution(
652 GetServersPorts(), /*service_config_json=*/nullptr,
653 /*attribute_key=*/nullptr, /*attribute=*/nullptr,
654 grpc_core::ChannelArgs().Set(GRPC_ARG_DEFAULT_AUTHORITY,
655 "foo.example.com"));
656 // Send an RPC.
657 EchoRequest request;
658 request.mutable_param()->set_echo_host_from_authority_header(true);
659 EchoResponse response;
660 Status status = SendRpc(stub, &response, /*timeout_ms=*/1000,
661 /*wait_for_ready=*/false, &request);
662 EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
663 << " message=" << status.error_message();
664 // Check that the right authority was seen by the server.
665 EXPECT_EQ("foo.example.com", response.param().host());
666 }
667
668 TEST_F(ClientLbEnd2endTest, AuthorityOverridePrecedence) {
669 StartServers(1);
670 // Set authority via channel arg.
671 auto response_generator = BuildResolverResponseGenerator();
672 ChannelArguments args;
673 args.SetString(GRPC_ARG_DEFAULT_AUTHORITY, "foo.example.com");
674 auto channel = BuildChannel("", response_generator, args);
675 auto stub = BuildStub(channel);
676 // Inject resolver result that sets the per-address authority to a
677 // different value.
678 response_generator.SetNextResolution(
679 GetServersPorts(), /*service_config_json=*/nullptr,
680 /*attribute_key=*/nullptr, /*attribute=*/nullptr,
681 grpc_core::ChannelArgs().Set(GRPC_ARG_DEFAULT_AUTHORITY,
682 "bar.example.com"));
683 // Send an RPC.
684 EchoRequest request;
685 request.mutable_param()->set_echo_host_from_authority_header(true);
686 EchoResponse response;
687 Status status = SendRpc(stub, &response, /*timeout_ms=*/1000,
688 /*wait_for_ready=*/false, &request);
689 EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
690 << " message=" << status.error_message();
691 // Check that the right authority was seen by the server.
692 EXPECT_EQ("foo.example.com", response.param().host());
693 }
694
695 //
696 // pick_first tests
697 //
698
699 using PickFirstTest = ClientLbEnd2endTest;
700
701 TEST_F(PickFirstTest, Basic) {
702 // Start servers and send one RPC per server.
703 const int kNumServers = 3;
704 StartServers(kNumServers);
705 auto response_generator = BuildResolverResponseGenerator();
706 auto channel = BuildChannel(
707 "", response_generator); // test that pick first is the default.
708 auto stub = BuildStub(channel);
709 response_generator.SetNextResolution(GetServersPorts());
710 for (size_t i = 0; i < servers_.size(); ++i) {
711 CheckRpcSendOk(DEBUG_LOCATION, stub);
712 }
713 // All requests should have gone to a single server.
714 bool found = false;
715 for (size_t i = 0; i < servers_.size(); ++i) {
716 const int request_count = servers_[i]->service_.request_count();
717 if (request_count == kNumServers) {
718 found = true;
719 } else {
720 EXPECT_EQ(0, request_count);
721 }
722 }
723 EXPECT_TRUE(found);
724 // Check LB policy name for the channel.
725 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
726 }
727
728 TEST_F(PickFirstTest, ProcessPending) {
729 StartServers(1); // Single server
730 auto response_generator = BuildResolverResponseGenerator();
731 auto channel = BuildChannel(
732 "", response_generator); // test that pick first is the default.
733 auto stub = BuildStub(channel);
734 response_generator.SetNextResolution({servers_[0]->port_});
735 WaitForServer(DEBUG_LOCATION, stub, 0);
736 // Create a new channel and its corresponding PF LB policy, which will pick
737 // the subchannels in READY state from the previous RPC against the same
738 // target (even if it happened over a different channel, because subchannels
739 // are globally reused). Progress should happen without any transition from
740 // this READY state.
741 auto second_response_generator = BuildResolverResponseGenerator();
742 auto second_channel = BuildChannel("", second_response_generator);
743 auto second_stub = BuildStub(second_channel);
744 second_response_generator.SetNextResolution({servers_[0]->port_});
745 CheckRpcSendOk(DEBUG_LOCATION, second_stub);
746 }
747
748 TEST_F(PickFirstTest, SelectsReadyAtStartup) {
749 ChannelArguments args;
750 constexpr int kInitialBackOffMs = 5000;
751 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS,
752 kInitialBackOffMs * grpc_test_slowdown_factor());
753 // Create 2 servers, but start only the second one.
754 std::vector<int> ports = {grpc_pick_unused_port_or_die(),
755 grpc_pick_unused_port_or_die()};
756 CreateServers(2, ports);
757 StartServer(1);
758 auto response_generator1 = BuildResolverResponseGenerator();
759 auto channel1 = BuildChannel("pick_first", response_generator1, args);
760 auto stub1 = BuildStub(channel1);
761 response_generator1.SetNextResolution(ports);
762 // Wait for second server to be ready.
763 WaitForServer(DEBUG_LOCATION, stub1, 1);
764 // Create a second channel with the same addresses. Its PF instance
765 // should immediately pick the second subchannel, since it's already
766 // in READY state.
767 auto response_generator2 = BuildResolverResponseGenerator();
768 auto channel2 = BuildChannel("pick_first", response_generator2, args);
769 response_generator2.SetNextResolution(ports);
770 // Check that the channel reports READY without waiting for the
771 // initial backoff.
772 EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1 /* timeout_seconds */));
773 }
774
775 TEST_F(PickFirstTest, BackOffInitialReconnect) {
776 ChannelArguments args;
777 constexpr int kInitialBackOffMs = 100;
778 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS,
779 kInitialBackOffMs * grpc_test_slowdown_factor());
780 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
781 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
782 auto response_generator = BuildResolverResponseGenerator();
783 auto channel = BuildChannel("pick_first", response_generator, args);
784 auto stub = BuildStub(channel);
785 response_generator.SetNextResolution(ports);
786 // The channel won't become connected (there's no server).
787 ASSERT_FALSE(channel->WaitForConnected(
788 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
789 // Bring up a server on the chosen port.
790 StartServers(1, ports);
791 // Now it will.
792 ASSERT_TRUE(channel->WaitForConnected(
793 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
794 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
795 const grpc_core::Duration waited =
796 grpc_core::Duration::FromTimespec(gpr_time_sub(t1, t0));
797 gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited.millis());
798 // We should have waited at least kInitialBackOffMs. We substract one to
799 // account for test and precision accuracy drift.
800 EXPECT_GE(waited.millis(),
801 (kInitialBackOffMs * grpc_test_slowdown_factor()) - 1);
802 // But not much more.
803 EXPECT_GT(
804 gpr_time_cmp(
805 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 1.10), t1),
806 0);
807 }
808
809 TEST_F(PickFirstTest, BackOffMinReconnect) {
810 ChannelArguments args;
811 constexpr int kMinReconnectBackOffMs = 1000;
812 args.SetInt(GRPC_ARG_MIN_RECONNECT_BACKOFF_MS,
813 kMinReconnectBackOffMs * grpc_test_slowdown_factor());
814 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
815 auto response_generator = BuildResolverResponseGenerator();
816 auto channel = BuildChannel("pick_first", response_generator, args);
817 auto stub = BuildStub(channel);
818 response_generator.SetNextResolution(ports);
819 // Make connection delay a 10% longer than it's willing to in order to make
820 // sure we are hitting the codepath that waits for the min reconnect backoff.
821 ConnectionAttemptInjector injector;
822 injector.SetDelay(grpc_core::Duration::Milliseconds(
823 kMinReconnectBackOffMs * grpc_test_slowdown_factor() * 1.10));
824 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
825 channel->WaitForConnected(
826 grpc_timeout_milliseconds_to_deadline(kMinReconnectBackOffMs * 2));
827 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
828 const grpc_core::Duration waited =
829 grpc_core::Duration::FromTimespec(gpr_time_sub(t1, t0));
830 gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited.millis());
831 // We should have waited at least kMinReconnectBackOffMs. We substract one to
832 // account for test and precision accuracy drift.
833 EXPECT_GE(waited.millis(),
834 (kMinReconnectBackOffMs * grpc_test_slowdown_factor()) - 1);
835 }
836
837 TEST_F(PickFirstTest, ResetConnectionBackoff) {
838 ChannelArguments args;
839 constexpr int kInitialBackOffMs = 1000;
840 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS,
841 kInitialBackOffMs * grpc_test_slowdown_factor());
842 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
843 auto response_generator = BuildResolverResponseGenerator();
844 auto channel = BuildChannel("pick_first", response_generator, args);
845 auto stub = BuildStub(channel);
846 response_generator.SetNextResolution(ports);
847 // The channel won't become connected (there's no server).
848 EXPECT_FALSE(
849 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
850 // Bring up a server on the chosen port.
851 StartServers(1, ports);
852 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
853 // Wait for connect, but not long enough. This proves that we're
854 // being throttled by initial backoff.
855 EXPECT_FALSE(
856 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
857 // Reset connection backoff.
858 experimental::ChannelResetConnectionBackoff(channel.get());
859 // Wait for connect. Should happen as soon as the client connects to
860 // the newly started server, which should be before the initial
861 // backoff timeout elapses.
862 EXPECT_TRUE(channel->WaitForConnected(
863 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs)));
864 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
865 const grpc_core::Duration waited =
866 grpc_core::Duration::FromTimespec(gpr_time_sub(t1, t0));
867 gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited.millis());
868 // We should have waited less than kInitialBackOffMs.
869 EXPECT_LT(waited.millis(), kInitialBackOffMs * grpc_test_slowdown_factor());
870 }
871
872 TEST_F(ClientLbEnd2endTest,
873 ResetConnectionBackoffNextAttemptStartsImmediately) {
874 // Start connection injector.
875 ConnectionAttemptInjector injector;
876 // Create client.
877 const int port = grpc_pick_unused_port_or_die();
878 ChannelArguments args;
879 const int kInitialBackOffMs = 5000;
880 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS,
881 kInitialBackOffMs * grpc_test_slowdown_factor());
882 auto response_generator = BuildResolverResponseGenerator();
883 auto channel = BuildChannel("pick_first", response_generator, args);
884 auto stub = BuildStub(channel);
885 response_generator.SetNextResolution({port});
886 // Intercept initial connection attempt.
887 auto hold1 = injector.AddHold(port);
888 gpr_log(GPR_INFO, "=== TRIGGERING INITIAL CONNECTION ATTEMPT");
889 EXPECT_EQ(GRPC_CHANNEL_IDLE, channel->GetState(/*try_to_connect=*/true));
890 hold1->Wait();
891 EXPECT_EQ(GRPC_CHANNEL_CONNECTING,
892 channel->GetState(/*try_to_connect=*/false));
893 // Reset backoff.
894 gpr_log(GPR_INFO, "=== RESETTING BACKOFF");
895 experimental::ChannelResetConnectionBackoff(channel.get());
896 // Intercept next attempt. Do this before resuming the first attempt,
897 // just in case the client makes progress faster than this thread.
898 auto hold2 = injector.AddHold(port);
899 // Fail current attempt and wait for next one to start.
900 gpr_log(GPR_INFO, "=== RESUMING INITIAL ATTEMPT");
901 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
902 hold1->Resume();
903 gpr_log(GPR_INFO, "=== WAITING FOR SECOND ATTEMPT");
904 // This WaitForStateChange() call just makes sure we're doing some polling.
905 EXPECT_TRUE(channel->WaitForStateChange(GRPC_CHANNEL_CONNECTING,
906 grpc_timeout_seconds_to_deadline(1)));
907 hold2->Wait();
908 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
909 gpr_log(GPR_INFO, "=== RESUMING SECOND ATTEMPT");
910 hold2->Resume();
911 // Elapsed time should be very short, much less than kInitialBackOffMs.
912 const grpc_core::Duration waited =
913 grpc_core::Duration::FromTimespec(gpr_time_sub(t1, t0));
914 gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited.millis());
915 EXPECT_LT(waited.millis(), 1000 * grpc_test_slowdown_factor());
916 }
917
918 TEST_F(
919 PickFirstTest,
920 TriesAllSubchannelsBeforeReportingTransientFailureWithSubchannelSharing) {
921 // Start connection injector.
922 ConnectionAttemptInjector injector;
923 // Get 5 unused ports. Each channel will have 2 unique ports followed
924 // by a common port.
925 std::vector<int> ports1 = {grpc_pick_unused_port_or_die(),
926 grpc_pick_unused_port_or_die(),
927 grpc_pick_unused_port_or_die()};
928 std::vector<int> ports2 = {grpc_pick_unused_port_or_die(),
929 grpc_pick_unused_port_or_die(), ports1[2]};
930 // Create channel 1.
931 auto response_generator1 = BuildResolverResponseGenerator();
932 auto channel1 = BuildChannel("pick_first", response_generator1);
933 auto stub1 = BuildStub(channel1);
934 response_generator1.SetNextResolution(ports1);
935 // Allow the connection attempts for ports 0 and 1 to fail normally.
936 // Inject a hold for the connection attempt to port 2.
937 auto hold_channel1_port2 = injector.AddHold(ports1[2]);
938 // Trigger connection attempt.
939 gpr_log(GPR_INFO, "=== START CONNECTING CHANNEL 1 ===");
940 channel1->GetState(/*try_to_connect=*/true);
941 // Wait for connection attempt to port 2.
942 gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL 1 PORT 2 TO START ===");
943 hold_channel1_port2->Wait();
944 gpr_log(GPR_INFO, "=== CHANNEL 1 PORT 2 STARTED ===");
945 // Now create channel 2.
946 auto response_generator2 = BuildResolverResponseGenerator();
947 auto channel2 = BuildChannel("pick_first", response_generator2);
948 response_generator2.SetNextResolution(ports2);
949 // Inject a hold for port 0.
950 auto hold_channel2_port0 = injector.AddHold(ports2[0]);
951 // Trigger connection attempt.
952 gpr_log(GPR_INFO, "=== START CONNECTING CHANNEL 2 ===");
953 channel2->GetState(/*try_to_connect=*/true);
954 // Wait for connection attempt to port 0.
955 gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL 2 PORT 0 TO START ===");
956 hold_channel2_port0->Wait();
957 gpr_log(GPR_INFO, "=== CHANNEL 2 PORT 0 STARTED ===");
958 // Inject a hold for port 0, which will be retried by channel 1.
959 auto hold_channel1_port0 = injector.AddHold(ports1[0]);
960 // Now allow the connection attempt to port 2 to complete. The subchannel
961 // will deliver a TRANSIENT_FAILURE notification to both channels.
962 gpr_log(GPR_INFO, "=== RESUMING CHANNEL 1 PORT 2 ===");
963 hold_channel1_port2->Resume();
964 // Wait for channel 1 to retry port 0, so that we know it's seen the
965 // connectivity state notification for port 2.
966 gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL 1 PORT 0 ===");
967 hold_channel1_port0->Wait();
968 gpr_log(GPR_INFO, "=== CHANNEL 1 PORT 0 STARTED ===");
969 // Channel 1 should now report TRANSIENT_FAILURE.
970 // Channel 2 should continue to report CONNECTING.
971 EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel1->GetState(false));
972 EXPECT_EQ(GRPC_CHANNEL_CONNECTING, channel2->GetState(false));
973 // Inject a hold for port 2, which will eventually be tried by channel 2.
974 auto hold_channel2_port2 = injector.AddHold(ports2[2]);
975 // Allow channel 2 to resume port 0. Port 0 will fail, as will port 1.
976 gpr_log(GPR_INFO, "=== RESUMING CHANNEL 2 PORT 0 ===");
977 hold_channel2_port0->Resume();
978 // Wait for channel 2 to try port 2.
979 gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL 2 PORT 2 ===");
980 hold_channel2_port2->Wait();
981 gpr_log(GPR_INFO, "=== CHANNEL 2 PORT 2 STARTED ===");
982 // Channel 2 should still be CONNECTING here.
983 EXPECT_EQ(GRPC_CHANNEL_CONNECTING, channel2->GetState(false));
984 // Add a hold for channel 2 port 0.
985 hold_channel2_port0 = injector.AddHold(ports2[0]);
986 gpr_log(GPR_INFO, "=== RESUMING CHANNEL 2 PORT 2 ===");
987 hold_channel2_port2->Resume();
988 // Wait for channel 2 to retry port 0.
989 gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL 2 PORT 0 ===");
990 hold_channel2_port0->Wait();
991 // Now channel 2 should be reporting TRANSIENT_FAILURE.
992 EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel2->GetState(false));
993 // Clean up.
994 gpr_log(GPR_INFO, "=== RESUMING CHANNEL 1 PORT 0 AND CHANNEL 2 PORT 0 ===");
995 hold_channel1_port0->Resume();
996 hold_channel2_port0->Resume();
997 }
998
999 TEST_F(PickFirstTest, Updates) {
1000 // Start servers and send one RPC per server.
1001 const int kNumServers = 3;
1002 StartServers(kNumServers);
1003 auto response_generator = BuildResolverResponseGenerator();
1004 auto channel = BuildChannel("pick_first", response_generator);
1005 auto stub = BuildStub(channel);
1006
1007 std::vector<int> ports;
1008
1009 // Perform one RPC against the first server.
1010 ports.emplace_back(servers_[0]->port_);
1011 response_generator.SetNextResolution(ports);
1012 gpr_log(GPR_INFO, "****** SET [0] *******");
1013 CheckRpcSendOk(DEBUG_LOCATION, stub);
1014 EXPECT_EQ(servers_[0]->service_.request_count(), 1);
1015
1016 // An empty update will result in the channel going into TRANSIENT_FAILURE.
1017 ports.clear();
1018 response_generator.SetNextResolution(ports);
1019 gpr_log(GPR_INFO, "****** SET none *******");
1020 grpc_connectivity_state channel_state;
1021 do {
1022 channel_state = channel->GetState(true /* try to connect */);
1023 } while (channel_state == GRPC_CHANNEL_READY);
1024 ASSERT_NE(channel_state, GRPC_CHANNEL_READY);
1025 servers_[0]->service_.ResetCounters();
1026
1027 // Next update introduces servers_[1], making the channel recover.
1028 ports.clear();
1029 ports.emplace_back(servers_[1]->port_);
1030 response_generator.SetNextResolution(ports);
1031 gpr_log(GPR_INFO, "****** SET [1] *******");
1032 WaitForServer(DEBUG_LOCATION, stub, 1);
1033 EXPECT_EQ(servers_[0]->service_.request_count(), 0);
1034
1035 // And again for servers_[2]
1036 ports.clear();
1037 ports.emplace_back(servers_[2]->port_);
1038 response_generator.SetNextResolution(ports);
1039 gpr_log(GPR_INFO, "****** SET [2] *******");
1040 WaitForServer(DEBUG_LOCATION, stub, 2);
1041 EXPECT_EQ(servers_[0]->service_.request_count(), 0);
1042 EXPECT_EQ(servers_[1]->service_.request_count(), 0);
1043
1044 // Check LB policy name for the channel.
1045 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
1046 }
1047
1048 TEST_F(PickFirstTest, UpdateSuperset) {
1049 // Start servers and send one RPC per server.
1050 const int kNumServers = 3;
1051 StartServers(kNumServers);
1052 auto response_generator = BuildResolverResponseGenerator();
1053 auto channel = BuildChannel("pick_first", response_generator);
1054 auto stub = BuildStub(channel);
1055
1056 std::vector<int> ports;
1057
1058 // Perform one RPC against the first server.
1059 ports.emplace_back(servers_[0]->port_);
1060 response_generator.SetNextResolution(ports);
1061 gpr_log(GPR_INFO, "****** SET [0] *******");
1062 CheckRpcSendOk(DEBUG_LOCATION, stub);
1063 EXPECT_EQ(servers_[0]->service_.request_count(), 1);
1064 servers_[0]->service_.ResetCounters();
1065
1066 // Send and superset update
1067 ports.clear();
1068 ports.emplace_back(servers_[1]->port_);
1069 ports.emplace_back(servers_[0]->port_);
1070 response_generator.SetNextResolution(ports);
1071 gpr_log(GPR_INFO, "****** SET superset *******");
1072 CheckRpcSendOk(DEBUG_LOCATION, stub);
1073 // We stick to the previously connected server.
1074 WaitForServer(DEBUG_LOCATION, stub, 0);
1075 EXPECT_EQ(0, servers_[1]->service_.request_count());
1076
1077 // Check LB policy name for the channel.
1078 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
1079 }
1080
1081 TEST_F(PickFirstTest, UpdateToUnconnected) {
1082 const int kNumServers = 2;
1083 CreateServers(kNumServers);
1084 StartServer(0);
1085 auto response_generator = BuildResolverResponseGenerator();
1086 auto channel = BuildChannel("pick_first", response_generator);
1087 auto stub = BuildStub(channel);
1088
1089 std::vector<int> ports;
1090
1091 // Try to send rpcs against a list where the server is available.
1092 ports.emplace_back(servers_[0]->port_);
1093 response_generator.SetNextResolution(ports);
1094 gpr_log(GPR_INFO, "****** SET [0] *******");
1095 CheckRpcSendOk(DEBUG_LOCATION, stub);
1096
1097 // Send resolution for which all servers are currently unavailable. Eventually
1098 // this triggers replacing the existing working subchannel_list with the new
1099 // currently unresponsive list.
1100 ports.clear();
1101 ports.emplace_back(grpc_pick_unused_port_or_die());
1102 ports.emplace_back(servers_[1]->port_);
1103 response_generator.SetNextResolution(ports);
1104 gpr_log(GPR_INFO, "****** SET [unavailable] *******");
1105 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
1106
1107 // Ensure that the last resolution was installed correctly by verifying that
1108 // the channel becomes ready once one of if its endpoints becomes available.
1109 gpr_log(GPR_INFO, "****** StartServer(1) *******");
1110 StartServer(1);
1111 EXPECT_TRUE(WaitForChannelReady(channel.get()));
1112 }
1113
1114 TEST_F(PickFirstTest, GlobalSubchannelPool) {
1115 // Start one server.
1116 const int kNumServers = 1;
1117 StartServers(kNumServers);
1118 std::vector<int> ports = GetServersPorts();
1119 // Create two channels that (by default) use the global subchannel pool.
1120 auto response_generator1 = BuildResolverResponseGenerator();
1121 auto channel1 = BuildChannel("pick_first", response_generator1);
1122 auto stub1 = BuildStub(channel1);
1123 response_generator1.SetNextResolution(ports);
1124 auto response_generator2 = BuildResolverResponseGenerator();
1125 auto channel2 = BuildChannel("pick_first", response_generator2);
1126 auto stub2 = BuildStub(channel2);
1127 response_generator2.SetNextResolution(ports);
1128 WaitForServer(DEBUG_LOCATION, stub1, 0);
1129 // Send one RPC on each channel.
1130 CheckRpcSendOk(DEBUG_LOCATION, stub1);
1131 CheckRpcSendOk(DEBUG_LOCATION, stub2);
1132 // The server receives two requests.
1133 EXPECT_EQ(2, servers_[0]->service_.request_count());
1134 // The two requests are from the same client port, because the two channels
1135 // share subchannels via the global subchannel pool.
1136 EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
1137 }
1138
1139 TEST_F(PickFirstTest, LocalSubchannelPool) {
1140 // Start one server.
1141 const int kNumServers = 1;
1142 StartServers(kNumServers);
1143 std::vector<int> ports = GetServersPorts();
1144 // Create two channels that use local subchannel pool.
1145 ChannelArguments args;
1146 args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
1147 auto response_generator1 = BuildResolverResponseGenerator();
1148 auto channel1 = BuildChannel("pick_first", response_generator1, args);
1149 auto stub1 = BuildStub(channel1);
1150 response_generator1.SetNextResolution(ports);
1151 auto response_generator2 = BuildResolverResponseGenerator();
1152 auto channel2 = BuildChannel("pick_first", response_generator2, args);
1153 auto stub2 = BuildStub(channel2);
1154 response_generator2.SetNextResolution(ports);
1155 WaitForServer(DEBUG_LOCATION, stub1, 0);
1156 // Send one RPC on each channel.
1157 CheckRpcSendOk(DEBUG_LOCATION, stub1);
1158 CheckRpcSendOk(DEBUG_LOCATION, stub2);
1159 // The server receives two requests.
1160 EXPECT_EQ(2, servers_[0]->service_.request_count());
1161 // The two requests are from two client ports, because the two channels didn't
1162 // share subchannels with each other.
1163 EXPECT_EQ(2UL, servers_[0]->service_.clients().size());
1164 }
1165
1166 TEST_F(PickFirstTest, ManyUpdates) {
1167 const int kNumUpdates = 1000;
1168 const int kNumServers = 3;
1169 StartServers(kNumServers);
1170 auto response_generator = BuildResolverResponseGenerator();
1171 auto channel = BuildChannel("pick_first", response_generator);
1172 auto stub = BuildStub(channel);
1173 std::vector<int> ports = GetServersPorts();
1174 for (size_t i = 0; i < kNumUpdates; ++i) {
1175 std::shuffle(ports.begin(), ports.end(),
1176 std::mt19937(std::random_device()()));
1177 response_generator.SetNextResolution(ports);
1178 // We should re-enter core at the end of the loop to give the resolution
1179 // setting closure a chance to run.
1180 if ((i + 1) % 10 == 0) CheckRpcSendOk(DEBUG_LOCATION, stub);
1181 }
1182 // Check LB policy name for the channel.
1183 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
1184 }
1185
1186 TEST_F(PickFirstTest, ReresolutionNoSelected) {
1187 // Prepare the ports for up servers and down servers.
1188 const int kNumServers = 3;
1189 const int kNumAliveServers = 1;
1190 StartServers(kNumAliveServers);
1191 std::vector<int> alive_ports, dead_ports;
1192 for (size_t i = 0; i < kNumServers; ++i) {
1193 if (i < kNumAliveServers) {
1194 alive_ports.emplace_back(servers_[i]->port_);
1195 } else {
1196 dead_ports.emplace_back(grpc_pick_unused_port_or_die());
1197 }
1198 }
1199 auto response_generator = BuildResolverResponseGenerator();
1200 auto channel = BuildChannel("pick_first", response_generator);
1201 auto stub = BuildStub(channel);
1202 // The initial resolution only contains dead ports. There won't be any
1203 // selected subchannel. Re-resolution will return the same result.
1204 response_generator.SetNextResolution(dead_ports);
1205 gpr_log(GPR_INFO, "****** INITIAL RESOLUTION SET *******");
1206 for (size_t i = 0; i < 10; ++i) {
1207 CheckRpcSendFailure(
1208 DEBUG_LOCATION, stub, StatusCode::UNAVAILABLE,
1209 MakeConnectionFailureRegex("failed to connect to all addresses"));
1210 }
1211 // Set a re-resolution result that contains reachable ports, so that the
1212 // pick_first LB policy can recover soon.
1213 response_generator.SetNextResolutionUponError(alive_ports);
1214 gpr_log(GPR_INFO, "****** RE-RESOLUTION SET *******");
1215 WaitForServer(DEBUG_LOCATION, stub, 0, [](const Status& status) {
1216 EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
1217 EXPECT_THAT(status.error_message(),
1218 ::testing::ContainsRegex(MakeConnectionFailureRegex(
1219 "failed to connect to all addresses")));
1220 });
1221 CheckRpcSendOk(DEBUG_LOCATION, stub);
1222 EXPECT_EQ(servers_[0]->service_.request_count(), 1);
1223 // Check LB policy name for the channel.
1224 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
1225 }
1226
1227 TEST_F(PickFirstTest, ReconnectWithoutNewResolverResult) {
1228 std::vector<int> ports = {grpc_pick_unused_port_or_die()};
1229 StartServers(1, ports);
1230 auto response_generator = BuildResolverResponseGenerator();
1231 auto channel = BuildChannel("pick_first", response_generator);
1232 auto stub = BuildStub(channel);
1233 response_generator.SetNextResolution(ports);
1234 gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
1235 WaitForServer(DEBUG_LOCATION, stub, 0);
1236 gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
1237 servers_[0]->Shutdown();
1238 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
1239 gpr_log(GPR_INFO, "****** RESTARTING SERVER ******");
1240 StartServers(1, ports);
1241 WaitForServer(DEBUG_LOCATION, stub, 0);
1242 }
1243
1244 TEST_F(PickFirstTest, ReconnectWithoutNewResolverResultStartsFromTopOfList) {
1245 std::vector<int> ports = {grpc_pick_unused_port_or_die(),
1246 grpc_pick_unused_port_or_die()};
1247 CreateServers(2, ports);
1248 StartServer(1);
1249 auto response_generator = BuildResolverResponseGenerator();
1250 auto channel = BuildChannel("pick_first", response_generator);
1251 auto stub = BuildStub(channel);
1252 response_generator.SetNextResolution(ports);
1253 gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
1254 WaitForServer(DEBUG_LOCATION, stub, 1);
1255 gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
1256 servers_[1]->Shutdown();
1257 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
1258 gpr_log(GPR_INFO, "****** STARTING BOTH SERVERS ******");
1259 StartServers(2, ports);
1260 WaitForServer(DEBUG_LOCATION, stub, 0);
1261 }
1262
1263 TEST_F(PickFirstTest, FailsEmptyResolverUpdate) {
1264 auto response_generator = BuildResolverResponseGenerator();
1265 auto channel = BuildChannel("pick_first", response_generator);
1266 auto stub = BuildStub(channel);
1267 gpr_log(GPR_INFO, "****** SENDING INITIAL RESOLVER RESULT *******");
1268 // Send a resolver result with an empty address list and a callback
1269 // that triggers a notification.
1270 grpc_core::Notification notification;
1271 grpc_core::Resolver::Result result;
1272 result.addresses.emplace();
1273 result.result_health_callback = [&](absl::Status status) {
1274 EXPECT_EQ(absl::StatusCode::kUnavailable, status.code());
1275 EXPECT_EQ("address list must not be empty", status.message()) << status;
1276 notification.Notify();
1277 };
1278 response_generator.SetResponse(std::move(result));
1279 // Wait for channel to report TRANSIENT_FAILURE.
1280 gpr_log(GPR_INFO, "****** TELLING CHANNEL TO CONNECT *******");
1281 auto predicate = [](grpc_connectivity_state state) {
1282 return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
1283 };
1284 EXPECT_TRUE(
1285 WaitForChannelState(channel.get(), predicate, /*try_to_connect=*/true));
1286 // Callback should have been run.
1287 ASSERT_TRUE(notification.HasBeenNotified());
1288 // Return a valid address.
1289 gpr_log(GPR_INFO, "****** SENDING NEXT RESOLVER RESULT *******");
1290 StartServers(1);
1291 response_generator.SetNextResolution(GetServersPorts());
1292 gpr_log(GPR_INFO, "****** SENDING WAIT_FOR_READY RPC *******");
1293 CheckRpcSendOk(DEBUG_LOCATION, stub, /*wait_for_ready=*/true);
1294 }
1295
1296 TEST_F(PickFirstTest, CheckStateBeforeStartWatch) {
1297 std::vector<int> ports = {grpc_pick_unused_port_or_die()};
1298 StartServers(1, ports);
1299 auto response_generator = BuildResolverResponseGenerator();
1300 auto channel_1 = BuildChannel("pick_first", response_generator);
1301 auto stub_1 = BuildStub(channel_1);
1302 response_generator.SetNextResolution(ports);
1303 gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 1 *******");
1304 WaitForServer(DEBUG_LOCATION, stub_1, 0);
1305 gpr_log(GPR_INFO, "****** CHANNEL 1 CONNECTED *******");
1306 servers_[0]->Shutdown();
1307 EXPECT_TRUE(WaitForChannelNotReady(channel_1.get()));
1308 // Channel 1 will receive a re-resolution containing the same server. It will
1309 // create a new subchannel and hold a ref to it.
1310 StartServers(1, ports);
1311 gpr_log(GPR_INFO, "****** SERVER RESTARTED *******");
1312 auto response_generator_2 = BuildResolverResponseGenerator();
1313 auto channel_2 = BuildChannel("pick_first", response_generator_2);
1314 auto stub_2 = BuildStub(channel_2);
1315 response_generator_2.SetNextResolution(ports);
1316 gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 2 *******");
1317 WaitForServer(DEBUG_LOCATION, stub_2, 0);
1318 gpr_log(GPR_INFO, "****** CHANNEL 2 CONNECTED *******");
1319 servers_[0]->Shutdown();
1320 // Wait until the disconnection has triggered the connectivity notification.
1321 // Otherwise, the subchannel may be picked for next call but will fail soon.
1322 EXPECT_TRUE(WaitForChannelNotReady(channel_2.get()));
1323 // Channel 2 will also receive a re-resolution containing the same server.
1324 // Both channels will ref the same subchannel that failed.
1325 StartServers(1, ports);
1326 gpr_log(GPR_INFO, "****** SERVER RESTARTED AGAIN *******");
1327 gpr_log(GPR_INFO, "****** CHANNEL 2 STARTING A CALL *******");
1328 // The first call after the server restart will succeed.
1329 CheckRpcSendOk(DEBUG_LOCATION, stub_2);
1330 gpr_log(GPR_INFO, "****** CHANNEL 2 FINISHED A CALL *******");
1331 // Check LB policy name for the channel.
1332 EXPECT_EQ("pick_first", channel_1->GetLoadBalancingPolicyName());
1333 // Check LB policy name for the channel.
1334 EXPECT_EQ("pick_first", channel_2->GetLoadBalancingPolicyName());
1335 }
1336
1337 TEST_F(PickFirstTest, IdleOnDisconnect) {
1338 // Start server, send RPC, and make sure channel is READY.
1339 const int kNumServers = 1;
1340 StartServers(kNumServers);
1341 auto response_generator = BuildResolverResponseGenerator();
1342 auto channel =
1343 BuildChannel("", response_generator); // pick_first is the default.
1344 auto stub = BuildStub(channel);
1345 response_generator.SetNextResolution(GetServersPorts());
1346 CheckRpcSendOk(DEBUG_LOCATION, stub);
1347 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
1348 // Stop server. Channel should go into state IDLE.
1349 response_generator.SetFailureOnReresolution();
1350 servers_[0]->Shutdown();
1351 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
1352 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
1353 servers_.clear();
1354 }
1355
1356 TEST_F(PickFirstTest, PendingUpdateAndSelectedSubchannelFails) {
1357 auto response_generator = BuildResolverResponseGenerator();
1358 auto channel =
1359 BuildChannel("", response_generator); // pick_first is the default.
1360 auto stub = BuildStub(channel);
1361 StartServers(2);
1362 // Initially resolve to first server and make sure it connects.
1363 gpr_log(GPR_INFO, "Phase 1: Connect to first server.");
1364 response_generator.SetNextResolution({servers_[0]->port_});
1365 CheckRpcSendOk(DEBUG_LOCATION, stub, true /* wait_for_ready */);
1366 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
1367 ConnectionAttemptInjector injector;
1368 auto hold = injector.AddHold(servers_[1]->port_);
1369 // Send a resolution update with the remaining servers, none of which are
1370 // running yet, so the update will stay pending.
1371 gpr_log(GPR_INFO,
1372 "Phase 2: Resolver update pointing to remaining "
1373 "(not started) servers.");
1374 response_generator.SetNextResolution(GetServersPorts(1 /* start_index */));
1375 // Add hold before connection attempt to ensure RPCs will be sent to first
1376 // server. Otherwise, pending subchannel list might already have gone into
1377 // TRANSIENT_FAILURE due to hitting the end of the server list by the time
1378 // we check the state.
1379 hold->Wait();
1380 // RPCs will continue to be sent to the first server.
1381 CheckRpcSendOk(DEBUG_LOCATION, stub);
1382 // Now stop the first server, so that the current subchannel list
1383 // fails. This should cause us to immediately swap over to the
1384 // pending list, even though it's not yet connected. The state should
1385 // be set to CONNECTING, since that's what the pending subchannel list
1386 // was doing when we swapped over.
1387 gpr_log(GPR_INFO, "Phase 3: Stopping first server.");
1388 servers_[0]->Shutdown();
1389 WaitForChannelNotReady(channel.get());
1390 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_CONNECTING);
1391 // Resume connection attempt to second server now that first server is down.
1392 // The channel should go to READY state and RPCs should go to the second
1393 // server.
1394 gpr_log(GPR_INFO, "Phase 4: Resuming connection attempt to second server.");
1395 hold->Resume();
1396 WaitForChannelReady(channel.get());
1397 WaitForServer(DEBUG_LOCATION, stub, 1);
1398 }
1399
1400 TEST_F(PickFirstTest, StaysIdleUponEmptyUpdate) {
1401 // Start server, send RPC, and make sure channel is READY.
1402 const int kNumServers = 1;
1403 StartServers(kNumServers);
1404 auto response_generator = BuildResolverResponseGenerator();
1405 auto channel =
1406 BuildChannel("", response_generator); // pick_first is the default.
1407 auto stub = BuildStub(channel);
1408 response_generator.SetNextResolution(GetServersPorts());
1409 CheckRpcSendOk(DEBUG_LOCATION, stub);
1410 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
1411 // Stop server. Channel should go into state IDLE.
1412 servers_[0]->Shutdown();
1413 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
1414 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
1415 // Now send resolver update that includes no addresses. Channel
1416 // should stay in state IDLE.
1417 response_generator.SetNextResolution({});
1418 EXPECT_FALSE(channel->WaitForStateChange(
1419 GRPC_CHANNEL_IDLE, grpc_timeout_seconds_to_deadline(3)));
1420 // Now bring the backend back up and send a non-empty resolver update,
1421 // and then try to send an RPC. Channel should go back into state READY.
1422 StartServer(0);
1423 response_generator.SetNextResolution(GetServersPorts());
1424 CheckRpcSendOk(DEBUG_LOCATION, stub);
1425 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
1426 }
1427
1428 TEST_F(PickFirstTest,
1429 StaysTransientFailureOnFailedConnectionAttemptUntilReady) {
1430 // Allocate 3 ports, with no servers running.
1431 std::vector<int> ports = {grpc_pick_unused_port_or_die(),
1432 grpc_pick_unused_port_or_die(),
1433 grpc_pick_unused_port_or_die()};
1434 // Create channel with a 1-second backoff.
1435 ChannelArguments args;
1436 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS,
1437 1000 * grpc_test_slowdown_factor());
1438 auto response_generator = BuildResolverResponseGenerator();
1439 auto channel = BuildChannel("", response_generator, args);
1440 auto stub = BuildStub(channel);
1441 response_generator.SetNextResolution(ports);
1442 EXPECT_EQ(GRPC_CHANNEL_IDLE, channel->GetState(false));
1443 // Send an RPC, which should fail.
1444 CheckRpcSendFailure(
1445 DEBUG_LOCATION, stub, StatusCode::UNAVAILABLE,
1446 MakeConnectionFailureRegex("failed to connect to all addresses"));
1447 // Channel should be in TRANSIENT_FAILURE.
1448 EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel->GetState(false));
1449 // Now start a server on the last port.
1450 StartServers(1, {ports.back()});
1451 // Channel should remain in TRANSIENT_FAILURE until it transitions to READY.
1452 EXPECT_TRUE(channel->WaitForStateChange(GRPC_CHANNEL_TRANSIENT_FAILURE,
1453 grpc_timeout_seconds_to_deadline(4)));
1454 EXPECT_EQ(GRPC_CHANNEL_READY, channel->GetState(false));
1455 CheckRpcSendOk(DEBUG_LOCATION, stub);
1456 }
1457
1458 //
1459 // round_robin tests
1460 //
1461
1462 using RoundRobinTest = ClientLbEnd2endTest;
1463
1464 TEST_F(RoundRobinTest, Basic) {
1465 // Start servers and send one RPC per server.
1466 const int kNumServers = 3;
1467 StartServers(kNumServers);
1468 auto response_generator = BuildResolverResponseGenerator();
1469 auto channel = BuildChannel("round_robin", response_generator);
1470 auto stub = BuildStub(channel);
1471 response_generator.SetNextResolution(GetServersPorts());
1472 // Wait until all backends are ready.
1473 do {
1474 CheckRpcSendOk(DEBUG_LOCATION, stub);
1475 } while (!SeenAllServers());
1476 ResetCounters();
1477 // "Sync" to the end of the list. Next sequence of picks will start at the
1478 // first server (index 0).
1479 WaitForServer(DEBUG_LOCATION, stub, servers_.size() - 1);
1480 std::vector<int> connection_order;
1481 for (size_t i = 0; i < servers_.size(); ++i) {
1482 CheckRpcSendOk(DEBUG_LOCATION, stub);
1483 UpdateConnectionOrder(servers_, &connection_order);
1484 }
1485 // Backends should be iterated over in the order in which the addresses were
1486 // given.
1487 const auto expected = std::vector<int>{0, 1, 2};
1488 EXPECT_EQ(expected, connection_order);
1489 // Check LB policy name for the channel.
1490 EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
1491 }
1492
1493 TEST_F(RoundRobinTest, ProcessPending) {
1494 StartServers(1); // Single server
1495 auto response_generator = BuildResolverResponseGenerator();
1496 auto channel = BuildChannel("round_robin", response_generator);
1497 auto stub = BuildStub(channel);
1498 response_generator.SetNextResolution({servers_[0]->port_});
1499 WaitForServer(DEBUG_LOCATION, stub, 0);
1500 // Create a new channel and its corresponding RR LB policy, which will pick
1501 // the subchannels in READY state from the previous RPC against the same
1502 // target (even if it happened over a different channel, because subchannels
1503 // are globally reused). Progress should happen without any transition from
1504 // this READY state.
1505 auto second_response_generator = BuildResolverResponseGenerator();
1506 auto second_channel = BuildChannel("round_robin", second_response_generator);
1507 auto second_stub = BuildStub(second_channel);
1508 second_response_generator.SetNextResolution({servers_[0]->port_});
1509 CheckRpcSendOk(DEBUG_LOCATION, second_stub);
1510 }
1511
1512 TEST_F(RoundRobinTest, Updates) {
1513 // Start servers.
1514 const int kNumServers = 3;
1515 StartServers(kNumServers);
1516 auto response_generator = BuildResolverResponseGenerator();
1517 auto channel = BuildChannel("round_robin", response_generator);
1518 auto stub = BuildStub(channel);
1519 // Start with a single server.
1520 gpr_log(GPR_INFO, "*** FIRST BACKEND ***");
1521 std::vector<int> ports = {servers_[0]->port_};
1522 response_generator.SetNextResolution(ports);
1523 WaitForServer(DEBUG_LOCATION, stub, 0);
1524 // Send RPCs. They should all go servers_[0]
1525 for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(DEBUG_LOCATION, stub);
1526 EXPECT_EQ(10, servers_[0]->service_.request_count());
1527 EXPECT_EQ(0, servers_[1]->service_.request_count());
1528 EXPECT_EQ(0, servers_[2]->service_.request_count());
1529 ResetCounters();
1530 // And now for the second server.
1531 gpr_log(GPR_INFO, "*** SECOND BACKEND ***");
1532 ports.clear();
1533 ports.emplace_back(servers_[1]->port_);
1534 response_generator.SetNextResolution(ports);
1535 // Wait until update has been processed, as signaled by the second backend
1536 // receiving a request.
1537 EXPECT_EQ(0, servers_[1]->service_.request_count());
1538 WaitForServer(DEBUG_LOCATION, stub, 1);
1539 for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(DEBUG_LOCATION, stub);
1540 EXPECT_EQ(0, servers_[0]->service_.request_count());
1541 EXPECT_EQ(10, servers_[1]->service_.request_count());
1542 EXPECT_EQ(0, servers_[2]->service_.request_count());
1543 ResetCounters();
1544 // ... and for the last server.
1545 gpr_log(GPR_INFO, "*** THIRD BACKEND ***");
1546 ports.clear();
1547 ports.emplace_back(servers_[2]->port_);
1548 response_generator.SetNextResolution(ports);
1549 WaitForServer(DEBUG_LOCATION, stub, 2);
1550 for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(DEBUG_LOCATION, stub);
1551 EXPECT_EQ(0, servers_[0]->service_.request_count());
1552 EXPECT_EQ(0, servers_[1]->service_.request_count());
1553 EXPECT_EQ(10, servers_[2]->service_.request_count());
1554 ResetCounters();
1555 // Back to all servers.
1556 gpr_log(GPR_INFO, "*** ALL BACKENDS ***");
1557 ports.clear();
1558 ports.emplace_back(servers_[0]->port_);
1559 ports.emplace_back(servers_[1]->port_);
1560 ports.emplace_back(servers_[2]->port_);
1561 response_generator.SetNextResolution(ports);
1562 WaitForServers(DEBUG_LOCATION, stub);
1563 // Send three RPCs, one per server.
1564 for (size_t i = 0; i < 3; ++i) CheckRpcSendOk(DEBUG_LOCATION, stub);
1565 EXPECT_EQ(1, servers_[0]->service_.request_count());
1566 EXPECT_EQ(1, servers_[1]->service_.request_count());
1567 EXPECT_EQ(1, servers_[2]->service_.request_count());
1568 ResetCounters();
1569 // An empty update will result in the channel going into TRANSIENT_FAILURE.
1570 gpr_log(GPR_INFO, "*** NO BACKENDS ***");
1571 ports.clear();
1572 response_generator.SetNextResolution(ports);
1573 WaitForChannelNotReady(channel.get());
1574 CheckRpcSendFailure(DEBUG_LOCATION, stub, StatusCode::UNAVAILABLE,
1575 "empty address list: fake resolver empty address list");
1576 servers_[0]->service_.ResetCounters();
1577 // Next update introduces servers_[1], making the channel recover.
1578 gpr_log(GPR_INFO, "*** BACK TO SECOND BACKEND ***");
1579 ports.clear();
1580 ports.emplace_back(servers_[1]->port_);
1581 response_generator.SetNextResolution(ports);
1582 WaitForServer(DEBUG_LOCATION, stub, 1);
1583 EXPECT_EQ(GRPC_CHANNEL_READY, channel->GetState(/*try_to_connect=*/false));
1584 // Check LB policy name for the channel.
1585 EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
1586 }
1587
1588 TEST_F(RoundRobinTest, UpdateInError) {
1589 StartServers(2);
1590 auto response_generator = BuildResolverResponseGenerator();
1591 auto channel = BuildChannel("round_robin", response_generator);
1592 auto stub = BuildStub(channel);
1593 // Start with a single server.
1594 response_generator.SetNextResolution(GetServersPorts(0, 1));
1595 // Send RPCs. They should all go to server 0.
1596 for (size_t i = 0; i < 10; ++i) {
1597 CheckRpcSendOk(DEBUG_LOCATION, stub, /*wait_for_ready=*/false,
1598 /*load_report=*/nullptr, /*timeout_ms=*/4000);
1599 }
1600 EXPECT_EQ(10, servers_[0]->service_.request_count());
1601 EXPECT_EQ(0, servers_[1]->service_.request_count());
1602 servers_[0]->service_.ResetCounters();
1603 // Send an update adding an unreachable server and server 1.
1604 std::vector<int> ports = {servers_[0]->port_, grpc_pick_unused_port_or_die(),
1605 servers_[1]->port_};
1606 response_generator.SetNextResolution(ports);
1607 WaitForServers(DEBUG_LOCATION, stub, 0, 2, /*status_check=*/nullptr,
1608 /*timeout=*/absl::Seconds(60));
1609 // Send a bunch more RPCs. They should all succeed and should be
1610 // split evenly between the two servers.
1611 // Note: The split may be slightly uneven because of an extra picker
1612 // update that can happen if the subchannels for servers 0 and 1
1613 // report READY before the subchannel for the unreachable server
1614 // transitions from CONNECTING to TRANSIENT_FAILURE.
1615 for (size_t i = 0; i < 10; ++i) {
1616 CheckRpcSendOk(DEBUG_LOCATION, stub, /*wait_for_ready=*/false,
1617 /*load_report=*/nullptr, /*timeout_ms=*/4000);
1618 }
1619 EXPECT_THAT(servers_[0]->service_.request_count(),
1620 ::testing::AllOf(::testing::Ge(4), ::testing::Le(6)));
1621 EXPECT_THAT(servers_[1]->service_.request_count(),
1622 ::testing::AllOf(::testing::Ge(4), ::testing::Le(6)));
1623 EXPECT_EQ(10, servers_[0]->service_.request_count() +
1624 servers_[1]->service_.request_count());
1625 }
1626
1627 TEST_F(RoundRobinTest, ManyUpdates) {
1628 // Start servers and send one RPC per server.
1629 const int kNumServers = 3;
1630 StartServers(kNumServers);
1631 auto response_generator = BuildResolverResponseGenerator();
1632 auto channel = BuildChannel("round_robin", response_generator);
1633 auto stub = BuildStub(channel);
1634 std::vector<int> ports = GetServersPorts();
1635 for (size_t i = 0; i < 1000; ++i) {
1636 std::shuffle(ports.begin(), ports.end(),
1637 std::mt19937(std::random_device()()));
1638 response_generator.SetNextResolution(ports);
1639 if (i % 10 == 0) CheckRpcSendOk(DEBUG_LOCATION, stub);
1640 }
1641 // Check LB policy name for the channel.
1642 EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
1643 }
1644
1645 TEST_F(RoundRobinTest, ReresolveOnSubchannelConnectionFailure) {
1646 // Start 3 servers.
1647 StartServers(3);
1648 // Create channel.
1649 auto response_generator = BuildResolverResponseGenerator();
1650 auto channel = BuildChannel("round_robin", response_generator);
1651 auto stub = BuildStub(channel);
1652 // Initially, tell the channel about only the first two servers.
1653 std::vector<int> ports = {servers_[0]->port_, servers_[1]->port_};
1654 response_generator.SetNextResolution(ports);
1655 // Wait for both servers to be seen.
1656 WaitForServers(DEBUG_LOCATION, stub, 0, 2);
1657 // Tell the fake resolver to send an update that adds the last server, but
1658 // only when the LB policy requests re-resolution.
1659 ports.push_back(servers_[2]->port_);
1660 response_generator.SetNextResolutionUponError(ports);
1661 // Have server 0 send a GOAWAY. This should trigger a re-resolution.
1662 gpr_log(GPR_INFO, "****** SENDING GOAWAY FROM SERVER 0 *******");
1663 {
1664 grpc_core::ExecCtx exec_ctx;
1665 grpc_core::Server::FromC(servers_[0]->server_->c_server())->SendGoaways();
1666 }
1667 // Wait for the client to see server 2.
1668 WaitForServer(DEBUG_LOCATION, stub, 2);
1669 }
1670
1671 TEST_F(RoundRobinTest, FailsEmptyResolverUpdate) {
1672 auto response_generator = BuildResolverResponseGenerator();
1673 auto channel = BuildChannel("round_robin", response_generator);
1674 auto stub = BuildStub(channel);
1675 gpr_log(GPR_INFO, "****** SENDING INITIAL RESOLVER RESULT *******");
1676 // Send a resolver result with an empty address list and a callback
1677 // that triggers a notification.
1678 grpc_core::Notification notification;
1679 grpc_core::Resolver::Result result;
1680 result.addresses.emplace();
1681 result.resolution_note = "injected error";
1682 result.result_health_callback = [&](absl::Status status) {
1683 EXPECT_EQ(absl::StatusCode::kUnavailable, status.code());
1684 EXPECT_EQ("empty address list: injected error", status.message()) << status;
1685 notification.Notify();
1686 };
1687 response_generator.SetResponse(std::move(result));
1688 // Wait for channel to report TRANSIENT_FAILURE.
1689 gpr_log(GPR_INFO, "****** TELLING CHANNEL TO CONNECT *******");
1690 auto predicate = [](grpc_connectivity_state state) {
1691 return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
1692 };
1693 EXPECT_TRUE(
1694 WaitForChannelState(channel.get(), predicate, /*try_to_connect=*/true));
1695 // Callback should have been run.
1696 ASSERT_TRUE(notification.HasBeenNotified());
1697 // Return a valid address.
1698 gpr_log(GPR_INFO, "****** SENDING NEXT RESOLVER RESULT *******");
1699 StartServers(1);
1700 response_generator.SetNextResolution(GetServersPorts());
1701 gpr_log(GPR_INFO, "****** SENDING WAIT_FOR_READY RPC *******");
1702 CheckRpcSendOk(DEBUG_LOCATION, stub, /*wait_for_ready=*/true);
1703 }
1704
1705 TEST_F(RoundRobinTest, TransientFailure) {
1706 // Start servers and create channel. Channel should go to READY state.
1707 const int kNumServers = 3;
1708 StartServers(kNumServers);
1709 auto response_generator = BuildResolverResponseGenerator();
1710 auto channel = BuildChannel("round_robin", response_generator);
1711 auto stub = BuildStub(channel);
1712 response_generator.SetNextResolution(GetServersPorts());
1713 EXPECT_TRUE(WaitForChannelReady(channel.get()));
1714 // Now kill the servers. The channel should transition to TRANSIENT_FAILURE.
1715 for (size_t i = 0; i < servers_.size(); ++i) {
1716 servers_[i]->Shutdown();
1717 }
1718 auto predicate = [](grpc_connectivity_state state) {
1719 return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
1720 };
1721 EXPECT_TRUE(WaitForChannelState(channel.get(), predicate));
1722 CheckRpcSendFailure(
1723 DEBUG_LOCATION, stub, StatusCode::UNAVAILABLE,
1724 MakeConnectionFailureRegex("connections to all backends failing"));
1725 }
1726
1727 TEST_F(RoundRobinTest, TransientFailureAtStartup) {
1728 // Create channel and return servers that don't exist. Channel should
1729 // quickly transition into TRANSIENT_FAILURE.
1730 auto response_generator = BuildResolverResponseGenerator();
1731 auto channel = BuildChannel("round_robin", response_generator);
1732 auto stub = BuildStub(channel);
1733 response_generator.SetNextResolution({
1734 grpc_pick_unused_port_or_die(),
1735 grpc_pick_unused_port_or_die(),
1736 grpc_pick_unused_port_or_die(),
1737 });
1738 for (size_t i = 0; i < servers_.size(); ++i) {
1739 servers_[i]->Shutdown();
1740 }
1741 auto predicate = [](grpc_connectivity_state state) {
1742 return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
1743 };
1744 EXPECT_TRUE(WaitForChannelState(channel.get(), predicate, true));
1745 CheckRpcSendFailure(
1746 DEBUG_LOCATION, stub, StatusCode::UNAVAILABLE,
1747 MakeConnectionFailureRegex("connections to all backends failing"));
1748 }
1749
1750 TEST_F(RoundRobinTest, StaysInTransientFailureInSubsequentConnecting) {
1751 // Start connection injector.
1752 ConnectionAttemptInjector injector;
1753 // Get port.
1754 const int port = grpc_pick_unused_port_or_die();
1755 // Create channel.
1756 auto response_generator = BuildResolverResponseGenerator();
1757 auto channel = BuildChannel("round_robin", response_generator);
1758 auto stub = BuildStub(channel);
1759 response_generator.SetNextResolution({port});
1760 // Allow first connection attempt to fail normally, and wait for
1761 // channel to report TRANSIENT_FAILURE.
1762 gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL TO REPORT TF ===");
1763 auto predicate = [](grpc_connectivity_state state) {
1764 return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
1765 };
1766 EXPECT_TRUE(
1767 WaitForChannelState(channel.get(), predicate, /*try_to_connect=*/true));
1768 // Wait for next connection attempt to start.
1769 auto hold = injector.AddHold(port);
1770 hold->Wait();
1771 // Now the subchannel should be reporting CONNECTING. Make sure the
1772 // channel is still in TRANSIENT_FAILURE and is still reporting the
1773 // right status.
1774 EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel->GetState(false));
1775 // Send a few RPCs, just to give the channel a chance to propagate a
1776 // new picker, in case it was going to incorrectly do so.
1777 gpr_log(GPR_INFO, "=== EXPECTING RPCs TO FAIL ===");
1778 for (size_t i = 0; i < 5; ++i) {
1779 CheckRpcSendFailure(
1780 DEBUG_LOCATION, stub, StatusCode::UNAVAILABLE,
1781 MakeConnectionFailureRegex("connections to all backends failing"));
1782 }
1783 // Clean up.
1784 hold->Resume();
1785 }
1786
1787 TEST_F(RoundRobinTest, ReportsLatestStatusInTransientFailure) {
1788 // Start connection injector.
1789 ConnectionAttemptInjector injector;
1790 // Get port.
1791 const std::vector<int> ports = {grpc_pick_unused_port_or_die(),
1792 grpc_pick_unused_port_or_die()};
1793 // Create channel.
1794 auto response_generator = BuildResolverResponseGenerator();
1795 auto channel = BuildChannel("round_robin", response_generator);
1796 auto stub = BuildStub(channel);
1797 response_generator.SetNextResolution(ports);
1798 // Allow first connection attempts to fail normally, and check that
1799 // the RPC fails with the right status message.
1800 CheckRpcSendFailure(
1801 DEBUG_LOCATION, stub, StatusCode::UNAVAILABLE,
1802 MakeConnectionFailureRegex("connections to all backends failing"));
1803 // Now intercept the next connection attempt for each port.
1804 auto hold1 = injector.AddHold(ports[0]);
1805 auto hold2 = injector.AddHold(ports[1]);
1806 hold1->Wait();
1807 hold2->Wait();
1808 // Inject a custom failure message.
1809 hold1->Wait();
1810 hold1->Fail(GRPC_ERROR_CREATE("Survey says... Bzzzzt!"));
1811 // Wait until RPC fails with the right message.
1812 absl::Time deadline =
1813 absl::Now() + (absl::Seconds(5) * grpc_test_slowdown_factor());
1814 while (true) {
1815 Status status = SendRpc(stub);
1816 EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
1817 if (::testing::Matches(::testing::MatchesRegex(
1818 "connections to all backends failing; last error: "
1819 "UNKNOWN: (ipv6:%5B::1%5D|ipv4:127.0.0.1):[0-9]+: "
1820 "Survey says... Bzzzzt!"))(status.error_message())) {
1821 break;
1822 }
1823 EXPECT_THAT(status.error_message(),
1824 ::testing::MatchesRegex(MakeConnectionFailureRegex(
1825 "connections to all backends failing")));
1826 EXPECT_LT(absl::Now(), deadline);
1827 if (absl::Now() >= deadline) break;
1828 }
1829 // Clean up.
1830 hold2->Resume();
1831 }
1832
1833 TEST_F(RoundRobinTest, DoesNotFailRpcsUponDisconnection) {
1834 // Start connection injector.
1835 ConnectionAttemptInjector injector;
1836 // Start server.
1837 StartServers(1);
1838 // Create channel.
1839 auto response_generator = BuildResolverResponseGenerator();
1840 auto channel = BuildChannel("round_robin", response_generator);
1841 auto stub = BuildStub(channel);
1842 response_generator.SetNextResolution(GetServersPorts());
1843 // Start a thread constantly sending RPCs in a loop.
1844 gpr_log(GPR_ERROR, "=== STARTING CLIENT THREAD ===");
1845 std::atomic<bool> shutdown{false};
1846 gpr_event ev;
1847 gpr_event_init(&ev);
1848 std::thread thd([&]() {
1849 gpr_log(GPR_INFO, "sending first RPC");
1850 CheckRpcSendOk(DEBUG_LOCATION, stub);
1851 gpr_event_set(&ev, reinterpret_cast<void*>(1));
1852 while (!shutdown.load()) {
1853 gpr_log(GPR_INFO, "sending RPC");
1854 CheckRpcSendOk(DEBUG_LOCATION, stub);
1855 }
1856 });
1857 // Wait for first RPC to complete.
1858 gpr_log(GPR_ERROR, "=== WAITING FOR FIRST RPC TO COMPLETE ===");
1859 ASSERT_EQ(reinterpret_cast<void*>(1),
1860 gpr_event_wait(&ev, grpc_timeout_seconds_to_deadline(1)));
1861 // Channel should now be READY.
1862 ASSERT_EQ(GRPC_CHANNEL_READY, channel->GetState(false));
1863 // Tell injector to intercept the next connection attempt.
1864 auto hold1 =
1865 injector.AddHold(servers_[0]->port_, /*intercept_completion=*/true);
1866 // Now kill the server. The subchannel should report IDLE and be
1867 // immediately reconnected to, but this should not cause any test
1868 // failures.
1869 gpr_log(GPR_ERROR, "=== SHUTTING DOWN SERVER ===");
1870 {
1871 grpc_core::ExecCtx exec_ctx;
1872 grpc_core::Server::FromC(servers_[0]->server_->c_server())->SendGoaways();
1873 }
1874 gpr_sleep_until(grpc_timeout_seconds_to_deadline(1));
1875 servers_[0]->Shutdown();
1876 // Wait for next attempt to start.
1877 gpr_log(GPR_ERROR, "=== WAITING FOR RECONNECTION ATTEMPT ===");
1878 hold1->Wait();
1879 // Start server and allow attempt to continue.
1880 gpr_log(GPR_ERROR, "=== RESTARTING SERVER ===");
1881 StartServer(0);
1882 hold1->Resume();
1883 // Wait for next attempt to complete.
1884 gpr_log(GPR_ERROR, "=== WAITING FOR RECONNECTION ATTEMPT TO COMPLETE ===");
1885 hold1->WaitForCompletion();
1886 // Now shut down the thread.
1887 gpr_log(GPR_ERROR, "=== SHUTTING DOWN CLIENT THREAD ===");
1888 shutdown.store(true);
1889 thd.join();
1890 }
1891
1892 TEST_F(RoundRobinTest, SingleReconnect) {
1893 const int kNumServers = 3;
1894 StartServers(kNumServers);
1895 const auto ports = GetServersPorts();
1896 auto response_generator = BuildResolverResponseGenerator();
1897 auto channel = BuildChannel("round_robin", response_generator);
1898 auto stub = BuildStub(channel);
1899 response_generator.SetNextResolution(ports);
1900 WaitForServers(DEBUG_LOCATION, stub);
1901 // Sync to end of list.
1902 WaitForServer(DEBUG_LOCATION, stub, servers_.size() - 1);
1903 for (size_t i = 0; i < servers_.size(); ++i) {
1904 CheckRpcSendOk(DEBUG_LOCATION, stub);
1905 EXPECT_EQ(1, servers_[i]->service_.request_count()) << "for backend #" << i;
1906 }
1907 // One request should have gone to each server.
1908 for (size_t i = 0; i < servers_.size(); ++i) {
1909 EXPECT_EQ(1, servers_[i]->service_.request_count());
1910 }
1911 // Kill the first server.
1912 servers_[0]->StopListeningAndSendGoaways();
1913 // Wait for client to notice that the backend is down. We know that's
1914 // happened when we see kNumServers RPCs that do not go to backend 0.
1915 ResetCounters();
1916 SendRpcsUntil(DEBUG_LOCATION, stub,
1917 [&, num_rpcs_not_on_backend_0 = 0](Status status) mutable {
1918 EXPECT_TRUE(status.ok())
1919 << "code=" << status.error_code()
1920 << " message=" << status.error_message();
1921 if (servers_[0]->service_.request_count() == 1) {
1922 num_rpcs_not_on_backend_0 = 0;
1923 } else {
1924 ++num_rpcs_not_on_backend_0;
1925 }
1926 ResetCounters();
1927 return num_rpcs_not_on_backend_0 < kNumServers;
1928 });
1929 // Send a bunch of RPCs.
1930 for (int i = 0; i < 10 * kNumServers; ++i) {
1931 CheckRpcSendOk(DEBUG_LOCATION, stub);
1932 }
1933 // No requests have gone to the deceased server.
1934 EXPECT_EQ(0UL, servers_[0]->service_.request_count());
1935 // Bring the first server back up.
1936 servers_[0]->Shutdown();
1937 StartServer(0);
1938 // Requests should start arriving at the first server either right away (if
1939 // the server managed to start before the RR policy retried the subchannel) or
1940 // after the subchannel retry delay otherwise (RR's subchannel retried before
1941 // the server was fully back up).
1942 WaitForServer(DEBUG_LOCATION, stub, 0);
1943 }
1944
1945 // If health checking is required by client but health checking service
1946 // is not running on the server, the channel should be treated as healthy.
1947 TEST_F(RoundRobinTest, ServersHealthCheckingUnimplementedTreatedAsHealthy) {
1948 StartServers(1); // Single server
1949 ChannelArguments args;
1950 args.SetServiceConfigJSON(
1951 "{\"healthCheckConfig\": "
1952 "{\"serviceName\": \"health_check_service_name\"}}");
1953 auto response_generator = BuildResolverResponseGenerator();
1954 auto channel = BuildChannel("round_robin", response_generator, args);
1955 auto stub = BuildStub(channel);
1956 response_generator.SetNextResolution({servers_[0]->port_});
1957 EXPECT_TRUE(WaitForChannelReady(channel.get()));
1958 CheckRpcSendOk(DEBUG_LOCATION, stub);
1959 }
1960
1961 TEST_F(RoundRobinTest, HealthChecking) {
1962 EnableDefaultHealthCheckService(true);
1963 // Start servers.
1964 const int kNumServers = 3;
1965 StartServers(kNumServers);
1966 ChannelArguments args;
1967 args.SetServiceConfigJSON(
1968 "{\"healthCheckConfig\": "
1969 "{\"serviceName\": \"health_check_service_name\"}}");
1970 auto response_generator = BuildResolverResponseGenerator();
1971 auto channel = BuildChannel("round_robin", response_generator, args);
1972 auto stub = BuildStub(channel);
1973 response_generator.SetNextResolution(GetServersPorts());
1974 // Channel should not become READY, because health checks should be failing.
1975 gpr_log(GPR_INFO,
1976 "*** initial state: unknown health check service name for "
1977 "all servers");
1978 EXPECT_FALSE(WaitForChannelReady(channel.get(), 1));
1979 // Now set one of the servers to be healthy.
1980 // The channel should become healthy and all requests should go to
1981 // the healthy server.
1982 gpr_log(GPR_INFO, "*** server 0 healthy");
1983 servers_[0]->SetServingStatus("health_check_service_name", true);
1984 EXPECT_TRUE(WaitForChannelReady(channel.get()));
1985 for (int i = 0; i < 10; ++i) {
1986 CheckRpcSendOk(DEBUG_LOCATION, stub);
1987 }
1988 EXPECT_EQ(10, servers_[0]->service_.request_count());
1989 EXPECT_EQ(0, servers_[1]->service_.request_count());
1990 EXPECT_EQ(0, servers_[2]->service_.request_count());
1991 // Now set a second server to be healthy.
1992 gpr_log(GPR_INFO, "*** server 2 healthy");
1993 servers_[2]->SetServingStatus("health_check_service_name", true);
1994 WaitForServer(DEBUG_LOCATION, stub, 2);
1995 for (int i = 0; i < 10; ++i) {
1996 CheckRpcSendOk(DEBUG_LOCATION, stub);
1997 }
1998 EXPECT_EQ(5, servers_[0]->service_.request_count());
1999 EXPECT_EQ(0, servers_[1]->service_.request_count());
2000 EXPECT_EQ(5, servers_[2]->service_.request_count());
2001 // Now set the remaining server to be healthy.
2002 gpr_log(GPR_INFO, "*** server 1 healthy");
2003 servers_[1]->SetServingStatus("health_check_service_name", true);
2004 WaitForServer(DEBUG_LOCATION, stub, 1);
2005 for (int i = 0; i < 9; ++i) {
2006 CheckRpcSendOk(DEBUG_LOCATION, stub);
2007 }
2008 EXPECT_EQ(3, servers_[0]->service_.request_count());
2009 EXPECT_EQ(3, servers_[1]->service_.request_count());
2010 EXPECT_EQ(3, servers_[2]->service_.request_count());
2011 // Now set one server to be unhealthy again. Then wait until the
2012 // unhealthiness has hit the client. We know that the client will see
2013 // this when we send kNumServers requests and one of the remaining servers
2014 // sees two of the requests.
2015 gpr_log(GPR_INFO, "*** server 0 unhealthy");
2016 servers_[0]->SetServingStatus("health_check_service_name", false);
2017 do {
2018 ResetCounters();
2019 for (int i = 0; i < kNumServers; ++i) {
2020 CheckRpcSendOk(DEBUG_LOCATION, stub);
2021 }
2022 } while (servers_[1]->service_.request_count() != 2 &&
2023 servers_[2]->service_.request_count() != 2);
2024 // Now set the remaining two servers to be unhealthy. Make sure the
2025 // channel leaves READY state and that RPCs fail.
2026 gpr_log(GPR_INFO, "*** all servers unhealthy");
2027 servers_[1]->SetServingStatus("health_check_service_name", false);
2028 servers_[2]->SetServingStatus("health_check_service_name", false);
2029 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
2030 CheckRpcSendFailure(DEBUG_LOCATION, stub, StatusCode::UNAVAILABLE,
2031 "connections to all backends failing; last error: "
2032 "UNAVAILABLE: backend unhealthy");
2033 // Clean up.
2034 EnableDefaultHealthCheckService(false);
2035 }
2036
2037 TEST_F(RoundRobinTest, HealthCheckingHandlesSubchannelFailure) {
2038 EnableDefaultHealthCheckService(true);
2039 // Start servers.
2040 const int kNumServers = 3;
2041 StartServers(kNumServers);
2042 servers_[0]->SetServingStatus("health_check_service_name", true);
2043 servers_[1]->SetServingStatus("health_check_service_name", true);
2044 servers_[2]->SetServingStatus("health_check_service_name", true);
2045 ChannelArguments args;
2046 args.SetServiceConfigJSON(
2047 "{\"healthCheckConfig\": "
2048 "{\"serviceName\": \"health_check_service_name\"}}");
2049 auto response_generator = BuildResolverResponseGenerator();
2050 auto channel = BuildChannel("round_robin", response_generator, args);
2051 auto stub = BuildStub(channel);
2052 response_generator.SetNextResolution(GetServersPorts());
2053 WaitForServer(DEBUG_LOCATION, stub, 0);
2054 // Stop server 0 and send a new resolver result to ensure that RR
2055 // checks each subchannel's state.
2056 servers_[0]->StopListeningAndSendGoaways();
2057 response_generator.SetNextResolution(GetServersPorts());
2058 // Send a bunch more RPCs.
2059 for (size_t i = 0; i < 100; i++) {
2060 CheckRpcSendOk(DEBUG_LOCATION, stub);
2061 }
2062 }
2063
2064 TEST_F(RoundRobinTest, WithHealthCheckingInhibitPerChannel) {
2065 EnableDefaultHealthCheckService(true);
2066 // Start server.
2067 const int kNumServers = 1;
2068 StartServers(kNumServers);
2069 // Create a channel with health-checking enabled.
2070 ChannelArguments args;
2071 args.SetServiceConfigJSON(
2072 "{\"healthCheckConfig\": "
2073 "{\"serviceName\": \"health_check_service_name\"}}");
2074 auto response_generator1 = BuildResolverResponseGenerator();
2075 auto channel1 = BuildChannel("round_robin", response_generator1, args);
2076 auto stub1 = BuildStub(channel1);
2077 std::vector<int> ports = GetServersPorts();
2078 response_generator1.SetNextResolution(ports);
2079 // Create a channel with health checking enabled but inhibited.
2080 args.SetInt(GRPC_ARG_INHIBIT_HEALTH_CHECKING, 1);
2081 auto response_generator2 = BuildResolverResponseGenerator();
2082 auto channel2 = BuildChannel("round_robin", response_generator2, args);
2083 auto stub2 = BuildStub(channel2);
2084 response_generator2.SetNextResolution(ports);
2085 // First channel should not become READY, because health checks should be
2086 // failing.
2087 EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
2088 CheckRpcSendFailure(DEBUG_LOCATION, stub1, StatusCode::UNAVAILABLE,
2089 "connections to all backends failing; last error: "
2090 "UNAVAILABLE: backend unhealthy");
2091 // Second channel should be READY.
2092 EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
2093 CheckRpcSendOk(DEBUG_LOCATION, stub2);
2094 // Enable health checks on the backend and wait for channel 1 to succeed.
2095 servers_[0]->SetServingStatus("health_check_service_name", true);
2096 CheckRpcSendOk(DEBUG_LOCATION, stub1, true /* wait_for_ready */);
2097 // Check that we created only one subchannel to the backend.
2098 EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
2099 // Clean up.
2100 EnableDefaultHealthCheckService(false);
2101 }
2102
2103 TEST_F(RoundRobinTest, HealthCheckingServiceNamePerChannel) {
2104 EnableDefaultHealthCheckService(true);
2105 // Start server.
2106 const int kNumServers = 1;
2107 StartServers(kNumServers);
2108 // Create a channel with health-checking enabled.
2109 ChannelArguments args;
2110 args.SetServiceConfigJSON(
2111 "{\"healthCheckConfig\": "
2112 "{\"serviceName\": \"health_check_service_name\"}}");
2113 auto response_generator1 = BuildResolverResponseGenerator();
2114 auto channel1 = BuildChannel("round_robin", response_generator1, args);
2115 auto stub1 = BuildStub(channel1);
2116 std::vector<int> ports = GetServersPorts();
2117 response_generator1.SetNextResolution(ports);
2118 // Create a channel with health-checking enabled with a different
2119 // service name.
2120 ChannelArguments args2;
2121 args2.SetServiceConfigJSON(
2122 "{\"healthCheckConfig\": "
2123 "{\"serviceName\": \"health_check_service_name2\"}}");
2124 auto response_generator2 = BuildResolverResponseGenerator();
2125 auto channel2 = BuildChannel("round_robin", response_generator2, args2);
2126 auto stub2 = BuildStub(channel2);
2127 response_generator2.SetNextResolution(ports);
2128 // Allow health checks from channel 2 to succeed.
2129 servers_[0]->SetServingStatus("health_check_service_name2", true);
2130 // First channel should not become READY, because health checks should be
2131 // failing.
2132 EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
2133 CheckRpcSendFailure(DEBUG_LOCATION, stub1, StatusCode::UNAVAILABLE,
2134 "connections to all backends failing; last error: "
2135 "UNAVAILABLE: backend unhealthy");
2136 // Second channel should be READY.
2137 EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
2138 CheckRpcSendOk(DEBUG_LOCATION, stub2);
2139 // Enable health checks for channel 1 and wait for it to succeed.
2140 servers_[0]->SetServingStatus("health_check_service_name", true);
2141 CheckRpcSendOk(DEBUG_LOCATION, stub1, true /* wait_for_ready */);
2142 // Check that we created only one subchannel to the backend.
2143 EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
2144 // Clean up.
2145 EnableDefaultHealthCheckService(false);
2146 }
2147
2148 TEST_F(RoundRobinTest,
2149 HealthCheckingServiceNameChangesAfterSubchannelsCreated) {
2150 EnableDefaultHealthCheckService(true);
2151 // Start server.
2152 const int kNumServers = 1;
2153 StartServers(kNumServers);
2154 // Create a channel with health-checking enabled.
2155 const char* kServiceConfigJson =
2156 "{\"healthCheckConfig\": "
2157 "{\"serviceName\": \"health_check_service_name\"}}";
2158 auto response_generator = BuildResolverResponseGenerator();
2159 auto channel = BuildChannel("round_robin", response_generator);
2160 auto stub = BuildStub(channel);
2161 std::vector<int> ports = GetServersPorts();
2162 response_generator.SetNextResolution(ports, kServiceConfigJson);
2163 servers_[0]->SetServingStatus("health_check_service_name", true);
2164 EXPECT_TRUE(WaitForChannelReady(channel.get(), 1 /* timeout_seconds */));
2165 // Send an update on the channel to change it to use a health checking
2166 // service name that is not being reported as healthy.
2167 const char* kServiceConfigJson2 =
2168 "{\"healthCheckConfig\": "
2169 "{\"serviceName\": \"health_check_service_name2\"}}";
2170 response_generator.SetNextResolution(ports, kServiceConfigJson2);
2171 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
2172 // Clean up.
2173 EnableDefaultHealthCheckService(false);
2174 }
2175
2176 //
2177 // LB policy pick args
2178 //
2179
2180 class ClientLbPickArgsTest : public ClientLbEnd2endTest {
2181 protected:
2182 void SetUp() override {
2183 ClientLbEnd2endTest::SetUp();
2184 current_test_instance_ = this;
2185 }
2186
2187 static void SetUpTestCase() {
2188 grpc_core::CoreConfiguration::Reset();
2189 grpc_core::CoreConfiguration::RegisterBuilder(
2190 [](grpc_core::CoreConfiguration::Builder* builder) {
2191 grpc_core::RegisterTestPickArgsLoadBalancingPolicy(builder,
2192 SavePickArgs);
2193 });
2194 grpc_init();
2195 }
2196
2197 static void TearDownTestCase() {
2198 grpc_shutdown();
2199 grpc_core::CoreConfiguration::Reset();
2200 }
2201
2202 std::vector<grpc_core::PickArgsSeen> args_seen_list() {
2203 grpc_core::MutexLock lock(&mu_);
2204 return args_seen_list_;
2205 }
2206
2207 static std::string ArgsSeenListString(
2208 const std::vector<grpc_core::PickArgsSeen>& args_seen_list) {
2209 std::vector<std::string> entries;
2210 for (const auto& args_seen : args_seen_list) {
2211 std::vector<std::string> metadata;
2212 for (const auto& p : args_seen.metadata) {
2213 metadata.push_back(absl::StrCat(p.first, "=", p.second));
2214 }
2215 entries.push_back(absl::StrFormat("{path=\"%s\", metadata=[%s]}",
2216 args_seen.path,
2217 absl::StrJoin(metadata, ", ")));
2218 }
2219 return absl::StrCat("[", absl::StrJoin(entries, ", "), "]");
2220 }
2221
2222 private:
2223 static void SavePickArgs(const grpc_core::PickArgsSeen& args_seen) {
2224 ClientLbPickArgsTest* self = current_test_instance_;
2225 grpc_core::MutexLock lock(&self->mu_);
2226 self->args_seen_list_.emplace_back(args_seen);
2227 }
2228
2229 static ClientLbPickArgsTest* current_test_instance_;
2230 grpc_core::Mutex mu_;
2231 std::vector<grpc_core::PickArgsSeen> args_seen_list_;
2232 };
2233
2234 ClientLbPickArgsTest* ClientLbPickArgsTest::current_test_instance_ = nullptr;
2235
2236 TEST_F(ClientLbPickArgsTest, Basic) {
2237 const int kNumServers = 1;
2238 StartServers(kNumServers);
2239 auto response_generator = BuildResolverResponseGenerator();
2240 auto channel = BuildChannel("test_pick_args_lb", response_generator);
2241 auto stub = BuildStub(channel);
2242 response_generator.SetNextResolution(GetServersPorts());
2243 // Proactively connect the channel, so that the LB policy will always
2244 // be connected before it sees the pick. Otherwise, the test would be
2245 // flaky because sometimes the pick would be seen twice (once in
2246 // CONNECTING and again in READY) and other times only once (in READY).
2247 ASSERT_TRUE(channel->WaitForConnected(gpr_inf_future(GPR_CLOCK_MONOTONIC)));
2248 // Check LB policy name for the channel.
2249 EXPECT_EQ("test_pick_args_lb", channel->GetLoadBalancingPolicyName());
2250 // Now send an RPC and check that the picker sees the expected data.
2251 CheckRpcSendOk(DEBUG_LOCATION, stub, /*wait_for_ready=*/true);
2252 auto pick_args_seen_list = args_seen_list();
2253 EXPECT_THAT(pick_args_seen_list,
2254 ::testing::ElementsAre(::testing::AllOf(
2255 ::testing::Field(&grpc_core::PickArgsSeen::path,
2256 "/grpc.testing.EchoTestService/Echo"),
2257 ::testing::Field(&grpc_core::PickArgsSeen::metadata,
2258 ::testing::UnorderedElementsAre(
2259 ::testing::Pair("foo", "1"),
2260 ::testing::Pair("bar", "2"),
2261 ::testing::Pair("baz", "3"))))))
2262 << ArgsSeenListString(pick_args_seen_list);
2263 }
2264
2265 //
2266 // tests that LB policies can get the call's trailing metadata
2267 //
2268
2269 xds::data::orca::v3::OrcaLoadReport BackendMetricDataToOrcaLoadReport(
2270 const grpc_core::BackendMetricData& backend_metric_data) {
2271 xds::data::orca::v3::OrcaLoadReport load_report;
2272 load_report.set_cpu_utilization(backend_metric_data.cpu_utilization);
2273 load_report.set_mem_utilization(backend_metric_data.mem_utilization);
2274 for (const auto& p : backend_metric_data.request_cost) {
2275 std::string name(p.first);
2276 (*load_report.mutable_request_cost())[name] = p.second;
2277 }
2278 for (const auto& p : backend_metric_data.utilization) {
2279 std::string name(p.first);
2280 (*load_report.mutable_utilization())[name] = p.second;
2281 }
2282 return load_report;
2283 }
2284
2285 class ClientLbInterceptTrailingMetadataTest : public ClientLbEnd2endTest {
2286 protected:
2287 void SetUp() override {
2288 ClientLbEnd2endTest::SetUp();
2289 current_test_instance_ = this;
2290 }
2291
2292 static void SetUpTestCase() {
2293 grpc_core::CoreConfiguration::Reset();
2294 grpc_core::CoreConfiguration::RegisterBuilder(
2295 [](grpc_core::CoreConfiguration::Builder* builder) {
2296 grpc_core::RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
2297 builder, ReportTrailerIntercepted);
2298 });
2299 grpc_init();
2300 }
2301
2302 static void TearDownTestCase() {
2303 grpc_shutdown();
2304 grpc_core::CoreConfiguration::Reset();
2305 }
2306
2307 int num_trailers_intercepted() {
2308 grpc_core::MutexLock lock(&mu_);
2309 return num_trailers_intercepted_;
2310 }
2311
2312 absl::Status last_status() {
2313 grpc_core::MutexLock lock(&mu_);
2314 return last_status_;
2315 }
2316
2317 grpc_core::MetadataVector trailing_metadata() {
2318 grpc_core::MutexLock lock(&mu_);
2319 return std::move(trailing_metadata_);
2320 }
2321
2322 absl::optional<xds::data::orca::v3::OrcaLoadReport> backend_load_report() {
2323 grpc_core::MutexLock lock(&mu_);
2324 return std::move(load_report_);
2325 }
2326
2327 // Returns true if received callback within deadline.
2328 bool WaitForLbCallback() {
2329 grpc_core::MutexLock lock(&mu_);
2330 while (!trailer_intercepted_) {
2331 if (cond_.WaitWithTimeout(&mu_, absl::Seconds(3))) return false;
2332 }
2333 trailer_intercepted_ = false;
2334 return true;
2335 }
2336
2337 private:
2338 static void ReportTrailerIntercepted(
2339 const grpc_core::TrailingMetadataArgsSeen& args_seen) {
2340 const auto* backend_metric_data = args_seen.backend_metric_data;
2341 ClientLbInterceptTrailingMetadataTest* self = current_test_instance_;
2342 grpc_core::MutexLock lock(&self->mu_);
2343 self->last_status_ = args_seen.status;
2344 self->num_trailers_intercepted_++;
2345 self->trailer_intercepted_ = true;
2346 self->trailing_metadata_ = args_seen.metadata;
2347 if (backend_metric_data != nullptr) {
2348 self->load_report_ =
2349 BackendMetricDataToOrcaLoadReport(*backend_metric_data);
2350 }
2351 self->cond_.Signal();
2352 }
2353
2354 static ClientLbInterceptTrailingMetadataTest* current_test_instance_;
2355 int num_trailers_intercepted_ = 0;
2356 bool trailer_intercepted_ = false;
2357 grpc_core::Mutex mu_;
2358 grpc_core::CondVar cond_;
2359 absl::Status last_status_;
2360 grpc_core::MetadataVector trailing_metadata_;
2361 absl::optional<xds::data::orca::v3::OrcaLoadReport> load_report_;
2362 };
2363
2364 ClientLbInterceptTrailingMetadataTest*
2365 ClientLbInterceptTrailingMetadataTest::current_test_instance_ = nullptr;
2366
2367 TEST_F(ClientLbInterceptTrailingMetadataTest, StatusOk) {
2368 StartServers(1);
2369 auto response_generator = BuildResolverResponseGenerator();
2370 auto channel =
2371 BuildChannel("intercept_trailing_metadata_lb", response_generator);
2372 auto stub = BuildStub(channel);
2373 response_generator.SetNextResolution(GetServersPorts());
2374 // Send an OK RPC.
2375 CheckRpcSendOk(DEBUG_LOCATION, stub);
2376 // Check LB policy name for the channel.
2377 EXPECT_EQ("intercept_trailing_metadata_lb",
2378 channel->GetLoadBalancingPolicyName());
2379 EXPECT_EQ(1, num_trailers_intercepted());
2380 EXPECT_EQ(absl::OkStatus(), last_status());
2381 }
2382
2383 TEST_F(ClientLbInterceptTrailingMetadataTest, StatusFailed) {
2384 StartServers(1);
2385 auto response_generator = BuildResolverResponseGenerator();
2386 auto channel =
2387 BuildChannel("intercept_trailing_metadata_lb", response_generator);
2388 auto stub = BuildStub(channel);
2389 response_generator.SetNextResolution(GetServersPorts());
2390 EchoRequest request;
2391 auto* expected_error = request.mutable_param()->mutable_expected_error();
2392 expected_error->set_code(GRPC_STATUS_PERMISSION_DENIED);
2393 expected_error->set_error_message("bummer, man");
2394 Status status = SendRpc(stub, /*response=*/nullptr, /*timeout_ms=*/1000,
2395 /*wait_for_ready=*/false, &request);
2396 EXPECT_EQ(status.error_code(), StatusCode::PERMISSION_DENIED);
2397 EXPECT_EQ(status.error_message(), "bummer, man");
2398 absl::Status status_seen_by_lb = last_status();
2399 EXPECT_EQ(status_seen_by_lb.code(), absl::StatusCode::kPermissionDenied);
2400 EXPECT_EQ(status_seen_by_lb.message(), "bummer, man");
2401 }
2402
2403 TEST_F(ClientLbInterceptTrailingMetadataTest,
2404 StatusCancelledWithoutStartingRecvTrailingMetadata) {
2405 StartServers(1);
2406 auto response_generator = BuildResolverResponseGenerator();
2407 auto channel =
2408 BuildChannel("intercept_trailing_metadata_lb", response_generator);
2409 response_generator.SetNextResolution(GetServersPorts());
2410 auto stub = BuildStub(channel);
2411 {
2412 // Start a stream (sends initial metadata) and then cancel without
2413 // calling Finish().
2414 ClientContext ctx;
2415 auto stream = stub->BidiStream(&ctx);
2416 ctx.TryCancel();
2417 }
2418 // Wait for stream to be cancelled.
2419 ASSERT_TRUE(WaitForLbCallback());
2420 // Check status seen by LB policy.
2421 EXPECT_EQ(1, num_trailers_intercepted());
2422 absl::Status status_seen_by_lb = last_status();
2423 EXPECT_EQ(status_seen_by_lb.code(), absl::StatusCode::kCancelled);
2424 EXPECT_EQ(status_seen_by_lb.message(), "call cancelled");
2425 }
2426
2427 TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesDisabled) {
2428 const int kNumServers = 1;
2429 const int kNumRpcs = 10;
2430 StartServers(kNumServers);
2431 auto response_generator = BuildResolverResponseGenerator();
2432 ChannelArguments channel_args;
2433 channel_args.SetInt(GRPC_ARG_ENABLE_RETRIES, 0);
2434 auto channel = BuildChannel("intercept_trailing_metadata_lb",
2435 response_generator, channel_args);
2436 auto stub = BuildStub(channel);
2437 response_generator.SetNextResolution(GetServersPorts());
2438 for (size_t i = 0; i < kNumRpcs; ++i) {
2439 CheckRpcSendOk(DEBUG_LOCATION, stub);
2440 }
2441 // Check LB policy name for the channel.
2442 EXPECT_EQ("intercept_trailing_metadata_lb",
2443 channel->GetLoadBalancingPolicyName());
2444 EXPECT_EQ(kNumRpcs, num_trailers_intercepted());
2445 EXPECT_THAT(trailing_metadata(),
2446 ::testing::UnorderedElementsAre(
2447 // TODO(roth): Should grpc-status be visible here?
2448 ::testing::Pair("grpc-status", "0"),
2449 ::testing::Pair("user-agent", ::testing::_),
2450 ::testing::Pair("foo", "1"), ::testing::Pair("bar", "2"),
2451 ::testing::Pair("baz", "3")));
2452 EXPECT_FALSE(backend_load_report().has_value());
2453 }
2454
2455 TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesEnabled) {
2456 const int kNumServers = 1;
2457 const int kNumRpcs = 10;
2458 StartServers(kNumServers);
2459 ChannelArguments args;
2460 args.SetServiceConfigJSON(
2461 "{\n"
2462 " \"methodConfig\": [ {\n"
2463 " \"name\": [\n"
2464 " { \"service\": \"grpc.testing.EchoTestService\" }\n"
2465 " ],\n"
2466 " \"retryPolicy\": {\n"
2467 " \"maxAttempts\": 3,\n"
2468 " \"initialBackoff\": \"1s\",\n"
2469 " \"maxBackoff\": \"120s\",\n"
2470 " \"backoffMultiplier\": 1.6,\n"
2471 " \"retryableStatusCodes\": [ \"ABORTED\" ]\n"
2472 " }\n"
2473 " } ]\n"
2474 "}");
2475 auto response_generator = BuildResolverResponseGenerator();
2476 auto channel =
2477 BuildChannel("intercept_trailing_metadata_lb", response_generator, args);
2478 auto stub = BuildStub(channel);
2479 response_generator.SetNextResolution(GetServersPorts());
2480 for (size_t i = 0; i < kNumRpcs; ++i) {
2481 CheckRpcSendOk(DEBUG_LOCATION, stub);
2482 }
2483 // Check LB policy name for the channel.
2484 EXPECT_EQ("intercept_trailing_metadata_lb",
2485 channel->GetLoadBalancingPolicyName());
2486 EXPECT_EQ(kNumRpcs, num_trailers_intercepted());
2487 EXPECT_THAT(trailing_metadata(),
2488 ::testing::UnorderedElementsAre(
2489 // TODO(roth): Should grpc-status be visible here?
2490 ::testing::Pair("grpc-status", "0"),
2491 ::testing::Pair("user-agent", ::testing::_),
2492 ::testing::Pair("foo", "1"), ::testing::Pair("bar", "2"),
2493 ::testing::Pair("baz", "3")));
2494 EXPECT_FALSE(backend_load_report().has_value());
2495 }
2496
2497 TEST_F(ClientLbInterceptTrailingMetadataTest, BackendMetricData) {
2498 const int kNumServers = 1;
2499 const int kNumRpcs = 10;
2500 StartServers(kNumServers);
2501 xds::data::orca::v3::OrcaLoadReport load_report;
2502 load_report.set_cpu_utilization(0.5);
2503 load_report.set_mem_utilization(0.75);
2504 auto* request_cost = load_report.mutable_request_cost();
2505 (*request_cost)["foo"] = 0.8;
2506 (*request_cost)["bar"] = 1.4;
2507 auto* utilization = load_report.mutable_utilization();
2508 (*utilization)["baz"] = 1.1;
2509 (*utilization)["quux"] = 0.9;
2510 auto response_generator = BuildResolverResponseGenerator();
2511 auto channel =
2512 BuildChannel("intercept_trailing_metadata_lb", response_generator);
2513 auto stub = BuildStub(channel);
2514 response_generator.SetNextResolution(GetServersPorts());
2515 for (size_t i = 0; i < kNumRpcs; ++i) {
2516 CheckRpcSendOk(DEBUG_LOCATION, stub, false, &load_report);
2517 auto actual = backend_load_report();
2518 ASSERT_TRUE(actual.has_value());
2519 // TODO(roth): Change this to use EqualsProto() once that becomes
2520 // available in OSS.
2521 EXPECT_EQ(actual->cpu_utilization(), load_report.cpu_utilization());
2522 EXPECT_EQ(actual->mem_utilization(), load_report.mem_utilization());
2523 EXPECT_EQ(actual->request_cost().size(), load_report.request_cost().size());
2524 for (const auto& p : actual->request_cost()) {
2525 auto it = load_report.request_cost().find(p.first);
2526 ASSERT_NE(it, load_report.request_cost().end());
2527 EXPECT_EQ(it->second, p.second);
2528 }
2529 EXPECT_EQ(actual->utilization().size(), load_report.utilization().size());
2530 for (const auto& p : actual->utilization()) {
2531 auto it = load_report.utilization().find(p.first);
2532 ASSERT_NE(it, load_report.utilization().end());
2533 EXPECT_EQ(it->second, p.second);
2534 }
2535 }
2536 // Check LB policy name for the channel.
2537 EXPECT_EQ("intercept_trailing_metadata_lb",
2538 channel->GetLoadBalancingPolicyName());
2539 EXPECT_EQ(kNumRpcs, num_trailers_intercepted());
2540 }
2541
2542 //
2543 // tests that address attributes from the resolver are visible to the LB policy
2544 //
2545
2546 class ClientLbAddressTest : public ClientLbEnd2endTest {
2547 protected:
2548 static const char* kAttributeKey;
2549
2550 class Attribute : public grpc_core::ServerAddress::AttributeInterface {
2551 public:
2552 explicit Attribute(const std::string& str) : str_(str) {}
2553
2554 std::unique_ptr<AttributeInterface> Copy() const override {
2555 return std::make_unique<Attribute>(str_);
2556 }
2557
2558 int Cmp(const AttributeInterface* other) const override {
2559 return str_.compare(static_cast<const Attribute*>(other)->str_);
2560 }
2561
2562 std::string ToString() const override { return str_; }
2563
2564 private:
2565 std::string str_;
2566 };
2567
2568 void SetUp() override {
2569 ClientLbEnd2endTest::SetUp();
2570 current_test_instance_ = this;
2571 }
2572
2573 static void SetUpTestCase() {
2574 grpc_core::CoreConfiguration::Reset();
2575 grpc_core::CoreConfiguration::RegisterBuilder(
2576 [](grpc_core::CoreConfiguration::Builder* builder) {
2577 grpc_core::RegisterAddressTestLoadBalancingPolicy(builder,
2578 SaveAddress);
2579 });
2580 grpc_init();
2581 }
2582
2583 static void TearDownTestCase() {
2584 grpc_shutdown();
2585 grpc_core::CoreConfiguration::Reset();
2586 }
2587
2588 const std::vector<std::string>& addresses_seen() {
2589 grpc_core::MutexLock lock(&mu_);
2590 return addresses_seen_;
2591 }
2592
2593 private:
2594 static void SaveAddress(const grpc_core::ServerAddress& address) {
2595 ClientLbAddressTest* self = current_test_instance_;
2596 grpc_core::MutexLock lock(&self->mu_);
2597 self->addresses_seen_.emplace_back(address.ToString());
2598 }
2599
2600 static ClientLbAddressTest* current_test_instance_;
2601 grpc_core::Mutex mu_;
2602 std::vector<std::string> addresses_seen_;
2603 };
2604
2605 const char* ClientLbAddressTest::kAttributeKey = "attribute_key";
2606
2607 ClientLbAddressTest* ClientLbAddressTest::current_test_instance_ = nullptr;
2608
2609 TEST_F(ClientLbAddressTest, Basic) {
2610 const int kNumServers = 1;
2611 StartServers(kNumServers);
2612 auto response_generator = BuildResolverResponseGenerator();
2613 auto channel = BuildChannel("address_test_lb", response_generator);
2614 auto stub = BuildStub(channel);
2615 // Addresses returned by the resolver will have attached attributes.
2616 response_generator.SetNextResolution(GetServersPorts(), nullptr,
2617 kAttributeKey,
2618 std::make_unique<Attribute>("foo"));
2619 CheckRpcSendOk(DEBUG_LOCATION, stub);
2620 // Check LB policy name for the channel.
2621 EXPECT_EQ("address_test_lb", channel->GetLoadBalancingPolicyName());
2622 // Make sure that the attributes wind up on the subchannels.
2623 std::vector<std::string> expected;
2624 for (const int port : GetServersPorts()) {
2625 expected.emplace_back(
2626 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", port,
2627 " attributes={", kAttributeKey, "=foo}"));
2628 }
2629 EXPECT_EQ(addresses_seen(), expected);
2630 }
2631
2632 //
2633 // tests OOB backend metric API
2634 //
2635
2636 class OobBackendMetricTest : public ClientLbEnd2endTest {
2637 protected:
2638 using BackendMetricReport =
2639 std::pair<int /*port*/, xds::data::orca::v3::OrcaLoadReport>;
2640
2641 void SetUp() override {
2642 ClientLbEnd2endTest::SetUp();
2643 current_test_instance_ = this;
2644 }
2645
2646 static void SetUpTestCase() {
2647 grpc_core::CoreConfiguration::Reset();
2648 grpc_core::CoreConfiguration::RegisterBuilder(
2649 [](grpc_core::CoreConfiguration::Builder* builder) {
2650 grpc_core::RegisterOobBackendMetricTestLoadBalancingPolicy(
2651 builder, BackendMetricCallback);
2652 });
2653 grpc_init();
2654 }
2655
2656 static void TearDownTestCase() {
2657 grpc_shutdown();
2658 grpc_core::CoreConfiguration::Reset();
2659 }
2660
2661 absl::optional<BackendMetricReport> GetBackendMetricReport() {
2662 grpc_core::MutexLock lock(&mu_);
2663 if (backend_metric_reports_.empty()) return absl::nullopt;
2664 auto result = std::move(backend_metric_reports_.front());
2665 backend_metric_reports_.pop_front();
2666 return result;
2667 }
2668
2669 private:
2670 static void BackendMetricCallback(
2671 grpc_core::ServerAddress address,
2672 const grpc_core::BackendMetricData& backend_metric_data) {
2673 auto load_report = BackendMetricDataToOrcaLoadReport(backend_metric_data);
2674 int port = grpc_sockaddr_get_port(&address.address());
2675 grpc_core::MutexLock lock(&current_test_instance_->mu_);
2676 current_test_instance_->backend_metric_reports_.push_back(
2677 {port, std::move(load_report)});
2678 }
2679
2680 static OobBackendMetricTest* current_test_instance_;
2681 grpc_core::Mutex mu_;
2682 std::deque<BackendMetricReport> backend_metric_reports_ ABSL_GUARDED_BY(&mu_);
2683 };
2684
2685 OobBackendMetricTest* OobBackendMetricTest::current_test_instance_ = nullptr;
2686
2687 TEST_F(OobBackendMetricTest, Basic) {
2688 StartServers(1);
2689 // Set initial backend metric data on server.
2690 constexpr char kMetricName[] = "foo";
2691 servers_[0]->orca_service_.SetCpuUtilization(0.1);
2692 servers_[0]->orca_service_.SetMemoryUtilization(0.2);
2693 servers_[0]->orca_service_.SetNamedUtilization(kMetricName, 0.3);
2694 // Start client.
2695 auto response_generator = BuildResolverResponseGenerator();
2696 auto channel = BuildChannel("oob_backend_metric_test_lb", response_generator);
2697 auto stub = BuildStub(channel);
2698 response_generator.SetNextResolution(GetServersPorts());
2699 // Send an OK RPC.
2700 CheckRpcSendOk(DEBUG_LOCATION, stub);
2701 // Check LB policy name for the channel.
2702 EXPECT_EQ("oob_backend_metric_test_lb",
2703 channel->GetLoadBalancingPolicyName());
2704 // Check report seen by client.
2705 for (size_t i = 0; i < 5; ++i) {
2706 auto report = GetBackendMetricReport();
2707 if (report.has_value()) {
2708 EXPECT_EQ(report->first, servers_[0]->port_);
2709 EXPECT_EQ(report->second.cpu_utilization(), 0.1);
2710 EXPECT_EQ(report->second.mem_utilization(), 0.2);
2711 EXPECT_THAT(
2712 report->second.utilization(),
2713 ::testing::UnorderedElementsAre(::testing::Pair(kMetricName, 0.3)));
2714 break;
2715 }
2716 gpr_sleep_until(grpc_timeout_seconds_to_deadline(1));
2717 }
2718 // Now update the utilization data on the server.
2719 // Note that the server may send a new report while we're updating these,
2720 // so we set them in reverse order, so that we know we'll get all new
2721 // data once we see a report with the new CPU utilization value.
2722 servers_[0]->orca_service_.SetNamedUtilization(kMetricName, 0.6);
2723 servers_[0]->orca_service_.SetMemoryUtilization(0.5);
2724 servers_[0]->orca_service_.SetCpuUtilization(0.4);
2725 // Wait for client to see new report.
2726 for (size_t i = 0; i < 5; ++i) {
2727 auto report = GetBackendMetricReport();
2728 if (report.has_value()) {
2729 EXPECT_EQ(report->first, servers_[0]->port_);
2730 if (report->second.cpu_utilization() != 0.1) {
2731 EXPECT_EQ(report->second.cpu_utilization(), 0.4);
2732 EXPECT_EQ(report->second.mem_utilization(), 0.5);
2733 EXPECT_THAT(
2734 report->second.utilization(),
2735 ::testing::UnorderedElementsAre(::testing::Pair(kMetricName, 0.6)));
2736 break;
2737 }
2738 }
2739 gpr_sleep_until(grpc_timeout_seconds_to_deadline(1));
2740 }
2741 }
2742
2743 //
2744 // tests rewriting of control plane status codes
2745 //
2746
2747 class ControlPlaneStatusRewritingTest : public ClientLbEnd2endTest {
2748 protected:
2749 static void SetUpTestCase() {
2750 grpc_core::CoreConfiguration::Reset();
2751 grpc_core::CoreConfiguration::RegisterBuilder(
2752 [](grpc_core::CoreConfiguration::Builder* builder) {
2753 grpc_core::RegisterFailLoadBalancingPolicy(
2754 builder, absl::AbortedError("nope"));
2755 });
2756 grpc_init();
2757 }
2758
2759 static void TearDownTestCase() {
2760 grpc_shutdown();
2761 grpc_core::CoreConfiguration::Reset();
2762 }
2763 };
2764
2765 TEST_F(ControlPlaneStatusRewritingTest, RewritesFromLb) {
2766 // Start client.
2767 auto response_generator = BuildResolverResponseGenerator();
2768 auto channel = BuildChannel("fail_lb", response_generator);
2769 auto stub = BuildStub(channel);
2770 response_generator.SetNextResolution(GetServersPorts());
2771 // Send an RPC, verify that status was rewritten.
2772 CheckRpcSendFailure(
2773 DEBUG_LOCATION, stub, StatusCode::INTERNAL,
2774 "Illegal status code from LB pick; original status: ABORTED: nope");
2775 }
2776
2777 TEST_F(ControlPlaneStatusRewritingTest, RewritesFromResolver) {
2778 // Start client.
2779 auto response_generator = BuildResolverResponseGenerator();
2780 auto channel = BuildChannel("pick_first", response_generator);
2781 auto stub = BuildStub(channel);
2782 grpc_core::Resolver::Result result;
2783 result.service_config = absl::AbortedError("nope");
2784 result.addresses.emplace();
2785 response_generator.SetResponse(std::move(result));
2786 // Send an RPC, verify that status was rewritten.
2787 CheckRpcSendFailure(
2788 DEBUG_LOCATION, stub, StatusCode::INTERNAL,
2789 "Illegal status code from resolver; original status: ABORTED: nope");
2790 }
2791
2792 TEST_F(ControlPlaneStatusRewritingTest, RewritesFromConfigSelector) {
2793 class FailConfigSelector : public grpc_core::ConfigSelector {
2794 public:
2795 explicit FailConfigSelector(absl::Status status)
2796 : status_(std::move(status)) {}
2797 const char* name() const override { return "FailConfigSelector"; }
2798 bool Equals(const ConfigSelector* other) const override {
2799 return status_ == static_cast<const FailConfigSelector*>(other)->status_;
2800 }
2801 CallConfig GetCallConfig(GetCallConfigArgs /*args*/) override {
2802 CallConfig config;
2803 config.status = status_;
2804 return config;
2805 }
2806
2807 private:
2808 absl::Status status_;
2809 };
2810 // Start client.
2811 auto response_generator = BuildResolverResponseGenerator();
2812 auto channel = BuildChannel("pick_first", response_generator);
2813 auto stub = BuildStub(channel);
2814 auto config_selector =
2815 grpc_core::MakeRefCounted<FailConfigSelector>(absl::AbortedError("nope"));
2816 grpc_core::Resolver::Result result;
2817 result.addresses.emplace();
2818 result.service_config =
2819 grpc_core::ServiceConfigImpl::Create(grpc_core::ChannelArgs(), "{}");
2820 ASSERT_TRUE(result.service_config.ok()) << result.service_config.status();
2821 result.args = grpc_core::ChannelArgs().SetObject(config_selector);
2822 response_generator.SetResponse(std::move(result));
2823 // Send an RPC, verify that status was rewritten.
2824 CheckRpcSendFailure(
2825 DEBUG_LOCATION, stub, StatusCode::INTERNAL,
2826 "Illegal status code from ConfigSelector; original status: "
2827 "ABORTED: nope");
2828 }
2829
2830 } // namespace
2831 } // namespace testing
2832 } // namespace grpc
2833
2834 int main(int argc, char** argv) {
2835 ::testing::InitGoogleTest(&argc, argv);
2836 grpc::testing::TestEnvironment env(&argc, argv);
2837 grpc_init();
2838 grpc::testing::ConnectionAttemptInjector::Init();
2839 const auto result = RUN_ALL_TESTS();
2840 grpc_shutdown();
2841 return result;
2842 }