| 1 |
// |
| 2 |
// Copyright 2018 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 |
#include <grpc/support/port_platform.h> |
| 18 |
|
| 19 |
#include "src/core/ext/xds/xds_client.h" |
| 20 |
|
| 21 |
#include <inttypes.h> |
| 22 |
#include <string.h> |
| 23 |
|
| 24 |
#include <algorithm> |
| 25 |
|
| 26 |
#include "absl/strings/match.h" |
| 27 |
#include "absl/strings/str_cat.h" |
| 28 |
#include "absl/strings/str_join.h" |
| 29 |
#include "absl/strings/str_split.h" |
| 30 |
#include "absl/strings/string_view.h" |
| 31 |
#include "absl/strings/strip.h" |
| 32 |
#include "absl/types/optional.h" |
| 33 |
#include "upb/arena.h" |
| 34 |
|
| 35 |
#include <grpc/event_engine/event_engine.h> |
| 36 |
#include <grpc/support/log.h> |
| 37 |
|
| 38 |
#include "src/core/ext/xds/xds_api.h" |
| 39 |
#include "src/core/ext/xds/xds_bootstrap.h" |
| 40 |
#include "src/core/ext/xds/xds_client_stats.h" |
| 41 |
#include "src/core/lib/backoff/backoff.h" |
| 42 |
#include "src/core/lib/event_engine/default_event_engine.h" |
| 43 |
#include "src/core/lib/gprpp/debug_location.h" |
| 44 |
#include "src/core/lib/gprpp/orphanable.h" |
| 45 |
#include "src/core/lib/gprpp/ref_counted_ptr.h" |
| 46 |
#include "src/core/lib/gprpp/sync.h" |
| 47 |
#include "src/core/lib/iomgr/exec_ctx.h" |
| 48 |
#include "src/core/lib/uri/uri_parser.h" |
| 49 |
|
| 50 |
#define GRPC_XDS_INITIAL_CONNECT_BACKOFF_SECONDS 1 |
| 51 |
#define GRPC_XDS_RECONNECT_BACKOFF_MULTIPLIER 1.6 |
| 52 |
#define GRPC_XDS_RECONNECT_MAX_BACKOFF_SECONDS 120 |
| 53 |
#define GRPC_XDS_RECONNECT_JITTER 0.2 |
| 54 |
#define GRPC_XDS_MIN_CLIENT_LOAD_REPORTING_INTERVAL_MS 1000 |
| 55 |
|
| 56 |
namespace grpc_core { |
| 57 |
|
| 58 |
using ::grpc_event_engine::experimental::EventEngine; |
| 59 |
|
| 60 |
TraceFlag grpc_xds_client_trace(false, "xds_client"); |
| 61 |
TraceFlag grpc_xds_client_refcount_trace(false, "xds_client_refcount"); |
| 62 |
|
| 63 |
// |
| 64 |
// Internal class declarations |
| 65 |
// |
| 66 |
|
| 67 |
// An xds call wrapper that can restart a call upon failure. Holds a ref to |
| 68 |
// the xds channel. The template parameter is the kind of wrapped xds call. |
| 69 |
template <typename T> |
| 70 |
class XdsClient::ChannelState::RetryableCall |
| 71 |
: public InternallyRefCounted<RetryableCall<T>> { |
| 72 |
public: |
| 73 |
explicit RetryableCall(WeakRefCountedPtr<ChannelState> chand); |
| 74 |
|
| 75 |
// Disable thread-safety analysis because this method is called via |
| 76 |
// OrphanablePtr<>, but there's no way to pass the lock annotation |
| 77 |
// through there. |
| 78 |
void Orphan() override ABSL_NO_THREAD_SAFETY_ANALYSIS; |
| 79 |
|
| 80 |
void OnCallFinishedLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 81 |
|
| 82 |
T* calld() const { return calld_.get(); } |
| 83 |
ChannelState* chand() const { return chand_.get(); } |
| 84 |
|
| 85 |
bool IsCurrentCallOnChannel() const; |
| 86 |
|
| 87 |
private: |
| 88 |
void StartNewCallLocked(); |
| 89 |
void StartRetryTimerLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 90 |
|
| 91 |
void OnRetryTimer(); |
| 92 |
|
| 93 |
// The wrapped xds call that talks to the xds server. It's instantiated |
| 94 |
// every time we start a new call. It's null during call retry backoff. |
| 95 |
OrphanablePtr<T> calld_; |
| 96 |
// The owning xds channel. |
| 97 |
WeakRefCountedPtr<ChannelState> chand_; |
| 98 |
|
| 99 |
// Retry state. |
| 100 |
BackOff backoff_; |
| 101 |
absl::optional<EventEngine::TaskHandle> timer_handle_ |
| 102 |
ABSL_GUARDED_BY(&XdsClient::mu_); |
| 103 |
|
| 104 |
bool shutting_down_ = false; |
| 105 |
}; |
| 106 |
|
| 107 |
// Contains an ADS call to the xds server. |
| 108 |
class XdsClient::ChannelState::AdsCallState |
| 109 |
: public InternallyRefCounted<AdsCallState> { |
| 110 |
public: |
| 111 |
// The ctor and dtor should not be used directly. |
| 112 |
explicit AdsCallState(RefCountedPtr<RetryableCall<AdsCallState>> parent); |
| 113 |
|
| 114 |
void Orphan() override; |
| 115 |
|
| 116 |
RetryableCall<AdsCallState>* parent() const { return parent_.get(); } |
| 117 |
ChannelState* chand() const { return parent_->chand(); } |
| 118 |
XdsClient* xds_client() const { return chand()->xds_client(); } |
| 119 |
bool seen_response() const { return seen_response_; } |
| 120 |
|
| 121 |
void SubscribeLocked(const XdsResourceType* type, const XdsResourceName& name, |
| 122 |
bool delay_send) |
| 123 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 124 |
void UnsubscribeLocked(const XdsResourceType* type, |
| 125 |
const XdsResourceName& name, bool delay_unsubscription) |
| 126 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 127 |
|
| 128 |
bool HasSubscribedResources() const; |
| 129 |
|
| 130 |
private: |
| 131 |
class AdsResponseParser : public XdsApi::AdsResponseParserInterface { |
| 132 |
public: |
| 133 |
struct Result { |
| 134 |
const XdsResourceType* type; |
| 135 |
std::string type_url; |
| 136 |
std::string version; |
| 137 |
std::string nonce; |
| 138 |
std::vector<std::string> errors; |
| 139 |
std::map<std::string /*authority*/, std::set<XdsResourceKey>> |
| 140 |
resources_seen; |
| 141 |
bool have_valid_resources = false; |
| 142 |
}; |
| 143 |
|
| 144 |
explicit AdsResponseParser(AdsCallState* ads_call_state) |
| 145 |
: ads_call_state_(ads_call_state) {} |
| 146 |
|
| 147 |
absl::Status ProcessAdsResponseFields(AdsResponseFields fields) override |
| 148 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 149 |
|
| 150 |
void ParseResource(upb_Arena* arena, size_t idx, absl::string_view type_url, |
| 151 |
absl::string_view resource_name, |
| 152 |
absl::string_view serialized_resource) override |
| 153 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 154 |
|
| 155 |
void ResourceWrapperParsingFailed(size_t idx) override; |
| 156 |
|
| 157 |
Result TakeResult() { return std::move(result_); } |
| 158 |
|
| 159 |
private: |
| 160 |
XdsClient* xds_client() const { return ads_call_state_->xds_client(); } |
| 161 |
|
| 162 |
AdsCallState* ads_call_state_; |
| 163 |
const Timestamp update_time_ = Timestamp::Now(); |
| 164 |
Result result_; |
| 165 |
}; |
| 166 |
|
| 167 |
class ResourceTimer : public InternallyRefCounted<ResourceTimer> { |
| 168 |
public: |
| 169 |
ResourceTimer(const XdsResourceType* type, const XdsResourceName& name) |
| 170 |
: type_(type), name_(name) {} |
| 171 |
|
| 172 |
// Disable thread-safety analysis because this method is called via |
| 173 |
// OrphanablePtr<>, but there's no way to pass the lock annotation |
| 174 |
// through there. |
| 175 |
void Orphan() override ABSL_NO_THREAD_SAFETY_ANALYSIS { |
| 176 |
MaybeCancelTimer(); |
| 177 |
Unref(DEBUG_LOCATION, "Orphan"); |
| 178 |
} |
| 179 |
|
| 180 |
void MarkSubscriptionSendStarted() |
| 181 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) { |
| 182 |
subscription_sent_ = true; |
| 183 |
} |
| 184 |
|
| 185 |
void MaybeMarkSubscriptionSendComplete( |
| 186 |
RefCountedPtr<AdsCallState> ads_calld) |
| 187 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) { |
| 188 |
if (subscription_sent_) MaybeStartTimer(std::move(ads_calld)); |
| 189 |
} |
| 190 |
|
| 191 |
void MarkSeen() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) { |
| 192 |
resource_seen_ = true; |
| 193 |
MaybeCancelTimer(); |
| 194 |
} |
| 195 |
|
| 196 |
void MaybeCancelTimer() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) { |
| 197 |
if (timer_handle_.has_value() && |
| 198 |
ads_calld_->xds_client()->engine()->Cancel(*timer_handle_)) { |
| 199 |
timer_handle_.reset(); |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
private: |
| 204 |
void MaybeStartTimer(RefCountedPtr<AdsCallState> ads_calld) |
| 205 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) { |
| 206 |
// Don't start timer if we've already either seen the resource or |
| 207 |
// marked it as non-existing. |
| 208 |
// Note: There are edge cases where we can have seen the resource |
| 209 |
// before we have sent the initial subscription request, such as |
| 210 |
// when we unsubscribe and then resubscribe to a given resource |
| 211 |
// and then get a response containing that resource, all while a |
| 212 |
// send_message op is in flight. |
| 213 |
if (resource_seen_) return; |
| 214 |
// Don't start timer if we haven't yet sent the initial subscription |
| 215 |
// request for the resource. |
| 216 |
if (!subscription_sent_) return; |
| 217 |
// Don't start timer if it's already running. |
| 218 |
if (timer_handle_.has_value()) return; |
| 219 |
// Check if we already have a cached version of this resource |
| 220 |
// (i.e., if this is the initial request for the resource after an |
| 221 |
// ADS stream restart). If so, we don't start the timer, because |
| 222 |
// (a) we already have the resource and (b) the server may |
| 223 |
// optimize by not resending the resource that we already have. |
| 224 |
auto& authority_state = |
| 225 |
ads_calld->xds_client()->authority_state_map_[name_.authority]; |
| 226 |
ResourceState& state = authority_state.resource_map[type_][name_.key]; |
| 227 |
if (state.resource != nullptr) return; |
| 228 |
// Start timer. |
| 229 |
ads_calld_ = std::move(ads_calld); |
| 230 |
timer_handle_ = ads_calld_->xds_client()->engine()->RunAfter( |
| 231 |
ads_calld_->xds_client()->request_timeout_, |
| 232 |
[self = Ref(DEBUG_LOCATION, "timer")]() { |
| 233 |
ApplicationCallbackExecCtx callback_exec_ctx; |
| 234 |
ExecCtx exec_ctx; |
| 235 |
self->OnTimer(); |
| 236 |
}); |
| 237 |
} |
| 238 |
|
| 239 |
void OnTimer() { |
| 240 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 241 |
gpr_log(GPR_INFO, |
| 242 |
"[xds_client %p] xds server %s: timeout obtaining resource " |
| 243 |
"{type=%s name=%s} from xds server", |
| 244 |
ads_calld_->xds_client(), |
| 245 |
ads_calld_->chand()->server_.server_uri().c_str(), |
| 246 |
std::string(type_->type_url()).c_str(), |
| 247 |
XdsClient::ConstructFullXdsResourceName( |
| 248 |
name_.authority, type_->type_url(), name_.key) |
| 249 |
.c_str()); |
| 250 |
} |
| 251 |
{ |
| 252 |
MutexLock lock(&ads_calld_->xds_client()->mu_); |
| 253 |
timer_handle_.reset(); |
| 254 |
resource_seen_ = true; |
| 255 |
auto& authority_state = |
| 256 |
ads_calld_->xds_client()->authority_state_map_[name_.authority]; |
| 257 |
ResourceState& state = authority_state.resource_map[type_][name_.key]; |
| 258 |
state.meta.client_status = XdsApi::ResourceMetadata::DOES_NOT_EXIST; |
| 259 |
ads_calld_->xds_client()->NotifyWatchersOnResourceDoesNotExist( |
| 260 |
state.watchers); |
| 261 |
} |
| 262 |
ads_calld_->xds_client()->work_serializer_.DrainQueue(); |
| 263 |
ads_calld_.reset(); |
| 264 |
} |
| 265 |
|
| 266 |
const XdsResourceType* type_; |
| 267 |
const XdsResourceName name_; |
| 268 |
|
| 269 |
RefCountedPtr<AdsCallState> ads_calld_; |
| 270 |
// True if we have sent the initial subscription request for this |
| 271 |
// resource on this ADS stream. |
| 272 |
bool subscription_sent_ ABSL_GUARDED_BY(&XdsClient::mu_) = false; |
| 273 |
// True if we have either (a) seen the resource in a response on this |
| 274 |
// stream or (b) declared the resource to not exist due to the timer |
| 275 |
// firing. |
| 276 |
bool resource_seen_ ABSL_GUARDED_BY(&XdsClient::mu_) = false; |
| 277 |
absl::optional<EventEngine::TaskHandle> timer_handle_ |
| 278 |
ABSL_GUARDED_BY(&XdsClient::mu_); |
| 279 |
}; |
| 280 |
|
| 281 |
class StreamEventHandler |
| 282 |
: public XdsTransportFactory::XdsTransport::StreamingCall::EventHandler { |
| 283 |
public: |
| 284 |
explicit StreamEventHandler(RefCountedPtr<AdsCallState> ads_calld) |
| 285 |
: ads_calld_(std::move(ads_calld)) {} |
| 286 |
|
| 287 |
void OnRequestSent(bool ok) override { ads_calld_->OnRequestSent(ok); } |
| 288 |
void OnRecvMessage(absl::string_view payload) override { |
| 289 |
ads_calld_->OnRecvMessage(payload); |
| 290 |
} |
| 291 |
void OnStatusReceived(absl::Status status) override { |
| 292 |
ads_calld_->OnStatusReceived(std::move(status)); |
| 293 |
} |
| 294 |
|
| 295 |
private: |
| 296 |
RefCountedPtr<AdsCallState> ads_calld_; |
| 297 |
}; |
| 298 |
|
| 299 |
struct ResourceTypeState { |
| 300 |
// Nonce and status for this resource type. |
| 301 |
std::string nonce; |
| 302 |
absl::Status status; |
| 303 |
|
| 304 |
// Subscribed resources of this type. |
| 305 |
std::map<std::string /*authority*/, |
| 306 |
std::map<XdsResourceKey, OrphanablePtr<ResourceTimer>>> |
| 307 |
subscribed_resources; |
| 308 |
}; |
| 309 |
|
| 310 |
void SendMessageLocked(const XdsResourceType* type) |
| 311 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 312 |
|
| 313 |
void OnRequestSent(bool ok); |
| 314 |
void OnRecvMessage(absl::string_view payload); |
| 315 |
void OnStatusReceived(absl::Status status); |
| 316 |
|
| 317 |
bool IsCurrentCallOnChannel() const; |
| 318 |
|
| 319 |
// Constructs a list of resource names of a given type for an ADS |
| 320 |
// request. Also starts the timer for each resource if needed. |
| 321 |
std::vector<std::string> ResourceNamesForRequest(const XdsResourceType* type) |
| 322 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 323 |
|
| 324 |
// The owning RetryableCall<>. |
| 325 |
RefCountedPtr<RetryableCall<AdsCallState>> parent_; |
| 326 |
|
| 327 |
OrphanablePtr<XdsTransportFactory::XdsTransport::StreamingCall> call_; |
| 328 |
|
| 329 |
bool sent_initial_message_ = false; |
| 330 |
bool seen_response_ = false; |
| 331 |
|
| 332 |
const XdsResourceType* send_message_pending_ |
| 333 |
ABSL_GUARDED_BY(&XdsClient::mu_) = nullptr; |
| 334 |
|
| 335 |
// Resource types for which requests need to be sent. |
| 336 |
std::set<const XdsResourceType*> buffered_requests_; |
| 337 |
|
| 338 |
// State for each resource type. |
| 339 |
std::map<const XdsResourceType*, ResourceTypeState> state_map_; |
| 340 |
}; |
| 341 |
|
| 342 |
// Contains an LRS call to the xds server. |
| 343 |
class XdsClient::ChannelState::LrsCallState |
| 344 |
: public InternallyRefCounted<LrsCallState> { |
| 345 |
public: |
| 346 |
// The ctor and dtor should not be used directly. |
| 347 |
explicit LrsCallState(RefCountedPtr<RetryableCall<LrsCallState>> parent); |
| 348 |
|
| 349 |
void Orphan() override; |
| 350 |
|
| 351 |
void MaybeStartReportingLocked() |
| 352 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 353 |
|
| 354 |
RetryableCall<LrsCallState>* parent() { return parent_.get(); } |
| 355 |
ChannelState* chand() const { return parent_->chand(); } |
| 356 |
XdsClient* xds_client() const { return chand()->xds_client(); } |
| 357 |
bool seen_response() const { return seen_response_; } |
| 358 |
|
| 359 |
private: |
| 360 |
class StreamEventHandler |
| 361 |
: public XdsTransportFactory::XdsTransport::StreamingCall::EventHandler { |
| 362 |
public: |
| 363 |
explicit StreamEventHandler(RefCountedPtr<LrsCallState> lrs_calld) |
| 364 |
: lrs_calld_(std::move(lrs_calld)) {} |
| 365 |
|
| 366 |
void OnRequestSent(bool ok) override { lrs_calld_->OnRequestSent(ok); } |
| 367 |
void OnRecvMessage(absl::string_view payload) override { |
| 368 |
lrs_calld_->OnRecvMessage(payload); |
| 369 |
} |
| 370 |
void OnStatusReceived(absl::Status status) override { |
| 371 |
lrs_calld_->OnStatusReceived(std::move(status)); |
| 372 |
} |
| 373 |
|
| 374 |
private: |
| 375 |
RefCountedPtr<LrsCallState> lrs_calld_; |
| 376 |
}; |
| 377 |
|
| 378 |
// Reports client-side load stats according to a fixed interval. |
| 379 |
class Reporter : public InternallyRefCounted<Reporter> { |
| 380 |
public: |
| 381 |
Reporter(RefCountedPtr<LrsCallState> parent, Duration report_interval) |
| 382 |
: parent_(std::move(parent)), report_interval_(report_interval) { |
| 383 |
ScheduleNextReportLocked(); |
| 384 |
} |
| 385 |
|
| 386 |
// Disable thread-safety analysis because this method is called via |
| 387 |
// OrphanablePtr<>, but there's no way to pass the lock annotation |
| 388 |
// through there. |
| 389 |
void Orphan() override ABSL_NO_THREAD_SAFETY_ANALYSIS; |
| 390 |
|
| 391 |
void OnReportDoneLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 392 |
|
| 393 |
private: |
| 394 |
void ScheduleNextReportLocked() |
| 395 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 396 |
bool OnNextReportTimer(); |
| 397 |
bool SendReportLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_); |
| 398 |
|
| 399 |
bool IsCurrentReporterOnCall() const { |
| 400 |
return this == parent_->reporter_.get(); |
| 401 |
} |
| 402 |
XdsClient* xds_client() const { return parent_->xds_client(); } |
| 403 |
|
| 404 |
// The owning LRS call. |
| 405 |
RefCountedPtr<LrsCallState> parent_; |
| 406 |
|
| 407 |
// The load reporting state. |
| 408 |
const Duration report_interval_; |
| 409 |
bool last_report_counters_were_zero_ = false; |
| 410 |
absl::optional<EventEngine::TaskHandle> timer_handle_ |
| 411 |
ABSL_GUARDED_BY(&XdsClient::mu_); |
| 412 |
}; |
| 413 |
|
| 414 |
void OnRequestSent(bool ok); |
| 415 |
void OnRecvMessage(absl::string_view payload); |
| 416 |
void OnStatusReceived(absl::Status status); |
| 417 |
|
| 418 |
bool IsCurrentCallOnChannel() const; |
| 419 |
|
| 420 |
// The owning RetryableCall<>. |
| 421 |
RefCountedPtr<RetryableCall<LrsCallState>> parent_; |
| 422 |
|
| 423 |
OrphanablePtr<XdsTransportFactory::XdsTransport::StreamingCall> call_; |
| 424 |
|
| 425 |
bool seen_response_ = false; |
| 426 |
bool send_message_pending_ ABSL_GUARDED_BY(&XdsClient::mu_) = false; |
| 427 |
|
| 428 |
// Load reporting state. |
| 429 |
bool send_all_clusters_ = false; |
| 430 |
std::set<std::string> cluster_names_; // Asked for by the LRS server. |
| 431 |
Duration load_reporting_interval_; |
| 432 |
OrphanablePtr<Reporter> reporter_; |
| 433 |
}; |
| 434 |
|
| 435 |
// |
| 436 |
// XdsClient::ChannelState |
| 437 |
// |
| 438 |
|
| 439 |
XdsClient::ChannelState::ChannelState(WeakRefCountedPtr<XdsClient> xds_client, |
| 440 |
const XdsBootstrap::XdsServer& server) |
| 441 |
: DualRefCounted<ChannelState>( |
| 442 |
GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace) |
| 443 |
? "ChannelState" |
| 444 |
: nullptr), |
| 445 |
xds_client_(std::move(xds_client)), |
| 446 |
server_(server) { |
| 447 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 448 |
gpr_log(GPR_INFO, "[xds_client %p] creating channel to %s", |
| 449 |
xds_client_.get(), server.server_uri().c_str()); |
| 450 |
} |
| 451 |
absl::Status status; |
| 452 |
transport_ = xds_client_->transport_factory_->Create( |
| 453 |
server, |
| 454 |
[self = WeakRef(DEBUG_LOCATION, "OnConnectivityFailure")]( |
| 455 |
absl::Status status) { |
| 456 |
self->OnConnectivityFailure(std::move(status)); |
| 457 |
}, |
| 458 |
&status); |
| 459 |
GPR_ASSERT(transport_ != nullptr); |
| 460 |
if (!status.ok()) SetChannelStatusLocked(std::move(status)); |
| 461 |
} |
| 462 |
|
| 463 |
XdsClient::ChannelState::~ChannelState() { |
| 464 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 465 |
gpr_log(GPR_INFO, "[xds_client %p] destroying xds channel %p for server %s", |
| 466 |
xds_client(), this, server_.server_uri().c_str()); |
| 467 |
} |
| 468 |
xds_client_.reset(DEBUG_LOCATION, "ChannelState"); |
| 469 |
} |
| 470 |
|
| 471 |
// This method should only ever be called when holding the lock, but we can't |
| 472 |
// use a ABSL_EXCLUSIVE_LOCKS_REQUIRED annotation, because Orphan() will be |
| 473 |
// called from DualRefCounted::Unref, which cannot have a lock annotation for |
| 474 |
// a lock in this subclass. |
| 475 |
void XdsClient::ChannelState::Orphan() ABSL_NO_THREAD_SAFETY_ANALYSIS { |
| 476 |
shutting_down_ = true; |
| 477 |
transport_.reset(); |
| 478 |
// At this time, all strong refs are removed, remove from channel map to |
| 479 |
// prevent subsequent subscription from trying to use this ChannelState as |
| 480 |
// it is shutting down. |
| 481 |
xds_client_->xds_server_channel_map_.erase(&server_); |
| 482 |
ads_calld_.reset(); |
| 483 |
lrs_calld_.reset(); |
| 484 |
} |
| 485 |
|
| 486 |
void XdsClient::ChannelState::ResetBackoff() { transport_->ResetBackoff(); } |
| 487 |
|
| 488 |
XdsClient::ChannelState::AdsCallState* XdsClient::ChannelState::ads_calld() |
| 489 |
const { |
| 490 |
return ads_calld_->calld(); |
| 491 |
} |
| 492 |
|
| 493 |
XdsClient::ChannelState::LrsCallState* XdsClient::ChannelState::lrs_calld() |
| 494 |
const { |
| 495 |
return lrs_calld_->calld(); |
| 496 |
} |
| 497 |
|
| 498 |
void XdsClient::ChannelState::MaybeStartLrsCall() { |
| 499 |
if (lrs_calld_ != nullptr) return; |
| 500 |
lrs_calld_.reset(new RetryableCall<LrsCallState>( |
| 501 |
WeakRef(DEBUG_LOCATION, "ChannelState+lrs"))); |
| 502 |
} |
| 503 |
|
| 504 |
void XdsClient::ChannelState::StopLrsCallLocked() { |
| 505 |
xds_client_->xds_load_report_server_map_.erase(&server_); |
| 506 |
lrs_calld_.reset(); |
| 507 |
} |
| 508 |
|
| 509 |
void XdsClient::ChannelState::SubscribeLocked(const XdsResourceType* type, |
| 510 |
const XdsResourceName& name) { |
| 511 |
if (ads_calld_ == nullptr) { |
| 512 |
// Start the ADS call if this is the first request. |
| 513 |
ads_calld_.reset(new RetryableCall<AdsCallState>( |
| 514 |
WeakRef(DEBUG_LOCATION, "ChannelState+ads"))); |
| 515 |
// Note: AdsCallState's ctor will automatically subscribe to all |
| 516 |
// resources that the XdsClient already has watchers for, so we can |
| 517 |
// return here. |
| 518 |
return; |
| 519 |
} |
| 520 |
// If the ADS call is in backoff state, we don't need to do anything now |
| 521 |
// because when the call is restarted it will resend all necessary requests. |
| 522 |
if (ads_calld() == nullptr) return; |
| 523 |
// Subscribe to this resource if the ADS call is active. |
| 524 |
ads_calld()->SubscribeLocked(type, name, /*delay_send=*/false); |
| 525 |
} |
| 526 |
|
| 527 |
void XdsClient::ChannelState::UnsubscribeLocked(const XdsResourceType* type, |
| 528 |
const XdsResourceName& name, |
| 529 |
bool delay_unsubscription) { |
| 530 |
if (ads_calld_ != nullptr) { |
| 531 |
auto* calld = ads_calld_->calld(); |
| 532 |
if (calld != nullptr) { |
| 533 |
calld->UnsubscribeLocked(type, name, delay_unsubscription); |
| 534 |
if (!calld->HasSubscribedResources()) { |
| 535 |
ads_calld_.reset(); |
| 536 |
} |
| 537 |
} |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
void XdsClient::ChannelState::OnConnectivityFailure(absl::Status status) { |
| 542 |
{ |
| 543 |
MutexLock lock(&xds_client_->mu_); |
| 544 |
SetChannelStatusLocked(std::move(status)); |
| 545 |
} |
| 546 |
xds_client_->work_serializer_.DrainQueue(); |
| 547 |
} |
| 548 |
|
| 549 |
void XdsClient::ChannelState::SetChannelStatusLocked(absl::Status status) { |
| 550 |
if (shutting_down_) return; |
| 551 |
status = absl::Status(status.code(), absl::StrCat("xDS channel for server ", |
| 552 |
server_.server_uri(), ": ", |
| 553 |
status.message())); |
| 554 |
gpr_log(GPR_INFO, "[xds_client %p] %s", xds_client(), |
| 555 |
status.ToString().c_str()); |
| 556 |
// If the node ID is set, append that to the status message that we send to |
| 557 |
// the watchers, so that it will appear in log messages visible to users. |
| 558 |
const auto* node = xds_client_->bootstrap_->node(); |
| 559 |
if (node != nullptr) { |
| 560 |
status = absl::Status( |
| 561 |
status.code(), |
| 562 |
absl::StrCat(status.message(), |
| 563 |
" (node ID:", xds_client_->bootstrap_->node()->id(), ")")); |
| 564 |
} |
| 565 |
// Save status in channel, so that we can immediately generate an |
| 566 |
// error for any new watchers that may be started. |
| 567 |
status_ = status; |
| 568 |
// Find all watchers for this channel. |
| 569 |
std::set<RefCountedPtr<ResourceWatcherInterface>> watchers; |
| 570 |
for (const auto& a : xds_client_->authority_state_map_) { // authority |
| 571 |
if (a.second.channel_state != this) continue; |
| 572 |
for (const auto& t : a.second.resource_map) { // type |
| 573 |
for (const auto& r : t.second) { // resource id |
| 574 |
for (const auto& w : r.second.watchers) { // watchers |
| 575 |
watchers.insert(w.second); |
| 576 |
} |
| 577 |
} |
| 578 |
} |
| 579 |
} |
| 580 |
// Enqueue notification for the watchers. |
| 581 |
xds_client_->work_serializer_.Schedule( |
| 582 |
[watchers = std::move(watchers), status = std::move(status)]() |
| 583 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(xds_client_->work_serializer_) { |
| 584 |
for (const auto& watcher : watchers) { |
| 585 |
watcher->OnError(status); |
| 586 |
} |
| 587 |
}, |
| 588 |
DEBUG_LOCATION); |
| 589 |
} |
| 590 |
|
| 591 |
// |
| 592 |
// XdsClient::ChannelState::RetryableCall<> |
| 593 |
// |
| 594 |
|
| 595 |
template <typename T> |
| 596 |
XdsClient::ChannelState::RetryableCall<T>::RetryableCall( |
| 597 |
WeakRefCountedPtr<ChannelState> chand) |
| 598 |
: chand_(std::move(chand)), |
| 599 |
backoff_(BackOff::Options() |
| 600 |
.set_initial_backoff(Duration::Seconds( |
| 601 |
GRPC_XDS_INITIAL_CONNECT_BACKOFF_SECONDS)) |
| 602 |
.set_multiplier(GRPC_XDS_RECONNECT_BACKOFF_MULTIPLIER) |
| 603 |
.set_jitter(GRPC_XDS_RECONNECT_JITTER) |
| 604 |
.set_max_backoff(Duration::Seconds( |
| 605 |
GRPC_XDS_RECONNECT_MAX_BACKOFF_SECONDS))) { |
| 606 |
StartNewCallLocked(); |
| 607 |
} |
| 608 |
|
| 609 |
template <typename T> |
| 610 |
void XdsClient::ChannelState::RetryableCall<T>::Orphan() { |
| 611 |
shutting_down_ = true; |
| 612 |
calld_.reset(); |
| 613 |
if (timer_handle_.has_value()) { |
| 614 |
chand()->xds_client()->engine()->Cancel(*timer_handle_); |
| 615 |
timer_handle_.reset(); |
| 616 |
} |
| 617 |
this->Unref(DEBUG_LOCATION, "RetryableCall+orphaned"); |
| 618 |
} |
| 619 |
|
| 620 |
template <typename T> |
| 621 |
void XdsClient::ChannelState::RetryableCall<T>::OnCallFinishedLocked() { |
| 622 |
// If we saw a response on the current stream, reset backoff. |
| 623 |
if (calld_->seen_response()) backoff_.Reset(); |
| 624 |
calld_.reset(); |
| 625 |
// Start retry timer. |
| 626 |
StartRetryTimerLocked(); |
| 627 |
} |
| 628 |
|
| 629 |
template <typename T> |
| 630 |
void XdsClient::ChannelState::RetryableCall<T>::StartNewCallLocked() { |
| 631 |
if (shutting_down_) return; |
| 632 |
GPR_ASSERT(chand_->transport_ != nullptr); |
| 633 |
GPR_ASSERT(calld_ == nullptr); |
| 634 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 635 |
gpr_log(GPR_INFO, |
| 636 |
"[xds_client %p] xds server %s: start new call from retryable " |
| 637 |
"call %p", |
| 638 |
chand()->xds_client(), chand()->server_.server_uri().c_str(), this); |
| 639 |
} |
| 640 |
calld_ = MakeOrphanable<T>( |
| 641 |
this->Ref(DEBUG_LOCATION, "RetryableCall+start_new_call")); |
| 642 |
} |
| 643 |
|
| 644 |
template <typename T> |
| 645 |
void XdsClient::ChannelState::RetryableCall<T>::StartRetryTimerLocked() { |
| 646 |
if (shutting_down_) return; |
| 647 |
const Timestamp next_attempt_time = backoff_.NextAttemptTime(); |
| 648 |
const Duration timeout = |
| 649 |
std::max(next_attempt_time - Timestamp::Now(), Duration::Zero()); |
| 650 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 651 |
gpr_log(GPR_INFO, |
| 652 |
"[xds_client %p] xds server %s: call attempt failed; " |
| 653 |
"retry timer will fire in %" PRId64 "ms.", |
| 654 |
chand()->xds_client(), chand()->server_.server_uri().c_str(), |
| 655 |
timeout.millis()); |
| 656 |
} |
| 657 |
timer_handle_ = chand()->xds_client()->engine()->RunAfter( |
| 658 |
timeout, |
| 659 |
[self = this->Ref(DEBUG_LOCATION, "RetryableCall+retry_timer_start")]() { |
| 660 |
ApplicationCallbackExecCtx callback_exec_ctx; |
| 661 |
ExecCtx exec_ctx; |
| 662 |
self->OnRetryTimer(); |
| 663 |
}); |
| 664 |
} |
| 665 |
|
| 666 |
template <typename T> |
| 667 |
void XdsClient::ChannelState::RetryableCall<T>::OnRetryTimer() { |
| 668 |
MutexLock lock(&chand_->xds_client()->mu_); |
| 669 |
if (timer_handle_.has_value()) { |
| 670 |
timer_handle_.reset(); |
| 671 |
if (shutting_down_) return; |
| 672 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 673 |
gpr_log(GPR_INFO, |
| 674 |
"[xds_client %p] xds server %s: retry timer fired (retryable " |
| 675 |
"call: %p)", |
| 676 |
chand()->xds_client(), chand()->server_.server_uri().c_str(), |
| 677 |
this); |
| 678 |
} |
| 679 |
StartNewCallLocked(); |
| 680 |
} |
| 681 |
} |
| 682 |
|
| 683 |
// |
| 684 |
// XdsClient::ChannelState::AdsCallState::AdsResponseParser |
| 685 |
// |
| 686 |
|
| 687 |
absl::Status XdsClient::ChannelState::AdsCallState::AdsResponseParser:: |
| 688 |
ProcessAdsResponseFields(AdsResponseFields fields) { |
| 689 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 690 |
gpr_log( |
| 691 |
GPR_INFO, |
| 692 |
"[xds_client %p] xds server %s: received ADS response: type_url=%s, " |
| 693 |
"version=%s, nonce=%s, num_resources=%" PRIuPTR, |
| 694 |
ads_call_state_->xds_client(), |
| 695 |
ads_call_state_->chand()->server_.server_uri().c_str(), |
| 696 |
fields.type_url.c_str(), fields.version.c_str(), fields.nonce.c_str(), |
| 697 |
fields.num_resources); |
| 698 |
} |
| 699 |
result_.type = |
| 700 |
ads_call_state_->xds_client()->GetResourceTypeLocked(fields.type_url); |
| 701 |
if (result_.type == nullptr) { |
| 702 |
return absl::InvalidArgumentError( |
| 703 |
absl::StrCat("unknown resource type ", fields.type_url)); |
| 704 |
} |
| 705 |
result_.type_url = std::move(fields.type_url); |
| 706 |
result_.version = std::move(fields.version); |
| 707 |
result_.nonce = std::move(fields.nonce); |
| 708 |
return absl::OkStatus(); |
| 709 |
} |
| 710 |
|
| 711 |
namespace { |
| 712 |
|
| 713 |
// Build a resource metadata struct for ADS result accepting methods and CSDS. |
| 714 |
XdsApi::ResourceMetadata CreateResourceMetadataAcked( |
| 715 |
std::string serialized_proto, std::string version, Timestamp update_time) { |
| 716 |
XdsApi::ResourceMetadata resource_metadata; |
| 717 |
resource_metadata.serialized_proto = std::move(serialized_proto); |
| 718 |
resource_metadata.update_time = update_time; |
| 719 |
resource_metadata.version = std::move(version); |
| 720 |
resource_metadata.client_status = XdsApi::ResourceMetadata::ACKED; |
| 721 |
return resource_metadata; |
| 722 |
} |
| 723 |
|
| 724 |
// Update resource_metadata for NACK. |
| 725 |
void UpdateResourceMetadataNacked(const std::string& version, |
| 726 |
const std::string& details, |
| 727 |
Timestamp update_time, |
| 728 |
XdsApi::ResourceMetadata* resource_metadata) { |
| 729 |
resource_metadata->client_status = XdsApi::ResourceMetadata::NACKED; |
| 730 |
resource_metadata->failed_version = version; |
| 731 |
resource_metadata->failed_details = details; |
| 732 |
resource_metadata->failed_update_time = update_time; |
| 733 |
} |
| 734 |
|
| 735 |
} // namespace |
| 736 |
|
| 737 |
void XdsClient::ChannelState::AdsCallState::AdsResponseParser::ParseResource( |
| 738 |
upb_Arena* arena, size_t idx, absl::string_view type_url, |
| 739 |
absl::string_view resource_name, absl::string_view serialized_resource) { |
| 740 |
std::string error_prefix = absl::StrCat( |
| 741 |
"resource index ", idx, ": ", |
| 742 |
resource_name.empty() ? "" : absl::StrCat(resource_name, ": ")); |
| 743 |
// Check the type_url of the resource. |
| 744 |
if (result_.type_url != type_url) { |
| 745 |
result_.errors.emplace_back( |
| 746 |
absl::StrCat(error_prefix, "incorrect resource type ", type_url, |
| 747 |
" (should be ", result_.type_url, ")")); |
| 748 |
return; |
| 749 |
} |
| 750 |
// Parse the resource. |
| 751 |
XdsResourceType::DecodeContext context = { |
| 752 |
xds_client(), ads_call_state_->chand()->server_, &grpc_xds_client_trace, |
| 753 |
xds_client()->symtab_.ptr(), arena}; |
| 754 |
XdsResourceType::DecodeResult decode_result = |
| 755 |
result_.type->Decode(context, serialized_resource); |
| 756 |
// If we didn't already have the resource name from the Resource |
| 757 |
// wrapper, try to get it from the decoding result. |
| 758 |
if (resource_name.empty()) { |
| 759 |
if (decode_result.name.has_value()) { |
| 760 |
resource_name = *decode_result.name; |
| 761 |
error_prefix = |
| 762 |
absl::StrCat("resource index ", idx, ": ", resource_name, ": "); |
| 763 |
} else { |
| 764 |
// We don't have any way of determining the resource name, so |
| 765 |
// there's nothing more we can do here. |
| 766 |
result_.errors.emplace_back(absl::StrCat( |
| 767 |
error_prefix, decode_result.resource.status().ToString())); |
| 768 |
return; |
| 769 |
} |
| 770 |
} |
| 771 |
// If decoding failed, make sure we include the error in the NACK. |
| 772 |
const absl::Status& decode_status = decode_result.resource.status(); |
| 773 |
if (!decode_status.ok()) { |
| 774 |
result_.errors.emplace_back( |
| 775 |
absl::StrCat(error_prefix, decode_status.ToString())); |
| 776 |
} |
| 777 |
// Check the resource name. |
| 778 |
auto parsed_resource_name = |
| 779 |
xds_client()->ParseXdsResourceName(resource_name, result_.type); |
| 780 |
if (!parsed_resource_name.ok()) { |
| 781 |
result_.errors.emplace_back( |
| 782 |
absl::StrCat(error_prefix, "Cannot parse xDS resource name")); |
| 783 |
return; |
| 784 |
} |
| 785 |
// Cancel resource-does-not-exist timer, if needed. |
| 786 |
auto timer_it = ads_call_state_->state_map_.find(result_.type); |
| 787 |
if (timer_it != ads_call_state_->state_map_.end()) { |
| 788 |
auto it = timer_it->second.subscribed_resources.find( |
| 789 |
parsed_resource_name->authority); |
| 790 |
if (it != timer_it->second.subscribed_resources.end()) { |
| 791 |
auto res_it = it->second.find(parsed_resource_name->key); |
| 792 |
if (res_it != it->second.end()) { |
| 793 |
res_it->second->MarkSeen(); |
| 794 |
} |
| 795 |
} |
| 796 |
} |
| 797 |
// Lookup the authority in the cache. |
| 798 |
auto authority_it = |
| 799 |
xds_client()->authority_state_map_.find(parsed_resource_name->authority); |
| 800 |
if (authority_it == xds_client()->authority_state_map_.end()) { |
| 801 |
return; // Skip resource -- we don't have a subscription for it. |
| 802 |
} |
| 803 |
// Found authority, so look up type. |
| 804 |
AuthorityState& authority_state = authority_it->second; |
| 805 |
auto type_it = authority_state.resource_map.find(result_.type); |
| 806 |
if (type_it == authority_state.resource_map.end()) { |
| 807 |
return; // Skip resource -- we don't have a subscription for it. |
| 808 |
} |
| 809 |
auto& type_map = type_it->second; |
| 810 |
// Found type, so look up resource key. |
| 811 |
auto it = type_map.find(parsed_resource_name->key); |
| 812 |
if (it == type_map.end()) { |
| 813 |
return; // Skip resource -- we don't have a subscription for it. |
| 814 |
} |
| 815 |
ResourceState& resource_state = it->second; |
| 816 |
// If needed, record that we've seen this resource. |
| 817 |
if (result_.type->AllResourcesRequiredInSotW()) { |
| 818 |
result_.resources_seen[parsed_resource_name->authority].insert( |
| 819 |
parsed_resource_name->key); |
| 820 |
} |
| 821 |
// If we previously ignored the resource's deletion, log that we're |
| 822 |
// now re-adding it. |
| 823 |
if (resource_state.ignored_deletion) { |
| 824 |
gpr_log(GPR_INFO, |
| 825 |
"[xds_client %p] xds server %s: server returned new version of " |
| 826 |
"resource for which we previously ignored a deletion: type %s " |
| 827 |
"name %s", |
| 828 |
xds_client(), |
| 829 |
ads_call_state_->chand()->server_.server_uri().c_str(), |
| 830 |
std::string(type_url).c_str(), std::string(resource_name).c_str()); |
| 831 |
resource_state.ignored_deletion = false; |
| 832 |
} |
| 833 |
// Update resource state based on whether the resource is valid. |
| 834 |
if (!decode_status.ok()) { |
| 835 |
xds_client()->NotifyWatchersOnErrorLocked( |
| 836 |
resource_state.watchers, |
| 837 |
absl::UnavailableError( |
| 838 |
absl::StrCat("invalid resource: ", decode_status.ToString()))); |
| 839 |
UpdateResourceMetadataNacked(result_.version, decode_status.ToString(), |
| 840 |
update_time_, &resource_state.meta); |
| 841 |
return; |
| 842 |
} |
| 843 |
// Resource is valid. |
| 844 |
result_.have_valid_resources = true; |
| 845 |
// If it didn't change, ignore it. |
| 846 |
if (resource_state.resource != nullptr && |
| 847 |
result_.type->ResourcesEqual(resource_state.resource.get(), |
| 848 |
decode_result.resource->get())) { |
| 849 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 850 |
gpr_log(GPR_INFO, |
| 851 |
"[xds_client %p] %s resource %s identical to current, ignoring.", |
| 852 |
xds_client(), result_.type_url.c_str(), |
| 853 |
std::string(resource_name).c_str()); |
| 854 |
} |
| 855 |
return; |
| 856 |
} |
| 857 |
// Update the resource state. |
| 858 |
resource_state.resource = std::move(*decode_result.resource); |
| 859 |
resource_state.meta = CreateResourceMetadataAcked( |
| 860 |
std::string(serialized_resource), result_.version, update_time_); |
| 861 |
// Notify watchers. |
| 862 |
auto& watchers_list = resource_state.watchers; |
| 863 |
auto* value = |
| 864 |
result_.type->CopyResource(resource_state.resource.get()).release(); |
| 865 |
xds_client()->work_serializer_.Schedule( |
| 866 |
[watchers_list, value]() |
| 867 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&xds_client()->work_serializer_) { |
| 868 |
for (const auto& p : watchers_list) { |
| 869 |
p.first->OnGenericResourceChanged(value); |
| 870 |
} |
| 871 |
delete value; |
| 872 |
}, |
| 873 |
DEBUG_LOCATION); |
| 874 |
} |
| 875 |
|
| 876 |
void XdsClient::ChannelState::AdsCallState::AdsResponseParser:: |
| 877 |
ResourceWrapperParsingFailed(size_t idx) { |
| 878 |
result_.errors.emplace_back(absl::StrCat( |
| 879 |
"resource index ", idx, ": Can't decode Resource proto wrapper")); |
| 880 |
} |
| 881 |
|
| 882 |
// |
| 883 |
// XdsClient::ChannelState::AdsCallState |
| 884 |
// |
| 885 |
|
| 886 |
XdsClient::ChannelState::AdsCallState::AdsCallState( |
| 887 |
RefCountedPtr<RetryableCall<AdsCallState>> parent) |
| 888 |
: InternallyRefCounted<AdsCallState>( |
| 889 |
GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace) |
| 890 |
? "AdsCallState" |
| 891 |
: nullptr), |
| 892 |
parent_(std::move(parent)) { |
| 893 |
GPR_ASSERT(xds_client() != nullptr); |
| 894 |
// Init the ADS call. |
| 895 |
const char* method = |
| 896 |
"/envoy.service.discovery.v3.AggregatedDiscoveryService/" |
| 897 |
"StreamAggregatedResources"; |
| 898 |
call_ = chand()->transport_->CreateStreamingCall( |
| 899 |
method, std::make_unique<StreamEventHandler>( |
| 900 |
// Passing the initial ref here. This ref will go away when |
| 901 |
// the StreamEventHandler is destroyed. |
| 902 |
RefCountedPtr<AdsCallState>(this))); |
| 903 |
GPR_ASSERT(call_ != nullptr); |
| 904 |
// Start the call. |
| 905 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 906 |
gpr_log(GPR_INFO, |
| 907 |
"[xds_client %p] xds server %s: starting ADS call " |
| 908 |
"(calld: %p, call: %p)", |
| 909 |
xds_client(), chand()->server_.server_uri().c_str(), this, |
| 910 |
call_.get()); |
| 911 |
} |
| 912 |
// If this is a reconnect, add any necessary subscriptions from what's |
| 913 |
// already in the cache. |
| 914 |
for (const auto& a : xds_client()->authority_state_map_) { |
| 915 |
const std::string& authority = a.first; |
| 916 |
// Skip authorities that are not using this xDS channel. |
| 917 |
if (a.second.channel_state != chand()) continue; |
| 918 |
for (const auto& t : a.second.resource_map) { |
| 919 |
const XdsResourceType* type = t.first; |
| 920 |
for (const auto& r : t.second) { |
| 921 |
const XdsResourceKey& resource_key = r.first; |
| 922 |
SubscribeLocked(type, {authority, resource_key}, /*delay_send=*/true); |
| 923 |
} |
| 924 |
} |
| 925 |
} |
| 926 |
// Send initial message if we added any subscriptions above. |
| 927 |
for (const auto& p : state_map_) { |
| 928 |
SendMessageLocked(p.first); |
| 929 |
} |
| 930 |
} |
| 931 |
|
| 932 |
void XdsClient::ChannelState::AdsCallState::Orphan() { |
| 933 |
state_map_.clear(); |
| 934 |
// Note that the initial ref is held by the StreamEventHandler, which |
| 935 |
// will be destroyed when call_ is destroyed, which may not happen |
| 936 |
// here, since there may be other refs held to call_ by internal callbacks. |
| 937 |
call_.reset(); |
| 938 |
} |
| 939 |
|
| 940 |
void XdsClient::ChannelState::AdsCallState::SendMessageLocked( |
| 941 |
const XdsResourceType* type) |
| 942 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) { |
| 943 |
// Buffer message sending if an existing message is in flight. |
| 944 |
if (send_message_pending_ != nullptr) { |
| 945 |
buffered_requests_.insert(type); |
| 946 |
return; |
| 947 |
} |
| 948 |
auto& state = state_map_[type]; |
| 949 |
std::string serialized_message = xds_client()->api_.CreateAdsRequest( |
| 950 |
type->type_url(), chand()->resource_type_version_map_[type], state.nonce, |
| 951 |
ResourceNamesForRequest(type), state.status, !sent_initial_message_); |
| 952 |
sent_initial_message_ = true; |
| 953 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 954 |
gpr_log(GPR_INFO, |
| 955 |
"[xds_client %p] xds server %s: sending ADS request: type=%s " |
| 956 |
"version=%s nonce=%s error=%s", |
| 957 |
xds_client(), chand()->server_.server_uri().c_str(), |
| 958 |
std::string(type->type_url()).c_str(), |
| 959 |
chand()->resource_type_version_map_[type].c_str(), |
| 960 |
state.nonce.c_str(), state.status.ToString().c_str()); |
| 961 |
} |
| 962 |
state.status = absl::OkStatus(); |
| 963 |
call_->SendMessage(std::move(serialized_message)); |
| 964 |
send_message_pending_ = type; |
| 965 |
} |
| 966 |
|
| 967 |
void XdsClient::ChannelState::AdsCallState::SubscribeLocked( |
| 968 |
const XdsResourceType* type, const XdsResourceName& name, bool delay_send) { |
| 969 |
auto& state = state_map_[type].subscribed_resources[name.authority][name.key]; |
| 970 |
if (state == nullptr) { |
| 971 |
state = MakeOrphanable<ResourceTimer>(type, name); |
| 972 |
if (!delay_send) SendMessageLocked(type); |
| 973 |
} |
| 974 |
} |
| 975 |
|
| 976 |
void XdsClient::ChannelState::AdsCallState::UnsubscribeLocked( |
| 977 |
const XdsResourceType* type, const XdsResourceName& name, |
| 978 |
bool delay_unsubscription) { |
| 979 |
auto& type_state_map = state_map_[type]; |
| 980 |
auto& authority_map = type_state_map.subscribed_resources[name.authority]; |
| 981 |
authority_map.erase(name.key); |
| 982 |
if (authority_map.empty()) { |
| 983 |
type_state_map.subscribed_resources.erase(name.authority); |
| 984 |
} |
| 985 |
if (!delay_unsubscription) SendMessageLocked(type); |
| 986 |
} |
| 987 |
|
| 988 |
bool XdsClient::ChannelState::AdsCallState::HasSubscribedResources() const { |
| 989 |
for (const auto& p : state_map_) { |
| 990 |
if (!p.second.subscribed_resources.empty()) return true; |
| 991 |
} |
| 992 |
return false; |
| 993 |
} |
| 994 |
|
| 995 |
void XdsClient::ChannelState::AdsCallState::OnRequestSent(bool ok) { |
| 996 |
MutexLock lock(&xds_client()->mu_); |
| 997 |
// For each resource that was in the message we just sent, start the |
| 998 |
// resource timer if needed. |
| 999 |
if (ok) { |
| 1000 |
auto& resource_type_state = state_map_[send_message_pending_]; |
| 1001 |
for (const auto& p : resource_type_state.subscribed_resources) { |
| 1002 |
for (auto& q : p.second) { |
| 1003 |
q.second->MaybeMarkSubscriptionSendComplete( |
| 1004 |
Ref(DEBUG_LOCATION, "ResourceTimer")); |
| 1005 |
} |
| 1006 |
} |
| 1007 |
} |
| 1008 |
send_message_pending_ = nullptr; |
| 1009 |
if (ok && IsCurrentCallOnChannel()) { |
| 1010 |
// Continue to send another pending message if any. |
| 1011 |
// TODO(roth): The current code to handle buffered messages has the |
| 1012 |
// advantage of sending only the most recent list of resource names for |
| 1013 |
// each resource type (no matter how many times that resource type has |
| 1014 |
// been requested to send while the current message sending is still |
| 1015 |
// pending). But its disadvantage is that we send the requests in fixed |
| 1016 |
// order of resource types. We need to fix this if we are seeing some |
| 1017 |
// resource type(s) starved due to frequent requests of other resource |
| 1018 |
// type(s). |
| 1019 |
auto it = buffered_requests_.begin(); |
| 1020 |
if (it != buffered_requests_.end()) { |
| 1021 |
SendMessageLocked(*it); |
| 1022 |
buffered_requests_.erase(it); |
| 1023 |
} |
| 1024 |
} |
| 1025 |
} |
| 1026 |
|
| 1027 |
void XdsClient::ChannelState::AdsCallState::OnRecvMessage( |
| 1028 |
absl::string_view payload) { |
| 1029 |
{ |
| 1030 |
MutexLock lock(&xds_client()->mu_); |
| 1031 |
if (!IsCurrentCallOnChannel()) return; |
| 1032 |
// Parse and validate the response. |
| 1033 |
AdsResponseParser parser(this); |
| 1034 |
absl::Status status = xds_client()->api_.ParseAdsResponse(payload, &parser); |
| 1035 |
if (!status.ok()) { |
| 1036 |
// Ignore unparsable response. |
| 1037 |
gpr_log(GPR_ERROR, |
| 1038 |
"[xds_client %p] xds server %s: error parsing ADS response (%s) " |
| 1039 |
"-- ignoring", |
| 1040 |
xds_client(), chand()->server_.server_uri().c_str(), |
| 1041 |
status.ToString().c_str()); |
| 1042 |
} else { |
| 1043 |
seen_response_ = true; |
| 1044 |
chand()->status_ = absl::OkStatus(); |
| 1045 |
AdsResponseParser::Result result = parser.TakeResult(); |
| 1046 |
// Update nonce. |
| 1047 |
auto& state = state_map_[result.type]; |
| 1048 |
state.nonce = result.nonce; |
| 1049 |
// If we got an error, set state.status so that we'll NACK the update. |
| 1050 |
if (!result.errors.empty()) { |
| 1051 |
state.status = absl::UnavailableError( |
| 1052 |
absl::StrCat("xDS response validation errors: [", |
| 1053 |
absl::StrJoin(result.errors, "; "), "]")); |
| 1054 |
gpr_log(GPR_ERROR, |
| 1055 |
"[xds_client %p] xds server %s: ADS response invalid for " |
| 1056 |
"resource " |
| 1057 |
"type %s version %s, will NACK: nonce=%s status=%s", |
| 1058 |
xds_client(), chand()->server_.server_uri().c_str(), |
| 1059 |
result.type_url.c_str(), result.version.c_str(), |
| 1060 |
state.nonce.c_str(), state.status.ToString().c_str()); |
| 1061 |
} |
| 1062 |
// Delete resources not seen in update if needed. |
| 1063 |
if (result.type->AllResourcesRequiredInSotW()) { |
| 1064 |
for (auto& a : xds_client()->authority_state_map_) { |
| 1065 |
const std::string& authority = a.first; |
| 1066 |
AuthorityState& authority_state = a.second; |
| 1067 |
// Skip authorities that are not using this xDS channel. |
| 1068 |
if (authority_state.channel_state != chand()) continue; |
| 1069 |
auto seen_authority_it = result.resources_seen.find(authority); |
| 1070 |
// Find this resource type. |
| 1071 |
auto type_it = authority_state.resource_map.find(result.type); |
| 1072 |
if (type_it == authority_state.resource_map.end()) continue; |
| 1073 |
// Iterate over resource ids. |
| 1074 |
for (auto& r : type_it->second) { |
| 1075 |
const XdsResourceKey& resource_key = r.first; |
| 1076 |
ResourceState& resource_state = r.second; |
| 1077 |
if (seen_authority_it == result.resources_seen.end() || |
| 1078 |
seen_authority_it->second.find(resource_key) == |
| 1079 |
seen_authority_it->second.end()) { |
| 1080 |
// If the resource was newly requested but has not yet been |
| 1081 |
// received, we don't want to generate an error for the |
| 1082 |
// watchers, because this ADS response may be in reaction to an |
| 1083 |
// earlier request that did not yet request the new resource, so |
| 1084 |
// its absence from the response does not necessarily indicate |
| 1085 |
// that the resource does not exist. For that case, we rely on |
| 1086 |
// the request timeout instead. |
| 1087 |
if (resource_state.resource == nullptr) continue; |
| 1088 |
if (chand()->server_.IgnoreResourceDeletion()) { |
| 1089 |
if (!resource_state.ignored_deletion) { |
| 1090 |
gpr_log(GPR_ERROR, |
| 1091 |
"[xds_client %p] xds server %s: ignoring deletion " |
| 1092 |
"for resource type %s name %s", |
| 1093 |
xds_client(), chand()->server_.server_uri().c_str(), |
| 1094 |
result.type_url.c_str(), |
| 1095 |
XdsClient::ConstructFullXdsResourceName( |
| 1096 |
authority, result.type_url.c_str(), resource_key) |
| 1097 |
.c_str()); |
| 1098 |
resource_state.ignored_deletion = true; |
| 1099 |
} |
| 1100 |
} else { |
| 1101 |
resource_state.resource.reset(); |
| 1102 |
resource_state.meta.client_status = |
| 1103 |
XdsApi::ResourceMetadata::DOES_NOT_EXIST; |
| 1104 |
xds_client()->NotifyWatchersOnResourceDoesNotExist( |
| 1105 |
resource_state.watchers); |
| 1106 |
} |
| 1107 |
} |
| 1108 |
} |
| 1109 |
} |
| 1110 |
} |
| 1111 |
// If we had valid resources or the update was empty, update the version. |
| 1112 |
if (result.have_valid_resources || result.errors.empty()) { |
| 1113 |
chand()->resource_type_version_map_[result.type] = |
| 1114 |
std::move(result.version); |
| 1115 |
// Start load reporting if needed. |
| 1116 |
auto& lrs_call = chand()->lrs_calld_; |
| 1117 |
if (lrs_call != nullptr) { |
| 1118 |
LrsCallState* lrs_calld = lrs_call->calld(); |
| 1119 |
if (lrs_calld != nullptr) lrs_calld->MaybeStartReportingLocked(); |
| 1120 |
} |
| 1121 |
} |
| 1122 |
// Send ACK or NACK. |
| 1123 |
SendMessageLocked(result.type); |
| 1124 |
} |
| 1125 |
} |
| 1126 |
xds_client()->work_serializer_.DrainQueue(); |
| 1127 |
} |
| 1128 |
|
| 1129 |
void XdsClient::ChannelState::AdsCallState::OnStatusReceived( |
| 1130 |
absl::Status status) { |
| 1131 |
{ |
| 1132 |
MutexLock lock(&xds_client()->mu_); |
| 1133 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1134 |
gpr_log(GPR_INFO, |
| 1135 |
"[xds_client %p] xds server %s: ADS call status received " |
| 1136 |
"(chand=%p, ads_calld=%p, call=%p): %s", |
| 1137 |
xds_client(), chand()->server_.server_uri().c_str(), chand(), |
| 1138 |
this, call_.get(), status.ToString().c_str()); |
| 1139 |
} |
| 1140 |
// Cancel any does-not-exist timers that may be pending. |
| 1141 |
for (const auto& p : state_map_) { |
| 1142 |
for (const auto& q : p.second.subscribed_resources) { |
| 1143 |
for (auto& r : q.second) { |
| 1144 |
r.second->MaybeCancelTimer(); |
| 1145 |
} |
| 1146 |
} |
| 1147 |
} |
| 1148 |
// Ignore status from a stale call. |
| 1149 |
if (IsCurrentCallOnChannel()) { |
| 1150 |
// Try to restart the call. |
| 1151 |
parent_->OnCallFinishedLocked(); |
| 1152 |
// If we didn't receive a response on the stream, report the |
| 1153 |
// stream failure as a connectivity failure, which will report the |
| 1154 |
// error to all watchers of resources on this channel. |
| 1155 |
if (!seen_response_) { |
| 1156 |
chand()->SetChannelStatusLocked(absl::UnavailableError( |
| 1157 |
absl::StrCat("xDS call failed with no responses received; status: ", |
| 1158 |
status.ToString()))); |
| 1159 |
} |
| 1160 |
} |
| 1161 |
} |
| 1162 |
xds_client()->work_serializer_.DrainQueue(); |
| 1163 |
} |
| 1164 |
|
| 1165 |
bool XdsClient::ChannelState::AdsCallState::IsCurrentCallOnChannel() const { |
| 1166 |
// If the retryable ADS call is null (which only happens when the xds |
| 1167 |
// channel is shutting down), all the ADS calls are stale. |
| 1168 |
if (chand()->ads_calld_ == nullptr) return false; |
| 1169 |
return this == chand()->ads_calld_->calld(); |
| 1170 |
} |
| 1171 |
|
| 1172 |
std::vector<std::string> |
| 1173 |
XdsClient::ChannelState::AdsCallState::ResourceNamesForRequest( |
| 1174 |
const XdsResourceType* type) { |
| 1175 |
std::vector<std::string> resource_names; |
| 1176 |
auto it = state_map_.find(type); |
| 1177 |
if (it != state_map_.end()) { |
| 1178 |
for (auto& a : it->second.subscribed_resources) { |
| 1179 |
const std::string& authority = a.first; |
| 1180 |
for (auto& p : a.second) { |
| 1181 |
const XdsResourceKey& resource_key = p.first; |
| 1182 |
resource_names.emplace_back(XdsClient::ConstructFullXdsResourceName( |
| 1183 |
authority, type->type_url(), resource_key)); |
| 1184 |
OrphanablePtr<ResourceTimer>& resource_timer = p.second; |
| 1185 |
resource_timer->MarkSubscriptionSendStarted(); |
| 1186 |
} |
| 1187 |
} |
| 1188 |
} |
| 1189 |
return resource_names; |
| 1190 |
} |
| 1191 |
|
| 1192 |
// |
| 1193 |
// XdsClient::ChannelState::LrsCallState::Reporter |
| 1194 |
// |
| 1195 |
|
| 1196 |
void XdsClient::ChannelState::LrsCallState::Reporter::Orphan() { |
| 1197 |
if (timer_handle_.has_value() && |
| 1198 |
xds_client()->engine()->Cancel(*timer_handle_)) { |
| 1199 |
timer_handle_.reset(); |
| 1200 |
Unref(DEBUG_LOCATION, "Orphan"); |
| 1201 |
} |
| 1202 |
} |
| 1203 |
|
| 1204 |
void XdsClient::ChannelState::LrsCallState::Reporter:: |
| 1205 |
ScheduleNextReportLocked() { |
| 1206 |
timer_handle_ = xds_client()->engine()->RunAfter(report_interval_, [this]() { |
| 1207 |
ApplicationCallbackExecCtx callback_exec_ctx; |
| 1208 |
ExecCtx exec_ctx; |
| 1209 |
if (OnNextReportTimer()) { |
| 1210 |
Unref(DEBUG_LOCATION, "OnNextReportTimer()"); |
| 1211 |
} |
| 1212 |
}); |
| 1213 |
} |
| 1214 |
|
| 1215 |
bool XdsClient::ChannelState::LrsCallState::Reporter::OnNextReportTimer() { |
| 1216 |
MutexLock lock(&xds_client()->mu_); |
| 1217 |
timer_handle_.reset(); |
| 1218 |
if (!IsCurrentReporterOnCall()) return true; |
| 1219 |
SendReportLocked(); |
| 1220 |
return false; |
| 1221 |
} |
| 1222 |
|
| 1223 |
namespace { |
| 1224 |
|
| 1225 |
bool LoadReportCountersAreZero(const XdsApi::ClusterLoadReportMap& snapshot) { |
| 1226 |
for (const auto& p : snapshot) { |
| 1227 |
const XdsApi::ClusterLoadReport& cluster_snapshot = p.second; |
| 1228 |
if (!cluster_snapshot.dropped_requests.IsZero()) return false; |
| 1229 |
for (const auto& q : cluster_snapshot.locality_stats) { |
| 1230 |
const XdsClusterLocalityStats::Snapshot& locality_snapshot = q.second; |
| 1231 |
if (!locality_snapshot.IsZero()) return false; |
| 1232 |
} |
| 1233 |
} |
| 1234 |
return true; |
| 1235 |
} |
| 1236 |
|
| 1237 |
} // namespace |
| 1238 |
|
| 1239 |
bool XdsClient::ChannelState::LrsCallState::Reporter::SendReportLocked() { |
| 1240 |
// Construct snapshot from all reported stats. |
| 1241 |
XdsApi::ClusterLoadReportMap snapshot = |
| 1242 |
xds_client()->BuildLoadReportSnapshotLocked(parent_->chand()->server_, |
| 1243 |
parent_->send_all_clusters_, |
| 1244 |
parent_->cluster_names_); |
| 1245 |
// Skip client load report if the counters were all zero in the last |
| 1246 |
// report and they are still zero in this one. |
| 1247 |
const bool old_val = last_report_counters_were_zero_; |
| 1248 |
last_report_counters_were_zero_ = LoadReportCountersAreZero(snapshot); |
| 1249 |
if (old_val && last_report_counters_were_zero_) { |
| 1250 |
auto it = xds_client()->xds_load_report_server_map_.find( |
| 1251 |
&parent_->chand()->server_); |
| 1252 |
if (it == xds_client()->xds_load_report_server_map_.end() || |
| 1253 |
it->second.load_report_map.empty()) { |
| 1254 |
it->second.channel_state->StopLrsCallLocked(); |
| 1255 |
return true; |
| 1256 |
} |
| 1257 |
ScheduleNextReportLocked(); |
| 1258 |
return false; |
| 1259 |
} |
| 1260 |
// Send a request that contains the snapshot. |
| 1261 |
std::string serialized_payload = |
| 1262 |
xds_client()->api_.CreateLrsRequest(std::move(snapshot)); |
| 1263 |
parent_->call_->SendMessage(std::move(serialized_payload)); |
| 1264 |
parent_->send_message_pending_ = true; |
| 1265 |
return false; |
| 1266 |
} |
| 1267 |
|
| 1268 |
void XdsClient::ChannelState::LrsCallState::Reporter::OnReportDoneLocked() { |
| 1269 |
// If a reporter starts a send_message op, then the reporting interval |
| 1270 |
// changes and we destroy that reporter and create a new one, and then |
| 1271 |
// the send_message op started by the old reporter finishes, this |
| 1272 |
// method will be called even though it was for a completion started |
| 1273 |
// by the old reporter. In that case, the timer will be pending, so |
| 1274 |
// we just ignore the completion and wait for the timer to fire. |
| 1275 |
if (timer_handle_.has_value()) return; |
| 1276 |
// If there are no more registered stats to report, cancel the call. |
| 1277 |
auto it = xds_client()->xds_load_report_server_map_.find( |
| 1278 |
&parent_->chand()->server_); |
| 1279 |
if (it == xds_client()->xds_load_report_server_map_.end()) return; |
| 1280 |
if (it->second.load_report_map.empty()) { |
| 1281 |
if (it->second.channel_state != nullptr) { |
| 1282 |
it->second.channel_state->StopLrsCallLocked(); |
| 1283 |
} |
| 1284 |
return; |
| 1285 |
} |
| 1286 |
// Otherwise, schedule the next load report. |
| 1287 |
ScheduleNextReportLocked(); |
| 1288 |
} |
| 1289 |
|
| 1290 |
// |
| 1291 |
// XdsClient::ChannelState::LrsCallState |
| 1292 |
// |
| 1293 |
|
| 1294 |
XdsClient::ChannelState::LrsCallState::LrsCallState( |
| 1295 |
RefCountedPtr<RetryableCall<LrsCallState>> parent) |
| 1296 |
: InternallyRefCounted<LrsCallState>( |
| 1297 |
GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace) |
| 1298 |
? "LrsCallState" |
| 1299 |
: nullptr), |
| 1300 |
parent_(std::move(parent)) { |
| 1301 |
// Init the LRS call. Note that the call will progress every time there's |
| 1302 |
// activity in xds_client()->interested_parties_, which is comprised of |
| 1303 |
// the polling entities from client_channel. |
| 1304 |
GPR_ASSERT(xds_client() != nullptr); |
| 1305 |
const char* method = |
| 1306 |
"/envoy.service.load_stats.v3.LoadReportingService/StreamLoadStats"; |
| 1307 |
call_ = chand()->transport_->CreateStreamingCall( |
| 1308 |
method, std::make_unique<StreamEventHandler>( |
| 1309 |
// Passing the initial ref here. This ref will go away when |
| 1310 |
// the StreamEventHandler is destroyed. |
| 1311 |
RefCountedPtr<LrsCallState>(this))); |
| 1312 |
GPR_ASSERT(call_ != nullptr); |
| 1313 |
// Start the call. |
| 1314 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1315 |
gpr_log(GPR_INFO, |
| 1316 |
"[xds_client %p] xds server %s: starting LRS call (calld=%p, " |
| 1317 |
"call=%p)", |
| 1318 |
xds_client(), chand()->server_.server_uri().c_str(), this, |
| 1319 |
call_.get()); |
| 1320 |
} |
| 1321 |
// Send the initial request. |
| 1322 |
std::string serialized_payload = xds_client()->api_.CreateLrsInitialRequest(); |
| 1323 |
call_->SendMessage(std::move(serialized_payload)); |
| 1324 |
send_message_pending_ = true; |
| 1325 |
} |
| 1326 |
|
| 1327 |
void XdsClient::ChannelState::LrsCallState::Orphan() { |
| 1328 |
reporter_.reset(); |
| 1329 |
// Note that the initial ref is held by the StreamEventHandler, which |
| 1330 |
// will be destroyed when call_ is destroyed, which may not happen |
| 1331 |
// here, since there may be other refs held to call_ by internal callbacks. |
| 1332 |
call_.reset(); |
| 1333 |
} |
| 1334 |
|
| 1335 |
void XdsClient::ChannelState::LrsCallState::MaybeStartReportingLocked() { |
| 1336 |
// Don't start again if already started. |
| 1337 |
if (reporter_ != nullptr) return; |
| 1338 |
// Don't start if the previous send_message op (of the initial request or |
| 1339 |
// the last report of the previous reporter) hasn't completed. |
| 1340 |
if (call_ != nullptr && send_message_pending_) return; |
| 1341 |
// Don't start if no LRS response has arrived. |
| 1342 |
if (!seen_response()) return; |
| 1343 |
// Don't start if the ADS call hasn't received any valid response. Note that |
| 1344 |
// this must be the first channel because it is the current channel but its |
| 1345 |
// ADS call hasn't seen any response. |
| 1346 |
if (chand()->ads_calld_ == nullptr || |
| 1347 |
chand()->ads_calld_->calld() == nullptr || |
| 1348 |
!chand()->ads_calld_->calld()->seen_response()) { |
| 1349 |
return; |
| 1350 |
} |
| 1351 |
// Start reporting. |
| 1352 |
reporter_ = MakeOrphanable<Reporter>( |
| 1353 |
Ref(DEBUG_LOCATION, "LRS+load_report+start"), load_reporting_interval_); |
| 1354 |
} |
| 1355 |
|
| 1356 |
void XdsClient::ChannelState::LrsCallState::OnRequestSent(bool /*ok*/) { |
| 1357 |
MutexLock lock(&xds_client()->mu_); |
| 1358 |
send_message_pending_ = false; |
| 1359 |
if (reporter_ != nullptr) { |
| 1360 |
reporter_->OnReportDoneLocked(); |
| 1361 |
} else { |
| 1362 |
MaybeStartReportingLocked(); |
| 1363 |
} |
| 1364 |
} |
| 1365 |
|
| 1366 |
void XdsClient::ChannelState::LrsCallState::OnRecvMessage( |
| 1367 |
absl::string_view payload) { |
| 1368 |
MutexLock lock(&xds_client()->mu_); |
| 1369 |
// If we're no longer the current call, ignore the result. |
| 1370 |
if (!IsCurrentCallOnChannel()) return; |
| 1371 |
// Parse the response. |
| 1372 |
bool send_all_clusters = false; |
| 1373 |
std::set<std::string> new_cluster_names; |
| 1374 |
Duration new_load_reporting_interval; |
| 1375 |
absl::Status status = xds_client()->api_.ParseLrsResponse( |
| 1376 |
payload, &send_all_clusters, &new_cluster_names, |
| 1377 |
&new_load_reporting_interval); |
| 1378 |
if (!status.ok()) { |
| 1379 |
gpr_log(GPR_ERROR, |
| 1380 |
"[xds_client %p] xds server %s: LRS response parsing failed: %s", |
| 1381 |
xds_client(), chand()->server_.server_uri().c_str(), |
| 1382 |
status.ToString().c_str()); |
| 1383 |
return; |
| 1384 |
} |
| 1385 |
seen_response_ = true; |
| 1386 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1387 |
gpr_log( |
| 1388 |
GPR_INFO, |
| 1389 |
"[xds_client %p] xds server %s: LRS response received, %" PRIuPTR |
| 1390 |
" cluster names, send_all_clusters=%d, load_report_interval=%" PRId64 |
| 1391 |
"ms", |
| 1392 |
xds_client(), chand()->server_.server_uri().c_str(), |
| 1393 |
new_cluster_names.size(), send_all_clusters, |
| 1394 |
new_load_reporting_interval.millis()); |
| 1395 |
size_t i = 0; |
| 1396 |
for (const auto& name : new_cluster_names) { |
| 1397 |
gpr_log(GPR_INFO, "[xds_client %p] cluster_name %" PRIuPTR ": %s", |
| 1398 |
xds_client(), i++, name.c_str()); |
| 1399 |
} |
| 1400 |
} |
| 1401 |
if (new_load_reporting_interval < |
| 1402 |
Duration::Milliseconds(GRPC_XDS_MIN_CLIENT_LOAD_REPORTING_INTERVAL_MS)) { |
| 1403 |
new_load_reporting_interval = |
| 1404 |
Duration::Milliseconds(GRPC_XDS_MIN_CLIENT_LOAD_REPORTING_INTERVAL_MS); |
| 1405 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1406 |
gpr_log(GPR_INFO, |
| 1407 |
"[xds_client %p] xds server %s: increased load_report_interval " |
| 1408 |
"to minimum value %dms", |
| 1409 |
xds_client(), chand()->server_.server_uri().c_str(), |
| 1410 |
GRPC_XDS_MIN_CLIENT_LOAD_REPORTING_INTERVAL_MS); |
| 1411 |
} |
| 1412 |
} |
| 1413 |
// Ignore identical update. |
| 1414 |
if (send_all_clusters == send_all_clusters_ && |
| 1415 |
cluster_names_ == new_cluster_names && |
| 1416 |
load_reporting_interval_ == new_load_reporting_interval) { |
| 1417 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1418 |
gpr_log(GPR_INFO, |
| 1419 |
"[xds_client %p] xds server %s: incoming LRS response identical " |
| 1420 |
"to current, ignoring.", |
| 1421 |
xds_client(), chand()->server_.server_uri().c_str()); |
| 1422 |
} |
| 1423 |
return; |
| 1424 |
} |
| 1425 |
// Stop current load reporting (if any) to adopt the new config. |
| 1426 |
reporter_.reset(); |
| 1427 |
// Record the new config. |
| 1428 |
send_all_clusters_ = send_all_clusters; |
| 1429 |
cluster_names_ = std::move(new_cluster_names); |
| 1430 |
load_reporting_interval_ = new_load_reporting_interval; |
| 1431 |
// Try starting sending load report. |
| 1432 |
MaybeStartReportingLocked(); |
| 1433 |
} |
| 1434 |
|
| 1435 |
void XdsClient::ChannelState::LrsCallState::OnStatusReceived( |
| 1436 |
absl::Status status) { |
| 1437 |
MutexLock lock(&xds_client()->mu_); |
| 1438 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1439 |
gpr_log(GPR_INFO, |
| 1440 |
"[xds_client %p] xds server %s: LRS call status received " |
| 1441 |
"(chand=%p, calld=%p, call=%p): %s", |
| 1442 |
xds_client(), chand()->server_.server_uri().c_str(), chand(), this, |
| 1443 |
call_.get(), status.ToString().c_str()); |
| 1444 |
} |
| 1445 |
// Ignore status from a stale call. |
| 1446 |
if (IsCurrentCallOnChannel()) { |
| 1447 |
// Try to restart the call. |
| 1448 |
parent_->OnCallFinishedLocked(); |
| 1449 |
} |
| 1450 |
} |
| 1451 |
|
| 1452 |
bool XdsClient::ChannelState::LrsCallState::IsCurrentCallOnChannel() const { |
| 1453 |
// If the retryable LRS call is null (which only happens when the xds |
| 1454 |
// channel is shutting down), all the LRS calls are stale. |
| 1455 |
if (chand()->lrs_calld_ == nullptr) return false; |
| 1456 |
return this == chand()->lrs_calld_->calld(); |
| 1457 |
} |
| 1458 |
|
| 1459 |
// |
| 1460 |
// XdsClient |
| 1461 |
// |
| 1462 |
|
| 1463 |
XdsClient::XdsClient(std::unique_ptr<XdsBootstrap> bootstrap, |
| 1464 |
OrphanablePtr<XdsTransportFactory> transport_factory, |
| 1465 |
Duration resource_request_timeout) |
| 1466 |
: DualRefCounted<XdsClient>( |
| 1467 |
GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace) ? "XdsClient" |
| 1468 |
: nullptr), |
| 1469 |
bootstrap_(std::move(bootstrap)), |
| 1470 |
transport_factory_(std::move(transport_factory)), |
| 1471 |
request_timeout_(resource_request_timeout), |
| 1472 |
xds_federation_enabled_(XdsFederationEnabled()), |
| 1473 |
api_(this, &grpc_xds_client_trace, bootstrap_->node(), &symtab_), |
| 1474 |
engine_(grpc_event_engine::experimental::GetDefaultEventEngine()) { |
| 1475 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1476 |
gpr_log(GPR_INFO, "[xds_client %p] creating xds client", this); |
| 1477 |
} |
| 1478 |
GPR_ASSERT(bootstrap_ != nullptr); |
| 1479 |
} |
| 1480 |
|
| 1481 |
XdsClient::~XdsClient() { |
| 1482 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1483 |
gpr_log(GPR_INFO, "[xds_client %p] destroying xds client", this); |
| 1484 |
} |
| 1485 |
} |
| 1486 |
|
| 1487 |
void XdsClient::Orphan() { |
| 1488 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1489 |
gpr_log(GPR_INFO, "[xds_client %p] shutting down xds client", this); |
| 1490 |
} |
| 1491 |
MutexLock lock(&mu_); |
| 1492 |
shutting_down_ = true; |
| 1493 |
// Clear cache and any remaining watchers that may not have been cancelled. |
| 1494 |
authority_state_map_.clear(); |
| 1495 |
invalid_watchers_.clear(); |
| 1496 |
// We may still be sending lingering queued load report data, so don't |
| 1497 |
// just clear the load reporting map, but we do want to clear the refs |
| 1498 |
// we're holding to the ChannelState objects, to make sure that |
| 1499 |
// everything shuts down properly. |
| 1500 |
for (auto& p : xds_load_report_server_map_) { |
| 1501 |
p.second.channel_state.reset(DEBUG_LOCATION, "XdsClient::Orphan()"); |
| 1502 |
} |
| 1503 |
} |
| 1504 |
|
| 1505 |
RefCountedPtr<XdsClient::ChannelState> XdsClient::GetOrCreateChannelStateLocked( |
| 1506 |
const XdsBootstrap::XdsServer& server, const char* reason) { |
| 1507 |
auto it = xds_server_channel_map_.find(&server); |
| 1508 |
if (it != xds_server_channel_map_.end()) { |
| 1509 |
return it->second->Ref(DEBUG_LOCATION, reason); |
| 1510 |
} |
| 1511 |
// Channel not found, so create a new one. |
| 1512 |
auto channel_state = MakeRefCounted<ChannelState>( |
| 1513 |
WeakRef(DEBUG_LOCATION, "ChannelState"), server); |
| 1514 |
xds_server_channel_map_[&server] = channel_state.get(); |
| 1515 |
return channel_state; |
| 1516 |
} |
| 1517 |
|
| 1518 |
void XdsClient::WatchResource(const XdsResourceType* type, |
| 1519 |
absl::string_view name, |
| 1520 |
RefCountedPtr<ResourceWatcherInterface> watcher) { |
| 1521 |
ResourceWatcherInterface* w = watcher.get(); |
| 1522 |
// Lambda for handling failure cases. |
| 1523 |
auto fail = [&](absl::Status status) mutable { |
| 1524 |
{ |
| 1525 |
MutexLock lock(&mu_); |
| 1526 |
MaybeRegisterResourceTypeLocked(type); |
| 1527 |
invalid_watchers_[w] = watcher; |
| 1528 |
} |
| 1529 |
work_serializer_.Run( |
| 1530 |
[watcher = std::move(watcher), status = std::move(status)]() |
| 1531 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) { |
| 1532 |
watcher->OnError(status); |
| 1533 |
}, |
| 1534 |
DEBUG_LOCATION); |
| 1535 |
}; |
| 1536 |
auto resource_name = ParseXdsResourceName(name, type); |
| 1537 |
if (!resource_name.ok()) { |
| 1538 |
fail(absl::UnavailableError( |
| 1539 |
absl::StrCat("Unable to parse resource name ", name))); |
| 1540 |
return; |
| 1541 |
} |
| 1542 |
// Find server to use. |
| 1543 |
const XdsBootstrap::XdsServer* xds_server = nullptr; |
| 1544 |
absl::string_view authority_name = resource_name->authority; |
| 1545 |
if (absl::ConsumePrefix(&authority_name, "xdstp:")) { |
| 1546 |
auto* authority = bootstrap_->LookupAuthority(std::string(authority_name)); |
| 1547 |
if (authority == nullptr) { |
| 1548 |
fail(absl::UnavailableError( |
| 1549 |
absl::StrCat("authority \"", authority_name, |
| 1550 |
"\" not present in bootstrap config"))); |
| 1551 |
return; |
| 1552 |
} |
| 1553 |
xds_server = authority->server(); |
| 1554 |
} |
| 1555 |
if (xds_server == nullptr) xds_server = &bootstrap_->server(); |
| 1556 |
{ |
| 1557 |
MutexLock lock(&mu_); |
| 1558 |
MaybeRegisterResourceTypeLocked(type); |
| 1559 |
AuthorityState& authority_state = |
| 1560 |
authority_state_map_[resource_name->authority]; |
| 1561 |
ResourceState& resource_state = |
| 1562 |
authority_state.resource_map[type][resource_name->key]; |
| 1563 |
resource_state.watchers[w] = watcher; |
| 1564 |
// If we already have a cached value for the resource, notify the new |
| 1565 |
// watcher immediately. |
| 1566 |
if (resource_state.resource != nullptr) { |
| 1567 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1568 |
gpr_log(GPR_INFO, |
| 1569 |
"[xds_client %p] returning cached listener data for %s", this, |
| 1570 |
std::string(name).c_str()); |
| 1571 |
} |
| 1572 |
auto* value = type->CopyResource(resource_state.resource.get()).release(); |
| 1573 |
work_serializer_.Schedule( |
| 1574 |
[watcher, value]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) { |
| 1575 |
watcher->OnGenericResourceChanged(value); |
| 1576 |
delete value; |
| 1577 |
}, |
| 1578 |
DEBUG_LOCATION); |
| 1579 |
} else if (resource_state.meta.client_status == |
| 1580 |
XdsApi::ResourceMetadata::DOES_NOT_EXIST) { |
| 1581 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1582 |
gpr_log(GPR_INFO, |
| 1583 |
"[xds_client %p] reporting cached does-not-exist for %s", this, |
| 1584 |
std::string(name).c_str()); |
| 1585 |
} |
| 1586 |
work_serializer_.Schedule( |
| 1587 |
[watcher]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) { |
| 1588 |
watcher->OnResourceDoesNotExist(); |
| 1589 |
}, |
| 1590 |
DEBUG_LOCATION); |
| 1591 |
} else if (resource_state.meta.client_status == |
| 1592 |
XdsApi::ResourceMetadata::NACKED) { |
| 1593 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1594 |
gpr_log( |
| 1595 |
GPR_INFO, |
| 1596 |
"[xds_client %p] reporting cached validation failure for %s: %s", |
| 1597 |
this, std::string(name).c_str(), |
| 1598 |
resource_state.meta.failed_details.c_str()); |
| 1599 |
} |
| 1600 |
std::string details = resource_state.meta.failed_details; |
| 1601 |
const auto* node = bootstrap_->node(); |
| 1602 |
if (node != nullptr) { |
| 1603 |
absl::StrAppend(&details, " (node ID:", bootstrap_->node()->id(), ")"); |
| 1604 |
} |
| 1605 |
work_serializer_.Schedule( |
| 1606 |
[watcher, details = std::move(details)]() |
| 1607 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) { |
| 1608 |
watcher->OnError(absl::UnavailableError( |
| 1609 |
absl::StrCat("invalid resource: ", details))); |
| 1610 |
}, |
| 1611 |
DEBUG_LOCATION); |
| 1612 |
} |
| 1613 |
// If the authority doesn't yet have a channel, set it, creating it if |
| 1614 |
// needed. |
| 1615 |
if (authority_state.channel_state == nullptr) { |
| 1616 |
authority_state.channel_state = |
| 1617 |
GetOrCreateChannelStateLocked(*xds_server, "start watch"); |
| 1618 |
} |
| 1619 |
absl::Status channel_status = authority_state.channel_state->status(); |
| 1620 |
if (!channel_status.ok()) { |
| 1621 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1622 |
gpr_log(GPR_INFO, |
| 1623 |
"[xds_client %p] returning cached channel error for %s: %s", |
| 1624 |
this, std::string(name).c_str(), |
| 1625 |
channel_status.ToString().c_str()); |
| 1626 |
} |
| 1627 |
work_serializer_.Schedule( |
| 1628 |
[watcher = std::move(watcher), status = std::move(channel_status)]() |
| 1629 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) mutable { |
| 1630 |
watcher->OnError(std::move(status)); |
| 1631 |
}, |
| 1632 |
DEBUG_LOCATION); |
| 1633 |
} |
| 1634 |
authority_state.channel_state->SubscribeLocked(type, *resource_name); |
| 1635 |
} |
| 1636 |
work_serializer_.DrainQueue(); |
| 1637 |
} |
| 1638 |
|
| 1639 |
void XdsClient::CancelResourceWatch(const XdsResourceType* type, |
| 1640 |
absl::string_view name, |
| 1641 |
ResourceWatcherInterface* watcher, |
| 1642 |
bool delay_unsubscription) { |
| 1643 |
auto resource_name = ParseXdsResourceName(name, type); |
| 1644 |
MutexLock lock(&mu_); |
| 1645 |
// We cannot be sure whether the watcher is in invalid_watchers_ or in |
| 1646 |
// authority_state_map_, so we check both, just to be safe. |
| 1647 |
invalid_watchers_.erase(watcher); |
| 1648 |
// Find authority. |
| 1649 |
if (!resource_name.ok()) return; |
| 1650 |
auto authority_it = authority_state_map_.find(resource_name->authority); |
| 1651 |
if (authority_it == authority_state_map_.end()) return; |
| 1652 |
AuthorityState& authority_state = authority_it->second; |
| 1653 |
// Find type map. |
| 1654 |
auto type_it = authority_state.resource_map.find(type); |
| 1655 |
if (type_it == authority_state.resource_map.end()) return; |
| 1656 |
auto& type_map = type_it->second; |
| 1657 |
// Find resource key. |
| 1658 |
auto resource_it = type_map.find(resource_name->key); |
| 1659 |
if (resource_it == type_map.end()) return; |
| 1660 |
ResourceState& resource_state = resource_it->second; |
| 1661 |
// Remove watcher. |
| 1662 |
resource_state.watchers.erase(watcher); |
| 1663 |
// Clean up empty map entries, if any. |
| 1664 |
if (resource_state.watchers.empty()) { |
| 1665 |
if (resource_state.ignored_deletion) { |
| 1666 |
gpr_log(GPR_INFO, |
| 1667 |
"[xds_client %p] unsubscribing from a resource for which we " |
| 1668 |
"previously ignored a deletion: type %s name %s", |
| 1669 |
this, std::string(type->type_url()).c_str(), |
| 1670 |
std::string(name).c_str()); |
| 1671 |
} |
| 1672 |
authority_state.channel_state->UnsubscribeLocked(type, *resource_name, |
| 1673 |
delay_unsubscription); |
| 1674 |
type_map.erase(resource_it); |
| 1675 |
if (type_map.empty()) { |
| 1676 |
authority_state.resource_map.erase(type_it); |
| 1677 |
if (authority_state.resource_map.empty()) { |
| 1678 |
authority_state.channel_state.reset(); |
| 1679 |
} |
| 1680 |
} |
| 1681 |
} |
| 1682 |
} |
| 1683 |
|
| 1684 |
void XdsClient::MaybeRegisterResourceTypeLocked( |
| 1685 |
const XdsResourceType* resource_type) { |
| 1686 |
auto it = resource_types_.find(resource_type->type_url()); |
| 1687 |
if (it != resource_types_.end()) { |
| 1688 |
GPR_ASSERT(it->second == resource_type); |
| 1689 |
return; |
| 1690 |
} |
| 1691 |
resource_types_.emplace(resource_type->type_url(), resource_type); |
| 1692 |
resource_type->InitUpbSymtab(this, symtab_.ptr()); |
| 1693 |
} |
| 1694 |
|
| 1695 |
const XdsResourceType* XdsClient::GetResourceTypeLocked( |
| 1696 |
absl::string_view resource_type) { |
| 1697 |
auto it = resource_types_.find(resource_type); |
| 1698 |
if (it != resource_types_.end()) return it->second; |
| 1699 |
return nullptr; |
| 1700 |
} |
| 1701 |
|
| 1702 |
absl::StatusOr<XdsClient::XdsResourceName> XdsClient::ParseXdsResourceName( |
| 1703 |
absl::string_view name, const XdsResourceType* type) { |
| 1704 |
// Old-style names use the empty string for authority. |
| 1705 |
// authority is prefixed with "old:" to indicate that it's an old-style |
| 1706 |
// name. |
| 1707 |
if (!xds_federation_enabled_ || !absl::StartsWith(name, "xdstp:")) { |
| 1708 |
return XdsResourceName{"old:", {std::string(name), {}}}; |
| 1709 |
} |
| 1710 |
// New style name. Parse URI. |
| 1711 |
auto uri = URI::Parse(name); |
| 1712 |
if (!uri.ok()) return uri.status(); |
| 1713 |
// Split the resource type off of the path to get the id. |
| 1714 |
std::pair<absl::string_view, absl::string_view> path_parts = absl::StrSplit( |
| 1715 |
absl::StripPrefix(uri->path(), "/"), absl::MaxSplits('/', 1)); |
| 1716 |
if (type->type_url() != path_parts.first) { |
| 1717 |
return absl::InvalidArgumentError( |
| 1718 |
"xdstp URI path must indicate valid xDS resource type"); |
| 1719 |
} |
| 1720 |
// Canonicalize order of query params. |
| 1721 |
std::vector<URI::QueryParam> query_params; |
| 1722 |
for (const auto& p : uri->query_parameter_map()) { |
| 1723 |
query_params.emplace_back( |
| 1724 |
URI::QueryParam{std::string(p.first), std::string(p.second)}); |
| 1725 |
} |
| 1726 |
return XdsResourceName{ |
| 1727 |
absl::StrCat("xdstp:", uri->authority()), |
| 1728 |
{std::string(path_parts.second), std::move(query_params)}}; |
| 1729 |
} |
| 1730 |
|
| 1731 |
std::string XdsClient::ConstructFullXdsResourceName( |
| 1732 |
absl::string_view authority, absl::string_view resource_type, |
| 1733 |
const XdsResourceKey& key) { |
| 1734 |
if (absl::ConsumePrefix(&authority, "xdstp:")) { |
| 1735 |
auto uri = URI::Create("xdstp", std::string(authority), |
| 1736 |
absl::StrCat("/", resource_type, "/", key.id), |
| 1737 |
key.query_params, /*fragment=*/""); |
| 1738 |
GPR_ASSERT(uri.ok()); |
| 1739 |
return uri->ToString(); |
| 1740 |
} |
| 1741 |
// Old-style name. |
| 1742 |
return key.id; |
| 1743 |
} |
| 1744 |
|
| 1745 |
RefCountedPtr<XdsClusterDropStats> XdsClient::AddClusterDropStats( |
| 1746 |
const XdsBootstrap::XdsServer& xds_server, absl::string_view cluster_name, |
| 1747 |
absl::string_view eds_service_name) { |
| 1748 |
const auto* server = bootstrap_->FindXdsServer(xds_server); |
| 1749 |
if (server == nullptr) return nullptr; |
| 1750 |
auto key = |
| 1751 |
std::make_pair(std::string(cluster_name), std::string(eds_service_name)); |
| 1752 |
RefCountedPtr<XdsClusterDropStats> cluster_drop_stats; |
| 1753 |
{ |
| 1754 |
MutexLock lock(&mu_); |
| 1755 |
// We jump through some hoops here to make sure that the const |
| 1756 |
// XdsBootstrap::XdsServer& and absl::string_views |
| 1757 |
// stored in the XdsClusterDropStats object point to the |
| 1758 |
// XdsBootstrap::XdsServer and strings |
| 1759 |
// in the load_report_map_ key, so that they have the same lifetime. |
| 1760 |
auto server_it = |
| 1761 |
xds_load_report_server_map_.emplace(server, LoadReportServer()).first; |
| 1762 |
if (server_it->second.channel_state == nullptr) { |
| 1763 |
server_it->second.channel_state = GetOrCreateChannelStateLocked( |
| 1764 |
*server, "load report map (drop stats)"); |
| 1765 |
} |
| 1766 |
auto load_report_it = server_it->second.load_report_map |
| 1767 |
.emplace(std::move(key), LoadReportState()) |
| 1768 |
.first; |
| 1769 |
LoadReportState& load_report_state = load_report_it->second; |
| 1770 |
if (load_report_state.drop_stats != nullptr) { |
| 1771 |
cluster_drop_stats = load_report_state.drop_stats->RefIfNonZero(); |
| 1772 |
} |
| 1773 |
if (cluster_drop_stats == nullptr) { |
| 1774 |
if (load_report_state.drop_stats != nullptr) { |
| 1775 |
load_report_state.deleted_drop_stats += |
| 1776 |
load_report_state.drop_stats->GetSnapshotAndReset(); |
| 1777 |
} |
| 1778 |
cluster_drop_stats = MakeRefCounted<XdsClusterDropStats>( |
| 1779 |
Ref(DEBUG_LOCATION, "DropStats"), *server, |
| 1780 |
load_report_it->first.first /*cluster_name*/, |
| 1781 |
load_report_it->first.second /*eds_service_name*/); |
| 1782 |
load_report_state.drop_stats = cluster_drop_stats.get(); |
| 1783 |
} |
| 1784 |
server_it->second.channel_state->MaybeStartLrsCall(); |
| 1785 |
} |
| 1786 |
work_serializer_.DrainQueue(); |
| 1787 |
return cluster_drop_stats; |
| 1788 |
} |
| 1789 |
|
| 1790 |
void XdsClient::RemoveClusterDropStats( |
| 1791 |
const XdsBootstrap::XdsServer& xds_server, absl::string_view cluster_name, |
| 1792 |
absl::string_view eds_service_name, |
| 1793 |
XdsClusterDropStats* cluster_drop_stats) { |
| 1794 |
const auto* server = bootstrap_->FindXdsServer(xds_server); |
| 1795 |
if (server == nullptr) return; |
| 1796 |
MutexLock lock(&mu_); |
| 1797 |
auto server_it = xds_load_report_server_map_.find(server); |
| 1798 |
if (server_it == xds_load_report_server_map_.end()) return; |
| 1799 |
auto load_report_it = server_it->second.load_report_map.find( |
| 1800 |
std::make_pair(std::string(cluster_name), std::string(eds_service_name))); |
| 1801 |
if (load_report_it == server_it->second.load_report_map.end()) return; |
| 1802 |
LoadReportState& load_report_state = load_report_it->second; |
| 1803 |
if (load_report_state.drop_stats == cluster_drop_stats) { |
| 1804 |
// Record final snapshot in deleted_drop_stats, which will be |
| 1805 |
// added to the next load report. |
| 1806 |
load_report_state.deleted_drop_stats += |
| 1807 |
load_report_state.drop_stats->GetSnapshotAndReset(); |
| 1808 |
load_report_state.drop_stats = nullptr; |
| 1809 |
} |
| 1810 |
} |
| 1811 |
|
| 1812 |
RefCountedPtr<XdsClusterLocalityStats> XdsClient::AddClusterLocalityStats( |
| 1813 |
const XdsBootstrap::XdsServer& xds_server, absl::string_view cluster_name, |
| 1814 |
absl::string_view eds_service_name, |
| 1815 |
RefCountedPtr<XdsLocalityName> locality) { |
| 1816 |
const auto* server = bootstrap_->FindXdsServer(xds_server); |
| 1817 |
if (server == nullptr) return nullptr; |
| 1818 |
auto key = |
| 1819 |
std::make_pair(std::string(cluster_name), std::string(eds_service_name)); |
| 1820 |
RefCountedPtr<XdsClusterLocalityStats> cluster_locality_stats; |
| 1821 |
{ |
| 1822 |
MutexLock lock(&mu_); |
| 1823 |
// We jump through some hoops here to make sure that the const |
| 1824 |
// XdsBootstrap::XdsServer& and absl::string_views |
| 1825 |
// stored in the XdsClusterDropStats object point to the |
| 1826 |
// XdsBootstrap::XdsServer and strings |
| 1827 |
// in the load_report_map_ key, so that they have the same lifetime. |
| 1828 |
auto server_it = |
| 1829 |
xds_load_report_server_map_.emplace(server, LoadReportServer()).first; |
| 1830 |
if (server_it->second.channel_state == nullptr) { |
| 1831 |
server_it->second.channel_state = GetOrCreateChannelStateLocked( |
| 1832 |
*server, "load report map (locality stats)"); |
| 1833 |
} |
| 1834 |
auto load_report_it = server_it->second.load_report_map |
| 1835 |
.emplace(std::move(key), LoadReportState()) |
| 1836 |
.first; |
| 1837 |
LoadReportState& load_report_state = load_report_it->second; |
| 1838 |
LoadReportState::LocalityState& locality_state = |
| 1839 |
load_report_state.locality_stats[locality]; |
| 1840 |
if (locality_state.locality_stats != nullptr) { |
| 1841 |
cluster_locality_stats = locality_state.locality_stats->RefIfNonZero(); |
| 1842 |
} |
| 1843 |
if (cluster_locality_stats == nullptr) { |
| 1844 |
if (locality_state.locality_stats != nullptr) { |
| 1845 |
locality_state.deleted_locality_stats += |
| 1846 |
locality_state.locality_stats->GetSnapshotAndReset(); |
| 1847 |
} |
| 1848 |
cluster_locality_stats = MakeRefCounted<XdsClusterLocalityStats>( |
| 1849 |
Ref(DEBUG_LOCATION, "LocalityStats"), *server, |
| 1850 |
load_report_it->first.first /*cluster_name*/, |
| 1851 |
load_report_it->first.second /*eds_service_name*/, |
| 1852 |
std::move(locality)); |
| 1853 |
locality_state.locality_stats = cluster_locality_stats.get(); |
| 1854 |
} |
| 1855 |
server_it->second.channel_state->MaybeStartLrsCall(); |
| 1856 |
} |
| 1857 |
work_serializer_.DrainQueue(); |
| 1858 |
return cluster_locality_stats; |
| 1859 |
} |
| 1860 |
|
| 1861 |
void XdsClient::RemoveClusterLocalityStats( |
| 1862 |
const XdsBootstrap::XdsServer& xds_server, absl::string_view cluster_name, |
| 1863 |
absl::string_view eds_service_name, |
| 1864 |
const RefCountedPtr<XdsLocalityName>& locality, |
| 1865 |
XdsClusterLocalityStats* cluster_locality_stats) { |
| 1866 |
const auto* server = bootstrap_->FindXdsServer(xds_server); |
| 1867 |
if (server == nullptr) return; |
| 1868 |
MutexLock lock(&mu_); |
| 1869 |
auto server_it = xds_load_report_server_map_.find(server); |
| 1870 |
if (server_it == xds_load_report_server_map_.end()) return; |
| 1871 |
auto load_report_it = server_it->second.load_report_map.find( |
| 1872 |
std::make_pair(std::string(cluster_name), std::string(eds_service_name))); |
| 1873 |
if (load_report_it == server_it->second.load_report_map.end()) return; |
| 1874 |
LoadReportState& load_report_state = load_report_it->second; |
| 1875 |
auto locality_it = load_report_state.locality_stats.find(locality); |
| 1876 |
if (locality_it == load_report_state.locality_stats.end()) return; |
| 1877 |
LoadReportState::LocalityState& locality_state = locality_it->second; |
| 1878 |
if (locality_state.locality_stats == cluster_locality_stats) { |
| 1879 |
// Record final snapshot in deleted_locality_stats, which will be |
| 1880 |
// added to the next load report. |
| 1881 |
locality_state.deleted_locality_stats += |
| 1882 |
locality_state.locality_stats->GetSnapshotAndReset(); |
| 1883 |
locality_state.locality_stats = nullptr; |
| 1884 |
} |
| 1885 |
} |
| 1886 |
|
| 1887 |
void XdsClient::ResetBackoff() { |
| 1888 |
MutexLock lock(&mu_); |
| 1889 |
for (auto& p : xds_server_channel_map_) { |
| 1890 |
p.second->ResetBackoff(); |
| 1891 |
} |
| 1892 |
} |
| 1893 |
|
| 1894 |
void XdsClient::NotifyWatchersOnErrorLocked( |
| 1895 |
const std::map<ResourceWatcherInterface*, |
| 1896 |
RefCountedPtr<ResourceWatcherInterface>>& watchers, |
| 1897 |
absl::Status status) { |
| 1898 |
const auto* node = bootstrap_->node(); |
| 1899 |
if (node != nullptr) { |
| 1900 |
status = absl::Status( |
| 1901 |
status.code(), |
| 1902 |
absl::StrCat(status.message(), " (node ID:", node->id(), ")")); |
| 1903 |
} |
| 1904 |
work_serializer_.Schedule( |
| 1905 |
[watchers, status = std::move(status)]() |
| 1906 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) { |
| 1907 |
for (const auto& p : watchers) { |
| 1908 |
p.first->OnError(status); |
| 1909 |
} |
| 1910 |
}, |
| 1911 |
DEBUG_LOCATION); |
| 1912 |
} |
| 1913 |
|
| 1914 |
void XdsClient::NotifyWatchersOnResourceDoesNotExist( |
| 1915 |
const std::map<ResourceWatcherInterface*, |
| 1916 |
RefCountedPtr<ResourceWatcherInterface>>& watchers) { |
| 1917 |
work_serializer_.Schedule( |
| 1918 |
[watchers]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) { |
| 1919 |
for (const auto& p : watchers) { |
| 1920 |
p.first->OnResourceDoesNotExist(); |
| 1921 |
} |
| 1922 |
}, |
| 1923 |
DEBUG_LOCATION); |
| 1924 |
} |
| 1925 |
|
| 1926 |
XdsApi::ClusterLoadReportMap XdsClient::BuildLoadReportSnapshotLocked( |
| 1927 |
const XdsBootstrap::XdsServer& xds_server, bool send_all_clusters, |
| 1928 |
const std::set<std::string>& clusters) { |
| 1929 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1930 |
gpr_log(GPR_INFO, "[xds_client %p] start building load report", this); |
| 1931 |
} |
| 1932 |
XdsApi::ClusterLoadReportMap snapshot_map; |
| 1933 |
auto server_it = xds_load_report_server_map_.find(&xds_server); |
| 1934 |
if (server_it == xds_load_report_server_map_.end()) return snapshot_map; |
| 1935 |
auto& load_report_map = server_it->second.load_report_map; |
| 1936 |
for (auto load_report_it = load_report_map.begin(); |
| 1937 |
load_report_it != load_report_map.end();) { |
| 1938 |
// Cluster key is cluster and EDS service name. |
| 1939 |
const auto& cluster_key = load_report_it->first; |
| 1940 |
LoadReportState& load_report = load_report_it->second; |
| 1941 |
// If the CDS response for a cluster indicates to use LRS but the |
| 1942 |
// LRS server does not say that it wants reports for this cluster, |
| 1943 |
// then we'll have stats objects here whose data we're not going to |
| 1944 |
// include in the load report. However, we still need to clear out |
| 1945 |
// the data from the stats objects, so that if the LRS server starts |
| 1946 |
// asking for the data in the future, we don't incorrectly include |
| 1947 |
// data from previous reporting intervals in that future report. |
| 1948 |
const bool record_stats = |
| 1949 |
send_all_clusters || clusters.find(cluster_key.first) != clusters.end(); |
| 1950 |
XdsApi::ClusterLoadReport snapshot; |
| 1951 |
// Aggregate drop stats. |
| 1952 |
snapshot.dropped_requests = std::move(load_report.deleted_drop_stats); |
| 1953 |
if (load_report.drop_stats != nullptr) { |
| 1954 |
snapshot.dropped_requests += |
| 1955 |
load_report.drop_stats->GetSnapshotAndReset(); |
| 1956 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1957 |
gpr_log(GPR_INFO, |
| 1958 |
"[xds_client %p] cluster=%s eds_service_name=%s drop_stats=%p", |
| 1959 |
this, cluster_key.first.c_str(), cluster_key.second.c_str(), |
| 1960 |
load_report.drop_stats); |
| 1961 |
} |
| 1962 |
} |
| 1963 |
// Aggregate locality stats. |
| 1964 |
for (auto it = load_report.locality_stats.begin(); |
| 1965 |
it != load_report.locality_stats.end();) { |
| 1966 |
const RefCountedPtr<XdsLocalityName>& locality_name = it->first; |
| 1967 |
auto& locality_state = it->second; |
| 1968 |
XdsClusterLocalityStats::Snapshot& locality_snapshot = |
| 1969 |
snapshot.locality_stats[locality_name]; |
| 1970 |
locality_snapshot = std::move(locality_state.deleted_locality_stats); |
| 1971 |
if (locality_state.locality_stats != nullptr) { |
| 1972 |
locality_snapshot += |
| 1973 |
locality_state.locality_stats->GetSnapshotAndReset(); |
| 1974 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) { |
| 1975 |
gpr_log(GPR_INFO, |
| 1976 |
"[xds_client %p] cluster=%s eds_service_name=%s " |
| 1977 |
"locality=%s locality_stats=%p", |
| 1978 |
this, cluster_key.first.c_str(), cluster_key.second.c_str(), |
| 1979 |
locality_name->AsHumanReadableString().c_str(), |
| 1980 |
locality_state.locality_stats); |
| 1981 |
} |
| 1982 |
} |
| 1983 |
// If the only thing left in this entry was final snapshots from |
| 1984 |
// deleted locality stats objects, remove the entry. |
| 1985 |
if (locality_state.locality_stats == nullptr) { |
| 1986 |
it = load_report.locality_stats.erase(it); |
| 1987 |
} else { |
| 1988 |
++it; |
| 1989 |
} |
| 1990 |
} |
| 1991 |
// Compute load report interval. |
| 1992 |
const Timestamp now = Timestamp::Now(); |
| 1993 |
snapshot.load_report_interval = now - load_report.last_report_time; |
| 1994 |
load_report.last_report_time = now; |
| 1995 |
// Record snapshot. |
| 1996 |
if (record_stats) { |
| 1997 |
snapshot_map[cluster_key] = std::move(snapshot); |
| 1998 |
} |
| 1999 |
// If the only thing left in this entry was final snapshots from |
| 2000 |
// deleted stats objects, remove the entry. |
| 2001 |
if (load_report.locality_stats.empty() && |
| 2002 |
load_report.drop_stats == nullptr) { |
| 2003 |
load_report_it = load_report_map.erase(load_report_it); |
| 2004 |
} else { |
| 2005 |
++load_report_it; |
| 2006 |
} |
| 2007 |
} |
| 2008 |
return snapshot_map; |
| 2009 |
} |
| 2010 |
|
| 2011 |
std::string XdsClient::DumpClientConfigBinary() { |
| 2012 |
MutexLock lock(&mu_); |
| 2013 |
XdsApi::ResourceTypeMetadataMap resource_type_metadata_map; |
| 2014 |
for (const auto& a : authority_state_map_) { // authority |
| 2015 |
const std::string& authority = a.first; |
| 2016 |
for (const auto& t : a.second.resource_map) { // type |
| 2017 |
const XdsResourceType* type = t.first; |
| 2018 |
auto& resource_metadata_map = |
| 2019 |
resource_type_metadata_map[type->type_url()]; |
| 2020 |
for (const auto& r : t.second) { // resource id |
| 2021 |
const XdsResourceKey& resource_key = r.first; |
| 2022 |
const ResourceState& resource_state = r.second; |
| 2023 |
resource_metadata_map[ConstructFullXdsResourceName( |
| 2024 |
authority, type->type_url(), resource_key)] = &resource_state.meta; |
| 2025 |
} |
| 2026 |
} |
| 2027 |
} |
| 2028 |
// Assemble config dump messages |
| 2029 |
return api_.AssembleClientConfig(resource_type_metadata_map); |
| 2030 |
} |
| 2031 |
|
| 2032 |
} // namespace grpc_core |