xref: /aosp_15_r20/external/grpc-grpc/test/cpp/end2end/grpclb_end2end_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 // Copyright 2017 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include <deque>
18 #include <memory>
19 #include <mutex>
20 #include <set>
21 #include <sstream>
22 #include <string>
23 #include <thread>
24 
25 #include <gmock/gmock.h>
26 #include <gtest/gtest.h>
27 
28 #include "absl/cleanup/cleanup.h"
29 #include "absl/memory/memory.h"
30 #include "absl/strings/str_cat.h"
31 #include "absl/strings/str_format.h"
32 #include "absl/synchronization/notification.h"
33 #include "absl/types/span.h"
34 
35 #include <grpc/grpc.h>
36 #include <grpc/support/alloc.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/server.h>
43 #include <grpcpp/server_builder.h>
44 
45 #include "src/core/client_channel/backup_poller.h"
46 #include "src/core/lib/address_utils/parse_address.h"
47 #include "src/core/lib/channel/channel_args.h"
48 #include "src/core/lib/config/config_vars.h"
49 #include "src/core/lib/gprpp/crash.h"
50 #include "src/core/lib/gprpp/debug_location.h"
51 #include "src/core/lib/gprpp/env.h"
52 #include "src/core/lib/gprpp/ref_counted_ptr.h"
53 #include "src/core/lib/gprpp/sync.h"
54 #include "src/core/lib/iomgr/sockaddr.h"
55 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
56 #include "src/core/load_balancing/grpclb/grpclb.h"
57 #include "src/core/load_balancing/grpclb/grpclb_balancer_addresses.h"
58 #include "src/core/resolver/endpoint_addresses.h"
59 #include "src/core/resolver/fake/fake_resolver.h"
60 #include "src/core/service_config/service_config_impl.h"
61 #include "src/cpp/server/secure_server_credentials.h"
62 #include "src/proto/grpc/lb/v1/load_balancer.grpc.pb.h"
63 #include "src/proto/grpc/testing/echo.grpc.pb.h"
64 #include "test/core/util/port.h"
65 #include "test/core/util/resolve_localhost_ip46.h"
66 #include "test/core/util/test_config.h"
67 #include "test/cpp/end2end/counted_service.h"
68 #include "test/cpp/end2end/test_service_impl.h"
69 #include "test/cpp/util/credentials.h"
70 #include "test/cpp/util/test_config.h"
71 
72 // TODO(dgq): Other scenarios in need of testing:
73 // - Send a serverlist with faulty ip:port addresses (port > 2^16, etc).
74 // - Test reception of invalid serverlist
75 // - Test against a non-LB server.
76 // - Random LB server closing the stream unexpectedly.
77 //
78 // Findings from end to end testing to be covered here:
79 // - Handling of LB servers restart, including reconnection after backing-off
80 //   retries.
81 // - Destruction of load balanced channel (and therefore of grpclb instance)
82 //   while:
83 //   1) the internal LB call is still active. This should work by virtue
84 //   of the weak reference the LB call holds. The call should be terminated as
85 //   part of the grpclb shutdown process.
86 //   2) the retry timer is active. Again, the weak reference it holds should
87 //   prevent a premature call to \a glb_destroy.
88 
89 using grpc::lb::v1::LoadBalancer;
90 using grpc::lb::v1::LoadBalanceRequest;
91 using grpc::lb::v1::LoadBalanceResponse;
92 
93 using grpc_core::SourceLocation;
94 
95 namespace grpc {
96 namespace testing {
97 namespace {
98 
99 constexpr char kDefaultServiceConfig[] =
100     "{\n"
101     "  \"loadBalancingConfig\":[\n"
102     "    { \"grpclb\":{} }\n"
103     "  ]\n"
104     "}";
105 
106 using BackendService = CountedService<TestServiceImpl>;
107 using BalancerService = CountedService<LoadBalancer::Service>;
108 
109 const char kCallCredsMdKey[] = "call-creds";
110 const char kCallCredsMdValue[] = "should not be received by balancer";
111 const char kRequestMessage[] = "Live long and prosper.";
112 const absl::string_view kApplicationTargetName = "application_target_name";
113 
114 // A test user agent string sent by the client only to the grpclb loadbalancer.
115 // The backend should not see this user-agent string.
116 constexpr char kGrpclbSpecificUserAgentString[] = "grpc-grpclb-test-user-agent";
117 
118 class BackendServiceImpl : public BackendService {
119  public:
BackendServiceImpl()120   BackendServiceImpl() {}
121 
Echo(ServerContext * context,const EchoRequest * request,EchoResponse * response)122   Status Echo(ServerContext* context, const EchoRequest* request,
123               EchoResponse* response) override {
124     // The backend should not see a test user agent configured at the client
125     // using GRPC_ARG_GRPCLB_CHANNEL_ARGS.
126     auto it = context->client_metadata().find("user-agent");
127     if (it != context->client_metadata().end()) {
128       EXPECT_FALSE(it->second.starts_with(kGrpclbSpecificUserAgentString));
129     }
130     // Backend should receive the call credentials metadata.
131     auto call_credentials_entry =
132         context->client_metadata().find(kCallCredsMdKey);
133     EXPECT_NE(call_credentials_entry, context->client_metadata().end());
134     if (call_credentials_entry != context->client_metadata().end()) {
135       EXPECT_EQ(call_credentials_entry->second, kCallCredsMdValue);
136     }
137     IncreaseRequestCount();
138     const auto status = TestServiceImpl::Echo(context, request, response);
139     IncreaseResponseCount();
140     AddClient(context->peer());
141     return status;
142   }
143 
Start()144   void Start() {}
145 
Shutdown()146   void Shutdown() {}
147 
clients()148   std::set<std::string> clients() {
149     grpc_core::MutexLock lock(&clients_mu_);
150     return clients_;
151   }
152 
153  private:
AddClient(const std::string & client)154   void AddClient(const std::string& client) {
155     grpc_core::MutexLock lock(&clients_mu_);
156     clients_.insert(client);
157   }
158 
159   grpc_core::Mutex clients_mu_;
160   std::set<std::string> clients_ ABSL_GUARDED_BY(&clients_mu_);
161 };
162 
Ip4ToPackedString(const char * ip_str)163 std::string Ip4ToPackedString(const char* ip_str) {
164   struct in_addr ip4;
165   GPR_ASSERT(inet_pton(AF_INET, ip_str, &ip4) == 1);
166   return std::string(reinterpret_cast<const char*>(&ip4), sizeof(ip4));
167 }
168 
Ip6ToPackedString(const char * ip_str)169 std::string Ip6ToPackedString(const char* ip_str) {
170   struct in6_addr ip6;
171   GPR_ASSERT(inet_pton(AF_INET6, ip_str, &ip6) == 1);
172   return std::string(reinterpret_cast<const char*>(&ip6), sizeof(ip6));
173 }
174 
175 struct ClientStats {
176   size_t num_calls_started = 0;
177   size_t num_calls_finished = 0;
178   size_t num_calls_finished_with_client_failed_to_send = 0;
179   size_t num_calls_finished_known_received = 0;
180   std::map<std::string, size_t> drop_token_counts;
181 
operator +=grpc::testing::__anon1a9bc1970111::ClientStats182   ClientStats& operator+=(const ClientStats& other) {
183     num_calls_started += other.num_calls_started;
184     num_calls_finished += other.num_calls_finished;
185     num_calls_finished_with_client_failed_to_send +=
186         other.num_calls_finished_with_client_failed_to_send;
187     num_calls_finished_known_received +=
188         other.num_calls_finished_known_received;
189     for (const auto& p : other.drop_token_counts) {
190       drop_token_counts[p.first] += p.second;
191     }
192     return *this;
193   }
194 
Resetgrpc::testing::__anon1a9bc1970111::ClientStats195   void Reset() {
196     num_calls_started = 0;
197     num_calls_finished = 0;
198     num_calls_finished_with_client_failed_to_send = 0;
199     num_calls_finished_known_received = 0;
200     drop_token_counts.clear();
201   }
202 };
203 
204 class BalancerServiceImpl : public BalancerService {
205  public:
206   using Stream = ServerReaderWriter<LoadBalanceResponse, LoadBalanceRequest>;
207 
Start()208   void Start() {
209     {
210       grpc_core::MutexLock lock(&mu_);
211       shutdown_ = false;
212       response_queue_.clear();
213     }
214     {
215       grpc_core::MutexLock lock(&load_report_mu_);
216       load_report_queue_.clear();
217     }
218   }
219 
Shutdown()220   void Shutdown() {
221     {
222       grpc_core::MutexLock lock(&mu_);
223       shutdown_ = true;
224     }
225     ShutdownStream();
226     gpr_log(GPR_INFO, "LB[%p]: shut down", this);
227   }
228 
set_client_load_reporting_interval_seconds(int seconds)229   void set_client_load_reporting_interval_seconds(int seconds) {
230     client_load_reporting_interval_seconds_ = seconds;
231   }
232 
SendResponse(LoadBalanceResponse response)233   void SendResponse(LoadBalanceResponse response) {
234     grpc_core::MutexLock lock(&mu_);
235     response_queue_.emplace_back(std::move(response));
236     if (response_cond_ != nullptr) response_cond_->SignalAll();
237   }
238 
ShutdownStream()239   void ShutdownStream() {
240     grpc_core::MutexLock lock(&mu_);
241     response_queue_.emplace_back(absl::nullopt);
242     if (response_cond_ != nullptr) response_cond_->SignalAll();
243   }
244 
WaitForLoadReport(absl::Duration timeout)245   absl::optional<ClientStats> WaitForLoadReport(absl::Duration timeout) {
246     grpc_core::MutexLock lock(&load_report_mu_);
247     if (load_report_queue_.empty()) {
248       grpc_core::CondVar condition;
249       load_report_cond_ = &condition;
250       condition.WaitWithTimeout(&load_report_mu_,
251                                 timeout * grpc_test_slowdown_factor());
252       load_report_cond_ = nullptr;
253     }
254     if (load_report_queue_.empty()) return absl::nullopt;
255     ClientStats load_report = std::move(load_report_queue_.front());
256     load_report_queue_.pop_front();
257     return load_report;
258   }
259 
WaitForNewStream(size_t prev_seen_count,absl::Duration timeout=absl::Seconds (5))260   bool WaitForNewStream(size_t prev_seen_count,
261                         absl::Duration timeout = absl::Seconds(5)) {
262     grpc_core::MutexLock lock(&stream_count_mu_);
263     if (stream_count_ == prev_seen_count) {
264       grpc_core::CondVar condition;
265       stream_count_cond_ = &condition;
266       condition.WaitWithTimeout(&stream_count_mu_,
267                                 timeout * grpc_test_slowdown_factor());
268       stream_count_cond_ = nullptr;
269     }
270     return stream_count_ > prev_seen_count;
271   }
272 
service_names()273   std::vector<std::string> service_names() {
274     grpc_core::MutexLock lock(&mu_);
275     return service_names_;
276   }
277 
clients()278   std::set<std::string> clients() {
279     grpc_core::MutexLock lock(&clients_mu_);
280     return clients_;
281   }
282 
283  private:
284   // Request handler.
BalanceLoad(ServerContext * context,Stream * stream)285   Status BalanceLoad(ServerContext* context, Stream* stream) override {
286     gpr_log(GPR_INFO, "LB[%p]: BalanceLoad", this);
287     {
288       grpc_core::MutexLock lock(&mu_);
289       if (shutdown_) {
290         gpr_log(GPR_INFO, "LB[%p]: shutdown at stream start", this);
291         return Status::OK;
292       }
293     }
294     IncrementStreamCount();
295     AddClient(context->peer());
296     // The loadbalancer should see a test user agent because it was
297     // specifically configured at the client using
298     // GRPC_ARG_GRPCLB_CHANNEL_ARGS
299     auto it = context->client_metadata().find("user-agent");
300     EXPECT_TRUE(it != context->client_metadata().end());
301     if (it != context->client_metadata().end()) {
302       EXPECT_THAT(std::string(it->second.data(), it->second.length()),
303                   ::testing::StartsWith(kGrpclbSpecificUserAgentString));
304     }
305     // Balancer shouldn't receive the call credentials metadata.
306     EXPECT_EQ(context->client_metadata().find(kCallCredsMdKey),
307               context->client_metadata().end());
308     // Read initial request.
309     LoadBalanceRequest request;
310     if (!stream->Read(&request)) {
311       gpr_log(GPR_INFO, "LB[%p]: stream read returned false", this);
312       return Status::OK;
313     }
314     EXPECT_TRUE(request.has_initial_request());
315     {
316       grpc_core::MutexLock lock(&mu_);
317       service_names_.push_back(request.initial_request().name());
318     }
319     IncreaseRequestCount();
320     gpr_log(GPR_INFO, "LB[%p]: received initial message '%s'", this,
321             request.DebugString().c_str());
322     // Send initial response.
323     LoadBalanceResponse response;
324     auto* initial_response = response.mutable_initial_response();
325     if (client_load_reporting_interval_seconds_ > 0) {
326       initial_response->mutable_client_stats_report_interval()->set_seconds(
327           client_load_reporting_interval_seconds_);
328     }
329     stream->Write(response);
330     // Spawn a separate thread to read requests from the client.
331     absl::Notification reader_shutdown;
332     std::thread reader(std::bind(&BalancerServiceImpl::ReadThread, this, stream,
333                                  &reader_shutdown));
334     auto thread_cleanup = absl::MakeCleanup([&]() {
335       gpr_log(GPR_INFO, "shutting down reader thread");
336       reader_shutdown.Notify();
337       gpr_log(GPR_INFO, "joining reader thread");
338       reader.join();
339       gpr_log(GPR_INFO, "joining reader thread complete");
340     });
341     // Send responses as instructed by the test.
342     while (true) {
343       auto response = GetNextResponse();
344       if (!response.has_value()) {
345         context->TryCancel();
346         break;
347       }
348       gpr_log(GPR_INFO, "LB[%p]: Sending response: %s", this,
349               response->DebugString().c_str());
350       IncreaseResponseCount();
351       stream->Write(*response);
352     }
353     gpr_log(GPR_INFO, "LB[%p]: done", this);
354     return Status::OK;
355   }
356 
357   // Reader thread spawned by request handler.
ReadThread(Stream * stream,absl::Notification * shutdown)358   void ReadThread(Stream* stream, absl::Notification* shutdown) {
359     LoadBalanceRequest request;
360     while (!shutdown->HasBeenNotified() && stream->Read(&request)) {
361       gpr_log(GPR_INFO, "LB[%p]: received client load report message '%s'",
362               this, request.DebugString().c_str());
363       EXPECT_GT(client_load_reporting_interval_seconds_, 0);
364       EXPECT_TRUE(request.has_client_stats());
365       ClientStats load_report;
366       load_report.num_calls_started =
367           request.client_stats().num_calls_started();
368       load_report.num_calls_finished =
369           request.client_stats().num_calls_finished();
370       load_report.num_calls_finished_with_client_failed_to_send =
371           request.client_stats()
372               .num_calls_finished_with_client_failed_to_send();
373       load_report.num_calls_finished_known_received =
374           request.client_stats().num_calls_finished_known_received();
375       for (const auto& drop_token_count :
376            request.client_stats().calls_finished_with_drop()) {
377         load_report.drop_token_counts[drop_token_count.load_balance_token()] =
378             drop_token_count.num_calls();
379       }
380       // We need to acquire the lock here in order to prevent the notify_one
381       // below from firing before its corresponding wait is executed.
382       grpc_core::MutexLock lock(&load_report_mu_);
383       load_report_queue_.emplace_back(std::move(load_report));
384       if (load_report_cond_ != nullptr) load_report_cond_->Signal();
385     }
386   }
387 
388   // Helper for request handler thread to get the next response to be
389   // sent on the stream.  Returns nullopt when the test has requested
390   // stream shutdown.
GetNextResponse()391   absl::optional<LoadBalanceResponse> GetNextResponse() {
392     grpc_core::MutexLock lock(&mu_);
393     if (response_queue_.empty()) {
394       grpc_core::CondVar condition;
395       response_cond_ = &condition;
396       condition.Wait(&mu_);
397       response_cond_ = nullptr;
398     }
399     auto response = std::move(response_queue_.front());
400     response_queue_.pop_front();
401     return response;
402   }
403 
AddClient(const std::string & client)404   void AddClient(const std::string& client) {
405     grpc_core::MutexLock lock(&clients_mu_);
406     clients_.insert(client);
407   }
408 
IncrementStreamCount()409   void IncrementStreamCount() {
410     grpc_core::MutexLock lock(&stream_count_mu_);
411     ++stream_count_;
412     if (stream_count_cond_ != nullptr) stream_count_cond_->Signal();
413   }
414 
415   int client_load_reporting_interval_seconds_ = 0;
416 
417   grpc_core::Mutex mu_;
418   bool shutdown_ ABSL_GUARDED_BY(&mu_) = false;
419   std::vector<std::string> service_names_ ABSL_GUARDED_BY(mu_);
420   std::deque<absl::optional<LoadBalanceResponse>> response_queue_
421       ABSL_GUARDED_BY(mu_);
422   grpc_core::CondVar* response_cond_ ABSL_GUARDED_BY(mu_) = nullptr;
423 
424   grpc_core::Mutex load_report_mu_;
425   grpc_core::CondVar* load_report_cond_ ABSL_GUARDED_BY(load_report_mu_) =
426       nullptr;
427   std::deque<ClientStats> load_report_queue_ ABSL_GUARDED_BY(load_report_mu_);
428 
429   grpc_core::Mutex clients_mu_;
430   std::set<std::string> clients_ ABSL_GUARDED_BY(&clients_mu_);
431 
432   grpc_core::Mutex stream_count_mu_;
433   grpc_core::CondVar* stream_count_cond_ ABSL_GUARDED_BY(&stream_count_mu_) =
434       nullptr;
435   size_t stream_count_ ABSL_GUARDED_BY(&stream_count_mu_) = 0;
436 };
437 
438 class GrpclbEnd2endTest : public ::testing::Test {
439  protected:
440   template <typename T>
441   class ServerThread {
442    public:
443     template <typename... Args>
ServerThread(const std::string & type,Args &&...args)444     explicit ServerThread(const std::string& type, Args&&... args)
445         : port_(grpc_pick_unused_port_or_die()),
446           type_(type),
447           service_(std::forward<Args>(args)...) {}
448 
~ServerThread()449     ~ServerThread() { Shutdown(); }
450 
Start()451     void Start() {
452       gpr_log(GPR_INFO, "starting %s server on port %d", type_.c_str(), port_);
453       GPR_ASSERT(!running_);
454       running_ = true;
455       service_.Start();
456       grpc_core::Mutex mu;
457       // We need to acquire the lock here in order to prevent the notify_one
458       // by ServerThread::Serve from firing before the wait below is hit.
459       grpc_core::MutexLock lock(&mu);
460       grpc_core::CondVar cond;
461       thread_ = std::make_unique<std::thread>(
462           std::bind(&ServerThread::Serve, this, &mu, &cond));
463       cond.Wait(&mu);
464       gpr_log(GPR_INFO, "%s server startup complete", type_.c_str());
465     }
466 
Serve(grpc_core::Mutex * mu,grpc_core::CondVar * cond)467     void Serve(grpc_core::Mutex* mu, grpc_core::CondVar* cond) {
468       // We need to acquire the lock here in order to prevent the notify_one
469       // below from firing before its corresponding wait is executed.
470       grpc_core::MutexLock lock(mu);
471       ServerBuilder builder;
472       std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
473           grpc_fake_transport_security_server_credentials_create()));
474       builder.AddListeningPort(grpc_core::LocalIpAndPort(port_), creds);
475       builder.RegisterService(&service_);
476       server_ = builder.BuildAndStart();
477       cond->Signal();
478     }
479 
Shutdown()480     void Shutdown() {
481       if (!running_) return;
482       gpr_log(GPR_INFO, "%s about to shutdown", type_.c_str());
483       service_.Shutdown();
484       server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
485       thread_->join();
486       gpr_log(GPR_INFO, "%s shutdown completed", type_.c_str());
487       running_ = false;
488     }
489 
port() const490     int port() const { return port_; }
491 
service()492     T& service() { return service_; }
493 
494    private:
495     const int port_;
496     std::string type_;
497     T service_;
498     std::unique_ptr<Server> server_;
499     std::unique_ptr<std::thread> thread_;
500     bool running_ = false;
501   };
502 
SetUpTestSuite()503   static void SetUpTestSuite() {
504     // Make the backup poller poll very frequently in order to pick up
505     // updates from all the subchannels's FDs.
506     grpc_core::ConfigVars::Overrides overrides;
507     overrides.client_channel_backup_poll_interval_ms = 1;
508     grpc_core::ConfigVars::SetOverrides(overrides);
509 #if TARGET_OS_IPHONE
510     // Workaround Apple CFStream bug
511     grpc_core::SetEnv("grpc_cfstream", "0");
512 #endif
513     grpc_init();
514   }
515 
TearDownTestSuite()516   static void TearDownTestSuite() { grpc_shutdown(); }
517 
SetUp()518   void SetUp() override {
519     response_generator_ =
520         grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
521     balancer_ = CreateAndStartBalancer();
522     ResetStub();
523   }
524 
TearDown()525   void TearDown() override {
526     ShutdownAllBackends();
527     balancer_->Shutdown();
528   }
529 
CreateBackends(size_t num_backends)530   void CreateBackends(size_t num_backends) {
531     for (size_t i = 0; i < num_backends; ++i) {
532       backends_.emplace_back(
533           std::make_unique<ServerThread<BackendServiceImpl>>("backend"));
534       backends_.back()->Start();
535     }
536   }
537 
StartAllBackends()538   void StartAllBackends() {
539     for (auto& backend : backends_) backend->Start();
540   }
541 
StartBackend(size_t index)542   void StartBackend(size_t index) { backends_[index]->Start(); }
543 
ShutdownAllBackends()544   void ShutdownAllBackends() {
545     for (auto& backend : backends_) backend->Shutdown();
546   }
547 
ShutdownBackend(size_t index)548   void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
549 
CreateAndStartBalancer()550   std::unique_ptr<ServerThread<BalancerServiceImpl>> CreateAndStartBalancer() {
551     auto balancer =
552         std::make_unique<ServerThread<BalancerServiceImpl>>("balancer");
553     balancer->Start();
554     return balancer;
555   }
556 
ResetStub(int fallback_timeout_ms=0,const std::string & expected_targets="",int subchannel_cache_delay_ms=0)557   void ResetStub(int fallback_timeout_ms = 0,
558                  const std::string& expected_targets = "",
559                  int subchannel_cache_delay_ms = 0) {
560     // Send a separate user agent string for the grpclb load balancer alone.
561     grpc_core::ChannelArgs grpclb_channel_args;
562     // Set a special user agent string for the grpclb load balancer. It
563     // will be verified at the load balancer.
564     grpclb_channel_args = grpclb_channel_args.Set(
565         GRPC_ARG_PRIMARY_USER_AGENT_STRING, kGrpclbSpecificUserAgentString);
566     ChannelArguments args;
567     if (fallback_timeout_ms > 0) {
568       args.SetGrpclbFallbackTimeout(fallback_timeout_ms *
569                                     grpc_test_slowdown_factor());
570     }
571     args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
572                     response_generator_.get());
573     if (!expected_targets.empty()) {
574       args.SetString(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
575       grpclb_channel_args = grpclb_channel_args.Set(
576           GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
577     }
578     if (subchannel_cache_delay_ms > 0) {
579       args.SetInt(GRPC_ARG_GRPCLB_SUBCHANNEL_CACHE_INTERVAL_MS,
580                   subchannel_cache_delay_ms * grpc_test_slowdown_factor());
581     }
582     static const grpc_arg_pointer_vtable channel_args_vtable = {
583         // copy
584         [](void* p) -> void* {
585           return grpc_channel_args_copy(static_cast<grpc_channel_args*>(p));
586         },
587         // destroy
588         [](void* p) {
589           grpc_channel_args_destroy(static_cast<grpc_channel_args*>(p));
590         },
591         // compare
592         [](void* p1, void* p2) {
593           return grpc_channel_args_compare(static_cast<grpc_channel_args*>(p1),
594                                            static_cast<grpc_channel_args*>(p2));
595         },
596     };
597     // Specify channel args for the channel to the load balancer.
598     args.SetPointerWithVtable(
599         GRPC_ARG_EXPERIMENTAL_GRPCLB_CHANNEL_ARGS,
600         const_cast<grpc_channel_args*>(grpclb_channel_args.ToC().get()),
601         &channel_args_vtable);
602     // TODO(dgq): templatize tests to run everything using both secure and
603     // insecure channel credentials.
604     grpc_channel_credentials* channel_creds =
605         grpc_fake_transport_security_credentials_create();
606     grpc_call_credentials* call_creds = grpc_md_only_test_credentials_create(
607         kCallCredsMdKey, kCallCredsMdValue);
608     auto creds = std::make_shared<TestCompositeChannelCredentials>(
609         channel_creds, call_creds);
610     call_creds->Unref();
611     channel_creds->Unref();
612     channel_ = grpc::CreateCustomChannel(
613         absl::StrCat("fake:", kApplicationTargetName), creds, args);
614     stub_ = grpc::testing::EchoTestService::NewStub(channel_);
615   }
616 
ResetBackendCounters()617   void ResetBackendCounters() {
618     for (auto& backend : backends_) backend->service().ResetCounters();
619   }
620 
WaitForLoadReports(absl::Duration timeout=absl::Seconds (5))621   absl::optional<ClientStats> WaitForLoadReports(
622       absl::Duration timeout = absl::Seconds(5)) {
623     return balancer_->service().WaitForLoadReport(timeout);
624   }
625 
SeenAllBackends(size_t start_index=0,size_t stop_index=0)626   bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0) {
627     if (stop_index == 0) stop_index = backends_.size();
628     for (size_t i = start_index; i < stop_index; ++i) {
629       if (backends_[i]->service().request_count() == 0) return false;
630     }
631     return true;
632   }
633 
SendRpcAndCount(int * num_total,int * num_ok,int * num_failure,int * num_drops)634   void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
635                        int* num_drops) {
636     const Status status = SendRpc();
637     if (status.ok()) {
638       ++*num_ok;
639     } else {
640       if (status.error_message() == "drop directed by grpclb balancer") {
641         ++*num_drops;
642       } else {
643         ++*num_failure;
644       }
645     }
646     ++*num_total;
647   }
648 
649   struct WaitForBackendOptions {
650     int timeout_seconds = 10;
651     int num_requests_multiple_of = 1;
652 
WaitForBackendOptionsgrpc::testing::__anon1a9bc1970111::GrpclbEnd2endTest::WaitForBackendOptions653     WaitForBackendOptions() {}
SetTimeoutSecondsgrpc::testing::__anon1a9bc1970111::GrpclbEnd2endTest::WaitForBackendOptions654     WaitForBackendOptions& SetTimeoutSeconds(int seconds) {
655       timeout_seconds = seconds;
656       return *this;
657     }
SetNumRequestsMultipleOfgrpc::testing::__anon1a9bc1970111::GrpclbEnd2endTest::WaitForBackendOptions658     WaitForBackendOptions& SetNumRequestsMultipleOf(int multiple) {
659       num_requests_multiple_of = multiple;
660       return *this;
661     }
662   };
663 
WaitForAllBackends(size_t start_index=0,size_t stop_index=0,WaitForBackendOptions options=WaitForBackendOptions (),SourceLocation location=SourceLocation ())664   std::tuple<int, int, int> WaitForAllBackends(
665       size_t start_index = 0, size_t stop_index = 0,
666       WaitForBackendOptions options = WaitForBackendOptions(),
667       SourceLocation location = SourceLocation()) {
668     gpr_log(GPR_INFO, "Waiting for backends [%" PRIuPTR ", %" PRIuPTR ")",
669             start_index, stop_index);
670     const absl::Time deadline =
671         absl::Now() +
672         absl::Seconds(options.timeout_seconds * grpc_test_slowdown_factor());
673     int num_ok = 0;
674     int num_failure = 0;
675     int num_drops = 0;
676     int num_total = 0;
677     while (!SeenAllBackends(start_index, stop_index)) {
678       absl::Time now = absl::Now();
679       EXPECT_LT(now, deadline) << location.file() << ":" << location.line();
680       if (now > deadline) break;
681       SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
682     }
683     while (num_total % options.num_requests_multiple_of != 0) {
684       absl::Time now = absl::Now();
685       EXPECT_LT(now, deadline) << location.file() << ":" << location.line();
686       if (now > deadline) break;
687       SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
688     }
689     ResetBackendCounters();
690     gpr_log(GPR_INFO,
691             "Performed %d warm up requests (a multiple of %d) against the "
692             "backends. %d succeeded, %d failed, %d dropped.",
693             num_total, options.num_requests_multiple_of, num_ok, num_failure,
694             num_drops);
695     return std::make_tuple(num_ok, num_failure, num_drops);
696   }
697 
WaitForBackend(size_t backend_idx,WaitForBackendOptions options=WaitForBackendOptions (),SourceLocation location=SourceLocation ())698   void WaitForBackend(size_t backend_idx,
699                       WaitForBackendOptions options = WaitForBackendOptions(),
700                       SourceLocation location = SourceLocation()) {
701     WaitForAllBackends(backend_idx, backend_idx + 1, options, location);
702   }
703 
CreateAddressListFromPorts(const absl::Span<const int> ports,absl::string_view balancer_name="")704   grpc_core::EndpointAddressesList CreateAddressListFromPorts(
705       const absl::Span<const int> ports, absl::string_view balancer_name = "") {
706     grpc_core::EndpointAddressesList addresses;
707     for (int port : ports) {
708       absl::StatusOr<grpc_core::URI> lb_uri =
709           grpc_core::URI::Parse(grpc_core::LocalIpUri(port));
710       GPR_ASSERT(lb_uri.ok());
711       grpc_resolved_address address;
712       GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
713       grpc_core::ChannelArgs args;
714       if (!balancer_name.empty()) {
715         args = args.Set(GRPC_ARG_DEFAULT_AUTHORITY, balancer_name);
716       }
717       addresses.emplace_back(address, args);
718     }
719     return addresses;
720   }
721 
SetNextResolutionFromEndpoints(grpc_core::EndpointAddressesList balancers,grpc_core::EndpointAddressesList backends={},const char * service_config_json=kDefaultServiceConfig)722   void SetNextResolutionFromEndpoints(
723       grpc_core::EndpointAddressesList balancers,
724       grpc_core::EndpointAddressesList backends = {},
725       const char* service_config_json = kDefaultServiceConfig) {
726     grpc_core::ExecCtx exec_ctx;
727     grpc_core::Resolver::Result result;
728     result.addresses = std::move(backends);
729     result.service_config = grpc_core::ServiceConfigImpl::Create(
730         grpc_core::ChannelArgs(), service_config_json);
731     GPR_ASSERT(result.service_config.ok());
732     result.args = grpc_core::SetGrpcLbBalancerAddresses(
733         grpc_core::ChannelArgs(), std::move(balancers));
734     response_generator_->SetResponseSynchronously(std::move(result));
735   }
736 
SetNextResolution(const absl::Span<const int> balancer_ports,const absl::Span<const int> backend_ports={},const char * service_config_json=kDefaultServiceConfig)737   void SetNextResolution(
738       const absl::Span<const int> balancer_ports,
739       const absl::Span<const int> backend_ports = {},
740       const char* service_config_json = kDefaultServiceConfig) {
741     SetNextResolutionFromEndpoints(CreateAddressListFromPorts(balancer_ports),
742                                    CreateAddressListFromPorts(backend_ports),
743                                    service_config_json);
744   }
745 
SetNextResolutionDefaultBalancer(const char * service_config_json=kDefaultServiceConfig)746   void SetNextResolutionDefaultBalancer(
747       const char* service_config_json = kDefaultServiceConfig) {
748     SetNextResolution({balancer_->port()}, {}, service_config_json);
749   }
750 
GetBackendPorts(size_t start_index=0,size_t stop_index=0) const751   std::vector<int> GetBackendPorts(size_t start_index = 0,
752                                    size_t stop_index = 0) const {
753     if (stop_index == 0) stop_index = backends_.size();
754     std::vector<int> backend_ports;
755     for (size_t i = start_index; i < stop_index; ++i) {
756       backend_ports.push_back(backends_[i]->port());
757     }
758     return backend_ports;
759   }
760 
SendBalancerResponse(LoadBalanceResponse response)761   void SendBalancerResponse(LoadBalanceResponse response) {
762     balancer_->service().SendResponse(std::move(response));
763   }
764 
BuildResponseForBackends(const std::vector<int> & backend_ports,const std::map<std::string,size_t> & drop_token_counts)765   LoadBalanceResponse BuildResponseForBackends(
766       const std::vector<int>& backend_ports,
767       const std::map<std::string, size_t>& drop_token_counts) {
768     LoadBalanceResponse response;
769     for (const auto& drop_token_count : drop_token_counts) {
770       for (size_t i = 0; i < drop_token_count.second; ++i) {
771         auto* server = response.mutable_server_list()->add_servers();
772         server->set_drop(true);
773         server->set_load_balance_token(drop_token_count.first);
774       }
775     }
776     for (const int& backend_port : backend_ports) {
777       auto* server = response.mutable_server_list()->add_servers();
778       server->set_ip_address(grpc_core::RunningWithIPv6Only()
779                                  ? Ip6ToPackedString("::1")
780                                  : Ip4ToPackedString("127.0.0.1"));
781       server->set_port(backend_port);
782       static int token_count = 0;
783       server->set_load_balance_token(
784           absl::StrFormat("token%03d", ++token_count));
785     }
786     return response;
787   }
788 
SendRpc(EchoResponse * response=nullptr,int timeout_ms=3000,bool wait_for_ready=false,const Status & expected_status=Status::OK)789   Status SendRpc(EchoResponse* response = nullptr, int timeout_ms = 3000,
790                  bool wait_for_ready = false,
791                  const Status& expected_status = Status::OK) {
792     const bool local_response = (response == nullptr);
793     if (local_response) response = new EchoResponse;
794     EchoRequest request;
795     request.set_message(kRequestMessage);
796     if (!expected_status.ok()) {
797       auto* error = request.mutable_param()->mutable_expected_error();
798       error->set_code(expected_status.error_code());
799       error->set_error_message(expected_status.error_message());
800     }
801     ClientContext context;
802     context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
803     if (wait_for_ready) context.set_wait_for_ready(true);
804     Status status = stub_->Echo(&context, request, response);
805     if (local_response) delete response;
806     return status;
807   }
808 
CheckRpcSendOk(const size_t times=1,const int timeout_ms=3000,bool wait_for_ready=false)809   void CheckRpcSendOk(const size_t times = 1, const int timeout_ms = 3000,
810                       bool wait_for_ready = false) {
811     for (size_t i = 0; i < times; ++i) {
812       EchoResponse response;
813       const Status status = SendRpc(&response, timeout_ms, wait_for_ready);
814       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
815                                << " message=" << status.error_message();
816       EXPECT_EQ(response.message(), kRequestMessage);
817     }
818   }
819 
CheckRpcSendFailure()820   void CheckRpcSendFailure() {
821     const Status status = SendRpc();
822     EXPECT_FALSE(status.ok());
823   }
824 
825   std::shared_ptr<Channel> channel_;
826   std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
827   std::vector<std::unique_ptr<ServerThread<BackendServiceImpl>>> backends_;
828   std::unique_ptr<ServerThread<BalancerServiceImpl>> balancer_;
829   grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
830       response_generator_;
831 };
832 
TEST_F(GrpclbEnd2endTest,Vanilla)833 TEST_F(GrpclbEnd2endTest, Vanilla) {
834   const size_t kNumBackends = 3;
835   const size_t kNumRpcsPerAddress = 100;
836   CreateBackends(kNumBackends);
837   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
838   SetNextResolutionDefaultBalancer();
839   // Make sure that trying to connect works without a call.
840   channel_->GetState(true /* try_to_connect */);
841   // We need to wait for all backends to come online.
842   WaitForAllBackends();
843   // Send kNumRpcsPerAddress RPCs per server.
844   CheckRpcSendOk(kNumRpcsPerAddress * kNumBackends);
845   // Each backend should have gotten 100 requests.
846   for (size_t i = 0; i < backends_.size(); ++i) {
847     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service().request_count());
848   }
849   // The balancer got a single request.
850   EXPECT_EQ(1U, balancer_->service().request_count());
851   // and sent a single response.
852   EXPECT_EQ(1U, balancer_->service().response_count());
853   // Check LB policy name for the channel.
854   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
855 }
856 
TEST_F(GrpclbEnd2endTest,SubchannelCaching)857 TEST_F(GrpclbEnd2endTest, SubchannelCaching) {
858   CreateBackends(3);
859   ResetStub(/*fallback_timeout_ms=*/0, /*expected_targets=*/"",
860             /*subchannel_cache_delay_ms=*/1500);
861   SetNextResolutionDefaultBalancer();
862   // Initially send backends 0 and 1.
863   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(0, 2), {}));
864   WaitForAllBackends(0, 2);
865   // Now remove backends 0 and 1 and add backend 2.
866   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(2), {}));
867   WaitForBackend(2);
868   // Now re-add backend 1.
869   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(1), {}));
870   WaitForBackend(1);
871   // Backend 1 should never have lost its connection from the client.
872   EXPECT_EQ(1UL, backends_[1]->service().clients().size());
873   // The balancer got a single request.
874   EXPECT_EQ(1U, balancer_->service().request_count());
875   // And sent 3 responses.
876   EXPECT_EQ(3U, balancer_->service().response_count());
877 }
878 
TEST_F(GrpclbEnd2endTest,ReturnServerStatus)879 TEST_F(GrpclbEnd2endTest, ReturnServerStatus) {
880   CreateBackends(1);
881   SetNextResolutionDefaultBalancer();
882   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
883   // We need to wait for all backends to come online.
884   WaitForAllBackends();
885   // Send a request that the backend will fail, and make sure we get
886   // back the right status.
887   Status expected(StatusCode::INVALID_ARGUMENT, "He's dead, Jim!");
888   Status actual = SendRpc(/*response=*/nullptr, /*timeout_ms=*/3000,
889                           /*wait_for_ready=*/false, expected);
890   EXPECT_EQ(actual.error_code(), expected.error_code());
891   EXPECT_EQ(actual.error_message(), expected.error_message());
892 }
893 
TEST_F(GrpclbEnd2endTest,SelectGrpclbWithMigrationServiceConfig)894 TEST_F(GrpclbEnd2endTest, SelectGrpclbWithMigrationServiceConfig) {
895   CreateBackends(1);
896   SetNextResolutionDefaultBalancer(
897       "{\n"
898       "  \"loadBalancingConfig\":[\n"
899       "    { \"does_not_exist\":{} },\n"
900       "    { \"grpclb\":{} }\n"
901       "  ]\n"
902       "}");
903   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
904   CheckRpcSendOk(1, 3000 /* timeout_ms */, true /* wait_for_ready */);
905   // The balancer got a single request.
906   EXPECT_EQ(1U, balancer_->service().request_count());
907   // and sent a single response.
908   EXPECT_EQ(1U, balancer_->service().response_count());
909   // Check LB policy name for the channel.
910   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
911 }
912 
TEST_F(GrpclbEnd2endTest,SelectGrpclbWithMigrationServiceConfigAndNoAddresses)913 TEST_F(GrpclbEnd2endTest,
914        SelectGrpclbWithMigrationServiceConfigAndNoAddresses) {
915   const int kFallbackTimeoutMs = 200;
916   ResetStub(kFallbackTimeoutMs);
917   SetNextResolution({}, {},
918                     "{\n"
919                     "  \"loadBalancingConfig\":[\n"
920                     "    { \"does_not_exist\":{} },\n"
921                     "    { \"grpclb\":{} }\n"
922                     "  ]\n"
923                     "}");
924   // Try to connect.
925   EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(true));
926   // Should go into state TRANSIENT_FAILURE when we enter fallback mode.
927   const gpr_timespec deadline = grpc_timeout_seconds_to_deadline(1);
928   grpc_connectivity_state state;
929   while ((state = channel_->GetState(false)) !=
930          GRPC_CHANNEL_TRANSIENT_FAILURE) {
931     ASSERT_TRUE(channel_->WaitForStateChange(state, deadline));
932   }
933   // Check LB policy name for the channel.
934   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
935 }
936 
TEST_F(GrpclbEnd2endTest,UsePickFirstChildPolicy)937 TEST_F(GrpclbEnd2endTest, UsePickFirstChildPolicy) {
938   const size_t kNumBackends = 2;
939   const size_t kNumRpcs = kNumBackends * 2;
940   CreateBackends(kNumBackends);
941   SetNextResolutionDefaultBalancer(
942       "{\n"
943       "  \"loadBalancingConfig\":[\n"
944       "    { \"grpclb\":{\n"
945       "      \"childPolicy\":[\n"
946       "        { \"pick_first\":{} }\n"
947       "      ]\n"
948       "    } }\n"
949       "  ]\n"
950       "}");
951   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
952   CheckRpcSendOk(kNumRpcs, 3000 /* timeout_ms */, true /* wait_for_ready */);
953   // Check that all requests went to the first backend.  This verifies
954   // that we used pick_first instead of round_robin as the child policy.
955   EXPECT_EQ(backends_[0]->service().request_count(), kNumRpcs);
956   for (size_t i = 1; i < backends_.size(); ++i) {
957     EXPECT_EQ(backends_[i]->service().request_count(), 0UL);
958   }
959   // The balancer got a single request.
960   EXPECT_EQ(1U, balancer_->service().request_count());
961   // and sent a single response.
962   EXPECT_EQ(1U, balancer_->service().response_count());
963   // Check LB policy name for the channel.
964   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
965 }
966 
TEST_F(GrpclbEnd2endTest,SwapChildPolicy)967 TEST_F(GrpclbEnd2endTest, SwapChildPolicy) {
968   const size_t kNumBackends = 2;
969   const size_t kNumRpcs = kNumBackends * 2;
970   CreateBackends(kNumBackends);
971   SetNextResolutionDefaultBalancer(
972       "{\n"
973       "  \"loadBalancingConfig\":[\n"
974       "    { \"grpclb\":{\n"
975       "      \"childPolicy\":[\n"
976       "        { \"pick_first\":{} }\n"
977       "      ]\n"
978       "    } }\n"
979       "  ]\n"
980       "}");
981   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
982   CheckRpcSendOk(kNumRpcs, 3000 /* timeout_ms */, true /* wait_for_ready */);
983   // Check that all requests went to the first backend.  This verifies
984   // that we used pick_first instead of round_robin as the child policy.
985   EXPECT_EQ(backends_[0]->service().request_count(), kNumRpcs);
986   for (size_t i = 1; i < backends_.size(); ++i) {
987     EXPECT_EQ(backends_[i]->service().request_count(), 0UL);
988   }
989   // Send new resolution that removes child policy from service config.
990   SetNextResolutionDefaultBalancer();
991   WaitForAllBackends();
992   CheckRpcSendOk(kNumRpcs, 3000 /* timeout_ms */, true /* wait_for_ready */);
993   // Check that every backend saw the same number of requests.  This verifies
994   // that we used round_robin.
995   for (size_t i = 0; i < backends_.size(); ++i) {
996     EXPECT_EQ(backends_[i]->service().request_count(), 2UL);
997   }
998   // The balancer got a single request.
999   EXPECT_EQ(1U, balancer_->service().request_count());
1000   // and sent a single response.
1001   EXPECT_EQ(1U, balancer_->service().response_count());
1002   // Check LB policy name for the channel.
1003   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
1004 }
1005 
TEST_F(GrpclbEnd2endTest,SameBackendListedMultipleTimes)1006 TEST_F(GrpclbEnd2endTest, SameBackendListedMultipleTimes) {
1007   CreateBackends(1);
1008   SetNextResolutionDefaultBalancer();
1009   // Same backend listed twice.
1010   std::vector<int> ports;
1011   ports.push_back(backends_[0]->port());
1012   ports.push_back(backends_[0]->port());
1013   const size_t kNumRpcsPerAddress = 10;
1014   SendBalancerResponse(BuildResponseForBackends(ports, {}));
1015   // We need to wait for the backend to come online.
1016   WaitForBackend(0);
1017   // Send kNumRpcsPerAddress RPCs per server.
1018   CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
1019   // Backend should have gotten 20 requests.
1020   EXPECT_EQ(kNumRpcsPerAddress * 2, backends_[0]->service().request_count());
1021   // And they should have come from a single client port, because of
1022   // subchannel sharing.
1023   EXPECT_EQ(1UL, backends_[0]->service().clients().size());
1024 }
1025 
TEST_F(GrpclbEnd2endTest,InitiallyEmptyServerlist)1026 TEST_F(GrpclbEnd2endTest, InitiallyEmptyServerlist) {
1027   CreateBackends(1);
1028   SetNextResolutionDefaultBalancer();
1029   // First response is an empty serverlist.  RPCs should fail.
1030   SendBalancerResponse(LoadBalanceResponse());
1031   CheckRpcSendFailure();
1032   // Now send a non-empty serverlist.
1033   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1034   CheckRpcSendOk(1, /*timeout_ms=*/3000, /*wait_for_ready=*/true);
1035   // The balancer got a single request.
1036   EXPECT_EQ(1U, balancer_->service().request_count());
1037   // and sent two responses.
1038   EXPECT_EQ(2U, balancer_->service().response_count());
1039 }
1040 
TEST_F(GrpclbEnd2endTest,AllServersUnreachableFailFast)1041 TEST_F(GrpclbEnd2endTest, AllServersUnreachableFailFast) {
1042   SetNextResolutionDefaultBalancer();
1043   const size_t kNumUnreachableServers = 5;
1044   std::vector<int> ports;
1045   for (size_t i = 0; i < kNumUnreachableServers; ++i) {
1046     ports.push_back(grpc_pick_unused_port_or_die());
1047   }
1048   SendBalancerResponse(BuildResponseForBackends(ports, {}));
1049   const Status status = SendRpc();
1050   // The error shouldn't be DEADLINE_EXCEEDED.
1051   EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
1052   // The balancer got a single request.
1053   EXPECT_EQ(1U, balancer_->service().request_count());
1054   // and sent a single response.
1055   EXPECT_EQ(1U, balancer_->service().response_count());
1056 }
1057 
TEST_F(GrpclbEnd2endTest,Fallback)1058 TEST_F(GrpclbEnd2endTest, Fallback) {
1059   const size_t kNumBackends = 4;
1060   const size_t kNumBackendsInResolution = kNumBackends / 2;
1061   CreateBackends(kNumBackends);
1062   // Inject resolver result that contains the fallback backends.
1063   SetNextResolution({balancer_->port()},
1064                     GetBackendPorts(0, kNumBackendsInResolution));
1065   // Balancer has not sent a serverlist, so we should use fallback.
1066   // Wait until all the fallback backends are reachable.
1067   WaitForAllBackends(0, kNumBackendsInResolution,
1068                      WaitForBackendOptions().SetTimeoutSeconds(20));
1069   // Send serverlist.
1070   SendBalancerResponse(BuildResponseForBackends(
1071       GetBackendPorts(/*start_index=*/kNumBackendsInResolution), {}));
1072   // Now we should be using the backends from the balancer.
1073   WaitForAllBackends(kNumBackendsInResolution);
1074   // The balancer got a single request.
1075   EXPECT_EQ(1U, balancer_->service().request_count());
1076   // and sent a single response.
1077   EXPECT_EQ(1U, balancer_->service().response_count());
1078 }
1079 
TEST_F(GrpclbEnd2endTest,FallbackUpdate)1080 TEST_F(GrpclbEnd2endTest, FallbackUpdate) {
1081   const size_t kNumBackends = 6;
1082   const size_t kNumBackendsInResolution = kNumBackends / 3;
1083   const size_t kNumBackendsInResolutionUpdate = kNumBackends / 3;
1084   ResetStub(/*fallback_timeout_ms=*/500);
1085   CreateBackends(kNumBackends);
1086   // Inject resolver result with fallback addresses.
1087   SetNextResolution({balancer_->port()},
1088                     GetBackendPorts(0, kNumBackendsInResolution));
1089   // Balancer has not sent a serverlist, so we should use fallback.
1090   // Wait until all the fallback backends are reachable.
1091   WaitForAllBackends(0, kNumBackendsInResolution);
1092   // Now send a resolver result with a different set of backend addresses.
1093   SetNextResolution({balancer_->port()},
1094                     GetBackendPorts(kNumBackendsInResolution,
1095                                     kNumBackendsInResolution +
1096                                         kNumBackendsInResolutionUpdate));
1097   // Wait until the new fallback backends are reachable.
1098   WaitForAllBackends(kNumBackendsInResolution,
1099                      kNumBackendsInResolution + kNumBackendsInResolutionUpdate);
1100   // Send non-empty serverlist.
1101   SendBalancerResponse(
1102       BuildResponseForBackends(GetBackendPorts(kNumBackendsInResolution +
1103                                                kNumBackendsInResolutionUpdate),
1104                                {}));
1105   // Wait for backends from balancer to be seen.
1106   WaitForAllBackends(kNumBackendsInResolution + kNumBackendsInResolutionUpdate);
1107   // The balancer got a single request.
1108   EXPECT_EQ(1U, balancer_->service().request_count());
1109   // and sent a single response.
1110   EXPECT_EQ(1U, balancer_->service().response_count());
1111 }
1112 
TEST_F(GrpclbEnd2endTest,FallbackAfterStartupLoseContactWithBalancerThenBackends)1113 TEST_F(GrpclbEnd2endTest,
1114        FallbackAfterStartupLoseContactWithBalancerThenBackends) {
1115   // First two backends are fallback, last two are pointed to by balancer.
1116   const size_t kNumBackends = 4;
1117   const size_t kNumFallbackBackends = 2;
1118   const size_t kNumBalancerBackends = kNumBackends - kNumFallbackBackends;
1119   CreateBackends(kNumBackends);
1120   SetNextResolution({balancer_->port()},
1121                     GetBackendPorts(0, kNumFallbackBackends));
1122   SendBalancerResponse(
1123       BuildResponseForBackends(GetBackendPorts(kNumFallbackBackends), {}));
1124   // Try to connect.
1125   WaitForAllBackends(kNumFallbackBackends /* start_index */);
1126   // Stop balancer.  RPCs should continue going to backends from balancer.
1127   balancer_->Shutdown();
1128   CheckRpcSendOk(100 * kNumBalancerBackends);
1129   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1130     EXPECT_EQ(100UL, backends_[i]->service().request_count());
1131   }
1132   // Stop backends from balancer.  This should put us in fallback mode.
1133   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1134     ShutdownBackend(i);
1135   }
1136   WaitForAllBackends(0, kNumFallbackBackends);
1137   // Restart the backends from the balancer.  We should *not* start
1138   // sending traffic back to them at this point.
1139   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1140     StartBackend(i);
1141   }
1142   CheckRpcSendOk(100 * kNumBalancerBackends);
1143   for (size_t i = 0; i < kNumFallbackBackends; ++i) {
1144     EXPECT_EQ(100UL, backends_[i]->service().request_count());
1145   }
1146   // Now start the balancer again.  This should cause us to exit
1147   // fallback mode.
1148   balancer_->Start();
1149   SendBalancerResponse(
1150       BuildResponseForBackends(GetBackendPorts(kNumFallbackBackends), {}));
1151   WaitForAllBackends(kNumFallbackBackends);
1152 }
1153 
TEST_F(GrpclbEnd2endTest,FallbackAfterStartupLoseContactWithBackendsThenBalancer)1154 TEST_F(GrpclbEnd2endTest,
1155        FallbackAfterStartupLoseContactWithBackendsThenBalancer) {
1156   // First two backends are fallback, last two are pointed to by balancer.
1157   const size_t kNumBackends = 4;
1158   const size_t kNumFallbackBackends = 2;
1159   const size_t kNumBalancerBackends = kNumBackends - kNumFallbackBackends;
1160   CreateBackends(kNumBackends);
1161   SetNextResolution({balancer_->port()},
1162                     GetBackendPorts(0, kNumFallbackBackends));
1163   SendBalancerResponse(
1164       BuildResponseForBackends(GetBackendPorts(kNumFallbackBackends), {}));
1165   // Try to connect.
1166   WaitForAllBackends(kNumFallbackBackends);
1167   // Stop backends from balancer.  Since we are still in contact with
1168   // the balancer at this point, RPCs should be failing.
1169   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1170     ShutdownBackend(i);
1171   }
1172   CheckRpcSendFailure();
1173   // Stop balancer.  This should put us in fallback mode.
1174   balancer_->Shutdown();
1175   WaitForAllBackends(0, kNumFallbackBackends);
1176   // Restart the backends from the balancer.  We should *not* start
1177   // sending traffic back to them at this point (although the behavior
1178   // in xds may be different).
1179   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1180     StartBackend(i);
1181   }
1182   CheckRpcSendOk(100 * kNumBalancerBackends);
1183   for (size_t i = 0; i < kNumFallbackBackends; ++i) {
1184     EXPECT_EQ(100UL, backends_[i]->service().request_count());
1185   }
1186   // Now start the balancer again.  This should cause us to exit
1187   // fallback mode.
1188   balancer_->Start();
1189   SendBalancerResponse(
1190       BuildResponseForBackends(GetBackendPorts(kNumFallbackBackends), {}));
1191   WaitForAllBackends(kNumFallbackBackends);
1192 }
1193 
TEST_F(GrpclbEnd2endTest,FallbackEarlyWhenBalancerChannelFails)1194 TEST_F(GrpclbEnd2endTest, FallbackEarlyWhenBalancerChannelFails) {
1195   const int kFallbackTimeoutMs = 10000;
1196   ResetStub(kFallbackTimeoutMs);
1197   CreateBackends(1);
1198   // Return an unreachable balancer and one fallback backend.
1199   SetNextResolution({grpc_pick_unused_port_or_die()}, GetBackendPorts());
1200   // Send RPC with deadline less than the fallback timeout and make sure it
1201   // succeeds.
1202   CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 3000,
1203                  /* wait_for_ready */ false);
1204 }
1205 
TEST_F(GrpclbEnd2endTest,FallbackEarlyWhenBalancerCallFails)1206 TEST_F(GrpclbEnd2endTest, FallbackEarlyWhenBalancerCallFails) {
1207   const int kFallbackTimeoutMs = 10000;
1208   ResetStub(kFallbackTimeoutMs);
1209   CreateBackends(1);
1210   // Return one balancer and one fallback backend.
1211   SetNextResolution({balancer_->port()}, GetBackendPorts());
1212   // Balancer drops call without sending a serverlist.
1213   balancer_->service().ShutdownStream();
1214   // Send RPC with deadline less than the fallback timeout and make sure it
1215   // succeeds.
1216   CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 3000,
1217                  /* wait_for_ready */ false);
1218 }
1219 
TEST_F(GrpclbEnd2endTest,FallbackControlledByBalancerBeforeFirstServerlist)1220 TEST_F(GrpclbEnd2endTest, FallbackControlledByBalancerBeforeFirstServerlist) {
1221   const int kFallbackTimeoutMs = 10000;
1222   ResetStub(kFallbackTimeoutMs);
1223   CreateBackends(1);
1224   // Return one balancer and one fallback backend.
1225   SetNextResolution({balancer_->port()}, GetBackendPorts());
1226   // Balancer explicitly tells client to fallback.
1227   LoadBalanceResponse response;
1228   response.mutable_fallback_response();
1229   SendBalancerResponse(std::move(response));
1230   // Send RPC with deadline less than the fallback timeout and make sure it
1231   // succeeds.
1232   CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 3000,
1233                  /* wait_for_ready */ false);
1234 }
1235 
TEST_F(GrpclbEnd2endTest,FallbackControlledByBalancerAfterFirstServerlist)1236 TEST_F(GrpclbEnd2endTest, FallbackControlledByBalancerAfterFirstServerlist) {
1237   CreateBackends(2);
1238   // Return one balancer and one fallback backend (backend 0).
1239   SetNextResolution({balancer_->port()}, {backends_[0]->port()});
1240   // Balancer sends a serverlist pointing to backend 1.
1241   SendBalancerResponse(BuildResponseForBackends({backends_[1]->port()}, {}));
1242   WaitForBackend(1);
1243   // Balancer tells client to fall back.
1244   LoadBalanceResponse fallback_response;
1245   fallback_response.mutable_fallback_response();
1246   SendBalancerResponse(std::move(fallback_response));
1247   WaitForBackend(0);
1248   // Balancer sends a new serverlist, so client exits fallback.
1249   SendBalancerResponse(BuildResponseForBackends({backends_[1]->port()}, {}));
1250   WaitForBackend(1);
1251 }
1252 
TEST_F(GrpclbEnd2endTest,BackendsRestart)1253 TEST_F(GrpclbEnd2endTest, BackendsRestart) {
1254   CreateBackends(2);
1255   SetNextResolutionDefaultBalancer();
1256   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1257   WaitForAllBackends();
1258   // Stop backends.  RPCs should fail.
1259   ShutdownAllBackends();
1260   CheckRpcSendFailure();
1261   // Restart backends.  RPCs should start succeeding again.
1262   StartAllBackends();
1263   CheckRpcSendOk(1 /* times */, 3000 /* timeout_ms */,
1264                  true /* wait_for_ready */);
1265   // The balancer got a single request.
1266   EXPECT_EQ(1U, balancer_->service().request_count());
1267   // and sent a single response.
1268   EXPECT_EQ(1U, balancer_->service().response_count());
1269 }
1270 
TEST_F(GrpclbEnd2endTest,ServiceNameFromLbPolicyConfig)1271 TEST_F(GrpclbEnd2endTest, ServiceNameFromLbPolicyConfig) {
1272   constexpr char kServiceConfigWithTarget[] =
1273       "{\n"
1274       "  \"loadBalancingConfig\":[\n"
1275       "    { \"grpclb\":{\n"
1276       "      \"serviceName\":\"test_service\"\n"
1277       "    }}\n"
1278       "  ]\n"
1279       "}";
1280   SetNextResolutionDefaultBalancer(kServiceConfigWithTarget);
1281   CreateBackends(1);
1282   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1283   WaitForAllBackends();
1284   EXPECT_EQ(balancer_->service().service_names().back(), "test_service");
1285 }
1286 
TEST_F(GrpclbEnd2endTest,NewBalancerAddressNotUsedIfOriginalStreamDoesNotFail)1287 TEST_F(GrpclbEnd2endTest,
1288        NewBalancerAddressNotUsedIfOriginalStreamDoesNotFail) {
1289   CreateBackends(3);
1290   // Default balancer sends backend 0.
1291   SendBalancerResponse(BuildResponseForBackends({backends_[0]->port()}, {}));
1292   // Second balancer sends backend 1.
1293   auto balancer2 = CreateAndStartBalancer();
1294   balancer2->service().SendResponse(
1295       BuildResponseForBackends({backends_[1]->port()}, {}));
1296   // Initially, the channel uses the default balancer.
1297   SetNextResolutionDefaultBalancer();
1298   WaitForBackend(0);
1299   // Send 10 requests.
1300   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1301   CheckRpcSendOk(10);
1302   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1303   // All 10 requests should have gone to the first backend.
1304   EXPECT_EQ(10U, backends_[0]->service().request_count());
1305   EXPECT_EQ(0U, backends_[1]->service().request_count());
1306   EXPECT_EQ(0U, backends_[2]->service().request_count());
1307   // Balancer 0 got a single request and sent a single response.
1308   EXPECT_EQ(1U, balancer_->service().request_count());
1309   EXPECT_EQ(1U, balancer_->service().response_count());
1310   EXPECT_EQ(0U, balancer2->service().request_count());
1311   EXPECT_EQ(0U, balancer2->service().response_count());
1312   // Now tell the channel to use balancer 2.  However, the stream to the
1313   // default balancer is not terminated, so the client will continue to
1314   // use it.
1315   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
1316   SetNextResolution({balancer2->port()});
1317   gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
1318   // Now the default balancer sends backend 2.
1319   SendBalancerResponse(BuildResponseForBackends({backends_[2]->port()}, {}));
1320   WaitForBackend(2);
1321 }
1322 
1323 // Send an update with the same set of LBs as the previous one in order to
1324 // verify that the LB channel inside grpclb keeps the initial connection (which
1325 // by definition is also present in the update).
TEST_F(GrpclbEnd2endTest,UpdatedBalancerAddressesWithSameAddressDoesNotBreakConnection)1326 TEST_F(GrpclbEnd2endTest,
1327        UpdatedBalancerAddressesWithSameAddressDoesNotBreakConnection) {
1328   CreateBackends(2);
1329   // Default balancer points to backend 0.
1330   SendBalancerResponse(BuildResponseForBackends({backends_[0]->port()}, {}));
1331   // Second balancer points to backend 1.
1332   auto balancer2 = CreateAndStartBalancer();
1333   balancer2->service().SendResponse(
1334       BuildResponseForBackends({backends_[1]->port()}, {}));
1335   // Send both balancer addresses.
1336   SetNextResolution({balancer_->port(), balancer2->port()});
1337   // Wait until the first backend is ready.
1338   WaitForBackend(0);
1339   // Send 10 requests.
1340   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1341   CheckRpcSendOk(10);
1342   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1343   // All 10 requests should have gone to the first backend.
1344   EXPECT_EQ(10U, backends_[0]->service().request_count());
1345   EXPECT_EQ(0U, backends_[1]->service().request_count());
1346   // Balancer 0 got a single request and sent a single response.
1347   EXPECT_EQ(1U, balancer_->service().request_count());
1348   EXPECT_EQ(1U, balancer_->service().response_count());
1349   EXPECT_EQ(0U, balancer2->service().request_count());
1350   EXPECT_EQ(0U, balancer2->service().response_count());
1351   // Send another address list with the same list of balancers.
1352   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
1353   SetNextResolution({balancer_->port(), balancer2->port()});
1354   gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
1355   // Shut down the balancer stream to force the client to create a new one.
1356   // The new stream should go to the default balancer, since the
1357   // underlying connection should not have been broken.
1358   gpr_log(GPR_INFO, "========= SHUTTING DOWN BALANCER CALL ==========");
1359   balancer_->service().ShutdownStream();
1360   gpr_log(GPR_INFO, "========= DONE SHUTTING DOWN BALANCER CALL ==========");
1361   // Wait until client has created a new balancer stream.
1362   EXPECT_TRUE(balancer_->service().WaitForNewStream(1));
1363   // Make sure there was only one client connection seen by the balancer.
1364   EXPECT_EQ(1UL, balancer_->service().clients().size());
1365 }
1366 
TEST_F(GrpclbEnd2endTest,BalancerDiesThenSwitchToNewBalancer)1367 TEST_F(GrpclbEnd2endTest, BalancerDiesThenSwitchToNewBalancer) {
1368   CreateBackends(2);
1369   // Default balancer sends backend 0.
1370   SendBalancerResponse(BuildResponseForBackends({backends_[0]->port()}, {}));
1371   // Balancer 2 sends backend 1.
1372   auto balancer2 = CreateAndStartBalancer();
1373   balancer2->service().SendResponse(
1374       BuildResponseForBackends({backends_[1]->port()}, {}));
1375   // Channel initially uses default balancer and therefore backend 0.
1376   SetNextResolutionDefaultBalancer();
1377   WaitForBackend(0);
1378   // Default balancer got a single request.
1379   EXPECT_EQ(1U, balancer_->service().request_count());
1380   EXPECT_EQ(1U, balancer_->service().response_count());
1381   EXPECT_EQ(0U, balancer2->service().request_count());
1382   EXPECT_EQ(0U, balancer2->service().response_count());
1383   // Send 10 RPCs.
1384   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1385   CheckRpcSendOk(10);
1386   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1387   // All 10 requests should have gone to the first backend.
1388   EXPECT_EQ(10U, backends_[0]->service().request_count());
1389   EXPECT_EQ(0U, backends_[1]->service().request_count());
1390   // Kill default balancer.
1391   gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER *************");
1392   balancer_->Shutdown();
1393   gpr_log(GPR_INFO, "********** KILLED BALANCER *************");
1394   // Channel should continue using the last backend it saw from the
1395   // balancer before the balancer died.
1396   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
1397   CheckRpcSendOk(10);
1398   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
1399   // All 10 requests should again have gone to the first backend.
1400   EXPECT_EQ(20U, backends_[0]->service().request_count());
1401   EXPECT_EQ(0U, backends_[1]->service().request_count());
1402   // Tell channel to start using balancer 2.
1403   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
1404   SetNextResolution({balancer2->port()});
1405   gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
1406   // Channel should start using backend 1.
1407   WaitForBackend(1);
1408   // This is serviced by the updated RR policy
1409   gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
1410   CheckRpcSendOk(10);
1411   gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
1412   // All 10 requests should have gone to the second backend.
1413   EXPECT_EQ(0U, backends_[0]->service().request_count());
1414   EXPECT_EQ(10U, backends_[1]->service().request_count());
1415   // Both balancers should have gotten one request and sent one response.
1416   EXPECT_EQ(1U, balancer_->service().request_count());
1417   EXPECT_EQ(1U, balancer_->service().response_count());
1418   EXPECT_EQ(1U, balancer2->service().request_count());
1419   EXPECT_EQ(1U, balancer2->service().response_count());
1420 }
1421 
TEST_F(GrpclbEnd2endTest,ReresolveDeadBackendWhileInFallback)1422 TEST_F(GrpclbEnd2endTest, ReresolveDeadBackendWhileInFallback) {
1423   ResetStub(/*fallback_timeout_ms=*/500);
1424   CreateBackends(2);
1425   // The first resolution contains the addresses of a balancer that never
1426   // responds, and a fallback backend.
1427   SetNextResolution({balancer_->port()}, {backends_[0]->port()});
1428   // Start servers and send 10 RPCs per server.
1429   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1430   CheckRpcSendOk(10);
1431   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1432   // All 10 requests should have gone to the fallback backend.
1433   EXPECT_EQ(10U, backends_[0]->service().request_count());
1434   // Kill backend 0.
1435   gpr_log(GPR_INFO, "********** ABOUT TO KILL BACKEND 0 *************");
1436   backends_[0]->Shutdown();
1437   gpr_log(GPR_INFO, "********** KILLED BACKEND 0 *************");
1438   // This should trigger re-resolution.
1439   EXPECT_TRUE(response_generator_->WaitForReresolutionRequest(
1440       absl::Seconds(5 * grpc_test_slowdown_factor())));
1441   // The re-resolution result will contain the addresses of the same balancer
1442   // and a new fallback backend.
1443   SetNextResolution({balancer_->port()}, {backends_[1]->port()});
1444   // Wait until re-resolution has been seen, as signaled by the second backend
1445   // receiving a request.
1446   WaitForBackend(1);
1447   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
1448   CheckRpcSendOk(10);
1449   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
1450   // All 10 requests should have gone to the second backend.
1451   EXPECT_EQ(10U, backends_[1]->service().request_count());
1452   EXPECT_EQ(1U, balancer_->service().request_count());
1453   EXPECT_EQ(0U, balancer_->service().response_count());
1454 }
1455 
TEST_F(GrpclbEnd2endTest,ReresolveWhenBalancerCallFails)1456 TEST_F(GrpclbEnd2endTest, ReresolveWhenBalancerCallFails) {
1457   CreateBackends(2);
1458   // Default balancer sends backend 0.
1459   SendBalancerResponse(BuildResponseForBackends({backends_[0]->port()}, {}));
1460   // Balancer 2 sends backend 1.
1461   auto balancer2 = CreateAndStartBalancer();
1462   balancer2->service().SendResponse(
1463       BuildResponseForBackends({backends_[1]->port()}, {}));
1464   // Channel initially uses default balancer and therefore backend 0.
1465   SetNextResolutionDefaultBalancer();
1466   WaitForBackend(0);
1467   // Send 10 RPCs.
1468   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1469   CheckRpcSendOk(10);
1470   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1471   // All 10 requests should have gone to the first backend.
1472   EXPECT_EQ(10U, backends_[0]->service().request_count());
1473   // Balancer 0 got a single request and sent a single request.
1474   EXPECT_EQ(1U, balancer_->service().request_count());
1475   EXPECT_EQ(1U, balancer_->service().response_count());
1476   EXPECT_EQ(0U, balancer2->service().request_count());
1477   EXPECT_EQ(0U, balancer2->service().response_count());
1478   // Kill balancer 0.
1479   gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
1480   balancer_->Shutdown();
1481   gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
1482   // This should trigger a re-resolution.
1483   EXPECT_TRUE(response_generator_->WaitForReresolutionRequest(
1484       absl::Seconds(5 * grpc_test_slowdown_factor())));
1485   gpr_log(GPR_INFO, "********** SAW RE-RESOLUTION REQUEST *************");
1486   // Re-resolution result switches to balancer 2.
1487   SetNextResolution({balancer2->port()});
1488   // Client should start using backend 1.
1489   WaitForBackend(1);
1490   // Both balancers should each have handled one request and sent one response.
1491   EXPECT_EQ(1U, balancer_->service().request_count());
1492   EXPECT_EQ(1U, balancer_->service().response_count());
1493   EXPECT_EQ(1U, balancer2->service().request_count());
1494   EXPECT_EQ(1U, balancer2->service().response_count());
1495 }
1496 
TEST_F(GrpclbEnd2endTest,Drop)1497 TEST_F(GrpclbEnd2endTest, Drop) {
1498   const size_t kNumRpcsPerAddress = 100;
1499   const size_t kNumBackends = 2;
1500   const int kNumDropRateLimiting = 1;
1501   const int kNumDropLoadBalancing = 2;
1502   const int kNumDropTotal = kNumDropRateLimiting + kNumDropLoadBalancing;
1503   const int kNumAddressesTotal = kNumBackends + kNumDropTotal;
1504   SetNextResolutionDefaultBalancer();
1505   CreateBackends(kNumBackends);
1506   SendBalancerResponse(BuildResponseForBackends(
1507       GetBackendPorts(), {{"rate_limiting", kNumDropRateLimiting},
1508                           {"load_balancing", kNumDropLoadBalancing}}));
1509   // Wait until all backends are ready.
1510   WaitForAllBackends();
1511   // Send kNumRpcsPerAddress RPCs for each server and drop address.
1512   size_t num_drops = 0;
1513   for (size_t i = 0; i < kNumRpcsPerAddress * kNumAddressesTotal; ++i) {
1514     EchoResponse response;
1515     const Status status = SendRpc(&response);
1516     if (!status.ok() &&
1517         status.error_message() == "drop directed by grpclb balancer") {
1518       ++num_drops;
1519     } else {
1520       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
1521                                << " message=" << status.error_message();
1522       EXPECT_EQ(response.message(), kRequestMessage);
1523     }
1524   }
1525   EXPECT_EQ(kNumRpcsPerAddress * kNumDropTotal, num_drops);
1526   // Each backend should have gotten 100 requests.
1527   for (size_t i = 0; i < backends_.size(); ++i) {
1528     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service().request_count());
1529   }
1530   // The balancer got a single request.
1531   EXPECT_EQ(1U, balancer_->service().request_count());
1532   // and sent a single response.
1533   EXPECT_EQ(1U, balancer_->service().response_count());
1534 }
1535 
TEST_F(GrpclbEnd2endTest,DropAllFirst)1536 TEST_F(GrpclbEnd2endTest, DropAllFirst) {
1537   SetNextResolutionDefaultBalancer();
1538   // All registered addresses are marked as "drop".
1539   const int kNumDropRateLimiting = 1;
1540   const int kNumDropLoadBalancing = 1;
1541   SendBalancerResponse(BuildResponseForBackends(
1542       {}, {{"rate_limiting", kNumDropRateLimiting},
1543            {"load_balancing", kNumDropLoadBalancing}}));
1544   const Status status = SendRpc(nullptr, 3000, true);
1545   EXPECT_FALSE(status.ok());
1546   EXPECT_EQ(status.error_message(), "drop directed by grpclb balancer");
1547 }
1548 
TEST_F(GrpclbEnd2endTest,DropAll)1549 TEST_F(GrpclbEnd2endTest, DropAll) {
1550   CreateBackends(1);
1551   SetNextResolutionDefaultBalancer();
1552   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1553   CheckRpcSendOk();
1554   SendBalancerResponse(BuildResponseForBackends(
1555       {}, {{"rate_limiting", 1}, {"load_balancing", 1}}));
1556   // Eventually, the update with only dropped servers is processed, and calls
1557   // fail.
1558   Status status;
1559   do {
1560     status = SendRpc(nullptr, 3000, true);
1561   } while (status.ok());
1562   EXPECT_FALSE(status.ok());
1563   EXPECT_EQ(status.error_message(), "drop directed by grpclb balancer");
1564 }
1565 
TEST_F(GrpclbEnd2endTest,ClientLoadReporting)1566 TEST_F(GrpclbEnd2endTest, ClientLoadReporting) {
1567   const size_t kNumBackends = 3;
1568   CreateBackends(kNumBackends);
1569   balancer_->service().set_client_load_reporting_interval_seconds(3);
1570   SetNextResolutionDefaultBalancer();
1571   const size_t kNumRpcsPerAddress = 100;
1572   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1573   // Wait until all backends are ready.
1574   int num_ok = 0;
1575   int num_failure = 0;
1576   int num_drops = 0;
1577   std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
1578   // Send kNumRpcsPerAddress RPCs per server.
1579   CheckRpcSendOk(kNumRpcsPerAddress * kNumBackends);
1580   // Each backend should have gotten 100 requests.
1581   for (size_t i = 0; i < backends_.size(); ++i) {
1582     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service().request_count());
1583   }
1584   // The balancer got a single request.
1585   EXPECT_EQ(1U, balancer_->service().request_count());
1586   // and sent a single response.
1587   EXPECT_EQ(1U, balancer_->service().response_count());
1588   ClientStats client_stats;
1589   do {
1590     auto stats = WaitForLoadReports();
1591     ASSERT_TRUE(stats.has_value());
1592     client_stats += *stats;
1593   } while (client_stats.num_calls_finished !=
1594            kNumRpcsPerAddress * kNumBackends + num_ok);
1595   EXPECT_EQ(kNumRpcsPerAddress * kNumBackends + num_ok,
1596             client_stats.num_calls_started);
1597   EXPECT_EQ(kNumRpcsPerAddress * kNumBackends + num_ok,
1598             client_stats.num_calls_finished);
1599   EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
1600   EXPECT_EQ(kNumRpcsPerAddress * kNumBackends + (num_ok + num_drops),
1601             client_stats.num_calls_finished_known_received);
1602   EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
1603 }
1604 
TEST_F(GrpclbEnd2endTest,LoadReportingWithBalancerRestart)1605 TEST_F(GrpclbEnd2endTest, LoadReportingWithBalancerRestart) {
1606   const size_t kNumBackends = 4;
1607   const size_t kNumBackendsFirstPass = 2;
1608   const size_t kNumBackendsSecondPass = kNumBackends - kNumBackendsFirstPass;
1609   CreateBackends(kNumBackends);
1610   balancer_->service().set_client_load_reporting_interval_seconds(3);
1611   SetNextResolutionDefaultBalancer();
1612   // Balancer returns backends starting at index 1.
1613   SendBalancerResponse(
1614       BuildResponseForBackends(GetBackendPorts(0, kNumBackendsFirstPass), {}));
1615   // Wait until all backends returned by the balancer are ready.
1616   int num_ok = 0;
1617   int num_failure = 0;
1618   int num_drops = 0;
1619   std::tie(num_ok, num_failure, num_drops) =
1620       WaitForAllBackends(0, kNumBackendsFirstPass);
1621   auto client_stats = WaitForLoadReports();
1622   ASSERT_TRUE(client_stats.has_value());
1623   EXPECT_EQ(static_cast<size_t>(num_ok), client_stats->num_calls_started);
1624   EXPECT_EQ(static_cast<size_t>(num_ok), client_stats->num_calls_finished);
1625   EXPECT_EQ(0U, client_stats->num_calls_finished_with_client_failed_to_send);
1626   EXPECT_EQ(static_cast<size_t>(num_ok),
1627             client_stats->num_calls_finished_known_received);
1628   EXPECT_THAT(client_stats->drop_token_counts, ::testing::ElementsAre());
1629   // Shut down the balancer.
1630   balancer_->Shutdown();
1631   // Send 10 more requests per backend.  This will continue using the
1632   // last serverlist we received from the balancer before it was shut down.
1633   ResetBackendCounters();
1634   CheckRpcSendOk(kNumBackendsFirstPass);
1635   // Each backend should have gotten 1 request.
1636   for (size_t i = 0; i < kNumBackendsFirstPass; ++i) {
1637     EXPECT_EQ(1UL, backends_[i]->service().request_count());
1638   }
1639   // Now restart the balancer, this time pointing to all backends.
1640   balancer_->Start();
1641   SendBalancerResponse(
1642       BuildResponseForBackends(GetBackendPorts(kNumBackendsFirstPass), {}));
1643   // Wait for queries to start going to one of the new backends.
1644   // This tells us that we're now using the new serverlist.
1645   do {
1646     CheckRpcSendOk();
1647   } while (backends_[2]->service().request_count() == 0 &&
1648            backends_[3]->service().request_count() == 0);
1649   // Send one RPC per backend.
1650   CheckRpcSendOk(kNumBackendsSecondPass);
1651   // Check client stats.
1652   client_stats = WaitForLoadReports();
1653   ASSERT_TRUE(client_stats.has_value());
1654   EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats->num_calls_started);
1655   EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats->num_calls_finished);
1656   EXPECT_EQ(0U, client_stats->num_calls_finished_with_client_failed_to_send);
1657   EXPECT_EQ(kNumBackendsSecondPass + 1,
1658             client_stats->num_calls_finished_known_received);
1659   EXPECT_THAT(client_stats->drop_token_counts, ::testing::ElementsAre());
1660 }
1661 
TEST_F(GrpclbEnd2endTest,LoadReportingWithDrops)1662 TEST_F(GrpclbEnd2endTest, LoadReportingWithDrops) {
1663   const size_t kNumBackends = 3;
1664   const size_t kNumRpcsPerAddress = 3;
1665   const int kNumDropRateLimiting = 2;
1666   const int kNumDropLoadBalancing = 1;
1667   const int kNumDropTotal = kNumDropRateLimiting + kNumDropLoadBalancing;
1668   const int kNumAddressesTotal = kNumBackends + kNumDropTotal;
1669   CreateBackends(kNumBackends);
1670   balancer_->service().set_client_load_reporting_interval_seconds(3);
1671   SetNextResolutionDefaultBalancer();
1672   SendBalancerResponse(BuildResponseForBackends(
1673       GetBackendPorts(), {{"rate_limiting", kNumDropRateLimiting},
1674                           {"load_balancing", kNumDropLoadBalancing}}));
1675   // Wait until all backends are ready.
1676   int num_warmup_ok = 0;
1677   int num_warmup_failure = 0;
1678   int num_warmup_drops = 0;
1679   std::tie(num_warmup_ok, num_warmup_failure, num_warmup_drops) =
1680       WaitForAllBackends(
1681           0, kNumBackends,
1682           WaitForBackendOptions().SetNumRequestsMultipleOf(kNumAddressesTotal));
1683   const int num_total_warmup_requests =
1684       num_warmup_ok + num_warmup_failure + num_warmup_drops;
1685   size_t num_drops = 0;
1686   for (size_t i = 0; i < kNumRpcsPerAddress * kNumAddressesTotal; ++i) {
1687     EchoResponse response;
1688     const Status status = SendRpc(&response);
1689     if (!status.ok() &&
1690         status.error_message() == "drop directed by grpclb balancer") {
1691       ++num_drops;
1692     } else {
1693       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
1694                                << " message=" << status.error_message();
1695       EXPECT_EQ(response.message(), kRequestMessage);
1696     }
1697   }
1698   EXPECT_EQ(kNumRpcsPerAddress * kNumDropTotal, num_drops);
1699   // Each backend should have gotten 100 requests.
1700   for (size_t i = 0; i < backends_.size(); ++i) {
1701     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service().request_count());
1702   }
1703   // The balancer got a single request.
1704   EXPECT_EQ(1U, balancer_->service().request_count());
1705   // and sent a single response.
1706   EXPECT_EQ(1U, balancer_->service().response_count());
1707   // Get load reports.
1708   auto client_stats = WaitForLoadReports();
1709   ASSERT_TRUE(client_stats.has_value());
1710   EXPECT_EQ(kNumRpcsPerAddress * kNumAddressesTotal + num_total_warmup_requests,
1711             client_stats->num_calls_started);
1712   EXPECT_EQ(kNumRpcsPerAddress * kNumAddressesTotal + num_total_warmup_requests,
1713             client_stats->num_calls_finished);
1714   EXPECT_EQ(0U, client_stats->num_calls_finished_with_client_failed_to_send);
1715   EXPECT_EQ(kNumRpcsPerAddress * kNumBackends + num_warmup_ok,
1716             client_stats->num_calls_finished_known_received);
1717   // The number of warmup request is a multiple of the number of addresses.
1718   // Therefore, all addresses in the scheduled balancer response are hit the
1719   // same number of times.
1720   const int num_times_drop_addresses_hit = num_warmup_drops / kNumDropTotal;
1721   EXPECT_THAT(
1722       client_stats->drop_token_counts,
1723       ::testing::ElementsAre(
1724           ::testing::Pair("load_balancing",
1725                           (kNumRpcsPerAddress + num_times_drop_addresses_hit)),
1726           ::testing::Pair(
1727               "rate_limiting",
1728               (kNumRpcsPerAddress + num_times_drop_addresses_hit) * 2)));
1729 }
1730 
TEST_F(GrpclbEnd2endTest,SecureNaming)1731 TEST_F(GrpclbEnd2endTest, SecureNaming) {
1732   CreateBackends(1);
1733   ResetStub(/*fallback_timeout_ms=*/0,
1734             absl::StrCat(kApplicationTargetName, ";lb"));
1735   SetNextResolutionFromEndpoints(
1736       CreateAddressListFromPorts({balancer_->port()}, "lb"));
1737   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1738   // We need to wait for all backends to come online.
1739   WaitForAllBackends();
1740   // The balancer got a single request.
1741   EXPECT_EQ(1U, balancer_->service().request_count());
1742   // and sent a single response.
1743   EXPECT_EQ(1U, balancer_->service().response_count());
1744   // Check LB policy name for the channel.
1745   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
1746 }
1747 
1748 // This death test is kept separate from the rest to ensure that it's run before
1749 // any others. See https://github.com/grpc/grpc/pull/32269 for details.
1750 using SingleBalancerDeathTest = GrpclbEnd2endTest;
1751 
TEST_F(SingleBalancerDeathTest,SecureNaming)1752 TEST_F(SingleBalancerDeathTest, SecureNaming) {
1753   GTEST_FLAG_SET(death_test_style, "threadsafe");
1754   // Make sure that we blow up (via abort() from the security connector) when
1755   // the name from the balancer doesn't match expectations.
1756   ASSERT_DEATH_IF_SUPPORTED(
1757       {
1758         ResetStub(/*fallback_timeout_ms=*/0,
1759                   absl::StrCat(kApplicationTargetName, ";lb"));
1760         SetNextResolutionFromEndpoints(
1761             CreateAddressListFromPorts({balancer_->port()}, "woops"));
1762         channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(1));
1763       },
1764       "");
1765 }
1766 
1767 }  // namespace
1768 }  // namespace testing
1769 }  // namespace grpc
1770 
main(int argc,char ** argv)1771 int main(int argc, char** argv) {
1772   grpc::testing::TestEnvironment env(&argc, argv);
1773   ::testing::InitGoogleTest(&argc, argv);
1774   const auto result = RUN_ALL_TESTS();
1775   return result;
1776 }
1777