Debian Codegraph @

test/cpp/end2end/xds/xds_server.h

raw ◀ ▶
1 Debian patch touch this file
1 //
2 // Copyright 2017 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #ifndef GRPC_TEST_CPP_END2END_XDS_XDS_SERVER_H
18 #define GRPC_TEST_CPP_END2END_XDS_XDS_SERVER_H
19
20 #include <deque>
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/types/optional.h"
•30 #include "absl/strings/numbers.h"
31
32 #include <grpc/support/log.h>
33
34 #include "src/core/lib/address_utils/parse_address.h"
35 #include "src/core/lib/gprpp/sync.h"
36 #include "src/proto/grpc/testing/xds/v3/ads.grpc.pb.h"
37 #include "src/proto/grpc/testing/xds/v3/cluster.grpc.pb.h"
38 #include "src/proto/grpc/testing/xds/v3/discovery.grpc.pb.h"
39 #include "src/proto/grpc/testing/xds/v3/discovery.pb.h"
40 #include "src/proto/grpc/testing/xds/v3/endpoint.grpc.pb.h"
41 #include "src/proto/grpc/testing/xds/v3/listener.grpc.pb.h"
42 #include "src/proto/grpc/testing/xds/v3/lrs.grpc.pb.h"
43 #include "src/proto/grpc/testing/xds/v3/route.grpc.pb.h"
44 #include "test/core/util/test_config.h"
45 #include "test/cpp/end2end/counted_service.h"
46
47 namespace grpc {
48 namespace testing {
49
50 constexpr char kLdsTypeUrl[] =
51 "type.googleapis.com/envoy.config.listener.v3.Listener";
52 constexpr char kRdsTypeUrl[] =
53 "type.googleapis.com/envoy.config.route.v3.RouteConfiguration";
54 constexpr char kCdsTypeUrl[] =
55 "type.googleapis.com/envoy.config.cluster.v3.Cluster";
56 constexpr char kEdsTypeUrl[] =
57 "type.googleapis.com/envoy.config.endpoint.v3.ClusterLoadAssignment";
58
59 // An ADS service implementation.
60 class AdsServiceImpl
61 : public CountedService<
62 ::envoy::service::discovery::v3::AggregatedDiscoveryService::Service>,
63 public std::enable_shared_from_this<AdsServiceImpl> {
64 public:
65 // State for a given xDS resource type.
66 struct ResponseState {
67 enum State {
68 ACKED, // ACK received.
69 NACKED, // NACK received; error_message will contain the error.
70 };
71 State state = ACKED;
72 std::string error_message;
73 };
74
75 AdsServiceImpl() {}
76
77 void set_wrap_resources(bool wrap_resources) {
78 grpc_core::MutexLock lock(&ads_mu_);
79 wrap_resources_ = wrap_resources;
80 }
81
82 void set_inject_bad_resources_for_resource_type(const std::string& type_url) {
83 grpc_core::MutexLock lock(&ads_mu_);
84 inject_bad_resources_for_resource_type_ = type_url;
85 }
86
87 // Sets a resource to a particular value, overwriting any previous value.
88 void SetResource(google::protobuf::Any resource, const std::string& type_url,
89 const std::string& name);
90
91 // Removes a resource from the server's state.
92 void UnsetResource(const std::string& type_url, const std::string& name);
93
94 void SetLdsResource(const ::envoy::config::listener::v3::Listener& listener) {
95 google::protobuf::Any resource;
96 resource.PackFrom(listener);
97 SetResource(std::move(resource), kLdsTypeUrl, listener.name());
98 }
99
100 void SetRdsResource(
101 const ::envoy::config::route::v3::RouteConfiguration& route) {
102 google::protobuf::Any resource;
103 resource.PackFrom(route);
104 SetResource(std::move(resource), kRdsTypeUrl, route.name());
105 }
106
107 void SetCdsResource(const ::envoy::config::cluster::v3::Cluster& cluster) {
108 google::protobuf::Any resource;
109 resource.PackFrom(cluster);
110 SetResource(std::move(resource), kCdsTypeUrl, cluster.name());
111 }
112
113 void SetEdsResource(
114 const ::envoy::config::endpoint::v3::ClusterLoadAssignment& assignment) {
115 google::protobuf::Any resource;
116 resource.PackFrom(assignment);
117 SetResource(std::move(resource), kEdsTypeUrl, assignment.cluster_name());
118 }
119
120 // Tells the server to ignore requests from the client for a given
121 // resource type.
122 void IgnoreResourceType(const std::string& type_url) {
123 grpc_core::MutexLock lock(&ads_mu_);
124 resource_types_to_ignore_.emplace(type_url);
125 }
126
127 // Sets the minimum version that the server will accept for a given
128 // resource type. Will cause a gmock expectation failure if we see a
129 // lower version.
130 void SetResourceMinVersion(const std::string& type_url, int version) {
131 grpc_core::MutexLock lock(&ads_mu_);
132 resource_type_min_versions_[type_url] = version;
133 }
134
135 // Get the list of response state for each resource type.
136 // TODO(roth): Consider adding an absl::Notification-based mechanism
137 // here to avoid the need for tests to poll the response state.
138 absl::optional<ResponseState> GetResponseState(const std::string& type_url) {
139 grpc_core::MutexLock lock(&ads_mu_);
140 if (resource_type_response_state_[type_url].empty()) {
141 return absl::nullopt;
142 }
143 auto response = resource_type_response_state_[type_url].front();
144 resource_type_response_state_[type_url].pop_front();
145 return response;
146 }
147 absl::optional<ResponseState> lds_response_state() {
148 return GetResponseState(kLdsTypeUrl);
149 }
150 absl::optional<ResponseState> rds_response_state() {
151 return GetResponseState(kRdsTypeUrl);
152 }
153 absl::optional<ResponseState> cds_response_state() {
154 return GetResponseState(kCdsTypeUrl);
155 }
156 absl::optional<ResponseState> eds_response_state() {
157 return GetResponseState(kEdsTypeUrl);
158 }
159
160 // Starts the service.
161 void Start();
162
163 // Shuts down the service.
164 void Shutdown();
165
166 // Returns the peer names of clients currently connected to the service.
167 std::set<std::string> clients() {
168 grpc_core::MutexLock lock(&clients_mu_);
169 return clients_;
170 }
171
172 void ForceADSFailure(Status status) {
173 grpc_core::MutexLock lock(&ads_mu_);
174 forced_ads_failure_ = std::move(status);
175 }
176
177 private:
178 // A queue of resource type/name pairs that have changed since the client
179 // subscribed to them.
180 using UpdateQueue = std::deque<
181 std::pair<std::string /* type url */, std::string /* resource name */>>;
182
183 // A struct representing a client's subscription to a particular resource.
184 struct SubscriptionState {
185 // The queue upon which to place updates when the resource is updated.
186 UpdateQueue* update_queue;
187 };
188
189 // A struct representing the a client's subscription to all the resources.
190 using SubscriptionNameMap =
191 std::map<std::string /* resource_name */, SubscriptionState>;
192 using SubscriptionMap =
193 std::map<std::string /* type_url */, SubscriptionNameMap>;
194
195 // Sent state for a given resource type.
196 struct SentState {
197 int nonce = 0;
198 int resource_type_version = 0;
199 };
200
201 // A struct representing the current state for an individual resource.
202 struct ResourceState {
203 // The resource itself, if present.
204 absl::optional<google::protobuf::Any> resource;
205 // The resource type version that this resource was last updated in.
206 int resource_type_version = 0;
207 // A list of subscriptions to this resource.
208 std::set<SubscriptionState*> subscriptions;
209 };
210
211 // The current state for all individual resources of a given type.
212 using ResourceNameMap =
213 std::map<std::string /* resource_name */, ResourceState>;
214
215 struct ResourceTypeState {
216 int resource_type_version = 0;
217 ResourceNameMap resource_name_map;
218 };
219
220 using ResourceMap = std::map<std::string /* type_url */, ResourceTypeState>;
221
222 using DiscoveryRequest = ::envoy::service::discovery::v3::DiscoveryRequest;
223 using DiscoveryResponse = ::envoy::service::discovery::v3::DiscoveryResponse;
224 using Stream = ServerReaderWriter<DiscoveryResponse, DiscoveryRequest>;
225
226 Status StreamAggregatedResources(ServerContext* context,
227 Stream* stream) override {
228 gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources starts", this);
229 {
230 grpc_core::MutexLock lock(&ads_mu_);
231 if (forced_ads_failure_.has_value()) {
232 gpr_log(GPR_INFO,
233 "ADS[%p]: StreamAggregatedResources forcing early failure "
234 "with status code: %d, message: %s",
235 this, forced_ads_failure_.value().error_code(),
236 forced_ads_failure_.value().error_message().c_str());
237 return forced_ads_failure_.value();
238 }
239 }
240 AddClient(context->peer());
241 // Take a reference of the AdsServiceImpl object, which will go
242 // out of scope when this request handler returns. This ensures
243 // that the parent won't be destroyed until this stream is complete.
244 std::shared_ptr<AdsServiceImpl> ads_service_impl = shared_from_this();
245 // Resources (type/name pairs) that have changed since the client
246 // subscribed to them.
247 UpdateQueue update_queue;
248 // Resources that the client will be subscribed to keyed by resource type
249 // url.
250 SubscriptionMap subscription_map;
251 // Sent state for each resource type.
252 std::map<std::string /*type_url*/, SentState> sent_state_map;
253 // Spawn a thread to read requests from the stream.
254 // Requests will be delivered to this thread in a queue.
255 std::deque<DiscoveryRequest> requests;
256 bool stream_closed = false;
257 std::thread reader(std::bind(&AdsServiceImpl::BlockingRead, this, stream,
258 &requests, &stream_closed));
259 // Main loop to process requests and updates.
260 while (true) {
261 // Boolean to keep track if the loop received any work to do: a
262 // request or an update; regardless whether a response was actually
263 // sent out.
264 bool did_work = false;
265 // Look for new requests and decide what to handle.
266 absl::optional<DiscoveryResponse> response;
267 {
268 grpc_core::MutexLock lock(&ads_mu_);
269 // If the stream has been closed or our parent is being shut
270 // down, stop immediately.
271 if (stream_closed || ads_done_) break;
272 // Otherwise, see if there's a request to read from the queue.
273 if (!requests.empty()) {
274 DiscoveryRequest request = std::move(requests.front());
275 requests.pop_front();
276 did_work = true;
277 gpr_log(GPR_INFO,
278 "ADS[%p]: Received request for type %s with content %s", this,
279 request.type_url().c_str(), request.DebugString().c_str());
280 SentState& sent_state = sent_state_map[request.type_url()];
281 // Process request.
282 ProcessRequest(request, &update_queue, &subscription_map, &sent_state,
283 &response);
284 }
285 }
286 if (response.has_value()) {
287 gpr_log(GPR_INFO, "ADS[%p]: Sending response: %s", this,
288 response->DebugString().c_str());
289 stream->Write(response.value());
290 }
291 response.reset();
292 // Look for updates and decide what to handle.
293 {
294 grpc_core::MutexLock lock(&ads_mu_);
295 if (!update_queue.empty()) {
296 const std::string resource_type =
297 std::move(update_queue.front().first);
298 const std::string resource_name =
299 std::move(update_queue.front().second);
300 update_queue.pop_front();
301 did_work = true;
302 SentState& sent_state = sent_state_map[resource_type];
303 ProcessUpdate(resource_type, resource_name, &subscription_map,
304 &sent_state, &response);
305 }
306 }
307 if (response.has_value()) {
308 gpr_log(GPR_INFO, "ADS[%p]: Sending update response: %s", this,
309 response->DebugString().c_str());
310 stream->Write(response.value());
311 }
312 {
313 grpc_core::MutexLock lock(&ads_mu_);
314 if (ads_done_) {
315 break;
316 }
317 }
318 // If we didn't find anything to do, delay before the next loop
319 // iteration; otherwise, check whether we should exit and then
320 // immediately continue.
321 gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(did_work ? 0 : 10));
322 }
323 // Done with main loop. Clean up before returning.
324 // Join reader thread.
325 reader.join();
326 // Clean up any subscriptions that were still active when the call
327 // finished.
328 {
329 grpc_core::MutexLock lock(&ads_mu_);
330 for (auto& p : subscription_map) {
331 const std::string& type_url = p.first;
332 SubscriptionNameMap& subscription_name_map = p.second;
333 for (auto& q : subscription_name_map) {
334 const std::string& resource_name = q.first;
335 SubscriptionState& subscription_state = q.second;
336 ResourceNameMap& resource_name_map =
337 resource_map_[type_url].resource_name_map;
338 ResourceState& resource_state = resource_name_map[resource_name];
339 resource_state.subscriptions.erase(&subscription_state);
340 }
341 }
342 }
343 gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources done", this);
344 RemoveClient(context->peer());
345 return Status::OK;
346 }
347
348 // Processes a response read from the client.
349 // Populates response if needed.
350 void ProcessRequest(const DiscoveryRequest& request,
351 UpdateQueue* update_queue,
352 SubscriptionMap* subscription_map, SentState* sent_state,
353 absl::optional<DiscoveryResponse>* response)
354 ABSL_EXCLUSIVE_LOCKS_REQUIRED(ads_mu_) {
355 // Check the nonce sent by the client, if any.
356 // (This will be absent on the first request on a stream.)
357 if (request.response_nonce().empty()) {
358 int client_resource_type_version = 0;
359 if (!request.version_info().empty()) {
360 GPR_ASSERT(absl::SimpleAtoi(request.version_info(),
361 &client_resource_type_version));
362 }
363 EXPECT_GE(client_resource_type_version,
364 resource_type_min_versions_[request.type_url()])
365 << "resource_type: " << request.type_url();
366 } else {
367 int client_nonce;
368 GPR_ASSERT(absl::SimpleAtoi(request.response_nonce(), &client_nonce));
369 // Check for ACK or NACK.
370 ResponseState response_state;
371 if (!request.has_error_detail()) {
372 response_state.state = ResponseState::ACKED;
373 gpr_log(GPR_INFO, "ADS[%p]: client ACKed resource_type=%s version=%s",
374 this, request.type_url().c_str(),
375 request.version_info().c_str());
376 } else {
377 response_state.state = ResponseState::NACKED;
378 EXPECT_EQ(request.error_detail().code(), GRPC_STATUS_INVALID_ARGUMENT);
379 response_state.error_message = request.error_detail().message();
380 gpr_log(GPR_INFO,
381 "ADS[%p]: client NACKed resource_type=%s version=%s: %s", this,
382 request.type_url().c_str(), request.version_info().c_str(),
383 response_state.error_message.c_str());
384 }
385 resource_type_response_state_[request.type_url()].emplace_back(
386 std::move(response_state));
387 // Ignore requests with stale nonces.
388 if (client_nonce < sent_state->nonce) return;
389 }
390 // Ignore resource types as requested by tests.
391 if (resource_types_to_ignore_.find(request.type_url()) !=
392 resource_types_to_ignore_.end()) {
393 return;
394 }
395 // Inject bad resources if needed.
396 if (inject_bad_resources_for_resource_type_ == request.type_url()) {
397 response->emplace();
398 // Unparseable Resource wrapper.
399 auto* resource = (*response)->add_resources();
400 resource->set_type_url(
401 "type.googleapis.com/envoy.service.discovery.v3.Resource");
402 resource->set_value(std::string("\0", 1));
403 // Unparseable resource within Resource wrapper.
404 envoy::service::discovery::v3::Resource resource_wrapper;
405 resource_wrapper.set_name("foo");
406 resource = resource_wrapper.mutable_resource();
407 resource->set_type_url(request.type_url());
408 resource->set_value(std::string("\0", 1));
409 (*response)->add_resources()->PackFrom(resource_wrapper);
410 }
411 // Look at all the resource names in the request.
412 auto& subscription_name_map = (*subscription_map)[request.type_url()];
413 auto& resource_type_state = resource_map_[request.type_url()];
414 auto& resource_name_map = resource_type_state.resource_name_map;
415 std::set<std::string> resources_in_current_request;
416 std::set<std::string> resources_added_to_response;
417 for (const std::string& resource_name : request.resource_names()) {
418 resources_in_current_request.emplace(resource_name);
419 auto& subscription_state = subscription_name_map[resource_name];
420 auto& resource_state = resource_name_map[resource_name];
421 // Subscribe if needed.
422 // Send the resource in the response if either (a) this is
423 // a new subscription or (b) there is an updated version of
424 // this resource to send.
425 if (MaybeSubscribe(request.type_url(), resource_name, &subscription_state,
426 &resource_state, update_queue) ||
427 ClientNeedsResourceUpdate(resource_type_state, resource_state,
428 sent_state->resource_type_version)) {
429 gpr_log(GPR_INFO, "ADS[%p]: Sending update for type=%s name=%s", this,
430 request.type_url().c_str(), resource_name.c_str());
431 resources_added_to_response.emplace(resource_name);
432 if (!response->has_value()) response->emplace();
433 if (resource_state.resource.has_value()) {
434 auto* resource = (*response)->add_resources();
435 resource->CopyFrom(resource_state.resource.value());
436 if (wrap_resources_) {
437 envoy::service::discovery::v3::Resource resource_wrapper;
438 *resource_wrapper.mutable_resource() = std::move(*resource);
439 resource->PackFrom(resource_wrapper);
440 }
441 }
442 } else {
443 gpr_log(GPR_INFO,
444 "ADS[%p]: client does not need update for type=%s name=%s",
445 this, request.type_url().c_str(), resource_name.c_str());
446 }
447 }
448 // Process unsubscriptions for any resource no longer
449 // present in the request's resource list.
450 ProcessUnsubscriptions(request.type_url(), resources_in_current_request,
451 &subscription_name_map, &resource_name_map);
452 // Construct response if needed.
453 if (!resources_added_to_response.empty()) {
454 CompleteBuildingDiscoveryResponse(
455 request.type_url(), resource_type_state.resource_type_version,
456 subscription_name_map, resources_added_to_response, sent_state,
457 &response->value());
458 }
459 }
460
461 // Processes a resource update from the test.
462 // Populates response if needed.
463 void ProcessUpdate(const std::string& resource_type,
464 const std::string& resource_name,
465 SubscriptionMap* subscription_map, SentState* sent_state,
466 absl::optional<DiscoveryResponse>* response)
467 ABSL_EXCLUSIVE_LOCKS_REQUIRED(ads_mu_) {
468 gpr_log(GPR_INFO, "ADS[%p]: Received update for type=%s name=%s", this,
469 resource_type.c_str(), resource_name.c_str());
470 auto& subscription_name_map = (*subscription_map)[resource_type];
471 auto& resource_type_state = resource_map_[resource_type];
472 auto& resource_name_map = resource_type_state.resource_name_map;
473 auto it = subscription_name_map.find(resource_name);
474 if (it != subscription_name_map.end()) {
475 ResourceState& resource_state = resource_name_map[resource_name];
476 if (ClientNeedsResourceUpdate(resource_type_state, resource_state,
477 sent_state->resource_type_version)) {
478 gpr_log(GPR_INFO, "ADS[%p]: Sending update for type=%s name=%s", this,
479 resource_type.c_str(), resource_name.c_str());
480 response->emplace();
481 if (resource_state.resource.has_value()) {
482 auto* resource = (*response)->add_resources();
483 resource->CopyFrom(resource_state.resource.value());
484 }
485 CompleteBuildingDiscoveryResponse(
486 resource_type, resource_type_state.resource_type_version,
487 subscription_name_map, {resource_name}, sent_state,
488 &response->value());
489 }
490 }
491 }
492
493 // Starting a thread to do blocking read on the stream until cancel.
494 void BlockingRead(Stream* stream, std::deque<DiscoveryRequest>* requests,
495 bool* stream_closed) {
496 DiscoveryRequest request;
497 bool seen_first_request = false;
498 while (stream->Read(&request)) {
499 if (!seen_first_request) {
500 EXPECT_TRUE(request.has_node());
501 EXPECT_THAT(request.node().client_features(),
502 ::testing::UnorderedElementsAre(
503 "envoy.lb.does_not_support_overprovisioning",
504 "xds.config.resource-in-sotw"));
505 seen_first_request = true;
506 }
507 {
508 grpc_core::MutexLock lock(&ads_mu_);
509 requests->emplace_back(std::move(request));
510 }
511 }
512 gpr_log(GPR_INFO, "ADS[%p]: Null read, stream closed", this);
513 grpc_core::MutexLock lock(&ads_mu_);
514 *stream_closed = true;
515 }
516
517 // Completing the building a DiscoveryResponse by adding common information
518 // for all resources and by adding all subscribed resources for LDS and CDS.
519 void CompleteBuildingDiscoveryResponse(
520 const std::string& resource_type, const int version,
521 const SubscriptionNameMap& subscription_name_map,
522 const std::set<std::string>& resources_added_to_response,
523 SentState* sent_state, DiscoveryResponse* response)
524 ABSL_EXCLUSIVE_LOCKS_REQUIRED(ads_mu_) {
525 response->set_type_url(resource_type);
526 response->set_version_info(std::to_string(version));
527 response->set_nonce(std::to_string(++sent_state->nonce));
528 if (resource_type == kLdsTypeUrl || resource_type == kCdsTypeUrl) {
529 // For LDS and CDS we must send back all subscribed resources
530 // (even the unchanged ones)
531 for (const auto& p : subscription_name_map) {
532 const std::string& resource_name = p.first;
533 if (resources_added_to_response.find(resource_name) ==
534 resources_added_to_response.end()) {
535 ResourceNameMap& resource_name_map =
536 resource_map_[resource_type].resource_name_map;
537 const ResourceState& resource_state =
538 resource_name_map[resource_name];
539 if (resource_state.resource.has_value()) {
540 auto* resource = response->add_resources();
541 resource->CopyFrom(resource_state.resource.value());
542 }
543 }
544 }
545 }
546 sent_state->resource_type_version = version;
547 }
548
549 // Checks whether the client needs to receive a newer version of
550 // the resource.
551 static bool ClientNeedsResourceUpdate(
552 const ResourceTypeState& resource_type_state,
553 const ResourceState& resource_state, int client_resource_type_version);
554
555 // Subscribes to a resource if not already subscribed:
556 // 1. Sets the update_queue field in subscription_state.
557 // 2. Adds subscription_state to resource_state->subscriptions.
558 bool MaybeSubscribe(const std::string& resource_type,
559 const std::string& resource_name,
560 SubscriptionState* subscription_state,
561 ResourceState* resource_state, UpdateQueue* update_queue);
562
563 // Removes subscriptions for resources no longer present in the
564 // current request.
565 void ProcessUnsubscriptions(
566 const std::string& resource_type,
567 const std::set<std::string>& resources_in_current_request,
568 SubscriptionNameMap* subscription_name_map,
569 ResourceNameMap* resource_name_map);
570
571 void AddClient(const std::string& client) {
572 grpc_core::MutexLock lock(&clients_mu_);
573 clients_.insert(client);
574 }
575
576 void RemoveClient(const std::string& client) {
577 grpc_core::MutexLock lock(&clients_mu_);
578 clients_.erase(client);
579 }
580
581 grpc_core::CondVar ads_cond_;
582 grpc_core::Mutex ads_mu_;
583 bool ads_done_ ABSL_GUARDED_BY(ads_mu_) = false;
584 std::map<std::string /* type_url */, std::deque<ResponseState>>
585 resource_type_response_state_ ABSL_GUARDED_BY(ads_mu_);
586 std::set<std::string /*resource_type*/> resource_types_to_ignore_
587 ABSL_GUARDED_BY(ads_mu_);
588 std::map<std::string /*resource_type*/, int> resource_type_min_versions_
589 ABSL_GUARDED_BY(ads_mu_);
590 // An instance data member containing the current state of all resources.
591 // Note that an entry will exist whenever either of the following is true:
592 // - The resource exists (i.e., has been created by SetResource() and has not
593 // yet been destroyed by UnsetResource()).
594 // - There is at least one subscription for the resource.
595 ResourceMap resource_map_ ABSL_GUARDED_BY(ads_mu_);
596 absl::optional<Status> forced_ads_failure_ ABSL_GUARDED_BY(ads_mu_);
597 bool wrap_resources_ ABSL_GUARDED_BY(ads_mu_) = false;
598 std::string inject_bad_resources_for_resource_type_ ABSL_GUARDED_BY(ads_mu_);
599
600 grpc_core::Mutex clients_mu_;
601 std::set<std::string> clients_ ABSL_GUARDED_BY(clients_mu_);
602 };
603
604 // An LRS service implementation.
605 class LrsServiceImpl
606 : public CountedService<
607 ::envoy::service::load_stats::v3::LoadReportingService::Service>,
608 public std::enable_shared_from_this<LrsServiceImpl> {
609 public:
610 // Stats reported by client.
611 class ClientStats {
612 public:
613 // Stats for a given locality.
614 struct LocalityStats {
615 LocalityStats() {}
616
617 // Converts from proto message class.
618 explicit LocalityStats(
619 const ::envoy::config::endpoint::v3::UpstreamLocalityStats&
620 upstream_locality_stats)
621 : total_successful_requests(
622 upstream_locality_stats.total_successful_requests()),
623 total_requests_in_progress(
624 upstream_locality_stats.total_requests_in_progress()),
625 total_error_requests(
626 upstream_locality_stats.total_error_requests()),
627 total_issued_requests(
628 upstream_locality_stats.total_issued_requests()) {}
629
630 LocalityStats& operator+=(const LocalityStats& other) {
631 total_successful_requests += other.total_successful_requests;
632 total_requests_in_progress += other.total_requests_in_progress;
633 total_error_requests += other.total_error_requests;
634 total_issued_requests += other.total_issued_requests;
635 return *this;
636 }
637
638 uint64_t total_successful_requests = 0;
639 uint64_t total_requests_in_progress = 0;
640 uint64_t total_error_requests = 0;
641 uint64_t total_issued_requests = 0;
642 };
643
644 ClientStats() {}
645
646 // Converts from proto message class.
647 explicit ClientStats(
648 const ::envoy::config::endpoint::v3::ClusterStats& cluster_stats)
649 : cluster_name_(cluster_stats.cluster_name()),
650 eds_service_name_(cluster_stats.cluster_service_name()),
651 total_dropped_requests_(cluster_stats.total_dropped_requests()) {
652 for (const auto& input_locality_stats :
653 cluster_stats.upstream_locality_stats()) {
654 locality_stats_.emplace(input_locality_stats.locality().sub_zone(),
655 LocalityStats(input_locality_stats));
656 }
657 for (const auto& input_dropped_requests :
658 cluster_stats.dropped_requests()) {
659 dropped_requests_.emplace(input_dropped_requests.category(),
660 input_dropped_requests.dropped_count());
661 }
662 }
663
664 const std::string& cluster_name() const { return cluster_name_; }
665 const std::string& eds_service_name() const { return eds_service_name_; }
666
667 const std::map<std::string, LocalityStats>& locality_stats() const {
668 return locality_stats_;
669 }
670
671 uint64_t total_successful_requests() const;
672 uint64_t total_requests_in_progress() const;
673 uint64_t total_error_requests() const;
674 uint64_t total_issued_requests() const;
675
676 uint64_t total_dropped_requests() const { return total_dropped_requests_; }
677
678 uint64_t dropped_requests(const std::string& category) const;
679
680 ClientStats& operator+=(const ClientStats& other);
681
682 private:
683 std::string cluster_name_;
684 std::string eds_service_name_;
685 std::map<std::string, LocalityStats> locality_stats_;
686 uint64_t total_dropped_requests_ = 0;
687 std::map<std::string, uint64_t> dropped_requests_;
688 };
689
690 LrsServiceImpl(int client_load_reporting_interval_seconds,
691 std::set<std::string> cluster_names)
692 : client_load_reporting_interval_seconds_(
693 client_load_reporting_interval_seconds),
694 cluster_names_(std::move(cluster_names)) {}
695
696 // Must be called before the LRS call is started.
697 void set_send_all_clusters(bool send_all_clusters) {
698 send_all_clusters_ = send_all_clusters;
699 }
700 void set_cluster_names(const std::set<std::string>& cluster_names) {
701 cluster_names_ = cluster_names;
702 }
703
704 void Start() ABSL_LOCKS_EXCLUDED(lrs_mu_, load_report_mu_);
705
706 void Shutdown();
707
708 std::vector<ClientStats> WaitForLoadReport();
709
710 private:
711 using LoadStatsRequest = ::envoy::service::load_stats::v3::LoadStatsRequest;
712 using LoadStatsResponse = ::envoy::service::load_stats::v3::LoadStatsResponse;
713 using Stream = ServerReaderWriter<LoadStatsResponse, LoadStatsRequest>;
714
715 Status StreamLoadStats(ServerContext* /*context*/, Stream* stream) override {
716 gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats starts", this);
717 EXPECT_GT(client_load_reporting_interval_seconds_, 0);
718 // Take a reference of the LrsServiceImpl object, reference will go
719 // out of scope after this method exits.
720 std::shared_ptr<LrsServiceImpl> lrs_service_impl = shared_from_this();
721 // Read initial request.
722 LoadStatsRequest request;
723 if (stream->Read(&request)) {
724 IncreaseRequestCount();
725 // Verify client features.
726 EXPECT_THAT(request.node().client_features(),
727 ::testing::Contains("envoy.lrs.supports_send_all_clusters"));
728 // Send initial response.
729 LoadStatsResponse response;
730 if (send_all_clusters_) {
731 response.set_send_all_clusters(true);
732 } else {
733 for (const std::string& cluster_name : cluster_names_) {
734 response.add_clusters(cluster_name);
735 }
736 }
737 response.mutable_load_reporting_interval()->set_seconds(
738 client_load_reporting_interval_seconds_ *
739 grpc_test_slowdown_factor());
740 stream->Write(response);
741 IncreaseResponseCount();
742 // Wait for report.
743 request.Clear();
744 while (stream->Read(&request)) {
745 gpr_log(GPR_INFO, "LRS[%p]: received client load report message: %s",
746 this, request.DebugString().c_str());
747 std::vector<ClientStats> stats;
748 for (const auto& cluster_stats : request.cluster_stats()) {
749 stats.emplace_back(cluster_stats);
750 }
751 grpc_core::MutexLock lock(&load_report_mu_);
752 result_queue_.emplace_back(std::move(stats));
753 if (load_report_cond_ != nullptr) {
754 load_report_cond_->Signal();
755 }
756 }
757 // Wait until notified done.
758 grpc_core::MutexLock lock(&lrs_mu_);
759 while (!lrs_done_) {
760 lrs_cv_.Wait(&lrs_mu_);
761 }
762 }
763 gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats done", this);
764 return Status::OK;
765 }
766
767 const int client_load_reporting_interval_seconds_;
768 bool send_all_clusters_ = false;
769 std::set<std::string> cluster_names_;
770
771 grpc_core::CondVar lrs_cv_;
772 grpc_core::Mutex lrs_mu_;
773 bool lrs_done_ ABSL_GUARDED_BY(lrs_mu_) = false;
774
775 grpc_core::Mutex load_report_mu_;
776 grpc_core::CondVar* load_report_cond_ ABSL_GUARDED_BY(load_report_mu_) =
777 nullptr;
778 std::deque<std::vector<ClientStats>> result_queue_
779 ABSL_GUARDED_BY(load_report_mu_);
780 };
781
782 } // namespace testing
783 } // namespace grpc
784
785 #endif // GRPC_TEST_CPP_END2END_XDS_XDS_SERVER_H