3 * Copyright 2016 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
26 #include <grpc/grpc.h>
27 #include <grpc/support/alloc.h>
28 #include <grpc/support/atm.h>
29 #include <grpc/support/log.h>
30 #include <grpc/support/string_util.h>
31 #include <grpc/support/time.h>
32 #include <grpcpp/channel.h>
33 #include <grpcpp/client_context.h>
34 #include <grpcpp/create_channel.h>
35 #include <grpcpp/health_check_service_interface.h>
36 #include <grpcpp/impl/codegen/sync.h>
37 #include <grpcpp/server.h>
38 #include <grpcpp/server_builder.h>
40 #include "src/core/ext/filters/client_channel/backup_poller.h"
41 #include "src/core/ext/filters/client_channel/global_subchannel_pool.h"
42 #include "src/core/ext/filters/client_channel/parse_address.h"
43 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
44 #include "src/core/ext/filters/client_channel/server_address.h"
45 #include "src/core/ext/filters/client_channel/service_config.h"
46 #include "src/core/lib/backoff/backoff.h"
47 #include "src/core/lib/channel/channel_args.h"
48 #include "src/core/lib/gpr/env.h"
49 #include "src/core/lib/gprpp/debug_location.h"
50 #include "src/core/lib/gprpp/ref_counted_ptr.h"
51 #include "src/core/lib/iomgr/tcp_client.h"
52 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
53 #include "src/cpp/client/secure_credentials.h"
54 #include "src/cpp/server/secure_server_credentials.h"
56 #include "src/proto/grpc/lb/v2/orca_load_report_for_test.pb.h"
57 #include "src/proto/grpc/testing/echo.grpc.pb.h"
58 #include "test/core/util/port.h"
59 #include "test/core/util/test_config.h"
60 #include "test/core/util/test_lb_policies.h"
61 #include "test/cpp/end2end/test_service_impl.h"
63 #include <gmock/gmock.h>
64 #include <gtest/gtest.h>
66 using grpc::testing::EchoRequest;
67 using grpc::testing::EchoResponse;
68 using std::chrono::system_clock;
70 // defined in tcp_client.cc
71 extern grpc_tcp_client_vtable* grpc_tcp_client_impl;
73 static grpc_tcp_client_vtable* default_client_impl;
79 gpr_atm g_connection_delay_ms;
81 void tcp_client_connect_with_delay(grpc_closure* closure, grpc_endpoint** ep,
82 grpc_pollset_set* interested_parties,
83 const grpc_channel_args* channel_args,
84 const grpc_resolved_address* addr,
85 grpc_millis deadline) {
86 const int delay_ms = gpr_atm_acq_load(&g_connection_delay_ms);
88 gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
90 default_client_impl->connect(closure, ep, interested_parties, channel_args,
91 addr, deadline + delay_ms);
94 grpc_tcp_client_vtable delayed_connect = {tcp_client_connect_with_delay};
96 // Subclass of TestServiceImpl that increments a request counter for
97 // every call to the Echo RPC.
98 class MyTestServiceImpl : public TestServiceImpl {
100 Status Echo(ServerContext* context, const EchoRequest* request,
101 EchoResponse* response) override {
102 const udpa::data::orca::v1::OrcaLoadReport* load_report = nullptr;
104 grpc::internal::MutexLock lock(&mu_);
106 load_report = load_report_;
108 AddClient(context->peer());
109 if (load_report != nullptr) {
110 // TODO(roth): Once we provide a more standard server-side API for
111 // populating this data, use that API here.
112 context->AddTrailingMetadata("x-endpoint-load-metrics-bin",
113 load_report->SerializeAsString());
115 return TestServiceImpl::Echo(context, request, response);
118 int request_count() {
119 grpc::internal::MutexLock lock(&mu_);
120 return request_count_;
123 void ResetCounters() {
124 grpc::internal::MutexLock lock(&mu_);
128 std::set<grpc::string> clients() {
129 grpc::internal::MutexLock lock(&clients_mu_);
133 void set_load_report(udpa::data::orca::v1::OrcaLoadReport* load_report) {
134 grpc::internal::MutexLock lock(&mu_);
135 load_report_ = load_report;
139 void AddClient(const grpc::string& client) {
140 grpc::internal::MutexLock lock(&clients_mu_);
141 clients_.insert(client);
144 grpc::internal::Mutex mu_;
145 int request_count_ = 0;
146 const udpa::data::orca::v1::OrcaLoadReport* load_report_ = nullptr;
147 grpc::internal::Mutex clients_mu_;
148 std::set<grpc::string> clients_;
151 class FakeResolverResponseGeneratorWrapper {
153 FakeResolverResponseGeneratorWrapper()
154 : response_generator_(grpc_core::MakeRefCounted<
155 grpc_core::FakeResolverResponseGenerator>()) {}
157 FakeResolverResponseGeneratorWrapper(
158 FakeResolverResponseGeneratorWrapper&& other) {
159 response_generator_ = std::move(other.response_generator_);
162 void SetNextResolution(const std::vector<int>& ports,
163 const char* service_config_json = nullptr) {
164 grpc_core::ExecCtx exec_ctx;
165 response_generator_->SetResponse(
166 BuildFakeResults(ports, service_config_json));
169 void SetNextResolutionUponError(const std::vector<int>& ports) {
170 grpc_core::ExecCtx exec_ctx;
171 response_generator_->SetReresolutionResponse(BuildFakeResults(ports));
174 void SetFailureOnReresolution() {
175 grpc_core::ExecCtx exec_ctx;
176 response_generator_->SetFailureOnReresolution();
179 grpc_core::FakeResolverResponseGenerator* Get() const {
180 return response_generator_.get();
184 static grpc_core::Resolver::Result BuildFakeResults(
185 const std::vector<int>& ports,
186 const char* service_config_json = nullptr) {
187 grpc_core::Resolver::Result result;
188 for (const int& port : ports) {
190 gpr_asprintf(&lb_uri_str, "ipv4:127.0.0.1:%d", port);
191 grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str, true);
192 GPR_ASSERT(lb_uri != nullptr);
193 grpc_resolved_address address;
194 GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
195 result.addresses.emplace_back(address.addr, address.len,
197 grpc_uri_destroy(lb_uri);
198 gpr_free(lb_uri_str);
200 if (service_config_json != nullptr) {
201 result.service_config = grpc_core::ServiceConfig::Create(
202 service_config_json, &result.service_config_error);
203 GPR_ASSERT(result.service_config != nullptr);
208 grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
212 class ClientLbEnd2endTest : public ::testing::Test {
214 ClientLbEnd2endTest()
215 : server_host_("localhost"),
216 kRequestMessage_("Live long and prosper."),
217 creds_(new SecureChannelCredentials(
218 grpc_fake_transport_security_credentials_create())) {}
220 static void SetUpTestCase() {
221 // Make the backup poller poll very frequently in order to pick up
222 // updates from all the subchannels's FDs.
223 GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
225 // Workaround Apple CFStream bug
226 gpr_setenv("grpc_cfstream", "0");
230 void SetUp() override { grpc_init(); }
232 void TearDown() override {
233 for (size_t i = 0; i < servers_.size(); ++i) {
234 servers_[i]->Shutdown();
236 // Explicitly destroy all the members so that we can make sure grpc_shutdown
237 // has finished by the end of this function, and thus all the registered
238 // LB policy factories are removed.
241 grpc_shutdown_blocking();
244 void CreateServers(size_t num_servers,
245 std::vector<int> ports = std::vector<int>()) {
247 for (size_t i = 0; i < num_servers; ++i) {
249 if (ports.size() == num_servers) port = ports[i];
250 servers_.emplace_back(new ServerData(port));
254 void StartServer(size_t index) { servers_[index]->Start(server_host_); }
256 void StartServers(size_t num_servers,
257 std::vector<int> ports = std::vector<int>()) {
258 CreateServers(num_servers, std::move(ports));
259 for (size_t i = 0; i < num_servers; ++i) {
264 std::vector<int> GetServersPorts(size_t start_index = 0) {
265 std::vector<int> ports;
266 for (size_t i = start_index; i < servers_.size(); ++i) {
267 ports.push_back(servers_[i]->port_);
272 FakeResolverResponseGeneratorWrapper BuildResolverResponseGenerator() {
273 return FakeResolverResponseGeneratorWrapper();
276 std::unique_ptr<grpc::testing::EchoTestService::Stub> BuildStub(
277 const std::shared_ptr<Channel>& channel) {
278 return grpc::testing::EchoTestService::NewStub(channel);
281 std::shared_ptr<Channel> BuildChannel(
282 const grpc::string& lb_policy_name,
283 const FakeResolverResponseGeneratorWrapper& response_generator,
284 ChannelArguments args = ChannelArguments()) {
285 if (lb_policy_name.size() > 0) {
286 args.SetLoadBalancingPolicyName(lb_policy_name);
287 } // else, default to pick first
288 args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
289 response_generator.Get());
290 return ::grpc::CreateCustomChannel("fake:///", creds_, args);
294 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
295 EchoResponse* response = nullptr, int timeout_ms = 1000,
296 Status* result = nullptr, bool wait_for_ready = false) {
297 const bool local_response = (response == nullptr);
298 if (local_response) response = new EchoResponse;
300 request.set_message(kRequestMessage_);
301 ClientContext context;
302 context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
303 if (wait_for_ready) context.set_wait_for_ready(true);
304 Status status = stub->Echo(&context, request, response);
305 if (result != nullptr) *result = status;
306 if (local_response) delete response;
311 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
312 const grpc_core::DebugLocation& location, bool wait_for_ready = false) {
313 EchoResponse response;
316 SendRpc(stub, &response, 2000, &status, wait_for_ready);
317 ASSERT_TRUE(success) << "From " << location.file() << ":" << location.line()
319 << "Error: " << status.error_message() << " "
320 << status.error_details();
321 ASSERT_EQ(response.message(), kRequestMessage_)
322 << "From " << location.file() << ":" << location.line();
323 if (!success) abort();
326 void CheckRpcSendFailure(
327 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub) {
328 const bool success = SendRpc(stub);
329 EXPECT_FALSE(success);
334 std::unique_ptr<Server> server_;
335 MyTestServiceImpl service_;
336 std::unique_ptr<std::thread> thread_;
337 bool server_ready_ = false;
338 bool started_ = false;
340 explicit ServerData(int port = 0) {
341 port_ = port > 0 ? port : grpc_pick_unused_port_or_die();
344 void Start(const grpc::string& server_host) {
345 gpr_log(GPR_INFO, "starting server on port %d", port_);
347 grpc::internal::Mutex mu;
348 grpc::internal::MutexLock lock(&mu);
349 grpc::internal::CondVar cond;
350 thread_.reset(new std::thread(
351 std::bind(&ServerData::Serve, this, server_host, &mu, &cond)));
352 cond.WaitUntil(&mu, [this] { return server_ready_; });
353 server_ready_ = false;
354 gpr_log(GPR_INFO, "server startup complete");
357 void Serve(const grpc::string& server_host, grpc::internal::Mutex* mu,
358 grpc::internal::CondVar* cond) {
359 std::ostringstream server_address;
360 server_address << server_host << ":" << port_;
361 ServerBuilder builder;
362 std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
363 grpc_fake_transport_security_server_credentials_create()));
364 builder.AddListeningPort(server_address.str(), std::move(creds));
365 builder.RegisterService(&service_);
366 server_ = builder.BuildAndStart();
367 grpc::internal::MutexLock lock(mu);
368 server_ready_ = true;
373 if (!started_) return;
374 server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
379 void SetServingStatus(const grpc::string& service, bool serving) {
380 server_->GetHealthCheckService()->SetServingStatus(service, serving);
384 void ResetCounters() {
385 for (const auto& server : servers_) server->service_.ResetCounters();
389 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
390 size_t server_idx, const grpc_core::DebugLocation& location,
391 bool ignore_failure = false) {
393 if (ignore_failure) {
396 CheckRpcSendOk(stub, location, true);
398 } while (servers_[server_idx]->service_.request_count() == 0);
402 bool WaitForChannelNotReady(Channel* channel, int timeout_seconds = 5) {
403 const gpr_timespec deadline =
404 grpc_timeout_seconds_to_deadline(timeout_seconds);
405 grpc_connectivity_state state;
406 while ((state = channel->GetState(false /* try_to_connect */)) ==
407 GRPC_CHANNEL_READY) {
408 if (!channel->WaitForStateChange(state, deadline)) return false;
413 bool WaitForChannelReady(Channel* channel, int timeout_seconds = 5) {
414 const gpr_timespec deadline =
415 grpc_timeout_seconds_to_deadline(timeout_seconds);
416 grpc_connectivity_state state;
417 while ((state = channel->GetState(true /* try_to_connect */)) !=
418 GRPC_CHANNEL_READY) {
419 if (!channel->WaitForStateChange(state, deadline)) return false;
424 bool SeenAllServers() {
425 for (const auto& server : servers_) {
426 if (server->service_.request_count() == 0) return false;
431 // Updates \a connection_order by appending to it the index of the newly
432 // connected server. Must be called after every single RPC.
433 void UpdateConnectionOrder(
434 const std::vector<std::unique_ptr<ServerData>>& servers,
435 std::vector<int>* connection_order) {
436 for (size_t i = 0; i < servers.size(); ++i) {
437 if (servers[i]->service_.request_count() == 1) {
438 // Was the server index known? If not, update connection_order.
440 std::find(connection_order->begin(), connection_order->end(), i);
441 if (it == connection_order->end()) {
442 connection_order->push_back(i);
449 const grpc::string server_host_;
450 std::vector<std::unique_ptr<ServerData>> servers_;
451 const grpc::string kRequestMessage_;
452 std::shared_ptr<ChannelCredentials> creds_;
455 TEST_F(ClientLbEnd2endTest, ChannelStateConnectingWhenResolving) {
456 const int kNumServers = 3;
457 StartServers(kNumServers);
458 auto response_generator = BuildResolverResponseGenerator();
459 auto channel = BuildChannel("", response_generator);
460 auto stub = BuildStub(channel);
461 // Initial state should be IDLE.
462 EXPECT_EQ(channel->GetState(false /* try_to_connect */), GRPC_CHANNEL_IDLE);
463 // Tell the channel to try to connect.
464 // Note that this call also returns IDLE, since the state change has
465 // not yet occurred; it just gets triggered by this call.
466 EXPECT_EQ(channel->GetState(true /* try_to_connect */), GRPC_CHANNEL_IDLE);
467 // Now that the channel is trying to connect, we should be in state
469 EXPECT_EQ(channel->GetState(false /* try_to_connect */),
470 GRPC_CHANNEL_CONNECTING);
471 // Return a resolver result, which allows the connection attempt to proceed.
472 response_generator.SetNextResolution(GetServersPorts());
473 // We should eventually transition into state READY.
474 EXPECT_TRUE(WaitForChannelReady(channel.get()));
477 TEST_F(ClientLbEnd2endTest, PickFirst) {
478 // Start servers and send one RPC per server.
479 const int kNumServers = 3;
480 StartServers(kNumServers);
481 auto response_generator = BuildResolverResponseGenerator();
482 auto channel = BuildChannel(
483 "", response_generator); // test that pick first is the default.
484 auto stub = BuildStub(channel);
485 response_generator.SetNextResolution(GetServersPorts());
486 for (size_t i = 0; i < servers_.size(); ++i) {
487 CheckRpcSendOk(stub, DEBUG_LOCATION);
489 // All requests should have gone to a single server.
491 for (size_t i = 0; i < servers_.size(); ++i) {
492 const int request_count = servers_[i]->service_.request_count();
493 if (request_count == kNumServers) {
496 EXPECT_EQ(0, request_count);
500 // Check LB policy name for the channel.
501 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
504 TEST_F(ClientLbEnd2endTest, PickFirstProcessPending) {
505 StartServers(1); // Single server
506 auto response_generator = BuildResolverResponseGenerator();
507 auto channel = BuildChannel(
508 "", response_generator); // test that pick first is the default.
509 auto stub = BuildStub(channel);
510 response_generator.SetNextResolution({servers_[0]->port_});
511 WaitForServer(stub, 0, DEBUG_LOCATION);
512 // Create a new channel and its corresponding PF LB policy, which will pick
513 // the subchannels in READY state from the previous RPC against the same
514 // target (even if it happened over a different channel, because subchannels
515 // are globally reused). Progress should happen without any transition from
517 auto second_response_generator = BuildResolverResponseGenerator();
518 auto second_channel = BuildChannel("", second_response_generator);
519 auto second_stub = BuildStub(second_channel);
520 second_response_generator.SetNextResolution({servers_[0]->port_});
521 CheckRpcSendOk(second_stub, DEBUG_LOCATION);
524 TEST_F(ClientLbEnd2endTest, PickFirstSelectsReadyAtStartup) {
525 ChannelArguments args;
526 constexpr int kInitialBackOffMs = 5000;
527 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
528 // Create 2 servers, but start only the second one.
529 std::vector<int> ports = {grpc_pick_unused_port_or_die(),
530 grpc_pick_unused_port_or_die()};
531 CreateServers(2, ports);
533 auto response_generator1 = BuildResolverResponseGenerator();
534 auto channel1 = BuildChannel("pick_first", response_generator1, args);
535 auto stub1 = BuildStub(channel1);
536 response_generator1.SetNextResolution(ports);
537 // Wait for second server to be ready.
538 WaitForServer(stub1, 1, DEBUG_LOCATION);
539 // Create a second channel with the same addresses. Its PF instance
540 // should immediately pick the second subchannel, since it's already
542 auto response_generator2 = BuildResolverResponseGenerator();
543 auto channel2 = BuildChannel("pick_first", response_generator2, args);
544 response_generator2.SetNextResolution(ports);
545 // Check that the channel reports READY without waiting for the
547 EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1 /* timeout_seconds */));
550 TEST_F(ClientLbEnd2endTest, PickFirstBackOffInitialReconnect) {
551 ChannelArguments args;
552 constexpr int kInitialBackOffMs = 100;
553 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
554 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
555 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
556 auto response_generator = BuildResolverResponseGenerator();
557 auto channel = BuildChannel("pick_first", response_generator, args);
558 auto stub = BuildStub(channel);
559 response_generator.SetNextResolution(ports);
560 // The channel won't become connected (there's no server).
561 ASSERT_FALSE(channel->WaitForConnected(
562 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
563 // Bring up a server on the chosen port.
564 StartServers(1, ports);
566 ASSERT_TRUE(channel->WaitForConnected(
567 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
568 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
569 const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
570 gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
571 // We should have waited at least kInitialBackOffMs. We substract one to
572 // account for test and precision accuracy drift.
573 EXPECT_GE(waited_ms, kInitialBackOffMs - 1);
574 // But not much more.
577 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 1.10), t1),
581 TEST_F(ClientLbEnd2endTest, PickFirstBackOffMinReconnect) {
582 ChannelArguments args;
583 constexpr int kMinReconnectBackOffMs = 1000;
584 args.SetInt(GRPC_ARG_MIN_RECONNECT_BACKOFF_MS, kMinReconnectBackOffMs);
585 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
586 auto response_generator = BuildResolverResponseGenerator();
587 auto channel = BuildChannel("pick_first", response_generator, args);
588 auto stub = BuildStub(channel);
589 response_generator.SetNextResolution(ports);
590 // Make connection delay a 10% longer than it's willing to in order to make
591 // sure we are hitting the codepath that waits for the min reconnect backoff.
592 gpr_atm_rel_store(&g_connection_delay_ms, kMinReconnectBackOffMs * 1.10);
593 default_client_impl = grpc_tcp_client_impl;
594 grpc_set_tcp_client_impl(&delayed_connect);
595 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
596 channel->WaitForConnected(
597 grpc_timeout_milliseconds_to_deadline(kMinReconnectBackOffMs * 2));
598 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
599 const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
600 gpr_log(GPR_DEBUG, "Waited %" PRId64 " ms", waited_ms);
601 // We should have waited at least kMinReconnectBackOffMs. We substract one to
602 // account for test and precision accuracy drift.
603 EXPECT_GE(waited_ms, kMinReconnectBackOffMs - 1);
604 gpr_atm_rel_store(&g_connection_delay_ms, 0);
607 TEST_F(ClientLbEnd2endTest, PickFirstResetConnectionBackoff) {
608 ChannelArguments args;
609 constexpr int kInitialBackOffMs = 1000;
610 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
611 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
612 auto response_generator = BuildResolverResponseGenerator();
613 auto channel = BuildChannel("pick_first", response_generator, args);
614 auto stub = BuildStub(channel);
615 response_generator.SetNextResolution(ports);
616 // The channel won't become connected (there's no server).
618 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
619 // Bring up a server on the chosen port.
620 StartServers(1, ports);
621 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
622 // Wait for connect, but not long enough. This proves that we're
623 // being throttled by initial backoff.
625 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
626 // Reset connection backoff.
627 experimental::ChannelResetConnectionBackoff(channel.get());
628 // Wait for connect. Should happen ~immediately.
630 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
631 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
632 const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
633 gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
634 // We should have waited less than kInitialBackOffMs.
635 EXPECT_LT(waited_ms, kInitialBackOffMs);
638 TEST_F(ClientLbEnd2endTest,
639 PickFirstResetConnectionBackoffNextAttemptStartsImmediately) {
640 ChannelArguments args;
641 constexpr int kInitialBackOffMs = 1000;
642 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
643 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
644 auto response_generator = BuildResolverResponseGenerator();
645 auto channel = BuildChannel("pick_first", response_generator, args);
646 auto stub = BuildStub(channel);
647 response_generator.SetNextResolution(ports);
648 // Wait for connect, which should fail ~immediately, because the server
650 gpr_log(GPR_INFO, "=== INITIAL CONNECTION ATTEMPT");
652 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
653 // Reset connection backoff.
654 // Note that the time at which the third attempt will be started is
655 // actually computed at this point, so we record the start time here.
656 gpr_log(GPR_INFO, "=== RESETTING BACKOFF");
657 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
658 experimental::ChannelResetConnectionBackoff(channel.get());
659 // Trigger a second connection attempt. This should also fail
660 // ~immediately, but the retry should be scheduled for
661 // kInitialBackOffMs instead of applying the multiplier.
662 gpr_log(GPR_INFO, "=== POLLING FOR SECOND CONNECTION ATTEMPT");
664 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
665 // Bring up a server on the chosen port.
666 gpr_log(GPR_INFO, "=== STARTING BACKEND");
667 StartServers(1, ports);
668 // Wait for connect. Should happen within kInitialBackOffMs.
669 // Give an extra 100ms to account for the time spent in the second and
670 // third connection attempts themselves (since what we really want to
671 // measure is the time between the two). As long as this is less than
672 // the 1.6x increase we would see if the backoff state was not reset
673 // properly, the test is still proving that the backoff was reset.
674 constexpr int kWaitMs = kInitialBackOffMs + 100;
675 gpr_log(GPR_INFO, "=== POLLING FOR THIRD CONNECTION ATTEMPT");
676 EXPECT_TRUE(channel->WaitForConnected(
677 grpc_timeout_milliseconds_to_deadline(kWaitMs)));
678 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
679 const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
680 gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
681 EXPECT_LT(waited_ms, kWaitMs);
684 TEST_F(ClientLbEnd2endTest, PickFirstUpdates) {
685 // Start servers and send one RPC per server.
686 const int kNumServers = 3;
687 StartServers(kNumServers);
688 auto response_generator = BuildResolverResponseGenerator();
689 auto channel = BuildChannel("pick_first", response_generator);
690 auto stub = BuildStub(channel);
692 std::vector<int> ports;
694 // Perform one RPC against the first server.
695 ports.emplace_back(servers_[0]->port_);
696 response_generator.SetNextResolution(ports);
697 gpr_log(GPR_INFO, "****** SET [0] *******");
698 CheckRpcSendOk(stub, DEBUG_LOCATION);
699 EXPECT_EQ(servers_[0]->service_.request_count(), 1);
701 // An empty update will result in the channel going into TRANSIENT_FAILURE.
703 response_generator.SetNextResolution(ports);
704 gpr_log(GPR_INFO, "****** SET none *******");
705 grpc_connectivity_state channel_state;
707 channel_state = channel->GetState(true /* try to connect */);
708 } while (channel_state == GRPC_CHANNEL_READY);
709 ASSERT_NE(channel_state, GRPC_CHANNEL_READY);
710 servers_[0]->service_.ResetCounters();
712 // Next update introduces servers_[1], making the channel recover.
714 ports.emplace_back(servers_[1]->port_);
715 response_generator.SetNextResolution(ports);
716 gpr_log(GPR_INFO, "****** SET [1] *******");
717 WaitForServer(stub, 1, DEBUG_LOCATION);
718 EXPECT_EQ(servers_[0]->service_.request_count(), 0);
720 // And again for servers_[2]
722 ports.emplace_back(servers_[2]->port_);
723 response_generator.SetNextResolution(ports);
724 gpr_log(GPR_INFO, "****** SET [2] *******");
725 WaitForServer(stub, 2, DEBUG_LOCATION);
726 EXPECT_EQ(servers_[0]->service_.request_count(), 0);
727 EXPECT_EQ(servers_[1]->service_.request_count(), 0);
729 // Check LB policy name for the channel.
730 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
733 TEST_F(ClientLbEnd2endTest, PickFirstUpdateSuperset) {
734 // Start servers and send one RPC per server.
735 const int kNumServers = 3;
736 StartServers(kNumServers);
737 auto response_generator = BuildResolverResponseGenerator();
738 auto channel = BuildChannel("pick_first", response_generator);
739 auto stub = BuildStub(channel);
741 std::vector<int> ports;
743 // Perform one RPC against the first server.
744 ports.emplace_back(servers_[0]->port_);
745 response_generator.SetNextResolution(ports);
746 gpr_log(GPR_INFO, "****** SET [0] *******");
747 CheckRpcSendOk(stub, DEBUG_LOCATION);
748 EXPECT_EQ(servers_[0]->service_.request_count(), 1);
749 servers_[0]->service_.ResetCounters();
751 // Send and superset update
753 ports.emplace_back(servers_[1]->port_);
754 ports.emplace_back(servers_[0]->port_);
755 response_generator.SetNextResolution(ports);
756 gpr_log(GPR_INFO, "****** SET superset *******");
757 CheckRpcSendOk(stub, DEBUG_LOCATION);
758 // We stick to the previously connected server.
759 WaitForServer(stub, 0, DEBUG_LOCATION);
760 EXPECT_EQ(0, servers_[1]->service_.request_count());
762 // Check LB policy name for the channel.
763 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
766 TEST_F(ClientLbEnd2endTest, PickFirstGlobalSubchannelPool) {
768 const int kNumServers = 1;
769 StartServers(kNumServers);
770 std::vector<int> ports = GetServersPorts();
771 // Create two channels that (by default) use the global subchannel pool.
772 auto response_generator1 = BuildResolverResponseGenerator();
773 auto channel1 = BuildChannel("pick_first", response_generator1);
774 auto stub1 = BuildStub(channel1);
775 response_generator1.SetNextResolution(ports);
776 auto response_generator2 = BuildResolverResponseGenerator();
777 auto channel2 = BuildChannel("pick_first", response_generator2);
778 auto stub2 = BuildStub(channel2);
779 response_generator2.SetNextResolution(ports);
780 WaitForServer(stub1, 0, DEBUG_LOCATION);
781 // Send one RPC on each channel.
782 CheckRpcSendOk(stub1, DEBUG_LOCATION);
783 CheckRpcSendOk(stub2, DEBUG_LOCATION);
784 // The server receives two requests.
785 EXPECT_EQ(2, servers_[0]->service_.request_count());
786 // The two requests are from the same client port, because the two channels
787 // share subchannels via the global subchannel pool.
788 EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
791 TEST_F(ClientLbEnd2endTest, PickFirstLocalSubchannelPool) {
793 const int kNumServers = 1;
794 StartServers(kNumServers);
795 std::vector<int> ports = GetServersPorts();
796 // Create two channels that use local subchannel pool.
797 ChannelArguments args;
798 args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
799 auto response_generator1 = BuildResolverResponseGenerator();
800 auto channel1 = BuildChannel("pick_first", response_generator1, args);
801 auto stub1 = BuildStub(channel1);
802 response_generator1.SetNextResolution(ports);
803 auto response_generator2 = BuildResolverResponseGenerator();
804 auto channel2 = BuildChannel("pick_first", response_generator2, args);
805 auto stub2 = BuildStub(channel2);
806 response_generator2.SetNextResolution(ports);
807 WaitForServer(stub1, 0, DEBUG_LOCATION);
808 // Send one RPC on each channel.
809 CheckRpcSendOk(stub1, DEBUG_LOCATION);
810 CheckRpcSendOk(stub2, DEBUG_LOCATION);
811 // The server receives two requests.
812 EXPECT_EQ(2, servers_[0]->service_.request_count());
813 // The two requests are from two client ports, because the two channels didn't
814 // share subchannels with each other.
815 EXPECT_EQ(2UL, servers_[0]->service_.clients().size());
818 TEST_F(ClientLbEnd2endTest, PickFirstManyUpdates) {
819 const int kNumUpdates = 1000;
820 const int kNumServers = 3;
821 StartServers(kNumServers);
822 auto response_generator = BuildResolverResponseGenerator();
823 auto channel = BuildChannel("pick_first", response_generator);
824 auto stub = BuildStub(channel);
825 std::vector<int> ports = GetServersPorts();
826 for (size_t i = 0; i < kNumUpdates; ++i) {
827 std::shuffle(ports.begin(), ports.end(),
828 std::mt19937(std::random_device()()));
829 response_generator.SetNextResolution(ports);
830 // We should re-enter core at the end of the loop to give the resolution
831 // setting closure a chance to run.
832 if ((i + 1) % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
834 // Check LB policy name for the channel.
835 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
838 TEST_F(ClientLbEnd2endTest, PickFirstReresolutionNoSelected) {
839 // Prepare the ports for up servers and down servers.
840 const int kNumServers = 3;
841 const int kNumAliveServers = 1;
842 StartServers(kNumAliveServers);
843 std::vector<int> alive_ports, dead_ports;
844 for (size_t i = 0; i < kNumServers; ++i) {
845 if (i < kNumAliveServers) {
846 alive_ports.emplace_back(servers_[i]->port_);
848 dead_ports.emplace_back(grpc_pick_unused_port_or_die());
851 auto response_generator = BuildResolverResponseGenerator();
852 auto channel = BuildChannel("pick_first", response_generator);
853 auto stub = BuildStub(channel);
854 // The initial resolution only contains dead ports. There won't be any
855 // selected subchannel. Re-resolution will return the same result.
856 response_generator.SetNextResolution(dead_ports);
857 gpr_log(GPR_INFO, "****** INITIAL RESOLUTION SET *******");
858 for (size_t i = 0; i < 10; ++i) CheckRpcSendFailure(stub);
859 // Set a re-resolution result that contains reachable ports, so that the
860 // pick_first LB policy can recover soon.
861 response_generator.SetNextResolutionUponError(alive_ports);
862 gpr_log(GPR_INFO, "****** RE-RESOLUTION SET *******");
863 WaitForServer(stub, 0, DEBUG_LOCATION, true /* ignore_failure */);
864 CheckRpcSendOk(stub, DEBUG_LOCATION);
865 EXPECT_EQ(servers_[0]->service_.request_count(), 1);
866 // Check LB policy name for the channel.
867 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
870 TEST_F(ClientLbEnd2endTest, PickFirstReconnectWithoutNewResolverResult) {
871 std::vector<int> ports = {grpc_pick_unused_port_or_die()};
872 StartServers(1, ports);
873 auto response_generator = BuildResolverResponseGenerator();
874 auto channel = BuildChannel("pick_first", response_generator);
875 auto stub = BuildStub(channel);
876 response_generator.SetNextResolution(ports);
877 gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
878 WaitForServer(stub, 0, DEBUG_LOCATION);
879 gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
880 servers_[0]->Shutdown();
881 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
882 gpr_log(GPR_INFO, "****** RESTARTING SERVER ******");
883 StartServers(1, ports);
884 WaitForServer(stub, 0, DEBUG_LOCATION);
887 TEST_F(ClientLbEnd2endTest,
888 PickFirstReconnectWithoutNewResolverResultStartsFromTopOfList) {
889 std::vector<int> ports = {grpc_pick_unused_port_or_die(),
890 grpc_pick_unused_port_or_die()};
891 CreateServers(2, ports);
893 auto response_generator = BuildResolverResponseGenerator();
894 auto channel = BuildChannel("pick_first", response_generator);
895 auto stub = BuildStub(channel);
896 response_generator.SetNextResolution(ports);
897 gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
898 WaitForServer(stub, 1, DEBUG_LOCATION);
899 gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
900 servers_[1]->Shutdown();
901 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
902 gpr_log(GPR_INFO, "****** STARTING BOTH SERVERS ******");
903 StartServers(2, ports);
904 WaitForServer(stub, 0, DEBUG_LOCATION);
907 TEST_F(ClientLbEnd2endTest, PickFirstCheckStateBeforeStartWatch) {
908 std::vector<int> ports = {grpc_pick_unused_port_or_die()};
909 StartServers(1, ports);
910 auto response_generator = BuildResolverResponseGenerator();
911 auto channel_1 = BuildChannel("pick_first", response_generator);
912 auto stub_1 = BuildStub(channel_1);
913 response_generator.SetNextResolution(ports);
914 gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 1 *******");
915 WaitForServer(stub_1, 0, DEBUG_LOCATION);
916 gpr_log(GPR_INFO, "****** CHANNEL 1 CONNECTED *******");
917 servers_[0]->Shutdown();
918 // Channel 1 will receive a re-resolution containing the same server. It will
919 // create a new subchannel and hold a ref to it.
920 StartServers(1, ports);
921 gpr_log(GPR_INFO, "****** SERVER RESTARTED *******");
922 auto response_generator_2 = BuildResolverResponseGenerator();
923 auto channel_2 = BuildChannel("pick_first", response_generator_2);
924 auto stub_2 = BuildStub(channel_2);
925 response_generator_2.SetNextResolution(ports);
926 gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 2 *******");
927 WaitForServer(stub_2, 0, DEBUG_LOCATION, true);
928 gpr_log(GPR_INFO, "****** CHANNEL 2 CONNECTED *******");
929 servers_[0]->Shutdown();
930 // Wait until the disconnection has triggered the connectivity notification.
931 // Otherwise, the subchannel may be picked for next call but will fail soon.
932 EXPECT_TRUE(WaitForChannelNotReady(channel_2.get()));
933 // Channel 2 will also receive a re-resolution containing the same server.
934 // Both channels will ref the same subchannel that failed.
935 StartServers(1, ports);
936 gpr_log(GPR_INFO, "****** SERVER RESTARTED AGAIN *******");
937 gpr_log(GPR_INFO, "****** CHANNEL 2 STARTING A CALL *******");
938 // The first call after the server restart will succeed.
939 CheckRpcSendOk(stub_2, DEBUG_LOCATION);
940 gpr_log(GPR_INFO, "****** CHANNEL 2 FINISHED A CALL *******");
941 // Check LB policy name for the channel.
942 EXPECT_EQ("pick_first", channel_1->GetLoadBalancingPolicyName());
943 // Check LB policy name for the channel.
944 EXPECT_EQ("pick_first", channel_2->GetLoadBalancingPolicyName());
947 TEST_F(ClientLbEnd2endTest, PickFirstIdleOnDisconnect) {
948 // Start server, send RPC, and make sure channel is READY.
949 const int kNumServers = 1;
950 StartServers(kNumServers);
951 auto response_generator = BuildResolverResponseGenerator();
953 BuildChannel("", response_generator); // pick_first is the default.
954 auto stub = BuildStub(channel);
955 response_generator.SetNextResolution(GetServersPorts());
956 CheckRpcSendOk(stub, DEBUG_LOCATION);
957 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
958 // Stop server. Channel should go into state IDLE.
959 response_generator.SetFailureOnReresolution();
960 servers_[0]->Shutdown();
961 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
962 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
966 TEST_F(ClientLbEnd2endTest, PickFirstPendingUpdateAndSelectedSubchannelFails) {
967 auto response_generator = BuildResolverResponseGenerator();
969 BuildChannel("", response_generator); // pick_first is the default.
970 auto stub = BuildStub(channel);
971 // Create a number of servers, but only start 1 of them.
974 // Initially resolve to first server and make sure it connects.
975 gpr_log(GPR_INFO, "Phase 1: Connect to first server.");
976 response_generator.SetNextResolution({servers_[0]->port_});
977 CheckRpcSendOk(stub, DEBUG_LOCATION, true /* wait_for_ready */);
978 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
979 // Send a resolution update with the remaining servers, none of which are
980 // running yet, so the update will stay pending. Note that it's important
981 // to have multiple servers here, or else the test will be flaky; with only
982 // one server, the pending subchannel list has already gone into
983 // TRANSIENT_FAILURE due to hitting the end of the list by the time we
986 "Phase 2: Resolver update pointing to remaining "
987 "(not started) servers.");
988 response_generator.SetNextResolution(GetServersPorts(1 /* start_index */));
989 // RPCs will continue to be sent to the first server.
990 CheckRpcSendOk(stub, DEBUG_LOCATION);
991 // Now stop the first server, so that the current subchannel list
992 // fails. This should cause us to immediately swap over to the
993 // pending list, even though it's not yet connected. The state should
994 // be set to CONNECTING, since that's what the pending subchannel list
995 // was doing when we swapped over.
996 gpr_log(GPR_INFO, "Phase 3: Stopping first server.");
997 servers_[0]->Shutdown();
998 WaitForChannelNotReady(channel.get());
999 // TODO(roth): This should always return CONNECTING, but it's flaky
1000 // between that and TRANSIENT_FAILURE. I suspect that this problem
1001 // will go away once we move the backoff code out of the subchannel
1002 // and into the LB policies.
1003 EXPECT_THAT(channel->GetState(false),
1004 ::testing::AnyOf(GRPC_CHANNEL_CONNECTING,
1005 GRPC_CHANNEL_TRANSIENT_FAILURE));
1006 // Now start the second server.
1007 gpr_log(GPR_INFO, "Phase 4: Starting second server.");
1009 // The channel should go to READY state and RPCs should go to the
1011 WaitForChannelReady(channel.get());
1012 WaitForServer(stub, 1, DEBUG_LOCATION, true /* ignore_failure */);
1015 TEST_F(ClientLbEnd2endTest, PickFirstStaysIdleUponEmptyUpdate) {
1016 // Start server, send RPC, and make sure channel is READY.
1017 const int kNumServers = 1;
1018 StartServers(kNumServers);
1019 auto response_generator = BuildResolverResponseGenerator();
1021 BuildChannel("", response_generator); // pick_first is the default.
1022 auto stub = BuildStub(channel);
1023 response_generator.SetNextResolution(GetServersPorts());
1024 CheckRpcSendOk(stub, DEBUG_LOCATION);
1025 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
1026 // Stop server. Channel should go into state IDLE.
1027 servers_[0]->Shutdown();
1028 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
1029 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
1030 // Now send resolver update that includes no addresses. Channel
1031 // should stay in state IDLE.
1032 response_generator.SetNextResolution({});
1033 EXPECT_FALSE(channel->WaitForStateChange(
1034 GRPC_CHANNEL_IDLE, grpc_timeout_seconds_to_deadline(3)));
1035 // Now bring the backend back up and send a non-empty resolver update,
1036 // and then try to send an RPC. Channel should go back into state READY.
1038 response_generator.SetNextResolution(GetServersPorts());
1039 CheckRpcSendOk(stub, DEBUG_LOCATION);
1040 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
1043 TEST_F(ClientLbEnd2endTest, RoundRobin) {
1044 // Start servers and send one RPC per server.
1045 const int kNumServers = 3;
1046 StartServers(kNumServers);
1047 auto response_generator = BuildResolverResponseGenerator();
1048 auto channel = BuildChannel("round_robin", response_generator);
1049 auto stub = BuildStub(channel);
1050 response_generator.SetNextResolution(GetServersPorts());
1051 // Wait until all backends are ready.
1053 CheckRpcSendOk(stub, DEBUG_LOCATION);
1054 } while (!SeenAllServers());
1056 // "Sync" to the end of the list. Next sequence of picks will start at the
1057 // first server (index 0).
1058 WaitForServer(stub, servers_.size() - 1, DEBUG_LOCATION);
1059 std::vector<int> connection_order;
1060 for (size_t i = 0; i < servers_.size(); ++i) {
1061 CheckRpcSendOk(stub, DEBUG_LOCATION);
1062 UpdateConnectionOrder(servers_, &connection_order);
1064 // Backends should be iterated over in the order in which the addresses were
1066 const auto expected = std::vector<int>{0, 1, 2};
1067 EXPECT_EQ(expected, connection_order);
1068 // Check LB policy name for the channel.
1069 EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
1072 TEST_F(ClientLbEnd2endTest, RoundRobinProcessPending) {
1073 StartServers(1); // Single server
1074 auto response_generator = BuildResolverResponseGenerator();
1075 auto channel = BuildChannel("round_robin", response_generator);
1076 auto stub = BuildStub(channel);
1077 response_generator.SetNextResolution({servers_[0]->port_});
1078 WaitForServer(stub, 0, DEBUG_LOCATION);
1079 // Create a new channel and its corresponding RR LB policy, which will pick
1080 // the subchannels in READY state from the previous RPC against the same
1081 // target (even if it happened over a different channel, because subchannels
1082 // are globally reused). Progress should happen without any transition from
1083 // this READY state.
1084 auto second_response_generator = BuildResolverResponseGenerator();
1085 auto second_channel = BuildChannel("round_robin", second_response_generator);
1086 auto second_stub = BuildStub(second_channel);
1087 second_response_generator.SetNextResolution({servers_[0]->port_});
1088 CheckRpcSendOk(second_stub, DEBUG_LOCATION);
1091 TEST_F(ClientLbEnd2endTest, RoundRobinUpdates) {
1092 // Start servers and send one RPC per server.
1093 const int kNumServers = 3;
1094 StartServers(kNumServers);
1095 auto response_generator = BuildResolverResponseGenerator();
1096 auto channel = BuildChannel("round_robin", response_generator);
1097 auto stub = BuildStub(channel);
1098 std::vector<int> ports;
1099 // Start with a single server.
1100 gpr_log(GPR_INFO, "*** FIRST BACKEND ***");
1101 ports.emplace_back(servers_[0]->port_);
1102 response_generator.SetNextResolution(ports);
1103 WaitForServer(stub, 0, DEBUG_LOCATION);
1104 // Send RPCs. They should all go servers_[0]
1105 for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
1106 EXPECT_EQ(10, servers_[0]->service_.request_count());
1107 EXPECT_EQ(0, servers_[1]->service_.request_count());
1108 EXPECT_EQ(0, servers_[2]->service_.request_count());
1109 servers_[0]->service_.ResetCounters();
1110 // And now for the second server.
1111 gpr_log(GPR_INFO, "*** SECOND BACKEND ***");
1113 ports.emplace_back(servers_[1]->port_);
1114 response_generator.SetNextResolution(ports);
1115 // Wait until update has been processed, as signaled by the second backend
1116 // receiving a request.
1117 EXPECT_EQ(0, servers_[1]->service_.request_count());
1118 WaitForServer(stub, 1, DEBUG_LOCATION);
1119 for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
1120 EXPECT_EQ(0, servers_[0]->service_.request_count());
1121 EXPECT_EQ(10, servers_[1]->service_.request_count());
1122 EXPECT_EQ(0, servers_[2]->service_.request_count());
1123 servers_[1]->service_.ResetCounters();
1124 // ... and for the last server.
1125 gpr_log(GPR_INFO, "*** THIRD BACKEND ***");
1127 ports.emplace_back(servers_[2]->port_);
1128 response_generator.SetNextResolution(ports);
1129 WaitForServer(stub, 2, DEBUG_LOCATION);
1130 for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
1131 EXPECT_EQ(0, servers_[0]->service_.request_count());
1132 EXPECT_EQ(0, servers_[1]->service_.request_count());
1133 EXPECT_EQ(10, servers_[2]->service_.request_count());
1134 servers_[2]->service_.ResetCounters();
1135 // Back to all servers.
1136 gpr_log(GPR_INFO, "*** ALL BACKENDS ***");
1138 ports.emplace_back(servers_[0]->port_);
1139 ports.emplace_back(servers_[1]->port_);
1140 ports.emplace_back(servers_[2]->port_);
1141 response_generator.SetNextResolution(ports);
1142 WaitForServer(stub, 0, DEBUG_LOCATION);
1143 WaitForServer(stub, 1, DEBUG_LOCATION);
1144 WaitForServer(stub, 2, DEBUG_LOCATION);
1145 // Send three RPCs, one per server.
1146 for (size_t i = 0; i < 3; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
1147 EXPECT_EQ(1, servers_[0]->service_.request_count());
1148 EXPECT_EQ(1, servers_[1]->service_.request_count());
1149 EXPECT_EQ(1, servers_[2]->service_.request_count());
1150 // An empty update will result in the channel going into TRANSIENT_FAILURE.
1151 gpr_log(GPR_INFO, "*** NO BACKENDS ***");
1153 response_generator.SetNextResolution(ports);
1154 grpc_connectivity_state channel_state;
1156 channel_state = channel->GetState(true /* try to connect */);
1157 } while (channel_state == GRPC_CHANNEL_READY);
1158 ASSERT_NE(channel_state, GRPC_CHANNEL_READY);
1159 servers_[0]->service_.ResetCounters();
1160 // Next update introduces servers_[1], making the channel recover.
1161 gpr_log(GPR_INFO, "*** BACK TO SECOND BACKEND ***");
1163 ports.emplace_back(servers_[1]->port_);
1164 response_generator.SetNextResolution(ports);
1165 WaitForServer(stub, 1, DEBUG_LOCATION);
1166 channel_state = channel->GetState(false /* try to connect */);
1167 ASSERT_EQ(channel_state, GRPC_CHANNEL_READY);
1168 // Check LB policy name for the channel.
1169 EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
1172 TEST_F(ClientLbEnd2endTest, RoundRobinUpdateInError) {
1173 const int kNumServers = 3;
1174 StartServers(kNumServers);
1175 auto response_generator = BuildResolverResponseGenerator();
1176 auto channel = BuildChannel("round_robin", response_generator);
1177 auto stub = BuildStub(channel);
1178 std::vector<int> ports;
1180 // Start with a single server.
1181 ports.emplace_back(servers_[0]->port_);
1182 response_generator.SetNextResolution(ports);
1183 WaitForServer(stub, 0, DEBUG_LOCATION);
1184 // Send RPCs. They should all go to servers_[0]
1185 for (size_t i = 0; i < 10; ++i) SendRpc(stub);
1186 EXPECT_EQ(10, servers_[0]->service_.request_count());
1187 EXPECT_EQ(0, servers_[1]->service_.request_count());
1188 EXPECT_EQ(0, servers_[2]->service_.request_count());
1189 servers_[0]->service_.ResetCounters();
1191 // Shutdown one of the servers to be sent in the update.
1192 servers_[1]->Shutdown();
1193 ports.emplace_back(servers_[1]->port_);
1194 ports.emplace_back(servers_[2]->port_);
1195 response_generator.SetNextResolution(ports);
1196 WaitForServer(stub, 0, DEBUG_LOCATION);
1197 WaitForServer(stub, 2, DEBUG_LOCATION);
1199 // Send three RPCs, one per server.
1200 for (size_t i = 0; i < kNumServers; ++i) SendRpc(stub);
1201 // The server in shutdown shouldn't receive any.
1202 EXPECT_EQ(0, servers_[1]->service_.request_count());
1205 TEST_F(ClientLbEnd2endTest, RoundRobinManyUpdates) {
1206 // Start servers and send one RPC per server.
1207 const int kNumServers = 3;
1208 StartServers(kNumServers);
1209 auto response_generator = BuildResolverResponseGenerator();
1210 auto channel = BuildChannel("round_robin", response_generator);
1211 auto stub = BuildStub(channel);
1212 std::vector<int> ports = GetServersPorts();
1213 for (size_t i = 0; i < 1000; ++i) {
1214 std::shuffle(ports.begin(), ports.end(),
1215 std::mt19937(std::random_device()()));
1216 response_generator.SetNextResolution(ports);
1217 if (i % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
1219 // Check LB policy name for the channel.
1220 EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
1223 TEST_F(ClientLbEnd2endTest, RoundRobinConcurrentUpdates) {
1224 // TODO(dgq): replicate the way internal testing exercises the concurrent
1225 // update provisions of RR.
1228 TEST_F(ClientLbEnd2endTest, RoundRobinReresolve) {
1229 // Start servers and send one RPC per server.
1230 const int kNumServers = 3;
1231 std::vector<int> first_ports;
1232 std::vector<int> second_ports;
1233 first_ports.reserve(kNumServers);
1234 for (int i = 0; i < kNumServers; ++i) {
1235 first_ports.push_back(grpc_pick_unused_port_or_die());
1237 second_ports.reserve(kNumServers);
1238 for (int i = 0; i < kNumServers; ++i) {
1239 second_ports.push_back(grpc_pick_unused_port_or_die());
1241 StartServers(kNumServers, first_ports);
1242 auto response_generator = BuildResolverResponseGenerator();
1243 auto channel = BuildChannel("round_robin", response_generator);
1244 auto stub = BuildStub(channel);
1245 response_generator.SetNextResolution(first_ports);
1246 // Send a number of RPCs, which succeed.
1247 for (size_t i = 0; i < 100; ++i) {
1248 CheckRpcSendOk(stub, DEBUG_LOCATION);
1251 gpr_log(GPR_INFO, "****** ABOUT TO KILL SERVERS *******");
1252 for (size_t i = 0; i < servers_.size(); ++i) {
1253 servers_[i]->Shutdown();
1255 gpr_log(GPR_INFO, "****** SERVERS KILLED *******");
1256 gpr_log(GPR_INFO, "****** SENDING DOOMED REQUESTS *******");
1257 // Client requests should fail. Send enough to tickle all subchannels.
1258 for (size_t i = 0; i < servers_.size(); ++i) CheckRpcSendFailure(stub);
1259 gpr_log(GPR_INFO, "****** DOOMED REQUESTS SENT *******");
1260 // Bring servers back up on a different set of ports. We need to do this to be
1261 // sure that the eventual success is *not* due to subchannel reconnection
1262 // attempts and that an actual re-resolution has happened as a result of the
1263 // RR policy going into transient failure when all its subchannels become
1264 // unavailable (in transient failure as well).
1265 gpr_log(GPR_INFO, "****** RESTARTING SERVERS *******");
1266 StartServers(kNumServers, second_ports);
1267 // Don't notify of the update. Wait for the LB policy's re-resolution to
1268 // "pull" the new ports.
1269 response_generator.SetNextResolutionUponError(second_ports);
1270 gpr_log(GPR_INFO, "****** SERVERS RESTARTED *******");
1271 gpr_log(GPR_INFO, "****** SENDING REQUEST TO SUCCEED *******");
1272 // Client request should eventually (but still fairly soon) succeed.
1273 const gpr_timespec deadline = grpc_timeout_seconds_to_deadline(5);
1274 gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
1275 while (gpr_time_cmp(deadline, now) > 0) {
1276 if (SendRpc(stub)) break;
1277 now = gpr_now(GPR_CLOCK_MONOTONIC);
1279 ASSERT_GT(gpr_time_cmp(deadline, now), 0);
1282 TEST_F(ClientLbEnd2endTest, RoundRobinSingleReconnect) {
1283 const int kNumServers = 3;
1284 StartServers(kNumServers);
1285 const auto ports = GetServersPorts();
1286 auto response_generator = BuildResolverResponseGenerator();
1287 auto channel = BuildChannel("round_robin", response_generator);
1288 auto stub = BuildStub(channel);
1289 response_generator.SetNextResolution(ports);
1290 for (size_t i = 0; i < kNumServers; ++i) {
1291 WaitForServer(stub, i, DEBUG_LOCATION);
1293 for (size_t i = 0; i < servers_.size(); ++i) {
1294 CheckRpcSendOk(stub, DEBUG_LOCATION);
1295 EXPECT_EQ(1, servers_[i]->service_.request_count()) << "for backend #" << i;
1297 // One request should have gone to each server.
1298 for (size_t i = 0; i < servers_.size(); ++i) {
1299 EXPECT_EQ(1, servers_[i]->service_.request_count());
1301 const auto pre_death = servers_[0]->service_.request_count();
1302 // Kill the first server.
1303 servers_[0]->Shutdown();
1304 // Client request still succeed. May need retrying if RR had returned a pick
1305 // before noticing the change in the server's connectivity.
1306 while (!SendRpc(stub)) {
1307 } // Retry until success.
1308 // Send a bunch of RPCs that should succeed.
1309 for (int i = 0; i < 10 * kNumServers; ++i) {
1310 CheckRpcSendOk(stub, DEBUG_LOCATION);
1312 const auto post_death = servers_[0]->service_.request_count();
1313 // No requests have gone to the deceased server.
1314 EXPECT_EQ(pre_death, post_death);
1315 // Bring the first server back up.
1317 // Requests should start arriving at the first server either right away (if
1318 // the server managed to start before the RR policy retried the subchannel) or
1319 // after the subchannel retry delay otherwise (RR's subchannel retried before
1320 // the server was fully back up).
1321 WaitForServer(stub, 0, DEBUG_LOCATION);
1324 // If health checking is required by client but health checking service
1325 // is not running on the server, the channel should be treated as healthy.
1326 TEST_F(ClientLbEnd2endTest,
1327 RoundRobinServersHealthCheckingUnimplementedTreatedAsHealthy) {
1328 StartServers(1); // Single server
1329 ChannelArguments args;
1330 args.SetServiceConfigJSON(
1331 "{\"healthCheckConfig\": "
1332 "{\"serviceName\": \"health_check_service_name\"}}");
1333 auto response_generator = BuildResolverResponseGenerator();
1334 auto channel = BuildChannel("round_robin", response_generator, args);
1335 auto stub = BuildStub(channel);
1336 response_generator.SetNextResolution({servers_[0]->port_});
1337 EXPECT_TRUE(WaitForChannelReady(channel.get()));
1338 CheckRpcSendOk(stub, DEBUG_LOCATION);
1341 TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthChecking) {
1342 EnableDefaultHealthCheckService(true);
1344 const int kNumServers = 3;
1345 StartServers(kNumServers);
1346 ChannelArguments args;
1347 args.SetServiceConfigJSON(
1348 "{\"healthCheckConfig\": "
1349 "{\"serviceName\": \"health_check_service_name\"}}");
1350 auto response_generator = BuildResolverResponseGenerator();
1351 auto channel = BuildChannel("round_robin", response_generator, args);
1352 auto stub = BuildStub(channel);
1353 response_generator.SetNextResolution(GetServersPorts());
1354 // Channel should not become READY, because health checks should be failing.
1356 "*** initial state: unknown health check service name for "
1358 EXPECT_FALSE(WaitForChannelReady(channel.get(), 1));
1359 // Now set one of the servers to be healthy.
1360 // The channel should become healthy and all requests should go to
1361 // the healthy server.
1362 gpr_log(GPR_INFO, "*** server 0 healthy");
1363 servers_[0]->SetServingStatus("health_check_service_name", true);
1364 EXPECT_TRUE(WaitForChannelReady(channel.get()));
1365 for (int i = 0; i < 10; ++i) {
1366 CheckRpcSendOk(stub, DEBUG_LOCATION);
1368 EXPECT_EQ(10, servers_[0]->service_.request_count());
1369 EXPECT_EQ(0, servers_[1]->service_.request_count());
1370 EXPECT_EQ(0, servers_[2]->service_.request_count());
1371 // Now set a second server to be healthy.
1372 gpr_log(GPR_INFO, "*** server 2 healthy");
1373 servers_[2]->SetServingStatus("health_check_service_name", true);
1374 WaitForServer(stub, 2, DEBUG_LOCATION);
1375 for (int i = 0; i < 10; ++i) {
1376 CheckRpcSendOk(stub, DEBUG_LOCATION);
1378 EXPECT_EQ(5, servers_[0]->service_.request_count());
1379 EXPECT_EQ(0, servers_[1]->service_.request_count());
1380 EXPECT_EQ(5, servers_[2]->service_.request_count());
1381 // Now set the remaining server to be healthy.
1382 gpr_log(GPR_INFO, "*** server 1 healthy");
1383 servers_[1]->SetServingStatus("health_check_service_name", true);
1384 WaitForServer(stub, 1, DEBUG_LOCATION);
1385 for (int i = 0; i < 9; ++i) {
1386 CheckRpcSendOk(stub, DEBUG_LOCATION);
1388 EXPECT_EQ(3, servers_[0]->service_.request_count());
1389 EXPECT_EQ(3, servers_[1]->service_.request_count());
1390 EXPECT_EQ(3, servers_[2]->service_.request_count());
1391 // Now set one server to be unhealthy again. Then wait until the
1392 // unhealthiness has hit the client. We know that the client will see
1393 // this when we send kNumServers requests and one of the remaining servers
1394 // sees two of the requests.
1395 gpr_log(GPR_INFO, "*** server 0 unhealthy");
1396 servers_[0]->SetServingStatus("health_check_service_name", false);
1399 for (int i = 0; i < kNumServers; ++i) {
1400 CheckRpcSendOk(stub, DEBUG_LOCATION);
1402 } while (servers_[1]->service_.request_count() != 2 &&
1403 servers_[2]->service_.request_count() != 2);
1404 // Now set the remaining two servers to be unhealthy. Make sure the
1405 // channel leaves READY state and that RPCs fail.
1406 gpr_log(GPR_INFO, "*** all servers unhealthy");
1407 servers_[1]->SetServingStatus("health_check_service_name", false);
1408 servers_[2]->SetServingStatus("health_check_service_name", false);
1409 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
1410 CheckRpcSendFailure(stub);
1412 EnableDefaultHealthCheckService(false);
1415 TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthCheckingInhibitPerChannel) {
1416 EnableDefaultHealthCheckService(true);
1418 const int kNumServers = 1;
1419 StartServers(kNumServers);
1420 // Create a channel with health-checking enabled.
1421 ChannelArguments args;
1422 args.SetServiceConfigJSON(
1423 "{\"healthCheckConfig\": "
1424 "{\"serviceName\": \"health_check_service_name\"}}");
1425 auto response_generator1 = BuildResolverResponseGenerator();
1426 auto channel1 = BuildChannel("round_robin", response_generator1, args);
1427 auto stub1 = BuildStub(channel1);
1428 std::vector<int> ports = GetServersPorts();
1429 response_generator1.SetNextResolution(ports);
1430 // Create a channel with health checking enabled but inhibited.
1431 args.SetInt(GRPC_ARG_INHIBIT_HEALTH_CHECKING, 1);
1432 auto response_generator2 = BuildResolverResponseGenerator();
1433 auto channel2 = BuildChannel("round_robin", response_generator2, args);
1434 auto stub2 = BuildStub(channel2);
1435 response_generator2.SetNextResolution(ports);
1436 // First channel should not become READY, because health checks should be
1438 EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
1439 CheckRpcSendFailure(stub1);
1440 // Second channel should be READY.
1441 EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
1442 CheckRpcSendOk(stub2, DEBUG_LOCATION);
1443 // Enable health checks on the backend and wait for channel 1 to succeed.
1444 servers_[0]->SetServingStatus("health_check_service_name", true);
1445 CheckRpcSendOk(stub1, DEBUG_LOCATION, true /* wait_for_ready */);
1446 // Check that we created only one subchannel to the backend.
1447 EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
1449 EnableDefaultHealthCheckService(false);
1452 TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthCheckingServiceNamePerChannel) {
1453 EnableDefaultHealthCheckService(true);
1455 const int kNumServers = 1;
1456 StartServers(kNumServers);
1457 // Create a channel with health-checking enabled.
1458 ChannelArguments args;
1459 args.SetServiceConfigJSON(
1460 "{\"healthCheckConfig\": "
1461 "{\"serviceName\": \"health_check_service_name\"}}");
1462 auto response_generator1 = BuildResolverResponseGenerator();
1463 auto channel1 = BuildChannel("round_robin", response_generator1, args);
1464 auto stub1 = BuildStub(channel1);
1465 std::vector<int> ports = GetServersPorts();
1466 response_generator1.SetNextResolution(ports);
1467 // Create a channel with health-checking enabled with a different
1469 ChannelArguments args2;
1470 args2.SetServiceConfigJSON(
1471 "{\"healthCheckConfig\": "
1472 "{\"serviceName\": \"health_check_service_name2\"}}");
1473 auto response_generator2 = BuildResolverResponseGenerator();
1474 auto channel2 = BuildChannel("round_robin", response_generator2, args2);
1475 auto stub2 = BuildStub(channel2);
1476 response_generator2.SetNextResolution(ports);
1477 // Allow health checks from channel 2 to succeed.
1478 servers_[0]->SetServingStatus("health_check_service_name2", true);
1479 // First channel should not become READY, because health checks should be
1481 EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
1482 CheckRpcSendFailure(stub1);
1483 // Second channel should be READY.
1484 EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
1485 CheckRpcSendOk(stub2, DEBUG_LOCATION);
1486 // Enable health checks for channel 1 and wait for it to succeed.
1487 servers_[0]->SetServingStatus("health_check_service_name", true);
1488 CheckRpcSendOk(stub1, DEBUG_LOCATION, true /* wait_for_ready */);
1489 // Check that we created only one subchannel to the backend.
1490 EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
1492 EnableDefaultHealthCheckService(false);
1495 TEST_F(ClientLbEnd2endTest,
1496 RoundRobinWithHealthCheckingServiceNameChangesAfterSubchannelsCreated) {
1497 EnableDefaultHealthCheckService(true);
1499 const int kNumServers = 1;
1500 StartServers(kNumServers);
1501 // Create a channel with health-checking enabled.
1502 const char* kServiceConfigJson =
1503 "{\"healthCheckConfig\": "
1504 "{\"serviceName\": \"health_check_service_name\"}}";
1505 auto response_generator = BuildResolverResponseGenerator();
1506 auto channel = BuildChannel("round_robin", response_generator);
1507 auto stub = BuildStub(channel);
1508 std::vector<int> ports = GetServersPorts();
1509 response_generator.SetNextResolution(ports, kServiceConfigJson);
1510 servers_[0]->SetServingStatus("health_check_service_name", true);
1511 EXPECT_TRUE(WaitForChannelReady(channel.get(), 1 /* timeout_seconds */));
1512 // Send an update on the channel to change it to use a health checking
1513 // service name that is not being reported as healthy.
1514 const char* kServiceConfigJson2 =
1515 "{\"healthCheckConfig\": "
1516 "{\"serviceName\": \"health_check_service_name2\"}}";
1517 response_generator.SetNextResolution(ports, kServiceConfigJson2);
1518 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
1520 EnableDefaultHealthCheckService(false);
1523 TEST_F(ClientLbEnd2endTest, ChannelIdleness) {
1525 const int kNumServers = 1;
1526 StartServers(kNumServers);
1527 // Set max idle time and build the channel.
1528 ChannelArguments args;
1529 args.SetInt(GRPC_ARG_CLIENT_IDLE_TIMEOUT_MS, 1000);
1530 auto response_generator = BuildResolverResponseGenerator();
1531 auto channel = BuildChannel("", response_generator, args);
1532 auto stub = BuildStub(channel);
1533 // The initial channel state should be IDLE.
1534 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
1535 // After sending RPC, channel state should be READY.
1536 response_generator.SetNextResolution(GetServersPorts());
1537 CheckRpcSendOk(stub, DEBUG_LOCATION);
1538 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
1539 // After a period time not using the channel, the channel state should switch
1541 gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(1200));
1542 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
1543 // Sending a new RPC should awake the IDLE channel.
1544 response_generator.SetNextResolution(GetServersPorts());
1545 CheckRpcSendOk(stub, DEBUG_LOCATION);
1546 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
1549 class ClientLbInterceptTrailingMetadataTest : public ClientLbEnd2endTest {
1551 void SetUp() override {
1552 ClientLbEnd2endTest::SetUp();
1553 grpc_core::RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
1554 ReportTrailerIntercepted, this);
1557 void TearDown() override { ClientLbEnd2endTest::TearDown(); }
1559 int trailers_intercepted() {
1560 grpc::internal::MutexLock lock(&mu_);
1561 return trailers_intercepted_;
1564 const udpa::data::orca::v1::OrcaLoadReport* backend_load_report() {
1565 grpc::internal::MutexLock lock(&mu_);
1566 return load_report_.get();
1570 static void ReportTrailerIntercepted(
1571 void* arg, const grpc_core::LoadBalancingPolicy::BackendMetricData*
1572 backend_metric_data) {
1573 ClientLbInterceptTrailingMetadataTest* self =
1574 static_cast<ClientLbInterceptTrailingMetadataTest*>(arg);
1575 grpc::internal::MutexLock lock(&self->mu_);
1576 self->trailers_intercepted_++;
1577 if (backend_metric_data != nullptr) {
1578 self->load_report_.reset(new udpa::data::orca::v1::OrcaLoadReport);
1579 self->load_report_->set_cpu_utilization(
1580 backend_metric_data->cpu_utilization);
1581 self->load_report_->set_mem_utilization(
1582 backend_metric_data->mem_utilization);
1583 self->load_report_->set_rps(backend_metric_data->requests_per_second);
1584 for (const auto& p : backend_metric_data->request_cost) {
1585 grpc_core::UniquePtr<char> name = p.first.dup();
1586 (*self->load_report_->mutable_request_cost())[name.get()] = p.second;
1588 for (const auto& p : backend_metric_data->utilization) {
1589 grpc_core::UniquePtr<char> name = p.first.dup();
1590 (*self->load_report_->mutable_utilization())[name.get()] = p.second;
1595 grpc::internal::Mutex mu_;
1596 int trailers_intercepted_ = 0;
1597 std::unique_ptr<udpa::data::orca::v1::OrcaLoadReport> load_report_;
1600 TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesDisabled) {
1601 const int kNumServers = 1;
1602 const int kNumRpcs = 10;
1603 StartServers(kNumServers);
1604 auto response_generator = BuildResolverResponseGenerator();
1606 BuildChannel("intercept_trailing_metadata_lb", response_generator);
1607 auto stub = BuildStub(channel);
1608 response_generator.SetNextResolution(GetServersPorts());
1609 for (size_t i = 0; i < kNumRpcs; ++i) {
1610 CheckRpcSendOk(stub, DEBUG_LOCATION);
1612 // Check LB policy name for the channel.
1613 EXPECT_EQ("intercept_trailing_metadata_lb",
1614 channel->GetLoadBalancingPolicyName());
1615 EXPECT_EQ(kNumRpcs, trailers_intercepted());
1616 EXPECT_EQ(nullptr, backend_load_report());
1619 TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesEnabled) {
1620 const int kNumServers = 1;
1621 const int kNumRpcs = 10;
1622 StartServers(kNumServers);
1623 ChannelArguments args;
1624 args.SetServiceConfigJSON(
1626 " \"methodConfig\": [ {\n"
1628 " { \"service\": \"grpc.testing.EchoTestService\" }\n"
1630 " \"retryPolicy\": {\n"
1631 " \"maxAttempts\": 3,\n"
1632 " \"initialBackoff\": \"1s\",\n"
1633 " \"maxBackoff\": \"120s\",\n"
1634 " \"backoffMultiplier\": 1.6,\n"
1635 " \"retryableStatusCodes\": [ \"ABORTED\" ]\n"
1639 auto response_generator = BuildResolverResponseGenerator();
1641 BuildChannel("intercept_trailing_metadata_lb", response_generator, args);
1642 auto stub = BuildStub(channel);
1643 response_generator.SetNextResolution(GetServersPorts());
1644 for (size_t i = 0; i < kNumRpcs; ++i) {
1645 CheckRpcSendOk(stub, DEBUG_LOCATION);
1647 // Check LB policy name for the channel.
1648 EXPECT_EQ("intercept_trailing_metadata_lb",
1649 channel->GetLoadBalancingPolicyName());
1650 EXPECT_EQ(kNumRpcs, trailers_intercepted());
1651 EXPECT_EQ(nullptr, backend_load_report());
1654 TEST_F(ClientLbInterceptTrailingMetadataTest, BackendMetricData) {
1655 const int kNumServers = 1;
1656 const int kNumRpcs = 10;
1657 StartServers(kNumServers);
1658 udpa::data::orca::v1::OrcaLoadReport load_report;
1659 load_report.set_cpu_utilization(0.5);
1660 load_report.set_mem_utilization(0.75);
1661 load_report.set_rps(25);
1662 auto* request_cost = load_report.mutable_request_cost();
1663 (*request_cost)["foo"] = 0.8;
1664 (*request_cost)["bar"] = 1.4;
1665 auto* utilization = load_report.mutable_utilization();
1666 (*utilization)["baz"] = 1.1;
1667 (*utilization)["quux"] = 0.9;
1668 for (const auto& server : servers_) {
1669 server->service_.set_load_report(&load_report);
1671 auto response_generator = BuildResolverResponseGenerator();
1673 BuildChannel("intercept_trailing_metadata_lb", response_generator);
1674 auto stub = BuildStub(channel);
1675 response_generator.SetNextResolution(GetServersPorts());
1676 for (size_t i = 0; i < kNumRpcs; ++i) {
1677 CheckRpcSendOk(stub, DEBUG_LOCATION);
1678 auto* actual = backend_load_report();
1679 ASSERT_NE(actual, nullptr);
1680 // TODO(roth): Change this to use EqualsProto() once that becomes
1681 // available in OSS.
1682 EXPECT_EQ(actual->cpu_utilization(), load_report.cpu_utilization());
1683 EXPECT_EQ(actual->mem_utilization(), load_report.mem_utilization());
1684 EXPECT_EQ(actual->rps(), load_report.rps());
1685 EXPECT_EQ(actual->request_cost().size(), load_report.request_cost().size());
1686 for (const auto& p : actual->request_cost()) {
1687 auto it = load_report.request_cost().find(p.first);
1688 ASSERT_NE(it, load_report.request_cost().end());
1689 EXPECT_EQ(it->second, p.second);
1691 EXPECT_EQ(actual->utilization().size(), load_report.utilization().size());
1692 for (const auto& p : actual->utilization()) {
1693 auto it = load_report.utilization().find(p.first);
1694 ASSERT_NE(it, load_report.utilization().end());
1695 EXPECT_EQ(it->second, p.second);
1698 // Check LB policy name for the channel.
1699 EXPECT_EQ("intercept_trailing_metadata_lb",
1700 channel->GetLoadBalancingPolicyName());
1701 EXPECT_EQ(kNumRpcs, trailers_intercepted());
1705 } // namespace testing
1708 int main(int argc, char** argv) {
1709 ::testing::InitGoogleTest(&argc, argv);
1710 grpc::testing::TestEnvironment env(argc, argv);
1711 const auto result = RUN_ALL_TESTS();