• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <gmock/gmock.h>
18 #include <grpc/credentials.h>
19 #include <grpc/grpc.h>
20 #include <grpc/support/alloc.h>
21 #include <grpc/support/time.h>
22 #include <grpcpp/channel.h>
23 #include <grpcpp/client_context.h>
24 #include <grpcpp/create_channel.h>
25 #include <grpcpp/server.h>
26 #include <grpcpp/server_builder.h>
27 #include <gtest/gtest.h>
28 
29 #include <deque>
30 #include <memory>
31 #include <mutex>
32 #include <set>
33 #include <sstream>
34 #include <string>
35 #include <thread>
36 
37 #include "absl/cleanup/cleanup.h"
38 #include "absl/log/check.h"
39 #include "absl/log/log.h"
40 #include "absl/memory/memory.h"
41 #include "absl/strings/str_cat.h"
42 #include "absl/strings/str_format.h"
43 #include "absl/synchronization/notification.h"
44 #include "absl/types/span.h"
45 #include "src/core/client_channel/backup_poller.h"
46 #include "src/core/config/config_vars.h"
47 #include "src/core/lib/address_utils/parse_address.h"
48 #include "src/core/lib/channel/channel_args.h"
49 #include "src/core/lib/iomgr/sockaddr.h"
50 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
51 #include "src/core/load_balancing/grpclb/grpclb.h"
52 #include "src/core/load_balancing/grpclb/grpclb_balancer_addresses.h"
53 #include "src/core/resolver/endpoint_addresses.h"
54 #include "src/core/resolver/fake/fake_resolver.h"
55 #include "src/core/service_config/service_config_impl.h"
56 #include "src/core/util/crash.h"
57 #include "src/core/util/debug_location.h"
58 #include "src/core/util/env.h"
59 #include "src/core/util/ref_counted_ptr.h"
60 #include "src/core/util/sync.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/test_util/port.h"
65 #include "test/core/test_util/resolve_localhost_ip46.h"
66 #include "test/core/test_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   CHECK_EQ(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   CHECK_EQ(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::__anon4b2c065b0111::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::__anon4b2c065b0111::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     LOG(INFO) << "LB[" << this << "]: shut down";
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     LOG(INFO) << "LB[" << this << "]: BalanceLoad";
287     {
288       grpc_core::MutexLock lock(&mu_);
289       if (shutdown_) {
290         LOG(INFO) << "LB[" << this << "]: shutdown at stream start";
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       LOG(INFO) << "LB[" << this << "]: stream read returned false";
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     LOG(INFO) << "LB[" << this << "]: received initial message '"
321               << request.DebugString() << "'";
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       LOG(INFO) << "shutting down reader thread";
336       reader_shutdown.Notify();
337       LOG(INFO) << "joining reader thread";
338       reader.join();
339       LOG(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       LOG(INFO) << "LB[" << this
349                 << "]: Sending response: " << response->DebugString();
350       IncreaseResponseCount();
351       stream->Write(*response);
352     }
353     LOG(INFO) << "LB[" << this << "]: done";
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       LOG(INFO) << "LB[" << this << "]: received client load report message '"
362                 << request.DebugString() << "'";
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       LOG(INFO) << "starting " << type_ << " server on port " << port_;
453       CHECK(!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       LOG(INFO) << type_ << " server startup complete";
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       LOG(INFO) << type_ << " about to shutdown";
483       service_.Shutdown();
484       server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
485       thread_->join();
486       LOG(INFO) << type_ << " shutdown completed";
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::__anon4b2c065b0111::GrpclbEnd2endTest::WaitForBackendOptions653     WaitForBackendOptions() {}
SetTimeoutSecondsgrpc::testing::__anon4b2c065b0111::GrpclbEnd2endTest::WaitForBackendOptions654     WaitForBackendOptions& SetTimeoutSeconds(int seconds) {
655       timeout_seconds = seconds;
656       return *this;
657     }
SetNumRequestsMultipleOfgrpc::testing::__anon4b2c065b0111::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     LOG(INFO) << "Waiting for backends [" << start_index << ", " << stop_index
669               << ")";
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     LOG(INFO) << "Performed " << num_total
691               << " warm up requests (a multiple of "
692               << options.num_requests_multiple_of << ") against the backends. "
693               << num_ok << " succeeded, " << num_failure << " failed, "
694               << num_drops << " dropped.";
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       CHECK_OK(lb_uri);
711       grpc_resolved_address address;
712       CHECK(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     CHECK_OK(result.service_config);
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 one backend.  This verifies that we
954   // used pick_first instead of round_robin as the child policy.
955   bool found = false;
956   for (size_t i = 0; i < backends_.size(); ++i) {
957     if (backends_[i]->service().request_count() > 0) {
958       LOG(INFO) << "backend " << i << " saw traffic";
959       EXPECT_EQ(backends_[i]->service().request_count(), kNumRpcs)
960           << "backend " << i;
961       EXPECT_FALSE(found) << "multiple backends saw traffic";
962       found = true;
963     }
964   }
965   EXPECT_TRUE(found) << "no backends saw traffic";
966   // The balancer got a single request.
967   EXPECT_EQ(1U, balancer_->service().request_count());
968   // and sent a single response.
969   EXPECT_EQ(1U, balancer_->service().response_count());
970   // Check LB policy name for the channel.
971   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
972 }
973 
TEST_F(GrpclbEnd2endTest,SwapChildPolicy)974 TEST_F(GrpclbEnd2endTest, SwapChildPolicy) {
975   const size_t kNumBackends = 2;
976   const size_t kNumRpcs = kNumBackends * 2;
977   CreateBackends(kNumBackends);
978   SetNextResolutionDefaultBalancer(
979       "{\n"
980       "  \"loadBalancingConfig\":[\n"
981       "    { \"grpclb\":{\n"
982       "      \"childPolicy\":[\n"
983       "        { \"pick_first\":{} }\n"
984       "      ]\n"
985       "    } }\n"
986       "  ]\n"
987       "}");
988   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
989   CheckRpcSendOk(kNumRpcs, 3000 /* timeout_ms */, true /* wait_for_ready */);
990   // Check that all requests went to one backend.  This verifies that we
991   // used pick_first instead of round_robin as the child policy.
992   bool found = false;
993   for (size_t i = 0; i < backends_.size(); ++i) {
994     if (backends_[i]->service().request_count() > 0) {
995       LOG(INFO) << "backend " << i << " saw traffic";
996       EXPECT_EQ(backends_[i]->service().request_count(), kNumRpcs)
997           << "backend " << i;
998       EXPECT_FALSE(found) << "multiple backends saw traffic";
999       found = true;
1000     }
1001   }
1002   EXPECT_TRUE(found) << "no backends saw traffic";
1003   // Send new resolution that removes child policy from service config.
1004   SetNextResolutionDefaultBalancer();
1005   // We should now be using round_robin, which will send traffic to all
1006   // backends.
1007   WaitForAllBackends();
1008   // The balancer got a single request.
1009   EXPECT_EQ(1U, balancer_->service().request_count());
1010   // and sent a single response.
1011   EXPECT_EQ(1U, balancer_->service().response_count());
1012   // Check LB policy name for the channel.
1013   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
1014 }
1015 
TEST_F(GrpclbEnd2endTest,SameBackendListedMultipleTimes)1016 TEST_F(GrpclbEnd2endTest, SameBackendListedMultipleTimes) {
1017   CreateBackends(1);
1018   SetNextResolutionDefaultBalancer();
1019   // Same backend listed twice.
1020   std::vector<int> ports;
1021   ports.push_back(backends_[0]->port());
1022   ports.push_back(backends_[0]->port());
1023   const size_t kNumRpcsPerAddress = 10;
1024   SendBalancerResponse(BuildResponseForBackends(ports, {}));
1025   // We need to wait for the backend to come online.
1026   WaitForBackend(0);
1027   // Send kNumRpcsPerAddress RPCs per server.
1028   CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
1029   // Backend should have gotten 20 requests.
1030   EXPECT_EQ(kNumRpcsPerAddress * 2, backends_[0]->service().request_count());
1031   // And they should have come from a single client port, because of
1032   // subchannel sharing.
1033   EXPECT_EQ(1UL, backends_[0]->service().clients().size());
1034 }
1035 
TEST_F(GrpclbEnd2endTest,InitiallyEmptyServerlist)1036 TEST_F(GrpclbEnd2endTest, InitiallyEmptyServerlist) {
1037   CreateBackends(1);
1038   SetNextResolutionDefaultBalancer();
1039   // First response is an empty serverlist.  RPCs should fail.
1040   SendBalancerResponse(LoadBalanceResponse());
1041   CheckRpcSendFailure();
1042   // Now send a non-empty serverlist.
1043   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1044   CheckRpcSendOk(1, /*timeout_ms=*/3000, /*wait_for_ready=*/true);
1045   // The balancer got a single request.
1046   EXPECT_EQ(1U, balancer_->service().request_count());
1047   // and sent two responses.
1048   EXPECT_EQ(2U, balancer_->service().response_count());
1049 }
1050 
TEST_F(GrpclbEnd2endTest,AllServersUnreachableFailFast)1051 TEST_F(GrpclbEnd2endTest, AllServersUnreachableFailFast) {
1052   SetNextResolutionDefaultBalancer();
1053   const size_t kNumUnreachableServers = 5;
1054   std::vector<int> ports;
1055   for (size_t i = 0; i < kNumUnreachableServers; ++i) {
1056     ports.push_back(grpc_pick_unused_port_or_die());
1057   }
1058   SendBalancerResponse(BuildResponseForBackends(ports, {}));
1059   const Status status = SendRpc();
1060   // The error shouldn't be DEADLINE_EXCEEDED.
1061   EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
1062   // The balancer got a single request.
1063   EXPECT_EQ(1U, balancer_->service().request_count());
1064   // and sent a single response.
1065   EXPECT_EQ(1U, balancer_->service().response_count());
1066 }
1067 
TEST_F(GrpclbEnd2endTest,Fallback)1068 TEST_F(GrpclbEnd2endTest, Fallback) {
1069   const size_t kNumBackends = 4;
1070   const size_t kNumBackendsInResolution = kNumBackends / 2;
1071   CreateBackends(kNumBackends);
1072   // Inject resolver result that contains the fallback backends.
1073   SetNextResolution({balancer_->port()},
1074                     GetBackendPorts(0, kNumBackendsInResolution));
1075   // Balancer has not sent a serverlist, so we should use fallback.
1076   // Wait until all the fallback backends are reachable.
1077   WaitForAllBackends(0, kNumBackendsInResolution,
1078                      WaitForBackendOptions().SetTimeoutSeconds(20));
1079   // Send serverlist.
1080   SendBalancerResponse(BuildResponseForBackends(
1081       GetBackendPorts(/*start_index=*/kNumBackendsInResolution), {}));
1082   // Now we should be using the backends from the balancer.
1083   WaitForAllBackends(kNumBackendsInResolution);
1084   // The balancer got a single request.
1085   EXPECT_EQ(1U, balancer_->service().request_count());
1086   // and sent a single response.
1087   EXPECT_EQ(1U, balancer_->service().response_count());
1088 }
1089 
TEST_F(GrpclbEnd2endTest,FallbackUpdate)1090 TEST_F(GrpclbEnd2endTest, FallbackUpdate) {
1091   const size_t kNumBackends = 6;
1092   const size_t kNumBackendsInResolution = kNumBackends / 3;
1093   const size_t kNumBackendsInResolutionUpdate = kNumBackends / 3;
1094   ResetStub(/*fallback_timeout_ms=*/500);
1095   CreateBackends(kNumBackends);
1096   // Inject resolver result with fallback addresses.
1097   SetNextResolution({balancer_->port()},
1098                     GetBackendPorts(0, kNumBackendsInResolution));
1099   // Balancer has not sent a serverlist, so we should use fallback.
1100   // Wait until all the fallback backends are reachable.
1101   WaitForAllBackends(0, kNumBackendsInResolution);
1102   // Now send a resolver result with a different set of backend addresses.
1103   SetNextResolution({balancer_->port()},
1104                     GetBackendPorts(kNumBackendsInResolution,
1105                                     kNumBackendsInResolution +
1106                                         kNumBackendsInResolutionUpdate));
1107   // Wait until the new fallback backends are reachable.
1108   WaitForAllBackends(kNumBackendsInResolution,
1109                      kNumBackendsInResolution + kNumBackendsInResolutionUpdate);
1110   // Send non-empty serverlist.
1111   SendBalancerResponse(
1112       BuildResponseForBackends(GetBackendPorts(kNumBackendsInResolution +
1113                                                kNumBackendsInResolutionUpdate),
1114                                {}));
1115   // Wait for backends from balancer to be seen.
1116   WaitForAllBackends(kNumBackendsInResolution + kNumBackendsInResolutionUpdate);
1117   // The balancer got a single request.
1118   EXPECT_EQ(1U, balancer_->service().request_count());
1119   // and sent a single response.
1120   EXPECT_EQ(1U, balancer_->service().response_count());
1121 }
1122 
TEST_F(GrpclbEnd2endTest,FallbackAfterStartupLoseContactWithBalancerThenBackends)1123 TEST_F(GrpclbEnd2endTest,
1124        FallbackAfterStartupLoseContactWithBalancerThenBackends) {
1125   // First two backends are fallback, last two are pointed to by balancer.
1126   const size_t kNumBackends = 4;
1127   const size_t kNumFallbackBackends = 2;
1128   const size_t kNumBalancerBackends = kNumBackends - kNumFallbackBackends;
1129   CreateBackends(kNumBackends);
1130   SetNextResolution({balancer_->port()},
1131                     GetBackendPorts(0, kNumFallbackBackends));
1132   SendBalancerResponse(
1133       BuildResponseForBackends(GetBackendPorts(kNumFallbackBackends), {}));
1134   // Try to connect.
1135   WaitForAllBackends(kNumFallbackBackends /* start_index */);
1136   // Stop balancer.  RPCs should continue going to backends from balancer.
1137   balancer_->Shutdown();
1138   CheckRpcSendOk(100 * kNumBalancerBackends);
1139   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1140     EXPECT_EQ(100UL, backends_[i]->service().request_count());
1141   }
1142   // Stop backends from balancer.  This should put us in fallback mode.
1143   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1144     ShutdownBackend(i);
1145   }
1146   WaitForAllBackends(0, kNumFallbackBackends);
1147   // Restart the backends from the balancer.  We should *not* start
1148   // sending traffic back to them at this point.
1149   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1150     StartBackend(i);
1151   }
1152   CheckRpcSendOk(100 * kNumBalancerBackends);
1153   for (size_t i = 0; i < kNumFallbackBackends; ++i) {
1154     EXPECT_EQ(100UL, backends_[i]->service().request_count());
1155   }
1156   // Now start the balancer again.  This should cause us to exit
1157   // fallback mode.
1158   balancer_->Start();
1159   SendBalancerResponse(
1160       BuildResponseForBackends(GetBackendPorts(kNumFallbackBackends), {}));
1161   WaitForAllBackends(kNumFallbackBackends);
1162 }
1163 
TEST_F(GrpclbEnd2endTest,FallbackAfterStartupLoseContactWithBackendsThenBalancer)1164 TEST_F(GrpclbEnd2endTest,
1165        FallbackAfterStartupLoseContactWithBackendsThenBalancer) {
1166   // First two backends are fallback, last two are pointed to by balancer.
1167   const size_t kNumBackends = 4;
1168   const size_t kNumFallbackBackends = 2;
1169   const size_t kNumBalancerBackends = kNumBackends - kNumFallbackBackends;
1170   CreateBackends(kNumBackends);
1171   SetNextResolution({balancer_->port()},
1172                     GetBackendPorts(0, kNumFallbackBackends));
1173   SendBalancerResponse(
1174       BuildResponseForBackends(GetBackendPorts(kNumFallbackBackends), {}));
1175   // Try to connect.
1176   WaitForAllBackends(kNumFallbackBackends);
1177   // Stop backends from balancer.  Since we are still in contact with
1178   // the balancer at this point, RPCs should be failing.
1179   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1180     ShutdownBackend(i);
1181   }
1182   CheckRpcSendFailure();
1183   // Stop balancer.  This should put us in fallback mode.
1184   balancer_->Shutdown();
1185   WaitForAllBackends(0, kNumFallbackBackends);
1186   // Restart the backends from the balancer.  We should *not* start
1187   // sending traffic back to them at this point (although the behavior
1188   // in xds may be different).
1189   for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
1190     StartBackend(i);
1191   }
1192   CheckRpcSendOk(100 * kNumBalancerBackends);
1193   for (size_t i = 0; i < kNumFallbackBackends; ++i) {
1194     EXPECT_EQ(100UL, backends_[i]->service().request_count());
1195   }
1196   // Now start the balancer again.  This should cause us to exit
1197   // fallback mode.
1198   balancer_->Start();
1199   SendBalancerResponse(
1200       BuildResponseForBackends(GetBackendPorts(kNumFallbackBackends), {}));
1201   WaitForAllBackends(kNumFallbackBackends);
1202 }
1203 
TEST_F(GrpclbEnd2endTest,FallbackEarlyWhenBalancerChannelFails)1204 TEST_F(GrpclbEnd2endTest, FallbackEarlyWhenBalancerChannelFails) {
1205   const int kFallbackTimeoutMs = 10000;
1206   ResetStub(kFallbackTimeoutMs);
1207   CreateBackends(1);
1208   // Return an unreachable balancer and one fallback backend.
1209   SetNextResolution({grpc_pick_unused_port_or_die()}, GetBackendPorts());
1210   // Send RPC with deadline less than the fallback timeout and make sure it
1211   // succeeds.
1212   CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 3000,
1213                  /* wait_for_ready */ false);
1214 }
1215 
TEST_F(GrpclbEnd2endTest,FallbackEarlyWhenBalancerCallFails)1216 TEST_F(GrpclbEnd2endTest, FallbackEarlyWhenBalancerCallFails) {
1217   const int kFallbackTimeoutMs = 10000;
1218   ResetStub(kFallbackTimeoutMs);
1219   CreateBackends(1);
1220   // Return one balancer and one fallback backend.
1221   SetNextResolution({balancer_->port()}, GetBackendPorts());
1222   // Balancer drops call without sending a serverlist.
1223   balancer_->service().ShutdownStream();
1224   // Send RPC with deadline less than the fallback timeout and make sure it
1225   // succeeds.
1226   CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 3000,
1227                  /* wait_for_ready */ false);
1228 }
1229 
TEST_F(GrpclbEnd2endTest,FallbackControlledByBalancerBeforeFirstServerlist)1230 TEST_F(GrpclbEnd2endTest, FallbackControlledByBalancerBeforeFirstServerlist) {
1231   const int kFallbackTimeoutMs = 10000;
1232   ResetStub(kFallbackTimeoutMs);
1233   CreateBackends(1);
1234   // Return one balancer and one fallback backend.
1235   SetNextResolution({balancer_->port()}, GetBackendPorts());
1236   // Balancer explicitly tells client to fallback.
1237   LoadBalanceResponse response;
1238   response.mutable_fallback_response();
1239   SendBalancerResponse(std::move(response));
1240   // Send RPC with deadline less than the fallback timeout and make sure it
1241   // succeeds.
1242   CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 3000,
1243                  /* wait_for_ready */ false);
1244 }
1245 
TEST_F(GrpclbEnd2endTest,FallbackControlledByBalancerAfterFirstServerlist)1246 TEST_F(GrpclbEnd2endTest, FallbackControlledByBalancerAfterFirstServerlist) {
1247   CreateBackends(2);
1248   // Return one balancer and one fallback backend (backend 0).
1249   SetNextResolution({balancer_->port()}, {backends_[0]->port()});
1250   // Balancer sends a serverlist pointing to backend 1.
1251   SendBalancerResponse(BuildResponseForBackends({backends_[1]->port()}, {}));
1252   WaitForBackend(1);
1253   // Balancer tells client to fall back.
1254   LoadBalanceResponse fallback_response;
1255   fallback_response.mutable_fallback_response();
1256   SendBalancerResponse(std::move(fallback_response));
1257   WaitForBackend(0);
1258   // Balancer sends a new serverlist, so client exits fallback.
1259   SendBalancerResponse(BuildResponseForBackends({backends_[1]->port()}, {}));
1260   WaitForBackend(1);
1261 }
1262 
TEST_F(GrpclbEnd2endTest,BackendsRestart)1263 TEST_F(GrpclbEnd2endTest, BackendsRestart) {
1264   CreateBackends(2);
1265   SetNextResolutionDefaultBalancer();
1266   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1267   WaitForAllBackends();
1268   // Stop backends.  RPCs should fail.
1269   ShutdownAllBackends();
1270   CheckRpcSendFailure();
1271   // Restart backends.  RPCs should start succeeding again.
1272   StartAllBackends();
1273   CheckRpcSendOk(1 /* times */, 3000 /* timeout_ms */,
1274                  true /* wait_for_ready */);
1275   // The balancer got a single request.
1276   EXPECT_EQ(1U, balancer_->service().request_count());
1277   // and sent a single response.
1278   EXPECT_EQ(1U, balancer_->service().response_count());
1279 }
1280 
TEST_F(GrpclbEnd2endTest,ServiceNameFromLbPolicyConfig)1281 TEST_F(GrpclbEnd2endTest, ServiceNameFromLbPolicyConfig) {
1282   constexpr char kServiceConfigWithTarget[] =
1283       "{\n"
1284       "  \"loadBalancingConfig\":[\n"
1285       "    { \"grpclb\":{\n"
1286       "      \"serviceName\":\"test_service\"\n"
1287       "    }}\n"
1288       "  ]\n"
1289       "}";
1290   SetNextResolutionDefaultBalancer(kServiceConfigWithTarget);
1291   CreateBackends(1);
1292   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1293   WaitForAllBackends();
1294   EXPECT_EQ(balancer_->service().service_names().back(), "test_service");
1295 }
1296 
TEST_F(GrpclbEnd2endTest,NewBalancerAddressNotUsedIfOriginalStreamDoesNotFail)1297 TEST_F(GrpclbEnd2endTest,
1298        NewBalancerAddressNotUsedIfOriginalStreamDoesNotFail) {
1299   CreateBackends(3);
1300   // Default balancer sends backend 0.
1301   SendBalancerResponse(BuildResponseForBackends({backends_[0]->port()}, {}));
1302   // Second balancer sends backend 1.
1303   auto balancer2 = CreateAndStartBalancer();
1304   balancer2->service().SendResponse(
1305       BuildResponseForBackends({backends_[1]->port()}, {}));
1306   // Initially, the channel uses the default balancer.
1307   SetNextResolutionDefaultBalancer();
1308   WaitForBackend(0);
1309   // Send 10 requests.
1310   LOG(INFO) << "========= BEFORE FIRST BATCH ==========";
1311   CheckRpcSendOk(10);
1312   LOG(INFO) << "========= DONE WITH FIRST BATCH ==========";
1313   // All 10 requests should have gone to the first backend.
1314   EXPECT_EQ(10U, backends_[0]->service().request_count());
1315   EXPECT_EQ(0U, backends_[1]->service().request_count());
1316   EXPECT_EQ(0U, backends_[2]->service().request_count());
1317   // Balancer 0 got a single request and sent a single response.
1318   EXPECT_EQ(1U, balancer_->service().request_count());
1319   EXPECT_EQ(1U, balancer_->service().response_count());
1320   EXPECT_EQ(0U, balancer2->service().request_count());
1321   EXPECT_EQ(0U, balancer2->service().response_count());
1322   // Now tell the channel to use balancer 2.  However, the stream to the
1323   // default balancer is not terminated, so the client will continue to
1324   // use it.
1325   LOG(INFO) << "========= ABOUT TO UPDATE 1 ==========";
1326   SetNextResolution({balancer2->port()});
1327   LOG(INFO) << "========= UPDATE 1 DONE ==========";
1328   // Now the default balancer sends backend 2.
1329   SendBalancerResponse(BuildResponseForBackends({backends_[2]->port()}, {}));
1330   WaitForBackend(2);
1331 }
1332 
1333 // Send an update with the same set of LBs as the previous one in order to
1334 // verify that the LB channel inside grpclb keeps the initial connection (which
1335 // by definition is also present in the update).
TEST_F(GrpclbEnd2endTest,UpdatedBalancerAddressesWithSameAddressDoesNotBreakConnection)1336 TEST_F(GrpclbEnd2endTest,
1337        UpdatedBalancerAddressesWithSameAddressDoesNotBreakConnection) {
1338   CreateBackends(2);
1339   // Default balancer points to backend 0.
1340   SendBalancerResponse(BuildResponseForBackends({backends_[0]->port()}, {}));
1341   // Second balancer points to backend 1.
1342   auto balancer2 = CreateAndStartBalancer();
1343   balancer2->service().SendResponse(
1344       BuildResponseForBackends({backends_[1]->port()}, {}));
1345   // Send both balancer addresses.
1346   SetNextResolution({balancer_->port(), balancer2->port()});
1347   // Wait until the first backend is ready.
1348   WaitForBackend(0);
1349   // Send 10 requests.
1350   LOG(INFO) << "========= BEFORE FIRST BATCH ==========";
1351   CheckRpcSendOk(10);
1352   LOG(INFO) << "========= DONE WITH FIRST BATCH ==========";
1353   // All 10 requests should have gone to the first backend.
1354   EXPECT_EQ(10U, backends_[0]->service().request_count());
1355   EXPECT_EQ(0U, backends_[1]->service().request_count());
1356   // Balancer 0 got a single request and sent a single response.
1357   EXPECT_EQ(1U, balancer_->service().request_count());
1358   EXPECT_EQ(1U, balancer_->service().response_count());
1359   EXPECT_EQ(0U, balancer2->service().request_count());
1360   EXPECT_EQ(0U, balancer2->service().response_count());
1361   // Send another address list with the same list of balancers.
1362   LOG(INFO) << "========= ABOUT TO UPDATE 1 ==========";
1363   SetNextResolution({balancer_->port(), balancer2->port()});
1364   LOG(INFO) << "========= UPDATE 1 DONE ==========";
1365   // Shut down the balancer stream to force the client to create a new one.
1366   // The new stream should go to the default balancer, since the
1367   // underlying connection should not have been broken.
1368   LOG(INFO) << "========= SHUTTING DOWN BALANCER CALL ==========";
1369   balancer_->service().ShutdownStream();
1370   LOG(INFO) << "========= DONE SHUTTING DOWN BALANCER CALL ==========";
1371   // Wait until client has created a new balancer stream.
1372   EXPECT_TRUE(balancer_->service().WaitForNewStream(1));
1373   // Make sure there was only one client connection seen by the balancer.
1374   EXPECT_EQ(1UL, balancer_->service().clients().size());
1375 }
1376 
TEST_F(GrpclbEnd2endTest,BalancerDiesThenSwitchToNewBalancer)1377 TEST_F(GrpclbEnd2endTest, BalancerDiesThenSwitchToNewBalancer) {
1378   CreateBackends(2);
1379   // Default balancer sends backend 0.
1380   SendBalancerResponse(BuildResponseForBackends({backends_[0]->port()}, {}));
1381   // Balancer 2 sends backend 1.
1382   auto balancer2 = CreateAndStartBalancer();
1383   balancer2->service().SendResponse(
1384       BuildResponseForBackends({backends_[1]->port()}, {}));
1385   // Channel initially uses default balancer and therefore backend 0.
1386   SetNextResolutionDefaultBalancer();
1387   WaitForBackend(0);
1388   // Default balancer got a single request.
1389   EXPECT_EQ(1U, balancer_->service().request_count());
1390   EXPECT_EQ(1U, balancer_->service().response_count());
1391   EXPECT_EQ(0U, balancer2->service().request_count());
1392   EXPECT_EQ(0U, balancer2->service().response_count());
1393   // Send 10 RPCs.
1394   LOG(INFO) << "========= BEFORE FIRST BATCH ==========";
1395   CheckRpcSendOk(10);
1396   LOG(INFO) << "========= DONE WITH FIRST BATCH ==========";
1397   // All 10 requests should have gone to the first backend.
1398   EXPECT_EQ(10U, backends_[0]->service().request_count());
1399   EXPECT_EQ(0U, backends_[1]->service().request_count());
1400   // Kill default balancer.
1401   LOG(INFO) << "********** ABOUT TO KILL BALANCER *************";
1402   balancer_->Shutdown();
1403   LOG(INFO) << "********** KILLED BALANCER *************";
1404   // Channel should continue using the last backend it saw from the
1405   // balancer before the balancer died.
1406   LOG(INFO) << "========= BEFORE SECOND BATCH ==========";
1407   CheckRpcSendOk(10);
1408   LOG(INFO) << "========= DONE WITH SECOND BATCH ==========";
1409   // All 10 requests should again have gone to the first backend.
1410   EXPECT_EQ(20U, backends_[0]->service().request_count());
1411   EXPECT_EQ(0U, backends_[1]->service().request_count());
1412   // Tell channel to start using balancer 2.
1413   LOG(INFO) << "========= ABOUT TO UPDATE 1 ==========";
1414   SetNextResolution({balancer2->port()});
1415   LOG(INFO) << "========= UPDATE 1 DONE ==========";
1416   // Channel should start using backend 1.
1417   WaitForBackend(1);
1418   // This is serviced by the updated RR policy
1419   LOG(INFO) << "========= BEFORE THIRD BATCH ==========";
1420   CheckRpcSendOk(10);
1421   LOG(INFO) << "========= DONE WITH THIRD BATCH ==========";
1422   // All 10 requests should have gone to the second backend.
1423   EXPECT_EQ(0U, backends_[0]->service().request_count());
1424   EXPECT_EQ(10U, backends_[1]->service().request_count());
1425   // Both balancers should have gotten one request and sent one response.
1426   EXPECT_EQ(1U, balancer_->service().request_count());
1427   EXPECT_EQ(1U, balancer_->service().response_count());
1428   EXPECT_EQ(1U, balancer2->service().request_count());
1429   EXPECT_EQ(1U, balancer2->service().response_count());
1430 }
1431 
TEST_F(GrpclbEnd2endTest,ReresolveDeadBackendWhileInFallback)1432 TEST_F(GrpclbEnd2endTest, ReresolveDeadBackendWhileInFallback) {
1433   ResetStub(/*fallback_timeout_ms=*/500);
1434   CreateBackends(2);
1435   // The first resolution contains the addresses of a balancer that never
1436   // responds, and a fallback backend.
1437   SetNextResolution({balancer_->port()}, {backends_[0]->port()});
1438   // Start servers and send 10 RPCs per server.
1439   LOG(INFO) << "========= BEFORE FIRST BATCH ==========";
1440   CheckRpcSendOk(10);
1441   LOG(INFO) << "========= DONE WITH FIRST BATCH ==========";
1442   // All 10 requests should have gone to the fallback backend.
1443   EXPECT_EQ(10U, backends_[0]->service().request_count());
1444   // Kill backend 0.
1445   LOG(INFO) << "********** ABOUT TO KILL BACKEND 0 *************";
1446   backends_[0]->Shutdown();
1447   LOG(INFO) << "********** KILLED BACKEND 0 *************";
1448   // This should trigger re-resolution.
1449   EXPECT_TRUE(response_generator_->WaitForReresolutionRequest(
1450       absl::Seconds(5 * grpc_test_slowdown_factor())));
1451   // The re-resolution result will contain the addresses of the same balancer
1452   // and a new fallback backend.
1453   SetNextResolution({balancer_->port()}, {backends_[1]->port()});
1454   // Wait until re-resolution has been seen, as signaled by the second backend
1455   // receiving a request.
1456   WaitForBackend(1);
1457   LOG(INFO) << "========= BEFORE SECOND BATCH ==========";
1458   CheckRpcSendOk(10);
1459   LOG(INFO) << "========= DONE WITH SECOND BATCH ==========";
1460   // All 10 requests should have gone to the second backend.
1461   EXPECT_EQ(10U, backends_[1]->service().request_count());
1462   EXPECT_EQ(1U, balancer_->service().request_count());
1463   EXPECT_EQ(0U, balancer_->service().response_count());
1464 }
1465 
TEST_F(GrpclbEnd2endTest,ReresolveWhenBalancerCallFails)1466 TEST_F(GrpclbEnd2endTest, ReresolveWhenBalancerCallFails) {
1467   CreateBackends(2);
1468   // Default balancer sends backend 0.
1469   SendBalancerResponse(BuildResponseForBackends({backends_[0]->port()}, {}));
1470   // Balancer 2 sends backend 1.
1471   auto balancer2 = CreateAndStartBalancer();
1472   balancer2->service().SendResponse(
1473       BuildResponseForBackends({backends_[1]->port()}, {}));
1474   // Channel initially uses default balancer and therefore backend 0.
1475   SetNextResolutionDefaultBalancer();
1476   WaitForBackend(0);
1477   // Send 10 RPCs.
1478   LOG(INFO) << "========= BEFORE FIRST BATCH ==========";
1479   CheckRpcSendOk(10);
1480   LOG(INFO) << "========= DONE WITH FIRST BATCH ==========";
1481   // All 10 requests should have gone to the first backend.
1482   EXPECT_EQ(10U, backends_[0]->service().request_count());
1483   // Balancer 0 got a single request and sent a single request.
1484   EXPECT_EQ(1U, balancer_->service().request_count());
1485   EXPECT_EQ(1U, balancer_->service().response_count());
1486   EXPECT_EQ(0U, balancer2->service().request_count());
1487   EXPECT_EQ(0U, balancer2->service().response_count());
1488   // Kill balancer 0.
1489   LOG(INFO) << "********** ABOUT TO KILL BALANCER 0 *************";
1490   balancer_->Shutdown();
1491   LOG(INFO) << "********** KILLED BALANCER 0 *************";
1492   // This should trigger a re-resolution.
1493   EXPECT_TRUE(response_generator_->WaitForReresolutionRequest(
1494       absl::Seconds(5 * grpc_test_slowdown_factor())));
1495   LOG(INFO) << "********** SAW RE-RESOLUTION REQUEST *************";
1496   // Re-resolution result switches to balancer 2.
1497   SetNextResolution({balancer2->port()});
1498   // Client should start using backend 1.
1499   WaitForBackend(1);
1500   // Both balancers should each have handled one request and sent one response.
1501   EXPECT_EQ(1U, balancer_->service().request_count());
1502   EXPECT_EQ(1U, balancer_->service().response_count());
1503   EXPECT_EQ(1U, balancer2->service().request_count());
1504   EXPECT_EQ(1U, balancer2->service().response_count());
1505 }
1506 
TEST_F(GrpclbEnd2endTest,Drop)1507 TEST_F(GrpclbEnd2endTest, Drop) {
1508   const size_t kNumRpcsPerAddress = 100;
1509   const size_t kNumBackends = 2;
1510   const int kNumDropRateLimiting = 1;
1511   const int kNumDropLoadBalancing = 2;
1512   const int kNumDropTotal = kNumDropRateLimiting + kNumDropLoadBalancing;
1513   const int kNumAddressesTotal = kNumBackends + kNumDropTotal;
1514   SetNextResolutionDefaultBalancer();
1515   CreateBackends(kNumBackends);
1516   SendBalancerResponse(BuildResponseForBackends(
1517       GetBackendPorts(), {{"rate_limiting", kNumDropRateLimiting},
1518                           {"load_balancing", kNumDropLoadBalancing}}));
1519   // Wait until all backends are ready.
1520   WaitForAllBackends();
1521   // Send kNumRpcsPerAddress RPCs for each server and drop address.
1522   size_t num_drops = 0;
1523   for (size_t i = 0; i < kNumRpcsPerAddress * kNumAddressesTotal; ++i) {
1524     EchoResponse response;
1525     const Status status = SendRpc(&response);
1526     if (!status.ok() &&
1527         status.error_message() == "drop directed by grpclb balancer") {
1528       ++num_drops;
1529     } else {
1530       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
1531                                << " message=" << status.error_message();
1532       EXPECT_EQ(response.message(), kRequestMessage);
1533     }
1534   }
1535   EXPECT_EQ(kNumRpcsPerAddress * kNumDropTotal, num_drops);
1536   // Each backend should have gotten 100 requests.
1537   for (size_t i = 0; i < backends_.size(); ++i) {
1538     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service().request_count());
1539   }
1540   // The balancer got a single request.
1541   EXPECT_EQ(1U, balancer_->service().request_count());
1542   // and sent a single response.
1543   EXPECT_EQ(1U, balancer_->service().response_count());
1544 }
1545 
TEST_F(GrpclbEnd2endTest,DropAllFirst)1546 TEST_F(GrpclbEnd2endTest, DropAllFirst) {
1547   SetNextResolutionDefaultBalancer();
1548   // All registered addresses are marked as "drop".
1549   const int kNumDropRateLimiting = 1;
1550   const int kNumDropLoadBalancing = 1;
1551   SendBalancerResponse(BuildResponseForBackends(
1552       {}, {{"rate_limiting", kNumDropRateLimiting},
1553            {"load_balancing", kNumDropLoadBalancing}}));
1554   const Status status = SendRpc(nullptr, 3000, true);
1555   EXPECT_FALSE(status.ok());
1556   EXPECT_EQ(status.error_message(), "drop directed by grpclb balancer");
1557 }
1558 
TEST_F(GrpclbEnd2endTest,DropAll)1559 TEST_F(GrpclbEnd2endTest, DropAll) {
1560   CreateBackends(1);
1561   SetNextResolutionDefaultBalancer();
1562   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1563   CheckRpcSendOk();
1564   SendBalancerResponse(BuildResponseForBackends(
1565       {}, {{"rate_limiting", 1}, {"load_balancing", 1}}));
1566   // Eventually, the update with only dropped servers is processed, and calls
1567   // fail.
1568   Status status;
1569   do {
1570     status = SendRpc(nullptr, 3000, true);
1571   } while (status.ok());
1572   EXPECT_FALSE(status.ok());
1573   EXPECT_EQ(status.error_message(), "drop directed by grpclb balancer");
1574 }
1575 
TEST_F(GrpclbEnd2endTest,ClientLoadReporting)1576 TEST_F(GrpclbEnd2endTest, ClientLoadReporting) {
1577   const size_t kNumBackends = 3;
1578   CreateBackends(kNumBackends);
1579   balancer_->service().set_client_load_reporting_interval_seconds(3);
1580   SetNextResolutionDefaultBalancer();
1581   const size_t kNumRpcsPerAddress = 100;
1582   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1583   // Wait until all backends are ready.
1584   int num_ok = 0;
1585   int num_failure = 0;
1586   int num_drops = 0;
1587   std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
1588   // Send kNumRpcsPerAddress RPCs per server.
1589   CheckRpcSendOk(kNumRpcsPerAddress * kNumBackends);
1590   // Each backend should have gotten 100 requests.
1591   for (size_t i = 0; i < backends_.size(); ++i) {
1592     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service().request_count());
1593   }
1594   // The balancer got a single request.
1595   EXPECT_EQ(1U, balancer_->service().request_count());
1596   // and sent a single response.
1597   EXPECT_EQ(1U, balancer_->service().response_count());
1598   ClientStats client_stats;
1599   do {
1600     auto stats = WaitForLoadReports();
1601     ASSERT_TRUE(stats.has_value());
1602     client_stats += *stats;
1603   } while (client_stats.num_calls_finished !=
1604            kNumRpcsPerAddress * kNumBackends + num_ok);
1605   EXPECT_EQ(kNumRpcsPerAddress * kNumBackends + num_ok,
1606             client_stats.num_calls_started);
1607   EXPECT_EQ(kNumRpcsPerAddress * kNumBackends + num_ok,
1608             client_stats.num_calls_finished);
1609   EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
1610   EXPECT_EQ(kNumRpcsPerAddress * kNumBackends + (num_ok + num_drops),
1611             client_stats.num_calls_finished_known_received);
1612   EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
1613 }
1614 
TEST_F(GrpclbEnd2endTest,LoadReportingWithBalancerRestart)1615 TEST_F(GrpclbEnd2endTest, LoadReportingWithBalancerRestart) {
1616   const size_t kNumBackends = 4;
1617   const size_t kNumBackendsFirstPass = 2;
1618   const size_t kNumBackendsSecondPass = kNumBackends - kNumBackendsFirstPass;
1619   CreateBackends(kNumBackends);
1620   balancer_->service().set_client_load_reporting_interval_seconds(3);
1621   SetNextResolutionDefaultBalancer();
1622   // Balancer returns backends starting at index 1.
1623   SendBalancerResponse(
1624       BuildResponseForBackends(GetBackendPorts(0, kNumBackendsFirstPass), {}));
1625   // Wait until all backends returned by the balancer are ready.
1626   int num_ok = 0;
1627   int num_failure = 0;
1628   int num_drops = 0;
1629   std::tie(num_ok, num_failure, num_drops) =
1630       WaitForAllBackends(0, kNumBackendsFirstPass);
1631   auto client_stats = WaitForLoadReports();
1632   ASSERT_TRUE(client_stats.has_value());
1633   EXPECT_EQ(static_cast<size_t>(num_ok), client_stats->num_calls_started);
1634   EXPECT_EQ(static_cast<size_t>(num_ok), client_stats->num_calls_finished);
1635   EXPECT_EQ(0U, client_stats->num_calls_finished_with_client_failed_to_send);
1636   EXPECT_EQ(static_cast<size_t>(num_ok),
1637             client_stats->num_calls_finished_known_received);
1638   EXPECT_THAT(client_stats->drop_token_counts, ::testing::ElementsAre());
1639   // Shut down the balancer.
1640   balancer_->Shutdown();
1641   // Send 10 more requests per backend.  This will continue using the
1642   // last serverlist we received from the balancer before it was shut down.
1643   ResetBackendCounters();
1644   CheckRpcSendOk(kNumBackendsFirstPass);
1645   // Each backend should have gotten 1 request.
1646   for (size_t i = 0; i < kNumBackendsFirstPass; ++i) {
1647     EXPECT_EQ(1UL, backends_[i]->service().request_count());
1648   }
1649   // Now restart the balancer, this time pointing to all backends.
1650   balancer_->Start();
1651   SendBalancerResponse(
1652       BuildResponseForBackends(GetBackendPorts(kNumBackendsFirstPass), {}));
1653   // Wait for queries to start going to one of the new backends.
1654   // This tells us that we're now using the new serverlist.
1655   do {
1656     CheckRpcSendOk();
1657   } while (backends_[2]->service().request_count() == 0 &&
1658            backends_[3]->service().request_count() == 0);
1659   // Send one RPC per backend.
1660   CheckRpcSendOk(kNumBackendsSecondPass);
1661   // Check client stats.
1662   client_stats = WaitForLoadReports();
1663   ASSERT_TRUE(client_stats.has_value());
1664   EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats->num_calls_started);
1665   EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats->num_calls_finished);
1666   EXPECT_EQ(0U, client_stats->num_calls_finished_with_client_failed_to_send);
1667   EXPECT_EQ(kNumBackendsSecondPass + 1,
1668             client_stats->num_calls_finished_known_received);
1669   EXPECT_THAT(client_stats->drop_token_counts, ::testing::ElementsAre());
1670 }
1671 
TEST_F(GrpclbEnd2endTest,LoadReportingWithDrops)1672 TEST_F(GrpclbEnd2endTest, LoadReportingWithDrops) {
1673   const size_t kNumBackends = 3;
1674   const size_t kNumRpcsPerAddress = 3;
1675   const int kNumDropRateLimiting = 2;
1676   const int kNumDropLoadBalancing = 1;
1677   const int kNumDropTotal = kNumDropRateLimiting + kNumDropLoadBalancing;
1678   const int kNumAddressesTotal = kNumBackends + kNumDropTotal;
1679   CreateBackends(kNumBackends);
1680   balancer_->service().set_client_load_reporting_interval_seconds(3);
1681   SetNextResolutionDefaultBalancer();
1682   SendBalancerResponse(BuildResponseForBackends(
1683       GetBackendPorts(), {{"rate_limiting", kNumDropRateLimiting},
1684                           {"load_balancing", kNumDropLoadBalancing}}));
1685   // Wait until all backends are ready.
1686   int num_warmup_ok = 0;
1687   int num_warmup_failure = 0;
1688   int num_warmup_drops = 0;
1689   std::tie(num_warmup_ok, num_warmup_failure, num_warmup_drops) =
1690       WaitForAllBackends(
1691           0, kNumBackends,
1692           WaitForBackendOptions().SetNumRequestsMultipleOf(kNumAddressesTotal));
1693   const int num_total_warmup_requests =
1694       num_warmup_ok + num_warmup_failure + num_warmup_drops;
1695   size_t num_drops = 0;
1696   for (size_t i = 0; i < kNumRpcsPerAddress * kNumAddressesTotal; ++i) {
1697     EchoResponse response;
1698     const Status status = SendRpc(&response);
1699     if (!status.ok() &&
1700         status.error_message() == "drop directed by grpclb balancer") {
1701       ++num_drops;
1702     } else {
1703       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
1704                                << " message=" << status.error_message();
1705       EXPECT_EQ(response.message(), kRequestMessage);
1706     }
1707   }
1708   EXPECT_EQ(kNumRpcsPerAddress * kNumDropTotal, num_drops);
1709   // Each backend should have gotten 100 requests.
1710   for (size_t i = 0; i < backends_.size(); ++i) {
1711     EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service().request_count());
1712   }
1713   // The balancer got a single request.
1714   EXPECT_EQ(1U, balancer_->service().request_count());
1715   // and sent a single response.
1716   EXPECT_EQ(1U, balancer_->service().response_count());
1717   // Get load reports.
1718   auto client_stats = WaitForLoadReports();
1719   ASSERT_TRUE(client_stats.has_value());
1720   EXPECT_EQ(kNumRpcsPerAddress * kNumAddressesTotal + num_total_warmup_requests,
1721             client_stats->num_calls_started);
1722   EXPECT_EQ(kNumRpcsPerAddress * kNumAddressesTotal + num_total_warmup_requests,
1723             client_stats->num_calls_finished);
1724   EXPECT_EQ(0U, client_stats->num_calls_finished_with_client_failed_to_send);
1725   EXPECT_EQ(kNumRpcsPerAddress * kNumBackends + num_warmup_ok,
1726             client_stats->num_calls_finished_known_received);
1727   // The number of warmup request is a multiple of the number of addresses.
1728   // Therefore, all addresses in the scheduled balancer response are hit the
1729   // same number of times.
1730   const int num_times_drop_addresses_hit = num_warmup_drops / kNumDropTotal;
1731   EXPECT_THAT(
1732       client_stats->drop_token_counts,
1733       ::testing::ElementsAre(
1734           ::testing::Pair("load_balancing",
1735                           (kNumRpcsPerAddress + num_times_drop_addresses_hit)),
1736           ::testing::Pair(
1737               "rate_limiting",
1738               (kNumRpcsPerAddress + num_times_drop_addresses_hit) * 2)));
1739 }
1740 
TEST_F(GrpclbEnd2endTest,SecureNaming)1741 TEST_F(GrpclbEnd2endTest, SecureNaming) {
1742   CreateBackends(1);
1743   ResetStub(/*fallback_timeout_ms=*/0,
1744             absl::StrCat(kApplicationTargetName, ";lb"));
1745   SetNextResolutionFromEndpoints(
1746       CreateAddressListFromPorts({balancer_->port()}, "lb"));
1747   SendBalancerResponse(BuildResponseForBackends(GetBackendPorts(), {}));
1748   // We need to wait for all backends to come online.
1749   WaitForAllBackends();
1750   // The balancer got a single request.
1751   EXPECT_EQ(1U, balancer_->service().request_count());
1752   // and sent a single response.
1753   EXPECT_EQ(1U, balancer_->service().response_count());
1754   // Check LB policy name for the channel.
1755   EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
1756 }
1757 
1758 // This death test is kept separate from the rest to ensure that it's run before
1759 // any others. See https://github.com/grpc/grpc/pull/32269 for details.
1760 using SingleBalancerDeathTest = GrpclbEnd2endTest;
1761 
TEST_F(SingleBalancerDeathTest,SecureNaming)1762 TEST_F(SingleBalancerDeathTest, SecureNaming) {
1763   GTEST_FLAG_SET(death_test_style, "threadsafe");
1764   // Make sure that we blow up (via abort() from the security connector) when
1765   // the name from the balancer doesn't match expectations.
1766   ASSERT_DEATH_IF_SUPPORTED(
1767       {
1768         ResetStub(/*fallback_timeout_ms=*/0,
1769                   absl::StrCat(kApplicationTargetName, ";lb"));
1770         SetNextResolutionFromEndpoints(
1771             CreateAddressListFromPorts({balancer_->port()}, "woops"));
1772         channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(1));
1773       },
1774       "");
1775 }
1776 
1777 }  // namespace
1778 }  // namespace testing
1779 }  // namespace grpc
1780 
main(int argc,char ** argv)1781 int main(int argc, char** argv) {
1782   grpc::testing::TestEnvironment env(&argc, argv);
1783   ::testing::InitGoogleTest(&argc, argv);
1784   const auto result = RUN_ALL_TESTS();
1785   return result;
1786 }
1787