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

grpc / grpc-java / #19572

27 Nov 2024 10:56PM CUT coverage: 84.622%. Remained the same
#19572

push

github

web-flow
[CSM] Use xds-enabled server and xds credentials in examples (#11706)

Backport #11706 to v1.68.x

33853 of 40005 relevant lines covered (84.62%)

0.85 hits per line

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

93.75
/../xds/src/main/java/io/grpc/xds/client/ControlPlaneClient.java
1
/*
2
 * Copyright 2020 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 static com.google.common.base.Preconditions.checkNotNull;
20
import static com.google.common.base.Preconditions.checkState;
21

22
import com.google.common.annotations.VisibleForTesting;
23
import com.google.common.base.Stopwatch;
24
import com.google.common.base.Supplier;
25
import com.google.protobuf.Any;
26
import com.google.rpc.Code;
27
import io.envoyproxy.envoy.service.discovery.v3.AggregatedDiscoveryServiceGrpc;
28
import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest;
29
import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse;
30
import io.grpc.InternalLogId;
31
import io.grpc.MethodDescriptor;
32
import io.grpc.Status;
33
import io.grpc.SynchronizationContext;
34
import io.grpc.SynchronizationContext.ScheduledHandle;
35
import io.grpc.internal.BackoffPolicy;
36
import io.grpc.xds.client.Bootstrapper.ServerInfo;
37
import io.grpc.xds.client.EnvoyProtoData.Node;
38
import io.grpc.xds.client.XdsClient.ProcessingTracker;
39
import io.grpc.xds.client.XdsClient.ResourceStore;
40
import io.grpc.xds.client.XdsClient.XdsResponseHandler;
41
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
42
import io.grpc.xds.client.XdsTransportFactory.EventHandler;
43
import io.grpc.xds.client.XdsTransportFactory.StreamingCall;
44
import io.grpc.xds.client.XdsTransportFactory.XdsTransport;
45
import java.util.Collection;
46
import java.util.Collections;
47
import java.util.HashMap;
48
import java.util.HashSet;
49
import java.util.List;
50
import java.util.Map;
51
import java.util.Set;
52
import java.util.concurrent.ScheduledExecutorService;
53
import java.util.concurrent.TimeUnit;
54
import javax.annotation.Nullable;
55

56
/**
57
 * Common base type for XdsClient implementations, which encapsulates the layer abstraction of
58
 * the xDS RPC stream.
59
 */
60
final class ControlPlaneClient {
61

62
  private final SynchronizationContext syncContext;
63
  private final InternalLogId logId;
64
  private final XdsLogger logger;
65
  private final ServerInfo serverInfo;
66
  private final XdsTransport xdsTransport;
67
  private final XdsResponseHandler xdsResponseHandler;
68
  private final ResourceStore resourceStore;
69
  private final ScheduledExecutorService timeService;
70
  private final BackoffPolicy.Provider backoffPolicyProvider;
71
  private final Stopwatch stopwatch;
72
  private final Node bootstrapNode;
73
  private final XdsClient xdsClient;
74

75
  // Last successfully applied version_info for each resource type. Starts with empty string.
76
  // A version_info is used to update management server with client's most recent knowledge of
77
  // resources.
78
  private final Map<XdsResourceType<?>, String> versions = new HashMap<>();
1✔
79

80
  private boolean shutdown;
81
  @Nullable
82
  private AdsStream adsStream;
83
  @Nullable
84
  private BackoffPolicy retryBackoffPolicy;
85
  @Nullable
86
  private ScheduledHandle rpcRetryTimer;
87
  private MessagePrettyPrinter messagePrinter;
88

89
  /** An entity that manages ADS RPCs over a single channel. */
90
  ControlPlaneClient(
91
      XdsTransport xdsTransport,
92
      ServerInfo serverInfo,
93
      Node bootstrapNode,
94
      XdsResponseHandler xdsResponseHandler,
95
      ResourceStore resourceStore,
96
      ScheduledExecutorService
97
      timeService,
98
      SynchronizationContext syncContext,
99
      BackoffPolicy.Provider backoffPolicyProvider,
100
      Supplier<Stopwatch> stopwatchSupplier,
101
      XdsClient xdsClient,
102
      MessagePrettyPrinter messagePrinter) {
1✔
103
    this.serverInfo = checkNotNull(serverInfo, "serverInfo");
1✔
104
    this.xdsTransport = checkNotNull(xdsTransport, "xdsTransport");
1✔
105
    this.xdsResponseHandler = checkNotNull(xdsResponseHandler, "xdsResponseHandler");
1✔
106
    this.resourceStore = checkNotNull(resourceStore, "resourcesSubscriber");
1✔
107
    this.bootstrapNode = checkNotNull(bootstrapNode, "bootstrapNode");
1✔
108
    this.timeService = checkNotNull(timeService, "timeService");
1✔
109
    this.syncContext = checkNotNull(syncContext, "syncContext");
1✔
110
    this.backoffPolicyProvider = checkNotNull(backoffPolicyProvider, "backoffPolicyProvider");
1✔
111
    this.xdsClient = checkNotNull(xdsClient, "xdsClient");
1✔
112
    this.messagePrinter = checkNotNull(messagePrinter, "messagePrinter");
1✔
113
    stopwatch = checkNotNull(stopwatchSupplier, "stopwatchSupplier").get();
1✔
114
    logId = InternalLogId.allocate("xds-client", serverInfo.target());
1✔
115
    logger = XdsLogger.withLogId(logId);
1✔
116
    logger.log(XdsLogLevel.INFO, "Created");
1✔
117
  }
1✔
118

119
  void shutdown() {
120
    syncContext.execute(new Runnable() {
1✔
121
      @Override
122
      public void run() {
123
        shutdown = true;
1✔
124
        logger.log(XdsLogLevel.INFO, "Shutting down");
1✔
125
        if (adsStream != null) {
1✔
126
          adsStream.close(Status.CANCELLED.withDescription("shutdown").asException());
1✔
127
        }
128
        if (rpcRetryTimer != null && rpcRetryTimer.isPending()) {
1✔
129
          rpcRetryTimer.cancel();
1✔
130
        }
131
        xdsTransport.shutdown();
1✔
132
      }
1✔
133
    });
134
  }
1✔
135

136
  @Override
137
  public String toString() {
138
    return logId.toString();
×
139
  }
140

141
  /**
142
   * Updates the resource subscription for the given resource type.
143
   */
144
  // Must be synchronized.
145
  void adjustResourceSubscription(XdsResourceType<?> resourceType) {
146
    if (isInBackoff()) {
1✔
147
      return;
1✔
148
    }
149
    if (adsStream == null) {
1✔
150
      startRpcStream();
1✔
151
    }
152
    Collection<String> resources = resourceStore.getSubscribedResources(serverInfo, resourceType);
1✔
153
    if (resources == null) {
1✔
154
      resources = Collections.emptyList();
1✔
155
    }
156
    adsStream.sendDiscoveryRequest(resourceType, resources);
1✔
157
    if (resources.isEmpty()) {
1✔
158
      // The resource type no longer has subscribing resources; clean up references to it
159
      versions.remove(resourceType);
1✔
160
      adsStream.respNonces.remove(resourceType);
1✔
161
    }
162
  }
1✔
163

164
  /**
165
   * Accepts the update for the given resource type by updating the latest resource version
166
   * and sends an ACK request to the management server.
167
   */
168
  // Must be synchronized.
169
  void ackResponse(XdsResourceType<?> type, String versionInfo, String nonce) {
170
    versions.put(type, versionInfo);
1✔
171
    logger.log(XdsLogLevel.INFO, "Sending ACK for {0} update, nonce: {1}, current version: {2}",
1✔
172
        type.typeName(), nonce, versionInfo);
1✔
173
    Collection<String> resources = resourceStore.getSubscribedResources(serverInfo, type);
1✔
174
    if (resources == null) {
1✔
175
      resources = Collections.emptyList();
×
176
    }
177
    adsStream.sendDiscoveryRequest(type, versionInfo, resources, nonce, null);
1✔
178
  }
1✔
179

180
  /**
181
   * Rejects the update for the given resource type and sends an NACK request (request with last
182
   * accepted version) to the management server.
183
   */
184
  // Must be synchronized.
185
  void nackResponse(XdsResourceType<?> type, String nonce, String errorDetail) {
186
    String versionInfo = versions.getOrDefault(type, "");
1✔
187
    logger.log(XdsLogLevel.INFO, "Sending NACK for {0} update, nonce: {1}, current version: {2}",
1✔
188
        type.typeName(), nonce, versionInfo);
1✔
189
    Collection<String> resources = resourceStore.getSubscribedResources(serverInfo, type);
1✔
190
    if (resources == null) {
1✔
191
      resources = Collections.emptyList();
×
192
    }
193
    adsStream.sendDiscoveryRequest(type, versionInfo, resources, nonce, errorDetail);
1✔
194
  }
1✔
195

196
  /**
197
   * Returns {@code true} if the resource discovery is currently in backoff.
198
   */
199
  // Must be synchronized.
200
  boolean isInBackoff() {
201
    return rpcRetryTimer != null && rpcRetryTimer.isPending();
1✔
202
  }
203

204
  // Must be synchronized.
205
  boolean isReady() {
206
    return adsStream != null && adsStream.call != null && adsStream.call.isReady();
1✔
207
  }
208

209
  /**
210
   * Starts a timer for each requested resource that hasn't been responded to and
211
   * has been waiting for the channel to get ready.
212
   */
213
  // Must be synchronized.
214
  void readyHandler() {
215
    if (!isReady()) {
1✔
216
      return;
1✔
217
    }
218

219
    if (isInBackoff()) {
1✔
220
      rpcRetryTimer.cancel();
×
221
      rpcRetryTimer = null;
×
222
    }
223

224
    xdsClient.startSubscriberTimersIfNeeded(serverInfo);
1✔
225
  }
1✔
226

227
  /**
228
   * Establishes the RPC connection by creating a new RPC stream on the given channel for
229
   * xDS protocol communication.
230
   */
231
  // Must be synchronized.
232
  private void startRpcStream() {
233
    checkState(adsStream == null, "Previous adsStream has not been cleared yet");
1✔
234
    adsStream = new AdsStream();
1✔
235
    logger.log(XdsLogLevel.INFO, "ADS stream started");
1✔
236
    stopwatch.reset().start();
1✔
237
  }
1✔
238

239
  @VisibleForTesting
240
  public final class RpcRetryTask implements Runnable {
1✔
241
    @Override
242
    public void run() {
243
      if (shutdown) {
1✔
244
        return;
×
245
      }
246
      startRpcStream();
1✔
247
      Set<XdsResourceType<?>> subscribedResourceTypes =
1✔
248
          new HashSet<>(resourceStore.getSubscribedResourceTypesWithTypeUrl().values());
1✔
249
      for (XdsResourceType<?> type : subscribedResourceTypes) {
1✔
250
        Collection<String> resources = resourceStore.getSubscribedResources(serverInfo, type);
1✔
251
        if (resources != null) {
1✔
252
          adsStream.sendDiscoveryRequest(type, resources);
1✔
253
        }
254
      }
1✔
255
      xdsResponseHandler.handleStreamRestarted(serverInfo);
1✔
256
    }
1✔
257
  }
258

259
  @VisibleForTesting
260
  @Nullable
261
  XdsResourceType<?> fromTypeUrl(String typeUrl) {
262
    return resourceStore.getSubscribedResourceTypesWithTypeUrl().get(typeUrl);
1✔
263
  }
264

265
  private class AdsStream implements EventHandler<DiscoveryResponse> {
266
    private boolean responseReceived;
267
    private boolean closed;
268
    // Response nonce for the most recently received discovery responses of each resource type.
269
    // Client initiated requests start response nonce with empty string.
270
    // Nonce in each response is echoed back in the following ACK/NACK request. It is
271
    // used for management server to identify which response the client is ACKing/NACking.
272
    // To avoid confusion, client-initiated requests will always use the nonce in
273
    // most recently received responses of each resource type.
274
    private final Map<XdsResourceType<?>, String> respNonces = new HashMap<>();
1✔
275
    private final StreamingCall<DiscoveryRequest, DiscoveryResponse> call;
276
    private final MethodDescriptor<DiscoveryRequest, DiscoveryResponse> methodDescriptor =
1✔
277
        AggregatedDiscoveryServiceGrpc.getStreamAggregatedResourcesMethod();
1✔
278

279
    private AdsStream() {
1✔
280
      this.call = xdsTransport.createStreamingCall(methodDescriptor.getFullMethodName(),
1✔
281
          methodDescriptor.getRequestMarshaller(), methodDescriptor.getResponseMarshaller());
1✔
282
      call.start(this);
1✔
283
    }
1✔
284

285
    /**
286
     * Sends a discovery request with the given {@code versionInfo}, {@code nonce} and
287
     * {@code errorDetail}. Used for reacting to a specific discovery response. For
288
     * client-initiated discovery requests, use {@link
289
     * #sendDiscoveryRequest(XdsResourceType, Collection)}.
290
     */
291
    void sendDiscoveryRequest(XdsResourceType<?> type, String versionInfo,
292
                              Collection<String> resources, String nonce,
293
                              @Nullable String errorDetail) {
294
      DiscoveryRequest.Builder builder =
295
          DiscoveryRequest.newBuilder()
1✔
296
              .setVersionInfo(versionInfo)
1✔
297
              .setNode(bootstrapNode.toEnvoyProtoNode())
1✔
298
              .addAllResourceNames(resources)
1✔
299
              .setTypeUrl(type.typeUrl())
1✔
300
              .setResponseNonce(nonce);
1✔
301
      if (errorDetail != null) {
1✔
302
        com.google.rpc.Status error =
303
            com.google.rpc.Status.newBuilder()
1✔
304
                .setCode(Code.INVALID_ARGUMENT_VALUE)  // FIXME(chengyuanzhang): use correct code
1✔
305
                .setMessage(errorDetail)
1✔
306
                .build();
1✔
307
        builder.setErrorDetail(error);
1✔
308
      }
309
      DiscoveryRequest request = builder.build();
1✔
310
      call.sendMessage(request);
1✔
311
      if (logger.isLoggable(XdsLogLevel.DEBUG)) {
1✔
312
        logger.log(XdsLogLevel.DEBUG, "Sent DiscoveryRequest\n{0}", messagePrinter.print(request));
×
313
      }
314
    }
1✔
315

316
    /**
317
     * Sends a client-initiated discovery request.
318
     */
319
    final void sendDiscoveryRequest(XdsResourceType<?> type, Collection<String> resources) {
320
      logger.log(XdsLogLevel.INFO, "Sending {0} request for resources: {1}", type, resources);
1✔
321
      sendDiscoveryRequest(type, versions.getOrDefault(type, ""), resources,
1✔
322
          respNonces.getOrDefault(type, ""), null);
1✔
323
    }
1✔
324

325
    @Override
326
    public void onReady() {
327
      syncContext.execute(ControlPlaneClient.this::readyHandler);
1✔
328
    }
1✔
329

330
    @Override
331
    public void onRecvMessage(DiscoveryResponse response) {
332
      syncContext.execute(new Runnable() {
1✔
333
        @Override
334
        public void run() {
335
          XdsResourceType<?> type = fromTypeUrl(response.getTypeUrl());
1✔
336
          if (logger.isLoggable(XdsLogLevel.DEBUG)) {
1✔
337
            logger.log(
×
338
                XdsLogLevel.DEBUG, "Received {0} response:\n{1}", type,
339
                messagePrinter.print(response));
×
340
          }
341
          if (type == null) {
1✔
342
            logger.log(
1✔
343
                XdsLogLevel.WARNING,
344
                "Ignore an unknown type of DiscoveryResponse: {0}",
345
                response.getTypeUrl());
1✔
346

347
            call.startRecvMessage();
1✔
348
            return;
1✔
349
          }
350
          handleRpcResponse(type, response.getVersionInfo(), response.getResourcesList(),
1✔
351
              response.getNonce());
1✔
352
        }
1✔
353
      });
354
    }
1✔
355

356
    @Override
357
    public void onStatusReceived(final Status status) {
358
      syncContext.execute(() -> {
1✔
359
        handleRpcStreamClosed(status);
1✔
360
      });
1✔
361
    }
1✔
362

363
    final void handleRpcResponse(XdsResourceType<?> type, String versionInfo, List<Any> resources,
364
                                 String nonce) {
365
      checkNotNull(type, "type");
1✔
366
      if (closed) {
1✔
367
        return;
×
368
      }
369
      responseReceived = true;
1✔
370
      respNonces.put(type, nonce);
1✔
371
      ProcessingTracker processingTracker = new ProcessingTracker(
1✔
372
          () -> call.startRecvMessage(), syncContext);
1✔
373
      xdsResponseHandler.handleResourceResponse(type, serverInfo, versionInfo, resources, nonce,
1✔
374
          processingTracker);
375
      processingTracker.onComplete();
1✔
376
    }
1✔
377

378
    private void handleRpcStreamClosed(Status status) {
379
      if (closed) {
1✔
380
        return;
1✔
381
      }
382

383
      if (responseReceived || retryBackoffPolicy == null) {
1✔
384
        // Reset the backoff sequence if had received a response, or backoff sequence
385
        // has never been initialized.
386
        retryBackoffPolicy = backoffPolicyProvider.get();
1✔
387
      }
388
      // FakeClock in tests isn't thread-safe. Schedule the retry timer before notifying callbacks
389
      // to avoid TSAN races, since tests may wait until callbacks are called but then would run
390
      // concurrently with the stopwatch and schedule.
391
      long elapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);
1✔
392
      long delayNanos = Math.max(0, retryBackoffPolicy.nextBackoffNanos() - elapsed);
1✔
393
      rpcRetryTimer = syncContext.schedule(
1✔
394
          new RpcRetryTask(), delayNanos, TimeUnit.NANOSECONDS, timeService);
1✔
395

396
      Status newStatus = status;
1✔
397
      if (responseReceived) {
1✔
398
        // A closed ADS stream after a successful response is not considered an error. Servers may
399
        // close streams for various reasons during normal operation, such as load balancing or
400
        // underlying connection hitting its max connection age limit  (see gRFC A9).
401
        if (!status.isOk()) {
1✔
402
          newStatus = Status.OK;
1✔
403
          logger.log( XdsLogLevel.DEBUG, "ADS stream closed with error {0}: {1}. However, a "
1✔
404
              + "response was received, so this will not be treated as an error. Cause: {2}",
405
              status.getCode(), status.getDescription(), status.getCause());
1✔
406
        } else {
407
          logger.log(XdsLogLevel.DEBUG,
1✔
408
              "ADS stream closed by server after a response was received");
409
        }
410
      } else {
411
        // If the ADS stream is closed without ever having received a response from the server, then
412
        // the XdsClient should consider that a connectivity error (see gRFC A57).
413
        if (status.isOk()) {
1✔
414
          newStatus = Status.UNAVAILABLE.withDescription(
1✔
415
              "ADS stream closed with OK before receiving a response");
416
        }
417
        logger.log(
1✔
418
            XdsLogLevel.ERROR, "ADS stream failed with status {0}: {1}. Cause: {2}",
419
            newStatus.getCode(), newStatus.getDescription(), newStatus.getCause());
1✔
420
      }
421

422
      closed = true;
1✔
423
      xdsResponseHandler.handleStreamClosed(newStatus);
1✔
424
      cleanUp();
1✔
425

426
      logger.log(XdsLogLevel.INFO, "Retry ADS stream in {0} ns", delayNanos);
1✔
427
    }
1✔
428

429
    private void close(Exception error) {
430
      if (closed) {
1✔
431
        return;
×
432
      }
433
      closed = true;
1✔
434
      cleanUp();
1✔
435
      call.sendError(error);
1✔
436
    }
1✔
437

438
    private void cleanUp() {
439
      if (adsStream == this) {
1✔
440
        adsStream = null;
1✔
441
      }
442
    }
1✔
443
  }
444
}
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