Debian Codegraph @

test/cpp/end2end/xds/xds_end2end_test_lib.cc

raw
1 // Copyright 2017 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15
16 #include "test/cpp/end2end/xds/xds_end2end_test_lib.h"
17
18 #include <functional>
19 #include <map>
20 #include <memory>
21 #include <set>
22 #include <string>
23 #include <thread>
24 #include <vector>
25
26 #include <gmock/gmock.h>
27 #include <gtest/gtest.h>
28
29 #include "absl/memory/memory.h"
30 #include "absl/strings/str_cat.h"
31 #include "absl/strings/str_format.h"
32 #include "absl/strings/str_join.h"
33 #include "absl/strings/str_replace.h"
34 #include "absl/strings/string_view.h"
35 #include "absl/types/optional.h"
36
37 #include <grpcpp/security/tls_certificate_provider.h>
38
39 #include "src/core/ext/filters/http/server/http_server_filter.h"
40 #include "src/core/ext/xds/xds_channel_args.h"
41 #include "src/core/ext/xds/xds_client_grpc.h"
42 #include "src/core/lib/gpr/tmpfile.h"
43 #include "src/core/lib/gprpp/env.h"
44 #include "src/core/lib/iomgr/load_file.h"
45 #include "src/core/lib/surface/server.h"
46 #include "src/cpp/client/secure_credentials.h"
47 #include "src/proto/grpc/testing/xds/v3/router.grpc.pb.h"
48 #include "test/core/util/resolve_localhost_ip46.h"
49 #include "test/cpp/util/tls_test_utils.h"
50
51 namespace grpc {
52 namespace testing {
53
54 using ::envoy::config::endpoint::v3::ClusterLoadAssignment;
55 using ::envoy::config::endpoint::v3::HealthStatus;
56 using ::envoy::config::listener::v3::Listener;
57 using ::envoy::extensions::filters::network::http_connection_manager::v3::
58 HttpConnectionManager;
59
60 using ::grpc::experimental::ExternalCertificateVerifier;
61 using ::grpc::experimental::IdentityKeyCertPair;
62 using ::grpc::experimental::StaticDataCertificateProvider;
63
64 //
65 // XdsEnd2endTest::ServerThread::XdsServingStatusNotifier
66 //
67
68 void XdsEnd2endTest::ServerThread::XdsServingStatusNotifier::
69 OnServingStatusUpdate(std::string uri, ServingStatusUpdate update) {
70 grpc_core::MutexLock lock(&mu_);
71 status_map[uri] = update.status;
72 cond_.Signal();
73 }
74
75 void XdsEnd2endTest::ServerThread::XdsServingStatusNotifier::
76 WaitOnServingStatusChange(std::string uri,
77 grpc::StatusCode expected_status) {
78 grpc_core::MutexLock lock(&mu_);
79 std::map<std::string, grpc::Status>::iterator it;
80 while ((it = status_map.find(uri)) == status_map.end() ||
81 it->second.error_code() != expected_status) {
82 cond_.Wait(&mu_);
83 }
84 }
85
86 //
87 // XdsEnd2endTest::ServerThread::XdsChannelArgsServerBuilderOption
88 //
89
90 namespace {
91
92 // Channel arg pointer vtable for storing xDS channel args in the parent
93 // channel's channel args.
94 void* ChannelArgsArgCopy(void* p) {
95 auto* args = static_cast<grpc_channel_args*>(p);
96 return grpc_channel_args_copy(args);
97 }
98 void ChannelArgsArgDestroy(void* p) {
99 auto* args = static_cast<grpc_channel_args*>(p);
100 grpc_channel_args_destroy(args);
101 }
102 int ChannelArgsArgCmp(void* a, void* b) {
103 auto* args_a = static_cast<grpc_channel_args*>(a);
104 auto* args_b = static_cast<grpc_channel_args*>(b);
105 return grpc_channel_args_compare(args_a, args_b);
106 }
107 const grpc_arg_pointer_vtable kChannelArgsArgVtable = {
108 ChannelArgsArgCopy, ChannelArgsArgDestroy, ChannelArgsArgCmp};
109
110 } // namespace
111
112 class XdsEnd2endTest::ServerThread::XdsChannelArgsServerBuilderOption
113 : public grpc::ServerBuilderOption {
114 public:
115 explicit XdsChannelArgsServerBuilderOption(XdsEnd2endTest* test_obj)
116 : test_obj_(test_obj) {}
117
118 void UpdateArguments(grpc::ChannelArguments* args) override {
119 args->SetString(GRPC_ARG_TEST_ONLY_DO_NOT_USE_IN_PROD_XDS_BOOTSTRAP_CONFIG,
120 test_obj_->bootstrap_);
121 args->SetPointerWithVtable(
122 GRPC_ARG_TEST_ONLY_DO_NOT_USE_IN_PROD_XDS_CLIENT_CHANNEL_ARGS,
123 &test_obj_->xds_channel_args_, &kChannelArgsArgVtable);
124 }
125
126 void UpdatePlugins(
127 std::vector<std::unique_ptr<grpc::ServerBuilderPlugin>>* /*plugins*/)
128 override {}
129
130 private:
131 XdsEnd2endTest* test_obj_;
132 };
133
134 //
135 // XdsEnd2endTest::ServerThread
136 //
137
138 void XdsEnd2endTest::ServerThread::Start() {
139 gpr_log(GPR_INFO, "starting %s server on port %d", Type(), port_);
140 GPR_ASSERT(!running_);
141 running_ = true;
142 StartAllServices();
143 grpc_core::Mutex mu;
144 // We need to acquire the lock here in order to prevent the notify_one
145 // by ServerThread::Serve from firing before the wait below is hit.
146 grpc_core::MutexLock lock(&mu);
147 grpc_core::CondVar cond;
148 thread_ = std::make_unique<std::thread>(
149 std::bind(&ServerThread::Serve, this, &mu, &cond));
150 cond.Wait(&mu);
151 gpr_log(GPR_INFO, "%s server startup complete", Type());
152 }
153
154 void XdsEnd2endTest::ServerThread::Shutdown() {
155 if (!running_) return;
156 gpr_log(GPR_INFO, "%s about to shutdown", Type());
157 ShutdownAllServices();
158 server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
159 thread_->join();
160 gpr_log(GPR_INFO, "%s shutdown completed", Type());
161 running_ = false;
162 }
163
164 void XdsEnd2endTest::ServerThread::StopListeningAndSendGoaways() {
165 gpr_log(GPR_INFO, "%s sending GOAWAYs", Type());
166 {
167 grpc_core::ExecCtx exec_ctx;
168 auto* server = grpc_core::Server::FromC(server_->c_server());
169 server->StopListening();
170 server->SendGoaways();
171 }
172 gpr_log(GPR_INFO, "%s done sending GOAWAYs", Type());
173 }
174
175 void XdsEnd2endTest::ServerThread::Serve(grpc_core::Mutex* mu,
176 grpc_core::CondVar* cond) {
177 // We need to acquire the lock here in order to prevent the notify_one
178 // below from firing before its corresponding wait is executed.
179 grpc_core::MutexLock lock(mu);
180 std::string server_address = absl::StrCat("localhost:", port_);
181 if (use_xds_enabled_server_) {
182 XdsServerBuilder builder;
183 if (GetParam().bootstrap_source() ==
184 XdsTestType::kBootstrapFromChannelArg) {
185 builder.SetOption(
186 std::make_unique<XdsChannelArgsServerBuilderOption>(test_obj_));
187 }
188 builder.set_status_notifier(&notifier_);
189 builder.experimental().set_drain_grace_time(
190 test_obj_->xds_drain_grace_time_ms_);
191 builder.AddListeningPort(server_address, Credentials());
192 // Allow gRPC Core's HTTP server to accept PUT requests for testing
193 // purposes.
194 if (allow_put_requests_) {
195 builder.AddChannelArgument(
196 GRPC_ARG_DO_NOT_USE_UNLESS_YOU_HAVE_PERMISSION_FROM_GRPC_TEAM_ALLOW_BROKEN_PUT_REQUESTS,
197 true);
198 }
199 RegisterAllServices(&builder);
200 server_ = builder.BuildAndStart();
201 } else {
202 ServerBuilder builder;
203 builder.AddListeningPort(server_address, Credentials());
204 RegisterAllServices(&builder);
205 server_ = builder.BuildAndStart();
206 }
207 cond->Signal();
208 }
209
210 //
211 // XdsEnd2endTest::BackendServerThread
212 //
213
214 XdsEnd2endTest::BackendServerThread::BackendServerThread(
215 XdsEnd2endTest* test_obj, bool use_xds_enabled_server)
216 : ServerThread(test_obj, use_xds_enabled_server) {
217 if (use_xds_enabled_server) {
218 test_obj->SetServerListenerNameAndRouteConfiguration(
219 test_obj->balancer_.get(), test_obj->default_server_listener_, port(),
220 test_obj->default_server_route_config_);
221 }
222 }
223
224 std::shared_ptr<ServerCredentials>
225 XdsEnd2endTest::BackendServerThread::Credentials() {
226 if (GetParam().use_xds_credentials()) {
227 if (use_xds_enabled_server()) {
228 // We are testing server's use of XdsServerCredentials
229 return XdsServerCredentials(InsecureServerCredentials());
230 } else {
231 // We are testing client's use of XdsCredentials
232 std::string root_cert = ReadFile(kCaCertPath);
233 std::string identity_cert = ReadFile(kServerCertPath);
234 std::string private_key = ReadFile(kServerKeyPath);
235 std::vector<experimental::IdentityKeyCertPair> identity_key_cert_pairs = {
236 {private_key, identity_cert}};
237 auto certificate_provider =
238 std::make_shared<grpc::experimental::StaticDataCertificateProvider>(
239 root_cert, identity_key_cert_pairs);
240 grpc::experimental::TlsServerCredentialsOptions options(
241 certificate_provider);
242 options.watch_root_certs();
243 options.watch_identity_key_cert_pairs();
244 options.set_cert_request_type(
245 GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY);
246 return grpc::experimental::TlsServerCredentials(options);
247 }
248 }
249 return ServerThread::Credentials();
250 }
251
252 void XdsEnd2endTest::BackendServerThread::RegisterAllServices(
253 ServerBuilder* builder) {
254 builder->RegisterService(&backend_service_);
255 builder->RegisterService(&backend_service1_);
256 builder->RegisterService(&backend_service2_);
257 }
258
259 void XdsEnd2endTest::BackendServerThread::StartAllServices() {
260 backend_service_.Start();
261 backend_service1_.Start();
262 backend_service2_.Start();
263 }
264
265 void XdsEnd2endTest::BackendServerThread::ShutdownAllServices() {
266 backend_service_.Shutdown();
267 backend_service1_.Shutdown();
268 backend_service2_.Shutdown();
269 }
270
271 //
272 // XdsEnd2endTest::BalancerServerThread
273 //
274
275 XdsEnd2endTest::BalancerServerThread::BalancerServerThread(
276 XdsEnd2endTest* test_obj)
277 : ServerThread(test_obj, /*use_xds_enabled_server=*/false),
278 ads_service_(new AdsServiceImpl()),
279 lrs_service_(new LrsServiceImpl(
280 (GetParam().enable_load_reporting() ? 20 * grpc_test_slowdown_factor()
281 : 0),
282 {kDefaultClusterName})) {}
283
284 void XdsEnd2endTest::BalancerServerThread::RegisterAllServices(
285 ServerBuilder* builder) {
286 builder->RegisterService(ads_service_.get());
287 builder->RegisterService(lrs_service_.get());
288 }
289
290 void XdsEnd2endTest::BalancerServerThread::StartAllServices() {
291 ads_service_->Start();
292 lrs_service_->Start();
293 }
294
295 void XdsEnd2endTest::BalancerServerThread::ShutdownAllServices() {
296 ads_service_->Shutdown();
297 lrs_service_->Shutdown();
298 }
299
300 //
301 // XdsEnd2endTest::BootstrapBuilder
302 //
303
304 std::string XdsEnd2endTest::BootstrapBuilder::Build() {
305 std::vector<std::string> fields;
306 fields.push_back(MakeXdsServersText(top_server_));
307 if (!client_default_listener_resource_name_template_.empty()) {
308 fields.push_back(
309 absl::StrCat(" \"client_default_listener_resource_name_template\": \"",
310 client_default_listener_resource_name_template_, "\""));
311 }
312 fields.push_back(MakeNodeText());
313 if (!server_listener_resource_name_template_.empty()) {
314 fields.push_back(
315 absl::StrCat(" \"server_listener_resource_name_template\": \"",
316 server_listener_resource_name_template_, "\""));
317 }
318 fields.push_back(MakeCertificateProviderText());
319 fields.push_back(MakeAuthorityText());
320 return absl::StrCat("{", absl::StrJoin(fields, ",\n"), "}");
321 }
322
323 std::string XdsEnd2endTest::BootstrapBuilder::MakeXdsServersText(
324 absl::string_view server_uri) {
325 constexpr char kXdsServerTemplate[] =
326 " \"xds_servers\": [\n"
327 " {\n"
328 " \"server_uri\": \"<SERVER_URI>\",\n"
329 " \"channel_creds\": [\n"
330 " {\n"
331 " \"type\": \"fake\"\n"
332 " }\n"
333 " ],\n"
334 " \"server_features\": [<SERVER_FEATURES>]\n"
335 " }\n"
336 " ]";
337 std::vector<std::string> server_features;
338 if (ignore_resource_deletion_) {
339 server_features.push_back("\"ignore_resource_deletion\"");
340 }
341 return absl::StrReplaceAll(
342 kXdsServerTemplate,
343 {{"<SERVER_URI>", server_uri},
344 {"<SERVER_FEATURES>", absl::StrJoin(server_features, ", ")}});
345 }
346
347 std::string XdsEnd2endTest::BootstrapBuilder::MakeNodeText() {
348 constexpr char kXdsNode[] =
349 " \"node\": {\n"
350 " \"id\": \"xds_end2end_test\",\n"
351 " \"cluster\": \"test\",\n"
352 " \"metadata\": {\n"
353 " \"foo\": \"bar\"\n"
354 " },\n"
355 " \"locality\": {\n"
356 " \"region\": \"corp\",\n"
357 " \"zone\": \"svl\",\n"
358 " \"sub_zone\": \"mp3\"\n"
359 " }\n"
360 " }";
361 return kXdsNode;
362 }
363
364 std::string XdsEnd2endTest::BootstrapBuilder::MakeCertificateProviderText() {
365 std::vector<std::string> entries;
366 for (const auto& p : plugins_) {
367 const std::string& key = p.first;
368 const PluginInfo& plugin_info = p.second;
369 std::vector<std::string> fields;
370 fields.push_back(absl::StrFormat(" \"%s\": {", key));
371 if (!plugin_info.plugin_config.empty()) {
372 fields.push_back(
373 absl::StrFormat(" \"plugin_name\": \"%s\",", plugin_info.name));
374 fields.push_back(absl::StrCat(" \"config\": {\n",
375 plugin_info.plugin_config, "\n }"));
376 } else {
377 fields.push_back(
378 absl::StrFormat(" \"plugin_name\": \"%s\"", plugin_info.name));
379 }
380 fields.push_back(" }");
381 entries.push_back(absl::StrJoin(fields, "\n"));
382 }
383 return absl::StrCat(" \"certificate_providers\": {\n",
384 absl::StrJoin(entries, ",\n"), " \n}");
385 }
386
387 std::string XdsEnd2endTest::BootstrapBuilder::MakeAuthorityText() {
388 std::vector<std::string> entries;
389 for (const auto& p : authorities_) {
390 const std::string& name = p.first;
391 const AuthorityInfo& authority_info = p.second;
392 std::vector<std::string> fields = {
393 MakeXdsServersText(authority_info.server)};
394 if (!authority_info.client_listener_resource_name_template.empty()) {
395 fields.push_back(absl::StrCat(
396 "\"client_listener_resource_name_template\": \"",
397 authority_info.client_listener_resource_name_template, "\""));
398 }
399 entries.push_back(absl::StrCat(absl::StrFormat("\"%s\": {\n ", name),
400 absl::StrJoin(fields, ",\n"), "\n}"));
401 }
402 return absl::StrCat("\"authorities\": {\n", absl::StrJoin(entries, ",\n"),
403 "\n}");
404 }
405
406 //
407 // XdsEnd2endTest::RpcOptions
408 //
409
410 void XdsEnd2endTest::RpcOptions::SetupRpc(ClientContext* context,
411 EchoRequest* request) const {
412 for (const auto& item : metadata) {
413 context->AddMetadata(item.first, item.second);
414 }
415 if (timeout_ms != 0) {
416 context->set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
417 }
418 if (wait_for_ready) context->set_wait_for_ready(true);
419 request->set_message(kRequestMessage);
420 if (server_fail) {
421 request->mutable_param()->mutable_expected_error()->set_code(
422 GRPC_STATUS_FAILED_PRECONDITION);
423 }
424 if (server_sleep_us != 0) {
425 request->mutable_param()->set_server_sleep_us(server_sleep_us);
426 }
427 if (client_cancel_after_us != 0) {
428 request->mutable_param()->set_client_cancel_after_us(
429 client_cancel_after_us);
430 }
431 if (skip_cancelled_check) {
432 request->mutable_param()->set_skip_cancelled_check(true);
433 }
434 }
435
436 //
437 // XdsEnd2endTest
438 //
439
440 const char XdsEnd2endTest::kDefaultLocalityRegion[] =
441 "xds_default_locality_region";
442 const char XdsEnd2endTest::kDefaultLocalityZone[] = "xds_default_locality_zone";
443
444 const char XdsEnd2endTest::kServerName[] = "server.example.com";
445 const char XdsEnd2endTest::kDefaultRouteConfigurationName[] =
446 "route_config_name";
447 const char XdsEnd2endTest::kDefaultClusterName[] = "cluster_name";
448 const char XdsEnd2endTest::kDefaultEdsServiceName[] = "eds_service_name";
449 const char XdsEnd2endTest::kDefaultServerRouteConfigurationName[] =
450 "default_server_route_config_name";
451
452 const char XdsEnd2endTest::kCaCertPath[] = "src/core/tsi/test_creds/ca.pem";
453 const char XdsEnd2endTest::kServerCertPath[] =
454 "src/core/tsi/test_creds/server1.pem";
455 const char XdsEnd2endTest::kServerKeyPath[] =
456 "src/core/tsi/test_creds/server1.key";
457
458 const char XdsEnd2endTest::kRequestMessage[] = "Live long and prosper.";
459
460 XdsEnd2endTest::XdsEnd2endTest() : balancer_(CreateAndStartBalancer()) {
461 bool localhost_resolves_to_ipv4 = false;
462 bool localhost_resolves_to_ipv6 = false;
463 grpc_core::LocalhostResolves(&localhost_resolves_to_ipv4,
464 &localhost_resolves_to_ipv6);
465 ipv6_only_ = !localhost_resolves_to_ipv4 && localhost_resolves_to_ipv6;
466 // Initialize default xDS resources.
467 // Construct LDS resource.
468 default_listener_.set_name(kServerName);
469 HttpConnectionManager http_connection_manager;
470 auto* filter = http_connection_manager.add_http_filters();
471 filter->set_name("router");
472 filter->mutable_typed_config()->PackFrom(
473 envoy::extensions::filters::http::router::v3::Router());
474 default_listener_.mutable_api_listener()->mutable_api_listener()->PackFrom(
475 http_connection_manager);
476 // Construct RDS resource.
477 default_route_config_.set_name(kDefaultRouteConfigurationName);
478 auto* virtual_host = default_route_config_.add_virtual_hosts();
479 virtual_host->add_domains("*");
480 auto* route = virtual_host->add_routes();
481 route->mutable_match()->set_prefix("");
482 route->mutable_route()->set_cluster(kDefaultClusterName);
483 // Construct CDS resource.
484 default_cluster_.set_name(kDefaultClusterName);
485 default_cluster_.set_type(Cluster::EDS);
486 auto* eds_config = default_cluster_.mutable_eds_cluster_config();
487 eds_config->mutable_eds_config()->mutable_self();
488 eds_config->set_service_name(kDefaultEdsServiceName);
489 default_cluster_.set_lb_policy(Cluster::ROUND_ROBIN);
490 if (GetParam().enable_load_reporting()) {
491 default_cluster_.mutable_lrs_server()->mutable_self();
492 }
493 // Initialize client-side resources on balancer.
494 SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
495 default_route_config_);
496 balancer_->ads_service()->SetCdsResource(default_cluster_);
497 // Construct a default server-side RDS resource for tests to use.
498 default_server_route_config_.set_name(kDefaultServerRouteConfigurationName);
499 virtual_host = default_server_route_config_.add_virtual_hosts();
500 virtual_host->add_domains("*");
501 route = virtual_host->add_routes();
502 route->mutable_match()->set_prefix("");
503 route->mutable_non_forwarding_action();
504 // Construct a default server-side Listener resource
505 default_server_listener_.mutable_address()
506 ->mutable_socket_address()
507 ->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
508 default_server_listener_.mutable_default_filter_chain()
509 ->add_filters()
510 ->mutable_typed_config()
511 ->PackFrom(http_connection_manager);
512 }
513
514 void XdsEnd2endTest::TearDown() {
515 ShutdownAllBackends();
516 balancer_->Shutdown();
517 // Clear global xDS channel args, since they will go out of scope
518 // when this test object is destroyed.
519 grpc_core::internal::SetXdsChannelArgsForTest(nullptr);
520 grpc_core::UnsetEnv("GRPC_XDS_BOOTSTRAP");
521 grpc_core::UnsetEnv("GRPC_XDS_BOOTSTRAP_CONFIG");
522 if (bootstrap_file_ != nullptr) {
523 remove(bootstrap_file_);
524 gpr_free(bootstrap_file_);
525 }
526 }
527
528 std::unique_ptr<XdsEnd2endTest::BalancerServerThread>
529 XdsEnd2endTest::CreateAndStartBalancer() {
530 std::unique_ptr<BalancerServerThread> balancer =
531 std::make_unique<BalancerServerThread>(this);
532 balancer->Start();
533 return balancer;
534 }
535
536 std::string XdsEnd2endTest::GetServerListenerName(int port) {
537 return absl::StrCat("grpc/server?xds.resource.listening_address=",
538 ipv6_only_ ? "[::1]:" : "127.0.0.1:", port);
539 }
540
541 Listener XdsEnd2endTest::PopulateServerListenerNameAndPort(
542 const Listener& listener_template, int port) {
543 Listener listener = listener_template;
544 listener.set_name(GetServerListenerName(port));
545 listener.mutable_address()->mutable_socket_address()->set_port_value(port);
546 return listener;
547 }
548
549 HttpConnectionManager XdsEnd2endTest::ClientHcmAccessor::Unpack(
550 const Listener& listener) const {
551 HttpConnectionManager http_connection_manager;
552 listener.api_listener().api_listener().UnpackTo(&http_connection_manager);
553 return http_connection_manager;
554 }
555
556 void XdsEnd2endTest::ClientHcmAccessor::Pack(const HttpConnectionManager& hcm,
557 Listener* listener) const {
558 auto* api_listener = listener->mutable_api_listener()->mutable_api_listener();
559 api_listener->PackFrom(hcm);
560 }
561
562 HttpConnectionManager XdsEnd2endTest::ServerHcmAccessor::Unpack(
563 const Listener& listener) const {
564 HttpConnectionManager http_connection_manager;
565 listener.default_filter_chain().filters().at(0).typed_config().UnpackTo(
566 &http_connection_manager);
567 return http_connection_manager;
568 }
569
570 void XdsEnd2endTest::ServerHcmAccessor::Pack(const HttpConnectionManager& hcm,
571 Listener* listener) const {
572 listener->mutable_default_filter_chain()
573 ->mutable_filters()
574 ->at(0)
575 .mutable_typed_config()
576 ->PackFrom(hcm);
577 }
578
579 void XdsEnd2endTest::SetListenerAndRouteConfiguration(
580 BalancerServerThread* balancer, Listener listener,
581 const RouteConfiguration& route_config, const HcmAccessor& hcm_accessor) {
582 HttpConnectionManager http_connection_manager = hcm_accessor.Unpack(listener);
583 if (GetParam().enable_rds_testing()) {
584 auto* rds = http_connection_manager.mutable_rds();
585 rds->set_route_config_name(route_config.name());
586 rds->mutable_config_source()->mutable_self();
587 balancer->ads_service()->SetRdsResource(route_config);
588 } else {
589 *http_connection_manager.mutable_route_config() = route_config;
590 }
591 hcm_accessor.Pack(http_connection_manager, &listener);
592 balancer->ads_service()->SetLdsResource(listener);
593 }
594
595 void XdsEnd2endTest::SetRouteConfiguration(
596 BalancerServerThread* balancer, const RouteConfiguration& route_config,
597 const Listener* listener_to_copy) {
598 if (GetParam().enable_rds_testing()) {
599 balancer->ads_service()->SetRdsResource(route_config);
600 } else {
601 Listener listener(listener_to_copy == nullptr ? default_listener_
602 : *listener_to_copy);
603 HttpConnectionManager http_connection_manager;
604 listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
605 &http_connection_manager);
606 *(http_connection_manager.mutable_route_config()) = route_config;
607 listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
608 http_connection_manager);
609 balancer->ads_service()->SetLdsResource(listener);
610 }
611 }
612
613 std::vector<XdsEnd2endTest::EdsResourceArgs::Endpoint>
614 XdsEnd2endTest::CreateEndpointsForBackends(size_t start_index,
615 size_t stop_index,
616 HealthStatus health_status,
617 int lb_weight) {
618 if (stop_index == 0) stop_index = backends_.size();
619 std::vector<EdsResourceArgs::Endpoint> endpoints;
620 for (size_t i = start_index; i < stop_index; ++i) {
621 endpoints.emplace_back(CreateEndpoint(i, health_status, lb_weight));
622 }
623 return endpoints;
624 }
625
626 ClusterLoadAssignment XdsEnd2endTest::BuildEdsResource(
627 const EdsResourceArgs& args, const char* eds_service_name) {
628 ClusterLoadAssignment assignment;
629 assignment.set_cluster_name(eds_service_name);
630 for (const auto& locality : args.locality_list) {
631 auto* endpoints = assignment.add_endpoints();
632 endpoints->mutable_load_balancing_weight()->set_value(locality.lb_weight);
633 endpoints->set_priority(locality.priority);
634 endpoints->mutable_locality()->set_region(kDefaultLocalityRegion);
635 endpoints->mutable_locality()->set_zone(kDefaultLocalityZone);
636 endpoints->mutable_locality()->set_sub_zone(locality.sub_zone);
637 for (size_t i = 0; i < locality.endpoints.size(); ++i) {
638 const int& port = locality.endpoints[i].port;
639 auto* lb_endpoints = endpoints->add_lb_endpoints();
640 if (locality.endpoints.size() > i &&
641 locality.endpoints[i].health_status != HealthStatus::UNKNOWN) {
642 lb_endpoints->set_health_status(locality.endpoints[i].health_status);
643 }
644 if (locality.endpoints.size() > i &&
645 locality.endpoints[i].lb_weight >= 1) {
646 lb_endpoints->mutable_load_balancing_weight()->set_value(
647 locality.endpoints[i].lb_weight);
648 }
649 auto* endpoint = lb_endpoints->mutable_endpoint();
650 auto* address = endpoint->mutable_address();
651 auto* socket_address = address->mutable_socket_address();
652 socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
653 socket_address->set_port_value(port);
654 }
655 }
656 if (!args.drop_categories.empty()) {
657 auto* policy = assignment.mutable_policy();
658 for (const auto& p : args.drop_categories) {
659 const std::string& name = p.first;
660 const uint32_t parts_per_million = p.second;
661 auto* drop_overload = policy->add_drop_overloads();
662 drop_overload->set_category(name);
663 auto* drop_percentage = drop_overload->mutable_drop_percentage();
664 drop_percentage->set_numerator(parts_per_million);
665 drop_percentage->set_denominator(args.drop_denominator);
666 }
667 }
668 return assignment;
669 }
670
671 void XdsEnd2endTest::ResetBackendCounters(size_t start_index,
672 size_t stop_index) {
673 if (stop_index == 0) stop_index = backends_.size();
674 for (size_t i = start_index; i < stop_index; ++i) {
675 backends_[i]->backend_service()->ResetCounters();
676 backends_[i]->backend_service1()->ResetCounters();
677 backends_[i]->backend_service2()->ResetCounters();
678 }
679 }
680
681 bool XdsEnd2endTest::SeenBackend(size_t backend_idx,
682 const RpcService rpc_service) {
683 switch (rpc_service) {
684 case SERVICE_ECHO:
685 if (backends_[backend_idx]->backend_service()->request_count() == 0) {
686 return false;
687 }
688 break;
689 case SERVICE_ECHO1:
690 if (backends_[backend_idx]->backend_service1()->request_count() == 0) {
691 return false;
692 }
693 break;
694 case SERVICE_ECHO2:
695 if (backends_[backend_idx]->backend_service2()->request_count() == 0) {
696 return false;
697 }
698 break;
699 }
700 return true;
701 }
702
703 bool XdsEnd2endTest::SeenAllBackends(size_t start_index, size_t stop_index,
704 const RpcService rpc_service) {
705 if (stop_index == 0) stop_index = backends_.size();
706 for (size_t i = start_index; i < stop_index; ++i) {
707 if (!SeenBackend(i, rpc_service)) {
708 return false;
709 }
710 }
711 return true;
712 }
713
714 std::vector<int> XdsEnd2endTest::GetBackendPorts(size_t start_index,
715 size_t stop_index) const {
716 if (stop_index == 0) stop_index = backends_.size();
717 std::vector<int> backend_ports;
718 for (size_t i = start_index; i < stop_index; ++i) {
719 backend_ports.push_back(backends_[i]->port());
720 }
721 return backend_ports;
722 }
723
724 void XdsEnd2endTest::InitClient(BootstrapBuilder builder,
725 std::string lb_expected_authority,
726 int xds_resource_does_not_exist_timeout_ms) {
727 if (xds_resource_does_not_exist_timeout_ms > 0) {
728 xds_channel_args_to_add_.emplace_back(grpc_channel_arg_integer_create(
729 const_cast<char*>(GRPC_ARG_XDS_RESOURCE_DOES_NOT_EXIST_TIMEOUT_MS),
730 xds_resource_does_not_exist_timeout_ms));
731 }
732 if (!lb_expected_authority.empty()) {
733 constexpr char authority_const[] = "localhost:%d";
734 if (lb_expected_authority == authority_const) {
735 lb_expected_authority =
736 absl::StrFormat(authority_const, balancer_->port());
737 }
738 xds_channel_args_to_add_.emplace_back(grpc_channel_arg_string_create(
739 const_cast<char*>(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS),
740 const_cast<char*>(lb_expected_authority.c_str())));
741 }
742 xds_channel_args_.num_args = xds_channel_args_to_add_.size();
743 xds_channel_args_.args = xds_channel_args_to_add_.data();
744 // Initialize XdsClient state.
745 builder.SetDefaultServer(absl::StrCat("localhost:", balancer_->port()));
746 bootstrap_ = builder.Build();
747 if (GetParam().bootstrap_source() == XdsTestType::kBootstrapFromEnvVar) {
748 grpc_core::SetEnv("GRPC_XDS_BOOTSTRAP_CONFIG", bootstrap_.c_str());
749 } else if (GetParam().bootstrap_source() == XdsTestType::kBootstrapFromFile) {
750 FILE* out = gpr_tmpfile("xds_bootstrap_v3", &bootstrap_file_);
751 fputs(bootstrap_.c_str(), out);
752 fclose(out);
753 grpc_core::SetEnv("GRPC_XDS_BOOTSTRAP", bootstrap_file_);
754 }
755 if (GetParam().bootstrap_source() != XdsTestType::kBootstrapFromChannelArg) {
756 // If getting bootstrap from channel arg, we'll pass these args in
757 // via the parent channel args in CreateChannel() instead.
758 grpc_core::internal::SetXdsChannelArgsForTest(&xds_channel_args_);
759 // Make sure each test creates a new XdsClient instance rather than
760 // reusing the one from the previous test. This avoids spurious failures
761 // caused when a load reporting test runs after a non-load reporting test
762 // and the XdsClient is still talking to the old LRS server, which fails
763 // because it's not expecting the client to connect. It also
764 // ensures that each test can independently set the global channel
765 // args for the xDS channel.
766 grpc_core::internal::UnsetGlobalXdsClientForTest();
767 }
768 // Create channel and stub.
769 ResetStub();
770 }
771
772 void XdsEnd2endTest::ResetStub(int failover_timeout_ms,
773 ChannelArguments* args) {
774 channel_ = CreateChannel(failover_timeout_ms, kServerName, "", args);
775 stub_ = grpc::testing::EchoTestService::NewStub(channel_);
776 stub1_ = grpc::testing::EchoTest1Service::NewStub(channel_);
777 stub2_ = grpc::testing::EchoTest2Service::NewStub(channel_);
778 }
779
780 std::shared_ptr<Channel> XdsEnd2endTest::CreateChannel(
781 int failover_timeout_ms, const char* server_name, const char* xds_authority,
782 ChannelArguments* args) {
783 ChannelArguments local_args;
784 if (args == nullptr) args = &local_args;
785 // TODO(roth): Remove this once we enable retries by default internally.
786 args->SetInt(GRPC_ARG_ENABLE_RETRIES, 1);
787 if (failover_timeout_ms > 0) {
788 args->SetInt(GRPC_ARG_PRIORITY_FAILOVER_TIMEOUT_MS,
789 failover_timeout_ms * grpc_test_slowdown_factor());
790 }
791 if (GetParam().bootstrap_source() == XdsTestType::kBootstrapFromChannelArg) {
792 // We're getting the bootstrap from a channel arg, so we do the
793 // same thing for the response generator to use for the xDS
794 // channel and the xDS resource-does-not-exist timeout value.
795 args->SetString(GRPC_ARG_TEST_ONLY_DO_NOT_USE_IN_PROD_XDS_BOOTSTRAP_CONFIG,
796 bootstrap_.c_str());
797 args->SetPointerWithVtable(
798 GRPC_ARG_TEST_ONLY_DO_NOT_USE_IN_PROD_XDS_CLIENT_CHANNEL_ARGS,
799 &xds_channel_args_, &kChannelArgsArgVtable);
800 }
801 std::string uri = absl::StrCat("xds://", xds_authority, "/", server_name);
802 std::shared_ptr<ChannelCredentials> channel_creds =
803 GetParam().use_xds_credentials()
804 ? XdsCredentials(CreateTlsFallbackCredentials())
805 : std::make_shared<SecureChannelCredentials>(
806 grpc_fake_transport_security_credentials_create());
807 return grpc::CreateCustomChannel(uri, channel_creds, *args);
808 }
809
810 Status XdsEnd2endTest::SendRpc(const RpcOptions& rpc_options,
811 EchoResponse* response) {
812 EchoResponse local_response;
813 if (response == nullptr) response = &local_response;
814 ClientContext context;
815 EchoRequest request;
816 if (rpc_options.server_expected_error != StatusCode::OK) {
817 auto* error = request.mutable_param()->mutable_expected_error();
818 error->set_code(rpc_options.server_expected_error);
819 }
820 rpc_options.SetupRpc(&context, &request);
821 Status status;
822 switch (rpc_options.service) {
823 case SERVICE_ECHO:
824 status =
825 SendRpcMethod(stub_.get(), rpc_options, &context, request, response);
826 break;
827 case SERVICE_ECHO1:
828 status =
829 SendRpcMethod(stub1_.get(), rpc_options, &context, request, response);
830 break;
831 case SERVICE_ECHO2:
832 status =
833 SendRpcMethod(stub2_.get(), rpc_options, &context, request, response);
834 break;
835 }
836 return status;
837 }
838
839 void XdsEnd2endTest::SendRpcsUntil(
840 const grpc_core::DebugLocation& debug_location,
841 std::function<bool(const RpcResult&)> continue_predicate, int timeout_ms,
842 const RpcOptions& rpc_options) {
843 absl::Time deadline = absl::InfiniteFuture();
844 if (timeout_ms != 0) {
845 deadline = absl::Now() +
846 (absl::Milliseconds(timeout_ms) * grpc_test_slowdown_factor());
847 }
848 while (true) {
849 RpcResult result;
850 result.status = SendRpc(rpc_options, &result.response);
851 if (!continue_predicate(result)) return;
852 EXPECT_LE(absl::Now(), deadline)
853 << debug_location.file() << ":" << debug_location.line();
854 if (absl::Now() >= deadline) break;
855 }
856 }
857
858 void XdsEnd2endTest::CheckRpcSendOk(
859 const grpc_core::DebugLocation& debug_location, const size_t times,
860 const RpcOptions& rpc_options) {
861 SendRpcsUntil(
862 debug_location,
863 [debug_location, times, n = size_t(0)](const RpcResult& result) mutable {
864 EXPECT_TRUE(result.status.ok())
865 << "code=" << result.status.error_code()
866 << " message=" << result.status.error_message() << " at "
867 << debug_location.file() << ":" << debug_location.line();
868 EXPECT_EQ(result.response.message(), kRequestMessage);
869 return ++n < times;
870 },
871 /*timeout_ms=*/0, rpc_options);
872 }
873
874 void XdsEnd2endTest::CheckRpcSendFailure(
875 const grpc_core::DebugLocation& debug_location, StatusCode expected_status,
876 absl::string_view expected_message_regex, const RpcOptions& rpc_options) {
877 const Status status = SendRpc(rpc_options);
878 EXPECT_FALSE(status.ok())
879 << debug_location.file() << ":" << debug_location.line();
880 EXPECT_EQ(expected_status, status.error_code())
881 << debug_location.file() << ":" << debug_location.line();
882 EXPECT_THAT(status.error_message(),
883 ::testing::MatchesRegex(expected_message_regex))
884 << debug_location.file() << ":" << debug_location.line();
885 }
886
887 size_t XdsEnd2endTest::SendRpcsAndCountFailuresWithMessage(
888 const grpc_core::DebugLocation& debug_location, size_t num_rpcs,
889 StatusCode expected_status, absl::string_view expected_message_prefix,
890 const RpcOptions& rpc_options) {
891 size_t num_failed = 0;
892 SendRpcsUntil(
893 debug_location,
894 [&, n = size_t(0)](const RpcResult& result) mutable {
895 if (!result.status.ok()) {
896 EXPECT_EQ(result.status.error_code(), expected_status)
897 << debug_location.file() << ":" << debug_location.line();
898 EXPECT_THAT(result.status.error_message(),
899 ::testing::StartsWith(expected_message_prefix))
900 << debug_location.file() << ":" << debug_location.line();
901 ++num_failed;
902 }
903 return ++n < num_rpcs;
904 },
905 /*timeout_ms=*/0, rpc_options);
906 return num_failed;
907 }
908
909 void XdsEnd2endTest::LongRunningRpc::StartRpc(
910 grpc::testing::EchoTestService::Stub* stub, const RpcOptions& rpc_options) {
911 sender_thread_ = std::thread([this, stub, rpc_options]() {
912 EchoRequest request;
913 EchoResponse response;
914 rpc_options.SetupRpc(&context_, &request);
915 status_ = stub->Echo(&context_, request, &response);
916 });
917 }
918
919 void XdsEnd2endTest::LongRunningRpc::CancelRpc() {
920 context_.TryCancel();
921 if (sender_thread_.joinable()) sender_thread_.join();
922 }
923
924 Status XdsEnd2endTest::LongRunningRpc::GetStatus() {
925 if (sender_thread_.joinable()) sender_thread_.join();
926 return status_;
927 }
928
929 std::vector<XdsEnd2endTest::ConcurrentRpc> XdsEnd2endTest::SendConcurrentRpcs(
930 const grpc_core::DebugLocation& debug_location,
931 grpc::testing::EchoTestService::Stub* stub, size_t num_rpcs,
932 const RpcOptions& rpc_options) {
933 // Variables for RPCs.
934 std::vector<ConcurrentRpc> rpcs(num_rpcs);
935 EchoRequest request;
936 // Variables for synchronization
937 grpc_core::Mutex mu;
938 grpc_core::CondVar cv;
939 size_t completed = 0;
940 // Set-off callback RPCs
941 for (size_t i = 0; i < num_rpcs; i++) {
942 ConcurrentRpc* rpc = &rpcs[i];
943 rpc_options.SetupRpc(&rpc->context, &request);
944 grpc_core::Timestamp t0 = NowFromCycleCounter();
945 stub->async()->Echo(&rpc->context, &request, &rpc->response,
946 [rpc, &mu, &completed, &cv, num_rpcs, t0](Status s) {
947 rpc->status = s;
948 rpc->elapsed_time = NowFromCycleCounter() - t0;
949 bool done;
950 {
951 grpc_core::MutexLock lock(&mu);
952 done = (++completed) == num_rpcs;
953 }
954 if (done) cv.Signal();
955 });
956 }
957 {
958 grpc_core::MutexLock lock(&mu);
959 cv.Wait(&mu);
960 }
961 EXPECT_EQ(completed, num_rpcs)
962 << " at " << debug_location.file() << ":" << debug_location.line();
963 return rpcs;
964 }
965
966 size_t XdsEnd2endTest::WaitForAllBackends(
967 const grpc_core::DebugLocation& debug_location, size_t start_index,
968 size_t stop_index, std::function<void(const RpcResult&)> check_status,
969 const WaitForBackendOptions& wait_options, const RpcOptions& rpc_options) {
970 if (check_status == nullptr) {
971 check_status = [&](const RpcResult& result) {
972 EXPECT_TRUE(result.status.ok())
973 << "code=" << result.status.error_code()
974 << " message=" << result.status.error_message() << " at "
975 << debug_location.file() << ":" << debug_location.line();
976 };
977 }
978 gpr_log(GPR_INFO,
979 "========= WAITING FOR BACKENDS [%" PRIuPTR ", %" PRIuPTR
980 ") ==========",
981 start_index, stop_index);
982 size_t num_rpcs = 0;
983 SendRpcsUntil(
984 debug_location,
985 [&](const RpcResult& result) {
986 ++num_rpcs;
987 check_status(result);
988 return !SeenAllBackends(start_index, stop_index, rpc_options.service);
989 },
990 wait_options.timeout_ms, rpc_options);
991 if (wait_options.reset_counters) ResetBackendCounters();
992 gpr_log(GPR_INFO, "Backends up; sent %" PRIuPTR " warm up requests",
993 num_rpcs);
994 return num_rpcs;
995 }
996
997 absl::optional<AdsServiceImpl::ResponseState> XdsEnd2endTest::WaitForNack(
998 const grpc_core::DebugLocation& debug_location,
999 std::function<absl::optional<AdsServiceImpl::ResponseState>()> get_state,
1000 const RpcOptions& rpc_options, StatusCode expected_status) {
1001 absl::optional<AdsServiceImpl::ResponseState> response_state;
1002 auto deadline =
1003 absl::Now() + (absl::Seconds(30) * grpc_test_slowdown_factor());
1004 auto continue_predicate = [&]() {
1005 if (absl::Now() >= deadline) {
1006 return false;
1007 }
1008 response_state = get_state();
1009 return !response_state.has_value() ||
1010 response_state->state != AdsServiceImpl::ResponseState::NACKED;
1011 };
1012 do {
1013 const Status status = SendRpc(rpc_options);
1014 EXPECT_EQ(expected_status, status.error_code())
1015 << "code=" << status.error_code()
1016 << " message=" << status.error_message() << " at "
1017 << debug_location.file() << ":" << debug_location.line();
1018 } while (continue_predicate());
1019 return response_state;
1020 }
1021
1022 void XdsEnd2endTest::SetProtoDuration(
1023 grpc_core::Duration duration, google::protobuf::Duration* duration_proto) {
1024 duration *= grpc_test_slowdown_factor();
1025 gpr_timespec ts = duration.as_timespec();
1026 duration_proto->set_seconds(ts.tv_sec);
1027 duration_proto->set_nanos(ts.tv_nsec);
1028 }
1029
1030 std::string XdsEnd2endTest::ReadFile(const char* file_path) {
1031 grpc_slice slice;
1032 GPR_ASSERT(
1033 GRPC_LOG_IF_ERROR("load_file", grpc_load_file(file_path, 0, &slice)));
1034 std::string file_contents(grpc_core::StringViewFromSlice(slice));
1035 grpc_slice_unref(slice);
1036 return file_contents;
1037 }
1038
1039 grpc_core::PemKeyCertPairList XdsEnd2endTest::ReadTlsIdentityPair(
1040 const char* key_path, const char* cert_path) {
1041 return grpc_core::PemKeyCertPairList{
1042 grpc_core::PemKeyCertPair(ReadFile(key_path), ReadFile(cert_path))};
1043 }
1044
1045 std::shared_ptr<ChannelCredentials>
1046 XdsEnd2endTest::CreateTlsFallbackCredentials() {
1047 IdentityKeyCertPair key_cert_pair;
1048 key_cert_pair.private_key = ReadFile(kServerKeyPath);
1049 key_cert_pair.certificate_chain = ReadFile(kServerCertPath);
1050 std::vector<IdentityKeyCertPair> identity_key_cert_pairs;
1051 identity_key_cert_pairs.emplace_back(key_cert_pair);
1052 auto certificate_provider = std::make_shared<StaticDataCertificateProvider>(
1053 ReadFile(kCaCertPath), identity_key_cert_pairs);
1054 grpc::experimental::TlsChannelCredentialsOptions options;
1055 options.set_certificate_provider(std::move(certificate_provider));
1056 options.watch_root_certs();
1057 options.watch_identity_key_cert_pairs();
1058 auto verifier =
1059 ExternalCertificateVerifier::Create<SyncCertificateVerifier>(true);
1060 options.set_certificate_verifier(std::move(verifier));
1061 options.set_verify_server_certs(true);
1062 options.set_check_call_host(false);
1063 auto channel_creds = grpc::experimental::TlsCredentials(options);
1064 GPR_ASSERT(channel_creds.get() != nullptr);
1065 return channel_creds;
1066 }
1067
1068 } // namespace testing
1069 } // namespace grpc