Imported Upstream version 1.22.0
[platform/upstream/grpc.git] / test / cpp / end2end / grpclb_end2end_test.cc
1 /*
2  *
3  * Copyright 2017 gRPC authors.
4  *
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
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  */
18
19 #include <memory>
20 #include <mutex>
21 #include <set>
22 #include <sstream>
23 #include <thread>
24
25 #include <grpc/grpc.h>
26 #include <grpc/support/alloc.h>
27 #include <grpc/support/log.h>
28 #include <grpc/support/string_util.h>
29 #include <grpc/support/time.h>
30 #include <grpcpp/channel.h>
31 #include <grpcpp/client_context.h>
32 #include <grpcpp/create_channel.h>
33 #include <grpcpp/impl/codegen/sync.h>
34 #include <grpcpp/server.h>
35 #include <grpcpp/server_builder.h>
36
37 #include "src/core/ext/filters/client_channel/backup_poller.h"
38 #include "src/core/ext/filters/client_channel/parse_address.h"
39 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
40 #include "src/core/ext/filters/client_channel/server_address.h"
41 #include "src/core/ext/filters/client_channel/service_config.h"
42 #include "src/core/lib/gprpp/ref_counted_ptr.h"
43 #include "src/core/lib/iomgr/sockaddr.h"
44 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
45 #include "src/cpp/client/secure_credentials.h"
46 #include "src/cpp/server/secure_server_credentials.h"
47
48 #include "test/core/util/port.h"
49 #include "test/core/util/test_config.h"
50 #include "test/cpp/end2end/test_service_impl.h"
51
52 #include "src/proto/grpc/lb/v1/load_balancer.grpc.pb.h"
53 #include "src/proto/grpc/testing/echo.grpc.pb.h"
54
55 #include <gmock/gmock.h>
56 #include <gtest/gtest.h>
57
58 // TODO(dgq): Other scenarios in need of testing:
59 // - Send a serverlist with faulty ip:port addresses (port > 2^16, etc).
60 // - Test reception of invalid serverlist
61 // - Test against a non-LB server.
62 // - Random LB server closing the stream unexpectedly.
63 //
64 // Findings from end to end testing to be covered here:
65 // - Handling of LB servers restart, including reconnection after backing-off
66 //   retries.
67 // - Destruction of load balanced channel (and therefore of grpclb instance)
68 //   while:
69 //   1) the internal LB call is still active. This should work by virtue
70 //   of the weak reference the LB call holds. The call should be terminated as
71 //   part of the grpclb shutdown process.
72 //   2) the retry timer is active. Again, the weak reference it holds should
73 //   prevent a premature call to \a glb_destroy.
74
75 using std::chrono::system_clock;
76
77 using grpc::lb::v1::LoadBalanceRequest;
78 using grpc::lb::v1::LoadBalanceResponse;
79 using grpc::lb::v1::LoadBalancer;
80
81 namespace grpc {
82 namespace testing {
83 namespace {
84
85 template <typename ServiceType>
86 class CountedService : public ServiceType {
87  public:
88   size_t request_count() {
89     grpc::internal::MutexLock lock(&mu_);
90     return request_count_;
91   }
92
93   size_t response_count() {
94     grpc::internal::MutexLock lock(&mu_);
95     return response_count_;
96   }
97
98   void IncreaseResponseCount() {
99     grpc::internal::MutexLock lock(&mu_);
100     ++response_count_;
101   }
102   void IncreaseRequestCount() {
103     grpc::internal::MutexLock lock(&mu_);
104     ++request_count_;
105   }
106
107   void ResetCounters() {
108     grpc::internal::MutexLock lock(&mu_);
109     request_count_ = 0;
110     response_count_ = 0;
111   }
112
113  protected:
114   grpc::internal::Mutex mu_;
115
116  private:
117   size_t request_count_ = 0;
118   size_t response_count_ = 0;
119 };
120
121 using BackendService = CountedService<TestServiceImpl>;
122 using BalancerService = CountedService<LoadBalancer::Service>;
123
124 const char g_kCallCredsMdKey[] = "Balancer should not ...";
125 const char g_kCallCredsMdValue[] = "... receive me";
126
127 class BackendServiceImpl : public BackendService {
128  public:
129   BackendServiceImpl() {}
130
131   Status Echo(ServerContext* context, const EchoRequest* request,
132               EchoResponse* response) override {
133     // Backend should receive the call credentials metadata.
134     auto call_credentials_entry =
135         context->client_metadata().find(g_kCallCredsMdKey);
136     EXPECT_NE(call_credentials_entry, context->client_metadata().end());
137     if (call_credentials_entry != context->client_metadata().end()) {
138       EXPECT_EQ(call_credentials_entry->second, g_kCallCredsMdValue);
139     }
140     IncreaseRequestCount();
141     const auto status = TestServiceImpl::Echo(context, request, response);
142     IncreaseResponseCount();
143     AddClient(context->peer());
144     return status;
145   }
146
147   void Start() {}
148
149   void Shutdown() {}
150
151   std::set<grpc::string> clients() {
152     grpc::internal::MutexLock lock(&clients_mu_);
153     return clients_;
154   }
155
156  private:
157   void AddClient(const grpc::string& client) {
158     grpc::internal::MutexLock lock(&clients_mu_);
159     clients_.insert(client);
160   }
161
162   grpc::internal::Mutex mu_;
163   grpc::internal::Mutex clients_mu_;
164   std::set<grpc::string> clients_;
165 };
166
167 grpc::string Ip4ToPackedString(const char* ip_str) {
168   struct in_addr ip4;
169   GPR_ASSERT(inet_pton(AF_INET, ip_str, &ip4) == 1);
170   return grpc::string(reinterpret_cast<const char*>(&ip4), sizeof(ip4));
171 }
172
173 struct ClientStats {
174   size_t num_calls_started = 0;
175   size_t num_calls_finished = 0;
176   size_t num_calls_finished_with_client_failed_to_send = 0;
177   size_t num_calls_finished_known_received = 0;
178   std::map<grpc::string, size_t> drop_token_counts;
179
180   ClientStats& operator+=(const ClientStats& other) {
181     num_calls_started += other.num_calls_started;
182     num_calls_finished += other.num_calls_finished;
183     num_calls_finished_with_client_failed_to_send +=
184         other.num_calls_finished_with_client_failed_to_send;
185     num_calls_finished_known_received +=
186         other.num_calls_finished_known_received;
187     for (const auto& p : other.drop_token_counts) {
188       drop_token_counts[p.first] += p.second;
189     }
190     return *this;
191   }
192
193   void Reset() {
194     num_calls_started = 0;
195     num_calls_finished = 0;
196     num_calls_finished_with_client_failed_to_send = 0;
197     num_calls_finished_known_received = 0;
198     drop_token_counts.clear();
199   }
200 };
201
202 class BalancerServiceImpl : public BalancerService {
203  public:
204   using Stream = ServerReaderWriter<LoadBalanceResponse, LoadBalanceRequest>;
205   using ResponseDelayPair = std::pair<LoadBalanceResponse, int>;
206
207   explicit BalancerServiceImpl(int client_load_reporting_interval_seconds)
208       : client_load_reporting_interval_seconds_(
209             client_load_reporting_interval_seconds) {}
210
211   Status BalanceLoad(ServerContext* context, Stream* stream) override {
212     gpr_log(GPR_INFO, "LB[%p]: BalanceLoad", this);
213     {
214       grpc::internal::MutexLock lock(&mu_);
215       if (serverlist_done_) goto done;
216     }
217     {
218       // Balancer shouldn't receive the call credentials metadata.
219       EXPECT_EQ(context->client_metadata().find(g_kCallCredsMdKey),
220                 context->client_metadata().end());
221       LoadBalanceRequest request;
222       std::vector<ResponseDelayPair> responses_and_delays;
223
224       if (!stream->Read(&request)) {
225         goto done;
226       }
227       IncreaseRequestCount();
228       gpr_log(GPR_INFO, "LB[%p]: received initial message '%s'", this,
229               request.DebugString().c_str());
230
231       // TODO(juanlishen): Initial response should always be the first response.
232       if (client_load_reporting_interval_seconds_ > 0) {
233         LoadBalanceResponse initial_response;
234         initial_response.mutable_initial_response()
235             ->mutable_client_stats_report_interval()
236             ->set_seconds(client_load_reporting_interval_seconds_);
237         stream->Write(initial_response);
238       }
239
240       {
241         grpc::internal::MutexLock lock(&mu_);
242         responses_and_delays = responses_and_delays_;
243       }
244       for (const auto& response_and_delay : responses_and_delays) {
245         SendResponse(stream, response_and_delay.first,
246                      response_and_delay.second);
247       }
248       {
249         grpc::internal::MutexLock lock(&mu_);
250         serverlist_cond_.WaitUntil(&mu_, [this] { return serverlist_done_; });
251       }
252
253       if (client_load_reporting_interval_seconds_ > 0) {
254         request.Clear();
255         if (stream->Read(&request)) {
256           gpr_log(GPR_INFO, "LB[%p]: received client load report message '%s'",
257                   this, request.DebugString().c_str());
258           GPR_ASSERT(request.has_client_stats());
259           // We need to acquire the lock here in order to prevent the notify_one
260           // below from firing before its corresponding wait is executed.
261           grpc::internal::MutexLock lock(&mu_);
262           client_stats_.num_calls_started +=
263               request.client_stats().num_calls_started();
264           client_stats_.num_calls_finished +=
265               request.client_stats().num_calls_finished();
266           client_stats_.num_calls_finished_with_client_failed_to_send +=
267               request.client_stats()
268                   .num_calls_finished_with_client_failed_to_send();
269           client_stats_.num_calls_finished_known_received +=
270               request.client_stats().num_calls_finished_known_received();
271           for (const auto& drop_token_count :
272                request.client_stats().calls_finished_with_drop()) {
273             client_stats_
274                 .drop_token_counts[drop_token_count.load_balance_token()] +=
275                 drop_token_count.num_calls();
276           }
277           load_report_ready_ = true;
278           load_report_cond_.Signal();
279         }
280       }
281     }
282   done:
283     gpr_log(GPR_INFO, "LB[%p]: done", this);
284     return Status::OK;
285   }
286
287   void add_response(const LoadBalanceResponse& response, int send_after_ms) {
288     grpc::internal::MutexLock lock(&mu_);
289     responses_and_delays_.push_back(std::make_pair(response, send_after_ms));
290   }
291
292   void Start() {
293     grpc::internal::MutexLock lock(&mu_);
294     serverlist_done_ = false;
295     load_report_ready_ = false;
296     responses_and_delays_.clear();
297     client_stats_.Reset();
298   }
299
300   void Shutdown() {
301     NotifyDoneWithServerlists();
302     gpr_log(GPR_INFO, "LB[%p]: shut down", this);
303   }
304
305   static LoadBalanceResponse BuildResponseForBackends(
306       const std::vector<int>& backend_ports,
307       const std::map<grpc::string, size_t>& drop_token_counts) {
308     LoadBalanceResponse response;
309     for (const auto& drop_token_count : drop_token_counts) {
310       for (size_t i = 0; i < drop_token_count.second; ++i) {
311         auto* server = response.mutable_server_list()->add_servers();
312         server->set_drop(true);
313         server->set_load_balance_token(drop_token_count.first);
314       }
315     }
316     for (const int& backend_port : backend_ports) {
317       auto* server = response.mutable_server_list()->add_servers();
318       server->set_ip_address(Ip4ToPackedString("127.0.0.1"));
319       server->set_port(backend_port);
320       static int token_count = 0;
321       char* token;
322       gpr_asprintf(&token, "token%03d", ++token_count);
323       server->set_load_balance_token(token);
324       gpr_free(token);
325     }
326     return response;
327   }
328
329   const ClientStats& WaitForLoadReport() {
330     grpc::internal::MutexLock lock(&mu_);
331     load_report_cond_.WaitUntil(&mu_, [this] { return load_report_ready_; });
332     load_report_ready_ = false;
333     return client_stats_;
334   }
335
336   void NotifyDoneWithServerlists() {
337     grpc::internal::MutexLock lock(&mu_);
338     if (!serverlist_done_) {
339       serverlist_done_ = true;
340       serverlist_cond_.Broadcast();
341     }
342   }
343
344  private:
345   void SendResponse(Stream* stream, const LoadBalanceResponse& response,
346                     int delay_ms) {
347     gpr_log(GPR_INFO, "LB[%p]: sleeping for %d ms...", this, delay_ms);
348     if (delay_ms > 0) {
349       gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
350     }
351     gpr_log(GPR_INFO, "LB[%p]: Woke up! Sending response '%s'", this,
352             response.DebugString().c_str());
353     IncreaseResponseCount();
354     stream->Write(response);
355   }
356
357   const int client_load_reporting_interval_seconds_;
358   std::vector<ResponseDelayPair> responses_and_delays_;
359   grpc::internal::Mutex mu_;
360   grpc::internal::CondVar load_report_cond_;
361   bool load_report_ready_ = false;
362   grpc::internal::CondVar serverlist_cond_;
363   bool serverlist_done_ = false;
364   ClientStats client_stats_;
365 };
366
367 class GrpclbEnd2endTest : public ::testing::Test {
368  protected:
369   GrpclbEnd2endTest(size_t num_backends, size_t num_balancers,
370                     int client_load_reporting_interval_seconds)
371       : server_host_("localhost"),
372         num_backends_(num_backends),
373         num_balancers_(num_balancers),
374         client_load_reporting_interval_seconds_(
375             client_load_reporting_interval_seconds) {}
376
377   void SetUp() override {
378     response_generator_ =
379         grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
380     // Start the backends.
381     for (size_t i = 0; i < num_backends_; ++i) {
382       backends_.emplace_back(new ServerThread<BackendServiceImpl>("backend"));
383       backends_.back()->Start(server_host_);
384     }
385     // Start the load balancers.
386     for (size_t i = 0; i < num_balancers_; ++i) {
387       balancers_.emplace_back(new ServerThread<BalancerServiceImpl>(
388           "balancer", client_load_reporting_interval_seconds_));
389       balancers_.back()->Start(server_host_);
390     }
391     ResetStub();
392   }
393
394   void TearDown() override {
395     ShutdownAllBackends();
396     for (auto& balancer : balancers_) balancer->Shutdown();
397   }
398
399   void StartAllBackends() {
400     for (auto& backend : backends_) backend->Start(server_host_);
401   }
402
403   void StartBackend(size_t index) { backends_[index]->Start(server_host_); }
404
405   void ShutdownAllBackends() {
406     for (auto& backend : backends_) backend->Shutdown();
407   }
408
409   void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
410
411   void ResetStub(int fallback_timeout = 0,
412                  const grpc::string& expected_targets = "") {
413     ChannelArguments args;
414     if (fallback_timeout > 0) args.SetGrpclbFallbackTimeout(fallback_timeout);
415     args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
416                     response_generator_.get());
417     if (!expected_targets.empty()) {
418       args.SetString(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
419     }
420     std::ostringstream uri;
421     uri << "fake:///" << kApplicationTargetName_;
422     // TODO(dgq): templatize tests to run everything using both secure and
423     // insecure channel credentials.
424     grpc_channel_credentials* channel_creds =
425         grpc_fake_transport_security_credentials_create();
426     grpc_call_credentials* call_creds = grpc_md_only_test_credentials_create(
427         g_kCallCredsMdKey, g_kCallCredsMdValue, false);
428     std::shared_ptr<ChannelCredentials> creds(
429         new SecureChannelCredentials(grpc_composite_channel_credentials_create(
430             channel_creds, call_creds, nullptr)));
431     call_creds->Unref();
432     channel_creds->Unref();
433     channel_ = ::grpc::CreateCustomChannel(uri.str(), creds, args);
434     stub_ = grpc::testing::EchoTestService::NewStub(channel_);
435   }
436
437   void ResetBackendCounters() {
438     for (auto& backend : backends_) backend->service_.ResetCounters();
439   }
440
441   ClientStats WaitForLoadReports() {
442     ClientStats client_stats;
443     for (auto& balancer : balancers_) {
444       client_stats += balancer->service_.WaitForLoadReport();
445     }
446     return client_stats;
447   }
448
449   bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0) {
450     if (stop_index == 0) stop_index = backends_.size();
451     for (size_t i = start_index; i < stop_index; ++i) {
452       if (backends_[i]->service_.request_count() == 0) return false;
453     }
454     return true;
455   }
456
457   void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
458                        int* num_drops) {
459     const Status status = SendRpc();
460     if (status.ok()) {
461       ++*num_ok;
462     } else {
463       if (status.error_message() == "Call dropped by load balancing policy") {
464         ++*num_drops;
465       } else {
466         ++*num_failure;
467       }
468     }
469     ++*num_total;
470   }
471
472   std::tuple<int, int, int> WaitForAllBackends(int num_requests_multiple_of = 1,
473                                                size_t start_index = 0,
474                                                size_t stop_index = 0) {
475     int num_ok = 0;
476     int num_failure = 0;
477     int num_drops = 0;
478     int num_total = 0;
479     while (!SeenAllBackends(start_index, stop_index)) {
480       SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
481     }
482     while (num_total % num_requests_multiple_of != 0) {
483       SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
484     }
485     ResetBackendCounters();
486     gpr_log(GPR_INFO,
487             "Performed %d warm up requests (a multiple of %d) against the "
488             "backends. %d succeeded, %d failed, %d dropped.",
489             num_total, num_requests_multiple_of, num_ok, num_failure,
490             num_drops);
491     return std::make_tuple(num_ok, num_failure, num_drops);
492   }
493
494   void WaitForBackend(size_t backend_idx) {
495     do {
496       (void)SendRpc();
497     } while (backends_[backend_idx]->service_.request_count() == 0);
498     ResetBackendCounters();
499   }
500
501   struct AddressData {
502     int port;
503     bool is_balancer;
504     grpc::string balancer_name;
505   };
506
507   grpc_core::ServerAddressList CreateLbAddressesFromAddressDataList(
508       const std::vector<AddressData>& address_data) {
509     grpc_core::ServerAddressList addresses;
510     for (const auto& addr : address_data) {
511       char* lb_uri_str;
512       gpr_asprintf(&lb_uri_str, "ipv4:127.0.0.1:%d", addr.port);
513       grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str, true);
514       GPR_ASSERT(lb_uri != nullptr);
515       grpc_resolved_address address;
516       GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
517       std::vector<grpc_arg> args_to_add;
518       if (addr.is_balancer) {
519         args_to_add.emplace_back(grpc_channel_arg_integer_create(
520             const_cast<char*>(GRPC_ARG_ADDRESS_IS_BALANCER), 1));
521         args_to_add.emplace_back(grpc_channel_arg_string_create(
522             const_cast<char*>(GRPC_ARG_ADDRESS_BALANCER_NAME),
523             const_cast<char*>(addr.balancer_name.c_str())));
524       }
525       grpc_channel_args* args = grpc_channel_args_copy_and_add(
526           nullptr, args_to_add.data(), args_to_add.size());
527       addresses.emplace_back(address.addr, address.len, args);
528       grpc_uri_destroy(lb_uri);
529       gpr_free(lb_uri_str);
530     }
531     return addresses;
532   }
533
534   void SetNextResolutionAllBalancers(
535       const char* service_config_json = nullptr) {
536     std::vector<AddressData> addresses;
537     for (size_t i = 0; i < balancers_.size(); ++i) {
538       addresses.emplace_back(AddressData{balancers_[i]->port_, true, ""});
539     }
540     SetNextResolution(addresses, service_config_json);
541   }
542
543   void SetNextResolution(const std::vector<AddressData>& address_data,
544                          const char* service_config_json = nullptr) {
545     grpc_core::ExecCtx exec_ctx;
546     grpc_core::Resolver::Result result;
547     result.addresses = CreateLbAddressesFromAddressDataList(address_data);
548     if (service_config_json != nullptr) {
549       grpc_error* error = GRPC_ERROR_NONE;
550       result.service_config =
551           grpc_core::ServiceConfig::Create(service_config_json, &error);
552       GRPC_ERROR_UNREF(error);
553     }
554     response_generator_->SetResponse(std::move(result));
555   }
556
557   void SetNextReresolutionResponse(
558       const std::vector<AddressData>& address_data) {
559     grpc_core::ExecCtx exec_ctx;
560     grpc_core::Resolver::Result result;
561     result.addresses = CreateLbAddressesFromAddressDataList(address_data);
562     response_generator_->SetReresolutionResponse(std::move(result));
563   }
564
565   const std::vector<int> GetBackendPorts(size_t start_index = 0,
566                                          size_t stop_index = 0) const {
567     if (stop_index == 0) stop_index = backends_.size();
568     std::vector<int> backend_ports;
569     for (size_t i = start_index; i < stop_index; ++i) {
570       backend_ports.push_back(backends_[i]->port_);
571     }
572     return backend_ports;
573   }
574
575   void ScheduleResponseForBalancer(size_t i,
576                                    const LoadBalanceResponse& response,
577                                    int delay_ms) {
578     balancers_[i]->service_.add_response(response, delay_ms);
579   }
580
581   Status SendRpc(EchoResponse* response = nullptr, int timeout_ms = 1000,
582                  bool wait_for_ready = false) {
583     const bool local_response = (response == nullptr);
584     if (local_response) response = new EchoResponse;
585     EchoRequest request;
586     request.set_message(kRequestMessage_);
587     ClientContext context;
588     context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
589     if (wait_for_ready) context.set_wait_for_ready(true);
590     Status status = stub_->Echo(&context, request, response);
591     if (local_response) delete response;
592     return status;
593   }
594
595   void CheckRpcSendOk(const size_t times = 1, const int timeout_ms = 1000,
596                       bool wait_for_ready = false) {
597     for (size_t i = 0; i < times; ++i) {
598       EchoResponse response;
599       const Status status = SendRpc(&response, timeout_ms, wait_for_ready);
600       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
601                                << " message=" << status.error_message();
602       EXPECT_EQ(response.message(), kRequestMessage_);
603     }
604   }
605
606   void CheckRpcSendFailure() {
607     const Status status = SendRpc();
608     EXPECT_FALSE(status.ok());
609   }
610
611   template <typename T>
612   struct ServerThread {
613     template <typename... Args>
614     explicit ServerThread(const grpc::string& type, Args&&... args)
615         : port_(grpc_pick_unused_port_or_die()),
616           type_(type),
617           service_(std::forward<Args>(args)...) {}
618
619     void Start(const grpc::string& server_host) {
620       gpr_log(GPR_INFO, "starting %s server on port %d", type_.c_str(), port_);
621       GPR_ASSERT(!running_);
622       running_ = true;
623       service_.Start();
624       grpc::internal::Mutex mu;
625       // We need to acquire the lock here in order to prevent the notify_one
626       // by ServerThread::Serve from firing before the wait below is hit.
627       grpc::internal::MutexLock lock(&mu);
628       grpc::internal::CondVar cond;
629       thread_.reset(new std::thread(
630           std::bind(&ServerThread::Serve, this, server_host, &mu, &cond)));
631       cond.Wait(&mu);
632       gpr_log(GPR_INFO, "%s server startup complete", type_.c_str());
633     }
634
635     void Serve(const grpc::string& server_host, grpc::internal::Mutex* mu,
636                grpc::internal::CondVar* cond) {
637       // We need to acquire the lock here in order to prevent the notify_one
638       // below from firing before its corresponding wait is executed.
639       grpc::internal::MutexLock lock(mu);
640       std::ostringstream server_address;
641       server_address << server_host << ":" << port_;
642       ServerBuilder builder;
643       std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
644           grpc_fake_transport_security_server_credentials_create()));
645       builder.AddListeningPort(server_address.str(), creds);
646       builder.RegisterService(&service_);
647       server_ = builder.BuildAndStart();
648       cond->Signal();
649     }
650
651     void Shutdown() {
652       if (!running_) return;
653       gpr_log(GPR_INFO, "%s about to shutdown", type_.c_str());
654       service_.Shutdown();
655       server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
656       thread_->join();
657       gpr_log(GPR_INFO, "%s shutdown completed", type_.c_str());
658       running_ = false;
659     }
660
661     const int port_;
662     grpc::string type_;
663     T service_;
664     std::unique_ptr<Server> server_;
665     std::unique_ptr<std::thread> thread_;
666     bool running_ = false;
667   };
668
669   const grpc::string server_host_;
670   const size_t num_backends_;
671   const size_t num_balancers_;
672   const int client_load_reporting_interval_seconds_;
673   std::shared_ptr<Channel> channel_;
674   std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
675   std::vector<std::unique_ptr<ServerThread<BackendServiceImpl>>> backends_;
676   std::vector<std::unique_ptr<ServerThread<BalancerServiceImpl>>> balancers_;
677   grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
678       response_generator_;
679   const grpc::string kRequestMessage_ = "Live long and prosper.";
680   const grpc::string kApplicationTargetName_ = "application_target_name";
681 };
682
683 class SingleBalancerTest : public GrpclbEnd2endTest {
684  public:
685   SingleBalancerTest() : GrpclbEnd2endTest(4, 1, 0) {}
686 };
687
688 TEST_F(SingleBalancerTest, Vanilla) {
689   SetNextResolutionAllBalancers();
690   const size_t kNumRpcsPerAddress = 100;
691   ScheduleResponseForBalancer(
692       0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
693       0);
694   // Make sure that trying to connect works without a call.
695   channel_->GetState(true /* try_to_connect */);
696   // We need to wait for all backends to come online.
697   WaitForAllBackends();
698   // Send kNumRpcsPerAddress RPCs per server.
699   CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
700
701   // Each backend should have gotten 100 requests.
702   for (size_t i = 0; i < backends_.size(); ++i) {
703     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
704   }
705   balancers_[0]->service_.NotifyDoneWithServerlists();
706   // The balancer got a single request.
707   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
708   // and sent a single response.
709   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
710
711   // Check LB policy name for the channel.
712   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
713 }
714
715 TEST_F(SingleBalancerTest, SelectGrpclbWithMigrationServiceConfig) {
716   SetNextResolutionAllBalancers(
717       "{\n"
718       "  \"loadBalancingConfig\":[\n"
719       "    { \"does_not_exist\":{} },\n"
720       "    { \"grpclb\":{} }\n"
721       "  ]\n"
722       "}");
723   ScheduleResponseForBalancer(
724       0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
725       0);
726   CheckRpcSendOk(1, 1000 /* timeout_ms */, true /* wait_for_ready */);
727   balancers_[0]->service_.NotifyDoneWithServerlists();
728   // The balancer got a single request.
729   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
730   // and sent a single response.
731   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
732   // Check LB policy name for the channel.
733   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
734 }
735
736 TEST_F(SingleBalancerTest,
737        DoNotSpecialCaseUseGrpclbWithLoadBalancingConfigTest) {
738   const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
739   ResetStub(kFallbackTimeoutMs);
740   SetNextResolution({AddressData{backends_[0]->port_, false, ""},
741                      AddressData{balancers_[0]->port_, true, ""}},
742                     "{\n"
743                     " \"loadBalancingConfig\":[\n"
744                     "  {\"pick_first\":{} }\n"
745                     " ]\n"
746                     "}");
747   CheckRpcSendOk();
748   // Check LB policy name for the channel.
749   EXPECT_EQ("pick_first", channel_->GetLoadBalancingPolicyName());
750 }
751
752 TEST_F(
753     SingleBalancerTest,
754     DoNotSpecialCaseUseGrpclbWithLoadBalancingConfigTestAndNoBackendAddress) {
755   const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
756   ResetStub(kFallbackTimeoutMs);
757   SetNextResolution({AddressData{balancers_[0]->port_, true, ""}},
758                     "{\n"
759                     " \"loadBalancingConfig\":[\n"
760                     "  {\"pick_first\":{} }\n"
761                     " ]\n"
762                     "}");
763   // This should fail since we do not have a non-balancer backend
764   CheckRpcSendFailure();
765   // Check LB policy name for the channel.
766   EXPECT_EQ("pick_first", channel_->GetLoadBalancingPolicyName());
767 }
768
769 TEST_F(SingleBalancerTest,
770        SelectGrpclbWithMigrationServiceConfigAndNoAddresses) {
771   const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
772   ResetStub(kFallbackTimeoutMs);
773   SetNextResolution({},
774                     "{\n"
775                     "  \"loadBalancingConfig\":[\n"
776                     "    { \"does_not_exist\":{} },\n"
777                     "    { \"grpclb\":{} }\n"
778                     "  ]\n"
779                     "}");
780   // Try to connect.
781   EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(true));
782   // Should go into state TRANSIENT_FAILURE when we enter fallback mode.
783   const gpr_timespec deadline = grpc_timeout_seconds_to_deadline(1);
784   grpc_connectivity_state state;
785   while ((state = channel_->GetState(false)) !=
786          GRPC_CHANNEL_TRANSIENT_FAILURE) {
787     ASSERT_TRUE(channel_->WaitForStateChange(state, deadline));
788   }
789   // Check LB policy name for the channel.
790   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
791 }
792
793 TEST_F(SingleBalancerTest,
794        SelectGrpclbWithMigrationServiceConfigAndNoBalancerAddresses) {
795   const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
796   ResetStub(kFallbackTimeoutMs);
797   // Resolution includes fallback address but no balancers.
798   SetNextResolution({AddressData{backends_[0]->port_, false, ""}},
799                     "{\n"
800                     "  \"loadBalancingConfig\":[\n"
801                     "    { \"does_not_exist\":{} },\n"
802                     "    { \"grpclb\":{} }\n"
803                     "  ]\n"
804                     "}");
805   CheckRpcSendOk(1, 1000 /* timeout_ms */, true /* wait_for_ready */);
806   // Check LB policy name for the channel.
807   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
808 }
809
810 TEST_F(SingleBalancerTest, UsePickFirstChildPolicy) {
811   SetNextResolutionAllBalancers(
812       "{\n"
813       "  \"loadBalancingConfig\":[\n"
814       "    { \"grpclb\":{\n"
815       "      \"childPolicy\":[\n"
816       "        { \"pick_first\":{} }\n"
817       "      ]\n"
818       "    } }\n"
819       "  ]\n"
820       "}");
821   ScheduleResponseForBalancer(
822       0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
823       0);
824   const size_t kNumRpcs = num_backends_ * 2;
825   CheckRpcSendOk(kNumRpcs, 1000 /* timeout_ms */, true /* wait_for_ready */);
826   balancers_[0]->service_.NotifyDoneWithServerlists();
827   // Check that all requests went to the first backend.  This verifies
828   // that we used pick_first instead of round_robin as the child policy.
829   EXPECT_EQ(backends_[0]->service_.request_count(), kNumRpcs);
830   for (size_t i = 1; i < backends_.size(); ++i) {
831     EXPECT_EQ(backends_[i]->service_.request_count(), 0UL);
832   }
833   // The balancer got a single request.
834   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
835   // and sent a single response.
836   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
837   // Check LB policy name for the channel.
838   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
839 }
840
841 TEST_F(SingleBalancerTest, SwapChildPolicy) {
842   SetNextResolutionAllBalancers(
843       "{\n"
844       "  \"loadBalancingConfig\":[\n"
845       "    { \"grpclb\":{\n"
846       "      \"childPolicy\":[\n"
847       "        { \"pick_first\":{} }\n"
848       "      ]\n"
849       "    } }\n"
850       "  ]\n"
851       "}");
852   ScheduleResponseForBalancer(
853       0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
854       0);
855   const size_t kNumRpcs = num_backends_ * 2;
856   CheckRpcSendOk(kNumRpcs, 1000 /* timeout_ms */, true /* wait_for_ready */);
857   // Check that all requests went to the first backend.  This verifies
858   // that we used pick_first instead of round_robin as the child policy.
859   EXPECT_EQ(backends_[0]->service_.request_count(), kNumRpcs);
860   for (size_t i = 1; i < backends_.size(); ++i) {
861     EXPECT_EQ(backends_[i]->service_.request_count(), 0UL);
862   }
863   // Send new resolution that removes child policy from service config.
864   SetNextResolutionAllBalancers("{}");
865   WaitForAllBackends();
866   CheckRpcSendOk(kNumRpcs, 1000 /* timeout_ms */, true /* wait_for_ready */);
867   // Check that every backend saw the same number of requests.  This verifies
868   // that we used round_robin.
869   for (size_t i = 0; i < backends_.size(); ++i) {
870     EXPECT_EQ(backends_[i]->service_.request_count(), 2UL);
871   }
872   // Done.
873   balancers_[0]->service_.NotifyDoneWithServerlists();
874   // The balancer got a single request.
875   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
876   // and sent a single response.
877   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
878   // Check LB policy name for the channel.
879   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
880 }
881
882 TEST_F(SingleBalancerTest, UpdatesGoToMostRecentChildPolicy) {
883   const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
884   ResetStub(kFallbackTimeoutMs);
885   int unreachable_balancer_port = grpc_pick_unused_port_or_die();
886   int unreachable_backend_port = grpc_pick_unused_port_or_die();
887   // Phase 1: Start with RR pointing to first backend.
888   gpr_log(GPR_INFO, "PHASE 1: Initial setup with RR with first backend");
889   SetNextResolution(
890       {
891           // Unreachable balancer.
892           {unreachable_balancer_port, true, ""},
893           // Fallback address: first backend.
894           {backends_[0]->port_, false, ""},
895       },
896       "{\n"
897       "  \"loadBalancingConfig\":[\n"
898       "    { \"grpclb\":{\n"
899       "      \"childPolicy\":[\n"
900       "        { \"round_robin\":{} }\n"
901       "      ]\n"
902       "    } }\n"
903       "  ]\n"
904       "}");
905   // RPCs should go to first backend.
906   WaitForBackend(0);
907   // Phase 2: Switch to PF pointing to unreachable backend.
908   gpr_log(GPR_INFO, "PHASE 2: Update to use PF with unreachable backend");
909   SetNextResolution(
910       {
911           // Unreachable balancer.
912           {unreachable_balancer_port, true, ""},
913           // Fallback address: unreachable backend.
914           {unreachable_backend_port, false, ""},
915       },
916       "{\n"
917       "  \"loadBalancingConfig\":[\n"
918       "    { \"grpclb\":{\n"
919       "      \"childPolicy\":[\n"
920       "        { \"pick_first\":{} }\n"
921       "      ]\n"
922       "    } }\n"
923       "  ]\n"
924       "}");
925   // RPCs should continue to go to the first backend, because the new
926   // PF child policy will never go into state READY.
927   WaitForBackend(0);
928   // Phase 3: Switch back to RR pointing to second and third backends.
929   // This ensures that we create a new policy rather than updating the
930   // pending PF policy.
931   gpr_log(GPR_INFO, "PHASE 3: Update to use RR again with two backends");
932   SetNextResolution(
933       {
934           // Unreachable balancer.
935           {unreachable_balancer_port, true, ""},
936           // Fallback address: second and third backends.
937           {backends_[1]->port_, false, ""},
938           {backends_[2]->port_, false, ""},
939       },
940       "{\n"
941       "  \"loadBalancingConfig\":[\n"
942       "    { \"grpclb\":{\n"
943       "      \"childPolicy\":[\n"
944       "        { \"round_robin\":{} }\n"
945       "      ]\n"
946       "    } }\n"
947       "  ]\n"
948       "}");
949   // RPCs should go to the second and third backends.
950   WaitForBackend(1);
951   WaitForBackend(2);
952 }
953
954 TEST_F(SingleBalancerTest, SameBackendListedMultipleTimes) {
955   SetNextResolutionAllBalancers();
956   // Same backend listed twice.
957   std::vector<int> ports;
958   ports.push_back(backends_[0]->port_);
959   ports.push_back(backends_[0]->port_);
960   const size_t kNumRpcsPerAddress = 10;
961   ScheduleResponseForBalancer(
962       0, BalancerServiceImpl::BuildResponseForBackends(ports, {}), 0);
963   // We need to wait for the backend to come online.
964   WaitForBackend(0);
965   // Send kNumRpcsPerAddress RPCs per server.
966   CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
967   // Backend should have gotten 20 requests.
968   EXPECT_EQ(kNumRpcsPerAddress * 2, backends_[0]->service_.request_count());
969   // And they should have come from a single client port, because of
970   // subchannel sharing.
971   EXPECT_EQ(1UL, backends_[0]->service_.clients().size());
972   balancers_[0]->service_.NotifyDoneWithServerlists();
973 }
974
975 TEST_F(SingleBalancerTest, SecureNaming) {
976   ResetStub(0, kApplicationTargetName_ + ";lb");
977   SetNextResolution({AddressData{balancers_[0]->port_, true, "lb"}});
978   const size_t kNumRpcsPerAddress = 100;
979   ScheduleResponseForBalancer(
980       0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
981       0);
982   // Make sure that trying to connect works without a call.
983   channel_->GetState(true /* try_to_connect */);
984   // We need to wait for all backends to come online.
985   WaitForAllBackends();
986   // Send kNumRpcsPerAddress RPCs per server.
987   CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
988
989   // Each backend should have gotten 100 requests.
990   for (size_t i = 0; i < backends_.size(); ++i) {
991     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
992   }
993   balancers_[0]->service_.NotifyDoneWithServerlists();
994   // The balancer got a single request.
995   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
996   // and sent a single response.
997   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
998   // Check LB policy name for the channel.
999   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
1000 }
1001
1002 TEST_F(SingleBalancerTest, SecureNamingDeathTest) {
1003   ::testing::FLAGS_gtest_death_test_style = "threadsafe";
1004   // Make sure that we blow up (via abort() from the security connector) when
1005   // the name from the balancer doesn't match expectations.
1006   ASSERT_DEATH(
1007       {
1008         ResetStub(0, kApplicationTargetName_ + ";lb");
1009         SetNextResolution({AddressData{balancers_[0]->port_, true, "woops"}});
1010         channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(1));
1011       },
1012       "");
1013 }
1014
1015 TEST_F(SingleBalancerTest, InitiallyEmptyServerlist) {
1016   SetNextResolutionAllBalancers();
1017   const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
1018   const int kCallDeadlineMs = kServerlistDelayMs * 2;
1019   // First response is an empty serverlist, sent right away.
1020   ScheduleResponseForBalancer(0, LoadBalanceResponse(), 0);
1021   // Send non-empty serverlist only after kServerlistDelayMs
1022   ScheduleResponseForBalancer(
1023       0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
1024       kServerlistDelayMs);
1025   const auto t0 = system_clock::now();
1026   // Client will block: LB will initially send empty serverlist.
1027   CheckRpcSendOk(1, kCallDeadlineMs, true /* wait_for_ready */);
1028   const auto ellapsed_ms =
1029       std::chrono::duration_cast<std::chrono::milliseconds>(
1030           system_clock::now() - t0);
1031   // but eventually, the LB sends a serverlist update that allows the call to
1032   // proceed. The call delay must be larger than the delay in sending the
1033   // populated serverlist but under the call's deadline (which is enforced by
1034   // the call's deadline).
1035   EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
1036   balancers_[0]->service_.NotifyDoneWithServerlists();
1037   // The balancer got a single request.
1038   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1039   // and sent two responses.
1040   EXPECT_EQ(2U, balancers_[0]->service_.response_count());
1041 }
1042
1043 TEST_F(SingleBalancerTest, AllServersUnreachableFailFast) {
1044   SetNextResolutionAllBalancers();
1045   const size_t kNumUnreachableServers = 5;
1046   std::vector<int> ports;
1047   for (size_t i = 0; i < kNumUnreachableServers; ++i) {
1048     ports.push_back(grpc_pick_unused_port_or_die());
1049   }
1050   ScheduleResponseForBalancer(
1051       0, BalancerServiceImpl::BuildResponseForBackends(ports, {}), 0);
1052   const Status status = SendRpc();
1053   // The error shouldn't be DEADLINE_EXCEEDED.
1054   EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
1055   balancers_[0]->service_.NotifyDoneWithServerlists();
1056   // The balancer got a single request.
1057   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1058   // and sent a single response.
1059   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1060 }
1061
1062 TEST_F(SingleBalancerTest, Fallback) {
1063   SetNextResolutionAllBalancers();
1064   const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
1065   const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
1066   const size_t kNumBackendsInResolution = backends_.size() / 2;
1067
1068   ResetStub(kFallbackTimeoutMs);
1069   std::vector<AddressData> addresses;
1070   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1071   for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
1072     addresses.emplace_back(AddressData{backends_[i]->port_, false, ""});
1073   }
1074   SetNextResolution(addresses);
1075
1076   // Send non-empty serverlist only after kServerlistDelayMs.
1077   ScheduleResponseForBalancer(
1078       0,
1079       BalancerServiceImpl::BuildResponseForBackends(
1080           GetBackendPorts(kNumBackendsInResolution /* start_index */), {}),
1081       kServerlistDelayMs);
1082
1083   // Wait until all the fallback backends are reachable.
1084   for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
1085     WaitForBackend(i);
1086   }
1087
1088   // The first request.
1089   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1090   CheckRpcSendOk(kNumBackendsInResolution);
1091   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1092
1093   // Fallback is used: each backend returned by the resolver should have
1094   // gotten one request.
1095   for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
1096     EXPECT_EQ(1U, backends_[i]->service_.request_count());
1097   }
1098   for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
1099     EXPECT_EQ(0U, backends_[i]->service_.request_count());
1100   }
1101
1102   // Wait until the serverlist reception has been processed and all backends
1103   // in the serverlist are reachable.
1104   for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
1105     WaitForBackend(i);
1106   }
1107
1108   // Send out the second request.
1109   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
1110   CheckRpcSendOk(backends_.size() - kNumBackendsInResolution);
1111   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
1112
1113   // Serverlist is used: each backend returned by the balancer should
1114   // have gotten one request.
1115   for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
1116     EXPECT_EQ(0U, backends_[i]->service_.request_count());
1117   }
1118   for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
1119     EXPECT_EQ(1U, backends_[i]->service_.request_count());
1120   }
1121
1122   balancers_[0]->service_.NotifyDoneWithServerlists();
1123   // The balancer got a single request.
1124   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1125   // and sent a single response.
1126   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1127 }
1128
1129 TEST_F(SingleBalancerTest, FallbackUpdate) {
1130   SetNextResolutionAllBalancers();
1131   const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
1132   const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
1133   const size_t kNumBackendsInResolution = backends_.size() / 3;
1134   const size_t kNumBackendsInResolutionUpdate = backends_.size() / 3;
1135
1136   ResetStub(kFallbackTimeoutMs);
1137   std::vector<AddressData> addresses;
1138   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1139   for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
1140     addresses.emplace_back(AddressData{backends_[i]->port_, false, ""});
1141   }
1142   SetNextResolution(addresses);
1143
1144   // Send non-empty serverlist only after kServerlistDelayMs.
1145   ScheduleResponseForBalancer(
1146       0,
1147       BalancerServiceImpl::BuildResponseForBackends(
1148           GetBackendPorts(kNumBackendsInResolution +
1149                           kNumBackendsInResolutionUpdate /* start_index */),
1150           {}),
1151       kServerlistDelayMs);
1152
1153   // Wait until all the fallback backends are reachable.
1154   for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
1155     WaitForBackend(i);
1156   }
1157
1158   // The first request.
1159   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1160   CheckRpcSendOk(kNumBackendsInResolution);
1161   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1162
1163   // Fallback is used: each backend returned by the resolver should have
1164   // gotten one request.
1165   for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
1166     EXPECT_EQ(1U, backends_[i]->service_.request_count());
1167   }
1168   for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
1169     EXPECT_EQ(0U, backends_[i]->service_.request_count());
1170   }
1171
1172   addresses.clear();
1173   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1174   for (size_t i = kNumBackendsInResolution;
1175        i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
1176     addresses.emplace_back(AddressData{backends_[i]->port_, false, ""});
1177   }
1178   SetNextResolution(addresses);
1179
1180   // Wait until the resolution update has been processed and all the new
1181   // fallback backends are reachable.
1182   for (size_t i = kNumBackendsInResolution;
1183        i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
1184     WaitForBackend(i);
1185   }
1186
1187   // Send out the second request.
1188   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
1189   CheckRpcSendOk(kNumBackendsInResolutionUpdate);
1190   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
1191
1192   // The resolution update is used: each backend in the resolution update should
1193   // have gotten one request.
1194   for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
1195     EXPECT_EQ(0U, backends_[i]->service_.request_count());
1196   }
1197   for (size_t i = kNumBackendsInResolution;
1198        i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
1199     EXPECT_EQ(1U, backends_[i]->service_.request_count());
1200   }
1201   for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
1202        i < backends_.size(); ++i) {
1203     EXPECT_EQ(0U, backends_[i]->service_.request_count());
1204   }
1205
1206   // Wait until the serverlist reception has been processed and all backends
1207   // in the serverlist are reachable.
1208   for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
1209        i < backends_.size(); ++i) {
1210     WaitForBackend(i);
1211   }
1212
1213   // Send out the third request.
1214   gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
1215   CheckRpcSendOk(backends_.size() - kNumBackendsInResolution -
1216                  kNumBackendsInResolutionUpdate);
1217   gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
1218
1219   // Serverlist is used: each backend returned by the balancer should
1220   // have gotten one request.
1221   for (size_t i = 0;
1222        i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
1223     EXPECT_EQ(0U, backends_[i]->service_.request_count());
1224   }
1225   for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
1226        i < backends_.size(); ++i) {
1227     EXPECT_EQ(1U, backends_[i]->service_.request_count());
1228   }
1229
1230   balancers_[0]->service_.NotifyDoneWithServerlists();
1231   // The balancer got a single request.
1232   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1233   // and sent a single response.
1234   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1235 }
1236
1237 TEST_F(SingleBalancerTest,
1238        FallbackAfterStartup_LoseContactWithBalancerThenBackends) {
1239   // First two backends are fallback, last two are pointed to by balancer.
1240   const size_t kNumFallbackBackends = 2;
1241   const size_t kNumBalancerBackends = backends_.size() - kNumFallbackBackends;
1242   std::vector<AddressData> addresses;
1243   for (size_t i = 0; i < kNumFallbackBackends; ++i) {
1244     addresses.emplace_back(AddressData{backends_[i]->port_, false, ""});
1245   }
1246   for (size_t i = 0; i < balancers_.size(); ++i) {
1247     addresses.emplace_back(AddressData{balancers_[i]->port_, true, ""});
1248   }
1249   SetNextResolution(addresses);
1250   ScheduleResponseForBalancer(0,
1251                               BalancerServiceImpl::BuildResponseForBackends(
1252                                   GetBackendPorts(kNumFallbackBackends), {}),
1253                               0);
1254   // Try to connect.
1255   channel_->GetState(true /* try_to_connect */);
1256   WaitForAllBackends(1 /* num_requests_multiple_of */,
1257                      kNumFallbackBackends /* start_index */);
1258   // Stop balancer.  RPCs should continue going to backends from balancer.
1259   balancers_[0]->Shutdown();
1260   CheckRpcSendOk(100 * kNumBalancerBackends);
1261   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1262     EXPECT_EQ(100UL, backends_[i]->service_.request_count());
1263   }
1264   // Stop backends from balancer.  This should put us in fallback mode.
1265   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1266     ShutdownBackend(i);
1267   }
1268   WaitForAllBackends(1 /* num_requests_multiple_of */, 0 /* start_index */,
1269                      kNumFallbackBackends /* stop_index */);
1270   // Restart the backends from the balancer.  We should *not* start
1271   // sending traffic back to them at this point (although the behavior
1272   // in xds may be different).
1273   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1274     StartBackend(i);
1275   }
1276   CheckRpcSendOk(100 * kNumBalancerBackends);
1277   for (size_t i = 0; i < kNumFallbackBackends; ++i) {
1278     EXPECT_EQ(100UL, backends_[i]->service_.request_count());
1279   }
1280   // Now start the balancer again.  This should cause us to exit
1281   // fallback mode.
1282   balancers_[0]->Start(server_host_);
1283   ScheduleResponseForBalancer(0,
1284                               BalancerServiceImpl::BuildResponseForBackends(
1285                                   GetBackendPorts(kNumFallbackBackends), {}),
1286                               0);
1287   WaitForAllBackends(1 /* num_requests_multiple_of */,
1288                      kNumFallbackBackends /* start_index */);
1289 }
1290
1291 TEST_F(SingleBalancerTest,
1292        FallbackAfterStartup_LoseContactWithBackendsThenBalancer) {
1293   // First two backends are fallback, last two are pointed to by balancer.
1294   const size_t kNumFallbackBackends = 2;
1295   const size_t kNumBalancerBackends = backends_.size() - kNumFallbackBackends;
1296   std::vector<AddressData> addresses;
1297   for (size_t i = 0; i < kNumFallbackBackends; ++i) {
1298     addresses.emplace_back(AddressData{backends_[i]->port_, false, ""});
1299   }
1300   for (size_t i = 0; i < balancers_.size(); ++i) {
1301     addresses.emplace_back(AddressData{balancers_[i]->port_, true, ""});
1302   }
1303   SetNextResolution(addresses);
1304   ScheduleResponseForBalancer(0,
1305                               BalancerServiceImpl::BuildResponseForBackends(
1306                                   GetBackendPorts(kNumFallbackBackends), {}),
1307                               0);
1308   // Try to connect.
1309   channel_->GetState(true /* try_to_connect */);
1310   WaitForAllBackends(1 /* num_requests_multiple_of */,
1311                      kNumFallbackBackends /* start_index */);
1312   // Stop backends from balancer.  Since we are still in contact with
1313   // the balancer at this point, RPCs should be failing.
1314   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1315     ShutdownBackend(i);
1316   }
1317   CheckRpcSendFailure();
1318   // Stop balancer.  This should put us in fallback mode.
1319   balancers_[0]->Shutdown();
1320   WaitForAllBackends(1 /* num_requests_multiple_of */, 0 /* start_index */,
1321                      kNumFallbackBackends /* stop_index */);
1322   // Restart the backends from the balancer.  We should *not* start
1323   // sending traffic back to them at this point (although the behavior
1324   // in xds may be different).
1325   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1326     StartBackend(i);
1327   }
1328   CheckRpcSendOk(100 * kNumBalancerBackends);
1329   for (size_t i = 0; i < kNumFallbackBackends; ++i) {
1330     EXPECT_EQ(100UL, backends_[i]->service_.request_count());
1331   }
1332   // Now start the balancer again.  This should cause us to exit
1333   // fallback mode.
1334   balancers_[0]->Start(server_host_);
1335   ScheduleResponseForBalancer(0,
1336                               BalancerServiceImpl::BuildResponseForBackends(
1337                                   GetBackendPorts(kNumFallbackBackends), {}),
1338                               0);
1339   WaitForAllBackends(1 /* num_requests_multiple_of */,
1340                      kNumFallbackBackends /* start_index */);
1341 }
1342
1343 TEST_F(SingleBalancerTest, FallbackEarlyWhenBalancerChannelFails) {
1344   const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
1345   ResetStub(kFallbackTimeoutMs);
1346   // Return an unreachable balancer and one fallback backend.
1347   std::vector<AddressData> addresses;
1348   addresses.emplace_back(AddressData{grpc_pick_unused_port_or_die(), true, ""});
1349   addresses.emplace_back(AddressData{backends_[0]->port_, false, ""});
1350   SetNextResolution(addresses);
1351   // Send RPC with deadline less than the fallback timeout and make sure it
1352   // succeeds.
1353   CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
1354                  /* wait_for_ready */ false);
1355 }
1356
1357 TEST_F(SingleBalancerTest, FallbackEarlyWhenBalancerCallFails) {
1358   const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
1359   ResetStub(kFallbackTimeoutMs);
1360   // Return an unreachable balancer and one fallback backend.
1361   std::vector<AddressData> addresses;
1362   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1363   addresses.emplace_back(AddressData{backends_[0]->port_, false, ""});
1364   SetNextResolution(addresses);
1365   // Balancer drops call without sending a serverlist.
1366   balancers_[0]->service_.NotifyDoneWithServerlists();
1367   // Send RPC with deadline less than the fallback timeout and make sure it
1368   // succeeds.
1369   CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
1370                  /* wait_for_ready */ false);
1371 }
1372
1373 TEST_F(SingleBalancerTest, BackendsRestart) {
1374   SetNextResolutionAllBalancers();
1375   const size_t kNumRpcsPerAddress = 100;
1376   ScheduleResponseForBalancer(
1377       0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
1378       0);
1379   // Make sure that trying to connect works without a call.
1380   channel_->GetState(true /* try_to_connect */);
1381   // Send kNumRpcsPerAddress RPCs per server.
1382   CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
1383   // Stop backends.  RPCs should fail.
1384   ShutdownAllBackends();
1385   CheckRpcSendFailure();
1386   // Restart backends.  RPCs should start succeeding again.
1387   StartAllBackends();
1388   CheckRpcSendOk(1 /* times */, 2000 /* timeout_ms */,
1389                  true /* wait_for_ready */);
1390   // The balancer got a single request.
1391   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1392   // and sent a single response.
1393   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1394 }
1395
1396 class UpdatesTest : public GrpclbEnd2endTest {
1397  public:
1398   UpdatesTest() : GrpclbEnd2endTest(4, 3, 0) {}
1399 };
1400
1401 TEST_F(UpdatesTest, UpdateBalancersButKeepUsingOriginalBalancer) {
1402   SetNextResolutionAllBalancers();
1403   const std::vector<int> first_backend{GetBackendPorts()[0]};
1404   const std::vector<int> second_backend{GetBackendPorts()[1]};
1405   ScheduleResponseForBalancer(
1406       0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
1407   ScheduleResponseForBalancer(
1408       1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
1409
1410   // Wait until the first backend is ready.
1411   WaitForBackend(0);
1412
1413   // Send 10 requests.
1414   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1415   CheckRpcSendOk(10);
1416   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1417
1418   // All 10 requests should have gone to the first backend.
1419   EXPECT_EQ(10U, backends_[0]->service_.request_count());
1420
1421   // Balancer 0 got a single request.
1422   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1423   // and sent a single response.
1424   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1425   EXPECT_EQ(0U, balancers_[1]->service_.request_count());
1426   EXPECT_EQ(0U, balancers_[1]->service_.response_count());
1427   EXPECT_EQ(0U, balancers_[2]->service_.request_count());
1428   EXPECT_EQ(0U, balancers_[2]->service_.response_count());
1429
1430   std::vector<AddressData> addresses;
1431   addresses.emplace_back(AddressData{balancers_[1]->port_, true, ""});
1432   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
1433   SetNextResolution(addresses);
1434   gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
1435
1436   EXPECT_EQ(0U, backends_[1]->service_.request_count());
1437   gpr_timespec deadline = gpr_time_add(
1438       gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
1439   // Send 10 seconds worth of RPCs
1440   do {
1441     CheckRpcSendOk();
1442   } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
1443   // The current LB call is still working, so grpclb continued using it to the
1444   // first balancer, which doesn't assign the second backend.
1445   EXPECT_EQ(0U, backends_[1]->service_.request_count());
1446
1447   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1448   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1449   EXPECT_EQ(0U, balancers_[1]->service_.request_count());
1450   EXPECT_EQ(0U, balancers_[1]->service_.response_count());
1451   EXPECT_EQ(0U, balancers_[2]->service_.request_count());
1452   EXPECT_EQ(0U, balancers_[2]->service_.response_count());
1453 }
1454
1455 // Send an update with the same set of LBs as the one in SetUp() in order to
1456 // verify that the LB channel inside grpclb keeps the initial connection (which
1457 // by definition is also present in the update).
1458 TEST_F(UpdatesTest, UpdateBalancersRepeated) {
1459   SetNextResolutionAllBalancers();
1460   const std::vector<int> first_backend{GetBackendPorts()[0]};
1461   const std::vector<int> second_backend{GetBackendPorts()[0]};
1462
1463   ScheduleResponseForBalancer(
1464       0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
1465   ScheduleResponseForBalancer(
1466       1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
1467
1468   // Wait until the first backend is ready.
1469   WaitForBackend(0);
1470
1471   // Send 10 requests.
1472   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1473   CheckRpcSendOk(10);
1474   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1475
1476   // All 10 requests should have gone to the first backend.
1477   EXPECT_EQ(10U, backends_[0]->service_.request_count());
1478
1479   balancers_[0]->service_.NotifyDoneWithServerlists();
1480   // Balancer 0 got a single request.
1481   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1482   // and sent a single response.
1483   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1484   EXPECT_EQ(0U, balancers_[1]->service_.request_count());
1485   EXPECT_EQ(0U, balancers_[1]->service_.response_count());
1486   EXPECT_EQ(0U, balancers_[2]->service_.request_count());
1487   EXPECT_EQ(0U, balancers_[2]->service_.response_count());
1488
1489   std::vector<AddressData> addresses;
1490   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1491   addresses.emplace_back(AddressData{balancers_[1]->port_, true, ""});
1492   addresses.emplace_back(AddressData{balancers_[2]->port_, true, ""});
1493   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
1494   SetNextResolution(addresses);
1495   gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
1496
1497   EXPECT_EQ(0U, backends_[1]->service_.request_count());
1498   gpr_timespec deadline = gpr_time_add(
1499       gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
1500   // Send 10 seconds worth of RPCs
1501   do {
1502     CheckRpcSendOk();
1503   } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
1504   // grpclb continued using the original LB call to the first balancer, which
1505   // doesn't assign the second backend.
1506   EXPECT_EQ(0U, backends_[1]->service_.request_count());
1507   balancers_[0]->service_.NotifyDoneWithServerlists();
1508
1509   addresses.clear();
1510   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1511   addresses.emplace_back(AddressData{balancers_[1]->port_, true, ""});
1512   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
1513   SetNextResolution(addresses);
1514   gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
1515
1516   EXPECT_EQ(0U, backends_[1]->service_.request_count());
1517   deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
1518                           gpr_time_from_millis(10000, GPR_TIMESPAN));
1519   // Send 10 seconds worth of RPCs
1520   do {
1521     CheckRpcSendOk();
1522   } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
1523   // grpclb continued using the original LB call to the first balancer, which
1524   // doesn't assign the second backend.
1525   EXPECT_EQ(0U, backends_[1]->service_.request_count());
1526   balancers_[0]->service_.NotifyDoneWithServerlists();
1527 }
1528
1529 TEST_F(UpdatesTest, UpdateBalancersDeadUpdate) {
1530   std::vector<AddressData> addresses;
1531   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1532   SetNextResolution(addresses);
1533   const std::vector<int> first_backend{GetBackendPorts()[0]};
1534   const std::vector<int> second_backend{GetBackendPorts()[1]};
1535
1536   ScheduleResponseForBalancer(
1537       0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
1538   ScheduleResponseForBalancer(
1539       1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
1540
1541   // Start servers and send 10 RPCs per server.
1542   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1543   CheckRpcSendOk(10);
1544   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1545   // All 10 requests should have gone to the first backend.
1546   EXPECT_EQ(10U, backends_[0]->service_.request_count());
1547
1548   // Kill balancer 0
1549   gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
1550   balancers_[0]->Shutdown();
1551   gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
1552
1553   // This is serviced by the existing RR policy
1554   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
1555   CheckRpcSendOk(10);
1556   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
1557   // All 10 requests should again have gone to the first backend.
1558   EXPECT_EQ(20U, backends_[0]->service_.request_count());
1559   EXPECT_EQ(0U, backends_[1]->service_.request_count());
1560
1561   // Balancer 0 got a single request.
1562   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1563   // and sent a single response.
1564   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1565   EXPECT_EQ(0U, balancers_[1]->service_.request_count());
1566   EXPECT_EQ(0U, balancers_[1]->service_.response_count());
1567   EXPECT_EQ(0U, balancers_[2]->service_.request_count());
1568   EXPECT_EQ(0U, balancers_[2]->service_.response_count());
1569
1570   addresses.clear();
1571   addresses.emplace_back(AddressData{balancers_[1]->port_, true, ""});
1572   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
1573   SetNextResolution(addresses);
1574   gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
1575
1576   // Wait until update has been processed, as signaled by the second backend
1577   // receiving a request. In the meantime, the client continues to be serviced
1578   // (by the first backend) without interruption.
1579   EXPECT_EQ(0U, backends_[1]->service_.request_count());
1580   WaitForBackend(1);
1581
1582   // This is serviced by the updated RR policy
1583   backends_[1]->service_.ResetCounters();
1584   gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
1585   CheckRpcSendOk(10);
1586   gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
1587   // All 10 requests should have gone to the second backend.
1588   EXPECT_EQ(10U, backends_[1]->service_.request_count());
1589
1590   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1591   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1592   // The second balancer, published as part of the first update, may end up
1593   // getting two requests (that is, 1 <= #req <= 2) if the LB call retry timer
1594   // firing races with the arrival of the update containing the second
1595   // balancer.
1596   EXPECT_GE(balancers_[1]->service_.request_count(), 1U);
1597   EXPECT_GE(balancers_[1]->service_.response_count(), 1U);
1598   EXPECT_LE(balancers_[1]->service_.request_count(), 2U);
1599   EXPECT_LE(balancers_[1]->service_.response_count(), 2U);
1600   EXPECT_EQ(0U, balancers_[2]->service_.request_count());
1601   EXPECT_EQ(0U, balancers_[2]->service_.response_count());
1602 }
1603
1604 TEST_F(UpdatesTest, ReresolveDeadBackend) {
1605   ResetStub(500);
1606   // The first resolution contains the addresses of a balancer that never
1607   // responds, and a fallback backend.
1608   std::vector<AddressData> addresses;
1609   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1610   addresses.emplace_back(AddressData{backends_[0]->port_, false, ""});
1611   SetNextResolution(addresses);
1612   // The re-resolution result will contain the addresses of the same balancer
1613   // and a new fallback backend.
1614   addresses.clear();
1615   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1616   addresses.emplace_back(AddressData{backends_[1]->port_, false, ""});
1617   SetNextReresolutionResponse(addresses);
1618
1619   // Start servers and send 10 RPCs per server.
1620   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1621   CheckRpcSendOk(10);
1622   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1623   // All 10 requests should have gone to the fallback backend.
1624   EXPECT_EQ(10U, backends_[0]->service_.request_count());
1625
1626   // Kill backend 0.
1627   gpr_log(GPR_INFO, "********** ABOUT TO KILL BACKEND 0 *************");
1628   backends_[0]->Shutdown();
1629   gpr_log(GPR_INFO, "********** KILLED BACKEND 0 *************");
1630
1631   // Wait until re-resolution has finished, as signaled by the second backend
1632   // receiving a request.
1633   WaitForBackend(1);
1634
1635   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
1636   CheckRpcSendOk(10);
1637   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
1638   // All 10 requests should have gone to the second backend.
1639   EXPECT_EQ(10U, backends_[1]->service_.request_count());
1640
1641   balancers_[0]->service_.NotifyDoneWithServerlists();
1642   balancers_[1]->service_.NotifyDoneWithServerlists();
1643   balancers_[2]->service_.NotifyDoneWithServerlists();
1644   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1645   EXPECT_EQ(0U, balancers_[0]->service_.response_count());
1646   EXPECT_EQ(0U, balancers_[1]->service_.request_count());
1647   EXPECT_EQ(0U, balancers_[1]->service_.response_count());
1648   EXPECT_EQ(0U, balancers_[2]->service_.request_count());
1649   EXPECT_EQ(0U, balancers_[2]->service_.response_count());
1650 }
1651
1652 // TODO(juanlishen): Should be removed when the first response is always the
1653 // initial response. Currently, if client load reporting is not enabled, the
1654 // balancer doesn't send initial response. When the backend shuts down, an
1655 // unexpected re-resolution will happen. This test configuration is a workaround
1656 // for test ReresolveDeadBalancer.
1657 class UpdatesWithClientLoadReportingTest : public GrpclbEnd2endTest {
1658  public:
1659   UpdatesWithClientLoadReportingTest() : GrpclbEnd2endTest(4, 3, 2) {}
1660 };
1661
1662 TEST_F(UpdatesWithClientLoadReportingTest, ReresolveDeadBalancer) {
1663   std::vector<AddressData> addresses;
1664   addresses.emplace_back(AddressData{balancers_[0]->port_, true, ""});
1665   SetNextResolution(addresses);
1666   addresses.clear();
1667   addresses.emplace_back(AddressData{balancers_[1]->port_, true, ""});
1668   SetNextReresolutionResponse(addresses);
1669   const std::vector<int> first_backend{GetBackendPorts()[0]};
1670   const std::vector<int> second_backend{GetBackendPorts()[1]};
1671
1672   ScheduleResponseForBalancer(
1673       0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
1674   ScheduleResponseForBalancer(
1675       1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
1676
1677   // Start servers and send 10 RPCs per server.
1678   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
1679   CheckRpcSendOk(10);
1680   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
1681   // All 10 requests should have gone to the first backend.
1682   EXPECT_EQ(10U, backends_[0]->service_.request_count());
1683
1684   // Kill backend 0.
1685   gpr_log(GPR_INFO, "********** ABOUT TO KILL BACKEND 0 *************");
1686   backends_[0]->Shutdown();
1687   gpr_log(GPR_INFO, "********** KILLED BACKEND 0 *************");
1688
1689   CheckRpcSendFailure();
1690
1691   // Balancer 0 got a single request.
1692   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1693   // and sent a single response.
1694   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1695   EXPECT_EQ(0U, balancers_[1]->service_.request_count());
1696   EXPECT_EQ(0U, balancers_[1]->service_.response_count());
1697   EXPECT_EQ(0U, balancers_[2]->service_.request_count());
1698   EXPECT_EQ(0U, balancers_[2]->service_.response_count());
1699
1700   // Kill balancer 0.
1701   gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
1702   balancers_[0]->Shutdown();
1703   gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
1704
1705   // Wait until re-resolution has finished, as signaled by the second backend
1706   // receiving a request.
1707   WaitForBackend(1);
1708
1709   // This is serviced by the new serverlist.
1710   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
1711   CheckRpcSendOk(10);
1712   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
1713   // All 10 requests should have gone to the second backend.
1714   EXPECT_EQ(10U, backends_[1]->service_.request_count());
1715
1716   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1717   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1718   // After balancer 0 is killed, we restart an LB call immediately (because we
1719   // disconnect to a previously connected balancer). Although we will cancel
1720   // this call when the re-resolution update is done and another LB call restart
1721   // is needed, this old call may still succeed reaching the LB server if
1722   // re-resolution is slow. So balancer 1 may have received 2 requests and sent
1723   // 2 responses.
1724   EXPECT_GE(balancers_[1]->service_.request_count(), 1U);
1725   EXPECT_GE(balancers_[1]->service_.response_count(), 1U);
1726   EXPECT_LE(balancers_[1]->service_.request_count(), 2U);
1727   EXPECT_LE(balancers_[1]->service_.response_count(), 2U);
1728   EXPECT_EQ(0U, balancers_[2]->service_.request_count());
1729   EXPECT_EQ(0U, balancers_[2]->service_.response_count());
1730 }
1731
1732 TEST_F(SingleBalancerTest, Drop) {
1733   SetNextResolutionAllBalancers();
1734   const size_t kNumRpcsPerAddress = 100;
1735   const int num_of_drop_by_rate_limiting_addresses = 1;
1736   const int num_of_drop_by_load_balancing_addresses = 2;
1737   const int num_of_drop_addresses = num_of_drop_by_rate_limiting_addresses +
1738                                     num_of_drop_by_load_balancing_addresses;
1739   const int num_total_addresses = num_backends_ + num_of_drop_addresses;
1740   ScheduleResponseForBalancer(
1741       0,
1742       BalancerServiceImpl::BuildResponseForBackends(
1743           GetBackendPorts(),
1744           {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
1745            {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
1746       0);
1747   // Wait until all backends are ready.
1748   WaitForAllBackends();
1749   // Send kNumRpcsPerAddress RPCs for each server and drop address.
1750   size_t num_drops = 0;
1751   for (size_t i = 0; i < kNumRpcsPerAddress * num_total_addresses; ++i) {
1752     EchoResponse response;
1753     const Status status = SendRpc(&response);
1754     if (!status.ok() &&
1755         status.error_message() == "Call dropped by load balancing policy") {
1756       ++num_drops;
1757     } else {
1758       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
1759                                << " message=" << status.error_message();
1760       EXPECT_EQ(response.message(), kRequestMessage_);
1761     }
1762   }
1763   EXPECT_EQ(kNumRpcsPerAddress * num_of_drop_addresses, num_drops);
1764   // Each backend should have gotten 100 requests.
1765   for (size_t i = 0; i < backends_.size(); ++i) {
1766     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
1767   }
1768   // The balancer got a single request.
1769   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1770   // and sent a single response.
1771   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1772 }
1773
1774 TEST_F(SingleBalancerTest, DropAllFirst) {
1775   SetNextResolutionAllBalancers();
1776   // All registered addresses are marked as "drop".
1777   const int num_of_drop_by_rate_limiting_addresses = 1;
1778   const int num_of_drop_by_load_balancing_addresses = 1;
1779   ScheduleResponseForBalancer(
1780       0,
1781       BalancerServiceImpl::BuildResponseForBackends(
1782           {}, {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
1783                {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
1784       0);
1785   const Status status = SendRpc(nullptr, 1000, true);
1786   EXPECT_FALSE(status.ok());
1787   EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
1788 }
1789
1790 TEST_F(SingleBalancerTest, DropAll) {
1791   SetNextResolutionAllBalancers();
1792   ScheduleResponseForBalancer(
1793       0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
1794       0);
1795   const int num_of_drop_by_rate_limiting_addresses = 1;
1796   const int num_of_drop_by_load_balancing_addresses = 1;
1797   ScheduleResponseForBalancer(
1798       0,
1799       BalancerServiceImpl::BuildResponseForBackends(
1800           {}, {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
1801                {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
1802       1000);
1803
1804   // First call succeeds.
1805   CheckRpcSendOk();
1806   // But eventually, the update with only dropped servers is processed and calls
1807   // fail.
1808   Status status;
1809   do {
1810     status = SendRpc(nullptr, 1000, true);
1811   } while (status.ok());
1812   EXPECT_FALSE(status.ok());
1813   EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
1814 }
1815
1816 class SingleBalancerWithClientLoadReportingTest : public GrpclbEnd2endTest {
1817  public:
1818   SingleBalancerWithClientLoadReportingTest() : GrpclbEnd2endTest(4, 1, 3) {}
1819 };
1820
1821 TEST_F(SingleBalancerWithClientLoadReportingTest, Vanilla) {
1822   SetNextResolutionAllBalancers();
1823   const size_t kNumRpcsPerAddress = 100;
1824   ScheduleResponseForBalancer(
1825       0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
1826       0);
1827   // Wait until all backends are ready.
1828   int num_ok = 0;
1829   int num_failure = 0;
1830   int num_drops = 0;
1831   std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
1832   // Send kNumRpcsPerAddress RPCs per server.
1833   CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
1834   // Each backend should have gotten 100 requests.
1835   for (size_t i = 0; i < backends_.size(); ++i) {
1836     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
1837   }
1838   balancers_[0]->service_.NotifyDoneWithServerlists();
1839   // The balancer got a single request.
1840   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1841   // and sent a single response.
1842   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1843
1844   const ClientStats client_stats = WaitForLoadReports();
1845   EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
1846             client_stats.num_calls_started);
1847   EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
1848             client_stats.num_calls_finished);
1849   EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
1850   EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + (num_ok + num_drops),
1851             client_stats.num_calls_finished_known_received);
1852   EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
1853 }
1854
1855 TEST_F(SingleBalancerWithClientLoadReportingTest, BalancerRestart) {
1856   SetNextResolutionAllBalancers();
1857   const size_t kNumBackendsFirstPass = 2;
1858   const size_t kNumBackendsSecondPass =
1859       backends_.size() - kNumBackendsFirstPass;
1860   // Balancer returns backends starting at index 1.
1861   ScheduleResponseForBalancer(
1862       0,
1863       BalancerServiceImpl::BuildResponseForBackends(
1864           GetBackendPorts(0, kNumBackendsFirstPass), {}),
1865       0);
1866   // Wait until all backends returned by the balancer are ready.
1867   int num_ok = 0;
1868   int num_failure = 0;
1869   int num_drops = 0;
1870   std::tie(num_ok, num_failure, num_drops) =
1871       WaitForAllBackends(/* num_requests_multiple_of */ 1, /* start_index */ 0,
1872                          /* stop_index */ kNumBackendsFirstPass);
1873   balancers_[0]->service_.NotifyDoneWithServerlists();
1874   ClientStats client_stats = WaitForLoadReports();
1875   EXPECT_EQ(static_cast<size_t>(num_ok), client_stats.num_calls_started);
1876   EXPECT_EQ(static_cast<size_t>(num_ok), client_stats.num_calls_finished);
1877   EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
1878   EXPECT_EQ(static_cast<size_t>(num_ok),
1879             client_stats.num_calls_finished_known_received);
1880   EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
1881   // Shut down the balancer.
1882   balancers_[0]->Shutdown();
1883   // Send 10 more requests per backend.  This will continue using the
1884   // last serverlist we received from the balancer before it was shut down.
1885   ResetBackendCounters();
1886   CheckRpcSendOk(kNumBackendsFirstPass);
1887   // Each backend should have gotten 1 request.
1888   for (size_t i = 0; i < kNumBackendsFirstPass; ++i) {
1889     EXPECT_EQ(1UL, backends_[i]->service_.request_count());
1890   }
1891   // Now restart the balancer, this time pointing to all backends.
1892   balancers_[0]->Start(server_host_);
1893   ScheduleResponseForBalancer(0,
1894                               BalancerServiceImpl::BuildResponseForBackends(
1895                                   GetBackendPorts(kNumBackendsFirstPass), {}),
1896                               0);
1897   // Wait for queries to start going to one of the new backends.
1898   // This tells us that we're now using the new serverlist.
1899   do {
1900     CheckRpcSendOk();
1901   } while (backends_[2]->service_.request_count() == 0 &&
1902            backends_[3]->service_.request_count() == 0);
1903   // Send one RPC per backend.
1904   CheckRpcSendOk(kNumBackendsSecondPass);
1905   balancers_[0]->service_.NotifyDoneWithServerlists();
1906   // Check client stats.
1907   client_stats = WaitForLoadReports();
1908   EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats.num_calls_started);
1909   EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats.num_calls_finished);
1910   EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
1911   EXPECT_EQ(kNumBackendsSecondPass + 1,
1912             client_stats.num_calls_finished_known_received);
1913   EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
1914 }
1915
1916 TEST_F(SingleBalancerWithClientLoadReportingTest, Drop) {
1917   SetNextResolutionAllBalancers();
1918   const size_t kNumRpcsPerAddress = 3;
1919   const int num_of_drop_by_rate_limiting_addresses = 2;
1920   const int num_of_drop_by_load_balancing_addresses = 1;
1921   const int num_of_drop_addresses = num_of_drop_by_rate_limiting_addresses +
1922                                     num_of_drop_by_load_balancing_addresses;
1923   const int num_total_addresses = num_backends_ + num_of_drop_addresses;
1924   ScheduleResponseForBalancer(
1925       0,
1926       BalancerServiceImpl::BuildResponseForBackends(
1927           GetBackendPorts(),
1928           {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
1929            {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
1930       0);
1931   // Wait until all backends are ready.
1932   int num_warmup_ok = 0;
1933   int num_warmup_failure = 0;
1934   int num_warmup_drops = 0;
1935   std::tie(num_warmup_ok, num_warmup_failure, num_warmup_drops) =
1936       WaitForAllBackends(num_total_addresses /* num_requests_multiple_of */);
1937   const int num_total_warmup_requests =
1938       num_warmup_ok + num_warmup_failure + num_warmup_drops;
1939   size_t num_drops = 0;
1940   for (size_t i = 0; i < kNumRpcsPerAddress * num_total_addresses; ++i) {
1941     EchoResponse response;
1942     const Status status = SendRpc(&response);
1943     if (!status.ok() &&
1944         status.error_message() == "Call dropped by load balancing policy") {
1945       ++num_drops;
1946     } else {
1947       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
1948                                << " message=" << status.error_message();
1949       EXPECT_EQ(response.message(), kRequestMessage_);
1950     }
1951   }
1952   EXPECT_EQ(kNumRpcsPerAddress * num_of_drop_addresses, num_drops);
1953   // Each backend should have gotten 100 requests.
1954   for (size_t i = 0; i < backends_.size(); ++i) {
1955     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
1956   }
1957   balancers_[0]->service_.NotifyDoneWithServerlists();
1958   // The balancer got a single request.
1959   EXPECT_EQ(1U, balancers_[0]->service_.request_count());
1960   // and sent a single response.
1961   EXPECT_EQ(1U, balancers_[0]->service_.response_count());
1962
1963   const ClientStats client_stats = WaitForLoadReports();
1964   EXPECT_EQ(
1965       kNumRpcsPerAddress * num_total_addresses + num_total_warmup_requests,
1966       client_stats.num_calls_started);
1967   EXPECT_EQ(
1968       kNumRpcsPerAddress * num_total_addresses + num_total_warmup_requests,
1969       client_stats.num_calls_finished);
1970   EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
1971   EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_warmup_ok,
1972             client_stats.num_calls_finished_known_received);
1973   // The number of warmup request is a multiple of the number of addresses.
1974   // Therefore, all addresses in the scheduled balancer response are hit the
1975   // same number of times.
1976   const int num_times_drop_addresses_hit =
1977       num_warmup_drops / num_of_drop_addresses;
1978   EXPECT_THAT(
1979       client_stats.drop_token_counts,
1980       ::testing::ElementsAre(
1981           ::testing::Pair("load_balancing",
1982                           (kNumRpcsPerAddress + num_times_drop_addresses_hit)),
1983           ::testing::Pair(
1984               "rate_limiting",
1985               (kNumRpcsPerAddress + num_times_drop_addresses_hit) * 2)));
1986 }
1987
1988 }  // namespace
1989 }  // namespace testing
1990 }  // namespace grpc
1991
1992 int main(int argc, char** argv) {
1993   // Make the backup poller poll very frequently in order to pick up
1994   // updates from all the subchannels's FDs.
1995   GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
1996   grpc_init();
1997   grpc::testing::TestEnvironment env(argc, argv);
1998   ::testing::InitGoogleTest(&argc, argv);
1999   const auto result = RUN_ALL_TESTS();
2000   grpc_shutdown();
2001   return result;
2002 }