Debian Codegraph @

src/core/ext/xds/xds_endpoint.cc

raw
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_endpoint.h"
20
21 #include <stdlib.h>
22 #include <string.h>
23
24 #include <algorithm>
25 #include <limits>
26 #include <set>
27 #include <vector>
28
29 #include "absl/status/status.h"
30 #include "absl/status/statusor.h"
31 #include "absl/strings/str_cat.h"
32 #include "absl/strings/str_join.h"
33 #include "absl/types/optional.h"
34 #include "envoy/config/core/v3/address.upb.h"
35 #include "envoy/config/core/v3/base.upb.h"
36 #include "envoy/config/core/v3/health_check.upb.h"
37 #include "envoy/config/endpoint/v3/endpoint.upb.h"
38 #include "envoy/config/endpoint/v3/endpoint.upbdefs.h"
39 #include "envoy/config/endpoint/v3/endpoint_components.upb.h"
40 #include "envoy/type/v3/percent.upb.h"
41 #include "google/protobuf/wrappers.upb.h"
42 #include "upb/text_encode.h"
43
44 #include <grpc/support/log.h>
45
46 #include "src/core/ext/xds/upb_utils.h"
47 #include "src/core/ext/xds/xds_resource_type.h"
48 #include "src/core/lib/address_utils/parse_address.h"
49 #include "src/core/lib/address_utils/sockaddr_utils.h"
50 #include "src/core/lib/channel/channel_args.h"
51 #include "src/core/lib/debug/trace.h"
52 #include "src/core/lib/gprpp/validation_errors.h"
53 #include "src/core/lib/iomgr/resolved_address.h"
54
55 namespace grpc_core {
56
57 //
58 // XdsEndpointResource
59 //
60
61 std::string XdsEndpointResource::Priority::Locality::ToString() const {
62 std::vector<std::string> endpoint_strings;
63 for (const ServerAddress& endpoint : endpoints) {
64 endpoint_strings.emplace_back(endpoint.ToString());
65 }
66 return absl::StrCat("{name=", name->AsHumanReadableString(),
67 ", lb_weight=", lb_weight, ", endpoints=[",
68 absl::StrJoin(endpoint_strings, ", "), "]}");
69 }
70
71 bool XdsEndpointResource::Priority::operator==(const Priority& other) const {
72 if (localities.size() != other.localities.size()) return false;
73 auto it1 = localities.begin();
74 auto it2 = other.localities.begin();
75 while (it1 != localities.end()) {
76 if (*it1->first != *it2->first) return false;
77 if (it1->second != it2->second) return false;
78 ++it1;
79 ++it2;
80 }
81 return true;
82 }
83
84 std::string XdsEndpointResource::Priority::ToString() const {
85 std::vector<std::string> locality_strings;
86 locality_strings.reserve(localities.size());
87 for (const auto& p : localities) {
88 locality_strings.emplace_back(p.second.ToString());
89 }
90 return absl::StrCat("[", absl::StrJoin(locality_strings, ", "), "]");
91 }
92
93 bool XdsEndpointResource::DropConfig::ShouldDrop(
94 const std::string** category_name) const {
95 for (size_t i = 0; i < drop_category_list_.size(); ++i) {
96 const auto& drop_category = drop_category_list_[i];
97 // Generate a random number in [0, 1000000).
98 const uint32_t random = static_cast<uint32_t>(rand()) % 1000000;
99 if (random < drop_category.parts_per_million) {
100 *category_name = &drop_category.name;
101 return true;
102 }
103 }
104 return false;
105 }
106
107 std::string XdsEndpointResource::DropConfig::ToString() const {
108 std::vector<std::string> category_strings;
109 for (const DropCategory& category : drop_category_list_) {
110 category_strings.emplace_back(
111 absl::StrCat(category.name, "=", category.parts_per_million));
112 }
113 return absl::StrCat("{[", absl::StrJoin(category_strings, ", "),
114 "], drop_all=", drop_all_, "}");
115 }
116
117 std::string XdsEndpointResource::ToString() const {
118 std::vector<std::string> priority_strings;
119 for (size_t i = 0; i < priorities.size(); ++i) {
120 const Priority& priority = priorities[i];
121 priority_strings.emplace_back(
122 absl::StrCat("priority ", i, ": ", priority.ToString()));
123 }
124 return absl::StrCat("priorities=[", absl::StrJoin(priority_strings, ", "),
125 "], drop_config=", drop_config->ToString());
126 }
127
128 //
129 // XdsEndpointResourceType
130 //
131
132 namespace {
133
134 void MaybeLogClusterLoadAssignment(
135 const XdsResourceType::DecodeContext& context,
136 const envoy_config_endpoint_v3_ClusterLoadAssignment* cla) {
137 if (GRPC_TRACE_FLAG_ENABLED(*context.tracer) &&
138 gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) {
139 const upb_MessageDef* msg_type =
140 envoy_config_endpoint_v3_ClusterLoadAssignment_getmsgdef(
141 context.symtab);
142 char buf[10240];
143 upb_TextEncode(cla, msg_type, nullptr, 0, buf, sizeof(buf));
144 gpr_log(GPR_DEBUG, "[xds_client %p] ClusterLoadAssignment: %s",
145 context.client, buf);
146 }
147 }
148
149 absl::optional<ServerAddress> ServerAddressParse(
150 const envoy_config_endpoint_v3_LbEndpoint* lb_endpoint,
151 ValidationErrors* errors) {
152 // health_status
153 // If not HEALTHY or UNKNOWN, skip this endpoint.
154 const int32_t health_status =
155 envoy_config_endpoint_v3_LbEndpoint_health_status(lb_endpoint);
156 if (health_status != envoy_config_core_v3_UNKNOWN &&
157 health_status != envoy_config_core_v3_HEALTHY) {
158 return absl::nullopt;
159 }
160 // load_balancing_weight
161 uint32_t weight = 1;
162 {
163 ValidationErrors::ScopedField field(errors, ".load_balancing_weight");
164 const google_protobuf_UInt32Value* load_balancing_weight =
165 envoy_config_endpoint_v3_LbEndpoint_load_balancing_weight(lb_endpoint);
166 if (load_balancing_weight != nullptr) {
167 weight = google_protobuf_UInt32Value_value(load_balancing_weight);
168 if (weight == 0) {
169 errors->AddError("must be greater than 0");
170 }
171 }
172 }
173 // endpoint
174 grpc_resolved_address grpc_address;
175 {
176 ValidationErrors::ScopedField field(errors, ".endpoint");
177 const envoy_config_endpoint_v3_Endpoint* endpoint =
178 envoy_config_endpoint_v3_LbEndpoint_endpoint(lb_endpoint);
179 if (endpoint == nullptr) {
180 errors->AddError("field not present");
181 return absl::nullopt;
182 }
183 ValidationErrors::ScopedField field2(errors, ".address");
184 const envoy_config_core_v3_Address* address =
185 envoy_config_endpoint_v3_Endpoint_address(endpoint);
186 if (address == nullptr) {
187 errors->AddError("field not present");
188 return absl::nullopt;
189 }
190 ValidationErrors::ScopedField field3(errors, ".socket_address");
191 const envoy_config_core_v3_SocketAddress* socket_address =
192 envoy_config_core_v3_Address_socket_address(address);
193 if (socket_address == nullptr) {
194 errors->AddError("field not present");
195 return absl::nullopt;
196 }
197 std::string address_str = UpbStringToStdString(
198 envoy_config_core_v3_SocketAddress_address(socket_address));
199 uint32_t port;
200 {
201 ValidationErrors::ScopedField field(errors, ".port_value");
202 port = envoy_config_core_v3_SocketAddress_port_value(socket_address);
203 if (GPR_UNLIKELY(port >> 16) != 0) {
204 errors->AddError("invalid port");
205 return absl::nullopt;
206 }
207 }
208 auto addr = StringToSockaddr(address_str, port);
209 if (!addr.ok()) {
210 errors->AddError(addr.status().message());
211 } else {
212 grpc_address = *addr;
213 }
214 }
215 // Convert to ServerAddress.
216 std::map<const char*, std::unique_ptr<ServerAddress::AttributeInterface>>
217 attributes;
218 attributes[ServerAddressWeightAttribute::kServerAddressWeightAttributeKey] =
219 std::make_unique<ServerAddressWeightAttribute>(weight);
220 return ServerAddress(grpc_address, ChannelArgs(), std::move(attributes));
221 }
222
223 struct ParsedLocality {
224 size_t priority;
225 XdsEndpointResource::Priority::Locality locality;
226 };
227
228 struct ResolvedAddressLessThan {
229 bool operator()(const grpc_resolved_address& a1,
230 const grpc_resolved_address& a2) const {
231 if (a1.len != a2.len) return a1.len < a2.len;
232 return memcmp(a1.addr, a2.addr, a1.len) < 0;
233 }
234 };
235 using ResolvedAddressSet =
236 std::set<grpc_resolved_address, ResolvedAddressLessThan>;
237
238 absl::optional<ParsedLocality> LocalityParse(
239 const envoy_config_endpoint_v3_LocalityLbEndpoints* locality_lb_endpoints,
240 ResolvedAddressSet* address_set, ValidationErrors* errors) {
241 const size_t original_error_size = errors->size();
242 ParsedLocality parsed_locality;
243 // load_balancing_weight
244 // If LB weight is not specified or 0, it means this locality is assigned
245 // no load.
246 const google_protobuf_UInt32Value* lb_weight =
247 envoy_config_endpoint_v3_LocalityLbEndpoints_load_balancing_weight(
248 locality_lb_endpoints);
249 parsed_locality.locality.lb_weight =
250 lb_weight != nullptr ? google_protobuf_UInt32Value_value(lb_weight) : 0;
251 if (parsed_locality.locality.lb_weight == 0) return absl::nullopt;
252 // locality
253 const envoy_config_core_v3_Locality* locality =
254 envoy_config_endpoint_v3_LocalityLbEndpoints_locality(
255 locality_lb_endpoints);
256 if (locality == nullptr) {
257 ValidationErrors::ScopedField field(errors, ".locality");
258 errors->AddError("field not present");
259 return absl::nullopt;
260 }
261 // region
262 std::string region =
263 UpbStringToStdString(envoy_config_core_v3_Locality_region(locality));
264 // zone
265 std::string zone =
266 UpbStringToStdString(envoy_config_core_v3_Locality_zone(locality));
267 // sub_zone
268 std::string sub_zone =
269 UpbStringToStdString(envoy_config_core_v3_Locality_sub_zone(locality));
270 parsed_locality.locality.name = MakeRefCounted<XdsLocalityName>(
271 std::move(region), std::move(zone), std::move(sub_zone));
272 // lb_endpoints
273 size_t size;
274 const envoy_config_endpoint_v3_LbEndpoint* const* lb_endpoints =
275 envoy_config_endpoint_v3_LocalityLbEndpoints_lb_endpoints(
276 locality_lb_endpoints, &size);
277 for (size_t i = 0; i < size; ++i) {
278 ValidationErrors::ScopedField field(errors,
279 absl::StrCat(".lb_endpoints[", i, "]"));
280 auto address = ServerAddressParse(lb_endpoints[i], errors);
281 if (address.has_value()) {
282 bool inserted = address_set->insert(address->address()).second;
283 if (!inserted) {
284 errors->AddError(absl::StrCat(
285 "duplicate endpoint address \"",
286 grpc_sockaddr_to_uri(&address->address()).value_or("<unknown>"),
287 "\""));
288 }
289 parsed_locality.locality.endpoints.push_back(std::move(*address));
290 }
291 }
292 // priority
293 parsed_locality.priority =
294 envoy_config_endpoint_v3_LocalityLbEndpoints_priority(
295 locality_lb_endpoints);
296 // Return result.
297 if (original_error_size != errors->size()) return absl::nullopt;
298 return parsed_locality;
299 }
300
301 void DropParseAndAppend(
302 const envoy_config_endpoint_v3_ClusterLoadAssignment_Policy_DropOverload*
303 drop_overload,
304 XdsEndpointResource::DropConfig* drop_config, ValidationErrors* errors) {
305 // category
306 std::string category = UpbStringToStdString(
307 envoy_config_endpoint_v3_ClusterLoadAssignment_Policy_DropOverload_category(
308 drop_overload));
309 if (category.empty()) {
310 ValidationErrors::ScopedField field(errors, ".category");
311 errors->AddError("empty drop category name");
312 }
313 // drop_percentage
314 uint32_t numerator;
315 {
316 ValidationErrors::ScopedField field(errors, ".drop_percentage");
317 const envoy_type_v3_FractionalPercent* drop_percentage =
318 envoy_config_endpoint_v3_ClusterLoadAssignment_Policy_DropOverload_drop_percentage(
319 drop_overload);
320 if (drop_percentage == nullptr) {
321 errors->AddError("field not present");
322 return;
323 }
324 numerator = envoy_type_v3_FractionalPercent_numerator(drop_percentage);
325 {
326 ValidationErrors::ScopedField field(errors, ".denominator");
327 const int denominator =
328 envoy_type_v3_FractionalPercent_denominator(drop_percentage);
329 // Normalize to million.
330 switch (denominator) {
331 case envoy_type_v3_FractionalPercent_HUNDRED:
332 numerator *= 10000;
333 break;
334 case envoy_type_v3_FractionalPercent_TEN_THOUSAND:
335 numerator *= 100;
336 break;
337 case envoy_type_v3_FractionalPercent_MILLION:
338 break;
339 default:
340 errors->AddError("unknown denominator type");
341 }
342 }
343 // Cap numerator to 1000000.
344 numerator = std::min(numerator, 1000000u);
345 }
346 // Add category.
347 drop_config->AddCategory(std::move(category), numerator);
348 }
349
350 absl::StatusOr<XdsEndpointResource> EdsResourceParse(
351 const XdsResourceType::DecodeContext& /*context*/,
352 const envoy_config_endpoint_v3_ClusterLoadAssignment*
353 cluster_load_assignment) {
354 ValidationErrors errors;
355 XdsEndpointResource eds_resource;
356 // endpoints
357 {
358 ValidationErrors::ScopedField field(&errors, "endpoints");
359 ResolvedAddressSet address_set;
360 size_t locality_size;
361 const envoy_config_endpoint_v3_LocalityLbEndpoints* const* endpoints =
362 envoy_config_endpoint_v3_ClusterLoadAssignment_endpoints(
363 cluster_load_assignment, &locality_size);
364 for (size_t i = 0; i < locality_size; ++i) {
365 ValidationErrors::ScopedField field(&errors, absl::StrCat("[", i, "]"));
366 auto parsed_locality = LocalityParse(endpoints[i], &address_set, &errors);
367 if (parsed_locality.has_value()) {
368 GPR_ASSERT(parsed_locality->locality.lb_weight != 0);
369 // Make sure prorities is big enough. Note that they might not
370 // arrive in priority order.
371 if (eds_resource.priorities.size() < parsed_locality->priority + 1) {
372 eds_resource.priorities.resize(parsed_locality->priority + 1);
373 }
374 auto& locality_map =
375 eds_resource.priorities[parsed_locality->priority].localities;
376 auto it = locality_map.find(parsed_locality->locality.name.get());
377 if (it != locality_map.end()) {
378 errors.AddError(absl::StrCat(
379 "duplicate locality ",
380 parsed_locality->locality.name->AsHumanReadableString(),
381 " found in priority ", parsed_locality->priority));
382 } else {
383 locality_map.emplace(parsed_locality->locality.name.get(),
384 std::move(parsed_locality->locality));
385 }
386 }
387 }
388 for (size_t i = 0; i < eds_resource.priorities.size(); ++i) {
389 const auto& priority = eds_resource.priorities[i];
390 if (priority.localities.empty()) {
391 errors.AddError(absl::StrCat("priority ", i, " empty"));
392 } else {
393 // Check that the sum of the locality weights in this priority
394 // does not exceed the max value for a uint32.
395 uint64_t total_weight = 0;
396 for (const auto& p : priority.localities) {
397 total_weight += p.second.lb_weight;
398 if (total_weight > std::numeric_limits<uint32_t>::max()) {
399 errors.AddError(
400 absl::StrCat("sum of locality weights for priority ", i,
401 " exceeds uint32 max"));
402 break;
403 }
404 }
405 }
406 }
407 }
408 // policy
409 eds_resource.drop_config = MakeRefCounted<XdsEndpointResource::DropConfig>();
410 const auto* policy = envoy_config_endpoint_v3_ClusterLoadAssignment_policy(
411 cluster_load_assignment);
412 if (policy != nullptr) {
413 ValidationErrors::ScopedField field(&errors, "policy");
414 size_t drop_size;
415 const auto* const* drop_overload =
416 envoy_config_endpoint_v3_ClusterLoadAssignment_Policy_drop_overloads(
417 policy, &drop_size);
418 for (size_t i = 0; i < drop_size; ++i) {
419 ValidationErrors::ScopedField field(
420 &errors, absl::StrCat(".drop_overloads[", i, "]"));
421 DropParseAndAppend(drop_overload[i], eds_resource.drop_config.get(),
422 &errors);
423 }
424 }
425 // Return result.
426 if (!errors.ok()) return errors.status("errors parsing EDS resource");
427 return eds_resource;
428 }
429
430 } // namespace
431
432 XdsResourceType::DecodeResult XdsEndpointResourceType::Decode(
433 const XdsResourceType::DecodeContext& context,
434 absl::string_view serialized_resource) const {
435 DecodeResult result;
436 // Parse serialized proto.
437 auto* resource = envoy_config_endpoint_v3_ClusterLoadAssignment_parse(
438 serialized_resource.data(), serialized_resource.size(), context.arena);
439 if (resource == nullptr) {
440 result.resource = absl::InvalidArgumentError(
441 "Can't parse ClusterLoadAssignment resource.");
442 return result;
443 }
444 MaybeLogClusterLoadAssignment(context, resource);
445 // Validate resource.
446 result.name = UpbStringToStdString(
447 envoy_config_endpoint_v3_ClusterLoadAssignment_cluster_name(resource));
448 auto eds_resource = EdsResourceParse(context, resource);
449 if (!eds_resource.ok()) {
450 if (GRPC_TRACE_FLAG_ENABLED(*context.tracer)) {
451 gpr_log(GPR_ERROR, "[xds_client %p] invalid ClusterLoadAssignment %s: %s",
452 context.client, result.name->c_str(),
453 eds_resource.status().ToString().c_str());
454 }
455 result.resource = eds_resource.status();
456 } else {
457 if (GRPC_TRACE_FLAG_ENABLED(*context.tracer)) {
458 gpr_log(GPR_INFO, "[xds_client %p] parsed ClusterLoadAssignment %s: %s",
459 context.client, result.name->c_str(),
460 eds_resource->ToString().c_str());
461 }
462 result.resource =
463 std::make_unique<XdsEndpointResource>(std::move(*eds_resource));
464 }
465 return result;
466 }
467
468 } // namespace grpc_core