Debian Codegraph @

test/cpp/end2end/xds/xds_end2end_test_lib.h

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 <memory>
17 #include <set>
18 #include <string>
19 #include <thread>
20 #include <vector>
21
22 #include <gmock/gmock.h>
23 #include <gtest/gtest.h>
24
25 #include "absl/status/statusor.h"
26 #include "absl/strings/str_cat.h"
27 #include "absl/strings/string_view.h"
28 #include "absl/types/optional.h"
29
30 #include <grpc/grpc.h>
31 #include <grpc/grpc_security.h>
32 #include <grpcpp/channel.h>
33 #include <grpcpp/client_context.h>
34 #include <grpcpp/xds_server_builder.h>
35
36 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
37 #include "src/core/lib/security/security_connector/ssl_utils.h"
38 #include "src/cpp/server/secure_server_credentials.h"
39 #include "src/proto/grpc/testing/echo.grpc.pb.h"
40 #include "src/proto/grpc/testing/xds/v3/http_connection_manager.grpc.pb.h"
41 #include "src/proto/grpc/testing/xds/v3/http_filter_rbac.grpc.pb.h"
42 #include "test/core/util/port.h"
43 #include "test/cpp/end2end/counted_service.h"
44 #include "test/cpp/end2end/test_service_impl.h"
45 #include "test/cpp/end2end/xds/xds_server.h"
46
47 namespace grpc {
48 namespace testing {
49
50 // The parameter type for INSTANTIATE_TEST_SUITE_P().
51 class XdsTestType {
52 public:
53 enum HttpFilterConfigLocation {
54 // Set the HTTP filter config directly in LDS.
55 kHttpFilterConfigInListener,
56 // Enable the HTTP filter in LDS, but override the filter config in route.
57 kHttpFilterConfigInRoute,
58 };
59
60 enum BootstrapSource {
61 kBootstrapFromChannelArg,
62 kBootstrapFromFile,
63 kBootstrapFromEnvVar,
64 };
65
66 XdsTestType& set_enable_load_reporting() {
67 enable_load_reporting_ = true;
68 return *this;
69 }
70
71 XdsTestType& set_enable_rds_testing() {
72 enable_rds_testing_ = true;
73 return *this;
74 }
75
76 XdsTestType& set_use_xds_credentials() {
77 use_xds_credentials_ = true;
78 return *this;
79 }
80
81 XdsTestType& set_use_csds_streaming() {
82 use_csds_streaming_ = true;
83 return *this;
84 }
85
86 XdsTestType& set_filter_config_setup(HttpFilterConfigLocation setup) {
87 filter_config_setup_ = setup;
88 return *this;
89 }
90
91 XdsTestType& set_bootstrap_source(BootstrapSource bootstrap_source) {
92 bootstrap_source_ = bootstrap_source;
93 return *this;
94 }
95
96 XdsTestType& set_rbac_action(::envoy::config::rbac::v3::RBAC_Action action) {
97 rbac_action_ = action;
98 return *this;
99 }
100
101 bool enable_load_reporting() const { return enable_load_reporting_; }
102 bool enable_rds_testing() const { return enable_rds_testing_; }
103 bool use_xds_credentials() const { return use_xds_credentials_; }
104 bool use_csds_streaming() const { return use_csds_streaming_; }
105 HttpFilterConfigLocation filter_config_setup() const {
106 return filter_config_setup_;
107 }
108 BootstrapSource bootstrap_source() const { return bootstrap_source_; }
109 ::envoy::config::rbac::v3::RBAC_Action rbac_action() const {
110 return rbac_action_;
111 }
112
113 std::string AsString() const {
114 std::string retval = "V3";
115 if (enable_load_reporting_) retval += "WithLoadReporting";
116 if (enable_rds_testing_) retval += "Rds";
117 if (use_xds_credentials_) retval += "XdsCreds";
118 if (use_csds_streaming_) retval += "CsdsStreaming";
119 if (filter_config_setup_ == kHttpFilterConfigInRoute) {
120 retval += "FilterPerRouteOverride";
121 }
122 if (bootstrap_source_ == kBootstrapFromFile) {
123 retval += "BootstrapFromFile";
124 } else if (bootstrap_source_ == kBootstrapFromEnvVar) {
125 retval += "BootstrapFromEnvVar";
126 }
127 if (rbac_action_ == ::envoy::config::rbac::v3::RBAC_Action_ALLOW) {
128 retval += "RbacAllow";
129 } else if (rbac_action_ == ::envoy::config::rbac::v3::RBAC_Action_DENY) {
130 retval += "RbacDeny";
131 }
132 return retval;
133 }
134
135 // For use as the final parameter in INSTANTIATE_TEST_SUITE_P().
136 static std::string Name(const ::testing::TestParamInfo<XdsTestType>& info) {
137 return info.param.AsString();
138 }
139
140 private:
141 bool enable_load_reporting_ = false;
142 bool enable_rds_testing_ = false;
143 bool use_xds_credentials_ = false;
144 bool use_csds_streaming_ = false;
145 HttpFilterConfigLocation filter_config_setup_ = kHttpFilterConfigInListener;
146 BootstrapSource bootstrap_source_ = kBootstrapFromChannelArg;
147 ::envoy::config::rbac::v3::RBAC_Action rbac_action_ =
148 ::envoy::config::rbac::v3::RBAC_Action_LOG;
149 };
150
151 // A base class for xDS end-to-end tests.
152 //
153 // An xDS server is provided in balancer_. It is automatically started
154 // for every test. Additional xDS servers can be started if needed by
155 // calling CreateAndStartBalancer().
156 //
157 // A default set of LDS, RDS, and CDS resources are created for gRPC
158 // clients, available in default_listener_, default_route_config_, and
159 // default_cluster_. These resources are automatically loaded into
160 // balancer_ but can be modified by individual tests. No EDS resource
161 // is provided by default. There are also default LDS and RDS resources
162 // for the gRPC server side in default_server_listener_ and
163 // default_server_route_config_. Methods are provided for constructing new
164 // resources that can be added to the xDS server as needed.
165 //
166 // This class provides a mechanism for running backend servers, which will
167 // be stored in backends_. No servers are created or started by default,
168 // but tests can call CreateAndStartBackends() to start however many
169 // backends they want. There are also a number of methods for accessing
170 // backends by index, which is the index into the backends_ vector.
171 // For methods that take a start_index and stop_index, this refers to
172 // the indexes in the range [start_index, stop_index). If stop_index
173 // is 0, backends_.size() is used. Backends may or may not be
174 // xDS-enabled, at the discretion of the test.
175 class XdsEnd2endTest : public ::testing::TestWithParam<XdsTestType> {
176 protected:
177 using Cluster = ::envoy::config::cluster::v3::Cluster;
178 using ClusterLoadAssignment =
179 ::envoy::config::endpoint::v3::ClusterLoadAssignment;
180 using Listener = ::envoy::config::listener::v3::Listener;
181 using RouteConfiguration = ::envoy::config::route::v3::RouteConfiguration;
182 using HttpConnectionManager = ::envoy::extensions::filters::network::
183 http_connection_manager::v3::HttpConnectionManager;
184
185 // Default values for locality fields.
186 static const char kDefaultLocalityRegion[];
187 static const char kDefaultLocalityZone[];
188 static const uint32_t kDefaultLocalityWeight = 3;
189 static const int kDefaultLocalityPriority = 0;
190
191 // Default resource names.
192 static const char kServerName[];
193 static const char kDefaultRouteConfigurationName[];
194 static const char kDefaultClusterName[];
195 static const char kDefaultEdsServiceName[];
196 static const char kDefaultServerRouteConfigurationName[];
197
198 // TLS certificate paths.
199 static const char kCaCertPath[];
200 static const char kServerCertPath[];
201 static const char kServerKeyPath[];
202
203 // Message used in EchoRequest to the backend.
204 static const char kRequestMessage[];
205
206 // A base class for server threads.
207 class ServerThread {
208 public:
209 // A status notifier for xDS-enabled servers.
210 class XdsServingStatusNotifier
211 : public grpc::XdsServerServingStatusNotifierInterface {
212 public:
213 void OnServingStatusUpdate(std::string uri,
214 ServingStatusUpdate update) override;
215
216 void WaitOnServingStatusChange(std::string uri,
217 grpc::StatusCode expected_status);
218
219 private:
220 grpc_core::Mutex mu_;
221 grpc_core::CondVar cond_;
222 std::map<std::string, grpc::Status> status_map ABSL_GUARDED_BY(mu_);
223 };
224
225 // If use_xds_enabled_server is true, the server will use xDS.
226 explicit ServerThread(XdsEnd2endTest* test_obj,
227 bool use_xds_enabled_server = false)
228 : test_obj_(test_obj),
229 port_(grpc_pick_unused_port_or_die()),
230 use_xds_enabled_server_(use_xds_enabled_server) {}
231
232 virtual ~ServerThread() { Shutdown(); }
233
234 void Start();
235 void Shutdown();
236
237 virtual std::shared_ptr<ServerCredentials> Credentials() {
238 return std::make_shared<SecureServerCredentials>(
239 grpc_fake_transport_security_server_credentials_create());
240 }
241
242 int port() const { return port_; }
243
244 bool use_xds_enabled_server() const { return use_xds_enabled_server_; }
245
246 XdsServingStatusNotifier* notifier() { return &notifier_; }
247
248 void set_allow_put_requests(bool allow_put_requests) {
249 allow_put_requests_ = allow_put_requests;
250 }
251
252 void StopListeningAndSendGoaways();
253
254 private:
255 class XdsChannelArgsServerBuilderOption;
256
257 virtual const char* Type() = 0;
258 virtual void RegisterAllServices(ServerBuilder* builder) = 0;
259 virtual void StartAllServices() = 0;
260 virtual void ShutdownAllServices() = 0;
261
262 void Serve(grpc_core::Mutex* mu, grpc_core::CondVar* cond);
263
264 XdsEnd2endTest* test_obj_;
265 const int port_;
266 std::unique_ptr<Server> server_;
267 XdsServingStatusNotifier notifier_;
268 std::unique_ptr<std::thread> thread_;
269 bool running_ = false;
270 const bool use_xds_enabled_server_;
271 bool allow_put_requests_ = false;
272 };
273
274 // A server thread for a backend server.
275 class BackendServerThread : public ServerThread {
276 public:
277 // A wrapper around the backend echo test service impl that counts
278 // requests and responses.
279 template <typename RpcService>
280 class BackendServiceImpl
281 : public CountedService<TestMultipleServiceImpl<RpcService>> {
282 public:
283 BackendServiceImpl() {}
284
285 Status Echo(ServerContext* context, const EchoRequest* request,
286 EchoResponse* response) override {
287 auto peer_identity = context->auth_context()->GetPeerIdentity();
288 CountedService<
289 TestMultipleServiceImpl<RpcService>>::IncreaseRequestCount();
290 const auto status = TestMultipleServiceImpl<RpcService>::Echo(
291 context, request, response);
292 CountedService<
293 TestMultipleServiceImpl<RpcService>>::IncreaseResponseCount();
294 {
295 grpc_core::MutexLock lock(&mu_);
296 clients_.insert(context->peer());
297 last_peer_identity_.clear();
298 for (const auto& entry : peer_identity) {
299 last_peer_identity_.emplace_back(entry.data(), entry.size());
300 }
301 }
302 return status;
303 }
304
305 Status Echo1(ServerContext* context, const EchoRequest* request,
306 EchoResponse* response) override {
307 return Echo(context, request, response);
308 }
309
310 Status Echo2(ServerContext* context, const EchoRequest* request,
311 EchoResponse* response) override {
312 return Echo(context, request, response);
313 }
314
315 void Start() {}
316 void Shutdown() {}
317
318 std::set<std::string> clients() {
319 grpc_core::MutexLock lock(&mu_);
320 return clients_;
321 }
322
323 const std::vector<std::string>& last_peer_identity() {
324 grpc_core::MutexLock lock(&mu_);
325 return last_peer_identity_;
326 }
327
328 private:
329 grpc_core::Mutex mu_;
330 std::set<std::string> clients_ ABSL_GUARDED_BY(mu_);
331 std::vector<std::string> last_peer_identity_ ABSL_GUARDED_BY(mu_);
332 };
333
334 // If use_xds_enabled_server is true, the server will use xDS.
335 BackendServerThread(XdsEnd2endTest* test_obj, bool use_xds_enabled_server);
336
337 BackendServiceImpl<grpc::testing::EchoTestService::Service>*
338 backend_service() {
339 return &backend_service_;
340 }
341 BackendServiceImpl<grpc::testing::EchoTest1Service::Service>*
342 backend_service1() {
343 return &backend_service1_;
344 }
345 BackendServiceImpl<grpc::testing::EchoTest2Service::Service>*
346 backend_service2() {
347 return &backend_service2_;
348 }
349
350 // If XdsTestType::use_xds_credentials() and use_xds_enabled_server()
351 // are both true, returns XdsServerCredentials.
352 // Otherwise, if XdsTestType::use_xds_credentials() is true and
353 // use_xds_enabled_server() is false, returns TlsServerCredentials.
354 // Otherwise, returns fake credentials.
355 std::shared_ptr<ServerCredentials> Credentials() override;
356
357 private:
358 const char* Type() override { return "Backend"; }
359 void RegisterAllServices(ServerBuilder* builder) override;
360 void StartAllServices() override;
361 void ShutdownAllServices() override;
362
363 BackendServiceImpl<grpc::testing::EchoTestService::Service>
364 backend_service_;
365 BackendServiceImpl<grpc::testing::EchoTest1Service::Service>
366 backend_service1_;
367 BackendServiceImpl<grpc::testing::EchoTest2Service::Service>
368 backend_service2_;
369 };
370
371 // A server thread for the xDS server.
372 class BalancerServerThread : public ServerThread {
373 public:
374 explicit BalancerServerThread(XdsEnd2endTest* test_obj);
375
376 AdsServiceImpl* ads_service() { return ads_service_.get(); }
377 LrsServiceImpl* lrs_service() { return lrs_service_.get(); }
378
379 private:
380 const char* Type() override { return "Balancer"; }
381 void RegisterAllServices(ServerBuilder* builder) override;
382 void StartAllServices() override;
383 void ShutdownAllServices() override;
384
385 std::shared_ptr<AdsServiceImpl> ads_service_;
386 std::shared_ptr<LrsServiceImpl> lrs_service_;
387 };
388
389 // A builder for the xDS bootstrap config.
390 class BootstrapBuilder {
391 public:
392 BootstrapBuilder() {}
393 BootstrapBuilder& SetIgnoreResourceDeletion() {
394 ignore_resource_deletion_ = true;
395 return *this;
396 }
397 BootstrapBuilder& SetDefaultServer(const std::string& server) {
398 top_server_ = server;
399 return *this;
400 }
401 BootstrapBuilder& SetClientDefaultListenerResourceNameTemplate(
402 const std::string& client_default_listener_resource_name_template) {
403 client_default_listener_resource_name_template_ =
404 client_default_listener_resource_name_template;
405 return *this;
406 }
407 BootstrapBuilder& AddCertificateProviderPlugin(
408 const std::string& key, const std::string& name,
409 const std::string& plugin_config = "") {
410 plugins_[key] = {name, plugin_config};
411 return *this;
412 }
413 BootstrapBuilder& AddAuthority(
414 const std::string& authority, const std::string& servers = "",
415 const std::string& client_listener_resource_name_template = "") {
416 authorities_[authority] = {servers,
417 client_listener_resource_name_template};
418 return *this;
419 }
420 BootstrapBuilder& SetServerListenerResourceNameTemplate(
421 const std::string& server_listener_resource_name_template = "") {
422 server_listener_resource_name_template_ =
423 server_listener_resource_name_template;
424 return *this;
425 }
426
427 std::string Build();
428
429 private:
430 struct PluginInfo {
431 std::string name;
432 std::string plugin_config;
433 };
434 struct AuthorityInfo {
435 std::string server;
436 std::string client_listener_resource_name_template;
437 };
438
439 std::string MakeXdsServersText(absl::string_view server_uri);
440 std::string MakeNodeText();
441 std::string MakeCertificateProviderText();
442 std::string MakeAuthorityText();
443
444 bool ignore_resource_deletion_ = false;
445 std::string top_server_;
446 std::string client_default_listener_resource_name_template_;
447 std::map<std::string /*key*/, PluginInfo> plugins_;
448 std::map<std::string /*authority_name*/, AuthorityInfo> authorities_;
449 std::string server_listener_resource_name_template_ =
450 "grpc/server?xds.resource.listening_address=%s";
451 };
452
453 // RPC services used to talk to the backends.
454 enum RpcService {
455 SERVICE_ECHO,
456 SERVICE_ECHO1,
457 SERVICE_ECHO2,
458 };
459
460 // RPC methods used to talk to the backends.
461 enum RpcMethod {
462 METHOD_ECHO,
463 METHOD_ECHO1,
464 METHOD_ECHO2,
465 };
466
467 XdsEnd2endTest();
468
469 void SetUp() override { InitClient(); }
470 void TearDown() override;
471
472 //
473 // xDS server management
474 //
475
476 // Creates and starts a new balancer, running in its own thread.
477 // Most tests will not need to call this; instead, they can use
478 // balancer_, which is already populated with default resources.
479 std::unique_ptr<BalancerServerThread> CreateAndStartBalancer();
480
481 // Returns the name of the server-side xDS Listener resource for a
482 // backend on the specified port.
483 std::string GetServerListenerName(int port);
484
485 // Returns a copy of listener_template with the server-side resource
486 // name and the port in the socket address populated.
487 Listener PopulateServerListenerNameAndPort(const Listener& listener_template,
488 int port);
489
490 // Interface for accessing HttpConnectionManager config in Listener.
491 class HcmAccessor {
492 public:
493 virtual ~HcmAccessor() = default;
494 virtual HttpConnectionManager Unpack(const Listener& listener) const = 0;
495 virtual void Pack(const HttpConnectionManager& hcm,
496 Listener* listener) const = 0;
497 };
498
499 // Client-side impl.
500 class ClientHcmAccessor : public HcmAccessor {
501 public:
502 HttpConnectionManager Unpack(const Listener& listener) const override;
503 void Pack(const HttpConnectionManager& hcm,
504 Listener* listener) const override;
505 };
506
507 // Server-side impl.
508 class ServerHcmAccessor : public HcmAccessor {
509 public:
510 HttpConnectionManager Unpack(const Listener& listener) const override;
511 void Pack(const HttpConnectionManager& hcm,
512 Listener* listener) const override;
513 };
514
515 // Sets the Listener and RouteConfiguration resource on the specified
516 // balancer. If RDS is in use, they will be set as separate resources;
517 // otherwise, the RouteConfig will be inlined into the Listener.
518 void SetListenerAndRouteConfiguration(
519 BalancerServerThread* balancer, Listener listener,
520 const RouteConfiguration& route_config,
521 const HcmAccessor& hcm_accessor = ClientHcmAccessor());
522
523 // A convenient wrapper for setting the Listener and
524 // RouteConfiguration resources on the server side.
525 void SetServerListenerNameAndRouteConfiguration(
526 BalancerServerThread* balancer, Listener listener, int port,
527 const RouteConfiguration& route_config) {
528 SetListenerAndRouteConfiguration(
529 balancer, PopulateServerListenerNameAndPort(listener, port),
530 route_config, ServerHcmAccessor());
531 }
532
533 // Sets the RouteConfiguration resource on the specified balancer.
534 // If RDS is in use, it will be set directly as an independent
535 // resource; otherwise, it will be inlined into a Listener resource
536 // (either listener_to_copy, or if that is null, default_listener_).
537 void SetRouteConfiguration(BalancerServerThread* balancer,
538 const RouteConfiguration& route_config,
539 const Listener* listener_to_copy = nullptr);
540
541 // Arguments for constructing an EDS resource.
542 struct EdsResourceArgs {
543 // An individual endpoint for a backend running on a specified port.
544 struct Endpoint {
545 explicit Endpoint(
546 int port,
547 ::envoy::config::endpoint::v3::HealthStatus health_status =
548 ::envoy::config::endpoint::v3::HealthStatus::UNKNOWN,
549 int lb_weight = 1)
550 : port(port), health_status(health_status), lb_weight(lb_weight) {}
551
552 int port;
553 ::envoy::config::endpoint::v3::HealthStatus health_status;
554 int lb_weight;
555 };
556
557 // A locality.
558 struct Locality {
559 Locality(std::string sub_zone, std::vector<Endpoint> endpoints,
560 uint32_t lb_weight = kDefaultLocalityWeight,
561 int priority = kDefaultLocalityPriority)
562 : sub_zone(std::move(sub_zone)),
563 endpoints(std::move(endpoints)),
564 lb_weight(lb_weight),
565 priority(priority) {}
566
567 const std::string sub_zone;
568 std::vector<Endpoint> endpoints;
569 uint32_t lb_weight;
570 int priority;
571 };
572
573 EdsResourceArgs() = default;
574 explicit EdsResourceArgs(std::vector<Locality> locality_list)
575 : locality_list(std::move(locality_list)) {}
576
577 std::vector<Locality> locality_list;
578 std::map<std::string, uint32_t> drop_categories;
579 ::envoy::type::v3::FractionalPercent::DenominatorType drop_denominator =
580 ::envoy::type::v3::FractionalPercent::MILLION;
581 };
582
583 // Helper method for generating an endpoint for a backend, for use in
584 // constructing an EDS resource.
585 EdsResourceArgs::Endpoint CreateEndpoint(
586 size_t backend_idx,
587 ::envoy::config::endpoint::v3::HealthStatus health_status =
588 ::envoy::config::endpoint::v3::HealthStatus::UNKNOWN,
589 int lb_weight = 1) {
590 return EdsResourceArgs::Endpoint(backends_[backend_idx]->port(),
591 health_status, lb_weight);
592 }
593
594 // Creates a vector of endpoints for a specified range of backends,
595 // for use in constructing an EDS resource.
596 std::vector<EdsResourceArgs::Endpoint> CreateEndpointsForBackends(
597 size_t start_index = 0, size_t stop_index = 0,
598 ::envoy::config::endpoint::v3::HealthStatus health_status =
599 ::envoy::config::endpoint::v3::HealthStatus::UNKNOWN,
600 int lb_weight = 1);
601
602 // Returns an endpoint for an unused port, for use in constructing an
603 // EDS resource.
604 EdsResourceArgs::Endpoint MakeNonExistantEndpoint() {
605 return EdsResourceArgs::Endpoint(grpc_pick_unused_port_or_die());
606 }
607
608 // Constructs an EDS resource.
609 ClusterLoadAssignment BuildEdsResource(
610 const EdsResourceArgs& args,
611 const char* eds_service_name = kDefaultEdsServiceName);
612
613 //
614 // Backend management
615 //
616
617 // Creates num_backends backends and stores them in backends_, but
618 // does not actually start them. If xds_enabled is true, the backends
619 // are xDS-enabled.
620 void CreateBackends(size_t num_backends, bool xds_enabled = false) {
621 for (size_t i = 0; i < num_backends; ++i) {
622 backends_.emplace_back(new BackendServerThread(this, xds_enabled));
623 }
624 }
625
626 // Starts all backends in backends_.
627 void StartAllBackends() {
628 for (auto& backend : backends_) backend->Start();
629 }
630
631 // Same as CreateBackends(), but also starts the backends.
632 void CreateAndStartBackends(size_t num_backends, bool xds_enabled = false) {
633 CreateBackends(num_backends, xds_enabled);
634 StartAllBackends();
635 }
636
637 // Starts the backend at backends_[index].
638 void StartBackend(size_t index) { backends_[index]->Start(); }
639
640 // Shuts down all backends in backends_.
641 void ShutdownAllBackends() {
642 for (auto& backend : backends_) backend->Shutdown();
643 }
644
645 // Shuts down the backend at backends_[index].
646 void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
647
648 // Resets the request counters for backends in the specified range.
649 void ResetBackendCounters(size_t start_index = 0, size_t stop_index = 0);
650
651 // Returns true if the specified backend has received requests for the
652 // specified service.
653 bool SeenBackend(size_t backend_idx,
654 const RpcService rpc_service = SERVICE_ECHO);
655
656 // Returns true if all backends in the specified range have received
657 // requests for the specified service.
658 bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0,
659 const RpcService rpc_service = SERVICE_ECHO);
660
661 // Returns a vector containing the port for every backend in the
662 // specified range.
663 std::vector<int> GetBackendPorts(size_t start_index = 0,
664 size_t stop_index = 0) const;
665
666 //
667 // Client management
668 //
669
670 // Initializes global state for the client, such as the bootstrap file
671 // and channel args for the XdsClient. Then calls ResetStub().
672 // All tests must call this exactly once at the start of the test.
673 void InitClient(BootstrapBuilder builder = BootstrapBuilder(),
674 std::string lb_expected_authority = "",
675 int xds_resource_does_not_exist_timeout_ms = 0);
676
677 // Sets channel_, stub_, stub1_, and stub2_.
678 void ResetStub(int failover_timeout_ms = 0, ChannelArguments* args = nullptr);
679
680 // Creates a new client channel. Requires that InitClient() has
681 // already been called.
682 std::shared_ptr<Channel> CreateChannel(int failover_timeout_ms = 0,
683 const char* server_name = kServerName,
684 const char* xds_authority = "",
685 ChannelArguments* args = nullptr);
686
687 //
688 // Sending RPCs
689 //
690
691 // Options used for sending an RPC.
692 struct RpcOptions {
693 RpcService service = SERVICE_ECHO;
694 RpcMethod method = METHOD_ECHO;
695 // Will be multiplied by grpc_test_slowdown_factor().
696 int timeout_ms = 5000;
697 bool wait_for_ready = false;
698 std::vector<std::pair<std::string, std::string>> metadata;
699 // These options are used by the backend service impl.
700 bool server_fail = false;
701 int server_sleep_us = 0;
702 int client_cancel_after_us = 0;
703 bool skip_cancelled_check = false;
704 StatusCode server_expected_error = StatusCode::OK;
705
706 RpcOptions() {}
707
708 RpcOptions& set_rpc_service(RpcService rpc_service) {
709 service = rpc_service;
710 return *this;
711 }
712
713 RpcOptions& set_rpc_method(RpcMethod rpc_method) {
714 method = rpc_method;
715 return *this;
716 }
717
718 RpcOptions& set_timeout_ms(int rpc_timeout_ms) {
719 timeout_ms = rpc_timeout_ms;
720 return *this;
721 }
722
723 RpcOptions& set_timeout(grpc_core::Duration timeout) {
724 timeout_ms = timeout.millis();
725 return *this;
726 }
727
728 RpcOptions& set_wait_for_ready(bool rpc_wait_for_ready) {
729 wait_for_ready = rpc_wait_for_ready;
730 return *this;
731 }
732
733 RpcOptions& set_metadata(
734 std::vector<std::pair<std::string, std::string>> rpc_metadata) {
735 metadata = std::move(rpc_metadata);
736 return *this;
737 }
738
739 RpcOptions& set_server_fail(bool rpc_server_fail) {
740 server_fail = rpc_server_fail;
741 return *this;
742 }
743
744 RpcOptions& set_server_sleep_us(int rpc_server_sleep_us) {
745 server_sleep_us = rpc_server_sleep_us;
746 return *this;
747 }
748
749 RpcOptions& set_client_cancel_after_us(int rpc_client_cancel_after_us) {
750 client_cancel_after_us = rpc_client_cancel_after_us;
751 return *this;
752 }
753
754 RpcOptions& set_skip_cancelled_check(bool rpc_skip_cancelled_check) {
755 skip_cancelled_check = rpc_skip_cancelled_check;
756 return *this;
757 }
758
759 RpcOptions& set_server_expected_error(StatusCode code) {
760 server_expected_error = code;
761 return *this;
762 }
763
764 // Populates context and request.
765 void SetupRpc(ClientContext* context, EchoRequest* request) const;
766 };
767
768 // Sends an RPC with the specified options.
769 // If response is non-null, it will be populated with the response.
770 // Returns the status of the RPC.
771 Status SendRpc(const RpcOptions& rpc_options = RpcOptions(),
772 EchoResponse* response = nullptr);
773
774 // Internal helper function for SendRpc().
775 template <typename Stub>
776 static Status SendRpcMethod(Stub* stub, const RpcOptions& rpc_options,
777 ClientContext* context, EchoRequest& request,
778 EchoResponse* response) {
779 switch (rpc_options.method) {
780 case METHOD_ECHO:
781 return stub->Echo(context, request, response);
782 case METHOD_ECHO1:
783 return stub->Echo1(context, request, response);
784 case METHOD_ECHO2:
785 return stub->Echo2(context, request, response);
786 }
787 GPR_UNREACHABLE_CODE(return grpc::Status::OK);
788 }
789
790 // Send RPCs in a loop until either continue_predicate() returns false
791 // or timeout_ms elapses.
792 struct RpcResult {
793 Status status;
794 EchoResponse response;
795 };
796 void SendRpcsUntil(const grpc_core::DebugLocation& debug_location,
797 std::function<bool(const RpcResult&)> continue_predicate,
798 int timeout_ms = 15000,
799 const RpcOptions& rpc_options = RpcOptions());
800
801 // Sends the specified number of RPCs and fails if the RPC fails.
802 void CheckRpcSendOk(const grpc_core::DebugLocation& debug_location,
803 const size_t times = 1,
804 const RpcOptions& rpc_options = RpcOptions());
805
806 // Sends one RPC, which must fail with the specified status code and
807 // a message matching the specified regex.
808 void CheckRpcSendFailure(const grpc_core::DebugLocation& debug_location,
809 StatusCode expected_status,
810 absl::string_view expected_message_regex,
811 const RpcOptions& rpc_options = RpcOptions());
812
813 // Sends num_rpcs RPCs, counting how many of them fail with a message
814 // matching the specfied expected_message_prefix.
815 // Any failure with a non-matching status or message is a test failure.
816 size_t SendRpcsAndCountFailuresWithMessage(
817 const grpc_core::DebugLocation& debug_location, size_t num_rpcs,
818 StatusCode expected_status, absl::string_view expected_message_prefix,
819 const RpcOptions& rpc_options = RpcOptions());
820
821 // A class for running a long-running RPC in its own thread.
822 // TODO(roth): Maybe consolidate this and SendConcurrentRpcs()
823 // somehow? LongRunningRpc has a cleaner API, but SendConcurrentRpcs()
824 // uses the callback API, which is probably better.
825 class LongRunningRpc {
826 public:
827 // Starts the RPC.
828 void StartRpc(grpc::testing::EchoTestService::Stub* stub,
829 const RpcOptions& rpc_options =
830 RpcOptions().set_timeout_ms(0).set_client_cancel_after_us(
831 1 * 1000 * 1000));
832
833 // Cancels the RPC.
834 void CancelRpc();
835
836 // Gets the RPC's status. Blocks if the RPC is not yet complete.
837 Status GetStatus();
838
839 private:
840 std::thread sender_thread_;
841 ClientContext context_;
842 Status status_;
843 };
844
845 // Starts a set of concurrent RPCs.
846 struct ConcurrentRpc {
847 ClientContext context;
848 Status status;
849 grpc_core::Duration elapsed_time;
850 EchoResponse response;
851 };
852 std::vector<ConcurrentRpc> SendConcurrentRpcs(
853 const grpc_core::DebugLocation& debug_location,
854 grpc::testing::EchoTestService::Stub* stub, size_t num_rpcs,
855 const RpcOptions& rpc_options);
856
857 //
858 // Waiting for individual backends to be seen by the client
859 //
860
861 struct WaitForBackendOptions {
862 // If true, resets the backend counters before returning.
863 bool reset_counters = true;
864 // How long to wait for the backend(s) to see requests.
865 // Will be multiplied by grpc_test_slowdown_factor().
866 int timeout_ms = 15000;
867
868 WaitForBackendOptions() {}
869
870 WaitForBackendOptions& set_reset_counters(bool enable) {
871 reset_counters = enable;
872 return *this;
873 }
874
875 WaitForBackendOptions& set_timeout_ms(int ms) {
876 timeout_ms = ms;
877 return *this;
878 }
879 };
880
881 // Sends RPCs until all of the backends in the specified range see requests.
882 // The check_status callback will be invoked to check the status of
883 // every RPC; if null, the default is to check that the RPC succeeded.
884 // Returns the total number of RPCs sent.
885 size_t WaitForAllBackends(
886 const grpc_core::DebugLocation& debug_location, size_t start_index = 0,
887 size_t stop_index = 0,
888 std::function<void(const RpcResult&)> check_status = nullptr,
889 const WaitForBackendOptions& wait_options = WaitForBackendOptions(),
890 const RpcOptions& rpc_options = RpcOptions());
891
892 // Sends RPCs until the backend at index backend_idx sees requests.
893 void WaitForBackend(
894 const grpc_core::DebugLocation& debug_location, size_t backend_idx,
895 std::function<void(const RpcResult&)> check_status = nullptr,
896 const WaitForBackendOptions& wait_options = WaitForBackendOptions(),
897 const RpcOptions& rpc_options = RpcOptions()) {
898 WaitForAllBackends(debug_location, backend_idx, backend_idx + 1,
899 check_status, wait_options, rpc_options);
900 }
901
902 //
903 // Waiting for xDS NACKs
904 //
905 // These methods send RPCs in a loop until they see a NACK from the
906 // xDS server, or until a timeout expires.
907
908 // Sends RPCs until get_state() returns a response.
909 absl::optional<AdsServiceImpl::ResponseState> WaitForNack(
910 const grpc_core::DebugLocation& debug_location,
911 std::function<absl::optional<AdsServiceImpl::ResponseState>()> get_state,
912 const RpcOptions& rpc_options = RpcOptions(),
913 StatusCode expected_status = StatusCode::UNAVAILABLE);
914
915 // Sends RPCs until an LDS NACK is seen.
916 absl::optional<AdsServiceImpl::ResponseState> WaitForLdsNack(
917 const grpc_core::DebugLocation& debug_location,
918 const RpcOptions& rpc_options = RpcOptions(),
919 StatusCode expected_status = StatusCode::UNAVAILABLE) {
920 return WaitForNack(
921 debug_location,
922 [&]() { return balancer_->ads_service()->lds_response_state(); },
923 rpc_options, expected_status);
924 }
925
926 // Sends RPCs until an RDS NACK is seen.
927 absl::optional<AdsServiceImpl::ResponseState> WaitForRdsNack(
928 const grpc_core::DebugLocation& debug_location,
929 const RpcOptions& rpc_options = RpcOptions(),
930 StatusCode expected_status = StatusCode::UNAVAILABLE) {
931 return WaitForNack(
932 debug_location,
933 [&]() { return RouteConfigurationResponseState(balancer_.get()); },
934 rpc_options, expected_status);
935 }
936
937 // Sends RPCs until a CDS NACK is seen.
938 absl::optional<AdsServiceImpl::ResponseState> WaitForCdsNack(
939 const grpc_core::DebugLocation& debug_location,
940 const RpcOptions& rpc_options = RpcOptions(),
941 StatusCode expected_status = StatusCode::UNAVAILABLE) {
942 return WaitForNack(
943 debug_location,
944 [&]() { return balancer_->ads_service()->cds_response_state(); },
945 rpc_options, expected_status);
946 }
947
948 // Sends RPCs until an EDS NACK is seen.
949 absl::optional<AdsServiceImpl::ResponseState> WaitForEdsNack(
950 const grpc_core::DebugLocation& debug_location,
951 const RpcOptions& rpc_options = RpcOptions()) {
952 return WaitForNack(
953 debug_location,
954 [&]() { return balancer_->ads_service()->eds_response_state(); },
955 rpc_options);
956 }
957
958 // Convenient front-end to wait for RouteConfiguration to be NACKed,
959 // regardless of whether it's sent in LDS or RDS.
960 absl::optional<AdsServiceImpl::ResponseState> WaitForRouteConfigNack(
961 const grpc_core::DebugLocation& debug_location,
962 const RpcOptions& rpc_options = RpcOptions(),
963 StatusCode expected_status = StatusCode::UNAVAILABLE) {
964 if (GetParam().enable_rds_testing()) {
965 return WaitForRdsNack(debug_location, rpc_options, expected_status);
966 }
967 return WaitForLdsNack(debug_location, rpc_options, expected_status);
968 }
969
970 // Convenient front-end for accessing xDS response state for a
971 // RouteConfiguration, regardless of whether it's sent in LDS or RDS.
972 absl::optional<AdsServiceImpl::ResponseState> RouteConfigurationResponseState(
973 BalancerServerThread* balancer) const {
974 AdsServiceImpl* ads_service = balancer->ads_service();
975 if (GetParam().enable_rds_testing()) {
976 return ads_service->rds_response_state();
977 }
978 return ads_service->lds_response_state();
979 }
980
981 //
982 // Miscellaneous helper methods
983 //
984
985 // There is slight difference between time fetched by GPR and by C++ system
986 // clock API. It's unclear if they are using the same syscall, but we do know
987 // GPR round the number at millisecond-level. This creates a 1ms difference,
988 // which could cause flake.
989 static grpc_core::Timestamp NowFromCycleCounter() {
990 return grpc_core::Timestamp::FromTimespecRoundDown(
991 gpr_now(GPR_CLOCK_MONOTONIC));
992 }
993
994 // Sets duration_proto to duration times grpc_test_slowdown_factor().
995 static void SetProtoDuration(grpc_core::Duration duration,
996 google::protobuf::Duration* duration_proto);
997
998 // Returns the number of RPCs needed to pass error_tolerance at 99.99994%
999 // chance. Rolling dices in drop/fault-injection generates a binomial
1000 // distribution (if our code is not horribly wrong). Let's make "n" the number
1001 // of samples, "p" the probability. If we have np>5 & n(1-p)>5, we can
1002 // approximately treat the binomial distribution as a normal distribution.
1003 //
1004 // For normal distribution, we can easily look up how many standard deviation
1005 // we need to reach 99.995%. Based on Wiki's table
1006 // https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule, we need 5.00
1007 // sigma (standard deviation) to cover the probability area of 99.99994%. In
1008 // another word, for a sample with size "n" probability "p" error-tolerance
1009 // "k", we want the error always land within 5.00 sigma. The sigma of
1010 // binominal distribution and be computed as sqrt(np(1-p)). Hence, we have
1011 // the equation:
1012 //
1013 // kn <= 5.00 * sqrt(np(1-p))
1014 // TODO(yashykt): The above explanation assumes a normal distribution, but we
1015 // use a uniform distribution instead. We need a better estimate of how many
1016 // RPCs are needed with what error tolerance.
1017 static size_t ComputeIdealNumRpcs(double p, double error_tolerance) {
1018 GPR_ASSERT(p >= 0 && p <= 1);
1019 size_t num_rpcs =
1020 ceil(p * (1 - p) * 5.00 * 5.00 / error_tolerance / error_tolerance);
1021 gpr_log(GPR_INFO,
1022 "Sending %" PRIuPTR
1023 " RPCs for percentage=%.3f error_tolerance=%.3f",
1024 num_rpcs, p, error_tolerance);
1025 return num_rpcs;
1026 }
1027
1028 // Returns the contents of the specified file.
1029 static std::string ReadFile(const char* file_path);
1030
1031 // Returns a private key pair, read from local files.
1032 static grpc_core::PemKeyCertPairList ReadTlsIdentityPair(
1033 const char* key_path, const char* cert_path);
1034
1035 // Returns client credentials suitable for using as fallback
1036 // credentials for XdsCredentials.
1037 static std::shared_ptr<ChannelCredentials> CreateTlsFallbackCredentials();
1038
1039 bool ipv6_only_ = false;
1040
1041 std::unique_ptr<BalancerServerThread> balancer_;
1042
1043 std::shared_ptr<Channel> channel_;
1044 std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
1045 std::unique_ptr<grpc::testing::EchoTest1Service::Stub> stub1_;
1046 std::unique_ptr<grpc::testing::EchoTest2Service::Stub> stub2_;
1047
1048 std::vector<std::unique_ptr<BackendServerThread>> backends_;
1049
1050 // Default xDS resources.
1051 Listener default_listener_;
1052 RouteConfiguration default_route_config_;
1053 Listener default_server_listener_;
1054 RouteConfiguration default_server_route_config_;
1055 Cluster default_cluster_;
1056
1057 int xds_drain_grace_time_ms_ = 10 * 60 * 1000; // 10 mins
1058
1059 bool bootstrap_contents_from_env_var_;
1060 std::string bootstrap_;
1061 char* bootstrap_file_ = nullptr;
1062 absl::InlinedVector<grpc_arg, 3> xds_channel_args_to_add_;
1063 grpc_channel_args xds_channel_args_;
1064 };
1065
1066 } // namespace testing
1067 } // namespace grpc