• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

grpc / grpc-java / #20099

30 Nov 2025 07:31AM UTC coverage: 88.619% (+0.05%) from 88.572%
#20099

push

github

web-flow
xds: gRFC A88 - Changes to XdsClient Watcher APIs (#12446)

Implements
https://github.com/grpc/proposal/blob/master/A88-xds-data-error-handling.md#a88-xds-data-error-handling

35149 of 39663 relevant lines covered (88.62%)

0.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.17
/../xds/src/main/java/io/grpc/xds/client/BootstrapperImpl.java
1
/*
2
 * Copyright 2021 The 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
package io.grpc.xds.client;
18

19
import com.google.common.annotations.VisibleForTesting;
20
import com.google.common.collect.ImmutableList;
21
import com.google.common.collect.ImmutableMap;
22
import io.grpc.Internal;
23
import io.grpc.InternalLogId;
24
import io.grpc.internal.GrpcUtil;
25
import io.grpc.internal.GrpcUtil.GrpcBuildVersion;
26
import io.grpc.internal.JsonParser;
27
import io.grpc.internal.JsonUtil;
28
import io.grpc.xds.client.EnvoyProtoData.Node;
29
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
30
import java.io.IOException;
31
import java.nio.charset.StandardCharsets;
32
import java.nio.file.Files;
33
import java.nio.file.Paths;
34
import java.util.HashMap;
35
import java.util.List;
36
import java.util.Map;
37

38
/**
39
 * A {@link Bootstrapper} implementation that reads xDS configurations from local file system.
40
 */
41
@Internal
42
public abstract class BootstrapperImpl extends Bootstrapper {
43

44
  public static final String GRPC_EXPERIMENTAL_XDS_FALLBACK =
45
      "GRPC_EXPERIMENTAL_XDS_FALLBACK";
46
  public static final String GRPC_EXPERIMENTAL_XDS_DATA_ERROR_HANDLING =
47
      "GRPC_EXPERIMENTAL_XDS_DATA_ERROR_HANDLING";
48

49
  // Client features.
50
  @VisibleForTesting
51
  public static final String CLIENT_FEATURE_DISABLE_OVERPROVISIONING =
52
      "envoy.lb.does_not_support_overprovisioning";
53
  @VisibleForTesting
54
  public static final String CLIENT_FEATURE_RESOURCE_IN_SOTW = "xds.config.resource-in-sotw";
55

56
  // Server features.
57
  private static final String SERVER_FEATURE_IGNORE_RESOURCE_DELETION = "ignore_resource_deletion";
58
  private static final String SERVER_FEATURE_TRUSTED_XDS_SERVER = "trusted_xds_server";
59
  private static final String
60
      SERVER_FEATURE_RESOURCE_TIMER_IS_TRANSIENT_ERROR = "resource_timer_is_transient_error";
61

62
  @VisibleForTesting
63
  static boolean enableXdsFallback = GrpcUtil.getFlag(GRPC_EXPERIMENTAL_XDS_FALLBACK, true);
1✔
64

65
  @VisibleForTesting
66
  public static boolean xdsDataErrorHandlingEnabled
1✔
67
      = GrpcUtil.getFlag(GRPC_EXPERIMENTAL_XDS_DATA_ERROR_HANDLING, false);
1✔
68

69
  protected final XdsLogger logger;
70

71
  protected FileReader reader = LocalFileReader.INSTANCE;
1✔
72

73
  protected BootstrapperImpl() {
1✔
74
    logger = XdsLogger.withLogId(InternalLogId.allocate("bootstrapper", null));
1✔
75
  }
1✔
76

77
  protected abstract String getJsonContent() throws IOException, XdsInitializationException;
78

79
  protected abstract Object getImplSpecificConfig(Map<String, ?> serverConfig, String serverUri)
80
      throws XdsInitializationException;
81

82

83
  /**
84
   * Reads and parses bootstrap config. The config is expected to be in JSON format.
85
   */
86
  @SuppressWarnings("unchecked")
87
  @Override
88
  public BootstrapInfo bootstrap() throws XdsInitializationException {
89
    String jsonContent;
90
    try {
91
      jsonContent = getJsonContent();
1✔
92
    } catch (IOException e) {
×
93
      throw new XdsInitializationException("Fail to read bootstrap file", e);
×
94
    }
1✔
95

96
    Map<String, ?> rawBootstrap;
97
    try {
98
      rawBootstrap = (Map<String, ?>) JsonParser.parse(jsonContent);
1✔
99
    } catch (IOException e) {
×
100
      throw new XdsInitializationException("Failed to parse JSON", e);
×
101
    }
1✔
102

103
    logger.log(XdsLogLevel.DEBUG, "Bootstrap configuration:\n{0}", rawBootstrap);
1✔
104
    return bootstrap(rawBootstrap);
1✔
105
  }
106

107
  @Override
108
  public BootstrapInfo bootstrap(Map<String, ?> rawData) throws XdsInitializationException {
109
    return bootstrapBuilder(rawData).build();
1✔
110
  }
111

112
  protected BootstrapInfo.Builder bootstrapBuilder(Map<String, ?> rawData)
113
      throws XdsInitializationException {
114
    BootstrapInfo.Builder builder = BootstrapInfo.builder();
1✔
115

116
    List<?> rawServerConfigs = JsonUtil.getList(rawData, "xds_servers");
1✔
117
    if (rawServerConfigs == null) {
1✔
118
      throw new XdsInitializationException("Invalid bootstrap: 'xds_servers' does not exist.");
1✔
119
    }
120
    List<ServerInfo> servers = parseServerInfos(rawServerConfigs, logger);
1✔
121
    if (servers.size() > 1 && !enableXdsFallback) {
1✔
122
      servers = ImmutableList.of(servers.get(0));
×
123
    }
124
    builder.servers(servers);
1✔
125

126
    Node.Builder nodeBuilder = Node.newBuilder();
1✔
127
    Map<String, ?> rawNode = JsonUtil.getObject(rawData, "node");
1✔
128
    if (rawNode != null) {
1✔
129
      String id = JsonUtil.getString(rawNode, "id");
1✔
130
      if (id != null) {
1✔
131
        logger.log(XdsLogLevel.INFO, "Node id: {0}", id);
1✔
132
        nodeBuilder.setId(id);
1✔
133
      }
134
      String cluster = JsonUtil.getString(rawNode, "cluster");
1✔
135
      if (cluster != null) {
1✔
136
        logger.log(XdsLogLevel.INFO, "Node cluster: {0}", cluster);
1✔
137
        nodeBuilder.setCluster(cluster);
1✔
138
      }
139
      Map<String, ?> metadata = JsonUtil.getObject(rawNode, "metadata");
1✔
140
      if (metadata != null) {
1✔
141
        nodeBuilder.setMetadata(metadata);
1✔
142
      }
143
      Map<String, ?> rawLocality = JsonUtil.getObject(rawNode, "locality");
1✔
144
      if (rawLocality != null) {
1✔
145
        String region = "";
1✔
146
        String zone = "";
1✔
147
        String subZone = "";
1✔
148
        if (rawLocality.containsKey("region")) {
1✔
149
          region = JsonUtil.getString(rawLocality, "region");
1✔
150
        }
151
        if (rawLocality.containsKey("zone")) {
1✔
152
          zone = JsonUtil.getString(rawLocality, "zone");
1✔
153
        }
154
        if (rawLocality.containsKey("sub_zone")) {
1✔
155
          subZone = JsonUtil.getString(rawLocality, "sub_zone");
1✔
156
        }
157
        logger.log(XdsLogLevel.INFO, "Locality region: {0}, zone: {1}, subZone: {2}",
1✔
158
            region, zone, subZone);
159
        Locality locality = Locality.create(region, zone, subZone);
1✔
160
        nodeBuilder.setLocality(locality);
1✔
161
      }
162
    }
163
    GrpcBuildVersion buildVersion = GrpcUtil.getGrpcBuildVersion();
1✔
164
    logger.log(XdsLogLevel.INFO, "Build version: {0}", buildVersion);
1✔
165
    nodeBuilder.setBuildVersion(buildVersion.toString());
1✔
166
    nodeBuilder.setUserAgentName(buildVersion.getUserAgent());
1✔
167
    nodeBuilder.setUserAgentVersion(buildVersion.getImplementationVersion());
1✔
168
    nodeBuilder.addClientFeatures(CLIENT_FEATURE_DISABLE_OVERPROVISIONING);
1✔
169
    nodeBuilder.addClientFeatures(CLIENT_FEATURE_RESOURCE_IN_SOTW);
1✔
170
    builder.node(nodeBuilder.build());
1✔
171

172
    Map<String, ?> certProvidersBlob = JsonUtil.getObject(rawData, "certificate_providers");
1✔
173
    if (certProvidersBlob != null) {
1✔
174
      logger.log(XdsLogLevel.INFO, "Configured with {0} cert providers", certProvidersBlob.size());
1✔
175
      Map<String, CertificateProviderInfo> certProviders = new HashMap<>(certProvidersBlob.size());
1✔
176
      for (String name : certProvidersBlob.keySet()) {
1✔
177
        Map<String, ?> valueMap = JsonUtil.getObject(certProvidersBlob, name);
1✔
178
        String pluginName =
1✔
179
            checkForNull(JsonUtil.getString(valueMap, "plugin_name"), "plugin_name");
1✔
180
        logger.log(XdsLogLevel.INFO, "cert provider: {0}, plugin name: {1}", name, pluginName);
1✔
181
        Map<String, ?> config = checkForNull(JsonUtil.getObject(valueMap, "config"), "config");
1✔
182
        CertificateProviderInfo certificateProviderInfo =
1✔
183
            CertificateProviderInfo.create(pluginName, config);
1✔
184
        certProviders.put(name, certificateProviderInfo);
1✔
185
      }
1✔
186
      builder.certProviders(certProviders);
1✔
187
    }
188

189
    String serverResourceId =
1✔
190
        JsonUtil.getString(rawData, "server_listener_resource_name_template");
1✔
191
    logger.log(
1✔
192
        XdsLogLevel.INFO, "server_listener_resource_name_template: {0}", serverResourceId);
193
    builder.serverListenerResourceNameTemplate(serverResourceId);
1✔
194

195
    String clientDefaultListener =
1✔
196
        JsonUtil.getString(rawData, "client_default_listener_resource_name_template");
1✔
197
    logger.log(
1✔
198
        XdsLogLevel.INFO, "client_default_listener_resource_name_template: {0}",
199
        clientDefaultListener);
200
    if (clientDefaultListener != null) {
1✔
201
      builder.clientDefaultListenerResourceNameTemplate(clientDefaultListener);
1✔
202
    }
203

204
    Map<String, ?> rawAuthoritiesMap =
1✔
205
        JsonUtil.getObject(rawData, "authorities");
1✔
206
    ImmutableMap.Builder<String, AuthorityInfo> authorityInfoMapBuilder = ImmutableMap.builder();
1✔
207
    if (rawAuthoritiesMap != null) {
1✔
208
      logger.log(
1✔
209
          XdsLogLevel.INFO, "Configured with {0} xDS server authorities", rawAuthoritiesMap.size());
1✔
210
      for (String authorityName : rawAuthoritiesMap.keySet()) {
1✔
211
        logger.log(XdsLogLevel.INFO, "xDS server authority: {0}", authorityName);
1✔
212
        Map<String, ?> rawAuthority = JsonUtil.getObject(rawAuthoritiesMap, authorityName);
1✔
213
        String clientListnerTemplate =
1✔
214
            JsonUtil.getString(rawAuthority, "client_listener_resource_name_template");
1✔
215
        logger.log(
1✔
216
            XdsLogLevel.INFO, "client_listener_resource_name_template: {0}", clientListnerTemplate);
217
        String prefix = XDSTP_SCHEME + "//" + authorityName + "/";
1✔
218
        if (clientListnerTemplate == null) {
1✔
219
          clientListnerTemplate = prefix + "envoy.config.listener.v3.Listener/%s";
1✔
220
        } else if (!clientListnerTemplate.startsWith(prefix)) {
1✔
221
          throw new XdsInitializationException(
1✔
222
              "client_listener_resource_name_template: '" + clientListnerTemplate
223
                  + "' does not start with " + prefix);
224
        }
225
        List<?> rawAuthorityServers = JsonUtil.getList(rawAuthority, "xds_servers");
1✔
226
        List<ServerInfo> authorityServers;
227
        if (rawAuthorityServers == null || rawAuthorityServers.isEmpty()) {
1✔
228
          authorityServers = servers;
1✔
229
        } else {
230
          if (rawAuthorityServers.size() > 1 && !enableXdsFallback) {
1✔
231
            rawAuthorityServers = ImmutableList.of(rawAuthorityServers.get(0));
×
232
          }
233
          authorityServers = parseServerInfos(rawAuthorityServers, logger);
1✔
234
        }
235
        authorityInfoMapBuilder.put(
1✔
236
            authorityName, AuthorityInfo.create(clientListnerTemplate, authorityServers));
1✔
237
      }
1✔
238
      builder.authorities(authorityInfoMapBuilder.buildOrThrow());
1✔
239
    }
240

241
    return builder;
1✔
242
  }
243

244
  private List<ServerInfo> parseServerInfos(List<?> rawServerConfigs, XdsLogger logger)
245
      throws XdsInitializationException {
246
    logger.log(XdsLogLevel.INFO, "Configured with {0} xDS servers", rawServerConfigs.size());
1✔
247
    ImmutableList.Builder<ServerInfo> servers = ImmutableList.builder();
1✔
248
    List<Map<String, ?>> serverConfigList = JsonUtil.checkObjectList(rawServerConfigs);
1✔
249
    for (Map<String, ?> serverConfig : serverConfigList) {
1✔
250
      String serverUri = JsonUtil.getString(serverConfig, "server_uri");
1✔
251
      if (serverUri == null) {
1✔
252
        throw new XdsInitializationException("Invalid bootstrap: missing 'server_uri'");
1✔
253
      }
254
      logger.log(XdsLogLevel.INFO, "xDS server URI: {0}", serverUri);
1✔
255

256
      Object implSpecificConfig = getImplSpecificConfig(serverConfig, serverUri);
1✔
257

258
      boolean resourceTimerIsTransientError = false;
1✔
259
      boolean ignoreResourceDeletion = false;
1✔
260
      // "For forward compatibility reasons, the client will ignore any entry in the list that it
261
      // does not understand, regardless of type."
262
      List<?> serverFeatures = JsonUtil.getList(serverConfig, "server_features");
1✔
263
      if (serverFeatures != null) {
1✔
264
        logger.log(XdsLogLevel.INFO, "Server features: {0}", serverFeatures);
1✔
265
        if (serverFeatures.contains(SERVER_FEATURE_IGNORE_RESOURCE_DELETION)) {
1✔
266
          ignoreResourceDeletion = true;
1✔
267
        }
268
        resourceTimerIsTransientError = xdsDataErrorHandlingEnabled
1✔
269
            && serverFeatures.contains(SERVER_FEATURE_RESOURCE_TIMER_IS_TRANSIENT_ERROR);
1✔
270
      }
271
      servers.add(
1✔
272
          ServerInfo.create(serverUri, implSpecificConfig, ignoreResourceDeletion,
1✔
273
              serverFeatures != null
274
                  && serverFeatures.contains(SERVER_FEATURE_TRUSTED_XDS_SERVER),
1✔
275
              resourceTimerIsTransientError));
276
    }
1✔
277
    return servers.build();
1✔
278
  }
279

280
  @VisibleForTesting
281
  public void setFileReader(FileReader reader) {
282
    this.reader = reader;
1✔
283
  }
1✔
284

285
  /**
286
   * Reads the content of the file with the given path in the file system.
287
   */
288
  public interface FileReader {
289
    String readFile(String path) throws IOException;
290
  }
291

292
  protected enum LocalFileReader implements FileReader {
1✔
293
    INSTANCE;
1✔
294

295
    @Override
296
    public String readFile(String path) throws IOException {
297
      return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
×
298
    }
299
  }
300

301
  private static <T> T checkForNull(T value, String fieldName) throws XdsInitializationException {
302
    if (value == null) {
1✔
303
      throw new XdsInitializationException(
1✔
304
          "Invalid bootstrap: '" + fieldName + "' does not exist.");
305
    }
306
    return value;
1✔
307
  }
308

309
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc