Debian Codegraph @

src/core/ext/xds/xds_client.h

raw
1 //
2 // Copyright 2019 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #ifndef GRPC_CORE_EXT_XDS_XDS_CLIENT_H
18 #define GRPC_CORE_EXT_XDS_XDS_CLIENT_H
19
20 #include <grpc/support/port_platform.h>
21
22 #include <map>
23 #include <memory>
24 #include <set>
25 #include <string>
26 #include <utility>
27 #include <vector>
28
29 #include "absl/base/thread_annotations.h"
30 #include "absl/status/status.h"
31 #include "absl/status/statusor.h"
32 #include "absl/strings/string_view.h"
33 #include "upb/def.hpp"
34
35 #include <grpc/event_engine/event_engine.h>
36
37 #include "src/core/ext/xds/xds_api.h"
38 #include "src/core/ext/xds/xds_bootstrap.h"
39 #include "src/core/ext/xds/xds_client_stats.h"
40 #include "src/core/ext/xds/xds_resource_type.h"
41 #include "src/core/ext/xds/xds_transport.h"
42 #include "src/core/lib/debug/trace.h"
43 #include "src/core/lib/gprpp/dual_ref_counted.h"
44 #include "src/core/lib/gprpp/orphanable.h"
45 #include "src/core/lib/gprpp/ref_counted.h"
46 #include "src/core/lib/gprpp/ref_counted_ptr.h"
47 #include "src/core/lib/gprpp/sync.h"
48 #include "src/core/lib/gprpp/time.h"
49 #include "src/core/lib/gprpp/work_serializer.h"
50 #include "src/core/lib/uri/uri_parser.h"
51
52 namespace grpc_core {
53
54 extern TraceFlag grpc_xds_client_trace;
55 extern TraceFlag grpc_xds_client_refcount_trace;
56
57 class XdsClient : public DualRefCounted<XdsClient> {
58 public:
59 // Resource watcher interface. Implemented by callers.
60 // Note: Most callers will not use this API directly but rather via a
61 // resource-type-specific wrapper API provided by the relevant
62 // XdsResourceType implementation.
63 class ResourceWatcherInterface : public RefCounted<ResourceWatcherInterface> {
64 public:
65 virtual void OnGenericResourceChanged(
66 const XdsResourceType::ResourceData* resource)
67 ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) = 0;
68 virtual void OnError(absl::Status status)
69 ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) = 0;
70 virtual void OnResourceDoesNotExist()
71 ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) = 0;
72 };
73
74 XdsClient(std::unique_ptr<XdsBootstrap> bootstrap,
75 OrphanablePtr<XdsTransportFactory> transport_factory,
76 Duration resource_request_timeout = Duration::Seconds(15));
77 ~XdsClient() override;
78
79 const XdsBootstrap& bootstrap() const {
80 return *bootstrap_; // ctor asserts that it is non-null
81 }
82
83 XdsTransportFactory* transport_factory() const {
84 return transport_factory_.get();
85 }
86
87 void Orphan() override;
88
89 // Start and cancel watch for a resource.
90 //
91 // The XdsClient takes ownership of the watcher, but the caller may
92 // keep a raw pointer to the watcher, which may be used only for
93 // cancellation. (Because the caller does not own the watcher, the
94 // pointer must not be used for any other purpose.)
95 // If the caller is going to start a new watch after cancelling the
96 // old one, it should set delay_unsubscription to true.
97 //
98 // The resource type object must be a global singleton, since the first
99 // time the XdsClient sees a particular resource type object, it will
100 // store the pointer to that object as the authoritative implementation for
101 // its type URLs. The resource type object must outlive the XdsClient object,
102 // and it is illegal to start a subsequent watch for the same type URLs using
103 // a different resource type object.
104 //
105 // Note: Most callers will not use this API directly but rather via a
106 // resource-type-specific wrapper API provided by the relevant
107 // XdsResourceType implementation.
108 void WatchResource(const XdsResourceType* type, absl::string_view name,
109 RefCountedPtr<ResourceWatcherInterface> watcher);
110 void CancelResourceWatch(const XdsResourceType* type,
111 absl::string_view listener_name,
112 ResourceWatcherInterface* watcher,
113 bool delay_unsubscription = false);
114
115 // Adds and removes drop stats for cluster_name and eds_service_name.
116 RefCountedPtr<XdsClusterDropStats> AddClusterDropStats(
117 const XdsBootstrap::XdsServer& xds_server, absl::string_view cluster_name,
118 absl::string_view eds_service_name);
119 void RemoveClusterDropStats(const XdsBootstrap::XdsServer& xds_server,
120 absl::string_view cluster_name,
121 absl::string_view eds_service_name,
122 XdsClusterDropStats* cluster_drop_stats);
123
124 // Adds and removes locality stats for cluster_name and eds_service_name
125 // for the specified locality.
126 RefCountedPtr<XdsClusterLocalityStats> AddClusterLocalityStats(
127 const XdsBootstrap::XdsServer& xds_server, absl::string_view cluster_name,
128 absl::string_view eds_service_name,
129 RefCountedPtr<XdsLocalityName> locality);
130 void RemoveClusterLocalityStats(
131 const XdsBootstrap::XdsServer& xds_server, absl::string_view cluster_name,
132 absl::string_view eds_service_name,
133 const RefCountedPtr<XdsLocalityName>& locality,
134 XdsClusterLocalityStats* cluster_locality_stats);
135
136 // Resets connection backoff state.
137 void ResetBackoff();
138
139 // Dumps the active xDS config in JSON format.
140 // Individual xDS resource is encoded as envoy.admin.v3.*ConfigDump. Returns
141 // envoy.service.status.v3.ClientConfig which also includes the config
142 // status (e.g., CLIENT_REQUESTED, CLIENT_ACKED, CLIENT_NACKED).
143 //
144 // Expected to be invoked by wrapper languages in their CSDS service
145 // implementation.
146 std::string DumpClientConfigBinary();
147
148 grpc_event_engine::experimental::EventEngine* engine() {
149 return engine_.get();
150 }
151
152 private:
153 struct XdsResourceKey {
154 std::string id;
155 std::vector<URI::QueryParam> query_params;
156
157 bool operator<(const XdsResourceKey& other) const {
158 int c = id.compare(other.id);
159 if (c != 0) return c < 0;
160 return query_params < other.query_params;
161 }
162 };
163
164 struct XdsResourceName {
165 std::string authority;
166 XdsResourceKey key;
167 };
168
169 // Contains a channel to the xds server and all the data related to the
170 // channel. Holds a ref to the xds client object.
171 class ChannelState : public DualRefCounted<ChannelState> {
172 public:
173 template <typename T>
174 class RetryableCall;
175
176 class AdsCallState;
177 class LrsCallState;
178
179 ChannelState(WeakRefCountedPtr<XdsClient> xds_client,
180 const XdsBootstrap::XdsServer& server);
181 ~ChannelState() override;
182
183 void Orphan() override;
184
185 XdsClient* xds_client() const { return xds_client_.get(); }
186 AdsCallState* ads_calld() const;
187 LrsCallState* lrs_calld() const;
188
189 void ResetBackoff();
190
191 void MaybeStartLrsCall();
192 void StopLrsCallLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);
193
194 // Returns non-OK if there has been an error since the last time the
195 // ADS stream saw a response.
196 const absl::Status& status() const { return status_; }
197
198 void SubscribeLocked(const XdsResourceType* type,
199 const XdsResourceName& name)
200 ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);
201 void UnsubscribeLocked(const XdsResourceType* type,
202 const XdsResourceName& name,
203 bool delay_unsubscription)
204 ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);
205
206 private:
207 void OnConnectivityFailure(absl::Status status);
208
209 // Enqueues error notifications to watchers. Caller must drain
210 // XdsClient::work_serializer_ after releasing the lock.
211 void SetChannelStatusLocked(absl::Status status)
212 ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);
213
214 // The owning xds client.
215 WeakRefCountedPtr<XdsClient> xds_client_;
216
217 const XdsBootstrap::XdsServer& server_; // Owned by bootstrap.
218
219 OrphanablePtr<XdsTransportFactory::XdsTransport> transport_;
220
221 bool shutting_down_ = false;
222
223 // The retryable XDS calls.
224 OrphanablePtr<RetryableCall<AdsCallState>> ads_calld_;
225 OrphanablePtr<RetryableCall<LrsCallState>> lrs_calld_;
226
227 // Stores the most recent accepted resource version for each resource type.
228 std::map<const XdsResourceType*, std::string /*version*/>
229 resource_type_version_map_;
230
231 absl::Status status_;
232 };
233
234 struct ResourceState {
235 std::map<ResourceWatcherInterface*, RefCountedPtr<ResourceWatcherInterface>>
236 watchers;
237 // The latest data seen for the resource.
238 std::unique_ptr<XdsResourceType::ResourceData> resource;
239 XdsApi::ResourceMetadata meta;
240 bool ignored_deletion = false;
241 };
242
243 struct AuthorityState {
244 RefCountedPtr<ChannelState> channel_state;
245 std::map<const XdsResourceType*, std::map<XdsResourceKey, ResourceState>>
246 resource_map;
247 };
248
249 struct LoadReportState {
250 struct LocalityState {
251 XdsClusterLocalityStats* locality_stats = nullptr;
252 XdsClusterLocalityStats::Snapshot deleted_locality_stats;
253 };
254
255 XdsClusterDropStats* drop_stats = nullptr;
256 XdsClusterDropStats::Snapshot deleted_drop_stats;
257 std::map<RefCountedPtr<XdsLocalityName>, LocalityState,
258 XdsLocalityName::Less>
259 locality_stats;
260 Timestamp last_report_time = Timestamp::Now();
261 };
262
263 // Load report data.
264 using LoadReportMap = std::map<
265 std::pair<std::string /*cluster_name*/, std::string /*eds_service_name*/>,
266 LoadReportState>;
267
268 struct LoadReportServer {
269 RefCountedPtr<ChannelState> channel_state;
270 LoadReportMap load_report_map;
271 };
272
273 // Sends an error notification to a specific set of watchers.
274 void NotifyWatchersOnErrorLocked(
275 const std::map<ResourceWatcherInterface*,
276 RefCountedPtr<ResourceWatcherInterface>>& watchers,
277 absl::Status status);
278 // Sends a resource-does-not-exist notification to a specific set of watchers.
279 void NotifyWatchersOnResourceDoesNotExist(
280 const std::map<ResourceWatcherInterface*,
281 RefCountedPtr<ResourceWatcherInterface>>& watchers);
282
283 void MaybeRegisterResourceTypeLocked(const XdsResourceType* resource_type)
284 ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
285
286 // Gets the type for resource_type, or null if the type is unknown.
287 const XdsResourceType* GetResourceTypeLocked(absl::string_view resource_type)
288 ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
289
290 absl::StatusOr<XdsResourceName> ParseXdsResourceName(
291 absl::string_view name, const XdsResourceType* type);
292 static std::string ConstructFullXdsResourceName(
293 absl::string_view authority, absl::string_view resource_type,
294 const XdsResourceKey& key);
295
296 XdsApi::ClusterLoadReportMap BuildLoadReportSnapshotLocked(
297 const XdsBootstrap::XdsServer& xds_server, bool send_all_clusters,
298 const std::set<std::string>& clusters) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
299
300 RefCountedPtr<ChannelState> GetOrCreateChannelStateLocked(
301 const XdsBootstrap::XdsServer& server, const char* reason)
302 ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
303
304 std::unique_ptr<XdsBootstrap> bootstrap_;
305 OrphanablePtr<XdsTransportFactory> transport_factory_;
306 const Duration request_timeout_;
307 const bool xds_federation_enabled_;
308 XdsApi api_;
309 WorkSerializer work_serializer_;
310 std::shared_ptr<grpc_event_engine::experimental::EventEngine> engine_;
311
312 Mutex mu_;
313
314 // Stores resource type objects seen by type URL.
315 std::map<absl::string_view /*resource_type*/, const XdsResourceType*>
316 resource_types_ ABSL_GUARDED_BY(mu_);
317 upb::SymbolTable symtab_ ABSL_GUARDED_BY(mu_);
318
319 // Map of existing xDS server channels.
320 // Key is owned by the bootstrap config.
321 std::map<const XdsBootstrap::XdsServer*, ChannelState*>
322 xds_server_channel_map_ ABSL_GUARDED_BY(mu_);
323
324 std::map<std::string /*authority*/, AuthorityState> authority_state_map_
325 ABSL_GUARDED_BY(mu_);
326
327 // Key is owned by the bootstrap config.
328 std::map<const XdsBootstrap::XdsServer*, LoadReportServer>
329 xds_load_report_server_map_ ABSL_GUARDED_BY(mu_);
330
331 // Stores started watchers whose resource name was not parsed successfully,
332 // waiting to be cancelled or reset in Orphan().
333 std::map<ResourceWatcherInterface*, RefCountedPtr<ResourceWatcherInterface>>
334 invalid_watchers_ ABSL_GUARDED_BY(mu_);
335
336 bool shutting_down_ ABSL_GUARDED_BY(mu_) = false;
337 };
338
339 } // namespace grpc_core
340
341 #endif // GRPC_CORE_EXT_XDS_XDS_CLIENT_H