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_route_config.h"
20 
21 #include <stddef.h>
22 #include <stdint.h>
23 
24 #include <initializer_list>
25 #include <limits>
26 #include <map>
27 #include <memory>
28 #include <set>
29 #include <string>
30 #include <utility>
31 #include <vector>
32 
33 #include "absl/status/status.h"
34 #include "absl/status/statusor.h"
35 #include "absl/strings/str_cat.h"
36 #include "absl/strings/str_format.h"
37 #include "absl/strings/str_join.h"
38 #include "absl/strings/str_split.h"
39 #include "absl/strings/string_view.h"
40 #include "absl/types/optional.h"
41 #include "absl/types/variant.h"
42 #include "envoy/config/core/v3/base.upb.h"
43 #include "envoy/config/core/v3/extension.upb.h"
44 #include "envoy/config/route/v3/route.upb.h"
45 #include "envoy/config/route/v3/route.upbdefs.h"
46 #include "envoy/config/route/v3/route_components.upb.h"
47 #include "envoy/type/matcher/v3/regex.upb.h"
48 #include "envoy/type/matcher/v3/string.upb.h"
49 #include "envoy/type/v3/percent.upb.h"
50 #include "envoy/type/v3/range.upb.h"
51 #include "google/protobuf/any.upb.h"
52 #include "google/protobuf/duration.upb.h"
53 #include "google/protobuf/wrappers.upb.h"
54 #include "re2/re2.h"
55 #include "upb/base/string_view.h"
56 #include "upb/collections/map.h"
57 #include "upb/text/encode.h"
58 
59 #include <grpc/status.h>
60 #include <grpc/support/log.h>
61 
62 #include "src/core/ext/xds/upb_utils.h"
63 #include "src/core/ext/xds/xds_cluster_specifier_plugin.h"
64 #include "src/core/ext/xds/xds_common_types.h"
65 #include "src/core/ext/xds/xds_http_filters.h"
66 #include "src/core/ext/xds/xds_resource_type.h"
67 #include "src/core/ext/xds/xds_routing.h"
68 #include "src/core/lib/channel/status_util.h"
69 #include "src/core/lib/config/core_configuration.h"
70 #include "src/core/lib/debug/trace.h"
71 #include "src/core/lib/gpr/string.h"
72 #include "src/core/lib/gprpp/env.h"
73 #include "src/core/lib/gprpp/match.h"
74 #include "src/core/lib/gprpp/ref_counted_ptr.h"
75 #include "src/core/lib/gprpp/time.h"
76 #include "src/core/lib/json/json.h"
77 #include "src/core/lib/json/json_writer.h"
78 #include "src/core/lib/load_balancing/lb_policy_registry.h"
79 #include "src/core/lib/matchers/matchers.h"
80 
81 namespace grpc_core {
82 
83 // TODO(apolcyn): remove this flag by the 1.58 release
XdsRlsEnabled()84 bool XdsRlsEnabled() {
85   auto value = GetEnv("GRPC_EXPERIMENTAL_XDS_RLS_LB");
86   if (!value.has_value()) return true;
87   bool parsed_value;
88   bool parse_succeeded = gpr_parse_bool_value(value->c_str(), &parsed_value);
89   return parse_succeeded && parsed_value;
90 }
91 
92 //
93 // XdsRouteConfigResource::RetryPolicy
94 //
95 
ToString() const96 std::string XdsRouteConfigResource::RetryPolicy::RetryBackOff::ToString()
97     const {
98   std::vector<std::string> contents;
99   contents.push_back(
100       absl::StrCat("RetryBackOff Base: ", base_interval.ToString()));
101   contents.push_back(
102       absl::StrCat("RetryBackOff max: ", max_interval.ToString()));
103   return absl::StrJoin(contents, ",");
104 }
105 
ToString() const106 std::string XdsRouteConfigResource::RetryPolicy::ToString() const {
107   std::vector<std::string> contents;
108   contents.push_back(absl::StrFormat("num_retries=%d", num_retries));
109   contents.push_back(retry_back_off.ToString());
110   return absl::StrCat("{", absl::StrJoin(contents, ","), "}");
111 }
112 
113 //
114 // XdsRouteConfigResource::Route::Matchers
115 //
116 
ToString() const117 std::string XdsRouteConfigResource::Route::Matchers::ToString() const {
118   std::vector<std::string> contents;
119   contents.push_back(
120       absl::StrFormat("PathMatcher{%s}", path_matcher.ToString()));
121   for (const HeaderMatcher& header_matcher : header_matchers) {
122     contents.push_back(header_matcher.ToString());
123   }
124   if (fraction_per_million.has_value()) {
125     contents.push_back(absl::StrFormat("Fraction Per Million %d",
126                                        fraction_per_million.value()));
127   }
128   return absl::StrJoin(contents, "\n");
129 }
130 
131 //
132 // XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header
133 //
134 
Header(const Header & other)135 XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header::Header(
136     const Header& other)
137     : header_name(other.header_name),
138       regex_substitution(other.regex_substitution) {
139   if (other.regex != nullptr) {
140     regex =
141         std::make_unique<RE2>(other.regex->pattern(), other.regex->options());
142   }
143 }
144 
145 XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header&
operator =(const Header & other)146 XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header::operator=(
147     const Header& other) {
148   header_name = other.header_name;
149   if (other.regex != nullptr) {
150     regex =
151         std::make_unique<RE2>(other.regex->pattern(), other.regex->options());
152   }
153   regex_substitution = other.regex_substitution;
154   return *this;
155 }
156 
Header(Header && other)157 XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header::Header(
158     Header&& other) noexcept
159     : header_name(std::move(other.header_name)),
160       regex(std::move(other.regex)),
161       regex_substitution(std::move(other.regex_substitution)) {}
162 
163 XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header&
operator =(Header && other)164 XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header::operator=(
165     Header&& other) noexcept {
166   header_name = std::move(other.header_name);
167   regex = std::move(other.regex);
168   regex_substitution = std::move(other.regex_substitution);
169   return *this;
170 }
171 
operator ==(const Header & other) const172 bool XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header::operator==(
173     const Header& other) const {
174   if (header_name != other.header_name) return false;
175   if (regex == nullptr) {
176     if (other.regex != nullptr) return false;
177   } else {
178     if (other.regex == nullptr) return false;
179     if (regex->pattern() != other.regex->pattern()) return false;
180   }
181   return regex_substitution == other.regex_substitution;
182 }
183 
184 std::string
ToString() const185 XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header::ToString()
186     const {
187   return absl::StrCat("Header ", header_name, "/",
188                       (regex == nullptr) ? "" : regex->pattern(), "/",
189                       regex_substitution);
190 }
191 
192 //
193 // XdsRouteConfigResource::Route::RouteAction::HashPolicy
194 //
195 
ToString() const196 std::string XdsRouteConfigResource::Route::RouteAction::HashPolicy::ToString()
197     const {
198   std::string type = Match(
199       policy, [](const Header& header) { return header.ToString(); },
200       [](const ChannelId&) -> std::string { return "ChannelId"; });
201   return absl::StrCat("{", type, ", terminal=", terminal ? "true" : "false",
202                       "}");
203 }
204 
205 //
206 // XdsRouteConfigResource::Route::RouteAction::ClusterWeight
207 //
208 
209 std::string
ToString() const210 XdsRouteConfigResource::Route::RouteAction::ClusterWeight::ToString() const {
211   std::vector<std::string> contents;
212   contents.push_back(absl::StrCat("cluster=", name));
213   contents.push_back(absl::StrCat("weight=", weight));
214   if (!typed_per_filter_config.empty()) {
215     std::vector<std::string> parts;
216     for (const auto& p : typed_per_filter_config) {
217       const std::string& key = p.first;
218       const auto& config = p.second;
219       parts.push_back(absl::StrCat(key, "=", config.ToString()));
220     }
221     contents.push_back(absl::StrCat("typed_per_filter_config={",
222                                     absl::StrJoin(parts, ", "), "}"));
223   }
224   return absl::StrCat("{", absl::StrJoin(contents, ", "), "}");
225 }
226 
227 //
228 // XdsRouteConfigResource::Route::RouteAction
229 //
230 
ToString() const231 std::string XdsRouteConfigResource::Route::RouteAction::ToString() const {
232   std::vector<std::string> contents;
233   contents.reserve(hash_policies.size());
234   for (const HashPolicy& hash_policy : hash_policies) {
235     contents.push_back(absl::StrCat("hash_policy=", hash_policy.ToString()));
236   }
237   if (retry_policy.has_value()) {
238     contents.push_back(absl::StrCat("retry_policy=", retry_policy->ToString()));
239   }
240   Match(
241       action,
242       [&contents](const ClusterName& cluster_name) {
243         contents.push_back(
244             absl::StrFormat("Cluster name: %s", cluster_name.cluster_name));
245       },
246       [&contents](const std::vector<ClusterWeight>& weighted_clusters) {
247         for (const ClusterWeight& cluster_weight : weighted_clusters) {
248           contents.push_back(cluster_weight.ToString());
249         }
250       },
251       [&contents](
252           const ClusterSpecifierPluginName& cluster_specifier_plugin_name) {
253         contents.push_back(absl::StrFormat(
254             "Cluster specifier plugin name: %s",
255             cluster_specifier_plugin_name.cluster_specifier_plugin_name));
256       });
257   if (max_stream_duration.has_value()) {
258     contents.push_back(max_stream_duration->ToString());
259   }
260   return absl::StrCat("{", absl::StrJoin(contents, ", "), "}");
261 }
262 
263 //
264 // XdsRouteConfigResource::Route
265 //
266 
ToString() const267 std::string XdsRouteConfigResource::Route::ToString() const {
268   std::vector<std::string> contents;
269   contents.push_back(matchers.ToString());
270   auto* route_action =
271       absl::get_if<XdsRouteConfigResource::Route::RouteAction>(&action);
272   if (route_action != nullptr) {
273     contents.push_back(absl::StrCat("route=", route_action->ToString()));
274   } else if (absl::holds_alternative<
275                  XdsRouteConfigResource::Route::NonForwardingAction>(action)) {
276     contents.push_back("non_forwarding_action={}");
277   } else {
278     contents.push_back("unknown_action={}");
279   }
280   if (!typed_per_filter_config.empty()) {
281     contents.push_back("typed_per_filter_config={");
282     for (const auto& p : typed_per_filter_config) {
283       const std::string& name = p.first;
284       const auto& config = p.second;
285       contents.push_back(absl::StrCat("  ", name, "=", config.ToString()));
286     }
287     contents.push_back("}");
288   }
289   return absl::StrJoin(contents, "\n");
290 }
291 
292 //
293 // XdsRouteConfigResource
294 //
295 
ToString() const296 std::string XdsRouteConfigResource::ToString() const {
297   std::vector<std::string> parts;
298   for (const VirtualHost& vhost : virtual_hosts) {
299     parts.push_back(
300         absl::StrCat("vhost={\n"
301                      "  domains=[",
302                      absl::StrJoin(vhost.domains, ", "),
303                      "]\n"
304                      "  routes=[\n"));
305     for (const XdsRouteConfigResource::Route& route : vhost.routes) {
306       parts.push_back("    {\n");
307       parts.push_back(route.ToString());
308       parts.push_back("\n    }\n");
309     }
310     parts.push_back("  ]\n");
311     parts.push_back("  typed_per_filter_config={\n");
312     for (const auto& p : vhost.typed_per_filter_config) {
313       const std::string& name = p.first;
314       const auto& config = p.second;
315       parts.push_back(absl::StrCat("    ", name, "=", config.ToString(), "\n"));
316     }
317     parts.push_back("  }\n");
318     parts.push_back("]\n");
319   }
320   parts.push_back("cluster_specifier_plugins={\n");
321   for (const auto& it : cluster_specifier_plugin_map) {
322     parts.push_back(absl::StrFormat("%s={%s}\n", it.first, it.second));
323   }
324   parts.push_back("}");
325   return absl::StrJoin(parts, "");
326 }
327 
328 namespace {
329 
ClusterSpecifierPluginParse(const XdsResourceType::DecodeContext & context,const envoy_config_route_v3_RouteConfiguration * route_config,ValidationErrors * errors)330 XdsRouteConfigResource::ClusterSpecifierPluginMap ClusterSpecifierPluginParse(
331     const XdsResourceType::DecodeContext& context,
332     const envoy_config_route_v3_RouteConfiguration* route_config,
333     ValidationErrors* errors) {
334   XdsRouteConfigResource::ClusterSpecifierPluginMap
335       cluster_specifier_plugin_map;
336   const auto& cluster_specifier_plugin_registry =
337       static_cast<const GrpcXdsBootstrap&>(context.client->bootstrap())
338           .cluster_specifier_plugin_registry();
339   size_t num_cluster_specifier_plugins;
340   const envoy_config_route_v3_ClusterSpecifierPlugin* const*
341       cluster_specifier_plugin =
342           envoy_config_route_v3_RouteConfiguration_cluster_specifier_plugins(
343               route_config, &num_cluster_specifier_plugins);
344   for (size_t i = 0; i < num_cluster_specifier_plugins; ++i) {
345     bool is_optional = envoy_config_route_v3_ClusterSpecifierPlugin_is_optional(
346         cluster_specifier_plugin[i]);
347     ValidationErrors::ScopedField field(
348         errors, absl::StrCat(".cluster_specifier_plugins[", i, "].extension"));
349     const envoy_config_core_v3_TypedExtensionConfig* typed_extension_config =
350         envoy_config_route_v3_ClusterSpecifierPlugin_extension(
351             cluster_specifier_plugin[i]);
352     std::string name = UpbStringToStdString(
353         envoy_config_core_v3_TypedExtensionConfig_name(typed_extension_config));
354     if (cluster_specifier_plugin_map.find(name) !=
355         cluster_specifier_plugin_map.end()) {
356       ValidationErrors::ScopedField field(errors, ".name");
357       errors->AddError(absl::StrCat("duplicate name \"", name, "\""));
358     } else {
359       // Add a sentinel entry in case we encounter an error later, just so we
360       // don't generate duplicate errors for each route that uses this plugin.
361       cluster_specifier_plugin_map[name] = "<sentinel>";
362     }
363     ValidationErrors::ScopedField field2(errors, ".typed_config");
364     const google_protobuf_Any* any =
365         envoy_config_core_v3_TypedExtensionConfig_typed_config(
366             typed_extension_config);
367     auto extension = ExtractXdsExtension(context, any, errors);
368     if (!extension.has_value()) continue;
369     const XdsClusterSpecifierPluginImpl* cluster_specifier_plugin_impl =
370         cluster_specifier_plugin_registry.GetPluginForType(extension->type);
371     if (cluster_specifier_plugin_impl == nullptr) {
372       if (is_optional) {
373         // Empty string indicates an optional plugin.
374         // This is used later when validating routes, and since we will skip
375         // any routes that refer to this plugin, we won't wind up including
376         // this plugin in the resource that we return to the watcher.
377         cluster_specifier_plugin_map[std::move(name)] = "";
378       } else {
379         // Not optional, report error.
380         errors->AddError("unsupported ClusterSpecifierPlugin type");
381       }
382       continue;
383     }
384     const size_t original_error_size = errors->size();
385     Json lb_policy_config =
386         cluster_specifier_plugin_impl->GenerateLoadBalancingPolicyConfig(
387             std::move(*extension), context.arena, context.symtab, errors);
388     if (errors->size() != original_error_size) continue;
389     auto config =
390         CoreConfiguration::Get().lb_policy_registry().ParseLoadBalancingConfig(
391             lb_policy_config);
392     if (!config.ok()) {
393       errors->AddError(absl::StrCat(
394           "ClusterSpecifierPlugin returned invalid LB policy config: ",
395           config.status().message()));
396     } else {
397       cluster_specifier_plugin_map[std::move(name)] =
398           JsonDump(lb_policy_config);
399     }
400   }
401   return cluster_specifier_plugin_map;
402 }
403 
RoutePathMatchParse(const envoy_config_route_v3_RouteMatch * match,ValidationErrors * errors)404 absl::optional<StringMatcher> RoutePathMatchParse(
405     const envoy_config_route_v3_RouteMatch* match, ValidationErrors* errors) {
406   bool case_sensitive = true;
407   auto* case_sensitive_ptr =
408       envoy_config_route_v3_RouteMatch_case_sensitive(match);
409   if (case_sensitive_ptr != nullptr) {
410     case_sensitive = google_protobuf_BoolValue_value(case_sensitive_ptr);
411   }
412   StringMatcher::Type type;
413   std::string match_string;
414   if (envoy_config_route_v3_RouteMatch_has_prefix(match)) {
415     absl::string_view prefix =
416         UpbStringToAbsl(envoy_config_route_v3_RouteMatch_prefix(match));
417     // For any prefix that cannot match a path of the form "/service/method",
418     // ignore the route.
419     if (!prefix.empty()) {
420       // Does not start with a slash.
421       if (prefix[0] != '/') return absl::nullopt;
422       std::vector<absl::string_view> prefix_elements =
423           absl::StrSplit(prefix.substr(1), absl::MaxSplits('/', 2));
424       // More than 2 slashes.
425       if (prefix_elements.size() > 2) return absl::nullopt;
426       // Two consecutive slashes.
427       if (prefix_elements.size() == 2 && prefix_elements[0].empty()) {
428         return absl::nullopt;
429       }
430     }
431     type = StringMatcher::Type::kPrefix;
432     match_string = std::string(prefix);
433   } else if (envoy_config_route_v3_RouteMatch_has_path(match)) {
434     absl::string_view path =
435         UpbStringToAbsl(envoy_config_route_v3_RouteMatch_path(match));
436     // For any path not of the form "/service/method", ignore the route.
437     // Empty path.
438     if (path.empty()) return absl::nullopt;
439     // Does not start with a slash.
440     if (path[0] != '/') return absl::nullopt;
441     std::vector<absl::string_view> path_elements =
442         absl::StrSplit(path.substr(1), absl::MaxSplits('/', 2));
443     // Number of slashes does not equal 2.
444     if (path_elements.size() != 2) return absl::nullopt;
445     // Empty service name.
446     if (path_elements[0].empty()) return absl::nullopt;
447     // Empty method name.
448     if (path_elements[1].empty()) return absl::nullopt;
449     type = StringMatcher::Type::kExact;
450     match_string = std::string(path);
451   } else if (envoy_config_route_v3_RouteMatch_has_safe_regex(match)) {
452     const envoy_type_matcher_v3_RegexMatcher* regex_matcher =
453         envoy_config_route_v3_RouteMatch_safe_regex(match);
454     GPR_ASSERT(regex_matcher != nullptr);
455     type = StringMatcher::Type::kSafeRegex;
456     match_string = UpbStringToStdString(
457         envoy_type_matcher_v3_RegexMatcher_regex(regex_matcher));
458   } else {
459     errors->AddError("invalid path specifier");
460     return absl::nullopt;
461   }
462   absl::StatusOr<StringMatcher> string_matcher =
463       StringMatcher::Create(type, match_string, case_sensitive);
464   if (!string_matcher.ok()) {
465     errors->AddError(absl::StrCat("error creating path matcher: ",
466                                   string_matcher.status().message()));
467     return absl::nullopt;
468   }
469   return std::move(*string_matcher);
470 }
471 
RouteHeaderMatchersParse(const envoy_config_route_v3_RouteMatch * match,XdsRouteConfigResource::Route * route,ValidationErrors * errors)472 void RouteHeaderMatchersParse(const envoy_config_route_v3_RouteMatch* match,
473                               XdsRouteConfigResource::Route* route,
474                               ValidationErrors* errors) {
475   size_t size;
476   const envoy_config_route_v3_HeaderMatcher* const* headers =
477       envoy_config_route_v3_RouteMatch_headers(match, &size);
478   for (size_t i = 0; i < size; ++i) {
479     ValidationErrors::ScopedField field(errors,
480                                         absl::StrCat(".headers[", i, "]"));
481     const envoy_config_route_v3_HeaderMatcher* header = headers[i];
482     GPR_ASSERT(header != nullptr);
483     const std::string name =
484         UpbStringToStdString(envoy_config_route_v3_HeaderMatcher_name(header));
485     HeaderMatcher::Type type;
486     std::string match_string;
487     int64_t range_start = 0;
488     int64_t range_end = 0;
489     bool present_match = false;
490     bool case_sensitive = true;
491     if (envoy_config_route_v3_HeaderMatcher_has_exact_match(header)) {
492       type = HeaderMatcher::Type::kExact;
493       match_string = UpbStringToStdString(
494           envoy_config_route_v3_HeaderMatcher_exact_match(header));
495     } else if (envoy_config_route_v3_HeaderMatcher_has_prefix_match(header)) {
496       type = HeaderMatcher::Type::kPrefix;
497       match_string = UpbStringToStdString(
498           envoy_config_route_v3_HeaderMatcher_prefix_match(header));
499     } else if (envoy_config_route_v3_HeaderMatcher_has_suffix_match(header)) {
500       type = HeaderMatcher::Type::kSuffix;
501       match_string = UpbStringToStdString(
502           envoy_config_route_v3_HeaderMatcher_suffix_match(header));
503     } else if (envoy_config_route_v3_HeaderMatcher_has_contains_match(header)) {
504       type = HeaderMatcher::Type::kContains;
505       match_string = UpbStringToStdString(
506           envoy_config_route_v3_HeaderMatcher_contains_match(header));
507     } else if (envoy_config_route_v3_HeaderMatcher_has_safe_regex_match(
508                    header)) {
509       const envoy_type_matcher_v3_RegexMatcher* regex_matcher =
510           envoy_config_route_v3_HeaderMatcher_safe_regex_match(header);
511       GPR_ASSERT(regex_matcher != nullptr);
512       type = HeaderMatcher::Type::kSafeRegex;
513       match_string = UpbStringToStdString(
514           envoy_type_matcher_v3_RegexMatcher_regex(regex_matcher));
515     } else if (envoy_config_route_v3_HeaderMatcher_has_range_match(header)) {
516       type = HeaderMatcher::Type::kRange;
517       const envoy_type_v3_Int64Range* range_matcher =
518           envoy_config_route_v3_HeaderMatcher_range_match(header);
519       GPR_ASSERT(range_matcher != nullptr);
520       range_start = envoy_type_v3_Int64Range_start(range_matcher);
521       range_end = envoy_type_v3_Int64Range_end(range_matcher);
522     } else if (envoy_config_route_v3_HeaderMatcher_has_present_match(header)) {
523       type = HeaderMatcher::Type::kPresent;
524       present_match = envoy_config_route_v3_HeaderMatcher_present_match(header);
525     } else if (envoy_config_route_v3_HeaderMatcher_has_string_match(header)) {
526       ValidationErrors::ScopedField field(errors, ".string_match");
527       const auto* matcher =
528           envoy_config_route_v3_HeaderMatcher_string_match(header);
529       GPR_ASSERT(matcher != nullptr);
530       if (envoy_type_matcher_v3_StringMatcher_has_exact(matcher)) {
531         type = HeaderMatcher::Type::kExact;
532         match_string = UpbStringToStdString(
533             envoy_type_matcher_v3_StringMatcher_exact(matcher));
534       } else if (envoy_type_matcher_v3_StringMatcher_has_prefix(matcher)) {
535         type = HeaderMatcher::Type::kPrefix;
536         match_string = UpbStringToStdString(
537             envoy_type_matcher_v3_StringMatcher_prefix(matcher));
538       } else if (envoy_type_matcher_v3_StringMatcher_has_suffix(matcher)) {
539         type = HeaderMatcher::Type::kSuffix;
540         match_string = UpbStringToStdString(
541             envoy_type_matcher_v3_StringMatcher_suffix(matcher));
542       } else if (envoy_type_matcher_v3_StringMatcher_has_contains(matcher)) {
543         type = HeaderMatcher::Type::kContains;
544         match_string = UpbStringToStdString(
545             envoy_type_matcher_v3_StringMatcher_contains(matcher));
546       } else if (envoy_type_matcher_v3_StringMatcher_has_safe_regex(matcher)) {
547         type = HeaderMatcher::Type::kSafeRegex;
548         const auto* regex_matcher =
549             envoy_type_matcher_v3_StringMatcher_safe_regex(matcher);
550         GPR_ASSERT(regex_matcher != nullptr);
551         match_string = UpbStringToStdString(
552             envoy_type_matcher_v3_RegexMatcher_regex(regex_matcher));
553       } else {
554         errors->AddError("invalid string matcher");
555         continue;
556       }
557       case_sensitive =
558           !envoy_type_matcher_v3_StringMatcher_ignore_case(matcher);
559     } else {
560       errors->AddError("invalid header matcher");
561       continue;
562     }
563     bool invert_match =
564         envoy_config_route_v3_HeaderMatcher_invert_match(header);
565     absl::StatusOr<HeaderMatcher> header_matcher =
566         HeaderMatcher::Create(name, type, match_string, range_start, range_end,
567                               present_match, invert_match, case_sensitive);
568     if (!header_matcher.ok()) {
569       errors->AddError(absl::StrCat("cannot create header matcher: ",
570                                     header_matcher.status().message()));
571     } else {
572       route->matchers.header_matchers.emplace_back(std::move(*header_matcher));
573     }
574   }
575 }
576 
RouteRuntimeFractionParse(const envoy_config_route_v3_RouteMatch * match,XdsRouteConfigResource::Route * route,ValidationErrors * errors)577 void RouteRuntimeFractionParse(const envoy_config_route_v3_RouteMatch* match,
578                                XdsRouteConfigResource::Route* route,
579                                ValidationErrors* errors) {
580   const envoy_config_core_v3_RuntimeFractionalPercent* runtime_fraction =
581       envoy_config_route_v3_RouteMatch_runtime_fraction(match);
582   if (runtime_fraction != nullptr) {
583     const envoy_type_v3_FractionalPercent* fraction =
584         envoy_config_core_v3_RuntimeFractionalPercent_default_value(
585             runtime_fraction);
586     if (fraction != nullptr) {
587       uint32_t numerator = envoy_type_v3_FractionalPercent_numerator(fraction);
588       const uint32_t denominator =
589           envoy_type_v3_FractionalPercent_denominator(fraction);
590       // Normalize to million.
591       switch (denominator) {
592         case envoy_type_v3_FractionalPercent_HUNDRED:
593           numerator *= 10000;
594           break;
595         case envoy_type_v3_FractionalPercent_TEN_THOUSAND:
596           numerator *= 100;
597           break;
598         case envoy_type_v3_FractionalPercent_MILLION:
599           break;
600         default: {
601           ValidationErrors::ScopedField field(
602               errors, ".runtime_fraction.default_value.denominator");
603           errors->AddError("unknown denominator type");
604           return;
605         }
606       }
607       route->matchers.fraction_per_million = numerator;
608     }
609   }
610 }
611 
612 template <typename ParentType, typename EntryType>
ParseTypedPerFilterConfig(const XdsResourceType::DecodeContext & context,const ParentType * parent,const EntryType * (* entry_func)(const ParentType *,size_t *),upb_StringView (* key_func)(const EntryType *),const google_protobuf_Any * (* value_func)(const EntryType *),ValidationErrors * errors)613 XdsRouteConfigResource::TypedPerFilterConfig ParseTypedPerFilterConfig(
614     const XdsResourceType::DecodeContext& context, const ParentType* parent,
615     const EntryType* (*entry_func)(const ParentType*, size_t*),
616     upb_StringView (*key_func)(const EntryType*),
617     const google_protobuf_Any* (*value_func)(const EntryType*),
618     ValidationErrors* errors) {
619   XdsRouteConfigResource::TypedPerFilterConfig typed_per_filter_config;
620   size_t filter_it = kUpb_Map_Begin;
621   while (true) {
622     const auto* filter_entry = entry_func(parent, &filter_it);
623     if (filter_entry == nullptr) break;
624     absl::string_view key = UpbStringToAbsl(key_func(filter_entry));
625     ValidationErrors::ScopedField field(errors, absl::StrCat("[", key, "]"));
626     if (key.empty()) errors->AddError("filter name must be non-empty");
627     const google_protobuf_Any* any = value_func(filter_entry);
628     auto extension = ExtractXdsExtension(context, any, errors);
629     if (!extension.has_value()) continue;
630     auto* extension_to_use = &*extension;
631     absl::optional<XdsExtension> nested_extension;
632     bool is_optional = false;
633     if (extension->type == "envoy.config.route.v3.FilterConfig") {
634       absl::string_view* serialized_config =
635           absl::get_if<absl::string_view>(&extension->value);
636       if (serialized_config == nullptr) {
637         errors->AddError("could not parse FilterConfig");
638         continue;
639       }
640       const auto* filter_config = envoy_config_route_v3_FilterConfig_parse(
641           serialized_config->data(), serialized_config->size(), context.arena);
642       if (filter_config == nullptr) {
643         errors->AddError("could not parse FilterConfig");
644         continue;
645       }
646       is_optional =
647           envoy_config_route_v3_FilterConfig_is_optional(filter_config);
648       any = envoy_config_route_v3_FilterConfig_config(filter_config);
649       extension->validation_fields.emplace_back(errors, ".config");
650       nested_extension = ExtractXdsExtension(context, any, errors);
651       if (!nested_extension.has_value()) continue;
652       extension_to_use = &*nested_extension;
653     }
654     const auto& http_filter_registry =
655         static_cast<const GrpcXdsBootstrap&>(context.client->bootstrap())
656             .http_filter_registry();
657     const XdsHttpFilterImpl* filter_impl =
658         http_filter_registry.GetFilterForType(extension_to_use->type);
659     if (filter_impl == nullptr) {
660       if (!is_optional) errors->AddError("unsupported filter type");
661       continue;
662     }
663     absl::optional<XdsHttpFilterImpl::FilterConfig> filter_config =
664         filter_impl->GenerateFilterConfigOverride(
665             context, std::move(*extension_to_use), errors);
666     if (filter_config.has_value()) {
667       typed_per_filter_config[std::string(key)] = std::move(*filter_config);
668     }
669   }
670   return typed_per_filter_config;
671 }
672 
RetryPolicyParse(const XdsResourceType::DecodeContext & context,const envoy_config_route_v3_RetryPolicy * retry_policy_proto,ValidationErrors * errors)673 XdsRouteConfigResource::RetryPolicy RetryPolicyParse(
674     const XdsResourceType::DecodeContext& context,
675     const envoy_config_route_v3_RetryPolicy* retry_policy_proto,
676     ValidationErrors* errors) {
677   XdsRouteConfigResource::RetryPolicy retry_policy;
678   auto retry_on = UpbStringToStdString(
679       envoy_config_route_v3_RetryPolicy_retry_on(retry_policy_proto));
680   std::vector<absl::string_view> codes = absl::StrSplit(retry_on, ',');
681   for (const auto& code : codes) {
682     if (code == "cancelled") {
683       retry_policy.retry_on.Add(GRPC_STATUS_CANCELLED);
684     } else if (code == "deadline-exceeded") {
685       retry_policy.retry_on.Add(GRPC_STATUS_DEADLINE_EXCEEDED);
686     } else if (code == "internal") {
687       retry_policy.retry_on.Add(GRPC_STATUS_INTERNAL);
688     } else if (code == "resource-exhausted") {
689       retry_policy.retry_on.Add(GRPC_STATUS_RESOURCE_EXHAUSTED);
690     } else if (code == "unavailable") {
691       retry_policy.retry_on.Add(GRPC_STATUS_UNAVAILABLE);
692     } else {
693       if (GRPC_TRACE_FLAG_ENABLED(*context.tracer)) {
694         gpr_log(GPR_INFO, "Unsupported retry_on policy %s.",
695                 std::string(code).c_str());
696       }
697     }
698   }
699   const google_protobuf_UInt32Value* num_retries =
700       envoy_config_route_v3_RetryPolicy_num_retries(retry_policy_proto);
701   if (num_retries != nullptr) {
702     uint32_t num_retries_value = google_protobuf_UInt32Value_value(num_retries);
703     if (num_retries_value == 0) {
704       ValidationErrors::ScopedField field(errors, ".num_retries");
705       errors->AddError("must be greater than 0");
706     } else {
707       retry_policy.num_retries = num_retries_value;
708     }
709   } else {
710     retry_policy.num_retries = 1;
711   }
712   const envoy_config_route_v3_RetryPolicy_RetryBackOff* backoff =
713       envoy_config_route_v3_RetryPolicy_retry_back_off(retry_policy_proto);
714   if (backoff != nullptr) {
715     ValidationErrors::ScopedField field(errors, ".retry_back_off");
716     {
717       ValidationErrors::ScopedField field(errors, ".base_interval");
718       const google_protobuf_Duration* base_interval =
719           envoy_config_route_v3_RetryPolicy_RetryBackOff_base_interval(backoff);
720       if (base_interval == nullptr) {
721         errors->AddError("field not present");
722       } else {
723         retry_policy.retry_back_off.base_interval =
724             ParseDuration(base_interval, errors);
725       }
726     }
727     {
728       ValidationErrors::ScopedField field(errors, ".max_interval");
729       const google_protobuf_Duration* max_interval =
730           envoy_config_route_v3_RetryPolicy_RetryBackOff_max_interval(backoff);
731       Duration max;
732       if (max_interval != nullptr) {
733         max = ParseDuration(max_interval, errors);
734       } else {
735         // if max interval is not set, it is 10x the base.
736         max = 10 * retry_policy.retry_back_off.base_interval;
737       }
738       retry_policy.retry_back_off.max_interval = max;
739     }
740   } else {
741     retry_policy.retry_back_off.base_interval = Duration::Milliseconds(25);
742     retry_policy.retry_back_off.max_interval = Duration::Milliseconds(250);
743   }
744   return retry_policy;
745 }
746 
RouteActionParse(const XdsResourceType::DecodeContext & context,const envoy_config_route_v3_RouteAction * route_action_proto,const std::map<std::string,std::string> & cluster_specifier_plugin_map,ValidationErrors * errors)747 absl::optional<XdsRouteConfigResource::Route::RouteAction> RouteActionParse(
748     const XdsResourceType::DecodeContext& context,
749     const envoy_config_route_v3_RouteAction* route_action_proto,
750     const std::map<std::string /*cluster_specifier_plugin_name*/,
751                    std::string /*LB policy config*/>&
752         cluster_specifier_plugin_map,
753     ValidationErrors* errors) {
754   XdsRouteConfigResource::Route::RouteAction route_action;
755   // grpc_timeout_header_max or max_stream_duration
756   const auto* max_stream_duration =
757       envoy_config_route_v3_RouteAction_max_stream_duration(route_action_proto);
758   if (max_stream_duration != nullptr) {
759     ValidationErrors::ScopedField field(errors, ".max_stream_duration");
760     const google_protobuf_Duration* duration =
761         envoy_config_route_v3_RouteAction_MaxStreamDuration_grpc_timeout_header_max(
762             max_stream_duration);
763     if (duration != nullptr) {
764       ValidationErrors::ScopedField field(errors, ".grpc_timeout_header_max");
765       route_action.max_stream_duration = ParseDuration(duration, errors);
766     } else {
767       duration =
768           envoy_config_route_v3_RouteAction_MaxStreamDuration_max_stream_duration(
769               max_stream_duration);
770       if (duration != nullptr) {
771         ValidationErrors::ScopedField field(errors, ".max_stream_duration");
772         route_action.max_stream_duration = ParseDuration(duration, errors);
773       }
774     }
775   }
776   // hash_policy
777   size_t size = 0;
778   const envoy_config_route_v3_RouteAction_HashPolicy* const* hash_policies =
779       envoy_config_route_v3_RouteAction_hash_policy(route_action_proto, &size);
780   for (size_t i = 0; i < size; ++i) {
781     ValidationErrors::ScopedField field(errors,
782                                         absl::StrCat(".hash_policy[", i, "]"));
783     const auto* hash_policy = hash_policies[i];
784     XdsRouteConfigResource::Route::RouteAction::HashPolicy policy;
785     policy.terminal =
786         envoy_config_route_v3_RouteAction_HashPolicy_terminal(hash_policy);
787     const envoy_config_route_v3_RouteAction_HashPolicy_Header* header;
788     const envoy_config_route_v3_RouteAction_HashPolicy_FilterState*
789         filter_state;
790     if ((header = envoy_config_route_v3_RouteAction_HashPolicy_header(
791              hash_policy)) != nullptr) {
792       // header
793       ValidationErrors::ScopedField field(errors, ".header");
794       XdsRouteConfigResource::Route::RouteAction::HashPolicy::Header
795           header_policy;
796       header_policy.header_name = UpbStringToStdString(
797           envoy_config_route_v3_RouteAction_HashPolicy_Header_header_name(
798               header));
799       if (header_policy.header_name.empty()) {
800         ValidationErrors::ScopedField field(errors, ".header_name");
801         errors->AddError("must be non-empty");
802       }
803       // regex_rewrite
804       const auto* regex_rewrite =
805           envoy_config_route_v3_RouteAction_HashPolicy_Header_regex_rewrite(
806               header);
807       if (regex_rewrite != nullptr) {
808         ValidationErrors::ScopedField field(errors, ".regex_rewrite.pattern");
809         const auto* pattern =
810             envoy_type_matcher_v3_RegexMatchAndSubstitute_pattern(
811                 regex_rewrite);
812         if (pattern == nullptr) {
813           errors->AddError("field not present");
814           continue;
815         }
816         ValidationErrors::ScopedField field2(errors, ".regex");
817         std::string regex = UpbStringToStdString(
818             envoy_type_matcher_v3_RegexMatcher_regex(pattern));
819         if (regex.empty()) {
820           errors->AddError("field not present");
821           continue;
822         }
823         RE2::Options options;
824         header_policy.regex = std::make_unique<RE2>(regex, options);
825         if (!header_policy.regex->ok()) {
826           errors->AddError(absl::StrCat("errors compiling regex: ",
827                                         header_policy.regex->error()));
828           continue;
829         }
830         header_policy.regex_substitution = UpbStringToStdString(
831             envoy_type_matcher_v3_RegexMatchAndSubstitute_substitution(
832                 regex_rewrite));
833       }
834       policy.policy = std::move(header_policy);
835     } else if ((filter_state =
836                     envoy_config_route_v3_RouteAction_HashPolicy_filter_state(
837                         hash_policy)) != nullptr) {
838       // filter_state
839       std::string key = UpbStringToStdString(
840           envoy_config_route_v3_RouteAction_HashPolicy_FilterState_key(
841               filter_state));
842       if (key != "io.grpc.channel_id") continue;
843       policy.policy =
844           XdsRouteConfigResource::Route::RouteAction::HashPolicy::ChannelId();
845     } else {
846       // Unsupported hash policy type, ignore it.
847       continue;
848     }
849     route_action.hash_policies.emplace_back(std::move(policy));
850   }
851   // Get retry policy
852   const envoy_config_route_v3_RetryPolicy* retry_policy =
853       envoy_config_route_v3_RouteAction_retry_policy(route_action_proto);
854   if (retry_policy != nullptr) {
855     ValidationErrors::ScopedField field(errors, ".retry_policy");
856     route_action.retry_policy = RetryPolicyParse(context, retry_policy, errors);
857   }
858   // Parse cluster specifier, which is one of several options.
859   if (envoy_config_route_v3_RouteAction_has_cluster(route_action_proto)) {
860     // Cluster name.
861     std::string cluster_name = UpbStringToStdString(
862         envoy_config_route_v3_RouteAction_cluster(route_action_proto));
863     if (cluster_name.empty()) {
864       ValidationErrors::ScopedField field(errors, ".cluster");
865       errors->AddError("must be non-empty");
866     }
867     route_action.action =
868         XdsRouteConfigResource::Route::RouteAction::ClusterName{
869             std::move(cluster_name)};
870   } else if (envoy_config_route_v3_RouteAction_has_weighted_clusters(
871                  route_action_proto)) {
872     // WeightedClusters.
873     ValidationErrors::ScopedField field(errors, ".weighted_clusters");
874     const envoy_config_route_v3_WeightedCluster* weighted_clusters_proto =
875         envoy_config_route_v3_RouteAction_weighted_clusters(route_action_proto);
876     GPR_ASSERT(weighted_clusters_proto != nullptr);
877     std::vector<XdsRouteConfigResource::Route::RouteAction::ClusterWeight>
878         action_weighted_clusters;
879     uint64_t total_weight = 0;
880     size_t clusters_size;
881     const envoy_config_route_v3_WeightedCluster_ClusterWeight* const* clusters =
882         envoy_config_route_v3_WeightedCluster_clusters(weighted_clusters_proto,
883                                                        &clusters_size);
884     for (size_t i = 0; i < clusters_size; ++i) {
885       ValidationErrors::ScopedField field(errors,
886                                           absl::StrCat(".clusters[", i, "]"));
887       const auto* cluster_proto = clusters[i];
888       XdsRouteConfigResource::Route::RouteAction::ClusterWeight cluster;
889       // typed_per_filter_config
890       {
891         ValidationErrors::ScopedField field(errors, ".typed_per_filter_config");
892         cluster.typed_per_filter_config = ParseTypedPerFilterConfig<
893             envoy_config_route_v3_WeightedCluster_ClusterWeight,
894             envoy_config_route_v3_WeightedCluster_ClusterWeight_TypedPerFilterConfigEntry>(
895             context, cluster_proto,
896             envoy_config_route_v3_WeightedCluster_ClusterWeight_typed_per_filter_config_next,
897             envoy_config_route_v3_WeightedCluster_ClusterWeight_TypedPerFilterConfigEntry_key,
898             envoy_config_route_v3_WeightedCluster_ClusterWeight_TypedPerFilterConfigEntry_value,
899             errors);
900       }
901       // name
902       cluster.name = UpbStringToStdString(
903           envoy_config_route_v3_WeightedCluster_ClusterWeight_name(
904               cluster_proto));
905       if (cluster.name.empty()) {
906         ValidationErrors::ScopedField field(errors, ".name");
907         errors->AddError("must be non-empty");
908       }
909       // weight
910       const google_protobuf_UInt32Value* weight_proto =
911           envoy_config_route_v3_WeightedCluster_ClusterWeight_weight(
912               cluster_proto);
913       if (weight_proto == nullptr) {
914         ValidationErrors::ScopedField field(errors, ".weight");
915         errors->AddError("field not present");
916       } else {
917         cluster.weight = google_protobuf_UInt32Value_value(weight_proto);
918         if (cluster.weight == 0) continue;
919         total_weight += cluster.weight;
920       }
921       // Add entry to WeightedClusters.
922       action_weighted_clusters.emplace_back(std::move(cluster));
923     }
924     if (action_weighted_clusters.empty()) {
925       errors->AddError("no valid clusters specified");
926     } else if (total_weight > std::numeric_limits<uint32_t>::max()) {
927       errors->AddError("sum of cluster weights exceeds uint32 max");
928     }
929     route_action.action = std::move(action_weighted_clusters);
930   } else if (XdsRlsEnabled() &&
931              envoy_config_route_v3_RouteAction_has_cluster_specifier_plugin(
932                  route_action_proto)) {
933     // ClusterSpecifierPlugin
934     ValidationErrors::ScopedField field(errors, ".cluster_specifier_plugin");
935     std::string plugin_name = UpbStringToStdString(
936         envoy_config_route_v3_RouteAction_cluster_specifier_plugin(
937             route_action_proto));
938     if (plugin_name.empty()) {
939       errors->AddError("must be non-empty");
940       return absl::nullopt;
941     }
942     auto it = cluster_specifier_plugin_map.find(plugin_name);
943     if (it == cluster_specifier_plugin_map.end()) {
944       errors->AddError(absl::StrCat("unknown cluster specifier plugin name \"",
945                                     plugin_name, "\""));
946     } else {
947       // If the cluster specifier config is empty, that means that the
948       // plugin was unsupported but optional.  In that case, skip this route.
949       if (it->second.empty()) return absl::nullopt;
950     }
951     route_action.action =
952         XdsRouteConfigResource::Route::RouteAction::ClusterSpecifierPluginName{
953             std::move(plugin_name)};
954   } else {
955     // Not a supported cluster specifier, so ignore this route.
956     return absl::nullopt;
957   }
958   return route_action;
959 }
960 
ParseRoute(const XdsResourceType::DecodeContext & context,const envoy_config_route_v3_Route * route_proto,const absl::optional<XdsRouteConfigResource::RetryPolicy> & virtual_host_retry_policy,const XdsRouteConfigResource::ClusterSpecifierPluginMap & cluster_specifier_plugin_map,std::set<absl::string_view> * cluster_specifier_plugins_not_seen,ValidationErrors * errors)961 absl::optional<XdsRouteConfigResource::Route> ParseRoute(
962     const XdsResourceType::DecodeContext& context,
963     const envoy_config_route_v3_Route* route_proto,
964     const absl::optional<XdsRouteConfigResource::RetryPolicy>&
965         virtual_host_retry_policy,
966     const XdsRouteConfigResource::ClusterSpecifierPluginMap&
967         cluster_specifier_plugin_map,
968     std::set<absl::string_view>* cluster_specifier_plugins_not_seen,
969     ValidationErrors* errors) {
970   XdsRouteConfigResource::Route route;
971   // Parse route match.
972   {
973     ValidationErrors::ScopedField field(errors, ".match");
974     const auto* match = envoy_config_route_v3_Route_match(route_proto);
975     if (match == nullptr) {
976       errors->AddError("field not present");
977       return absl::nullopt;
978     }
979     // Skip routes with query_parameters set.
980     size_t query_parameters_size;
981     static_cast<void>(envoy_config_route_v3_RouteMatch_query_parameters(
982         match, &query_parameters_size));
983     if (query_parameters_size > 0) return absl::nullopt;
984     // Parse matchers.
985     auto path_matcher = RoutePathMatchParse(match, errors);
986     if (!path_matcher.has_value()) return absl::nullopt;
987     route.matchers.path_matcher = std::move(*path_matcher);
988     RouteHeaderMatchersParse(match, &route, errors);
989     RouteRuntimeFractionParse(match, &route, errors);
990   }
991   // Parse route action.
992   const envoy_config_route_v3_RouteAction* route_action_proto =
993       envoy_config_route_v3_Route_route(route_proto);
994   if (route_action_proto != nullptr) {
995     ValidationErrors::ScopedField field(errors, ".route");
996     auto route_action = RouteActionParse(context, route_action_proto,
997                                          cluster_specifier_plugin_map, errors);
998     if (!route_action.has_value()) return absl::nullopt;
999     // If the route does not have a retry policy but the vhost does,
1000     // use the vhost retry policy for this route.
1001     if (!route_action->retry_policy.has_value()) {
1002       route_action->retry_policy = virtual_host_retry_policy;
1003     }
1004     // Mark off plugins used in route action.
1005     auto* cluster_specifier_action = absl::get_if<
1006         XdsRouteConfigResource::Route::RouteAction::ClusterSpecifierPluginName>(
1007         &route_action->action);
1008     if (cluster_specifier_action != nullptr) {
1009       cluster_specifier_plugins_not_seen->erase(
1010           cluster_specifier_action->cluster_specifier_plugin_name);
1011     }
1012     route.action = std::move(*route_action);
1013   } else if (envoy_config_route_v3_Route_has_non_forwarding_action(
1014                  route_proto)) {
1015     route.action = XdsRouteConfigResource::Route::NonForwardingAction();
1016   } else {
1017     // Leave route.action initialized to UnknownAction (its default).
1018   }
1019   // Parse typed_per_filter_config.
1020   {
1021     ValidationErrors::ScopedField field(errors, ".typed_per_filter_config");
1022     route.typed_per_filter_config = ParseTypedPerFilterConfig<
1023         envoy_config_route_v3_Route,
1024         envoy_config_route_v3_Route_TypedPerFilterConfigEntry>(
1025         context, route_proto,
1026         envoy_config_route_v3_Route_typed_per_filter_config_next,
1027         envoy_config_route_v3_Route_TypedPerFilterConfigEntry_key,
1028         envoy_config_route_v3_Route_TypedPerFilterConfigEntry_value, errors);
1029   }
1030   return route;
1031 }
1032 
1033 }  // namespace
1034 
Parse(const XdsResourceType::DecodeContext & context,const envoy_config_route_v3_RouteConfiguration * route_config,ValidationErrors * errors)1035 XdsRouteConfigResource XdsRouteConfigResource::Parse(
1036     const XdsResourceType::DecodeContext& context,
1037     const envoy_config_route_v3_RouteConfiguration* route_config,
1038     ValidationErrors* errors) {
1039   XdsRouteConfigResource rds_update;
1040   // Get the cluster spcifier plugin map.
1041   if (XdsRlsEnabled()) {
1042     rds_update.cluster_specifier_plugin_map =
1043         ClusterSpecifierPluginParse(context, route_config, errors);
1044   }
1045   // Build a set of configured cluster_specifier_plugin names to make sure
1046   // each is actually referenced by a route action.
1047   std::set<absl::string_view> cluster_specifier_plugins_not_seen;
1048   for (auto& plugin : rds_update.cluster_specifier_plugin_map) {
1049     cluster_specifier_plugins_not_seen.emplace(plugin.first);
1050   }
1051   // Get the virtual hosts.
1052   size_t num_virtual_hosts;
1053   const envoy_config_route_v3_VirtualHost* const* virtual_hosts =
1054       envoy_config_route_v3_RouteConfiguration_virtual_hosts(
1055           route_config, &num_virtual_hosts);
1056   for (size_t i = 0; i < num_virtual_hosts; ++i) {
1057     ValidationErrors::ScopedField field(
1058         errors, absl::StrCat(".virtual_hosts[", i, "]"));
1059     rds_update.virtual_hosts.emplace_back();
1060     XdsRouteConfigResource::VirtualHost& vhost =
1061         rds_update.virtual_hosts.back();
1062     // Parse domains.
1063     size_t domain_size;
1064     upb_StringView const* domains = envoy_config_route_v3_VirtualHost_domains(
1065         virtual_hosts[i], &domain_size);
1066     for (size_t j = 0; j < domain_size; ++j) {
1067       std::string domain_pattern = UpbStringToStdString(domains[j]);
1068       if (!XdsRouting::IsValidDomainPattern(domain_pattern)) {
1069         ValidationErrors::ScopedField field(errors,
1070                                             absl::StrCat(".domains[", j, "]"));
1071         errors->AddError(
1072             absl::StrCat("invalid domain pattern \"", domain_pattern, "\""));
1073       }
1074       vhost.domains.emplace_back(std::move(domain_pattern));
1075     }
1076     if (vhost.domains.empty()) {
1077       ValidationErrors::ScopedField field(errors, ".domains");
1078       errors->AddError("must be non-empty");
1079     }
1080     // Parse typed_per_filter_config.
1081     {
1082       ValidationErrors::ScopedField field(errors, ".typed_per_filter_config");
1083       vhost.typed_per_filter_config = ParseTypedPerFilterConfig<
1084           envoy_config_route_v3_VirtualHost,
1085           envoy_config_route_v3_VirtualHost_TypedPerFilterConfigEntry>(
1086           context, virtual_hosts[i],
1087           envoy_config_route_v3_VirtualHost_typed_per_filter_config_next,
1088           envoy_config_route_v3_VirtualHost_TypedPerFilterConfigEntry_key,
1089           envoy_config_route_v3_VirtualHost_TypedPerFilterConfigEntry_value,
1090           errors);
1091     }
1092     // Parse retry policy.
1093     absl::optional<XdsRouteConfigResource::RetryPolicy>
1094         virtual_host_retry_policy;
1095     const envoy_config_route_v3_RetryPolicy* retry_policy =
1096         envoy_config_route_v3_VirtualHost_retry_policy(virtual_hosts[i]);
1097     if (retry_policy != nullptr) {
1098       ValidationErrors::ScopedField field(errors, ".retry_policy");
1099       virtual_host_retry_policy =
1100           RetryPolicyParse(context, retry_policy, errors);
1101     }
1102     // Parse routes.
1103     ValidationErrors::ScopedField field2(errors, ".routes");
1104     size_t num_routes;
1105     const envoy_config_route_v3_Route* const* routes =
1106         envoy_config_route_v3_VirtualHost_routes(virtual_hosts[i], &num_routes);
1107     for (size_t j = 0; j < num_routes; ++j) {
1108       ValidationErrors::ScopedField field(errors, absl::StrCat("[", j, "]"));
1109       auto route = ParseRoute(context, routes[j], virtual_host_retry_policy,
1110                               rds_update.cluster_specifier_plugin_map,
1111                               &cluster_specifier_plugins_not_seen, errors);
1112       if (route.has_value()) vhost.routes.emplace_back(std::move(*route));
1113     }
1114   }
1115   // For cluster specifier plugins that were not used in any route action,
1116   // delete them from the update, since they will never be used.
1117   for (auto& unused_plugin : cluster_specifier_plugins_not_seen) {
1118     rds_update.cluster_specifier_plugin_map.erase(std::string(unused_plugin));
1119   }
1120   return rds_update;
1121 }
1122 
1123 //
1124 // XdsRouteConfigResourceType
1125 //
1126 
1127 namespace {
1128 
MaybeLogRouteConfiguration(const XdsResourceType::DecodeContext & context,const envoy_config_route_v3_RouteConfiguration * route_config)1129 void MaybeLogRouteConfiguration(
1130     const XdsResourceType::DecodeContext& context,
1131     const envoy_config_route_v3_RouteConfiguration* route_config) {
1132   if (GRPC_TRACE_FLAG_ENABLED(*context.tracer) &&
1133       gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) {
1134     const upb_MessageDef* msg_type =
1135         envoy_config_route_v3_RouteConfiguration_getmsgdef(context.symtab);
1136     char buf[10240];
1137     upb_TextEncode(route_config, msg_type, nullptr, 0, buf, sizeof(buf));
1138     gpr_log(GPR_DEBUG, "[xds_client %p] RouteConfiguration: %s", context.client,
1139             buf);
1140   }
1141 }
1142 
1143 }  // namespace
1144 
Decode(const XdsResourceType::DecodeContext & context,absl::string_view serialized_resource) const1145 XdsResourceType::DecodeResult XdsRouteConfigResourceType::Decode(
1146     const XdsResourceType::DecodeContext& context,
1147     absl::string_view serialized_resource) const {
1148   DecodeResult result;
1149   // Parse serialized proto.
1150   auto* resource = envoy_config_route_v3_RouteConfiguration_parse(
1151       serialized_resource.data(), serialized_resource.size(), context.arena);
1152   if (resource == nullptr) {
1153     result.resource =
1154         absl::InvalidArgumentError("Can't parse RouteConfiguration resource.");
1155     return result;
1156   }
1157   MaybeLogRouteConfiguration(context, resource);
1158   // Validate resource.
1159   result.name = UpbStringToStdString(
1160       envoy_config_route_v3_RouteConfiguration_name(resource));
1161   ValidationErrors errors;
1162   auto rds_update = XdsRouteConfigResource::Parse(context, resource, &errors);
1163   if (!errors.ok()) {
1164     absl::Status status =
1165         errors.status(absl::StatusCode::kInvalidArgument,
1166                       "errors validating RouteConfiguration resource");
1167     if (GRPC_TRACE_FLAG_ENABLED(*context.tracer)) {
1168       gpr_log(GPR_ERROR, "[xds_client %p] invalid RouteConfiguration %s: %s",
1169               context.client, result.name->c_str(), status.ToString().c_str());
1170     }
1171     result.resource = std::move(status);
1172   } else {
1173     if (GRPC_TRACE_FLAG_ENABLED(*context.tracer)) {
1174       gpr_log(GPR_INFO, "[xds_client %p] parsed RouteConfiguration %s: %s",
1175               context.client, result.name->c_str(),
1176               rds_update.ToString().c_str());
1177     }
1178     result.resource =
1179         std::make_unique<XdsRouteConfigResource>(std::move(rds_update));
1180   }
1181   return result;
1182 }
1183 
1184 }  // namespace grpc_core
1185