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 <deque>
20 #include <memory>
21 #include <mutex>
22 #include <numeric>
23 #include <set>
24 #include <sstream>
25 #include <string>
26 #include <thread>
27 #include <vector>
28 
29 #include <grpc/grpc.h>
30 #include <grpc/support/alloc.h>
31 #include <grpc/support/log.h>
32 #include <grpc/support/string_util.h>
33 #include <grpc/support/time.h>
34 #include <grpcpp/channel.h>
35 #include <grpcpp/client_context.h>
36 #include <grpcpp/create_channel.h>
37 #include <grpcpp/server.h>
38 #include <grpcpp/server_builder.h>
39 
40 #include "absl/strings/str_cat.h"
41 #include "absl/types/optional.h"
42 
43 #include "src/core/ext/filters/client_channel/backup_poller.h"
44 #include "src/core/ext/filters/client_channel/parse_address.h"
45 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
46 #include "src/core/ext/filters/client_channel/server_address.h"
47 #include "src/core/ext/filters/client_channel/xds/xds_api.h"
48 #include "src/core/lib/gpr/env.h"
49 #include "src/core/lib/gpr/tmpfile.h"
50 #include "src/core/lib/gprpp/map.h"
51 #include "src/core/lib/gprpp/ref_counted_ptr.h"
52 #include "src/core/lib/gprpp/sync.h"
53 #include "src/core/lib/iomgr/sockaddr.h"
54 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
55 #include "src/cpp/client/secure_credentials.h"
56 #include "src/cpp/server/secure_server_credentials.h"
57 
58 #include "test/core/util/port.h"
59 #include "test/core/util/test_config.h"
60 #include "test/cpp/end2end/test_service_impl.h"
61 
62 #include "src/proto/grpc/testing/echo.grpc.pb.h"
63 #include "src/proto/grpc/testing/xds/ads_for_test.grpc.pb.h"
64 #include "src/proto/grpc/testing/xds/cds_for_test.grpc.pb.h"
65 #include "src/proto/grpc/testing/xds/eds_for_test.grpc.pb.h"
66 #include "src/proto/grpc/testing/xds/lds_rds_for_test.grpc.pb.h"
67 #include "src/proto/grpc/testing/xds/lrs_for_test.grpc.pb.h"
68 
69 #include <gmock/gmock.h>
70 #include <gtest/gtest.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 xds 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 xds 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 namespace grpc {
90 namespace testing {
91 namespace {
92 
93 using std::chrono::system_clock;
94 
95 using ::envoy::api::v2::Cluster;
96 using ::envoy::api::v2::ClusterLoadAssignment;
97 using ::envoy::api::v2::DiscoveryRequest;
98 using ::envoy::api::v2::DiscoveryResponse;
99 using ::envoy::api::v2::FractionalPercent;
100 using ::envoy::api::v2::HttpConnectionManager;
101 using ::envoy::api::v2::Listener;
102 using ::envoy::api::v2::RouteConfiguration;
103 using ::envoy::service::discovery::v2::AggregatedDiscoveryService;
104 using ::envoy::service::load_stats::v2::ClusterStats;
105 using ::envoy::service::load_stats::v2::LoadReportingService;
106 using ::envoy::service::load_stats::v2::LoadStatsRequest;
107 using ::envoy::service::load_stats::v2::LoadStatsResponse;
108 using ::envoy::service::load_stats::v2::UpstreamLocalityStats;
109 
110 constexpr char kLdsTypeUrl[] = "type.googleapis.com/envoy.api.v2.Listener";
111 constexpr char kRdsTypeUrl[] =
112     "type.googleapis.com/envoy.api.v2.RouteConfiguration";
113 constexpr char kCdsTypeUrl[] = "type.googleapis.com/envoy.api.v2.Cluster";
114 constexpr char kEdsTypeUrl[] =
115     "type.googleapis.com/envoy.api.v2.ClusterLoadAssignment";
116 constexpr char kDefaultLocalityRegion[] = "xds_default_locality_region";
117 constexpr char kDefaultLocalityZone[] = "xds_default_locality_zone";
118 constexpr char kLbDropType[] = "lb";
119 constexpr char kThrottleDropType[] = "throttle";
120 constexpr char kDefaultResourceName[] = "application_target_name";
121 constexpr int kDefaultLocalityWeight = 3;
122 constexpr int kDefaultLocalityPriority = 0;
123 
124 constexpr char kBootstrapFile[] =
125     "{\n"
126     "  \"xds_servers\": [\n"
127     "    {\n"
128     "      \"server_uri\": \"fake:///lb\",\n"
129     "      \"channel_creds\": [\n"
130     "        {\n"
131     "          \"type\": \"fake\"\n"
132     "        }\n"
133     "      ]\n"
134     "    }\n"
135     "  ],\n"
136     "  \"node\": {\n"
137     "    \"id\": \"xds_end2end_test\",\n"
138     "    \"cluster\": \"test\",\n"
139     "    \"metadata\": {\n"
140     "      \"foo\": \"bar\"\n"
141     "    },\n"
142     "    \"locality\": {\n"
143     "      \"region\": \"corp\",\n"
144     "      \"zone\": \"svl\",\n"
145     "      \"subzone\": \"mp3\"\n"
146     "    }\n"
147     "  }\n"
148     "}\n";
149 
150 constexpr char kBootstrapFileBad[] =
151     "{\n"
152     "  \"xds_servers\": [\n"
153     "    {\n"
154     "      \"server_uri\": \"fake:///wrong_lb\",\n"
155     "      \"channel_creds\": [\n"
156     "        {\n"
157     "          \"type\": \"fake\"\n"
158     "        }\n"
159     "      ]\n"
160     "    }\n"
161     "  ],\n"
162     "  \"node\": {\n"
163     "  }\n"
164     "}\n";
165 
166 char* g_bootstrap_file;
167 char* g_bootstrap_file_bad;
168 
WriteBootstrapFiles()169 void WriteBootstrapFiles() {
170   char* bootstrap_file;
171   FILE* out = gpr_tmpfile("xds_bootstrap", &bootstrap_file);
172   fputs(kBootstrapFile, out);
173   fclose(out);
174   g_bootstrap_file = bootstrap_file;
175   out = gpr_tmpfile("xds_bootstrap_bad", &bootstrap_file);
176   fputs(kBootstrapFileBad, out);
177   fclose(out);
178   g_bootstrap_file_bad = bootstrap_file;
179 }
180 
181 // Helper class to minimize the number of unique ports we use for this test.
182 class PortSaver {
183  public:
GetPort()184   int GetPort() {
185     if (idx_ >= ports_.size()) {
186       ports_.push_back(grpc_pick_unused_port_or_die());
187     }
188     return ports_[idx_++];
189   }
190 
Reset()191   void Reset() { idx_ = 0; }
192 
193  private:
194   std::vector<int> ports_;
195   size_t idx_ = 0;
196 };
197 
198 PortSaver* g_port_saver = nullptr;
199 
200 template <typename ServiceType>
201 class CountedService : public ServiceType {
202  public:
request_count()203   size_t request_count() {
204     grpc_core::MutexLock lock(&mu_);
205     return request_count_;
206   }
207 
response_count()208   size_t response_count() {
209     grpc_core::MutexLock lock(&mu_);
210     return response_count_;
211   }
212 
IncreaseResponseCount()213   void IncreaseResponseCount() {
214     grpc_core::MutexLock lock(&mu_);
215     ++response_count_;
216   }
IncreaseRequestCount()217   void IncreaseRequestCount() {
218     grpc_core::MutexLock lock(&mu_);
219     ++request_count_;
220   }
221 
ResetCounters()222   void ResetCounters() {
223     grpc_core::MutexLock lock(&mu_);
224     request_count_ = 0;
225     response_count_ = 0;
226   }
227 
228  private:
229   grpc_core::Mutex mu_;
230   size_t request_count_ = 0;
231   size_t response_count_ = 0;
232 };
233 
234 using LrsService = CountedService<LoadReportingService::Service>;
235 
236 const char g_kCallCredsMdKey[] = "Balancer should not ...";
237 const char g_kCallCredsMdValue[] = "... receive me";
238 
239 template <typename RpcService>
240 class BackendServiceImpl
241     : public CountedService<TestMultipleServiceImpl<RpcService>> {
242  public:
BackendServiceImpl()243   BackendServiceImpl() {}
244 
Echo(ServerContext * context,const EchoRequest * request,EchoResponse * response)245   Status Echo(ServerContext* context, const EchoRequest* request,
246               EchoResponse* response) override {
247     // Backend should receive the call credentials metadata.
248     auto call_credentials_entry =
249         context->client_metadata().find(g_kCallCredsMdKey);
250     EXPECT_NE(call_credentials_entry, context->client_metadata().end());
251     if (call_credentials_entry != context->client_metadata().end()) {
252       EXPECT_EQ(call_credentials_entry->second, g_kCallCredsMdValue);
253     }
254     CountedService<TestMultipleServiceImpl<RpcService>>::IncreaseRequestCount();
255     const auto status =
256         TestMultipleServiceImpl<RpcService>::Echo(context, request, response);
257     CountedService<
258         TestMultipleServiceImpl<RpcService>>::IncreaseResponseCount();
259     AddClient(context->peer());
260     return status;
261   }
262 
Echo1(ServerContext * context,const EchoRequest * request,EchoResponse * response)263   Status Echo1(ServerContext* context, const EchoRequest* request,
264                EchoResponse* response) override {
265     return Echo(context, request, response);
266   }
267 
Echo2(ServerContext * context,const EchoRequest * request,EchoResponse * response)268   Status Echo2(ServerContext* context, const EchoRequest* request,
269                EchoResponse* response) override {
270     return Echo(context, request, response);
271   }
272 
Start()273   void Start() {}
Shutdown()274   void Shutdown() {}
275 
clients()276   std::set<grpc::string> clients() {
277     grpc_core::MutexLock lock(&clients_mu_);
278     return clients_;
279   }
280 
281  private:
AddClient(const grpc::string & client)282   void AddClient(const grpc::string& client) {
283     grpc_core::MutexLock lock(&clients_mu_);
284     clients_.insert(client);
285   }
286 
287   grpc_core::Mutex clients_mu_;
288   std::set<grpc::string> clients_;
289 };
290 
291 class ClientStats {
292  public:
293   struct LocalityStats {
294     // Converts from proto message class.
LocalityStatsgrpc::testing::__anon74ea63330111::ClientStats::LocalityStats295     LocalityStats(const UpstreamLocalityStats& upstream_locality_stats)
296         : total_successful_requests(
297               upstream_locality_stats.total_successful_requests()),
298           total_requests_in_progress(
299               upstream_locality_stats.total_requests_in_progress()),
300           total_error_requests(upstream_locality_stats.total_error_requests()),
301           total_issued_requests(
302               upstream_locality_stats.total_issued_requests()) {}
303 
304     uint64_t total_successful_requests;
305     uint64_t total_requests_in_progress;
306     uint64_t total_error_requests;
307     uint64_t total_issued_requests;
308   };
309 
310   // Converts from proto message class.
ClientStats(const ClusterStats & cluster_stats)311   explicit ClientStats(const ClusterStats& cluster_stats)
312       : cluster_name_(cluster_stats.cluster_name()),
313         total_dropped_requests_(cluster_stats.total_dropped_requests()) {
314     for (const auto& input_locality_stats :
315          cluster_stats.upstream_locality_stats()) {
316       locality_stats_.emplace(input_locality_stats.locality().sub_zone(),
317                               LocalityStats(input_locality_stats));
318     }
319     for (const auto& input_dropped_requests :
320          cluster_stats.dropped_requests()) {
321       dropped_requests_.emplace(input_dropped_requests.category(),
322                                 input_dropped_requests.dropped_count());
323     }
324   }
325 
cluster_name() const326   const std::string& cluster_name() const { return cluster_name_; }
327 
locality_stats() const328   const std::map<grpc::string, LocalityStats>& locality_stats() const {
329     return locality_stats_;
330   }
total_successful_requests() const331   uint64_t total_successful_requests() const {
332     uint64_t sum = 0;
333     for (auto& p : locality_stats_) {
334       sum += p.second.total_successful_requests;
335     }
336     return sum;
337   }
total_requests_in_progress() const338   uint64_t total_requests_in_progress() const {
339     uint64_t sum = 0;
340     for (auto& p : locality_stats_) {
341       sum += p.second.total_requests_in_progress;
342     }
343     return sum;
344   }
total_error_requests() const345   uint64_t total_error_requests() const {
346     uint64_t sum = 0;
347     for (auto& p : locality_stats_) {
348       sum += p.second.total_error_requests;
349     }
350     return sum;
351   }
total_issued_requests() const352   uint64_t total_issued_requests() const {
353     uint64_t sum = 0;
354     for (auto& p : locality_stats_) {
355       sum += p.second.total_issued_requests;
356     }
357     return sum;
358   }
359 
total_dropped_requests() const360   uint64_t total_dropped_requests() const { return total_dropped_requests_; }
361 
dropped_requests(const grpc::string & category) const362   uint64_t dropped_requests(const grpc::string& category) const {
363     auto iter = dropped_requests_.find(category);
364     GPR_ASSERT(iter != dropped_requests_.end());
365     return iter->second;
366   }
367 
368  private:
369   std::string cluster_name_;
370   std::map<grpc::string, LocalityStats> locality_stats_;
371   uint64_t total_dropped_requests_;
372   std::map<grpc::string, uint64_t> dropped_requests_;
373 };
374 
375 class AdsServiceImpl : public AggregatedDiscoveryService::Service,
376                        public std::enable_shared_from_this<AdsServiceImpl> {
377  public:
378   struct ResponseState {
379     enum State { NOT_SENT, SENT, ACKED, NACKED };
380     State state = NOT_SENT;
381     std::string error_message;
382   };
383 
384   struct EdsResourceArgs {
385     struct Locality {
Localitygrpc::testing::__anon74ea63330111::AdsServiceImpl::EdsResourceArgs::Locality386       Locality(const grpc::string& sub_zone, std::vector<int> ports,
387                int lb_weight = kDefaultLocalityWeight,
388                int priority = kDefaultLocalityPriority,
389                std::vector<envoy::api::v2::HealthStatus> health_statuses = {})
390           : sub_zone(std::move(sub_zone)),
391             ports(std::move(ports)),
392             lb_weight(lb_weight),
393             priority(priority),
394             health_statuses(std::move(health_statuses)) {}
395 
396       const grpc::string sub_zone;
397       std::vector<int> ports;
398       int lb_weight;
399       int priority;
400       std::vector<envoy::api::v2::HealthStatus> health_statuses;
401     };
402 
403     EdsResourceArgs() = default;
EdsResourceArgsgrpc::testing::__anon74ea63330111::AdsServiceImpl::EdsResourceArgs404     explicit EdsResourceArgs(std::vector<Locality> locality_list)
405         : locality_list(std::move(locality_list)) {}
406 
407     std::vector<Locality> locality_list;
408     std::map<grpc::string, uint32_t> drop_categories;
409     FractionalPercent::DenominatorType drop_denominator =
410         FractionalPercent::MILLION;
411   };
412 
413   using Stream = ServerReaderWriter<DiscoveryResponse, DiscoveryRequest>;
414 
AdsServiceImpl(bool enable_load_reporting)415   AdsServiceImpl(bool enable_load_reporting) {
416     // Construct RDS response data.
417     default_route_config_.set_name(kDefaultResourceName);
418     auto* virtual_host = default_route_config_.add_virtual_hosts();
419     virtual_host->add_domains("*");
420     auto* route = virtual_host->add_routes();
421     route->mutable_match()->set_prefix("");
422     route->mutable_route()->set_cluster(kDefaultResourceName);
423     SetRdsResource(default_route_config_);
424     // Construct LDS response data (with inlined RDS result).
425     default_listener_ = BuildListener(default_route_config_);
426     SetLdsResource(default_listener_);
427     // Construct CDS response data.
428     default_cluster_.set_name(kDefaultResourceName);
429     default_cluster_.set_type(envoy::api::v2::Cluster::EDS);
430     default_cluster_.mutable_eds_cluster_config()
431         ->mutable_eds_config()
432         ->mutable_ads();
433     default_cluster_.set_lb_policy(envoy::api::v2::Cluster::ROUND_ROBIN);
434     if (enable_load_reporting) {
435       default_cluster_.mutable_lrs_server()->mutable_self();
436     }
437     SetCdsResource(default_cluster_);
438   }
439 
StreamAggregatedResources(ServerContext * context,Stream * stream)440   Status StreamAggregatedResources(ServerContext* context,
441                                    Stream* stream) override {
442     gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources starts", this);
443     // Resources (type/name pairs) that have changed since the client
444     // subscribed to them.
445     UpdateQueue update_queue;
446     // Resources that the client will be subscribed to keyed by resource type
447     // url.
448     SubscriptionMap subscription_map;
449     [&]() {
450       {
451         grpc_core::MutexLock lock(&ads_mu_);
452         if (ads_done_) return;
453       }
454       // Balancer shouldn't receive the call credentials metadata.
455       EXPECT_EQ(context->client_metadata().find(g_kCallCredsMdKey),
456                 context->client_metadata().end());
457       // Current Version map keyed by resource type url.
458       std::map<std::string, int> resource_type_version;
459       // Creating blocking thread to read from stream.
460       std::deque<DiscoveryRequest> requests;
461       bool stream_closed = false;
462       // Take a reference of the AdsServiceImpl object, reference will go
463       // out of scope after the reader thread is joined.
464       std::shared_ptr<AdsServiceImpl> ads_service_impl = shared_from_this();
465       std::thread reader(std::bind(&AdsServiceImpl::BlockingRead, this, stream,
466                                    &requests, &stream_closed));
467       // Main loop to look for requests and updates.
468       while (true) {
469         // Look for new requests and and decide what to handle.
470         absl::optional<DiscoveryResponse> response;
471         // Boolean to keep track if the loop received any work to do: a request
472         // or an update; regardless whether a response was actually sent out.
473         bool did_work = false;
474         {
475           grpc_core::MutexLock lock(&ads_mu_);
476           if (stream_closed) break;
477           if (!requests.empty()) {
478             DiscoveryRequest request = std::move(requests.front());
479             requests.pop_front();
480             did_work = true;
481             gpr_log(GPR_INFO,
482                     "ADS[%p]: Received request for type %s with content %s",
483                     this, request.type_url().c_str(),
484                     request.DebugString().c_str());
485             // Identify ACK and NACK by looking for version information and
486             // comparing it to nonce (this server ensures they are always set to
487             // the same in a response.)
488             if (!request.response_nonce().empty()) {
489               resource_type_response_state_[request.type_url()].state =
490                   (!request.version_info().empty() &&
491                    request.version_info() == request.response_nonce())
492                       ? ResponseState::ACKED
493                       : ResponseState::NACKED;
494             }
495             if (request.has_error_detail()) {
496               resource_type_response_state_[request.type_url()].error_message =
497                   request.error_detail().message();
498             }
499             // As long as the test did not tell us to ignore this type of
500             // request, we will loop through all resources to:
501             // 1. subscribe if necessary
502             // 2. update if necessary
503             // 3. unsubscribe if necessary
504             if (resource_types_to_ignore_.find(request.type_url()) ==
505                 resource_types_to_ignore_.end()) {
506               auto& subscription_name_map =
507                   subscription_map[request.type_url()];
508               auto& resource_name_map = resource_map_[request.type_url()];
509               std::set<std::string> resources_in_current_request;
510               std::set<std::string> resources_added_to_response;
511               for (const std::string& resource_name :
512                    request.resource_names()) {
513                 resources_in_current_request.emplace(resource_name);
514                 auto& subscription_state = subscription_name_map[resource_name];
515                 auto& resource_state = resource_name_map[resource_name];
516                 MaybeSubscribe(request.type_url(), resource_name,
517                                &subscription_state, &resource_state,
518                                &update_queue);
519                 if (ClientNeedsResourceUpdate(resource_state,
520                                               &subscription_state)) {
521                   gpr_log(
522                       GPR_INFO,
523                       "ADS[%p]: Sending update for type=%s name=%s version=%d",
524                       this, request.type_url().c_str(), resource_name.c_str(),
525                       resource_state.version);
526                   resources_added_to_response.emplace(resource_name);
527                   if (!response.has_value()) response.emplace();
528                   if (resource_state.resource.has_value()) {
529                     response->add_resources()->CopyFrom(
530                         resource_state.resource.value());
531                   }
532                 }
533               }
534               // Process unsubscriptions for any resource no longer
535               // present in the request's resource list.
536               ProcessUnsubscriptions(
537                   request.type_url(), resources_in_current_request,
538                   &subscription_name_map, &resource_name_map);
539               // Send response if needed.
540               if (!resources_added_to_response.empty()) {
541                 CompleteBuildingDiscoveryResponse(
542                     request.type_url(),
543                     ++resource_type_version[request.type_url()],
544                     subscription_name_map, resources_added_to_response,
545                     &response.value());
546               }
547             }
548           }
549         }
550         if (response.has_value()) {
551           gpr_log(GPR_INFO, "ADS[%p]: Sending response: %s", this,
552                   response->DebugString().c_str());
553           stream->Write(response.value());
554         }
555         response.reset();
556         // Look for updates and decide what to handle.
557         {
558           grpc_core::MutexLock lock(&ads_mu_);
559           if (!update_queue.empty()) {
560             const std::string resource_type =
561                 std::move(update_queue.front().first);
562             const std::string resource_name =
563                 std::move(update_queue.front().second);
564             update_queue.pop_front();
565             did_work = true;
566             gpr_log(GPR_INFO, "ADS[%p]: Received update for type=%s name=%s",
567                     this, resource_type.c_str(), resource_name.c_str());
568             auto& subscription_name_map = subscription_map[resource_type];
569             auto& resource_name_map = resource_map_[resource_type];
570             auto it = subscription_name_map.find(resource_name);
571             if (it != subscription_name_map.end()) {
572               SubscriptionState& subscription_state = it->second;
573               ResourceState& resource_state = resource_name_map[resource_name];
574               if (ClientNeedsResourceUpdate(resource_state,
575                                             &subscription_state)) {
576                 gpr_log(
577                     GPR_INFO,
578                     "ADS[%p]: Sending update for type=%s name=%s version=%d",
579                     this, resource_type.c_str(), resource_name.c_str(),
580                     resource_state.version);
581                 response.emplace();
582                 if (resource_state.resource.has_value()) {
583                   response->add_resources()->CopyFrom(
584                       resource_state.resource.value());
585                 }
586                 CompleteBuildingDiscoveryResponse(
587                     resource_type, ++resource_type_version[resource_type],
588                     subscription_name_map, {resource_name}, &response.value());
589               }
590             }
591           }
592         }
593         if (response.has_value()) {
594           gpr_log(GPR_INFO, "ADS[%p]: Sending update response: %s", this,
595                   response->DebugString().c_str());
596           stream->Write(response.value());
597         }
598         // If we didn't find anything to do, delay before the next loop
599         // iteration; otherwise, check whether we should exit and then
600         // immediately continue.
601         gpr_timespec deadline =
602             grpc_timeout_milliseconds_to_deadline(did_work ? 0 : 10);
603         {
604           grpc_core::MutexLock lock(&ads_mu_);
605           if (!ads_cond_.WaitUntil(&ads_mu_, [this] { return ads_done_; },
606                                    deadline))
607             break;
608         }
609       }
610       reader.join();
611     }();
612     // Clean up any subscriptions that were still active when the call finished.
613     {
614       grpc_core::MutexLock lock(&ads_mu_);
615       for (auto& p : subscription_map) {
616         const std::string& type_url = p.first;
617         SubscriptionNameMap& subscription_name_map = p.second;
618         for (auto& q : subscription_name_map) {
619           const std::string& resource_name = q.first;
620           SubscriptionState& subscription_state = q.second;
621           ResourceState& resource_state =
622               resource_map_[type_url][resource_name];
623           resource_state.subscriptions.erase(&subscription_state);
624         }
625       }
626     }
627     gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources done", this);
628     return Status::OK;
629   }
630 
default_listener() const631   Listener default_listener() const { return default_listener_; }
default_route_config() const632   RouteConfiguration default_route_config() const {
633     return default_route_config_;
634   }
default_cluster() const635   Cluster default_cluster() const { return default_cluster_; }
636 
lds_response_state()637   ResponseState lds_response_state() {
638     grpc_core::MutexLock lock(&ads_mu_);
639     return resource_type_response_state_[kLdsTypeUrl];
640   }
641 
rds_response_state()642   ResponseState rds_response_state() {
643     grpc_core::MutexLock lock(&ads_mu_);
644     return resource_type_response_state_[kRdsTypeUrl];
645   }
646 
cds_response_state()647   ResponseState cds_response_state() {
648     grpc_core::MutexLock lock(&ads_mu_);
649     return resource_type_response_state_[kCdsTypeUrl];
650   }
651 
eds_response_state()652   ResponseState eds_response_state() {
653     grpc_core::MutexLock lock(&ads_mu_);
654     return resource_type_response_state_[kEdsTypeUrl];
655   }
656 
SetResourceIgnore(const std::string & type_url)657   void SetResourceIgnore(const std::string& type_url) {
658     grpc_core::MutexLock lock(&ads_mu_);
659     resource_types_to_ignore_.emplace(type_url);
660   }
661 
UnsetResource(const std::string & type_url,const std::string & name)662   void UnsetResource(const std::string& type_url, const std::string& name) {
663     grpc_core::MutexLock lock(&ads_mu_);
664     ResourceState& state = resource_map_[type_url][name];
665     ++state.version;
666     state.resource.reset();
667     gpr_log(GPR_INFO, "ADS[%p]: Unsetting %s resource %s to version %u", this,
668             type_url.c_str(), name.c_str(), state.version);
669     for (SubscriptionState* subscription : state.subscriptions) {
670       subscription->update_queue->emplace_back(type_url, name);
671     }
672   }
673 
SetResource(google::protobuf::Any resource,const std::string & type_url,const std::string & name)674   void SetResource(google::protobuf::Any resource, const std::string& type_url,
675                    const std::string& name) {
676     grpc_core::MutexLock lock(&ads_mu_);
677     ResourceState& state = resource_map_[type_url][name];
678     ++state.version;
679     state.resource = std::move(resource);
680     gpr_log(GPR_INFO, "ADS[%p]: Updating %s resource %s to version %u", this,
681             type_url.c_str(), name.c_str(), state.version);
682     for (SubscriptionState* subscription : state.subscriptions) {
683       subscription->update_queue->emplace_back(type_url, name);
684     }
685   }
686 
SetLdsResource(const Listener & listener)687   void SetLdsResource(const Listener& listener) {
688     google::protobuf::Any resource;
689     resource.PackFrom(listener);
690     SetResource(std::move(resource), kLdsTypeUrl, listener.name());
691   }
692 
SetRdsResource(const RouteConfiguration & route)693   void SetRdsResource(const RouteConfiguration& route) {
694     google::protobuf::Any resource;
695     resource.PackFrom(route);
696     SetResource(std::move(resource), kRdsTypeUrl, route.name());
697   }
698 
SetCdsResource(const Cluster & cluster)699   void SetCdsResource(const Cluster& cluster) {
700     google::protobuf::Any resource;
701     resource.PackFrom(cluster);
702     SetResource(std::move(resource), kCdsTypeUrl, cluster.name());
703   }
704 
SetEdsResource(const ClusterLoadAssignment & assignment)705   void SetEdsResource(const ClusterLoadAssignment& assignment) {
706     google::protobuf::Any resource;
707     resource.PackFrom(assignment);
708     SetResource(std::move(resource), kEdsTypeUrl, assignment.cluster_name());
709   }
710 
SetLdsToUseDynamicRds()711   void SetLdsToUseDynamicRds() {
712     auto listener = default_listener_;
713     HttpConnectionManager http_connection_manager;
714     auto* rds = http_connection_manager.mutable_rds();
715     rds->set_route_config_name(kDefaultResourceName);
716     rds->mutable_config_source()->mutable_ads();
717     listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
718         http_connection_manager);
719     SetLdsResource(listener);
720   }
721 
BuildListener(const RouteConfiguration & route_config)722   static Listener BuildListener(const RouteConfiguration& route_config) {
723     HttpConnectionManager http_connection_manager;
724     *(http_connection_manager.mutable_route_config()) = route_config;
725     Listener listener;
726     listener.set_name(kDefaultResourceName);
727     listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
728         http_connection_manager);
729     return listener;
730   }
731 
Start()732   void Start() {
733     grpc_core::MutexLock lock(&ads_mu_);
734     ads_done_ = false;
735   }
736 
Shutdown()737   void Shutdown() {
738     {
739       grpc_core::MutexLock lock(&ads_mu_);
740       NotifyDoneWithAdsCallLocked();
741       resource_type_response_state_.clear();
742     }
743     gpr_log(GPR_INFO, "ADS[%p]: shut down", this);
744   }
745 
BuildEdsResource(const EdsResourceArgs & args,const char * cluster_name=kDefaultResourceName)746   static ClusterLoadAssignment BuildEdsResource(
747       const EdsResourceArgs& args,
748       const char* cluster_name = kDefaultResourceName) {
749     ClusterLoadAssignment assignment;
750     assignment.set_cluster_name(cluster_name);
751     for (const auto& locality : args.locality_list) {
752       auto* endpoints = assignment.add_endpoints();
753       endpoints->mutable_load_balancing_weight()->set_value(locality.lb_weight);
754       endpoints->set_priority(locality.priority);
755       endpoints->mutable_locality()->set_region(kDefaultLocalityRegion);
756       endpoints->mutable_locality()->set_zone(kDefaultLocalityZone);
757       endpoints->mutable_locality()->set_sub_zone(locality.sub_zone);
758       for (size_t i = 0; i < locality.ports.size(); ++i) {
759         const int& port = locality.ports[i];
760         auto* lb_endpoints = endpoints->add_lb_endpoints();
761         if (locality.health_statuses.size() > i &&
762             locality.health_statuses[i] !=
763                 envoy::api::v2::HealthStatus::UNKNOWN) {
764           lb_endpoints->set_health_status(locality.health_statuses[i]);
765         }
766         auto* endpoint = lb_endpoints->mutable_endpoint();
767         auto* address = endpoint->mutable_address();
768         auto* socket_address = address->mutable_socket_address();
769         socket_address->set_address("127.0.0.1");
770         socket_address->set_port_value(port);
771       }
772     }
773     if (!args.drop_categories.empty()) {
774       auto* policy = assignment.mutable_policy();
775       for (const auto& p : args.drop_categories) {
776         const grpc::string& name = p.first;
777         const uint32_t parts_per_million = p.second;
778         auto* drop_overload = policy->add_drop_overloads();
779         drop_overload->set_category(name);
780         auto* drop_percentage = drop_overload->mutable_drop_percentage();
781         drop_percentage->set_numerator(parts_per_million);
782         drop_percentage->set_denominator(args.drop_denominator);
783       }
784     }
785     return assignment;
786   }
787 
NotifyDoneWithAdsCall()788   void NotifyDoneWithAdsCall() {
789     grpc_core::MutexLock lock(&ads_mu_);
790     NotifyDoneWithAdsCallLocked();
791   }
792 
NotifyDoneWithAdsCallLocked()793   void NotifyDoneWithAdsCallLocked() {
794     if (!ads_done_) {
795       ads_done_ = true;
796       ads_cond_.Broadcast();
797     }
798   }
799 
800  private:
801   // A queue of resource type/name pairs that have changed since the client
802   // subscribed to them.
803   using UpdateQueue = std::deque<
804       std::pair<std::string /* type url */, std::string /* resource name */>>;
805 
806   // A struct representing a client's subscription to a particular resource.
807   struct SubscriptionState {
808     // Version that the client currently knows about.
809     int current_version = 0;
810     // The queue upon which to place updates when the resource is updated.
811     UpdateQueue* update_queue;
812   };
813 
814   // A struct representing the a client's subscription to all the resources.
815   using SubscriptionNameMap =
816       std::map<std::string /* resource_name */, SubscriptionState>;
817   using SubscriptionMap =
818       std::map<std::string /* type_url */, SubscriptionNameMap>;
819 
820   // A struct representing the current state for a resource:
821   // - the version of the resource that is set by the SetResource() methods.
822   // - a list of subscriptions interested in this resource.
823   struct ResourceState {
824     int version = 0;
825     absl::optional<google::protobuf::Any> resource;
826     std::set<SubscriptionState*> subscriptions;
827   };
828 
829   // A struct representing the current state for all resources:
830   // LDS, CDS, EDS, and RDS for the class as a whole.
831   using ResourceNameMap =
832       std::map<std::string /* resource_name */, ResourceState>;
833   using ResourceMap = std::map<std::string /* type_url */, ResourceNameMap>;
834 
835   // Starting a thread to do blocking read on the stream until cancel.
BlockingRead(Stream * stream,std::deque<DiscoveryRequest> * requests,bool * stream_closed)836   void BlockingRead(Stream* stream, std::deque<DiscoveryRequest>* requests,
837                     bool* stream_closed) {
838     DiscoveryRequest request;
839     bool seen_first_request = false;
840     while (stream->Read(&request)) {
841       if (!seen_first_request) {
842         EXPECT_TRUE(request.has_node());
843         ASSERT_FALSE(request.node().client_features().empty());
844         EXPECT_EQ(request.node().client_features(0),
845                   "envoy.lb.does_not_support_overprovisioning");
846         seen_first_request = true;
847       }
848       {
849         grpc_core::MutexLock lock(&ads_mu_);
850         requests->emplace_back(std::move(request));
851       }
852     }
853     gpr_log(GPR_INFO, "ADS[%p]: Null read, stream closed", this);
854     grpc_core::MutexLock lock(&ads_mu_);
855     *stream_closed = true;
856   }
857 
858   // Checks whether the client needs to receive a newer version of
859   // the resource.  If so, updates subscription_state->current_version and
860   // returns true.
ClientNeedsResourceUpdate(const ResourceState & resource_state,SubscriptionState * subscription_state)861   bool ClientNeedsResourceUpdate(const ResourceState& resource_state,
862                                  SubscriptionState* subscription_state) {
863     if (subscription_state->current_version < resource_state.version) {
864       subscription_state->current_version = resource_state.version;
865       return true;
866     }
867     return false;
868   }
869 
870   // Subscribes to a resource if not already subscribed:
871   // 1. Sets the update_queue field in subscription_state.
872   // 2. Adds subscription_state to resource_state->subscriptions.
MaybeSubscribe(const std::string & resource_type,const std::string & resource_name,SubscriptionState * subscription_state,ResourceState * resource_state,UpdateQueue * update_queue)873   void MaybeSubscribe(const std::string& resource_type,
874                       const std::string& resource_name,
875                       SubscriptionState* subscription_state,
876                       ResourceState* resource_state,
877                       UpdateQueue* update_queue) {
878     // The update_queue will be null if we were not previously subscribed.
879     if (subscription_state->update_queue != nullptr) return;
880     subscription_state->update_queue = update_queue;
881     resource_state->subscriptions.emplace(subscription_state);
882     gpr_log(GPR_INFO, "ADS[%p]: subscribe to resource type %s name %s state %p",
883             this, resource_type.c_str(), resource_name.c_str(),
884             &subscription_state);
885   }
886 
887   // Removes subscriptions for resources no longer present in the
888   // current request.
ProcessUnsubscriptions(const std::string & resource_type,const std::set<std::string> & resources_in_current_request,SubscriptionNameMap * subscription_name_map,ResourceNameMap * resource_name_map)889   void ProcessUnsubscriptions(
890       const std::string& resource_type,
891       const std::set<std::string>& resources_in_current_request,
892       SubscriptionNameMap* subscription_name_map,
893       ResourceNameMap* resource_name_map) {
894     for (auto it = subscription_name_map->begin();
895          it != subscription_name_map->end();) {
896       const std::string& resource_name = it->first;
897       SubscriptionState& subscription_state = it->second;
898       if (resources_in_current_request.find(resource_name) !=
899           resources_in_current_request.end()) {
900         ++it;
901         continue;
902       }
903       gpr_log(GPR_INFO, "ADS[%p]: Unsubscribe to type=%s name=%s state=%p",
904               this, resource_type.c_str(), resource_name.c_str(),
905               &subscription_state);
906       auto resource_it = resource_name_map->find(resource_name);
907       GPR_ASSERT(resource_it != resource_name_map->end());
908       auto& resource_state = resource_it->second;
909       resource_state.subscriptions.erase(&subscription_state);
910       if (resource_state.subscriptions.empty() &&
911           !resource_state.resource.has_value()) {
912         resource_name_map->erase(resource_it);
913       }
914       it = subscription_name_map->erase(it);
915     }
916   }
917 
918   // Completing the building a DiscoveryResponse by adding common information
919   // for all resources and by adding all subscribed resources for LDS and CDS.
CompleteBuildingDiscoveryResponse(const std::string & resource_type,const int version,const SubscriptionNameMap & subscription_name_map,const std::set<std::string> & resources_added_to_response,DiscoveryResponse * response)920   void CompleteBuildingDiscoveryResponse(
921       const std::string& resource_type, const int version,
922       const SubscriptionNameMap& subscription_name_map,
923       const std::set<std::string>& resources_added_to_response,
924       DiscoveryResponse* response) {
925     auto& response_state = resource_type_response_state_[resource_type];
926     if (response_state.state == ResponseState::NOT_SENT) {
927       response_state.state = ResponseState::SENT;
928     }
929     response->set_type_url(resource_type);
930     response->set_version_info(absl::StrCat(version));
931     response->set_nonce(absl::StrCat(version));
932     if (resource_type == kLdsTypeUrl || resource_type == kCdsTypeUrl) {
933       // For LDS and CDS we must send back all subscribed resources
934       // (even the unchanged ones)
935       for (const auto& p : subscription_name_map) {
936         const std::string& resource_name = p.first;
937         if (resources_added_to_response.find(resource_name) ==
938             resources_added_to_response.end()) {
939           const ResourceState& resource_state =
940               resource_map_[resource_type][resource_name];
941           if (resource_state.resource.has_value()) {
942             response->add_resources()->CopyFrom(
943                 resource_state.resource.value());
944           }
945         }
946       }
947     }
948   }
949 
950   grpc_core::CondVar ads_cond_;
951   // Protect the members below.
952   grpc_core::Mutex ads_mu_;
953   bool ads_done_ = false;
954   Listener default_listener_;
955   RouteConfiguration default_route_config_;
956   Cluster default_cluster_;
957   std::map<std::string /* type_url */, ResponseState>
958       resource_type_response_state_;
959   std::set<std::string /*resource_type*/> resource_types_to_ignore_;
960   // An instance data member containing the current state of all resources.
961   // Note that an entry will exist whenever either of the following is true:
962   // - The resource exists (i.e., has been created by SetResource() and has not
963   //   yet been destroyed by UnsetResource()).
964   // - There is at least one subscription for the resource.
965   ResourceMap resource_map_;
966 };
967 
968 class LrsServiceImpl : public LrsService,
969                        public std::enable_shared_from_this<LrsServiceImpl> {
970  public:
971   using Stream = ServerReaderWriter<LoadStatsResponse, LoadStatsRequest>;
972 
LrsServiceImpl(int client_load_reporting_interval_seconds)973   explicit LrsServiceImpl(int client_load_reporting_interval_seconds)
974       : client_load_reporting_interval_seconds_(
975             client_load_reporting_interval_seconds),
976         cluster_names_({kDefaultResourceName}) {}
977 
StreamLoadStats(ServerContext *,Stream * stream)978   Status StreamLoadStats(ServerContext* /*context*/, Stream* stream) override {
979     gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats starts", this);
980     GPR_ASSERT(client_load_reporting_interval_seconds_ > 0);
981     // Take a reference of the LrsServiceImpl object, reference will go
982     // out of scope after this method exits.
983     std::shared_ptr<LrsServiceImpl> lrs_service_impl = shared_from_this();
984     // Read initial request.
985     LoadStatsRequest request;
986     if (stream->Read(&request)) {
987       IncreaseRequestCount();  // Only for initial request.
988       // Verify server name set in metadata.
989       auto it =
990           request.node().metadata().fields().find("PROXYLESS_CLIENT_HOSTNAME");
991       GPR_ASSERT(it != request.node().metadata().fields().end());
992       EXPECT_EQ(it->second.string_value(), kDefaultResourceName);
993       // Verify client features.
994       EXPECT_THAT(request.node().client_features(),
995                   ::testing::Contains("envoy.lrs.supports_send_all_clusters"));
996       // Send initial response.
997       LoadStatsResponse response;
998       if (send_all_clusters_) {
999         response.set_send_all_clusters(true);
1000       } else {
1001         for (const std::string& cluster_name : cluster_names_) {
1002           response.add_clusters(cluster_name);
1003         }
1004       }
1005       response.mutable_load_reporting_interval()->set_seconds(
1006           client_load_reporting_interval_seconds_);
1007       stream->Write(response);
1008       IncreaseResponseCount();
1009       // Wait for report.
1010       request.Clear();
1011       while (stream->Read(&request)) {
1012         gpr_log(GPR_INFO, "LRS[%p]: received client load report message: %s",
1013                 this, request.DebugString().c_str());
1014         std::vector<ClientStats> stats;
1015         for (const auto& cluster_stats : request.cluster_stats()) {
1016           stats.emplace_back(cluster_stats);
1017         }
1018         grpc_core::MutexLock lock(&load_report_mu_);
1019         result_queue_.emplace_back(std::move(stats));
1020         if (load_report_cond_ != nullptr) load_report_cond_->Signal();
1021       }
1022       // Wait until notified done.
1023       grpc_core::MutexLock lock(&lrs_mu_);
1024       lrs_cv_.WaitUntil(&lrs_mu_, [this] { return lrs_done_; });
1025     }
1026     gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats done", this);
1027     return Status::OK;
1028   }
1029 
1030   // Must be called before the LRS call is started.
set_send_all_clusters(bool send_all_clusters)1031   void set_send_all_clusters(bool send_all_clusters) {
1032     send_all_clusters_ = send_all_clusters;
1033   }
set_cluster_names(const std::set<std::string> & cluster_names)1034   void set_cluster_names(const std::set<std::string>& cluster_names) {
1035     cluster_names_ = cluster_names;
1036   }
1037 
Start()1038   void Start() {
1039     lrs_done_ = false;
1040     result_queue_.clear();
1041   }
1042 
Shutdown()1043   void Shutdown() {
1044     {
1045       grpc_core::MutexLock lock(&lrs_mu_);
1046       NotifyDoneWithLrsCallLocked();
1047     }
1048     gpr_log(GPR_INFO, "LRS[%p]: shut down", this);
1049   }
1050 
WaitForLoadReport()1051   std::vector<ClientStats> WaitForLoadReport() {
1052     grpc_core::MutexLock lock(&load_report_mu_);
1053     grpc_core::CondVar cv;
1054     if (result_queue_.empty()) {
1055       load_report_cond_ = &cv;
1056       load_report_cond_->WaitUntil(&load_report_mu_,
1057                                    [this] { return !result_queue_.empty(); });
1058       load_report_cond_ = nullptr;
1059     }
1060     std::vector<ClientStats> result = std::move(result_queue_.front());
1061     result_queue_.pop_front();
1062     return result;
1063   }
1064 
NotifyDoneWithLrsCall()1065   void NotifyDoneWithLrsCall() {
1066     grpc_core::MutexLock lock(&lrs_mu_);
1067     NotifyDoneWithLrsCallLocked();
1068   }
1069 
1070  private:
NotifyDoneWithLrsCallLocked()1071   void NotifyDoneWithLrsCallLocked() {
1072     if (!lrs_done_) {
1073       lrs_done_ = true;
1074       lrs_cv_.Broadcast();
1075     }
1076   }
1077 
1078   const int client_load_reporting_interval_seconds_;
1079   bool send_all_clusters_ = false;
1080   std::set<std::string> cluster_names_;
1081 
1082   grpc_core::CondVar lrs_cv_;
1083   grpc_core::Mutex lrs_mu_;  // Protects lrs_done_.
1084   bool lrs_done_ = false;
1085 
1086   grpc_core::Mutex load_report_mu_;  // Protects the members below.
1087   grpc_core::CondVar* load_report_cond_ = nullptr;
1088   std::deque<std::vector<ClientStats>> result_queue_;
1089 };
1090 
1091 class TestType {
1092  public:
TestType(bool use_xds_resolver,bool enable_load_reporting,bool enable_rds_testing=false)1093   TestType(bool use_xds_resolver, bool enable_load_reporting,
1094            bool enable_rds_testing = false)
1095       : use_xds_resolver_(use_xds_resolver),
1096         enable_load_reporting_(enable_load_reporting),
1097         enable_rds_testing_(enable_rds_testing) {}
1098 
use_xds_resolver() const1099   bool use_xds_resolver() const { return use_xds_resolver_; }
enable_load_reporting() const1100   bool enable_load_reporting() const { return enable_load_reporting_; }
enable_rds_testing() const1101   bool enable_rds_testing() const { return enable_rds_testing_; }
1102 
AsString() const1103   grpc::string AsString() const {
1104     grpc::string retval = (use_xds_resolver_ ? "XdsResolver" : "FakeResolver");
1105     if (enable_load_reporting_) retval += "WithLoadReporting";
1106     if (enable_rds_testing_) retval += "Rds";
1107     return retval;
1108   }
1109 
1110  private:
1111   const bool use_xds_resolver_;
1112   const bool enable_load_reporting_;
1113   const bool enable_rds_testing_;
1114 };
1115 
1116 class XdsEnd2endTest : public ::testing::TestWithParam<TestType> {
1117  protected:
XdsEnd2endTest(size_t num_backends,size_t num_balancers,int client_load_reporting_interval_seconds=100)1118   XdsEnd2endTest(size_t num_backends, size_t num_balancers,
1119                  int client_load_reporting_interval_seconds = 100)
1120       : num_backends_(num_backends),
1121         num_balancers_(num_balancers),
1122         client_load_reporting_interval_seconds_(
1123             client_load_reporting_interval_seconds) {}
1124 
SetUpTestCase()1125   static void SetUpTestCase() {
1126     // Make the backup poller poll very frequently in order to pick up
1127     // updates from all the subchannels's FDs.
1128     GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
1129 #if TARGET_OS_IPHONE
1130     // Workaround Apple CFStream bug
1131     gpr_setenv("grpc_cfstream", "0");
1132 #endif
1133     grpc_init();
1134   }
1135 
TearDownTestCase()1136   static void TearDownTestCase() { grpc_shutdown(); }
1137 
SetUp()1138   void SetUp() override {
1139     gpr_setenv("GRPC_XDS_BOOTSTRAP", g_bootstrap_file);
1140     g_port_saver->Reset();
1141     response_generator_ =
1142         grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
1143     lb_channel_response_generator_ =
1144         grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
1145     // Start the backends.
1146     for (size_t i = 0; i < num_backends_; ++i) {
1147       backends_.emplace_back(new BackendServerThread);
1148       backends_.back()->Start();
1149     }
1150     // Start the load balancers.
1151     for (size_t i = 0; i < num_balancers_; ++i) {
1152       balancers_.emplace_back(
1153           new BalancerServerThread(GetParam().enable_load_reporting()
1154                                        ? client_load_reporting_interval_seconds_
1155                                        : 0));
1156       balancers_.back()->Start();
1157       if (GetParam().enable_rds_testing()) {
1158         balancers_[i]->ads_service()->SetLdsToUseDynamicRds();
1159       }
1160     }
1161     ResetStub();
1162   }
1163 
TearDown()1164   void TearDown() override {
1165     ShutdownAllBackends();
1166     for (auto& balancer : balancers_) balancer->Shutdown();
1167   }
1168 
StartAllBackends()1169   void StartAllBackends() {
1170     for (auto& backend : backends_) backend->Start();
1171   }
1172 
StartBackend(size_t index)1173   void StartBackend(size_t index) { backends_[index]->Start(); }
1174 
ShutdownAllBackends()1175   void ShutdownAllBackends() {
1176     for (auto& backend : backends_) backend->Shutdown();
1177   }
1178 
ShutdownBackend(size_t index)1179   void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
1180 
ResetStub(int failover_timeout=0,const grpc::string & expected_targets="",int xds_resource_does_not_exist_timeout=0)1181   void ResetStub(int failover_timeout = 0,
1182                  const grpc::string& expected_targets = "",
1183                  int xds_resource_does_not_exist_timeout = 0) {
1184     ChannelArguments args;
1185     if (failover_timeout > 0) {
1186       args.SetInt(GRPC_ARG_PRIORITY_FAILOVER_TIMEOUT_MS, failover_timeout);
1187     }
1188     if (xds_resource_does_not_exist_timeout > 0) {
1189       args.SetInt(GRPC_ARG_XDS_RESOURCE_DOES_NOT_EXIST_TIMEOUT_MS,
1190                   xds_resource_does_not_exist_timeout);
1191     }
1192     // If the parent channel is using the fake resolver, we inject the
1193     // response generator for the parent here, and then SetNextResolution()
1194     // will inject the xds channel's response generator via the parent's
1195     // response generator.
1196     //
1197     // In contrast, if we are using the xds resolver, then the parent
1198     // channel never uses a response generator, and we inject the xds
1199     // channel's response generator here.
1200     args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
1201                     GetParam().use_xds_resolver()
1202                         ? lb_channel_response_generator_.get()
1203                         : response_generator_.get());
1204     if (!expected_targets.empty()) {
1205       args.SetString(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
1206     }
1207     grpc::string scheme = GetParam().use_xds_resolver() ? "xds" : "fake";
1208     std::ostringstream uri;
1209     uri << scheme << ":///" << kApplicationTargetName_;
1210     // TODO(dgq): templatize tests to run everything using both secure and
1211     // insecure channel credentials.
1212     grpc_channel_credentials* channel_creds =
1213         grpc_fake_transport_security_credentials_create();
1214     grpc_call_credentials* call_creds = grpc_md_only_test_credentials_create(
1215         g_kCallCredsMdKey, g_kCallCredsMdValue, false);
1216     std::shared_ptr<ChannelCredentials> creds(
1217         new SecureChannelCredentials(grpc_composite_channel_credentials_create(
1218             channel_creds, call_creds, nullptr)));
1219     call_creds->Unref();
1220     channel_creds->Unref();
1221     channel_ = ::grpc::CreateCustomChannel(uri.str(), creds, args);
1222     stub_ = grpc::testing::EchoTestService::NewStub(channel_);
1223     stub1_ = grpc::testing::EchoTest1Service::NewStub(channel_);
1224     stub2_ = grpc::testing::EchoTest2Service::NewStub(channel_);
1225   }
1226 
1227   enum RpcService {
1228     SERVICE_ECHO,
1229     SERVICE_ECHO1,
1230     SERVICE_ECHO2,
1231   };
1232 
1233   enum RpcMethod {
1234     METHOD_ECHO,
1235     METHOD_ECHO1,
1236     METHOD_ECHO2,
1237   };
1238 
1239   struct RpcOptions {
1240     RpcService service = SERVICE_ECHO;
1241     RpcMethod method = METHOD_ECHO;
1242     int timeout_ms = 1000;
1243     bool wait_for_ready = false;
1244     bool server_fail = false;
1245 
RpcOptionsgrpc::testing::__anon74ea63330111::XdsEnd2endTest::RpcOptions1246     RpcOptions() {}
1247 
set_rpc_servicegrpc::testing::__anon74ea63330111::XdsEnd2endTest::RpcOptions1248     RpcOptions& set_rpc_service(RpcService rpc_service) {
1249       service = rpc_service;
1250       return *this;
1251     }
1252 
set_rpc_methodgrpc::testing::__anon74ea63330111::XdsEnd2endTest::RpcOptions1253     RpcOptions& set_rpc_method(RpcMethod rpc_method) {
1254       method = rpc_method;
1255       return *this;
1256     }
1257 
set_timeout_msgrpc::testing::__anon74ea63330111::XdsEnd2endTest::RpcOptions1258     RpcOptions& set_timeout_ms(int rpc_timeout_ms) {
1259       timeout_ms = rpc_timeout_ms;
1260       return *this;
1261     }
1262 
set_wait_for_readygrpc::testing::__anon74ea63330111::XdsEnd2endTest::RpcOptions1263     RpcOptions& set_wait_for_ready(bool rpc_wait_for_ready) {
1264       wait_for_ready = rpc_wait_for_ready;
1265       return *this;
1266     }
1267 
set_server_failgrpc::testing::__anon74ea63330111::XdsEnd2endTest::RpcOptions1268     RpcOptions& set_server_fail(bool rpc_server_fail) {
1269       server_fail = rpc_server_fail;
1270       return *this;
1271     }
1272   };
1273 
1274   template <typename Stub>
SendRpcMethod(Stub * stub,const RpcOptions & rpc_options,ClientContext * context,EchoRequest & request,EchoResponse * response)1275   Status SendRpcMethod(Stub* stub, const RpcOptions& rpc_options,
1276                        ClientContext* context, EchoRequest& request,
1277                        EchoResponse* response) {
1278     switch (rpc_options.method) {
1279       case METHOD_ECHO:
1280         return (*stub)->Echo(context, request, response);
1281       case METHOD_ECHO1:
1282         return (*stub)->Echo1(context, request, response);
1283       case METHOD_ECHO2:
1284         return (*stub)->Echo2(context, request, response);
1285     }
1286   }
1287 
ResetBackendCounters(size_t start_index=0,size_t stop_index=0)1288   void ResetBackendCounters(size_t start_index = 0, size_t stop_index = 0) {
1289     if (stop_index == 0) stop_index = backends_.size();
1290     for (size_t i = start_index; i < stop_index; ++i) {
1291       backends_[i]->backend_service()->ResetCounters();
1292       backends_[i]->backend_service1()->ResetCounters();
1293       backends_[i]->backend_service2()->ResetCounters();
1294     }
1295   }
1296 
SeenAllBackends(size_t start_index=0,size_t stop_index=0,const RpcOptions & rpc_options=RpcOptions ())1297   bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0,
1298                        const RpcOptions& rpc_options = RpcOptions()) {
1299     if (stop_index == 0) stop_index = backends_.size();
1300     for (size_t i = start_index; i < stop_index; ++i) {
1301       switch (rpc_options.service) {
1302         case SERVICE_ECHO:
1303           if (backends_[i]->backend_service()->request_count() == 0)
1304             return false;
1305           break;
1306         case SERVICE_ECHO1:
1307           if (backends_[i]->backend_service1()->request_count() == 0)
1308             return false;
1309           break;
1310         case SERVICE_ECHO2:
1311           if (backends_[i]->backend_service2()->request_count() == 0)
1312             return false;
1313           break;
1314       }
1315     }
1316     return true;
1317   }
1318 
SendRpcAndCount(int * num_total,int * num_ok,int * num_failure,int * num_drops,const RpcOptions & rpc_options=RpcOptions ())1319   void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
1320                        int* num_drops,
1321                        const RpcOptions& rpc_options = RpcOptions()) {
1322     const Status status = SendRpc(rpc_options);
1323     if (status.ok()) {
1324       ++*num_ok;
1325     } else {
1326       if (status.error_message() == "Call dropped by load balancing policy") {
1327         ++*num_drops;
1328       } else {
1329         ++*num_failure;
1330       }
1331     }
1332     ++*num_total;
1333   }
1334 
WaitForAllBackends(size_t start_index=0,size_t stop_index=0,bool reset_counters=true,const RpcOptions & rpc_options=RpcOptions ())1335   std::tuple<int, int, int> WaitForAllBackends(
1336       size_t start_index = 0, size_t stop_index = 0, bool reset_counters = true,
1337       const RpcOptions& rpc_options = RpcOptions()) {
1338     int num_ok = 0;
1339     int num_failure = 0;
1340     int num_drops = 0;
1341     int num_total = 0;
1342     while (!SeenAllBackends(start_index, stop_index, rpc_options)) {
1343       SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops,
1344                       rpc_options);
1345     }
1346     if (reset_counters) ResetBackendCounters();
1347     gpr_log(GPR_INFO,
1348             "Performed %d warm up requests against the backends. "
1349             "%d succeeded, %d failed, %d dropped.",
1350             num_total, num_ok, num_failure, num_drops);
1351     return std::make_tuple(num_ok, num_failure, num_drops);
1352   }
1353 
WaitForBackend(size_t backend_idx,bool reset_counters=true,bool require_success=false)1354   void WaitForBackend(size_t backend_idx, bool reset_counters = true,
1355                       bool require_success = false) {
1356     gpr_log(GPR_INFO, "========= WAITING FOR BACKEND %lu ==========",
1357             static_cast<unsigned long>(backend_idx));
1358     do {
1359       Status status = SendRpc();
1360       if (require_success) {
1361         EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
1362                                  << " message=" << status.error_message();
1363       }
1364     } while (backends_[backend_idx]->backend_service()->request_count() == 0);
1365     if (reset_counters) ResetBackendCounters();
1366     gpr_log(GPR_INFO, "========= BACKEND %lu READY ==========",
1367             static_cast<unsigned long>(backend_idx));
1368   }
1369 
CreateAddressListFromPortList(const std::vector<int> & ports)1370   grpc_core::ServerAddressList CreateAddressListFromPortList(
1371       const std::vector<int>& ports) {
1372     grpc_core::ServerAddressList addresses;
1373     for (int port : ports) {
1374       char* lb_uri_str;
1375       gpr_asprintf(&lb_uri_str, "ipv4:127.0.0.1:%d", port);
1376       grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str, true);
1377       GPR_ASSERT(lb_uri != nullptr);
1378       grpc_resolved_address address;
1379       GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
1380       addresses.emplace_back(address.addr, address.len, nullptr);
1381       grpc_uri_destroy(lb_uri);
1382       gpr_free(lb_uri_str);
1383     }
1384     return addresses;
1385   }
1386 
SetNextResolution(const std::vector<int> & ports,grpc_core::FakeResolverResponseGenerator * lb_channel_response_generator=nullptr)1387   void SetNextResolution(const std::vector<int>& ports,
1388                          grpc_core::FakeResolverResponseGenerator*
1389                              lb_channel_response_generator = nullptr) {
1390     if (GetParam().use_xds_resolver()) return;  // Not used with xds resolver.
1391     grpc_core::ExecCtx exec_ctx;
1392     grpc_core::Resolver::Result result;
1393     result.addresses = CreateAddressListFromPortList(ports);
1394     grpc_error* error = GRPC_ERROR_NONE;
1395     const char* service_config_json =
1396         GetParam().enable_load_reporting()
1397             ? kDefaultServiceConfig_
1398             : kDefaultServiceConfigWithoutLoadReporting_;
1399     result.service_config =
1400         grpc_core::ServiceConfig::Create(service_config_json, &error);
1401     ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
1402     ASSERT_NE(result.service_config.get(), nullptr);
1403     grpc_arg arg = grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
1404         lb_channel_response_generator == nullptr
1405             ? lb_channel_response_generator_.get()
1406             : lb_channel_response_generator);
1407     result.args = grpc_channel_args_copy_and_add(nullptr, &arg, 1);
1408     response_generator_->SetResponse(std::move(result));
1409   }
1410 
SetNextResolutionForLbChannelAllBalancers(const char * service_config_json=nullptr,grpc_core::FakeResolverResponseGenerator * lb_channel_response_generator=nullptr)1411   void SetNextResolutionForLbChannelAllBalancers(
1412       const char* service_config_json = nullptr,
1413       grpc_core::FakeResolverResponseGenerator* lb_channel_response_generator =
1414           nullptr) {
1415     std::vector<int> ports;
1416     for (size_t i = 0; i < balancers_.size(); ++i) {
1417       ports.emplace_back(balancers_[i]->port());
1418     }
1419     SetNextResolutionForLbChannel(ports, service_config_json,
1420                                   lb_channel_response_generator);
1421   }
1422 
SetNextResolutionForLbChannel(const std::vector<int> & ports,const char * service_config_json=nullptr,grpc_core::FakeResolverResponseGenerator * lb_channel_response_generator=nullptr)1423   void SetNextResolutionForLbChannel(
1424       const std::vector<int>& ports, const char* service_config_json = nullptr,
1425       grpc_core::FakeResolverResponseGenerator* lb_channel_response_generator =
1426           nullptr) {
1427     grpc_core::ExecCtx exec_ctx;
1428     grpc_core::Resolver::Result result;
1429     result.addresses = CreateAddressListFromPortList(ports);
1430     if (service_config_json != nullptr) {
1431       grpc_error* error = GRPC_ERROR_NONE;
1432       result.service_config =
1433           grpc_core::ServiceConfig::Create(service_config_json, &error);
1434       ASSERT_NE(result.service_config.get(), nullptr);
1435       ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
1436     }
1437     if (lb_channel_response_generator == nullptr) {
1438       lb_channel_response_generator = lb_channel_response_generator_.get();
1439     }
1440     lb_channel_response_generator->SetResponse(std::move(result));
1441   }
1442 
SetNextReresolutionResponse(const std::vector<int> & ports)1443   void SetNextReresolutionResponse(const std::vector<int>& ports) {
1444     grpc_core::ExecCtx exec_ctx;
1445     grpc_core::Resolver::Result result;
1446     result.addresses = CreateAddressListFromPortList(ports);
1447     response_generator_->SetReresolutionResponse(std::move(result));
1448   }
1449 
GetBackendPorts(size_t start_index=0,size_t stop_index=0) const1450   const std::vector<int> GetBackendPorts(size_t start_index = 0,
1451                                          size_t stop_index = 0) const {
1452     if (stop_index == 0) stop_index = backends_.size();
1453     std::vector<int> backend_ports;
1454     for (size_t i = start_index; i < stop_index; ++i) {
1455       backend_ports.push_back(backends_[i]->port());
1456     }
1457     return backend_ports;
1458   }
1459 
SendRpc(const RpcOptions & rpc_options=RpcOptions (),EchoResponse * response=nullptr)1460   Status SendRpc(const RpcOptions& rpc_options = RpcOptions(),
1461                  EchoResponse* response = nullptr) {
1462     const bool local_response = (response == nullptr);
1463     if (local_response) response = new EchoResponse;
1464     EchoRequest request;
1465     ClientContext context;
1466     context.set_deadline(
1467         grpc_timeout_milliseconds_to_deadline(rpc_options.timeout_ms));
1468     if (rpc_options.wait_for_ready) context.set_wait_for_ready(true);
1469     request.set_message(kRequestMessage_);
1470     if (rpc_options.server_fail) {
1471       request.mutable_param()->mutable_expected_error()->set_code(
1472           GRPC_STATUS_FAILED_PRECONDITION);
1473     }
1474     Status status;
1475     switch (rpc_options.service) {
1476       case SERVICE_ECHO:
1477         status =
1478             SendRpcMethod(&stub_, rpc_options, &context, request, response);
1479         break;
1480       case SERVICE_ECHO1:
1481         status =
1482             SendRpcMethod(&stub1_, rpc_options, &context, request, response);
1483         break;
1484       case SERVICE_ECHO2:
1485         status =
1486             SendRpcMethod(&stub2_, rpc_options, &context, request, response);
1487         break;
1488     }
1489     if (local_response) delete response;
1490     return status;
1491   }
1492 
CheckRpcSendOk(const size_t times=1,const RpcOptions & rpc_options=RpcOptions ())1493   void CheckRpcSendOk(const size_t times = 1,
1494                       const RpcOptions& rpc_options = RpcOptions()) {
1495     for (size_t i = 0; i < times; ++i) {
1496       EchoResponse response;
1497       const Status status = SendRpc(rpc_options, &response);
1498       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
1499                                << " message=" << status.error_message();
1500       EXPECT_EQ(response.message(), kRequestMessage_);
1501     }
1502   }
1503 
CheckRpcSendFailure(const size_t times=1,bool server_fail=false)1504   void CheckRpcSendFailure(const size_t times = 1, bool server_fail = false) {
1505     for (size_t i = 0; i < times; ++i) {
1506       const Status status = SendRpc(RpcOptions().set_server_fail(server_fail));
1507       EXPECT_FALSE(status.ok());
1508     }
1509   }
1510 
SetRouteConfiguration(int idx,const RouteConfiguration & route_config)1511   void SetRouteConfiguration(int idx, const RouteConfiguration& route_config) {
1512     if (GetParam().enable_rds_testing()) {
1513       balancers_[idx]->ads_service()->SetRdsResource(route_config);
1514     } else {
1515       balancers_[idx]->ads_service()->SetLdsResource(
1516           AdsServiceImpl::BuildListener(route_config));
1517     }
1518   }
1519 
RouteConfigurationResponseState(int idx) const1520   AdsServiceImpl::ResponseState RouteConfigurationResponseState(int idx) const {
1521     AdsServiceImpl* ads_service = balancers_[idx]->ads_service();
1522     if (GetParam().enable_rds_testing()) {
1523       return ads_service->rds_response_state();
1524     }
1525     return ads_service->lds_response_state();
1526   }
1527 
1528  public:
1529   // This method could benefit test subclasses; to make it accessible
1530   // via bind with a qualified name, it needs to be public.
SetEdsResourceWithDelay(size_t i,const ClusterLoadAssignment & assignment,int delay_ms)1531   void SetEdsResourceWithDelay(size_t i,
1532                                const ClusterLoadAssignment& assignment,
1533                                int delay_ms) {
1534     GPR_ASSERT(delay_ms > 0);
1535     gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
1536     balancers_[i]->ads_service()->SetEdsResource(assignment);
1537   }
1538 
1539  protected:
1540   class ServerThread {
1541    public:
ServerThread()1542     ServerThread() : port_(g_port_saver->GetPort()) {}
~ServerThread()1543     virtual ~ServerThread(){};
1544 
Start()1545     void Start() {
1546       gpr_log(GPR_INFO, "starting %s server on port %d", Type(), port_);
1547       GPR_ASSERT(!running_);
1548       running_ = true;
1549       StartAllServices();
1550       grpc_core::Mutex mu;
1551       // We need to acquire the lock here in order to prevent the notify_one
1552       // by ServerThread::Serve from firing before the wait below is hit.
1553       grpc_core::MutexLock lock(&mu);
1554       grpc_core::CondVar cond;
1555       thread_.reset(
1556           new std::thread(std::bind(&ServerThread::Serve, this, &mu, &cond)));
1557       cond.Wait(&mu);
1558       gpr_log(GPR_INFO, "%s server startup complete", Type());
1559     }
1560 
Serve(grpc_core::Mutex * mu,grpc_core::CondVar * cond)1561     void Serve(grpc_core::Mutex* mu, grpc_core::CondVar* cond) {
1562       // We need to acquire the lock here in order to prevent the notify_one
1563       // below from firing before its corresponding wait is executed.
1564       grpc_core::MutexLock lock(mu);
1565       std::ostringstream server_address;
1566       server_address << "localhost:" << port_;
1567       ServerBuilder builder;
1568       std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
1569           grpc_fake_transport_security_server_credentials_create()));
1570       builder.AddListeningPort(server_address.str(), creds);
1571       RegisterAllServices(&builder);
1572       server_ = builder.BuildAndStart();
1573       cond->Signal();
1574     }
1575 
Shutdown()1576     void Shutdown() {
1577       if (!running_) return;
1578       gpr_log(GPR_INFO, "%s about to shutdown", Type());
1579       ShutdownAllServices();
1580       server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
1581       thread_->join();
1582       gpr_log(GPR_INFO, "%s shutdown completed", Type());
1583       running_ = false;
1584     }
1585 
port() const1586     int port() const { return port_; }
1587 
1588    private:
1589     virtual void RegisterAllServices(ServerBuilder* builder) = 0;
1590     virtual void StartAllServices() = 0;
1591     virtual void ShutdownAllServices() = 0;
1592 
1593     virtual const char* Type() = 0;
1594 
1595     const int port_;
1596     std::unique_ptr<Server> server_;
1597     std::unique_ptr<std::thread> thread_;
1598     bool running_ = false;
1599   };
1600 
1601   class BackendServerThread : public ServerThread {
1602    public:
1603     BackendServiceImpl<::grpc::testing::EchoTestService::Service>*
backend_service()1604     backend_service() {
1605       return &backend_service_;
1606     }
1607     BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>*
backend_service1()1608     backend_service1() {
1609       return &backend_service1_;
1610     }
1611     BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>*
backend_service2()1612     backend_service2() {
1613       return &backend_service2_;
1614     }
1615 
1616    private:
RegisterAllServices(ServerBuilder * builder)1617     void RegisterAllServices(ServerBuilder* builder) override {
1618       builder->RegisterService(&backend_service_);
1619       builder->RegisterService(&backend_service1_);
1620       builder->RegisterService(&backend_service2_);
1621     }
1622 
StartAllServices()1623     void StartAllServices() override {
1624       backend_service_.Start();
1625       backend_service1_.Start();
1626       backend_service2_.Start();
1627     }
1628 
ShutdownAllServices()1629     void ShutdownAllServices() override {
1630       backend_service_.Shutdown();
1631       backend_service1_.Shutdown();
1632       backend_service2_.Shutdown();
1633     }
1634 
Type()1635     const char* Type() override { return "Backend"; }
1636 
1637     BackendServiceImpl<::grpc::testing::EchoTestService::Service>
1638         backend_service_;
1639     BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>
1640         backend_service1_;
1641     BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>
1642         backend_service2_;
1643   };
1644 
1645   class BalancerServerThread : public ServerThread {
1646    public:
BalancerServerThread(int client_load_reporting_interval=0)1647     explicit BalancerServerThread(int client_load_reporting_interval = 0)
1648         : ads_service_(new AdsServiceImpl(client_load_reporting_interval > 0)),
1649           lrs_service_(new LrsServiceImpl(client_load_reporting_interval)) {}
1650 
ads_service()1651     AdsServiceImpl* ads_service() { return ads_service_.get(); }
lrs_service()1652     LrsServiceImpl* lrs_service() { return lrs_service_.get(); }
1653 
1654    private:
RegisterAllServices(ServerBuilder * builder)1655     void RegisterAllServices(ServerBuilder* builder) override {
1656       builder->RegisterService(ads_service_.get());
1657       builder->RegisterService(lrs_service_.get());
1658     }
1659 
StartAllServices()1660     void StartAllServices() override {
1661       ads_service_->Start();
1662       lrs_service_->Start();
1663     }
1664 
ShutdownAllServices()1665     void ShutdownAllServices() override {
1666       ads_service_->Shutdown();
1667       lrs_service_->Shutdown();
1668     }
1669 
Type()1670     const char* Type() override { return "Balancer"; }
1671 
1672     std::shared_ptr<AdsServiceImpl> ads_service_;
1673     std::shared_ptr<LrsServiceImpl> lrs_service_;
1674   };
1675 
1676   const size_t num_backends_;
1677   const size_t num_balancers_;
1678   const int client_load_reporting_interval_seconds_;
1679   std::shared_ptr<Channel> channel_;
1680   std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
1681   std::unique_ptr<grpc::testing::EchoTest1Service::Stub> stub1_;
1682   std::unique_ptr<grpc::testing::EchoTest2Service::Stub> stub2_;
1683   std::vector<std::unique_ptr<BackendServerThread>> backends_;
1684   std::vector<std::unique_ptr<BalancerServerThread>> balancers_;
1685   grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
1686       response_generator_;
1687   grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
1688       lb_channel_response_generator_;
1689   const grpc::string kRequestMessage_ = "Live long and prosper.";
1690   const grpc::string kApplicationTargetName_ = kDefaultResourceName;
1691   const char* kDefaultServiceConfig_ =
1692       "{\n"
1693       "  \"loadBalancingConfig\":[\n"
1694       "    { \"does_not_exist\":{} },\n"
1695       "    { \"eds_experimental\":{\n"
1696       "      \"clusterName\": \"application_target_name\",\n"
1697       "      \"lrsLoadReportingServerName\": \"\"\n"
1698       "    } }\n"
1699       "  ]\n"
1700       "}";
1701   const char* kDefaultServiceConfigWithoutLoadReporting_ =
1702       "{\n"
1703       "  \"loadBalancingConfig\":[\n"
1704       "    { \"does_not_exist\":{} },\n"
1705       "    { \"eds_experimental\":{\n"
1706       "      \"clusterName\": \"application_target_name\"\n"
1707       "    } }\n"
1708       "  ]\n"
1709       "}";
1710 };
1711 
1712 class BasicTest : public XdsEnd2endTest {
1713  public:
BasicTest()1714   BasicTest() : XdsEnd2endTest(4, 1) {}
1715 };
1716 
1717 // Tests that the balancer sends the correct response to the client, and the
1718 // client sends RPCs to the backends using the default child policy.
TEST_P(BasicTest,Vanilla)1719 TEST_P(BasicTest, Vanilla) {
1720   SetNextResolution({});
1721   SetNextResolutionForLbChannelAllBalancers();
1722   const size_t kNumRpcsPerAddress = 100;
1723   AdsServiceImpl::EdsResourceArgs args({
1724       {"locality0", GetBackendPorts()},
1725   });
1726   balancers_[0]->ads_service()->SetEdsResource(
1727       AdsServiceImpl::BuildEdsResource(args));
1728   // Make sure that trying to connect works without a call.
1729   channel_->GetState(true /* try_to_connect */);
1730   // We need to wait for all backends to come online.
1731   WaitForAllBackends();
1732   // Send kNumRpcsPerAddress RPCs per server.
1733   CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
1734   // Each backend should have gotten 100 requests.
1735   for (size_t i = 0; i < backends_.size(); ++i) {
1736     EXPECT_EQ(kNumRpcsPerAddress,
1737               backends_[i]->backend_service()->request_count());
1738   }
1739   // Check LB policy name for the channel.
1740   EXPECT_EQ((GetParam().use_xds_resolver() ? "xds_routing_experimental"
1741                                            : "eds_experimental"),
1742             channel_->GetLoadBalancingPolicyName());
1743 }
1744 
TEST_P(BasicTest,IgnoresUnhealthyEndpoints)1745 TEST_P(BasicTest, IgnoresUnhealthyEndpoints) {
1746   SetNextResolution({});
1747   SetNextResolutionForLbChannelAllBalancers();
1748   const size_t kNumRpcsPerAddress = 100;
1749   AdsServiceImpl::EdsResourceArgs args({
1750       {"locality0",
1751        GetBackendPorts(),
1752        kDefaultLocalityWeight,
1753        kDefaultLocalityPriority,
1754        {envoy::api::v2::HealthStatus::DRAINING}},
1755   });
1756   balancers_[0]->ads_service()->SetEdsResource(
1757       AdsServiceImpl::BuildEdsResource(args));
1758   // Make sure that trying to connect works without a call.
1759   channel_->GetState(true /* try_to_connect */);
1760   // We need to wait for all backends to come online.
1761   WaitForAllBackends(/*start_index=*/1);
1762   // Send kNumRpcsPerAddress RPCs per server.
1763   CheckRpcSendOk(kNumRpcsPerAddress * (num_backends_ - 1));
1764   // Each backend should have gotten 100 requests.
1765   for (size_t i = 1; i < backends_.size(); ++i) {
1766     EXPECT_EQ(kNumRpcsPerAddress,
1767               backends_[i]->backend_service()->request_count());
1768   }
1769 }
1770 
1771 // Tests that subchannel sharing works when the same backend is listed multiple
1772 // times.
TEST_P(BasicTest,SameBackendListedMultipleTimes)1773 TEST_P(BasicTest, SameBackendListedMultipleTimes) {
1774   SetNextResolution({});
1775   SetNextResolutionForLbChannelAllBalancers();
1776   // Same backend listed twice.
1777   std::vector<int> ports(2, backends_[0]->port());
1778   AdsServiceImpl::EdsResourceArgs args({
1779       {"locality0", ports},
1780   });
1781   const size_t kNumRpcsPerAddress = 10;
1782   balancers_[0]->ads_service()->SetEdsResource(
1783       AdsServiceImpl::BuildEdsResource(args));
1784   // We need to wait for the backend to come online.
1785   WaitForBackend(0);
1786   // Send kNumRpcsPerAddress RPCs per server.
1787   CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
1788   // Backend should have gotten 20 requests.
1789   EXPECT_EQ(kNumRpcsPerAddress * ports.size(),
1790             backends_[0]->backend_service()->request_count());
1791   // And they should have come from a single client port, because of
1792   // subchannel sharing.
1793   EXPECT_EQ(1UL, backends_[0]->backend_service()->clients().size());
1794 }
1795 
1796 // Tests that RPCs will be blocked until a non-empty serverlist is received.
TEST_P(BasicTest,InitiallyEmptyServerlist)1797 TEST_P(BasicTest, InitiallyEmptyServerlist) {
1798   SetNextResolution({});
1799   SetNextResolutionForLbChannelAllBalancers();
1800   const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
1801   const int kCallDeadlineMs = kServerlistDelayMs * 2;
1802   // First response is an empty serverlist, sent right away.
1803   AdsServiceImpl::EdsResourceArgs::Locality empty_locality("locality0", {});
1804   AdsServiceImpl::EdsResourceArgs args({
1805       empty_locality,
1806   });
1807   balancers_[0]->ads_service()->SetEdsResource(
1808       AdsServiceImpl::BuildEdsResource(args));
1809   // Send non-empty serverlist only after kServerlistDelayMs.
1810   args = AdsServiceImpl::EdsResourceArgs({
1811       {"locality0", GetBackendPorts()},
1812   });
1813   std::thread delayed_resource_setter(
1814       std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
1815                 AdsServiceImpl::BuildEdsResource(args), kServerlistDelayMs));
1816   const auto t0 = system_clock::now();
1817   // Client will block: LB will initially send empty serverlist.
1818   CheckRpcSendOk(
1819       1, RpcOptions().set_timeout_ms(kCallDeadlineMs).set_wait_for_ready(true));
1820   const auto ellapsed_ms =
1821       std::chrono::duration_cast<std::chrono::milliseconds>(
1822           system_clock::now() - t0);
1823   // but eventually, the LB sends a serverlist update that allows the call to
1824   // proceed. The call delay must be larger than the delay in sending the
1825   // populated serverlist but under the call's deadline (which is enforced by
1826   // the call's deadline).
1827   EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
1828   delayed_resource_setter.join();
1829 }
1830 
1831 // Tests that RPCs will fail with UNAVAILABLE instead of DEADLINE_EXCEEDED if
1832 // all the servers are unreachable.
TEST_P(BasicTest,AllServersUnreachableFailFast)1833 TEST_P(BasicTest, AllServersUnreachableFailFast) {
1834   SetNextResolution({});
1835   SetNextResolutionForLbChannelAllBalancers();
1836   const size_t kNumUnreachableServers = 5;
1837   std::vector<int> ports;
1838   for (size_t i = 0; i < kNumUnreachableServers; ++i) {
1839     ports.push_back(g_port_saver->GetPort());
1840   }
1841   AdsServiceImpl::EdsResourceArgs args({
1842       {"locality0", ports},
1843   });
1844   balancers_[0]->ads_service()->SetEdsResource(
1845       AdsServiceImpl::BuildEdsResource(args));
1846   const Status status = SendRpc();
1847   // The error shouldn't be DEADLINE_EXCEEDED.
1848   EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
1849 }
1850 
1851 // Tests that RPCs fail when the backends are down, and will succeed again after
1852 // the backends are restarted.
TEST_P(BasicTest,BackendsRestart)1853 TEST_P(BasicTest, BackendsRestart) {
1854   SetNextResolution({});
1855   SetNextResolutionForLbChannelAllBalancers();
1856   AdsServiceImpl::EdsResourceArgs args({
1857       {"locality0", GetBackendPorts()},
1858   });
1859   balancers_[0]->ads_service()->SetEdsResource(
1860       AdsServiceImpl::BuildEdsResource(args));
1861   WaitForAllBackends();
1862   // Stop backends.  RPCs should fail.
1863   ShutdownAllBackends();
1864   // Sending multiple failed requests instead of just one to ensure that the
1865   // client notices that all backends are down before we restart them. If we
1866   // didn't do this, then a single RPC could fail here due to the race condition
1867   // between the LB pick and the GOAWAY from the chosen backend being shut down,
1868   // which would not actually prove that the client noticed that all of the
1869   // backends are down. Then, when we send another request below (which we
1870   // expect to succeed), if the callbacks happen in the wrong order, the same
1871   // race condition could happen again due to the client not yet having noticed
1872   // that the backends were all down.
1873   CheckRpcSendFailure(num_backends_);
1874   // Restart all backends.  RPCs should start succeeding again.
1875   StartAllBackends();
1876   CheckRpcSendOk(1, RpcOptions().set_timeout_ms(2000).set_wait_for_ready(true));
1877 }
1878 
1879 using XdsResolverOnlyTest = BasicTest;
1880 
1881 // Tests switching over from one cluster to another.
TEST_P(XdsResolverOnlyTest,ChangeClusters)1882 TEST_P(XdsResolverOnlyTest, ChangeClusters) {
1883   const char* kNewClusterName = "new_cluster_name";
1884   SetNextResolution({});
1885   SetNextResolutionForLbChannelAllBalancers();
1886   AdsServiceImpl::EdsResourceArgs args({
1887       {"locality0", GetBackendPorts(0, 2)},
1888   });
1889   balancers_[0]->ads_service()->SetEdsResource(
1890       AdsServiceImpl::BuildEdsResource(args));
1891   // We need to wait for all backends to come online.
1892   WaitForAllBackends(0, 2);
1893   // Populate new EDS resource.
1894   AdsServiceImpl::EdsResourceArgs args2({
1895       {"locality0", GetBackendPorts(2, 4)},
1896   });
1897   balancers_[0]->ads_service()->SetEdsResource(
1898       AdsServiceImpl::BuildEdsResource(args2, kNewClusterName));
1899   // Populate new CDS resource.
1900   Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
1901   new_cluster.set_name(kNewClusterName);
1902   balancers_[0]->ads_service()->SetCdsResource(new_cluster);
1903   // Change RDS resource to point to new cluster.
1904   RouteConfiguration new_route_config =
1905       balancers_[0]->ads_service()->default_route_config();
1906   new_route_config.mutable_virtual_hosts(0)
1907       ->mutable_routes(0)
1908       ->mutable_route()
1909       ->set_cluster(kNewClusterName);
1910   Listener listener =
1911       balancers_[0]->ads_service()->BuildListener(new_route_config);
1912   balancers_[0]->ads_service()->SetLdsResource(listener);
1913   // Wait for all new backends to be used.
1914   std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
1915   // Make sure no RPCs failed in the transition.
1916   EXPECT_EQ(0, std::get<1>(counts));
1917 }
1918 
1919 // Tests that we go into TRANSIENT_FAILURE if the Cluster disappears.
TEST_P(XdsResolverOnlyTest,ClusterRemoved)1920 TEST_P(XdsResolverOnlyTest, ClusterRemoved) {
1921   SetNextResolution({});
1922   SetNextResolutionForLbChannelAllBalancers();
1923   AdsServiceImpl::EdsResourceArgs args({
1924       {"locality0", GetBackendPorts()},
1925   });
1926   balancers_[0]->ads_service()->SetEdsResource(
1927       AdsServiceImpl::BuildEdsResource(args));
1928   // We need to wait for all backends to come online.
1929   WaitForAllBackends();
1930   // Unset CDS resource.
1931   balancers_[0]->ads_service()->UnsetResource(kCdsTypeUrl,
1932                                               kDefaultResourceName);
1933   // Wait for RPCs to start failing.
1934   do {
1935   } while (SendRpc(RpcOptions(), nullptr).ok());
1936   // Make sure RPCs are still failing.
1937   CheckRpcSendFailure(1000);
1938   // Make sure we ACK'ed the update.
1939   EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
1940             AdsServiceImpl::ResponseState::ACKED);
1941 }
1942 
1943 // Tests that we restart all xDS requests when we reestablish the ADS call.
TEST_P(XdsResolverOnlyTest,RestartsRequestsUponReconnection)1944 TEST_P(XdsResolverOnlyTest, RestartsRequestsUponReconnection) {
1945   balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
1946   const char* kNewClusterName = "new_cluster_name";
1947   SetNextResolution({});
1948   SetNextResolutionForLbChannelAllBalancers();
1949   AdsServiceImpl::EdsResourceArgs args({
1950       {"locality0", GetBackendPorts(0, 2)},
1951   });
1952   balancers_[0]->ads_service()->SetEdsResource(
1953       AdsServiceImpl::BuildEdsResource(args));
1954   // We need to wait for all backends to come online.
1955   WaitForAllBackends(0, 2);
1956   // Now shut down and restart the balancer.  When the client
1957   // reconnects, it should automatically restart the requests for all
1958   // resource types.
1959   balancers_[0]->Shutdown();
1960   balancers_[0]->Start();
1961   // Make sure things are still working.
1962   CheckRpcSendOk(100);
1963   // Populate new EDS resource.
1964   AdsServiceImpl::EdsResourceArgs args2({
1965       {"locality0", GetBackendPorts(2, 4)},
1966   });
1967   balancers_[0]->ads_service()->SetEdsResource(
1968       AdsServiceImpl::BuildEdsResource(args2, kNewClusterName));
1969   // Populate new CDS resource.
1970   Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
1971   new_cluster.set_name(kNewClusterName);
1972   balancers_[0]->ads_service()->SetCdsResource(new_cluster);
1973   // Change RDS resource to point to new cluster.
1974   RouteConfiguration new_route_config =
1975       balancers_[0]->ads_service()->default_route_config();
1976   new_route_config.mutable_virtual_hosts(0)
1977       ->mutable_routes(0)
1978       ->mutable_route()
1979       ->set_cluster(kNewClusterName);
1980   balancers_[0]->ads_service()->SetRdsResource(new_route_config);
1981   // Wait for all new backends to be used.
1982   std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
1983   // Make sure no RPCs failed in the transition.
1984   EXPECT_EQ(0, std::get<1>(counts));
1985 }
1986 
TEST_P(XdsResolverOnlyTest,DefaultRouteSpecifiesSlashPrefix)1987 TEST_P(XdsResolverOnlyTest, DefaultRouteSpecifiesSlashPrefix) {
1988   RouteConfiguration route_config =
1989       balancers_[0]->ads_service()->default_route_config();
1990   route_config.mutable_virtual_hosts(0)
1991       ->mutable_routes(0)
1992       ->mutable_match()
1993       ->set_prefix("/");
1994   balancers_[0]->ads_service()->SetLdsResource(
1995       AdsServiceImpl::BuildListener(route_config));
1996   SetNextResolution({});
1997   SetNextResolutionForLbChannelAllBalancers();
1998   AdsServiceImpl::EdsResourceArgs args({
1999       {"locality0", GetBackendPorts()},
2000   });
2001   balancers_[0]->ads_service()->SetEdsResource(
2002       AdsServiceImpl::BuildEdsResource(args));
2003   // We need to wait for all backends to come online.
2004   WaitForAllBackends();
2005 }
2006 
2007 class XdsResolverLoadReportingOnlyTest : public XdsEnd2endTest {
2008  public:
XdsResolverLoadReportingOnlyTest()2009   XdsResolverLoadReportingOnlyTest() : XdsEnd2endTest(4, 1, 3) {}
2010 };
2011 
2012 // Tests load reporting when switching over from one cluster to another.
TEST_P(XdsResolverLoadReportingOnlyTest,ChangeClusters)2013 TEST_P(XdsResolverLoadReportingOnlyTest, ChangeClusters) {
2014   const char* kNewClusterName = "new_cluster_name";
2015   balancers_[0]->lrs_service()->set_cluster_names(
2016       {kDefaultResourceName, kNewClusterName});
2017   SetNextResolution({});
2018   SetNextResolutionForLbChannelAllBalancers();
2019   // cluster kDefaultResourceName -> locality0 -> backends 0 and 1
2020   AdsServiceImpl::EdsResourceArgs args({
2021       {"locality0", GetBackendPorts(0, 2)},
2022   });
2023   balancers_[0]->ads_service()->SetEdsResource(
2024       AdsServiceImpl::BuildEdsResource(args));
2025   // cluster kNewClusterName -> locality1 -> backends 2 and 3
2026   AdsServiceImpl::EdsResourceArgs args2({
2027       {"locality1", GetBackendPorts(2, 4)},
2028   });
2029   balancers_[0]->ads_service()->SetEdsResource(
2030       AdsServiceImpl::BuildEdsResource(args2, kNewClusterName));
2031   // CDS resource for kNewClusterName.
2032   Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
2033   new_cluster.set_name(kNewClusterName);
2034   balancers_[0]->ads_service()->SetCdsResource(new_cluster);
2035   // Wait for all backends to come online.
2036   int num_ok = 0;
2037   int num_failure = 0;
2038   int num_drops = 0;
2039   std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(0, 2);
2040   // The load report received at the balancer should be correct.
2041   std::vector<ClientStats> load_report =
2042       balancers_[0]->lrs_service()->WaitForLoadReport();
2043   EXPECT_THAT(
2044       load_report,
2045       ::testing::ElementsAre(::testing::AllOf(
2046           ::testing::Property(&ClientStats::cluster_name, kDefaultResourceName),
2047           ::testing::Property(
2048               &ClientStats::locality_stats,
2049               ::testing::ElementsAre(::testing::Pair(
2050                   "locality0",
2051                   ::testing::AllOf(
2052                       ::testing::Field(&ClientStats::LocalityStats::
2053                                            total_successful_requests,
2054                                        num_ok),
2055                       ::testing::Field(&ClientStats::LocalityStats::
2056                                            total_requests_in_progress,
2057                                        0UL),
2058                       ::testing::Field(
2059                           &ClientStats::LocalityStats::total_error_requests,
2060                           num_failure),
2061                       ::testing::Field(
2062                           &ClientStats::LocalityStats::total_issued_requests,
2063                           num_failure + num_ok))))),
2064           ::testing::Property(&ClientStats::total_dropped_requests,
2065                               num_drops))));
2066   // Change RDS resource to point to new cluster.
2067   RouteConfiguration new_route_config =
2068       balancers_[0]->ads_service()->default_route_config();
2069   new_route_config.mutable_virtual_hosts(0)
2070       ->mutable_routes(0)
2071       ->mutable_route()
2072       ->set_cluster(kNewClusterName);
2073   Listener listener =
2074       balancers_[0]->ads_service()->BuildListener(new_route_config);
2075   balancers_[0]->ads_service()->SetLdsResource(listener);
2076   // Wait for all new backends to be used.
2077   std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(2, 4);
2078   // The load report received at the balancer should be correct.
2079   load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
2080   EXPECT_THAT(
2081       load_report,
2082       ::testing::ElementsAre(
2083           ::testing::AllOf(
2084               ::testing::Property(&ClientStats::cluster_name,
2085                                   kDefaultResourceName),
2086               ::testing::Property(
2087                   &ClientStats::locality_stats,
2088                   ::testing::ElementsAre(::testing::Pair(
2089                       "locality0",
2090                       ::testing::AllOf(
2091                           ::testing::Field(&ClientStats::LocalityStats::
2092                                                total_successful_requests,
2093                                            ::testing::Lt(num_ok)),
2094                           ::testing::Field(&ClientStats::LocalityStats::
2095                                                total_requests_in_progress,
2096                                            0UL),
2097                           ::testing::Field(
2098                               &ClientStats::LocalityStats::total_error_requests,
2099                               ::testing::Le(num_failure)),
2100                           ::testing::Field(
2101                               &ClientStats::LocalityStats::
2102                                   total_issued_requests,
2103                               ::testing::Le(num_failure + num_ok)))))),
2104               ::testing::Property(&ClientStats::total_dropped_requests,
2105                                   num_drops)),
2106           ::testing::AllOf(
2107               ::testing::Property(&ClientStats::cluster_name, kNewClusterName),
2108               ::testing::Property(
2109                   &ClientStats::locality_stats,
2110                   ::testing::ElementsAre(::testing::Pair(
2111                       "locality1",
2112                       ::testing::AllOf(
2113                           ::testing::Field(&ClientStats::LocalityStats::
2114                                                total_successful_requests,
2115                                            ::testing::Le(num_ok)),
2116                           ::testing::Field(&ClientStats::LocalityStats::
2117                                                total_requests_in_progress,
2118                                            0UL),
2119                           ::testing::Field(
2120                               &ClientStats::LocalityStats::total_error_requests,
2121                               ::testing::Le(num_failure)),
2122                           ::testing::Field(
2123                               &ClientStats::LocalityStats::
2124                                   total_issued_requests,
2125                               ::testing::Le(num_failure + num_ok)))))),
2126               ::testing::Property(&ClientStats::total_dropped_requests,
2127                                   num_drops))));
2128   int total_ok = 0;
2129   int total_failure = 0;
2130   for (const ClientStats& client_stats : load_report) {
2131     total_ok += client_stats.total_successful_requests();
2132     total_failure += client_stats.total_error_requests();
2133   }
2134   EXPECT_EQ(total_ok, num_ok);
2135   EXPECT_EQ(total_failure, num_failure);
2136   // The LRS service got a single request, and sent a single response.
2137   EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
2138   EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
2139 }
2140 
2141 using SecureNamingTest = BasicTest;
2142 
2143 // Tests that secure naming check passes if target name is expected.
TEST_P(SecureNamingTest,TargetNameIsExpected)2144 TEST_P(SecureNamingTest, TargetNameIsExpected) {
2145   // TODO(juanlishen): Use separate fake creds for the balancer channel.
2146   ResetStub(0, kApplicationTargetName_ + ";lb");
2147   SetNextResolution({});
2148   SetNextResolutionForLbChannel({balancers_[0]->port()});
2149   const size_t kNumRpcsPerAddress = 100;
2150   AdsServiceImpl::EdsResourceArgs args({
2151       {"locality0", GetBackendPorts()},
2152   });
2153   balancers_[0]->ads_service()->SetEdsResource(
2154       AdsServiceImpl::BuildEdsResource(args));
2155   // Make sure that trying to connect works without a call.
2156   channel_->GetState(true /* try_to_connect */);
2157   // We need to wait for all backends to come online.
2158   WaitForAllBackends();
2159   // Send kNumRpcsPerAddress RPCs per server.
2160   CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
2161   // Each backend should have gotten 100 requests.
2162   for (size_t i = 0; i < backends_.size(); ++i) {
2163     EXPECT_EQ(kNumRpcsPerAddress,
2164               backends_[i]->backend_service()->request_count());
2165   }
2166 }
2167 
2168 // Tests that secure naming check fails if target name is unexpected.
TEST_P(SecureNamingTest,TargetNameIsUnexpected)2169 TEST_P(SecureNamingTest, TargetNameIsUnexpected) {
2170   gpr_setenv("GRPC_XDS_BOOTSTRAP", g_bootstrap_file_bad);
2171   ::testing::FLAGS_gtest_death_test_style = "threadsafe";
2172   // Make sure that we blow up (via abort() from the security connector) when
2173   // the name from the balancer doesn't match expectations.
2174   ASSERT_DEATH_IF_SUPPORTED(
2175       {
2176         ResetStub(0, kApplicationTargetName_ + ";lb");
2177         SetNextResolution({});
2178         SetNextResolutionForLbChannel({balancers_[0]->port()});
2179         channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(1));
2180       },
2181       "");
2182 }
2183 
2184 using LdsTest = BasicTest;
2185 
2186 // Tests that LDS client should send a NACK if there is no API listener in the
2187 // Listener in the LDS response.
TEST_P(LdsTest,NoApiListener)2188 TEST_P(LdsTest, NoApiListener) {
2189   auto listener = balancers_[0]->ads_service()->default_listener();
2190   listener.clear_api_listener();
2191   balancers_[0]->ads_service()->SetLdsResource(listener);
2192   SetNextResolution({});
2193   SetNextResolutionForLbChannelAllBalancers();
2194   CheckRpcSendFailure();
2195   const auto& response_state =
2196       balancers_[0]->ads_service()->lds_response_state();
2197   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2198   EXPECT_EQ(response_state.error_message, "Listener has no ApiListener.");
2199 }
2200 
2201 // Tests that LDS client should send a NACK if the route_specifier in the
2202 // http_connection_manager is neither inlined route_config nor RDS.
TEST_P(LdsTest,WrongRouteSpecifier)2203 TEST_P(LdsTest, WrongRouteSpecifier) {
2204   auto listener = balancers_[0]->ads_service()->default_listener();
2205   HttpConnectionManager http_connection_manager;
2206   http_connection_manager.mutable_scoped_routes();
2207   listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
2208       http_connection_manager);
2209   balancers_[0]->ads_service()->SetLdsResource(listener);
2210   SetNextResolution({});
2211   SetNextResolutionForLbChannelAllBalancers();
2212   CheckRpcSendFailure();
2213   const auto& response_state =
2214       balancers_[0]->ads_service()->lds_response_state();
2215   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2216   EXPECT_EQ(response_state.error_message,
2217             "HttpConnectionManager neither has inlined route_config nor RDS.");
2218 }
2219 
2220 // Tests that LDS client should send a NACK if the rds message in the
2221 // http_connection_manager is missing the config_source field.
TEST_P(LdsTest,RdsMissingConfigSource)2222 TEST_P(LdsTest, RdsMissingConfigSource) {
2223   auto listener = balancers_[0]->ads_service()->default_listener();
2224   HttpConnectionManager http_connection_manager;
2225   http_connection_manager.mutable_rds()->set_route_config_name(
2226       kDefaultResourceName);
2227   listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
2228       http_connection_manager);
2229   balancers_[0]->ads_service()->SetLdsResource(listener);
2230   SetNextResolution({});
2231   SetNextResolutionForLbChannelAllBalancers();
2232   CheckRpcSendFailure();
2233   const auto& response_state =
2234       balancers_[0]->ads_service()->lds_response_state();
2235   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2236   EXPECT_EQ(response_state.error_message,
2237             "HttpConnectionManager missing config_source for RDS.");
2238 }
2239 
2240 // Tests that LDS client should send a NACK if the rds message in the
2241 // http_connection_manager has a config_source field that does not specify ADS.
TEST_P(LdsTest,RdsConfigSourceDoesNotSpecifyAds)2242 TEST_P(LdsTest, RdsConfigSourceDoesNotSpecifyAds) {
2243   auto listener = balancers_[0]->ads_service()->default_listener();
2244   HttpConnectionManager http_connection_manager;
2245   auto* rds = http_connection_manager.mutable_rds();
2246   rds->set_route_config_name(kDefaultResourceName);
2247   rds->mutable_config_source()->mutable_self();
2248   listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
2249       http_connection_manager);
2250   balancers_[0]->ads_service()->SetLdsResource(listener);
2251   SetNextResolution({});
2252   SetNextResolutionForLbChannelAllBalancers();
2253   CheckRpcSendFailure();
2254   const auto& response_state =
2255       balancers_[0]->ads_service()->lds_response_state();
2256   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2257   EXPECT_EQ(response_state.error_message,
2258             "HttpConnectionManager ConfigSource for RDS does not specify ADS.");
2259 }
2260 
2261 using LdsRdsTest = BasicTest;
2262 
2263 // Tests that LDS client should send an ACK upon correct LDS response (with
2264 // inlined RDS result).
TEST_P(LdsRdsTest,Vanilla)2265 TEST_P(LdsRdsTest, Vanilla) {
2266   SetNextResolution({});
2267   SetNextResolutionForLbChannelAllBalancers();
2268   (void)SendRpc();
2269   EXPECT_EQ(RouteConfigurationResponseState(0).state,
2270             AdsServiceImpl::ResponseState::ACKED);
2271 }
2272 
2273 // Tests that we go into TRANSIENT_FAILURE if the Listener is removed.
TEST_P(LdsRdsTest,ListenerRemoved)2274 TEST_P(LdsRdsTest, ListenerRemoved) {
2275   SetNextResolution({});
2276   SetNextResolutionForLbChannelAllBalancers();
2277   AdsServiceImpl::EdsResourceArgs args({
2278       {"locality0", GetBackendPorts()},
2279   });
2280   balancers_[0]->ads_service()->SetEdsResource(
2281       AdsServiceImpl::BuildEdsResource(args));
2282   // We need to wait for all backends to come online.
2283   WaitForAllBackends();
2284   // Unset LDS resource.
2285   balancers_[0]->ads_service()->UnsetResource(kLdsTypeUrl,
2286                                               kDefaultResourceName);
2287   // Wait for RPCs to start failing.
2288   do {
2289   } while (SendRpc(RpcOptions(), nullptr).ok());
2290   // Make sure RPCs are still failing.
2291   CheckRpcSendFailure(1000);
2292   // Make sure we ACK'ed the update.
2293   EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
2294             AdsServiceImpl::ResponseState::ACKED);
2295 }
2296 
2297 // Tests that LDS client should send a NACK if matching domain can't be found in
2298 // the LDS response.
TEST_P(LdsRdsTest,NoMatchedDomain)2299 TEST_P(LdsRdsTest, NoMatchedDomain) {
2300   RouteConfiguration route_config =
2301       balancers_[0]->ads_service()->default_route_config();
2302   route_config.mutable_virtual_hosts(0)->clear_domains();
2303   route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
2304   SetRouteConfiguration(0, route_config);
2305   SetNextResolution({});
2306   SetNextResolutionForLbChannelAllBalancers();
2307   CheckRpcSendFailure();
2308   const auto& response_state = RouteConfigurationResponseState(0);
2309   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2310   EXPECT_EQ(response_state.error_message,
2311             "No matched virtual host found in the route config.");
2312 }
2313 
2314 // Tests that LDS client should choose the virtual host with matching domain if
2315 // multiple virtual hosts exist in the LDS response.
TEST_P(LdsRdsTest,ChooseMatchedDomain)2316 TEST_P(LdsRdsTest, ChooseMatchedDomain) {
2317   RouteConfiguration route_config =
2318       balancers_[0]->ads_service()->default_route_config();
2319   *(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
2320   route_config.mutable_virtual_hosts(0)->clear_domains();
2321   route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
2322   route_config.mutable_virtual_hosts(0)
2323       ->mutable_routes(0)
2324       ->mutable_route()
2325       ->mutable_cluster_header();
2326   SetRouteConfiguration(0, route_config);
2327   SetNextResolution({});
2328   SetNextResolutionForLbChannelAllBalancers();
2329   (void)SendRpc();
2330   EXPECT_EQ(RouteConfigurationResponseState(0).state,
2331             AdsServiceImpl::ResponseState::ACKED);
2332 }
2333 
2334 // Tests that LDS client should choose the last route in the virtual host if
2335 // multiple routes exist in the LDS response.
TEST_P(LdsRdsTest,ChooseLastRoute)2336 TEST_P(LdsRdsTest, ChooseLastRoute) {
2337   RouteConfiguration route_config =
2338       balancers_[0]->ads_service()->default_route_config();
2339   *(route_config.mutable_virtual_hosts(0)->add_routes()) =
2340       route_config.virtual_hosts(0).routes(0);
2341   route_config.mutable_virtual_hosts(0)
2342       ->mutable_routes(0)
2343       ->mutable_route()
2344       ->mutable_cluster_header();
2345   SetRouteConfiguration(0, route_config);
2346   SetNextResolution({});
2347   SetNextResolutionForLbChannelAllBalancers();
2348   (void)SendRpc();
2349   EXPECT_EQ(RouteConfigurationResponseState(0).state,
2350             AdsServiceImpl::ResponseState::ACKED);
2351 }
2352 
2353 // Tests that LDS client should send a NACK if route match has non-empty prefix
2354 // as the only route (default) in the LDS response.
TEST_P(LdsRdsTest,RouteMatchHasNonemptyPrefix)2355 TEST_P(LdsRdsTest, RouteMatchHasNonemptyPrefix) {
2356   RouteConfiguration route_config =
2357       balancers_[0]->ads_service()->default_route_config();
2358   route_config.mutable_virtual_hosts(0)
2359       ->mutable_routes(0)
2360       ->mutable_match()
2361       ->set_prefix("/nonempty_prefix/");
2362   SetRouteConfiguration(0, route_config);
2363   SetNextResolution({});
2364   SetNextResolutionForLbChannelAllBalancers();
2365   CheckRpcSendFailure();
2366   const auto& response_state = RouteConfigurationResponseState(0);
2367   balancers_[0]->ads_service()->lds_response_state();
2368   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2369   EXPECT_EQ(response_state.error_message,
2370             "Default route must have empty prefix.");
2371 }
2372 
2373 // Tests that LDS client should send a NACK if route match has path specifier
2374 // besides prefix as the only route (default) in the LDS response.
TEST_P(LdsRdsTest,RouteMatchHasUnsupportedSpecifier)2375 TEST_P(LdsRdsTest, RouteMatchHasUnsupportedSpecifier) {
2376   RouteConfiguration route_config =
2377       balancers_[0]->ads_service()->default_route_config();
2378   route_config.mutable_virtual_hosts(0)
2379       ->mutable_routes(0)
2380       ->mutable_match()
2381       ->set_path("");
2382   SetRouteConfiguration(0, route_config);
2383   SetNextResolution({});
2384   SetNextResolutionForLbChannelAllBalancers();
2385   CheckRpcSendFailure();
2386   const auto& response_state = RouteConfigurationResponseState(0);
2387   balancers_[0]->ads_service()->lds_response_state();
2388   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2389   EXPECT_EQ(response_state.error_message,
2390             "No prefix field found in Default RouteMatch.");
2391 }
2392 
2393 // Tests that LDS client should send a NACK if route match has a prefix
2394 // string with no "/".
TEST_P(LdsRdsTest,RouteMatchHasInvalidPrefixNonEmptyNoSlash)2395 TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixNonEmptyNoSlash) {
2396   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2397   RouteConfiguration route_config =
2398       balancers_[0]->ads_service()->default_route_config();
2399   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2400   route1->mutable_match()->set_prefix("grpc.testing.EchoTest1Service");
2401   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2402   default_route->mutable_match()->set_prefix("");
2403   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2404   SetRouteConfiguration(0, route_config);
2405   SetNextResolution({});
2406   SetNextResolutionForLbChannelAllBalancers();
2407   CheckRpcSendFailure();
2408   const auto& response_state = RouteConfigurationResponseState(0);
2409   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2410   EXPECT_EQ(response_state.error_message, "Prefix does not start with a /");
2411   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2412 }
2413 
2414 // Tests that LDS client should send a NACK if route match has a prefix
2415 // string does not end with "/".
TEST_P(LdsRdsTest,RouteMatchHasInvalidPrefixNoEndingSlash)2416 TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixNoEndingSlash) {
2417   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2418   RouteConfiguration route_config =
2419       balancers_[0]->ads_service()->default_route_config();
2420   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2421   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service");
2422   SetRouteConfiguration(0, route_config);
2423   SetNextResolution({});
2424   SetNextResolutionForLbChannelAllBalancers();
2425   CheckRpcSendFailure();
2426   const auto& response_state = RouteConfigurationResponseState(0);
2427   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2428   EXPECT_EQ(response_state.error_message,
2429             "Prefix not in the required format of /service/");
2430   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2431 }
2432 
2433 // Tests that LDS client should send a NACK if route match has a prefix
2434 // string does not start with "/".
TEST_P(LdsRdsTest,RouteMatchHasInvalidPrefixNoLeadingSlash)2435 TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixNoLeadingSlash) {
2436   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2437   RouteConfiguration route_config =
2438       balancers_[0]->ads_service()->default_route_config();
2439   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2440   route1->mutable_match()->set_prefix("grpc.testing.EchoTest1Service/");
2441   SetRouteConfiguration(0, route_config);
2442   SetNextResolution({});
2443   SetNextResolutionForLbChannelAllBalancers();
2444   CheckRpcSendFailure();
2445   const auto& response_state = RouteConfigurationResponseState(0);
2446   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2447   EXPECT_EQ(response_state.error_message, "Prefix does not start with a /");
2448   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2449 }
2450 
2451 // Tests that LDS client should send a NACK if route match has a prefix
2452 // string with extra content outside of "/service/".
TEST_P(LdsRdsTest,RouteMatchHasInvalidPrefixExtraContent)2453 TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixExtraContent) {
2454   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2455   RouteConfiguration route_config =
2456       balancers_[0]->ads_service()->default_route_config();
2457   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2458   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/Echo1");
2459   SetRouteConfiguration(0, route_config);
2460   SetNextResolution({});
2461   SetNextResolutionForLbChannelAllBalancers();
2462   CheckRpcSendFailure();
2463   const auto& response_state = RouteConfigurationResponseState(0);
2464   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2465   EXPECT_EQ(response_state.error_message, "Prefix does not end with a /");
2466   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2467 }
2468 
2469 // Tests that LDS client should send a NACK if route match has a prefix
2470 // string "//".
TEST_P(LdsRdsTest,RouteMatchHasInvalidPrefixNoContent)2471 TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixNoContent) {
2472   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2473   RouteConfiguration route_config =
2474       balancers_[0]->ads_service()->default_route_config();
2475   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2476   route1->mutable_match()->set_prefix("//");
2477   SetRouteConfiguration(0, route_config);
2478   SetNextResolution({});
2479   SetNextResolutionForLbChannelAllBalancers();
2480   CheckRpcSendFailure();
2481   const auto& response_state = RouteConfigurationResponseState(0);
2482   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2483   EXPECT_EQ(response_state.error_message, "Prefix contains empty service name");
2484   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2485 }
2486 
2487 // Tests that LDS client should send a NACK if route match has path
2488 // but it's empty.
TEST_P(LdsRdsTest,RouteMatchHasInvalidPathEmptyPath)2489 TEST_P(LdsRdsTest, RouteMatchHasInvalidPathEmptyPath) {
2490   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2491   RouteConfiguration route_config =
2492       balancers_[0]->ads_service()->default_route_config();
2493   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2494   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2495   default_route->mutable_match()->set_prefix("");
2496   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2497   route1->mutable_match()->set_path("");
2498   SetRouteConfiguration(0, route_config);
2499   SetNextResolution({});
2500   SetNextResolutionForLbChannelAllBalancers();
2501   CheckRpcSendFailure();
2502   const auto& response_state = RouteConfigurationResponseState(0);
2503   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2504   EXPECT_EQ(response_state.error_message, "Path if set cannot be empty");
2505   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2506 }
2507 
2508 // Tests that LDS client should send a NACK if route match has path
2509 // string does not start with "/".
TEST_P(LdsRdsTest,RouteMatchHasInvalidPathNoLeadingSlash)2510 TEST_P(LdsRdsTest, RouteMatchHasInvalidPathNoLeadingSlash) {
2511   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2512   RouteConfiguration route_config =
2513       balancers_[0]->ads_service()->default_route_config();
2514   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2515   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2516   default_route->mutable_match()->set_prefix("");
2517   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2518   route1->mutable_match()->set_path("grpc.testing.EchoTest1Service/Echo1");
2519   SetRouteConfiguration(0, route_config);
2520   SetNextResolution({});
2521   SetNextResolutionForLbChannelAllBalancers();
2522   CheckRpcSendFailure();
2523   const auto& response_state = RouteConfigurationResponseState(0);
2524   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2525   EXPECT_EQ(response_state.error_message, "Path does not start with a /");
2526   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2527 }
2528 
2529 // Tests that LDS client should send a NACK if route match has path
2530 // string that ends with "/".
TEST_P(LdsRdsTest,RouteMatchHasInvalidPathEndsWithSlash)2531 TEST_P(LdsRdsTest, RouteMatchHasInvalidPathEndsWithSlash) {
2532   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2533   RouteConfiguration route_config =
2534       balancers_[0]->ads_service()->default_route_config();
2535   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2536   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2537   default_route->mutable_match()->set_prefix("");
2538   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2539   route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1/");
2540   SetRouteConfiguration(0, route_config);
2541   SetNextResolution({});
2542   SetNextResolutionForLbChannelAllBalancers();
2543   CheckRpcSendFailure();
2544   const auto& response_state = RouteConfigurationResponseState(0);
2545   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2546   EXPECT_EQ(response_state.error_message,
2547             "Path not in the required format of /service/method");
2548   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2549 }
2550 
2551 // Tests that LDS client should send a NACK if route match has path
2552 // string that misses "/" between service and method.
TEST_P(LdsRdsTest,RouteMatchHasInvalidPathMissingMiddleSlash)2553 TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingMiddleSlash) {
2554   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2555   RouteConfiguration route_config =
2556       balancers_[0]->ads_service()->default_route_config();
2557   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2558   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2559   default_route->mutable_match()->set_prefix("");
2560   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2561   route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service.Echo1");
2562   SetRouteConfiguration(0, route_config);
2563   SetNextResolution({});
2564   SetNextResolutionForLbChannelAllBalancers();
2565   CheckRpcSendFailure();
2566   const auto& response_state = RouteConfigurationResponseState(0);
2567   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2568   EXPECT_EQ(response_state.error_message,
2569             "Path not in the required format of /service/method");
2570   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2571 }
2572 
2573 // Tests that LDS client should send a NACK if route match has path
2574 // string that is missing service.
TEST_P(LdsRdsTest,RouteMatchHasInvalidPathMissingService)2575 TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingService) {
2576   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2577   RouteConfiguration route_config =
2578       balancers_[0]->ads_service()->default_route_config();
2579   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2580   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2581   default_route->mutable_match()->set_prefix("");
2582   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2583   route1->mutable_match()->set_path("//Echo1");
2584   SetRouteConfiguration(0, route_config);
2585   SetNextResolution({});
2586   SetNextResolutionForLbChannelAllBalancers();
2587   CheckRpcSendFailure();
2588   const auto& response_state = RouteConfigurationResponseState(0);
2589   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2590   EXPECT_EQ(response_state.error_message, "Path contains empty service name");
2591   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2592 }
2593 
2594 // Tests that LDS client should send a NACK if route match has path
2595 // string that is missing method.
TEST_P(LdsRdsTest,RouteMatchHasInvalidPathMissingMethod)2596 TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingMethod) {
2597   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2598   RouteConfiguration route_config =
2599       balancers_[0]->ads_service()->default_route_config();
2600   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2601   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2602   default_route->mutable_match()->set_prefix("");
2603   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2604   route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/");
2605   SetRouteConfiguration(0, route_config);
2606   SetNextResolution({});
2607   SetNextResolutionForLbChannelAllBalancers();
2608   CheckRpcSendFailure();
2609   const auto& response_state = RouteConfigurationResponseState(0);
2610   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2611   EXPECT_EQ(response_state.error_message, "Path contains empty method name");
2612   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2613 }
2614 
2615 // Tests that LDS client should send a NACK if route has an action other than
2616 // RouteAction in the LDS response.
TEST_P(LdsRdsTest,RouteHasNoRouteAction)2617 TEST_P(LdsRdsTest, RouteHasNoRouteAction) {
2618   RouteConfiguration route_config =
2619       balancers_[0]->ads_service()->default_route_config();
2620   route_config.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_redirect();
2621   SetRouteConfiguration(0, route_config);
2622   SetNextResolution({});
2623   SetNextResolutionForLbChannelAllBalancers();
2624   CheckRpcSendFailure();
2625   const auto& response_state = RouteConfigurationResponseState(0);
2626   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2627   EXPECT_EQ(response_state.error_message, "No RouteAction found in route.");
2628 }
2629 
2630 // Tests that LDS client should send a NACK if route has a
2631 // cluster_specifier other than cluster or weighted_clusters in the LDS
2632 // response.
TEST_P(LdsRdsTest,RouteActionUnsupportedClusterSpecifier)2633 TEST_P(LdsRdsTest, RouteActionUnsupportedClusterSpecifier) {
2634   RouteConfiguration route_config =
2635       balancers_[0]->ads_service()->default_route_config();
2636   route_config.mutable_virtual_hosts(0)
2637       ->mutable_routes(0)
2638       ->mutable_route()
2639       ->mutable_cluster_header();
2640   SetRouteConfiguration(0, route_config);
2641   SetNextResolution({});
2642   SetNextResolutionForLbChannelAllBalancers();
2643   CheckRpcSendFailure();
2644   const auto& response_state = RouteConfigurationResponseState(0);
2645   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2646   EXPECT_EQ(response_state.error_message,
2647             "No cluster or weighted_clusters found in RouteAction.");
2648 }
2649 
TEST_P(LdsRdsTest,RouteActionClusterHasEmptyClusterName)2650 TEST_P(LdsRdsTest, RouteActionClusterHasEmptyClusterName) {
2651   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2652   RouteConfiguration route_config =
2653       balancers_[0]->ads_service()->default_route_config();
2654   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2655   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
2656   route1->mutable_route()->set_cluster("");
2657   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2658   default_route->mutable_match()->set_prefix("");
2659   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2660   SetRouteConfiguration(0, route_config);
2661   SetNextResolution({});
2662   SetNextResolutionForLbChannelAllBalancers();
2663   CheckRpcSendFailure();
2664   const auto& response_state = RouteConfigurationResponseState(0);
2665   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2666   EXPECT_EQ(response_state.error_message,
2667             "RouteAction cluster contains empty cluster name.");
2668   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2669 }
2670 
TEST_P(LdsRdsTest,RouteActionWeightedTargetHasIncorrectTotalWeightSet)2671 TEST_P(LdsRdsTest, RouteActionWeightedTargetHasIncorrectTotalWeightSet) {
2672   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2673   const size_t kWeight75 = 75;
2674   const char* kNewCluster1Name = "new_cluster_1";
2675   RouteConfiguration route_config =
2676       balancers_[0]->ads_service()->default_route_config();
2677   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2678   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
2679   auto* weighted_cluster1 =
2680       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
2681   weighted_cluster1->set_name(kNewCluster1Name);
2682   weighted_cluster1->mutable_weight()->set_value(kWeight75);
2683   route1->mutable_route()
2684       ->mutable_weighted_clusters()
2685       ->mutable_total_weight()
2686       ->set_value(kWeight75 + 1);
2687   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2688   default_route->mutable_match()->set_prefix("");
2689   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2690   SetRouteConfiguration(0, route_config);
2691   SetNextResolution({});
2692   SetNextResolutionForLbChannelAllBalancers();
2693   CheckRpcSendFailure();
2694   const auto& response_state = RouteConfigurationResponseState(0);
2695   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2696   EXPECT_EQ(response_state.error_message,
2697             "RouteAction weighted_cluster has incorrect total weight");
2698   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2699 }
2700 
TEST_P(LdsRdsTest,RouteActionWeightedTargetClusterHasEmptyClusterName)2701 TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasEmptyClusterName) {
2702   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2703   const size_t kWeight75 = 75;
2704   RouteConfiguration route_config =
2705       balancers_[0]->ads_service()->default_route_config();
2706   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2707   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
2708   auto* weighted_cluster1 =
2709       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
2710   weighted_cluster1->set_name("");
2711   weighted_cluster1->mutable_weight()->set_value(kWeight75);
2712   route1->mutable_route()
2713       ->mutable_weighted_clusters()
2714       ->mutable_total_weight()
2715       ->set_value(kWeight75);
2716   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2717   default_route->mutable_match()->set_prefix("");
2718   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2719   SetRouteConfiguration(0, route_config);
2720   SetNextResolution({});
2721   SetNextResolutionForLbChannelAllBalancers();
2722   CheckRpcSendFailure();
2723   const auto& response_state = RouteConfigurationResponseState(0);
2724   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2725   EXPECT_EQ(
2726       response_state.error_message,
2727       "RouteAction weighted_cluster cluster contains empty cluster name.");
2728   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2729 }
2730 
TEST_P(LdsRdsTest,RouteActionWeightedTargetClusterHasNoWeight)2731 TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasNoWeight) {
2732   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2733   const size_t kWeight75 = 75;
2734   const char* kNewCluster1Name = "new_cluster_1";
2735   RouteConfiguration route_config =
2736       balancers_[0]->ads_service()->default_route_config();
2737   auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2738   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
2739   auto* weighted_cluster1 =
2740       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
2741   weighted_cluster1->set_name(kNewCluster1Name);
2742   route1->mutable_route()
2743       ->mutable_weighted_clusters()
2744       ->mutable_total_weight()
2745       ->set_value(kWeight75);
2746   auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
2747   default_route->mutable_match()->set_prefix("");
2748   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2749   SetRouteConfiguration(0, route_config);
2750   SetNextResolution({});
2751   SetNextResolutionForLbChannelAllBalancers();
2752   CheckRpcSendFailure();
2753   const auto& response_state = RouteConfigurationResponseState(0);
2754   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
2755   EXPECT_EQ(response_state.error_message,
2756             "RouteAction weighted_cluster cluster missing weight");
2757   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2758 }
2759 
2760 // Tests that LDS client times out when no response received.
TEST_P(LdsRdsTest,Timeout)2761 TEST_P(LdsRdsTest, Timeout) {
2762   ResetStub(0, "", 500);
2763   if (GetParam().enable_rds_testing()) {
2764     balancers_[0]->ads_service()->SetResourceIgnore(kRdsTypeUrl);
2765   } else {
2766     balancers_[0]->ads_service()->SetResourceIgnore(kLdsTypeUrl);
2767   }
2768   SetNextResolution({});
2769   SetNextResolutionForLbChannelAllBalancers();
2770   CheckRpcSendFailure();
2771 }
2772 
2773 // Tests that LDS client should choose the default route (with no matching
2774 // specified) after unable to find a match with previous routes.
TEST_P(LdsRdsTest,XdsRoutingPathMatching)2775 TEST_P(LdsRdsTest, XdsRoutingPathMatching) {
2776   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2777   const char* kNewCluster1Name = "new_cluster_1";
2778   const char* kNewCluster2Name = "new_cluster_2";
2779   const size_t kNumEcho1Rpcs = 10;
2780   const size_t kNumEcho2Rpcs = 20;
2781   const size_t kNumEchoRpcs = 30;
2782   SetNextResolution({});
2783   SetNextResolutionForLbChannelAllBalancers();
2784   // Populate new EDS resources.
2785   AdsServiceImpl::EdsResourceArgs args({
2786       {"locality0", GetBackendPorts(0, 2)},
2787   });
2788   AdsServiceImpl::EdsResourceArgs args1({
2789       {"locality0", GetBackendPorts(2, 3)},
2790   });
2791   AdsServiceImpl::EdsResourceArgs args2({
2792       {"locality0", GetBackendPorts(3, 4)},
2793   });
2794   balancers_[0]->ads_service()->SetEdsResource(
2795       AdsServiceImpl::BuildEdsResource(args));
2796   balancers_[0]->ads_service()->SetEdsResource(
2797       AdsServiceImpl::BuildEdsResource(args1, kNewCluster1Name));
2798   balancers_[0]->ads_service()->SetEdsResource(
2799       AdsServiceImpl::BuildEdsResource(args2, kNewCluster2Name));
2800   // Populate new CDS resources.
2801   Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
2802   new_cluster1.set_name(kNewCluster1Name);
2803   balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
2804   Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
2805   new_cluster2.set_name(kNewCluster2Name);
2806   balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
2807   // Populating Route Configurations for LDS.
2808   RouteConfiguration new_route_config =
2809       balancers_[0]->ads_service()->default_route_config();
2810   auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2811   route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
2812   route1->mutable_route()->set_cluster(kNewCluster1Name);
2813   auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
2814   route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
2815   route2->mutable_route()->set_cluster(kNewCluster2Name);
2816   auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
2817   route3->mutable_match()->set_path("/grpc.testing.EchoTest3Service/Echo3");
2818   route3->mutable_route()->set_cluster(kDefaultResourceName);
2819   auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
2820   default_route->mutable_match()->set_prefix("");
2821   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2822   SetRouteConfiguration(0, new_route_config);
2823   WaitForAllBackends(0, 2);
2824   CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
2825   CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
2826                                     .set_rpc_service(SERVICE_ECHO1)
2827                                     .set_rpc_method(METHOD_ECHO1)
2828                                     .set_wait_for_ready(true));
2829   CheckRpcSendOk(kNumEcho2Rpcs, RpcOptions()
2830                                     .set_rpc_service(SERVICE_ECHO2)
2831                                     .set_rpc_method(METHOD_ECHO2)
2832                                     .set_wait_for_ready(true));
2833   // Make sure RPCs all go to the correct backend.
2834   for (size_t i = 0; i < 2; ++i) {
2835     EXPECT_EQ(kNumEchoRpcs / 2,
2836               backends_[i]->backend_service()->request_count());
2837     EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
2838     EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
2839   }
2840   EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
2841   EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
2842   EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
2843   EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
2844   EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
2845   EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
2846   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2847 }
2848 
TEST_P(LdsRdsTest,XdsRoutingPrefixMatching)2849 TEST_P(LdsRdsTest, XdsRoutingPrefixMatching) {
2850   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2851   const char* kNewCluster1Name = "new_cluster_1";
2852   const char* kNewCluster2Name = "new_cluster_2";
2853   const size_t kNumEcho1Rpcs = 10;
2854   const size_t kNumEcho2Rpcs = 20;
2855   const size_t kNumEchoRpcs = 30;
2856   SetNextResolution({});
2857   SetNextResolutionForLbChannelAllBalancers();
2858   // Populate new EDS resources.
2859   AdsServiceImpl::EdsResourceArgs args({
2860       {"locality0", GetBackendPorts(0, 2)},
2861   });
2862   AdsServiceImpl::EdsResourceArgs args1({
2863       {"locality0", GetBackendPorts(2, 3)},
2864   });
2865   AdsServiceImpl::EdsResourceArgs args2({
2866       {"locality0", GetBackendPorts(3, 4)},
2867   });
2868   balancers_[0]->ads_service()->SetEdsResource(
2869       AdsServiceImpl::BuildEdsResource(args));
2870   balancers_[0]->ads_service()->SetEdsResource(
2871       AdsServiceImpl::BuildEdsResource(args1, kNewCluster1Name));
2872   balancers_[0]->ads_service()->SetEdsResource(
2873       AdsServiceImpl::BuildEdsResource(args2, kNewCluster2Name));
2874   // Populate new CDS resources.
2875   Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
2876   new_cluster1.set_name(kNewCluster1Name);
2877   balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
2878   Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
2879   new_cluster2.set_name(kNewCluster2Name);
2880   balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
2881   // Populating Route Configurations for LDS.
2882   RouteConfiguration new_route_config =
2883       balancers_[0]->ads_service()->default_route_config();
2884   auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2885   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
2886   route1->mutable_route()->set_cluster(kNewCluster1Name);
2887   auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
2888   route2->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
2889   route2->mutable_route()->set_cluster(kNewCluster2Name);
2890   auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
2891   default_route->mutable_match()->set_prefix("");
2892   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2893   SetRouteConfiguration(0, new_route_config);
2894   WaitForAllBackends(0, 2);
2895   CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
2896   CheckRpcSendOk(
2897       kNumEcho1Rpcs,
2898       RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
2899   CheckRpcSendOk(
2900       kNumEcho2Rpcs,
2901       RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
2902   // Make sure RPCs all go to the correct backend.
2903   for (size_t i = 0; i < 2; ++i) {
2904     EXPECT_EQ(kNumEchoRpcs / 2,
2905               backends_[i]->backend_service()->request_count());
2906     EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
2907     EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
2908   }
2909   EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
2910   EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
2911   EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
2912   EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
2913   EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
2914   EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
2915   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
2916 }
2917 
TEST_P(LdsRdsTest,XdsRoutingWeightedCluster)2918 TEST_P(LdsRdsTest, XdsRoutingWeightedCluster) {
2919   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
2920   const char* kNewCluster1Name = "new_cluster_1";
2921   const char* kNewCluster2Name = "new_cluster_2";
2922   const size_t kNumEcho1Rpcs = 1000;
2923   const size_t kNumEchoRpcs = 10;
2924   const size_t kWeight75 = 75;
2925   const size_t kWeight25 = 25;
2926   SetNextResolution({});
2927   SetNextResolutionForLbChannelAllBalancers();
2928   // Populate new EDS resources.
2929   AdsServiceImpl::EdsResourceArgs args({
2930       {"locality0", GetBackendPorts(0, 1)},
2931   });
2932   AdsServiceImpl::EdsResourceArgs args1({
2933       {"locality0", GetBackendPorts(1, 2)},
2934   });
2935   AdsServiceImpl::EdsResourceArgs args2({
2936       {"locality0", GetBackendPorts(2, 3)},
2937   });
2938   balancers_[0]->ads_service()->SetEdsResource(
2939       AdsServiceImpl::BuildEdsResource(args));
2940   balancers_[0]->ads_service()->SetEdsResource(
2941       AdsServiceImpl::BuildEdsResource(args1, kNewCluster1Name));
2942   balancers_[0]->ads_service()->SetEdsResource(
2943       AdsServiceImpl::BuildEdsResource(args2, kNewCluster2Name));
2944   // Populate new CDS resources.
2945   Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
2946   new_cluster1.set_name(kNewCluster1Name);
2947   balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
2948   Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
2949   new_cluster2.set_name(kNewCluster2Name);
2950   balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
2951   // Populating Route Configurations for LDS.
2952   RouteConfiguration new_route_config =
2953       balancers_[0]->ads_service()->default_route_config();
2954   auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
2955   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
2956   auto* weighted_cluster1 =
2957       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
2958   weighted_cluster1->set_name(kNewCluster1Name);
2959   weighted_cluster1->mutable_weight()->set_value(kWeight75);
2960   auto* weighted_cluster2 =
2961       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
2962   weighted_cluster2->set_name(kNewCluster2Name);
2963   weighted_cluster2->mutable_weight()->set_value(kWeight25);
2964   route1->mutable_route()
2965       ->mutable_weighted_clusters()
2966       ->mutable_total_weight()
2967       ->set_value(kWeight75 + kWeight25);
2968   auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
2969   default_route->mutable_match()->set_prefix("");
2970   default_route->mutable_route()->set_cluster(kDefaultResourceName);
2971   SetRouteConfiguration(0, new_route_config);
2972   WaitForAllBackends(0, 1);
2973   WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
2974   CheckRpcSendOk(kNumEchoRpcs);
2975   CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
2976   // Make sure RPCs all go to the correct backend.
2977   EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
2978   EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
2979   EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
2980   const int weight_75_request_count =
2981       backends_[1]->backend_service1()->request_count();
2982   EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
2983   const int weight_25_request_count =
2984       backends_[2]->backend_service1()->request_count();
2985   const double kErrorTolerance = 0.2;
2986   EXPECT_THAT(weight_75_request_count,
2987               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight75 / 100 *
2988                                              (1 - kErrorTolerance)),
2989                                ::testing::Le(kNumEcho1Rpcs * kWeight75 / 100 *
2990                                              (1 + kErrorTolerance))));
2991   // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
2992   // test from flaking while debugging potential root cause.
2993   const double kErrorToleranceSmallLoad = 0.3;
2994   gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
2995           weight_75_request_count, weight_25_request_count);
2996   EXPECT_THAT(weight_25_request_count,
2997               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight25 / 100 *
2998                                              (1 - kErrorToleranceSmallLoad)),
2999                                ::testing::Le(kNumEcho1Rpcs * kWeight25 / 100 *
3000                                              (1 + kErrorToleranceSmallLoad))));
3001   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
3002 }
3003 
TEST_P(LdsRdsTest,RouteActionWeightedTargetDefaultRoute)3004 TEST_P(LdsRdsTest, RouteActionWeightedTargetDefaultRoute) {
3005   const char* kNewCluster1Name = "new_cluster_1";
3006   const char* kNewCluster2Name = "new_cluster_2";
3007   const size_t kNumEchoRpcs = 1000;
3008   const size_t kWeight75 = 75;
3009   const size_t kWeight25 = 25;
3010   SetNextResolution({});
3011   SetNextResolutionForLbChannelAllBalancers();
3012   // Populate new EDS resources.
3013   AdsServiceImpl::EdsResourceArgs args({
3014       {"locality0", GetBackendPorts(0, 1)},
3015   });
3016   AdsServiceImpl::EdsResourceArgs args1({
3017       {"locality0", GetBackendPorts(1, 2)},
3018   });
3019   AdsServiceImpl::EdsResourceArgs args2({
3020       {"locality0", GetBackendPorts(2, 3)},
3021   });
3022   balancers_[0]->ads_service()->SetEdsResource(
3023       AdsServiceImpl::BuildEdsResource(args));
3024   balancers_[0]->ads_service()->SetEdsResource(
3025       AdsServiceImpl::BuildEdsResource(args1, kNewCluster1Name));
3026   balancers_[0]->ads_service()->SetEdsResource(
3027       AdsServiceImpl::BuildEdsResource(args2, kNewCluster2Name));
3028   // Populate new CDS resources.
3029   Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
3030   new_cluster1.set_name(kNewCluster1Name);
3031   balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
3032   Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
3033   new_cluster2.set_name(kNewCluster2Name);
3034   balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
3035   // Populating Route Configurations for LDS.
3036   RouteConfiguration new_route_config =
3037       balancers_[0]->ads_service()->default_route_config();
3038   auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
3039   route1->mutable_match()->set_prefix("");
3040   auto* weighted_cluster1 =
3041       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
3042   weighted_cluster1->set_name(kNewCluster1Name);
3043   weighted_cluster1->mutable_weight()->set_value(kWeight75);
3044   auto* weighted_cluster2 =
3045       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
3046   weighted_cluster2->set_name(kNewCluster2Name);
3047   weighted_cluster2->mutable_weight()->set_value(kWeight25);
3048   route1->mutable_route()
3049       ->mutable_weighted_clusters()
3050       ->mutable_total_weight()
3051       ->set_value(kWeight75 + kWeight25);
3052   SetRouteConfiguration(0, new_route_config);
3053   WaitForAllBackends(1, 3);
3054   CheckRpcSendOk(kNumEchoRpcs);
3055   // Make sure RPCs all go to the correct backend.
3056   EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
3057   const int weight_75_request_count =
3058       backends_[1]->backend_service()->request_count();
3059   const int weight_25_request_count =
3060       backends_[2]->backend_service()->request_count();
3061   const double kErrorTolerance = 0.2;
3062   EXPECT_THAT(weight_75_request_count,
3063               ::testing::AllOf(::testing::Ge(kNumEchoRpcs * kWeight75 / 100 *
3064                                              (1 - kErrorTolerance)),
3065                                ::testing::Le(kNumEchoRpcs * kWeight75 / 100 *
3066                                              (1 + kErrorTolerance))));
3067   // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
3068   // test from flaking while debugging potential root cause.
3069   const double kErrorToleranceSmallLoad = 0.3;
3070   gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
3071           weight_75_request_count, weight_25_request_count);
3072   EXPECT_THAT(weight_25_request_count,
3073               ::testing::AllOf(::testing::Ge(kNumEchoRpcs * kWeight25 / 100 *
3074                                              (1 - kErrorToleranceSmallLoad)),
3075                                ::testing::Le(kNumEchoRpcs * kWeight25 / 100 *
3076                                              (1 + kErrorToleranceSmallLoad))));
3077 }
3078 
TEST_P(LdsRdsTest,XdsRoutingWeightedClusterUpdateWeights)3079 TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateWeights) {
3080   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
3081   const char* kNewCluster1Name = "new_cluster_1";
3082   const char* kNewCluster2Name = "anew_cluster_2";
3083   const char* kNewCluster3Name = "new_cluster_3";
3084   const size_t kNumEcho1Rpcs = 1000;
3085   const size_t kNumEchoRpcs = 10;
3086   const size_t kWeight75 = 75;
3087   const size_t kWeight25 = 25;
3088   const size_t kWeight50 = 50;
3089   SetNextResolution({});
3090   SetNextResolutionForLbChannelAllBalancers();
3091   // Populate new EDS resources.
3092   AdsServiceImpl::EdsResourceArgs args({
3093       {"locality0", GetBackendPorts(0, 1)},
3094   });
3095   AdsServiceImpl::EdsResourceArgs args1({
3096       {"locality0", GetBackendPorts(1, 2)},
3097   });
3098   AdsServiceImpl::EdsResourceArgs args2({
3099       {"locality0", GetBackendPorts(2, 3)},
3100   });
3101   AdsServiceImpl::EdsResourceArgs args3({
3102       {"locality0", GetBackendPorts(3, 4)},
3103   });
3104   balancers_[0]->ads_service()->SetEdsResource(
3105       AdsServiceImpl::BuildEdsResource(args));
3106   balancers_[0]->ads_service()->SetEdsResource(
3107       AdsServiceImpl::BuildEdsResource(args1, kNewCluster1Name));
3108   balancers_[0]->ads_service()->SetEdsResource(
3109       AdsServiceImpl::BuildEdsResource(args2, kNewCluster2Name));
3110   balancers_[0]->ads_service()->SetEdsResource(
3111       AdsServiceImpl::BuildEdsResource(args3, kNewCluster3Name));
3112   // Populate new CDS resources.
3113   Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
3114   new_cluster1.set_name(kNewCluster1Name);
3115   balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
3116   Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
3117   new_cluster2.set_name(kNewCluster2Name);
3118   balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
3119   Cluster new_cluster3 = balancers_[0]->ads_service()->default_cluster();
3120   new_cluster3.set_name(kNewCluster3Name);
3121   balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
3122   // Populating Route Configurations.
3123   RouteConfiguration new_route_config =
3124       balancers_[0]->ads_service()->default_route_config();
3125   auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
3126   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
3127   auto* weighted_cluster1 =
3128       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
3129   weighted_cluster1->set_name(kNewCluster1Name);
3130   weighted_cluster1->mutable_weight()->set_value(kWeight75);
3131   auto* weighted_cluster2 =
3132       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
3133   weighted_cluster2->set_name(kNewCluster2Name);
3134   weighted_cluster2->mutable_weight()->set_value(kWeight25);
3135   route1->mutable_route()
3136       ->mutable_weighted_clusters()
3137       ->mutable_total_weight()
3138       ->set_value(kWeight75 + kWeight25);
3139   auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
3140   default_route->mutable_match()->set_prefix("");
3141   default_route->mutable_route()->set_cluster(kDefaultResourceName);
3142   SetRouteConfiguration(0, new_route_config);
3143   WaitForAllBackends(0, 1);
3144   WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
3145   CheckRpcSendOk(kNumEchoRpcs);
3146   CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
3147   // Make sure RPCs all go to the correct backend.
3148   EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
3149   EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
3150   EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
3151   const int weight_75_request_count =
3152       backends_[1]->backend_service1()->request_count();
3153   EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
3154   EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
3155   const int weight_25_request_count =
3156       backends_[2]->backend_service1()->request_count();
3157   EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
3158   EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
3159   const double kErrorTolerance = 0.2;
3160   EXPECT_THAT(weight_75_request_count,
3161               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight75 / 100 *
3162                                              (1 - kErrorTolerance)),
3163                                ::testing::Le(kNumEcho1Rpcs * kWeight75 / 100 *
3164                                              (1 + kErrorTolerance))));
3165   // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
3166   // test from flaking while debugging potential root cause.
3167   const double kErrorToleranceSmallLoad = 0.3;
3168   gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
3169           weight_75_request_count, weight_25_request_count);
3170   EXPECT_THAT(weight_25_request_count,
3171               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight25 / 100 *
3172                                              (1 - kErrorToleranceSmallLoad)),
3173                                ::testing::Le(kNumEcho1Rpcs * kWeight25 / 100 *
3174                                              (1 + kErrorToleranceSmallLoad))));
3175   // Change Route Configurations: same clusters different weights.
3176   weighted_cluster1->mutable_weight()->set_value(kWeight50);
3177   weighted_cluster2->mutable_weight()->set_value(kWeight50);
3178   // Change default route to a new cluster to help to identify when new polices
3179   // are seen by the client.
3180   default_route->mutable_route()->set_cluster(kNewCluster3Name);
3181   SetRouteConfiguration(0, new_route_config);
3182   ResetBackendCounters();
3183   WaitForAllBackends(3, 4);
3184   CheckRpcSendOk(kNumEchoRpcs);
3185   CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
3186   // Make sure RPCs all go to the correct backend.
3187   EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
3188   EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
3189   EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
3190   const int weight_50_request_count_1 =
3191       backends_[1]->backend_service1()->request_count();
3192   EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
3193   const int weight_50_request_count_2 =
3194       backends_[2]->backend_service1()->request_count();
3195   EXPECT_EQ(kNumEchoRpcs, backends_[3]->backend_service()->request_count());
3196   EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
3197   EXPECT_THAT(weight_50_request_count_1,
3198               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight50 / 100 *
3199                                              (1 - kErrorTolerance)),
3200                                ::testing::Le(kNumEcho1Rpcs * kWeight50 / 100 *
3201                                              (1 + kErrorTolerance))));
3202   EXPECT_THAT(weight_50_request_count_2,
3203               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight50 / 100 *
3204                                              (1 - kErrorTolerance)),
3205                                ::testing::Le(kNumEcho1Rpcs * kWeight50 / 100 *
3206                                              (1 + kErrorTolerance))));
3207   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
3208 }
3209 
TEST_P(LdsRdsTest,XdsRoutingWeightedClusterUpdateClusters)3210 TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateClusters) {
3211   gpr_setenv("GRPC_XDS_EXPERIMENTAL_ROUTING", "true");
3212   const char* kNewCluster1Name = "new_cluster_1";
3213   const char* kNewCluster2Name = "anew_cluster_2";
3214   const char* kNewCluster3Name = "new_cluster_3";
3215   const size_t kNumEcho1Rpcs = 1000;
3216   const size_t kNumEchoRpcs = 10;
3217   const size_t kWeight75 = 75;
3218   const size_t kWeight25 = 25;
3219   const size_t kWeight50 = 50;
3220   SetNextResolution({});
3221   SetNextResolutionForLbChannelAllBalancers();
3222   // Populate new EDS resources.
3223   AdsServiceImpl::EdsResourceArgs args({
3224       {"locality0", GetBackendPorts(0, 1)},
3225   });
3226   AdsServiceImpl::EdsResourceArgs args1({
3227       {"locality0", GetBackendPorts(1, 2)},
3228   });
3229   AdsServiceImpl::EdsResourceArgs args2({
3230       {"locality0", GetBackendPorts(2, 3)},
3231   });
3232   AdsServiceImpl::EdsResourceArgs args3({
3233       {"locality0", GetBackendPorts(3, 4)},
3234   });
3235   balancers_[0]->ads_service()->SetEdsResource(
3236       AdsServiceImpl::BuildEdsResource(args));
3237   balancers_[0]->ads_service()->SetEdsResource(
3238       AdsServiceImpl::BuildEdsResource(args1, kNewCluster1Name));
3239   balancers_[0]->ads_service()->SetEdsResource(
3240       AdsServiceImpl::BuildEdsResource(args2, kNewCluster2Name));
3241   balancers_[0]->ads_service()->SetEdsResource(
3242       AdsServiceImpl::BuildEdsResource(args3, kNewCluster3Name));
3243   // Populate new CDS resources.
3244   Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
3245   new_cluster1.set_name(kNewCluster1Name);
3246   balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
3247   Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
3248   new_cluster2.set_name(kNewCluster2Name);
3249   balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
3250   Cluster new_cluster3 = balancers_[0]->ads_service()->default_cluster();
3251   new_cluster3.set_name(kNewCluster3Name);
3252   balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
3253   // Populating Route Configurations.
3254   RouteConfiguration new_route_config =
3255       balancers_[0]->ads_service()->default_route_config();
3256   auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
3257   route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
3258   auto* weighted_cluster1 =
3259       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
3260   weighted_cluster1->set_name(kNewCluster1Name);
3261   weighted_cluster1->mutable_weight()->set_value(kWeight75);
3262   auto* weighted_cluster2 =
3263       route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
3264   weighted_cluster2->set_name(kDefaultResourceName);
3265   weighted_cluster2->mutable_weight()->set_value(kWeight25);
3266   route1->mutable_route()
3267       ->mutable_weighted_clusters()
3268       ->mutable_total_weight()
3269       ->set_value(kWeight75 + kWeight25);
3270   auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
3271   default_route->mutable_match()->set_prefix("");
3272   default_route->mutable_route()->set_cluster(kDefaultResourceName);
3273   SetRouteConfiguration(0, new_route_config);
3274   WaitForAllBackends(0, 1);
3275   WaitForAllBackends(1, 2, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
3276   CheckRpcSendOk(kNumEchoRpcs);
3277   CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
3278   // Make sure RPCs all go to the correct backend.
3279   EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
3280   int weight_25_request_count =
3281       backends_[0]->backend_service1()->request_count();
3282   EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
3283   int weight_75_request_count =
3284       backends_[1]->backend_service1()->request_count();
3285   EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
3286   EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
3287   EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
3288   EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
3289   const double kErrorTolerance = 0.2;
3290   EXPECT_THAT(weight_75_request_count,
3291               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight75 / 100 *
3292                                              (1 - kErrorTolerance)),
3293                                ::testing::Le(kNumEcho1Rpcs * kWeight75 / 100 *
3294                                              (1 + kErrorTolerance))));
3295   // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
3296   // test from flaking while debugging potential root cause.
3297   const double kErrorToleranceSmallLoad = 0.3;
3298   gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
3299           weight_75_request_count, weight_25_request_count);
3300   EXPECT_THAT(weight_25_request_count,
3301               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight25 / 100 *
3302                                              (1 - kErrorToleranceSmallLoad)),
3303                                ::testing::Le(kNumEcho1Rpcs * kWeight25 / 100 *
3304                                              (1 + kErrorToleranceSmallLoad))));
3305   // Change Route Configurations: new set of clusters with different weights.
3306   weighted_cluster1->mutable_weight()->set_value(kWeight50);
3307   weighted_cluster2->set_name(kNewCluster2Name);
3308   weighted_cluster2->mutable_weight()->set_value(kWeight50);
3309   SetRouteConfiguration(0, new_route_config);
3310   ResetBackendCounters();
3311   WaitForAllBackends(2, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
3312   CheckRpcSendOk(kNumEchoRpcs);
3313   CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
3314   // Make sure RPCs all go to the correct backend.
3315   EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
3316   EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
3317   EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
3318   const int weight_50_request_count_1 =
3319       backends_[1]->backend_service1()->request_count();
3320   EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
3321   const int weight_50_request_count_2 =
3322       backends_[2]->backend_service1()->request_count();
3323   EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
3324   EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
3325   EXPECT_THAT(weight_50_request_count_1,
3326               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight50 / 100 *
3327                                              (1 - kErrorTolerance)),
3328                                ::testing::Le(kNumEcho1Rpcs * kWeight50 / 100 *
3329                                              (1 + kErrorTolerance))));
3330   EXPECT_THAT(weight_50_request_count_2,
3331               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight50 / 100 *
3332                                              (1 - kErrorTolerance)),
3333                                ::testing::Le(kNumEcho1Rpcs * kWeight50 / 100 *
3334                                              (1 + kErrorTolerance))));
3335   // Change Route Configurations.
3336   weighted_cluster1->mutable_weight()->set_value(kWeight75);
3337   weighted_cluster2->set_name(kNewCluster3Name);
3338   weighted_cluster2->mutable_weight()->set_value(kWeight25);
3339   SetRouteConfiguration(0, new_route_config);
3340   ResetBackendCounters();
3341   WaitForAllBackends(3, 4, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
3342   CheckRpcSendOk(kNumEchoRpcs);
3343   CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
3344   // Make sure RPCs all go to the correct backend.
3345   EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
3346   EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
3347   EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
3348   weight_75_request_count = backends_[1]->backend_service1()->request_count();
3349   EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
3350   EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
3351   EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
3352   weight_25_request_count = backends_[3]->backend_service1()->request_count();
3353   EXPECT_THAT(weight_75_request_count,
3354               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight75 / 100 *
3355                                              (1 - kErrorTolerance)),
3356                                ::testing::Le(kNumEcho1Rpcs * kWeight75 / 100 *
3357                                              (1 + kErrorTolerance))));
3358   // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
3359   // test from flaking while debugging potential root cause.
3360   gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
3361           weight_75_request_count, weight_25_request_count);
3362   EXPECT_THAT(weight_25_request_count,
3363               ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight25 / 100 *
3364                                              (1 - kErrorToleranceSmallLoad)),
3365                                ::testing::Le(kNumEcho1Rpcs * kWeight25 / 100 *
3366                                              (1 + kErrorToleranceSmallLoad))));
3367   gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ROUTING");
3368 }
3369 
3370 using CdsTest = BasicTest;
3371 
3372 // Tests that CDS client should send an ACK upon correct CDS response.
TEST_P(CdsTest,Vanilla)3373 TEST_P(CdsTest, Vanilla) {
3374   SetNextResolution({});
3375   SetNextResolutionForLbChannelAllBalancers();
3376   (void)SendRpc();
3377   EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
3378             AdsServiceImpl::ResponseState::ACKED);
3379 }
3380 
3381 // Tests that CDS client should send a NACK if the cluster type in CDS response
3382 // is other than EDS.
TEST_P(CdsTest,WrongClusterType)3383 TEST_P(CdsTest, WrongClusterType) {
3384   auto cluster = balancers_[0]->ads_service()->default_cluster();
3385   cluster.set_type(envoy::api::v2::Cluster::STATIC);
3386   balancers_[0]->ads_service()->SetCdsResource(cluster);
3387   SetNextResolution({});
3388   SetNextResolutionForLbChannelAllBalancers();
3389   CheckRpcSendFailure();
3390   const auto& response_state =
3391       balancers_[0]->ads_service()->cds_response_state();
3392   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
3393   EXPECT_EQ(response_state.error_message, "DiscoveryType is not EDS.");
3394 }
3395 
3396 // Tests that CDS client should send a NACK if the eds_config in CDS response is
3397 // other than ADS.
TEST_P(CdsTest,WrongEdsConfig)3398 TEST_P(CdsTest, WrongEdsConfig) {
3399   auto cluster = balancers_[0]->ads_service()->default_cluster();
3400   cluster.mutable_eds_cluster_config()->mutable_eds_config()->mutable_self();
3401   balancers_[0]->ads_service()->SetCdsResource(cluster);
3402   SetNextResolution({});
3403   SetNextResolutionForLbChannelAllBalancers();
3404   CheckRpcSendFailure();
3405   const auto& response_state =
3406       balancers_[0]->ads_service()->cds_response_state();
3407   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
3408   EXPECT_EQ(response_state.error_message, "EDS ConfigSource is not ADS.");
3409 }
3410 
3411 // Tests that CDS client should send a NACK if the lb_policy in CDS response is
3412 // other than ROUND_ROBIN.
TEST_P(CdsTest,WrongLbPolicy)3413 TEST_P(CdsTest, WrongLbPolicy) {
3414   auto cluster = balancers_[0]->ads_service()->default_cluster();
3415   cluster.set_lb_policy(envoy::api::v2::Cluster::LEAST_REQUEST);
3416   balancers_[0]->ads_service()->SetCdsResource(cluster);
3417   SetNextResolution({});
3418   SetNextResolutionForLbChannelAllBalancers();
3419   CheckRpcSendFailure();
3420   const auto& response_state =
3421       balancers_[0]->ads_service()->cds_response_state();
3422   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
3423   EXPECT_EQ(response_state.error_message, "LB policy is not ROUND_ROBIN.");
3424 }
3425 
3426 // Tests that CDS client should send a NACK if the lrs_server in CDS response is
3427 // other than SELF.
TEST_P(CdsTest,WrongLrsServer)3428 TEST_P(CdsTest, WrongLrsServer) {
3429   auto cluster = balancers_[0]->ads_service()->default_cluster();
3430   cluster.mutable_lrs_server()->mutable_ads();
3431   balancers_[0]->ads_service()->SetCdsResource(cluster);
3432   SetNextResolution({});
3433   SetNextResolutionForLbChannelAllBalancers();
3434   CheckRpcSendFailure();
3435   const auto& response_state =
3436       balancers_[0]->ads_service()->cds_response_state();
3437   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
3438   EXPECT_EQ(response_state.error_message, "LRS ConfigSource is not self.");
3439 }
3440 
3441 // Tests that CDS client times out when no response received.
TEST_P(CdsTest,Timeout)3442 TEST_P(CdsTest, Timeout) {
3443   ResetStub(0, "", 500);
3444   balancers_[0]->ads_service()->SetResourceIgnore(kCdsTypeUrl);
3445   SetNextResolution({});
3446   SetNextResolutionForLbChannelAllBalancers();
3447   CheckRpcSendFailure();
3448 }
3449 
3450 using EdsTest = BasicTest;
3451 
TEST_P(EdsTest,Timeout)3452 TEST_P(EdsTest, Timeout) {
3453   ResetStub(0, "", 500);
3454   balancers_[0]->ads_service()->SetResourceIgnore(kEdsTypeUrl);
3455   SetNextResolution({});
3456   SetNextResolutionForLbChannelAllBalancers();
3457   CheckRpcSendFailure();
3458 }
3459 
3460 // Tests that EDS client should send a NACK if the EDS update contains
3461 // sparse priorities.
TEST_P(EdsTest,NacksSparsePriorityList)3462 TEST_P(EdsTest, NacksSparsePriorityList) {
3463   SetNextResolution({});
3464   SetNextResolutionForLbChannelAllBalancers();
3465   AdsServiceImpl::EdsResourceArgs args({
3466       {"locality0", GetBackendPorts(), kDefaultLocalityWeight, 1},
3467   });
3468   balancers_[0]->ads_service()->SetEdsResource(
3469       AdsServiceImpl::BuildEdsResource(args));
3470   CheckRpcSendFailure();
3471   const auto& response_state =
3472       balancers_[0]->ads_service()->eds_response_state();
3473   EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
3474   EXPECT_EQ(response_state.error_message,
3475             "EDS update includes sparse priority list");
3476 }
3477 
3478 using LocalityMapTest = BasicTest;
3479 
3480 // Tests that the localities in a locality map are picked according to their
3481 // weights.
TEST_P(LocalityMapTest,WeightedRoundRobin)3482 TEST_P(LocalityMapTest, WeightedRoundRobin) {
3483   SetNextResolution({});
3484   SetNextResolutionForLbChannelAllBalancers();
3485   const size_t kNumRpcs = 5000;
3486   const int kLocalityWeight0 = 2;
3487   const int kLocalityWeight1 = 8;
3488   const int kTotalLocalityWeight = kLocalityWeight0 + kLocalityWeight1;
3489   const double kLocalityWeightRate0 =
3490       static_cast<double>(kLocalityWeight0) / kTotalLocalityWeight;
3491   const double kLocalityWeightRate1 =
3492       static_cast<double>(kLocalityWeight1) / kTotalLocalityWeight;
3493   // ADS response contains 2 localities, each of which contains 1 backend.
3494   AdsServiceImpl::EdsResourceArgs args({
3495       {"locality0", GetBackendPorts(0, 1), kLocalityWeight0},
3496       {"locality1", GetBackendPorts(1, 2), kLocalityWeight1},
3497   });
3498   balancers_[0]->ads_service()->SetEdsResource(
3499       AdsServiceImpl::BuildEdsResource(args));
3500   // Wait for both backends to be ready.
3501   WaitForAllBackends(0, 2);
3502   // Send kNumRpcs RPCs.
3503   CheckRpcSendOk(kNumRpcs);
3504   // The locality picking rates should be roughly equal to the expectation.
3505   const double locality_picked_rate_0 =
3506       static_cast<double>(backends_[0]->backend_service()->request_count()) /
3507       kNumRpcs;
3508   const double locality_picked_rate_1 =
3509       static_cast<double>(backends_[1]->backend_service()->request_count()) /
3510       kNumRpcs;
3511   const double kErrorTolerance = 0.2;
3512   EXPECT_THAT(locality_picked_rate_0,
3513               ::testing::AllOf(
3514                   ::testing::Ge(kLocalityWeightRate0 * (1 - kErrorTolerance)),
3515                   ::testing::Le(kLocalityWeightRate0 * (1 + kErrorTolerance))));
3516   EXPECT_THAT(locality_picked_rate_1,
3517               ::testing::AllOf(
3518                   ::testing::Ge(kLocalityWeightRate1 * (1 - kErrorTolerance)),
3519                   ::testing::Le(kLocalityWeightRate1 * (1 + kErrorTolerance))));
3520 }
3521 
3522 // Tests that we correctly handle a locality containing no endpoints.
TEST_P(LocalityMapTest,LocalityContainingNoEndpoints)3523 TEST_P(LocalityMapTest, LocalityContainingNoEndpoints) {
3524   SetNextResolution({});
3525   SetNextResolutionForLbChannelAllBalancers();
3526   const size_t kNumRpcs = 5000;
3527   // EDS response contains 2 localities, one with no endpoints.
3528   AdsServiceImpl::EdsResourceArgs args({
3529       {"locality0", GetBackendPorts()},
3530       {"locality1", {}},
3531   });
3532   balancers_[0]->ads_service()->SetEdsResource(
3533       AdsServiceImpl::BuildEdsResource(args));
3534   // Wait for both backends to be ready.
3535   WaitForAllBackends();
3536   // Send kNumRpcs RPCs.
3537   CheckRpcSendOk(kNumRpcs);
3538   // All traffic should go to the reachable locality.
3539   EXPECT_EQ(backends_[0]->backend_service()->request_count(),
3540             kNumRpcs / backends_.size());
3541   EXPECT_EQ(backends_[1]->backend_service()->request_count(),
3542             kNumRpcs / backends_.size());
3543   EXPECT_EQ(backends_[2]->backend_service()->request_count(),
3544             kNumRpcs / backends_.size());
3545   EXPECT_EQ(backends_[3]->backend_service()->request_count(),
3546             kNumRpcs / backends_.size());
3547 }
3548 
3549 // EDS update with no localities.
TEST_P(LocalityMapTest,NoLocalities)3550 TEST_P(LocalityMapTest, NoLocalities) {
3551   SetNextResolution({});
3552   SetNextResolutionForLbChannelAllBalancers();
3553   // EDS response contains 2 localities, one with no endpoints.
3554   balancers_[0]->ads_service()->SetEdsResource(
3555       AdsServiceImpl::BuildEdsResource({}));
3556   Status status = SendRpc();
3557   EXPECT_FALSE(status.ok());
3558   EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
3559 }
3560 
3561 // Tests that the locality map can work properly even when it contains a large
3562 // number of localities.
TEST_P(LocalityMapTest,StressTest)3563 TEST_P(LocalityMapTest, StressTest) {
3564   SetNextResolution({});
3565   SetNextResolutionForLbChannelAllBalancers();
3566   const size_t kNumLocalities = 100;
3567   // The first ADS response contains kNumLocalities localities, each of which
3568   // contains backend 0.
3569   AdsServiceImpl::EdsResourceArgs args;
3570   for (size_t i = 0; i < kNumLocalities; ++i) {
3571     std::string name = absl::StrCat("locality", i);
3572     AdsServiceImpl::EdsResourceArgs::Locality locality(name,
3573                                                        {backends_[0]->port()});
3574     args.locality_list.emplace_back(std::move(locality));
3575   }
3576   balancers_[0]->ads_service()->SetEdsResource(
3577       AdsServiceImpl::BuildEdsResource(args));
3578   // The second ADS response contains 1 locality, which contains backend 1.
3579   args = AdsServiceImpl::EdsResourceArgs({
3580       {"locality0", GetBackendPorts(1, 2)},
3581   });
3582   std::thread delayed_resource_setter(
3583       std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
3584                 AdsServiceImpl::BuildEdsResource(args), 60 * 1000));
3585   // Wait until backend 0 is ready, before which kNumLocalities localities are
3586   // received and handled by the xds policy.
3587   WaitForBackend(0, /*reset_counters=*/false);
3588   EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
3589   // Wait until backend 1 is ready, before which kNumLocalities localities are
3590   // removed by the xds policy.
3591   WaitForBackend(1);
3592   delayed_resource_setter.join();
3593 }
3594 
3595 // Tests that the localities in a locality map are picked correctly after update
3596 // (addition, modification, deletion).
TEST_P(LocalityMapTest,UpdateMap)3597 TEST_P(LocalityMapTest, UpdateMap) {
3598   SetNextResolution({});
3599   SetNextResolutionForLbChannelAllBalancers();
3600   const size_t kNumRpcs = 3000;
3601   // The locality weight for the first 3 localities.
3602   const std::vector<int> kLocalityWeights0 = {2, 3, 4};
3603   const double kTotalLocalityWeight0 =
3604       std::accumulate(kLocalityWeights0.begin(), kLocalityWeights0.end(), 0);
3605   std::vector<double> locality_weight_rate_0;
3606   for (int weight : kLocalityWeights0) {
3607     locality_weight_rate_0.push_back(weight / kTotalLocalityWeight0);
3608   }
3609   // Delete the first locality, keep the second locality, change the third
3610   // locality's weight from 4 to 2, and add a new locality with weight 6.
3611   const std::vector<int> kLocalityWeights1 = {3, 2, 6};
3612   const double kTotalLocalityWeight1 =
3613       std::accumulate(kLocalityWeights1.begin(), kLocalityWeights1.end(), 0);
3614   std::vector<double> locality_weight_rate_1 = {
3615       0 /* placeholder for locality 0 */};
3616   for (int weight : kLocalityWeights1) {
3617     locality_weight_rate_1.push_back(weight / kTotalLocalityWeight1);
3618   }
3619   AdsServiceImpl::EdsResourceArgs args({
3620       {"locality0", GetBackendPorts(0, 1), 2},
3621       {"locality1", GetBackendPorts(1, 2), 3},
3622       {"locality2", GetBackendPorts(2, 3), 4},
3623   });
3624   balancers_[0]->ads_service()->SetEdsResource(
3625       AdsServiceImpl::BuildEdsResource(args));
3626   // Wait for the first 3 backends to be ready.
3627   WaitForAllBackends(0, 3);
3628   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
3629   // Send kNumRpcs RPCs.
3630   CheckRpcSendOk(kNumRpcs);
3631   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
3632   // The picking rates of the first 3 backends should be roughly equal to the
3633   // expectation.
3634   std::vector<double> locality_picked_rates;
3635   for (size_t i = 0; i < 3; ++i) {
3636     locality_picked_rates.push_back(
3637         static_cast<double>(backends_[i]->backend_service()->request_count()) /
3638         kNumRpcs);
3639   }
3640   const double kErrorTolerance = 0.2;
3641   for (size_t i = 0; i < 3; ++i) {
3642     gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
3643             locality_picked_rates[i]);
3644     EXPECT_THAT(
3645         locality_picked_rates[i],
3646         ::testing::AllOf(
3647             ::testing::Ge(locality_weight_rate_0[i] * (1 - kErrorTolerance)),
3648             ::testing::Le(locality_weight_rate_0[i] * (1 + kErrorTolerance))));
3649   }
3650   args = AdsServiceImpl::EdsResourceArgs({
3651       {"locality1", GetBackendPorts(1, 2), 3},
3652       {"locality2", GetBackendPorts(2, 3), 2},
3653       {"locality3", GetBackendPorts(3, 4), 6},
3654   });
3655   balancers_[0]->ads_service()->SetEdsResource(
3656       AdsServiceImpl::BuildEdsResource(args));
3657   // Backend 3 hasn't received any request.
3658   EXPECT_EQ(0U, backends_[3]->backend_service()->request_count());
3659   // Wait until the locality update has been processed, as signaled by backend 3
3660   // receiving a request.
3661   WaitForAllBackends(3, 4);
3662   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
3663   // Send kNumRpcs RPCs.
3664   CheckRpcSendOk(kNumRpcs);
3665   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
3666   // Backend 0 no longer receives any request.
3667   EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
3668   // The picking rates of the last 3 backends should be roughly equal to the
3669   // expectation.
3670   locality_picked_rates = {0 /* placeholder for backend 0 */};
3671   for (size_t i = 1; i < 4; ++i) {
3672     locality_picked_rates.push_back(
3673         static_cast<double>(backends_[i]->backend_service()->request_count()) /
3674         kNumRpcs);
3675   }
3676   for (size_t i = 1; i < 4; ++i) {
3677     gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
3678             locality_picked_rates[i]);
3679     EXPECT_THAT(
3680         locality_picked_rates[i],
3681         ::testing::AllOf(
3682             ::testing::Ge(locality_weight_rate_1[i] * (1 - kErrorTolerance)),
3683             ::testing::Le(locality_weight_rate_1[i] * (1 + kErrorTolerance))));
3684   }
3685 }
3686 
3687 // Tests that we don't fail RPCs when replacing all of the localities in
3688 // a given priority.
TEST_P(LocalityMapTest,ReplaceAllLocalitiesInPriority)3689 TEST_P(LocalityMapTest, ReplaceAllLocalitiesInPriority) {
3690   SetNextResolution({});
3691   SetNextResolutionForLbChannelAllBalancers();
3692   AdsServiceImpl::EdsResourceArgs args({
3693       {"locality0", GetBackendPorts(0, 1)},
3694   });
3695   balancers_[0]->ads_service()->SetEdsResource(
3696       AdsServiceImpl::BuildEdsResource(args));
3697   args = AdsServiceImpl::EdsResourceArgs({
3698       {"locality1", GetBackendPorts(1, 2)},
3699   });
3700   std::thread delayed_resource_setter(
3701       std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
3702                 AdsServiceImpl::BuildEdsResource(args), 5000));
3703   // Wait for the first backend to be ready.
3704   WaitForBackend(0);
3705   // Keep sending RPCs until we switch over to backend 1, which tells us
3706   // that we received the update.  No RPCs should fail during this
3707   // transition.
3708   WaitForBackend(1, /*reset_counters=*/true, /*require_success=*/true);
3709   delayed_resource_setter.join();
3710 }
3711 
3712 class FailoverTest : public BasicTest {
3713  public:
SetUp()3714   void SetUp() override {
3715     BasicTest::SetUp();
3716     ResetStub(100, "");
3717   }
3718 };
3719 
3720 // Localities with the highest priority are used when multiple priority exist.
TEST_P(FailoverTest,ChooseHighestPriority)3721 TEST_P(FailoverTest, ChooseHighestPriority) {
3722   SetNextResolution({});
3723   SetNextResolutionForLbChannelAllBalancers();
3724   AdsServiceImpl::EdsResourceArgs args({
3725       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
3726       {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
3727       {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
3728       {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
3729   });
3730   balancers_[0]->ads_service()->SetEdsResource(
3731       AdsServiceImpl::BuildEdsResource(args));
3732   WaitForBackend(3, false);
3733   for (size_t i = 0; i < 3; ++i) {
3734     EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
3735   }
3736 }
3737 
3738 // Does not choose priority with no endpoints.
TEST_P(FailoverTest,DoesNotUsePriorityWithNoEndpoints)3739 TEST_P(FailoverTest, DoesNotUsePriorityWithNoEndpoints) {
3740   SetNextResolution({});
3741   SetNextResolutionForLbChannelAllBalancers();
3742   AdsServiceImpl::EdsResourceArgs args({
3743       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
3744       {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
3745       {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
3746       {"locality3", {}, kDefaultLocalityWeight, 0},
3747   });
3748   balancers_[0]->ads_service()->SetEdsResource(
3749       AdsServiceImpl::BuildEdsResource(args));
3750   WaitForBackend(0, false);
3751   for (size_t i = 1; i < 3; ++i) {
3752     EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
3753   }
3754 }
3755 
3756 // Does not choose locality with no endpoints.
TEST_P(FailoverTest,DoesNotUseLocalityWithNoEndpoints)3757 TEST_P(FailoverTest, DoesNotUseLocalityWithNoEndpoints) {
3758   SetNextResolution({});
3759   SetNextResolutionForLbChannelAllBalancers();
3760   AdsServiceImpl::EdsResourceArgs args({
3761       {"locality0", {}, kDefaultLocalityWeight, 0},
3762       {"locality1", GetBackendPorts(), kDefaultLocalityWeight, 0},
3763   });
3764   balancers_[0]->ads_service()->SetEdsResource(
3765       AdsServiceImpl::BuildEdsResource(args));
3766   // Wait for all backends to be used.
3767   std::tuple<int, int, int> counts = WaitForAllBackends();
3768   // Make sure no RPCs failed in the transition.
3769   EXPECT_EQ(0, std::get<1>(counts));
3770 }
3771 
3772 // If the higher priority localities are not reachable, failover to the highest
3773 // priority among the rest.
TEST_P(FailoverTest,Failover)3774 TEST_P(FailoverTest, Failover) {
3775   SetNextResolution({});
3776   SetNextResolutionForLbChannelAllBalancers();
3777   AdsServiceImpl::EdsResourceArgs args({
3778       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
3779       {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
3780       {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
3781       {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
3782   });
3783   ShutdownBackend(3);
3784   ShutdownBackend(0);
3785   balancers_[0]->ads_service()->SetEdsResource(
3786       AdsServiceImpl::BuildEdsResource(args));
3787   WaitForBackend(1, false);
3788   for (size_t i = 0; i < 4; ++i) {
3789     if (i == 1) continue;
3790     EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
3791   }
3792 }
3793 
3794 // If a locality with higher priority than the current one becomes ready,
3795 // switch to it.
TEST_P(FailoverTest,SwitchBackToHigherPriority)3796 TEST_P(FailoverTest, SwitchBackToHigherPriority) {
3797   SetNextResolution({});
3798   SetNextResolutionForLbChannelAllBalancers();
3799   const size_t kNumRpcs = 100;
3800   AdsServiceImpl::EdsResourceArgs args({
3801       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
3802       {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
3803       {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
3804       {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
3805   });
3806   ShutdownBackend(3);
3807   ShutdownBackend(0);
3808   balancers_[0]->ads_service()->SetEdsResource(
3809       AdsServiceImpl::BuildEdsResource(args));
3810   WaitForBackend(1, false);
3811   for (size_t i = 0; i < 4; ++i) {
3812     if (i == 1) continue;
3813     EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
3814   }
3815   StartBackend(0);
3816   WaitForBackend(0);
3817   CheckRpcSendOk(kNumRpcs);
3818   EXPECT_EQ(kNumRpcs, backends_[0]->backend_service()->request_count());
3819 }
3820 
3821 // The first update only contains unavailable priorities. The second update
3822 // contains available priorities.
TEST_P(FailoverTest,UpdateInitialUnavailable)3823 TEST_P(FailoverTest, UpdateInitialUnavailable) {
3824   SetNextResolution({});
3825   SetNextResolutionForLbChannelAllBalancers();
3826   AdsServiceImpl::EdsResourceArgs args({
3827       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
3828       {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
3829   });
3830   balancers_[0]->ads_service()->SetEdsResource(
3831       AdsServiceImpl::BuildEdsResource(args));
3832   args = AdsServiceImpl::EdsResourceArgs({
3833       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
3834       {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
3835       {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 2},
3836       {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
3837   });
3838   ShutdownBackend(0);
3839   ShutdownBackend(1);
3840   std::thread delayed_resource_setter(
3841       std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
3842                 AdsServiceImpl::BuildEdsResource(args), 1000));
3843   gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
3844                                        gpr_time_from_millis(500, GPR_TIMESPAN));
3845   // Send 0.5 second worth of RPCs.
3846   do {
3847     CheckRpcSendFailure();
3848   } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
3849   WaitForBackend(2, false);
3850   for (size_t i = 0; i < 4; ++i) {
3851     if (i == 2) continue;
3852     EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
3853   }
3854   delayed_resource_setter.join();
3855 }
3856 
3857 // Tests that after the localities' priorities are updated, we still choose the
3858 // highest READY priority with the updated localities.
TEST_P(FailoverTest,UpdatePriority)3859 TEST_P(FailoverTest, UpdatePriority) {
3860   SetNextResolution({});
3861   SetNextResolutionForLbChannelAllBalancers();
3862   const size_t kNumRpcs = 100;
3863   AdsServiceImpl::EdsResourceArgs args({
3864       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
3865       {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
3866       {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
3867       {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
3868   });
3869   balancers_[0]->ads_service()->SetEdsResource(
3870       AdsServiceImpl::BuildEdsResource(args));
3871   args = AdsServiceImpl::EdsResourceArgs({
3872       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 2},
3873       {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 0},
3874       {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 1},
3875       {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
3876   });
3877   std::thread delayed_resource_setter(
3878       std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
3879                 AdsServiceImpl::BuildEdsResource(args), 1000));
3880   WaitForBackend(3, false);
3881   for (size_t i = 0; i < 3; ++i) {
3882     EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
3883   }
3884   WaitForBackend(1);
3885   CheckRpcSendOk(kNumRpcs);
3886   EXPECT_EQ(kNumRpcs, backends_[1]->backend_service()->request_count());
3887   delayed_resource_setter.join();
3888 }
3889 
3890 // Moves all localities in the current priority to a higher priority.
TEST_P(FailoverTest,MoveAllLocalitiesInCurrentPriorityToHigherPriority)3891 TEST_P(FailoverTest, MoveAllLocalitiesInCurrentPriorityToHigherPriority) {
3892   SetNextResolution({});
3893   SetNextResolutionForLbChannelAllBalancers();
3894   // First update:
3895   // - Priority 0 is locality 0, containing backend 0, which is down.
3896   // - Priority 1 is locality 1, containing backends 1 and 2, which are up.
3897   ShutdownBackend(0);
3898   AdsServiceImpl::EdsResourceArgs args({
3899       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
3900       {"locality1", GetBackendPorts(1, 3), kDefaultLocalityWeight, 1},
3901   });
3902   balancers_[0]->ads_service()->SetEdsResource(
3903       AdsServiceImpl::BuildEdsResource(args));
3904   // Second update:
3905   // - Priority 0 contains both localities 0 and 1.
3906   // - Priority 1 is not present.
3907   // - We add backend 3 to locality 1, just so we have a way to know
3908   //   when the update has been seen by the client.
3909   args = AdsServiceImpl::EdsResourceArgs({
3910       {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
3911       {"locality1", GetBackendPorts(1, 4), kDefaultLocalityWeight, 0},
3912   });
3913   std::thread delayed_resource_setter(
3914       std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
3915                 AdsServiceImpl::BuildEdsResource(args), 1000));
3916   // When we get the first update, all backends in priority 0 are down,
3917   // so we will create priority 1.  Backends 1 and 2 should have traffic,
3918   // but backend 3 should not.
3919   WaitForAllBackends(1, 3, false);
3920   EXPECT_EQ(0UL, backends_[3]->backend_service()->request_count());
3921   // When backend 3 gets traffic, we know the second update has been seen.
3922   WaitForBackend(3);
3923   // The ADS service of balancer 0 got at least 1 response.
3924   EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
3925             AdsServiceImpl::ResponseState::NOT_SENT);
3926   delayed_resource_setter.join();
3927 }
3928 
3929 using DropTest = BasicTest;
3930 
3931 // Tests that RPCs are dropped according to the drop config.
TEST_P(DropTest,Vanilla)3932 TEST_P(DropTest, Vanilla) {
3933   SetNextResolution({});
3934   SetNextResolutionForLbChannelAllBalancers();
3935   const size_t kNumRpcs = 5000;
3936   const uint32_t kDropPerMillionForLb = 100000;
3937   const uint32_t kDropPerMillionForThrottle = 200000;
3938   const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
3939   const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
3940   const double KDropRateForLbAndThrottle =
3941       kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
3942   // The ADS response contains two drop categories.
3943   AdsServiceImpl::EdsResourceArgs args({
3944       {"locality0", GetBackendPorts()},
3945   });
3946   args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
3947                           {kThrottleDropType, kDropPerMillionForThrottle}};
3948   balancers_[0]->ads_service()->SetEdsResource(
3949       AdsServiceImpl::BuildEdsResource(args));
3950   WaitForAllBackends();
3951   // Send kNumRpcs RPCs and count the drops.
3952   size_t num_drops = 0;
3953   for (size_t i = 0; i < kNumRpcs; ++i) {
3954     EchoResponse response;
3955     const Status status = SendRpc(RpcOptions(), &response);
3956     if (!status.ok() &&
3957         status.error_message() == "Call dropped by load balancing policy") {
3958       ++num_drops;
3959     } else {
3960       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
3961                                << " message=" << status.error_message();
3962       EXPECT_EQ(response.message(), kRequestMessage_);
3963     }
3964   }
3965   // The drop rate should be roughly equal to the expectation.
3966   const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
3967   const double kErrorTolerance = 0.2;
3968   EXPECT_THAT(
3969       seen_drop_rate,
3970       ::testing::AllOf(
3971           ::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
3972           ::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
3973 }
3974 
3975 // Tests that drop config is converted correctly from per hundred.
TEST_P(DropTest,DropPerHundred)3976 TEST_P(DropTest, DropPerHundred) {
3977   SetNextResolution({});
3978   SetNextResolutionForLbChannelAllBalancers();
3979   const size_t kNumRpcs = 5000;
3980   const uint32_t kDropPerHundredForLb = 10;
3981   const double kDropRateForLb = kDropPerHundredForLb / 100.0;
3982   // The ADS response contains one drop category.
3983   AdsServiceImpl::EdsResourceArgs args({
3984       {"locality0", GetBackendPorts()},
3985   });
3986   args.drop_categories = {{kLbDropType, kDropPerHundredForLb}};
3987   args.drop_denominator = FractionalPercent::HUNDRED;
3988   balancers_[0]->ads_service()->SetEdsResource(
3989       AdsServiceImpl::BuildEdsResource(args));
3990   WaitForAllBackends();
3991   // Send kNumRpcs RPCs and count the drops.
3992   size_t num_drops = 0;
3993   for (size_t i = 0; i < kNumRpcs; ++i) {
3994     EchoResponse response;
3995     const Status status = SendRpc(RpcOptions(), &response);
3996     if (!status.ok() &&
3997         status.error_message() == "Call dropped by load balancing policy") {
3998       ++num_drops;
3999     } else {
4000       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
4001                                << " message=" << status.error_message();
4002       EXPECT_EQ(response.message(), kRequestMessage_);
4003     }
4004   }
4005   // The drop rate should be roughly equal to the expectation.
4006   const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
4007   const double kErrorTolerance = 0.2;
4008   EXPECT_THAT(
4009       seen_drop_rate,
4010       ::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
4011                        ::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
4012 }
4013 
4014 // Tests that drop config is converted correctly from per ten thousand.
TEST_P(DropTest,DropPerTenThousand)4015 TEST_P(DropTest, DropPerTenThousand) {
4016   SetNextResolution({});
4017   SetNextResolutionForLbChannelAllBalancers();
4018   const size_t kNumRpcs = 5000;
4019   const uint32_t kDropPerTenThousandForLb = 1000;
4020   const double kDropRateForLb = kDropPerTenThousandForLb / 10000.0;
4021   // The ADS response contains one drop category.
4022   AdsServiceImpl::EdsResourceArgs args({
4023       {"locality0", GetBackendPorts()},
4024   });
4025   args.drop_categories = {{kLbDropType, kDropPerTenThousandForLb}};
4026   args.drop_denominator = FractionalPercent::TEN_THOUSAND;
4027   balancers_[0]->ads_service()->SetEdsResource(
4028       AdsServiceImpl::BuildEdsResource(args));
4029   WaitForAllBackends();
4030   // Send kNumRpcs RPCs and count the drops.
4031   size_t num_drops = 0;
4032   for (size_t i = 0; i < kNumRpcs; ++i) {
4033     EchoResponse response;
4034     const Status status = SendRpc(RpcOptions(), &response);
4035     if (!status.ok() &&
4036         status.error_message() == "Call dropped by load balancing policy") {
4037       ++num_drops;
4038     } else {
4039       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
4040                                << " message=" << status.error_message();
4041       EXPECT_EQ(response.message(), kRequestMessage_);
4042     }
4043   }
4044   // The drop rate should be roughly equal to the expectation.
4045   const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
4046   const double kErrorTolerance = 0.2;
4047   EXPECT_THAT(
4048       seen_drop_rate,
4049       ::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
4050                        ::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
4051 }
4052 
4053 // Tests that drop is working correctly after update.
TEST_P(DropTest,Update)4054 TEST_P(DropTest, Update) {
4055   SetNextResolution({});
4056   SetNextResolutionForLbChannelAllBalancers();
4057   const size_t kNumRpcs = 3000;
4058   const uint32_t kDropPerMillionForLb = 100000;
4059   const uint32_t kDropPerMillionForThrottle = 200000;
4060   const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
4061   const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
4062   const double KDropRateForLbAndThrottle =
4063       kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
4064   // The first ADS response contains one drop category.
4065   AdsServiceImpl::EdsResourceArgs args({
4066       {"locality0", GetBackendPorts()},
4067   });
4068   args.drop_categories = {{kLbDropType, kDropPerMillionForLb}};
4069   balancers_[0]->ads_service()->SetEdsResource(
4070       AdsServiceImpl::BuildEdsResource(args));
4071   WaitForAllBackends();
4072   // Send kNumRpcs RPCs and count the drops.
4073   size_t num_drops = 0;
4074   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
4075   for (size_t i = 0; i < kNumRpcs; ++i) {
4076     EchoResponse response;
4077     const Status status = SendRpc(RpcOptions(), &response);
4078     if (!status.ok() &&
4079         status.error_message() == "Call dropped by load balancing policy") {
4080       ++num_drops;
4081     } else {
4082       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
4083                                << " message=" << status.error_message();
4084       EXPECT_EQ(response.message(), kRequestMessage_);
4085     }
4086   }
4087   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
4088   // The drop rate should be roughly equal to the expectation.
4089   double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
4090   gpr_log(GPR_INFO, "First batch drop rate %f", seen_drop_rate);
4091   const double kErrorTolerance = 0.3;
4092   EXPECT_THAT(
4093       seen_drop_rate,
4094       ::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
4095                        ::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
4096   // The second ADS response contains two drop categories, send an update EDS
4097   // response.
4098   args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
4099                           {kThrottleDropType, kDropPerMillionForThrottle}};
4100   balancers_[0]->ads_service()->SetEdsResource(
4101       AdsServiceImpl::BuildEdsResource(args));
4102   // Wait until the drop rate increases to the middle of the two configs, which
4103   // implies that the update has been in effect.
4104   const double kDropRateThreshold =
4105       (kDropRateForLb + KDropRateForLbAndThrottle) / 2;
4106   size_t num_rpcs = kNumRpcs;
4107   while (seen_drop_rate < kDropRateThreshold) {
4108     EchoResponse response;
4109     const Status status = SendRpc(RpcOptions(), &response);
4110     ++num_rpcs;
4111     if (!status.ok() &&
4112         status.error_message() == "Call dropped by load balancing policy") {
4113       ++num_drops;
4114     } else {
4115       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
4116                                << " message=" << status.error_message();
4117       EXPECT_EQ(response.message(), kRequestMessage_);
4118     }
4119     seen_drop_rate = static_cast<double>(num_drops) / num_rpcs;
4120   }
4121   // Send kNumRpcs RPCs and count the drops.
4122   num_drops = 0;
4123   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
4124   for (size_t i = 0; i < kNumRpcs; ++i) {
4125     EchoResponse response;
4126     const Status status = SendRpc(RpcOptions(), &response);
4127     if (!status.ok() &&
4128         status.error_message() == "Call dropped by load balancing policy") {
4129       ++num_drops;
4130     } else {
4131       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
4132                                << " message=" << status.error_message();
4133       EXPECT_EQ(response.message(), kRequestMessage_);
4134     }
4135   }
4136   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
4137   // The new drop rate should be roughly equal to the expectation.
4138   seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
4139   gpr_log(GPR_INFO, "Second batch drop rate %f", seen_drop_rate);
4140   EXPECT_THAT(
4141       seen_drop_rate,
4142       ::testing::AllOf(
4143           ::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
4144           ::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
4145 }
4146 
4147 // Tests that all the RPCs are dropped if any drop category drops 100%.
TEST_P(DropTest,DropAll)4148 TEST_P(DropTest, DropAll) {
4149   SetNextResolution({});
4150   SetNextResolutionForLbChannelAllBalancers();
4151   const size_t kNumRpcs = 1000;
4152   const uint32_t kDropPerMillionForLb = 100000;
4153   const uint32_t kDropPerMillionForThrottle = 1000000;
4154   // The ADS response contains two drop categories.
4155   AdsServiceImpl::EdsResourceArgs args;
4156   args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
4157                           {kThrottleDropType, kDropPerMillionForThrottle}};
4158   balancers_[0]->ads_service()->SetEdsResource(
4159       AdsServiceImpl::BuildEdsResource(args));
4160   // Send kNumRpcs RPCs and all of them are dropped.
4161   for (size_t i = 0; i < kNumRpcs; ++i) {
4162     EchoResponse response;
4163     const Status status = SendRpc(RpcOptions(), &response);
4164     EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
4165     EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
4166   }
4167 }
4168 
4169 class BalancerUpdateTest : public XdsEnd2endTest {
4170  public:
BalancerUpdateTest()4171   BalancerUpdateTest() : XdsEnd2endTest(4, 3) {}
4172 };
4173 
4174 // Tests that the old LB call is still used after the balancer address update as
4175 // long as that call is still alive.
TEST_P(BalancerUpdateTest,UpdateBalancersButKeepUsingOriginalBalancer)4176 TEST_P(BalancerUpdateTest, UpdateBalancersButKeepUsingOriginalBalancer) {
4177   SetNextResolution({});
4178   SetNextResolutionForLbChannelAllBalancers();
4179   AdsServiceImpl::EdsResourceArgs args({
4180       {"locality0", {backends_[0]->port()}},
4181   });
4182   balancers_[0]->ads_service()->SetEdsResource(
4183       AdsServiceImpl::BuildEdsResource(args));
4184   args = AdsServiceImpl::EdsResourceArgs({
4185       {"locality0", {backends_[1]->port()}},
4186   });
4187   balancers_[1]->ads_service()->SetEdsResource(
4188       AdsServiceImpl::BuildEdsResource(args));
4189   // Wait until the first backend is ready.
4190   WaitForBackend(0);
4191   // Send 10 requests.
4192   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
4193   CheckRpcSendOk(10);
4194   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
4195   // All 10 requests should have gone to the first backend.
4196   EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
4197   // The ADS service of balancer 0 sent at least 1 response.
4198   EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
4199             AdsServiceImpl::ResponseState::NOT_SENT);
4200   EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
4201             AdsServiceImpl::ResponseState::NOT_SENT);
4202   EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
4203             AdsServiceImpl::ResponseState::NOT_SENT);
4204   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
4205   SetNextResolutionForLbChannel({balancers_[1]->port()});
4206   gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
4207   EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
4208   gpr_timespec deadline = gpr_time_add(
4209       gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
4210   // Send 10 seconds worth of RPCs
4211   do {
4212     CheckRpcSendOk();
4213   } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
4214   // The current LB call is still working, so xds continued using it to the
4215   // first balancer, which doesn't assign the second backend.
4216   EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
4217   // The ADS service of balancer 0 sent at least 1 response.
4218   EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
4219             AdsServiceImpl::ResponseState::NOT_SENT);
4220   EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
4221             AdsServiceImpl::ResponseState::NOT_SENT);
4222   EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
4223             AdsServiceImpl::ResponseState::NOT_SENT);
4224 }
4225 
4226 // Tests that the old LB call is still used after multiple balancer address
4227 // updates as long as that call is still alive. Send an update with the same set
4228 // of LBs as the one in SetUp() in order to verify that the LB channel inside
4229 // xds keeps the initial connection (which by definition is also present in the
4230 // update).
TEST_P(BalancerUpdateTest,Repeated)4231 TEST_P(BalancerUpdateTest, Repeated) {
4232   SetNextResolution({});
4233   SetNextResolutionForLbChannelAllBalancers();
4234   AdsServiceImpl::EdsResourceArgs args({
4235       {"locality0", {backends_[0]->port()}},
4236   });
4237   balancers_[0]->ads_service()->SetEdsResource(
4238       AdsServiceImpl::BuildEdsResource(args));
4239   args = AdsServiceImpl::EdsResourceArgs({
4240       {"locality0", {backends_[1]->port()}},
4241   });
4242   balancers_[1]->ads_service()->SetEdsResource(
4243       AdsServiceImpl::BuildEdsResource(args));
4244   // Wait until the first backend is ready.
4245   WaitForBackend(0);
4246   // Send 10 requests.
4247   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
4248   CheckRpcSendOk(10);
4249   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
4250   // All 10 requests should have gone to the first backend.
4251   EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
4252   // The ADS service of balancer 0 sent at least 1 response.
4253   EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
4254             AdsServiceImpl::ResponseState::NOT_SENT);
4255   EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
4256             AdsServiceImpl::ResponseState::NOT_SENT);
4257   EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
4258             AdsServiceImpl::ResponseState::NOT_SENT);
4259   std::vector<int> ports;
4260   ports.emplace_back(balancers_[0]->port());
4261   ports.emplace_back(balancers_[1]->port());
4262   ports.emplace_back(balancers_[2]->port());
4263   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
4264   SetNextResolutionForLbChannel(ports);
4265   gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
4266   EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
4267   gpr_timespec deadline = gpr_time_add(
4268       gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
4269   // Send 10 seconds worth of RPCs
4270   do {
4271     CheckRpcSendOk();
4272   } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
4273   // xds continued using the original LB call to the first balancer, which
4274   // doesn't assign the second backend.
4275   EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
4276   ports.clear();
4277   ports.emplace_back(balancers_[0]->port());
4278   ports.emplace_back(balancers_[1]->port());
4279   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
4280   SetNextResolutionForLbChannel(ports);
4281   gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
4282   EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
4283   deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
4284                           gpr_time_from_millis(10000, GPR_TIMESPAN));
4285   // Send 10 seconds worth of RPCs
4286   do {
4287     CheckRpcSendOk();
4288   } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
4289   // xds continued using the original LB call to the first balancer, which
4290   // doesn't assign the second backend.
4291   EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
4292 }
4293 
4294 // Tests that if the balancer is down, the RPCs will still be sent to the
4295 // backends according to the last balancer response, until a new balancer is
4296 // reachable.
TEST_P(BalancerUpdateTest,DeadUpdate)4297 TEST_P(BalancerUpdateTest, DeadUpdate) {
4298   SetNextResolution({});
4299   SetNextResolutionForLbChannel({balancers_[0]->port()});
4300   AdsServiceImpl::EdsResourceArgs args({
4301       {"locality0", {backends_[0]->port()}},
4302   });
4303   balancers_[0]->ads_service()->SetEdsResource(
4304       AdsServiceImpl::BuildEdsResource(args));
4305   args = AdsServiceImpl::EdsResourceArgs({
4306       {"locality0", {backends_[1]->port()}},
4307   });
4308   balancers_[1]->ads_service()->SetEdsResource(
4309       AdsServiceImpl::BuildEdsResource(args));
4310   // Start servers and send 10 RPCs per server.
4311   gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
4312   CheckRpcSendOk(10);
4313   gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
4314   // All 10 requests should have gone to the first backend.
4315   EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
4316   // The ADS service of balancer 0 sent at least 1 response.
4317   EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
4318             AdsServiceImpl::ResponseState::NOT_SENT);
4319   EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
4320             AdsServiceImpl::ResponseState::NOT_SENT);
4321   EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
4322             AdsServiceImpl::ResponseState::NOT_SENT);
4323   // Kill balancer 0
4324   gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
4325   balancers_[0]->Shutdown();
4326   gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
4327   // This is serviced by the existing child policy.
4328   gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
4329   CheckRpcSendOk(10);
4330   gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
4331   // All 10 requests should again have gone to the first backend.
4332   EXPECT_EQ(20U, backends_[0]->backend_service()->request_count());
4333   EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
4334   // The ADS service of no balancers sent anything
4335   EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
4336             AdsServiceImpl::ResponseState::NOT_SENT);
4337   EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
4338             AdsServiceImpl::ResponseState::NOT_SENT);
4339   EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
4340             AdsServiceImpl::ResponseState::NOT_SENT);
4341   gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
4342   SetNextResolutionForLbChannel({balancers_[1]->port()});
4343   gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
4344   // Wait until update has been processed, as signaled by the second backend
4345   // receiving a request. In the meantime, the client continues to be serviced
4346   // (by the first backend) without interruption.
4347   EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
4348   WaitForBackend(1);
4349   // This is serviced by the updated RR policy
4350   backends_[1]->backend_service()->ResetCounters();
4351   gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
4352   CheckRpcSendOk(10);
4353   gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
4354   // All 10 requests should have gone to the second backend.
4355   EXPECT_EQ(10U, backends_[1]->backend_service()->request_count());
4356   // The ADS service of balancer 1 sent at least 1 response.
4357   EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
4358             AdsServiceImpl::ResponseState::NOT_SENT);
4359   EXPECT_GT(balancers_[1]->ads_service()->eds_response_state().state,
4360             AdsServiceImpl::ResponseState::NOT_SENT);
4361   EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
4362             AdsServiceImpl::ResponseState::NOT_SENT);
4363 }
4364 
4365 // The re-resolution tests are deferred because they rely on the fallback mode,
4366 // which hasn't been supported.
4367 
4368 // TODO(juanlishen): Add TEST_P(BalancerUpdateTest, ReresolveDeadBackend).
4369 
4370 // TODO(juanlishen): Add TEST_P(UpdatesWithClientLoadReportingTest,
4371 // ReresolveDeadBalancer)
4372 
4373 class ClientLoadReportingTest : public XdsEnd2endTest {
4374  public:
ClientLoadReportingTest()4375   ClientLoadReportingTest() : XdsEnd2endTest(4, 1, 3) {}
4376 };
4377 
4378 // Tests that the load report received at the balancer is correct.
TEST_P(ClientLoadReportingTest,Vanilla)4379 TEST_P(ClientLoadReportingTest, Vanilla) {
4380   SetNextResolution({});
4381   SetNextResolutionForLbChannel({balancers_[0]->port()});
4382   const size_t kNumRpcsPerAddress = 10;
4383   const size_t kNumFailuresPerAddress = 3;
4384   // TODO(juanlishen): Partition the backends after multiple localities is
4385   // tested.
4386   AdsServiceImpl::EdsResourceArgs args({
4387       {"locality0", GetBackendPorts()},
4388   });
4389   balancers_[0]->ads_service()->SetEdsResource(
4390       AdsServiceImpl::BuildEdsResource(args));
4391   // Wait until all backends are ready.
4392   int num_ok = 0;
4393   int num_failure = 0;
4394   int num_drops = 0;
4395   std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
4396   // Send kNumRpcsPerAddress RPCs per server.
4397   CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
4398   CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
4399                       /*server_fail=*/true);
4400   // Check that each backend got the right number of requests.
4401   for (size_t i = 0; i < backends_.size(); ++i) {
4402     EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
4403               backends_[i]->backend_service()->request_count());
4404   }
4405   // The load report received at the balancer should be correct.
4406   std::vector<ClientStats> load_report =
4407       balancers_[0]->lrs_service()->WaitForLoadReport();
4408   ASSERT_EQ(load_report.size(), 1UL);
4409   ClientStats& client_stats = load_report.front();
4410   EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
4411             client_stats.total_successful_requests());
4412   EXPECT_EQ(0U, client_stats.total_requests_in_progress());
4413   EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
4414                 num_ok + num_failure,
4415             client_stats.total_issued_requests());
4416   EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
4417             client_stats.total_error_requests());
4418   EXPECT_EQ(0U, client_stats.total_dropped_requests());
4419   // The LRS service got a single request, and sent a single response.
4420   EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
4421   EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
4422 }
4423 
4424 // Tests send_all_clusters.
TEST_P(ClientLoadReportingTest,SendAllClusters)4425 TEST_P(ClientLoadReportingTest, SendAllClusters) {
4426   balancers_[0]->lrs_service()->set_send_all_clusters(true);
4427   SetNextResolution({});
4428   SetNextResolutionForLbChannel({balancers_[0]->port()});
4429   const size_t kNumRpcsPerAddress = 10;
4430   const size_t kNumFailuresPerAddress = 3;
4431   // TODO(juanlishen): Partition the backends after multiple localities is
4432   // tested.
4433   AdsServiceImpl::EdsResourceArgs args({
4434       {"locality0", GetBackendPorts()},
4435   });
4436   balancers_[0]->ads_service()->SetEdsResource(
4437       AdsServiceImpl::BuildEdsResource(args));
4438   // Wait until all backends are ready.
4439   int num_ok = 0;
4440   int num_failure = 0;
4441   int num_drops = 0;
4442   std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
4443   // Send kNumRpcsPerAddress RPCs per server.
4444   CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
4445   CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
4446                       /*server_fail=*/true);
4447   // Check that each backend got the right number of requests.
4448   for (size_t i = 0; i < backends_.size(); ++i) {
4449     EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
4450               backends_[i]->backend_service()->request_count());
4451   }
4452   // The load report received at the balancer should be correct.
4453   std::vector<ClientStats> load_report =
4454       balancers_[0]->lrs_service()->WaitForLoadReport();
4455   ASSERT_EQ(load_report.size(), 1UL);
4456   ClientStats& client_stats = load_report.front();
4457   EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
4458             client_stats.total_successful_requests());
4459   EXPECT_EQ(0U, client_stats.total_requests_in_progress());
4460   EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
4461                 num_ok + num_failure,
4462             client_stats.total_issued_requests());
4463   EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
4464             client_stats.total_error_requests());
4465   EXPECT_EQ(0U, client_stats.total_dropped_requests());
4466   // The LRS service got a single request, and sent a single response.
4467   EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
4468   EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
4469 }
4470 
4471 // Tests that we don't include stats for clusters that are not requested
4472 // by the LRS server.
TEST_P(ClientLoadReportingTest,HonorsClustersRequestedByLrsServer)4473 TEST_P(ClientLoadReportingTest, HonorsClustersRequestedByLrsServer) {
4474   balancers_[0]->lrs_service()->set_cluster_names({"bogus"});
4475   SetNextResolution({});
4476   SetNextResolutionForLbChannel({balancers_[0]->port()});
4477   const size_t kNumRpcsPerAddress = 100;
4478   AdsServiceImpl::EdsResourceArgs args({
4479       {"locality0", GetBackendPorts()},
4480   });
4481   balancers_[0]->ads_service()->SetEdsResource(
4482       AdsServiceImpl::BuildEdsResource(args));
4483   // Wait until all backends are ready.
4484   int num_ok = 0;
4485   int num_failure = 0;
4486   int num_drops = 0;
4487   std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
4488   // Send kNumRpcsPerAddress RPCs per server.
4489   CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
4490   // Each backend should have gotten 100 requests.
4491   for (size_t i = 0; i < backends_.size(); ++i) {
4492     EXPECT_EQ(kNumRpcsPerAddress,
4493               backends_[i]->backend_service()->request_count());
4494   }
4495   // The LRS service got a single request, and sent a single response.
4496   EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
4497   EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
4498   // The load report received at the balancer should be correct.
4499   std::vector<ClientStats> load_report =
4500       balancers_[0]->lrs_service()->WaitForLoadReport();
4501   ASSERT_EQ(load_report.size(), 0UL);
4502 }
4503 
4504 // Tests that if the balancer restarts, the client load report contains the
4505 // stats before and after the restart correctly.
TEST_P(ClientLoadReportingTest,BalancerRestart)4506 TEST_P(ClientLoadReportingTest, BalancerRestart) {
4507   SetNextResolution({});
4508   SetNextResolutionForLbChannel({balancers_[0]->port()});
4509   const size_t kNumBackendsFirstPass = backends_.size() / 2;
4510   const size_t kNumBackendsSecondPass =
4511       backends_.size() - kNumBackendsFirstPass;
4512   AdsServiceImpl::EdsResourceArgs args({
4513       {"locality0", GetBackendPorts(0, kNumBackendsFirstPass)},
4514   });
4515   balancers_[0]->ads_service()->SetEdsResource(
4516       AdsServiceImpl::BuildEdsResource(args));
4517   // Wait until all backends returned by the balancer are ready.
4518   int num_ok = 0;
4519   int num_failure = 0;
4520   int num_drops = 0;
4521   std::tie(num_ok, num_failure, num_drops) =
4522       WaitForAllBackends(/* start_index */ 0,
4523                          /* stop_index */ kNumBackendsFirstPass);
4524   std::vector<ClientStats> load_report =
4525       balancers_[0]->lrs_service()->WaitForLoadReport();
4526   ASSERT_EQ(load_report.size(), 1UL);
4527   ClientStats client_stats = std::move(load_report.front());
4528   EXPECT_EQ(static_cast<size_t>(num_ok),
4529             client_stats.total_successful_requests());
4530   EXPECT_EQ(0U, client_stats.total_requests_in_progress());
4531   EXPECT_EQ(0U, client_stats.total_error_requests());
4532   EXPECT_EQ(0U, client_stats.total_dropped_requests());
4533   // Shut down the balancer.
4534   balancers_[0]->Shutdown();
4535   // We should continue using the last EDS response we received from the
4536   // balancer before it was shut down.
4537   // Note: We need to use WaitForAllBackends() here instead of just
4538   // CheckRpcSendOk(kNumBackendsFirstPass), because when the balancer
4539   // shuts down, the XdsClient will generate an error to the
4540   // ServiceConfigWatcher, which will cause the xds resolver to send a
4541   // no-op update to the LB policy.  When this update gets down to the
4542   // round_robin child policy for the locality, it will generate a new
4543   // subchannel list, which resets the start index randomly.  So we need
4544   // to be a little more permissive here to avoid spurious failures.
4545   ResetBackendCounters();
4546   int num_started = std::get<0>(WaitForAllBackends(
4547       /* start_index */ 0, /* stop_index */ kNumBackendsFirstPass));
4548   // Now restart the balancer, this time pointing to the new backends.
4549   balancers_[0]->Start();
4550   args = AdsServiceImpl::EdsResourceArgs({
4551       {"locality0", GetBackendPorts(kNumBackendsFirstPass)},
4552   });
4553   balancers_[0]->ads_service()->SetEdsResource(
4554       AdsServiceImpl::BuildEdsResource(args));
4555   // Wait for queries to start going to one of the new backends.
4556   // This tells us that we're now using the new serverlist.
4557   std::tie(num_ok, num_failure, num_drops) =
4558       WaitForAllBackends(/* start_index */ kNumBackendsFirstPass);
4559   num_started += num_ok + num_failure + num_drops;
4560   // Send one RPC per backend.
4561   CheckRpcSendOk(kNumBackendsSecondPass);
4562   num_started += kNumBackendsSecondPass;
4563   // Check client stats.
4564   load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
4565   ASSERT_EQ(load_report.size(), 1UL);
4566   client_stats = std::move(load_report.front());
4567   EXPECT_EQ(num_started, client_stats.total_successful_requests());
4568   EXPECT_EQ(0U, client_stats.total_requests_in_progress());
4569   EXPECT_EQ(0U, client_stats.total_error_requests());
4570   EXPECT_EQ(0U, client_stats.total_dropped_requests());
4571 }
4572 
4573 class ClientLoadReportingWithDropTest : public XdsEnd2endTest {
4574  public:
ClientLoadReportingWithDropTest()4575   ClientLoadReportingWithDropTest() : XdsEnd2endTest(4, 1, 20) {}
4576 };
4577 
4578 // Tests that the drop stats are correctly reported by client load reporting.
TEST_P(ClientLoadReportingWithDropTest,Vanilla)4579 TEST_P(ClientLoadReportingWithDropTest, Vanilla) {
4580   SetNextResolution({});
4581   SetNextResolutionForLbChannelAllBalancers();
4582   const size_t kNumRpcs = 3000;
4583   const uint32_t kDropPerMillionForLb = 100000;
4584   const uint32_t kDropPerMillionForThrottle = 200000;
4585   const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
4586   const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
4587   const double KDropRateForLbAndThrottle =
4588       kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
4589   // The ADS response contains two drop categories.
4590   AdsServiceImpl::EdsResourceArgs args({
4591       {"locality0", GetBackendPorts()},
4592   });
4593   args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
4594                           {kThrottleDropType, kDropPerMillionForThrottle}};
4595   balancers_[0]->ads_service()->SetEdsResource(
4596       AdsServiceImpl::BuildEdsResource(args));
4597   int num_ok = 0;
4598   int num_failure = 0;
4599   int num_drops = 0;
4600   std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
4601   const size_t num_warmup = num_ok + num_failure + num_drops;
4602   // Send kNumRpcs RPCs and count the drops.
4603   for (size_t i = 0; i < kNumRpcs; ++i) {
4604     EchoResponse response;
4605     const Status status = SendRpc(RpcOptions(), &response);
4606     if (!status.ok() &&
4607         status.error_message() == "Call dropped by load balancing policy") {
4608       ++num_drops;
4609     } else {
4610       EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
4611                                << " message=" << status.error_message();
4612       EXPECT_EQ(response.message(), kRequestMessage_);
4613     }
4614   }
4615   // The drop rate should be roughly equal to the expectation.
4616   const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
4617   const double kErrorTolerance = 0.2;
4618   EXPECT_THAT(
4619       seen_drop_rate,
4620       ::testing::AllOf(
4621           ::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
4622           ::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
4623   // Check client stats.
4624   std::vector<ClientStats> load_report =
4625       balancers_[0]->lrs_service()->WaitForLoadReport();
4626   ASSERT_EQ(load_report.size(), 1UL);
4627   ClientStats& client_stats = load_report.front();
4628   EXPECT_EQ(num_drops, client_stats.total_dropped_requests());
4629   const size_t total_rpc = num_warmup + kNumRpcs;
4630   EXPECT_THAT(
4631       client_stats.dropped_requests(kLbDropType),
4632       ::testing::AllOf(
4633           ::testing::Ge(total_rpc * kDropRateForLb * (1 - kErrorTolerance)),
4634           ::testing::Le(total_rpc * kDropRateForLb * (1 + kErrorTolerance))));
4635   EXPECT_THAT(client_stats.dropped_requests(kThrottleDropType),
4636               ::testing::AllOf(
4637                   ::testing::Ge(total_rpc * (1 - kDropRateForLb) *
4638                                 kDropRateForThrottle * (1 - kErrorTolerance)),
4639                   ::testing::Le(total_rpc * (1 - kDropRateForLb) *
4640                                 kDropRateForThrottle * (1 + kErrorTolerance))));
4641 }
4642 
TestTypeName(const::testing::TestParamInfo<TestType> & info)4643 grpc::string TestTypeName(const ::testing::TestParamInfo<TestType>& info) {
4644   return info.param.AsString();
4645 }
4646 
4647 INSTANTIATE_TEST_SUITE_P(XdsTest, BasicTest,
4648                          ::testing::Values(TestType(false, true),
4649                                            TestType(false, false),
4650                                            TestType(true, false),
4651                                            TestType(true, true)),
4652                          &TestTypeName);
4653 
4654 INSTANTIATE_TEST_SUITE_P(XdsTest, SecureNamingTest,
4655                          ::testing::Values(TestType(false, true),
4656                                            TestType(false, false),
4657                                            TestType(true, false),
4658                                            TestType(true, true)),
4659                          &TestTypeName);
4660 
4661 // LDS depends on XdsResolver.
4662 INSTANTIATE_TEST_SUITE_P(XdsTest, LdsTest,
4663                          ::testing::Values(TestType(true, false),
4664                                            TestType(true, true)),
4665                          &TestTypeName);
4666 
4667 // LDS RDS Commmon tests  depends on XdsResolver.
4668 INSTANTIATE_TEST_SUITE_P(XdsTest, LdsRdsTest,
4669                          ::testing::Values(TestType(true, false),
4670                                            TestType(true, true),
4671                                            TestType(true, false, true),
4672                                            TestType(true, true, true)),
4673                          &TestTypeName);
4674 
4675 // CDS depends on XdsResolver.
4676 INSTANTIATE_TEST_SUITE_P(XdsTest, CdsTest,
4677                          ::testing::Values(TestType(true, false),
4678                                            TestType(true, true)),
4679                          &TestTypeName);
4680 
4681 // EDS could be tested with or without XdsResolver, but the tests would
4682 // be the same either way, so we test it only with XdsResolver.
4683 INSTANTIATE_TEST_SUITE_P(XdsTest, EdsTest,
4684                          ::testing::Values(TestType(true, false),
4685                                            TestType(true, true)),
4686                          &TestTypeName);
4687 
4688 // XdsResolverOnlyTest depends on XdsResolver.
4689 INSTANTIATE_TEST_SUITE_P(XdsTest, XdsResolverOnlyTest,
4690                          ::testing::Values(TestType(true, false),
4691                                            TestType(true, true)),
4692                          &TestTypeName);
4693 
4694 // XdsResolverLoadReprtingOnlyTest depends on XdsResolver and load reporting.
4695 INSTANTIATE_TEST_SUITE_P(XdsTest, XdsResolverLoadReportingOnlyTest,
4696                          ::testing::Values(TestType(true, true)),
4697                          &TestTypeName);
4698 
4699 INSTANTIATE_TEST_SUITE_P(XdsTest, LocalityMapTest,
4700                          ::testing::Values(TestType(false, true),
4701                                            TestType(false, false),
4702                                            TestType(true, false),
4703                                            TestType(true, true)),
4704                          &TestTypeName);
4705 
4706 INSTANTIATE_TEST_SUITE_P(XdsTest, FailoverTest,
4707                          ::testing::Values(TestType(false, true),
4708                                            TestType(false, false),
4709                                            TestType(true, false),
4710                                            TestType(true, true)),
4711                          &TestTypeName);
4712 
4713 INSTANTIATE_TEST_SUITE_P(XdsTest, DropTest,
4714                          ::testing::Values(TestType(false, true),
4715                                            TestType(false, false),
4716                                            TestType(true, false),
4717                                            TestType(true, true)),
4718                          &TestTypeName);
4719 
4720 INSTANTIATE_TEST_SUITE_P(XdsTest, BalancerUpdateTest,
4721                          ::testing::Values(TestType(false, true),
4722                                            TestType(false, false),
4723                                            TestType(true, true)),
4724                          &TestTypeName);
4725 
4726 // Load reporting tests are not run with load reporting disabled.
4727 INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingTest,
4728                          ::testing::Values(TestType(false, true),
4729                                            TestType(true, true)),
4730                          &TestTypeName);
4731 
4732 // Load reporting tests are not run with load reporting disabled.
4733 INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingWithDropTest,
4734                          ::testing::Values(TestType(false, true),
4735                                            TestType(true, true)),
4736                          &TestTypeName);
4737 
4738 }  // namespace
4739 }  // namespace testing
4740 }  // namespace grpc
4741 
main(int argc,char ** argv)4742 int main(int argc, char** argv) {
4743   grpc::testing::TestEnvironment env(argc, argv);
4744   ::testing::InitGoogleTest(&argc, argv);
4745   grpc::testing::WriteBootstrapFiles();
4746   grpc::testing::g_port_saver = new grpc::testing::PortSaver();
4747   const auto result = RUN_ALL_TESTS();
4748   return result;
4749 }
4750