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