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

grpc / grpc-java / #19718

06 Mar 2025 08:31PM UTC coverage: 88.511% (-0.01%) from 88.525%
#19718

push

github

ejona86
core: Apply ManagedChannelImpl's updateBalancingState() immediately

ffcc360ba adjusted updateBalancingState() to require being run within
the sync context. However, it still queued the work into the sync
context, which was unnecessary. This re-entering the sync context
unnecessarily delays the new state from being used.

34569 of 39056 relevant lines covered (88.51%)

0.89 hits per line

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

94.0
/../core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
1
/*
2
 * Copyright 2016 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.internal;
18

19
import static com.google.common.base.Preconditions.checkArgument;
20
import static com.google.common.base.Preconditions.checkNotNull;
21
import static com.google.common.base.Preconditions.checkState;
22
import static io.grpc.ClientStreamTracer.NAME_RESOLUTION_DELAYED;
23
import static io.grpc.ConnectivityState.CONNECTING;
24
import static io.grpc.ConnectivityState.IDLE;
25
import static io.grpc.ConnectivityState.SHUTDOWN;
26
import static io.grpc.ConnectivityState.TRANSIENT_FAILURE;
27
import static io.grpc.EquivalentAddressGroup.ATTR_AUTHORITY_OVERRIDE;
28

29
import com.google.common.annotations.VisibleForTesting;
30
import com.google.common.base.MoreObjects;
31
import com.google.common.base.Stopwatch;
32
import com.google.common.base.Supplier;
33
import com.google.common.util.concurrent.ListenableFuture;
34
import com.google.common.util.concurrent.SettableFuture;
35
import com.google.errorprone.annotations.concurrent.GuardedBy;
36
import io.grpc.Attributes;
37
import io.grpc.CallCredentials;
38
import io.grpc.CallOptions;
39
import io.grpc.Channel;
40
import io.grpc.ChannelCredentials;
41
import io.grpc.ChannelLogger;
42
import io.grpc.ChannelLogger.ChannelLogLevel;
43
import io.grpc.ClientCall;
44
import io.grpc.ClientInterceptor;
45
import io.grpc.ClientInterceptors;
46
import io.grpc.ClientStreamTracer;
47
import io.grpc.ClientTransportFilter;
48
import io.grpc.CompressorRegistry;
49
import io.grpc.ConnectivityState;
50
import io.grpc.ConnectivityStateInfo;
51
import io.grpc.Context;
52
import io.grpc.Deadline;
53
import io.grpc.DecompressorRegistry;
54
import io.grpc.EquivalentAddressGroup;
55
import io.grpc.ForwardingChannelBuilder2;
56
import io.grpc.ForwardingClientCall;
57
import io.grpc.Grpc;
58
import io.grpc.InternalChannelz;
59
import io.grpc.InternalChannelz.ChannelStats;
60
import io.grpc.InternalChannelz.ChannelTrace;
61
import io.grpc.InternalConfigSelector;
62
import io.grpc.InternalInstrumented;
63
import io.grpc.InternalLogId;
64
import io.grpc.InternalWithLogId;
65
import io.grpc.LoadBalancer;
66
import io.grpc.LoadBalancer.CreateSubchannelArgs;
67
import io.grpc.LoadBalancer.PickResult;
68
import io.grpc.LoadBalancer.PickSubchannelArgs;
69
import io.grpc.LoadBalancer.ResolvedAddresses;
70
import io.grpc.LoadBalancer.SubchannelPicker;
71
import io.grpc.LoadBalancer.SubchannelStateListener;
72
import io.grpc.ManagedChannel;
73
import io.grpc.ManagedChannelBuilder;
74
import io.grpc.Metadata;
75
import io.grpc.MethodDescriptor;
76
import io.grpc.MetricInstrumentRegistry;
77
import io.grpc.MetricRecorder;
78
import io.grpc.NameResolver;
79
import io.grpc.NameResolver.ConfigOrError;
80
import io.grpc.NameResolver.ResolutionResult;
81
import io.grpc.NameResolverProvider;
82
import io.grpc.NameResolverRegistry;
83
import io.grpc.ProxyDetector;
84
import io.grpc.Status;
85
import io.grpc.StatusOr;
86
import io.grpc.SynchronizationContext;
87
import io.grpc.SynchronizationContext.ScheduledHandle;
88
import io.grpc.internal.AutoConfiguredLoadBalancerFactory.AutoConfiguredLoadBalancer;
89
import io.grpc.internal.ClientCallImpl.ClientStreamProvider;
90
import io.grpc.internal.ClientTransportFactory.SwapChannelCredentialsResult;
91
import io.grpc.internal.ManagedChannelImplBuilder.ClientTransportFactoryBuilder;
92
import io.grpc.internal.ManagedChannelImplBuilder.FixedPortProvider;
93
import io.grpc.internal.ManagedChannelServiceConfig.MethodInfo;
94
import io.grpc.internal.ManagedChannelServiceConfig.ServiceConfigConvertedSelector;
95
import io.grpc.internal.RetriableStream.ChannelBufferMeter;
96
import io.grpc.internal.RetriableStream.Throttle;
97
import io.grpc.internal.RetryingNameResolver.ResolutionResultListener;
98
import java.net.URI;
99
import java.util.ArrayList;
100
import java.util.Collection;
101
import java.util.Collections;
102
import java.util.HashSet;
103
import java.util.LinkedHashSet;
104
import java.util.List;
105
import java.util.Map;
106
import java.util.Set;
107
import java.util.concurrent.Callable;
108
import java.util.concurrent.CountDownLatch;
109
import java.util.concurrent.ExecutionException;
110
import java.util.concurrent.Executor;
111
import java.util.concurrent.Future;
112
import java.util.concurrent.ScheduledExecutorService;
113
import java.util.concurrent.ScheduledFuture;
114
import java.util.concurrent.TimeUnit;
115
import java.util.concurrent.TimeoutException;
116
import java.util.concurrent.atomic.AtomicBoolean;
117
import java.util.concurrent.atomic.AtomicReference;
118
import java.util.logging.Level;
119
import java.util.logging.Logger;
120
import javax.annotation.Nullable;
121
import javax.annotation.concurrent.ThreadSafe;
122

123
/** A communication channel for making outgoing RPCs. */
124
@ThreadSafe
125
final class ManagedChannelImpl extends ManagedChannel implements
126
    InternalInstrumented<ChannelStats> {
127
  @VisibleForTesting
128
  static final Logger logger = Logger.getLogger(ManagedChannelImpl.class.getName());
1✔
129

130
  static final long IDLE_TIMEOUT_MILLIS_DISABLE = -1;
131

132
  static final long SUBCHANNEL_SHUTDOWN_DELAY_SECONDS = 5;
133

134
  @VisibleForTesting
135
  static final Status SHUTDOWN_NOW_STATUS =
1✔
136
      Status.UNAVAILABLE.withDescription("Channel shutdownNow invoked");
1✔
137

138
  @VisibleForTesting
139
  static final Status SHUTDOWN_STATUS =
1✔
140
      Status.UNAVAILABLE.withDescription("Channel shutdown invoked");
1✔
141

142
  @VisibleForTesting
143
  static final Status SUBCHANNEL_SHUTDOWN_STATUS =
1✔
144
      Status.UNAVAILABLE.withDescription("Subchannel shutdown invoked");
1✔
145

146
  private static final ManagedChannelServiceConfig EMPTY_SERVICE_CONFIG =
147
      ManagedChannelServiceConfig.empty();
1✔
148
  private static final InternalConfigSelector INITIAL_PENDING_SELECTOR =
1✔
149
      new InternalConfigSelector() {
1✔
150
        @Override
151
        public Result selectConfig(PickSubchannelArgs args) {
152
          throw new IllegalStateException("Resolution is pending");
×
153
        }
154
      };
155
  private static final LoadBalancer.PickDetailsConsumer NOOP_PICK_DETAILS_CONSUMER =
1✔
156
      new LoadBalancer.PickDetailsConsumer() {};
1✔
157

158
  private final InternalLogId logId;
159
  private final String target;
160
  @Nullable
161
  private final String authorityOverride;
162
  private final NameResolverRegistry nameResolverRegistry;
163
  private final URI targetUri;
164
  private final NameResolverProvider nameResolverProvider;
165
  private final NameResolver.Args nameResolverArgs;
166
  private final AutoConfiguredLoadBalancerFactory loadBalancerFactory;
167
  private final ClientTransportFactory originalTransportFactory;
168
  @Nullable
169
  private final ChannelCredentials originalChannelCreds;
170
  private final ClientTransportFactory transportFactory;
171
  private final ClientTransportFactory oobTransportFactory;
172
  private final RestrictedScheduledExecutor scheduledExecutor;
173
  private final Executor executor;
174
  private final ObjectPool<? extends Executor> executorPool;
175
  private final ObjectPool<? extends Executor> balancerRpcExecutorPool;
176
  private final ExecutorHolder balancerRpcExecutorHolder;
177
  private final ExecutorHolder offloadExecutorHolder;
178
  private final TimeProvider timeProvider;
179
  private final int maxTraceEvents;
180

181
  @VisibleForTesting
1✔
182
  final SynchronizationContext syncContext = new SynchronizationContext(
183
      new Thread.UncaughtExceptionHandler() {
1✔
184
        @Override
185
        public void uncaughtException(Thread t, Throwable e) {
186
          logger.log(
1✔
187
              Level.SEVERE,
188
              "[" + getLogId() + "] Uncaught exception in the SynchronizationContext. Panic!",
1✔
189
              e);
190
          panic(e);
1✔
191
        }
1✔
192
      });
193

194
  private boolean fullStreamDecompression;
195

196
  private final DecompressorRegistry decompressorRegistry;
197
  private final CompressorRegistry compressorRegistry;
198

199
  private final Supplier<Stopwatch> stopwatchSupplier;
200
  /** The timeout before entering idle mode. */
201
  private final long idleTimeoutMillis;
202

203
  private final ConnectivityStateManager channelStateManager = new ConnectivityStateManager();
1✔
204
  private final BackoffPolicy.Provider backoffPolicyProvider;
205

206
  /**
207
   * We delegate to this channel, so that we can have interceptors as necessary. If there aren't
208
   * any interceptors and the {@link io.grpc.BinaryLog} is {@code null} then this will just be a
209
   * {@link RealChannel}.
210
   */
211
  private final Channel interceptorChannel;
212

213
  private final List<ClientTransportFilter> transportFilters;
214
  @Nullable private final String userAgent;
215

216
  // Only null after channel is terminated. Must be assigned from the syncContext.
217
  private NameResolver nameResolver;
218

219
  // Must be accessed from the syncContext.
220
  private boolean nameResolverStarted;
221

222
  // null when channel is in idle mode.  Must be assigned from syncContext.
223
  @Nullable
224
  private LbHelperImpl lbHelper;
225

226
  // Must ONLY be assigned from updateSubchannelPicker(), which is called from syncContext.
227
  // null if channel is in idle mode.
228
  @Nullable
229
  private volatile SubchannelPicker subchannelPicker;
230

231
  // Must be accessed from the syncContext
232
  private boolean panicMode;
233

234
  // Must be mutated from syncContext
235
  // If any monitoring hook to be added later needs to get a snapshot of this Set, we could
236
  // switch to a ConcurrentHashMap.
237
  private final Set<InternalSubchannel> subchannels = new HashSet<>(16, .75f);
1✔
238

239
  // Must be accessed from syncContext
240
  @Nullable
241
  private Collection<RealChannel.PendingCall<?, ?>> pendingCalls;
242
  private final Object pendingCallsInUseObject = new Object();
1✔
243

244
  // Must be mutated from syncContext
245
  private final Set<OobChannel> oobChannels = new HashSet<>(1, .75f);
1✔
246

247
  // reprocess() must be run from syncContext
248
  private final DelayedClientTransport delayedTransport;
249
  private final UncommittedRetriableStreamsRegistry uncommittedRetriableStreamsRegistry
1✔
250
      = new UncommittedRetriableStreamsRegistry();
251

252
  // Shutdown states.
253
  //
254
  // Channel's shutdown process:
255
  // 1. shutdown(): stop accepting new calls from applications
256
  //   1a shutdown <- true
257
  //   1b subchannelPicker <- null
258
  //   1c delayedTransport.shutdown()
259
  // 2. delayedTransport terminated: stop stream-creation functionality
260
  //   2a terminating <- true
261
  //   2b loadBalancer.shutdown()
262
  //     * LoadBalancer will shutdown subchannels and OOB channels
263
  //   2c loadBalancer <- null
264
  //   2d nameResolver.shutdown()
265
  //   2e nameResolver <- null
266
  // 3. All subchannels and OOB channels terminated: Channel considered terminated
267

268
  private final AtomicBoolean shutdown = new AtomicBoolean(false);
1✔
269
  // Must only be mutated and read from syncContext
270
  private boolean shutdownNowed;
271
  // Must only be mutated from syncContext
272
  private boolean terminating;
273
  // Must be mutated from syncContext
274
  private volatile boolean terminated;
275
  private final CountDownLatch terminatedLatch = new CountDownLatch(1);
1✔
276

277
  private final CallTracer.Factory callTracerFactory;
278
  private final CallTracer channelCallTracer;
279
  private final ChannelTracer channelTracer;
280
  private final ChannelLogger channelLogger;
281
  private final InternalChannelz channelz;
282
  private final RealChannel realChannel;
283
  // Must be mutated and read from syncContext
284
  // a flag for doing channel tracing when flipped
285
  private ResolutionState lastResolutionState = ResolutionState.NO_RESOLUTION;
1✔
286
  // Must be mutated and read from constructor or syncContext
287
  // used for channel tracing when value changed
288
  private ManagedChannelServiceConfig lastServiceConfig = EMPTY_SERVICE_CONFIG;
1✔
289

290
  @Nullable
291
  private final ManagedChannelServiceConfig defaultServiceConfig;
292
  // Must be mutated and read from constructor or syncContext
293
  private boolean serviceConfigUpdated = false;
1✔
294
  private final boolean lookUpServiceConfig;
295

296
  // One instance per channel.
297
  private final ChannelBufferMeter channelBufferUsed = new ChannelBufferMeter();
1✔
298

299
  private final long perRpcBufferLimit;
300
  private final long channelBufferLimit;
301

302
  // Temporary false flag that can skip the retry code path.
303
  private final boolean retryEnabled;
304

305
  private final Deadline.Ticker ticker = Deadline.getSystemTicker();
1✔
306

307
  // Called from syncContext
308
  private final ManagedClientTransport.Listener delayedTransportListener =
1✔
309
      new DelayedTransportListener();
310

311
  // Must be called from syncContext
312
  private void maybeShutdownNowSubchannels() {
313
    if (shutdownNowed) {
1✔
314
      for (InternalSubchannel subchannel : subchannels) {
1✔
315
        subchannel.shutdownNow(SHUTDOWN_NOW_STATUS);
1✔
316
      }
1✔
317
      for (OobChannel oobChannel : oobChannels) {
1✔
318
        oobChannel.getInternalSubchannel().shutdownNow(SHUTDOWN_NOW_STATUS);
1✔
319
      }
1✔
320
    }
321
  }
1✔
322

323
  // Must be accessed from syncContext
324
  @VisibleForTesting
1✔
325
  final InUseStateAggregator<Object> inUseStateAggregator = new IdleModeStateAggregator();
326

327
  @Override
328
  public ListenableFuture<ChannelStats> getStats() {
329
    final SettableFuture<ChannelStats> ret = SettableFuture.create();
1✔
330
    final class StatsFetcher implements Runnable {
1✔
331
      @Override
332
      public void run() {
333
        ChannelStats.Builder builder = new InternalChannelz.ChannelStats.Builder();
1✔
334
        channelCallTracer.updateBuilder(builder);
1✔
335
        channelTracer.updateBuilder(builder);
1✔
336
        builder.setTarget(target).setState(channelStateManager.getState());
1✔
337
        List<InternalWithLogId> children = new ArrayList<>();
1✔
338
        children.addAll(subchannels);
1✔
339
        children.addAll(oobChannels);
1✔
340
        builder.setSubchannels(children);
1✔
341
        ret.set(builder.build());
1✔
342
      }
1✔
343
    }
344

345
    // subchannels and oobchannels can only be accessed from syncContext
346
    syncContext.execute(new StatsFetcher());
1✔
347
    return ret;
1✔
348
  }
349

350
  @Override
351
  public InternalLogId getLogId() {
352
    return logId;
1✔
353
  }
354

355
  // Run from syncContext
356
  private class IdleModeTimer implements Runnable {
1✔
357

358
    @Override
359
    public void run() {
360
      // Workaround timer scheduled while in idle mode. This can happen from handleNotInUse() after
361
      // an explicit enterIdleMode() by the user. Protecting here as other locations are a bit too
362
      // subtle to change rapidly to resolve the channel panic. See #8714
363
      if (lbHelper == null) {
1✔
364
        return;
×
365
      }
366
      enterIdleMode();
1✔
367
    }
1✔
368
  }
369

370
  // Must be called from syncContext
371
  private void shutdownNameResolverAndLoadBalancer(boolean channelIsActive) {
372
    syncContext.throwIfNotInThisSynchronizationContext();
1✔
373
    if (channelIsActive) {
1✔
374
      checkState(nameResolverStarted, "nameResolver is not started");
1✔
375
      checkState(lbHelper != null, "lbHelper is null");
1✔
376
    }
377
    if (nameResolver != null) {
1✔
378
      nameResolver.shutdown();
1✔
379
      nameResolverStarted = false;
1✔
380
      if (channelIsActive) {
1✔
381
        nameResolver = getNameResolver(
1✔
382
            targetUri, authorityOverride, nameResolverProvider, nameResolverArgs);
383
      } else {
384
        nameResolver = null;
1✔
385
      }
386
    }
387
    if (lbHelper != null) {
1✔
388
      lbHelper.lb.shutdown();
1✔
389
      lbHelper = null;
1✔
390
    }
391
    subchannelPicker = null;
1✔
392
  }
1✔
393

394
  /**
395
   * Make the channel exit idle mode, if it's in it.
396
   *
397
   * <p>Must be called from syncContext
398
   */
399
  @VisibleForTesting
400
  void exitIdleMode() {
401
    syncContext.throwIfNotInThisSynchronizationContext();
1✔
402
    if (shutdown.get() || panicMode) {
1✔
403
      return;
1✔
404
    }
405
    if (inUseStateAggregator.isInUse()) {
1✔
406
      // Cancel the timer now, so that a racing due timer will not put Channel on idleness
407
      // when the caller of exitIdleMode() is about to use the returned loadBalancer.
408
      cancelIdleTimer(false);
1✔
409
    } else {
410
      // exitIdleMode() may be called outside of inUseStateAggregator.handleNotInUse() while
411
      // isInUse() == false, in which case we still need to schedule the timer.
412
      rescheduleIdleTimer();
1✔
413
    }
414
    if (lbHelper != null) {
1✔
415
      return;
1✔
416
    }
417
    channelLogger.log(ChannelLogLevel.INFO, "Exiting idle mode");
1✔
418
    LbHelperImpl lbHelper = new LbHelperImpl();
1✔
419
    lbHelper.lb = loadBalancerFactory.newLoadBalancer(lbHelper);
1✔
420
    // Delay setting lbHelper until fully initialized, since loadBalancerFactory is user code and
421
    // may throw. We don't want to confuse our state, even if we will enter panic mode.
422
    this.lbHelper = lbHelper;
1✔
423

424
    channelStateManager.gotoState(CONNECTING);
1✔
425
    NameResolverListener listener = new NameResolverListener(lbHelper, nameResolver);
1✔
426
    nameResolver.start(listener);
1✔
427
    nameResolverStarted = true;
1✔
428
  }
1✔
429

430
  // Must be run from syncContext
431
  private void enterIdleMode() {
432
    // nameResolver and loadBalancer are guaranteed to be non-null.  If any of them were null,
433
    // either the idleModeTimer ran twice without exiting the idle mode, or the task in shutdown()
434
    // did not cancel idleModeTimer, or enterIdle() ran while shutdown or in idle, all of
435
    // which are bugs.
436
    shutdownNameResolverAndLoadBalancer(true);
1✔
437
    delayedTransport.reprocess(null);
1✔
438
    channelLogger.log(ChannelLogLevel.INFO, "Entering IDLE state");
1✔
439
    channelStateManager.gotoState(IDLE);
1✔
440
    // If the inUseStateAggregator still considers pending calls to be queued up or the delayed
441
    // transport to be holding some we need to exit idle mode to give these calls a chance to
442
    // be processed.
443
    if (inUseStateAggregator.anyObjectInUse(pendingCallsInUseObject, delayedTransport)) {
1✔
444
      exitIdleMode();
1✔
445
    }
446
  }
1✔
447

448
  // Must be run from syncContext
449
  private void cancelIdleTimer(boolean permanent) {
450
    idleTimer.cancel(permanent);
1✔
451
  }
1✔
452

453
  // Always run from syncContext
454
  private void rescheduleIdleTimer() {
455
    if (idleTimeoutMillis == IDLE_TIMEOUT_MILLIS_DISABLE) {
1✔
456
      return;
1✔
457
    }
458
    idleTimer.reschedule(idleTimeoutMillis, TimeUnit.MILLISECONDS);
1✔
459
  }
1✔
460

461
  /**
462
   * Force name resolution refresh to happen immediately. Must be run
463
   * from syncContext.
464
   */
465
  private void refreshNameResolution() {
466
    syncContext.throwIfNotInThisSynchronizationContext();
1✔
467
    if (nameResolverStarted) {
1✔
468
      nameResolver.refresh();
1✔
469
    }
470
  }
1✔
471

472
  private final class ChannelStreamProvider implements ClientStreamProvider {
1✔
473
    volatile Throttle throttle;
474

475
    @Override
476
    public ClientStream newStream(
477
        final MethodDescriptor<?, ?> method,
478
        final CallOptions callOptions,
479
        final Metadata headers,
480
        final Context context) {
481
      // There is no need to reschedule the idle timer here. If the channel isn't shut down, either
482
      // the delayed transport or a real transport will go in-use and cancel the idle timer.
483
      if (!retryEnabled) {
1✔
484
        ClientStreamTracer[] tracers = GrpcUtil.getClientStreamTracers(
1✔
485
            callOptions, headers, 0, /* isTransparentRetry= */ false);
486
        Context origContext = context.attach();
1✔
487
        try {
488
          return delayedTransport.newStream(method, headers, callOptions, tracers);
1✔
489
        } finally {
490
          context.detach(origContext);
1✔
491
        }
492
      } else {
493
        MethodInfo methodInfo = callOptions.getOption(MethodInfo.KEY);
1✔
494
        final RetryPolicy retryPolicy = methodInfo == null ? null : methodInfo.retryPolicy;
1✔
495
        final HedgingPolicy hedgingPolicy = methodInfo == null ? null : methodInfo.hedgingPolicy;
1✔
496
        final class RetryStream<ReqT> extends RetriableStream<ReqT> {
497
          @SuppressWarnings("unchecked")
498
          RetryStream() {
1✔
499
            super(
1✔
500
                (MethodDescriptor<ReqT, ?>) method,
501
                headers,
502
                channelBufferUsed,
1✔
503
                perRpcBufferLimit,
1✔
504
                channelBufferLimit,
1✔
505
                getCallExecutor(callOptions),
1✔
506
                transportFactory.getScheduledExecutorService(),
1✔
507
                retryPolicy,
508
                hedgingPolicy,
509
                throttle);
510
          }
1✔
511

512
          @Override
513
          Status prestart() {
514
            return uncommittedRetriableStreamsRegistry.add(this);
1✔
515
          }
516

517
          @Override
518
          void postCommit() {
519
            uncommittedRetriableStreamsRegistry.remove(this);
1✔
520
          }
1✔
521

522
          @Override
523
          ClientStream newSubstream(
524
              Metadata newHeaders, ClientStreamTracer.Factory factory, int previousAttempts,
525
              boolean isTransparentRetry) {
526
            CallOptions newOptions = callOptions.withStreamTracerFactory(factory);
1✔
527
            ClientStreamTracer[] tracers = GrpcUtil.getClientStreamTracers(
1✔
528
                newOptions, newHeaders, previousAttempts, isTransparentRetry);
529
            Context origContext = context.attach();
1✔
530
            try {
531
              return delayedTransport.newStream(method, newHeaders, newOptions, tracers);
1✔
532
            } finally {
533
              context.detach(origContext);
1✔
534
            }
535
          }
536
        }
537

538
        return new RetryStream<>();
1✔
539
      }
540
    }
541
  }
542

543
  private final ChannelStreamProvider transportProvider = new ChannelStreamProvider();
1✔
544

545
  private final Rescheduler idleTimer;
546
  private final MetricRecorder metricRecorder;
547

548
  ManagedChannelImpl(
549
      ManagedChannelImplBuilder builder,
550
      ClientTransportFactory clientTransportFactory,
551
      URI targetUri,
552
      NameResolverProvider nameResolverProvider,
553
      BackoffPolicy.Provider backoffPolicyProvider,
554
      ObjectPool<? extends Executor> balancerRpcExecutorPool,
555
      Supplier<Stopwatch> stopwatchSupplier,
556
      List<ClientInterceptor> interceptors,
557
      final TimeProvider timeProvider) {
1✔
558
    this.target = checkNotNull(builder.target, "target");
1✔
559
    this.logId = InternalLogId.allocate("Channel", target);
1✔
560
    this.timeProvider = checkNotNull(timeProvider, "timeProvider");
1✔
561
    this.executorPool = checkNotNull(builder.executorPool, "executorPool");
1✔
562
    this.executor = checkNotNull(executorPool.getObject(), "executor");
1✔
563
    this.originalChannelCreds = builder.channelCredentials;
1✔
564
    this.originalTransportFactory = clientTransportFactory;
1✔
565
    this.offloadExecutorHolder =
1✔
566
        new ExecutorHolder(checkNotNull(builder.offloadExecutorPool, "offloadExecutorPool"));
1✔
567
    this.transportFactory = new CallCredentialsApplyingTransportFactory(
1✔
568
        clientTransportFactory, builder.callCredentials, this.offloadExecutorHolder);
569
    this.oobTransportFactory = new CallCredentialsApplyingTransportFactory(
1✔
570
        clientTransportFactory, null, this.offloadExecutorHolder);
571
    this.scheduledExecutor =
1✔
572
        new RestrictedScheduledExecutor(transportFactory.getScheduledExecutorService());
1✔
573
    maxTraceEvents = builder.maxTraceEvents;
1✔
574
    channelTracer = new ChannelTracer(
1✔
575
        logId, builder.maxTraceEvents, timeProvider.currentTimeNanos(),
1✔
576
        "Channel for '" + target + "'");
577
    channelLogger = new ChannelLoggerImpl(channelTracer, timeProvider);
1✔
578
    ProxyDetector proxyDetector =
579
        builder.proxyDetector != null ? builder.proxyDetector : GrpcUtil.DEFAULT_PROXY_DETECTOR;
1✔
580
    this.retryEnabled = builder.retryEnabled;
1✔
581
    this.loadBalancerFactory = new AutoConfiguredLoadBalancerFactory(builder.defaultLbPolicy);
1✔
582
    this.nameResolverRegistry = builder.nameResolverRegistry;
1✔
583
    this.targetUri = checkNotNull(targetUri, "targetUri");
1✔
584
    this.nameResolverProvider = checkNotNull(nameResolverProvider, "nameResolverProvider");
1✔
585
    ScParser serviceConfigParser =
1✔
586
        new ScParser(
587
            retryEnabled,
588
            builder.maxRetryAttempts,
589
            builder.maxHedgedAttempts,
590
            loadBalancerFactory);
591
    this.authorityOverride = builder.authorityOverride;
1✔
592
    this.metricRecorder = new MetricRecorderImpl(builder.metricSinks,
1✔
593
        MetricInstrumentRegistry.getDefaultRegistry());
1✔
594
    NameResolver.Args.Builder nameResolverArgsBuilder = NameResolver.Args.newBuilder()
1✔
595
            .setDefaultPort(builder.getDefaultPort())
1✔
596
            .setProxyDetector(proxyDetector)
1✔
597
            .setSynchronizationContext(syncContext)
1✔
598
            .setScheduledExecutorService(scheduledExecutor)
1✔
599
            .setServiceConfigParser(serviceConfigParser)
1✔
600
            .setChannelLogger(channelLogger)
1✔
601
            .setOffloadExecutor(this.offloadExecutorHolder)
1✔
602
            .setOverrideAuthority(this.authorityOverride)
1✔
603
            .setMetricRecorder(this.metricRecorder);
1✔
604
    builder.copyAllNameResolverCustomArgsTo(nameResolverArgsBuilder);
1✔
605
    this.nameResolverArgs = nameResolverArgsBuilder.build();
1✔
606
    this.nameResolver = getNameResolver(
1✔
607
        targetUri, authorityOverride, nameResolverProvider, nameResolverArgs);
608
    this.balancerRpcExecutorPool = checkNotNull(balancerRpcExecutorPool, "balancerRpcExecutorPool");
1✔
609
    this.balancerRpcExecutorHolder = new ExecutorHolder(balancerRpcExecutorPool);
1✔
610
    this.delayedTransport = new DelayedClientTransport(this.executor, this.syncContext);
1✔
611
    this.delayedTransport.start(delayedTransportListener);
1✔
612
    this.backoffPolicyProvider = backoffPolicyProvider;
1✔
613

614
    if (builder.defaultServiceConfig != null) {
1✔
615
      ConfigOrError parsedDefaultServiceConfig =
1✔
616
          serviceConfigParser.parseServiceConfig(builder.defaultServiceConfig);
1✔
617
      checkState(
1✔
618
          parsedDefaultServiceConfig.getError() == null,
1✔
619
          "Default config is invalid: %s",
620
          parsedDefaultServiceConfig.getError());
1✔
621
      this.defaultServiceConfig =
1✔
622
          (ManagedChannelServiceConfig) parsedDefaultServiceConfig.getConfig();
1✔
623
      this.transportProvider.throttle = this.defaultServiceConfig.getRetryThrottling();
1✔
624
    } else {
1✔
625
      this.defaultServiceConfig = null;
1✔
626
    }
627
    this.lookUpServiceConfig = builder.lookUpServiceConfig;
1✔
628
    realChannel = new RealChannel(nameResolver.getServiceAuthority());
1✔
629
    Channel channel = realChannel;
1✔
630
    if (builder.binlog != null) {
1✔
631
      channel = builder.binlog.wrapChannel(channel);
1✔
632
    }
633
    this.interceptorChannel = ClientInterceptors.intercept(channel, interceptors);
1✔
634
    this.transportFilters = new ArrayList<>(builder.transportFilters);
1✔
635
    this.stopwatchSupplier = checkNotNull(stopwatchSupplier, "stopwatchSupplier");
1✔
636
    if (builder.idleTimeoutMillis == IDLE_TIMEOUT_MILLIS_DISABLE) {
1✔
637
      this.idleTimeoutMillis = builder.idleTimeoutMillis;
1✔
638
    } else {
639
      checkArgument(
1✔
640
          builder.idleTimeoutMillis
641
              >= ManagedChannelImplBuilder.IDLE_MODE_MIN_TIMEOUT_MILLIS,
642
          "invalid idleTimeoutMillis %s", builder.idleTimeoutMillis);
643
      this.idleTimeoutMillis = builder.idleTimeoutMillis;
1✔
644
    }
645

646
    idleTimer = new Rescheduler(
1✔
647
        new IdleModeTimer(),
648
        syncContext,
649
        transportFactory.getScheduledExecutorService(),
1✔
650
        stopwatchSupplier.get());
1✔
651
    this.fullStreamDecompression = builder.fullStreamDecompression;
1✔
652
    this.decompressorRegistry = checkNotNull(builder.decompressorRegistry, "decompressorRegistry");
1✔
653
    this.compressorRegistry = checkNotNull(builder.compressorRegistry, "compressorRegistry");
1✔
654
    this.userAgent = builder.userAgent;
1✔
655

656
    this.channelBufferLimit = builder.retryBufferSize;
1✔
657
    this.perRpcBufferLimit = builder.perRpcBufferLimit;
1✔
658
    final class ChannelCallTracerFactory implements CallTracer.Factory {
1✔
659
      @Override
660
      public CallTracer create() {
661
        return new CallTracer(timeProvider);
1✔
662
      }
663
    }
664

665
    this.callTracerFactory = new ChannelCallTracerFactory();
1✔
666
    channelCallTracer = callTracerFactory.create();
1✔
667
    this.channelz = checkNotNull(builder.channelz);
1✔
668
    channelz.addRootChannel(this);
1✔
669

670
    if (!lookUpServiceConfig) {
1✔
671
      if (defaultServiceConfig != null) {
1✔
672
        channelLogger.log(
1✔
673
            ChannelLogLevel.INFO, "Service config look-up disabled, using default service config");
674
      }
675
      serviceConfigUpdated = true;
1✔
676
    }
677
  }
1✔
678

679
  @VisibleForTesting
680
  static NameResolver getNameResolver(
681
      URI targetUri, @Nullable final String overrideAuthority,
682
      NameResolverProvider provider, NameResolver.Args nameResolverArgs) {
683
    NameResolver resolver = provider.newNameResolver(targetUri, nameResolverArgs);
1✔
684
    if (resolver == null) {
1✔
685
      throw new IllegalArgumentException("cannot create a NameResolver for " + targetUri);
1✔
686
    }
687

688
    // We wrap the name resolver in a RetryingNameResolver to give it the ability to retry failures.
689
    // TODO: After a transition period, all NameResolver implementations that need retry should use
690
    //       RetryingNameResolver directly and this step can be removed.
691
    NameResolver usedNameResolver = new RetryingNameResolver(resolver,
1✔
692
          new BackoffPolicyRetryScheduler(new ExponentialBackoffPolicy.Provider(),
693
              nameResolverArgs.getScheduledExecutorService(),
1✔
694
              nameResolverArgs.getSynchronizationContext()),
1✔
695
          nameResolverArgs.getSynchronizationContext());
1✔
696

697
    if (overrideAuthority == null) {
1✔
698
      return usedNameResolver;
1✔
699
    }
700

701
    return new ForwardingNameResolver(usedNameResolver) {
1✔
702
      @Override
703
      public String getServiceAuthority() {
704
        return overrideAuthority;
1✔
705
      }
706
    };
707
  }
708

709
  @VisibleForTesting
710
  InternalConfigSelector getConfigSelector() {
711
    return realChannel.configSelector.get();
1✔
712
  }
713
  
714
  @VisibleForTesting
715
  boolean hasThrottle() {
716
    return this.transportProvider.throttle != null;
1✔
717
  }
718

719
  /**
720
   * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately
721
   * cancelled.
722
   */
723
  @Override
724
  public ManagedChannelImpl shutdown() {
725
    channelLogger.log(ChannelLogLevel.DEBUG, "shutdown() called");
1✔
726
    if (!shutdown.compareAndSet(false, true)) {
1✔
727
      return this;
1✔
728
    }
729
    final class Shutdown implements Runnable {
1✔
730
      @Override
731
      public void run() {
732
        channelLogger.log(ChannelLogLevel.INFO, "Entering SHUTDOWN state");
1✔
733
        channelStateManager.gotoState(SHUTDOWN);
1✔
734
      }
1✔
735
    }
736

737
    syncContext.execute(new Shutdown());
1✔
738
    realChannel.shutdown();
1✔
739
    final class CancelIdleTimer implements Runnable {
1✔
740
      @Override
741
      public void run() {
742
        cancelIdleTimer(/* permanent= */ true);
1✔
743
      }
1✔
744
    }
745

746
    syncContext.execute(new CancelIdleTimer());
1✔
747
    return this;
1✔
748
  }
749

750
  /**
751
   * Initiates a forceful shutdown in which preexisting and new calls are cancelled. Although
752
   * forceful, the shutdown process is still not instantaneous; {@link #isTerminated()} will likely
753
   * return {@code false} immediately after this method returns.
754
   */
755
  @Override
756
  public ManagedChannelImpl shutdownNow() {
757
    channelLogger.log(ChannelLogLevel.DEBUG, "shutdownNow() called");
1✔
758
    shutdown();
1✔
759
    realChannel.shutdownNow();
1✔
760
    final class ShutdownNow implements Runnable {
1✔
761
      @Override
762
      public void run() {
763
        if (shutdownNowed) {
1✔
764
          return;
1✔
765
        }
766
        shutdownNowed = true;
1✔
767
        maybeShutdownNowSubchannels();
1✔
768
      }
1✔
769
    }
770

771
    syncContext.execute(new ShutdownNow());
1✔
772
    return this;
1✔
773
  }
774

775
  // Called from syncContext
776
  @VisibleForTesting
777
  void panic(final Throwable t) {
778
    if (panicMode) {
1✔
779
      // Preserve the first panic information
780
      return;
×
781
    }
782
    panicMode = true;
1✔
783
    try {
784
      cancelIdleTimer(/* permanent= */ true);
1✔
785
      shutdownNameResolverAndLoadBalancer(false);
1✔
786
    } finally {
787
      updateSubchannelPicker(new LoadBalancer.FixedResultPicker(PickResult.withDrop(
1✔
788
          Status.INTERNAL.withDescription("Panic! This is a bug!").withCause(t))));
1✔
789
      realChannel.updateConfigSelector(null);
1✔
790
      channelLogger.log(ChannelLogLevel.ERROR, "PANIC! Entering TRANSIENT_FAILURE");
1✔
791
      channelStateManager.gotoState(TRANSIENT_FAILURE);
1✔
792
    }
793
  }
1✔
794

795
  @VisibleForTesting
796
  boolean isInPanicMode() {
797
    return panicMode;
1✔
798
  }
799

800
  // Called from syncContext
801
  private void updateSubchannelPicker(SubchannelPicker newPicker) {
802
    subchannelPicker = newPicker;
1✔
803
    delayedTransport.reprocess(newPicker);
1✔
804
  }
1✔
805

806
  @Override
807
  public boolean isShutdown() {
808
    return shutdown.get();
1✔
809
  }
810

811
  @Override
812
  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
813
    return terminatedLatch.await(timeout, unit);
1✔
814
  }
815

816
  @Override
817
  public boolean isTerminated() {
818
    return terminated;
1✔
819
  }
820

821
  /*
822
   * Creates a new outgoing call on the channel.
823
   */
824
  @Override
825
  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(MethodDescriptor<ReqT, RespT> method,
826
      CallOptions callOptions) {
827
    return interceptorChannel.newCall(method, callOptions);
1✔
828
  }
829

830
  @Override
831
  public String authority() {
832
    return interceptorChannel.authority();
1✔
833
  }
834

835
  private Executor getCallExecutor(CallOptions callOptions) {
836
    Executor executor = callOptions.getExecutor();
1✔
837
    if (executor == null) {
1✔
838
      executor = this.executor;
1✔
839
    }
840
    return executor;
1✔
841
  }
842

843
  private class RealChannel extends Channel {
844
    // Reference to null if no config selector is available from resolution result
845
    // Reference must be set() from syncContext
846
    private final AtomicReference<InternalConfigSelector> configSelector =
1✔
847
        new AtomicReference<>(INITIAL_PENDING_SELECTOR);
1✔
848
    // Set when the NameResolver is initially created. When we create a new NameResolver for the
849
    // same target, the new instance must have the same value.
850
    private final String authority;
851

852
    private final Channel clientCallImplChannel = new Channel() {
1✔
853
      @Override
854
      public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(
855
          MethodDescriptor<RequestT, ResponseT> method, CallOptions callOptions) {
856
        return new ClientCallImpl<>(
1✔
857
            method,
858
            getCallExecutor(callOptions),
1✔
859
            callOptions,
860
            transportProvider,
1✔
861
            terminated ? null : transportFactory.getScheduledExecutorService(),
1✔
862
            channelCallTracer,
1✔
863
            null)
864
            .setFullStreamDecompression(fullStreamDecompression)
1✔
865
            .setDecompressorRegistry(decompressorRegistry)
1✔
866
            .setCompressorRegistry(compressorRegistry);
1✔
867
      }
868

869
      @Override
870
      public String authority() {
871
        return authority;
×
872
      }
873
    };
874

875
    private RealChannel(String authority) {
1✔
876
      this.authority =  checkNotNull(authority, "authority");
1✔
877
    }
1✔
878

879
    @Override
880
    public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
881
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions) {
882
      if (configSelector.get() != INITIAL_PENDING_SELECTOR) {
1✔
883
        return newClientCall(method, callOptions);
1✔
884
      }
885
      syncContext.execute(new Runnable() {
1✔
886
        @Override
887
        public void run() {
888
          exitIdleMode();
1✔
889
        }
1✔
890
      });
891
      if (configSelector.get() != INITIAL_PENDING_SELECTOR) {
1✔
892
        // This is an optimization for the case (typically with InProcessTransport) when name
893
        // resolution result is immediately available at this point. Otherwise, some users'
894
        // tests might observe slight behavior difference from earlier grpc versions.
895
        return newClientCall(method, callOptions);
1✔
896
      }
897
      if (shutdown.get()) {
1✔
898
        // Return a failing ClientCall.
899
        return new ClientCall<ReqT, RespT>() {
×
900
          @Override
901
          public void start(Listener<RespT> responseListener, Metadata headers) {
902
            responseListener.onClose(SHUTDOWN_STATUS, new Metadata());
×
903
          }
×
904

905
          @Override public void request(int numMessages) {}
×
906

907
          @Override public void cancel(@Nullable String message, @Nullable Throwable cause) {}
×
908

909
          @Override public void halfClose() {}
×
910

911
          @Override public void sendMessage(ReqT message) {}
×
912
        };
913
      }
914
      Context context = Context.current();
1✔
915
      final PendingCall<ReqT, RespT> pendingCall = new PendingCall<>(context, method, callOptions);
1✔
916
      syncContext.execute(new Runnable() {
1✔
917
        @Override
918
        public void run() {
919
          if (configSelector.get() == INITIAL_PENDING_SELECTOR) {
1✔
920
            if (pendingCalls == null) {
1✔
921
              pendingCalls = new LinkedHashSet<>();
1✔
922
              inUseStateAggregator.updateObjectInUse(pendingCallsInUseObject, true);
1✔
923
            }
924
            pendingCalls.add(pendingCall);
1✔
925
          } else {
926
            pendingCall.reprocess();
1✔
927
          }
928
        }
1✔
929
      });
930
      return pendingCall;
1✔
931
    }
932

933
    // Must run in SynchronizationContext.
934
    void updateConfigSelector(@Nullable InternalConfigSelector config) {
935
      InternalConfigSelector prevConfig = configSelector.get();
1✔
936
      configSelector.set(config);
1✔
937
      if (prevConfig == INITIAL_PENDING_SELECTOR && pendingCalls != null) {
1✔
938
        for (RealChannel.PendingCall<?, ?> pendingCall : pendingCalls) {
1✔
939
          pendingCall.reprocess();
1✔
940
        }
1✔
941
      }
942
    }
1✔
943

944
    // Must run in SynchronizationContext.
945
    void onConfigError() {
946
      if (configSelector.get() == INITIAL_PENDING_SELECTOR) {
1✔
947
        // Apply Default Service Config if initial name resolution fails.
948
        if (defaultServiceConfig != null) {
1✔
949
          updateConfigSelector(defaultServiceConfig.getDefaultConfigSelector());
1✔
950
          lastServiceConfig = defaultServiceConfig;
1✔
951
          channelLogger.log(ChannelLogLevel.ERROR,
1✔
952
              "Initial Name Resolution error, using default service config");
953
        } else {
954
          updateConfigSelector(null);
1✔
955
        }
956
      }
957
    }
1✔
958

959
    void shutdown() {
960
      final class RealChannelShutdown implements Runnable {
1✔
961
        @Override
962
        public void run() {
963
          if (pendingCalls == null) {
1✔
964
            if (configSelector.get() == INITIAL_PENDING_SELECTOR) {
1✔
965
              configSelector.set(null);
1✔
966
            }
967
            uncommittedRetriableStreamsRegistry.onShutdown(SHUTDOWN_STATUS);
1✔
968
          }
969
        }
1✔
970
      }
971

972
      syncContext.execute(new RealChannelShutdown());
1✔
973
    }
1✔
974

975
    void shutdownNow() {
976
      final class RealChannelShutdownNow implements Runnable {
1✔
977
        @Override
978
        public void run() {
979
          if (configSelector.get() == INITIAL_PENDING_SELECTOR) {
1✔
980
            configSelector.set(null);
1✔
981
          }
982
          if (pendingCalls != null) {
1✔
983
            for (RealChannel.PendingCall<?, ?> pendingCall : pendingCalls) {
1✔
984
              pendingCall.cancel("Channel is forcefully shutdown", null);
1✔
985
            }
1✔
986
          }
987
          uncommittedRetriableStreamsRegistry.onShutdownNow(SHUTDOWN_NOW_STATUS);
1✔
988
        }
1✔
989
      }
990

991
      syncContext.execute(new RealChannelShutdownNow());
1✔
992
    }
1✔
993

994
    @Override
995
    public String authority() {
996
      return authority;
1✔
997
    }
998

999
    private final class PendingCall<ReqT, RespT> extends DelayedClientCall<ReqT, RespT> {
1000
      final Context context;
1001
      final MethodDescriptor<ReqT, RespT> method;
1002
      final CallOptions callOptions;
1003
      private final long callCreationTime;
1004

1005
      PendingCall(
1006
          Context context, MethodDescriptor<ReqT, RespT> method, CallOptions callOptions) {
1✔
1007
        super(getCallExecutor(callOptions), scheduledExecutor, callOptions.getDeadline());
1✔
1008
        this.context = context;
1✔
1009
        this.method = method;
1✔
1010
        this.callOptions = callOptions;
1✔
1011
        this.callCreationTime = ticker.nanoTime();
1✔
1012
      }
1✔
1013

1014
      /** Called when it's ready to create a real call and reprocess the pending call. */
1015
      void reprocess() {
1016
        ClientCall<ReqT, RespT> realCall;
1017
        Context previous = context.attach();
1✔
1018
        try {
1019
          CallOptions delayResolutionOption = callOptions.withOption(NAME_RESOLUTION_DELAYED,
1✔
1020
              ticker.nanoTime() - callCreationTime);
1✔
1021
          realCall = newClientCall(method, delayResolutionOption);
1✔
1022
        } finally {
1023
          context.detach(previous);
1✔
1024
        }
1025
        Runnable toRun = setCall(realCall);
1✔
1026
        if (toRun == null) {
1✔
1027
          syncContext.execute(new PendingCallRemoval());
1✔
1028
        } else {
1029
          getCallExecutor(callOptions).execute(new Runnable() {
1✔
1030
            @Override
1031
            public void run() {
1032
              toRun.run();
1✔
1033
              syncContext.execute(new PendingCallRemoval());
1✔
1034
            }
1✔
1035
          });
1036
        }
1037
      }
1✔
1038

1039
      @Override
1040
      protected void callCancelled() {
1041
        super.callCancelled();
1✔
1042
        syncContext.execute(new PendingCallRemoval());
1✔
1043
      }
1✔
1044

1045
      final class PendingCallRemoval implements Runnable {
1✔
1046
        @Override
1047
        public void run() {
1048
          if (pendingCalls != null) {
1✔
1049
            pendingCalls.remove(PendingCall.this);
1✔
1050
            if (pendingCalls.isEmpty()) {
1✔
1051
              inUseStateAggregator.updateObjectInUse(pendingCallsInUseObject, false);
1✔
1052
              pendingCalls = null;
1✔
1053
              if (shutdown.get()) {
1✔
1054
                uncommittedRetriableStreamsRegistry.onShutdown(SHUTDOWN_STATUS);
1✔
1055
              }
1056
            }
1057
          }
1058
        }
1✔
1059
      }
1060
    }
1061

1062
    private <ReqT, RespT> ClientCall<ReqT, RespT> newClientCall(
1063
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions) {
1064
      InternalConfigSelector selector = configSelector.get();
1✔
1065
      if (selector == null) {
1✔
1066
        return clientCallImplChannel.newCall(method, callOptions);
1✔
1067
      }
1068
      if (selector instanceof ServiceConfigConvertedSelector) {
1✔
1069
        MethodInfo methodInfo =
1✔
1070
            ((ServiceConfigConvertedSelector) selector).config.getMethodConfig(method);
1✔
1071
        if (methodInfo != null) {
1✔
1072
          callOptions = callOptions.withOption(MethodInfo.KEY, methodInfo);
1✔
1073
        }
1074
        return clientCallImplChannel.newCall(method, callOptions);
1✔
1075
      }
1076
      return new ConfigSelectingClientCall<>(
1✔
1077
          selector, clientCallImplChannel, executor, method, callOptions);
1✔
1078
    }
1079
  }
1080

1081
  /**
1082
   * A client call for a given channel that applies a given config selector when it starts.
1083
   */
1084
  static final class ConfigSelectingClientCall<ReqT, RespT>
1085
      extends ForwardingClientCall<ReqT, RespT> {
1086

1087
    private final InternalConfigSelector configSelector;
1088
    private final Channel channel;
1089
    private final Executor callExecutor;
1090
    private final MethodDescriptor<ReqT, RespT> method;
1091
    private final Context context;
1092
    private CallOptions callOptions;
1093

1094
    private ClientCall<ReqT, RespT> delegate;
1095

1096
    ConfigSelectingClientCall(
1097
        InternalConfigSelector configSelector, Channel channel, Executor channelExecutor,
1098
        MethodDescriptor<ReqT, RespT> method,
1099
        CallOptions callOptions) {
1✔
1100
      this.configSelector = configSelector;
1✔
1101
      this.channel = channel;
1✔
1102
      this.method = method;
1✔
1103
      this.callExecutor =
1✔
1104
          callOptions.getExecutor() == null ? channelExecutor : callOptions.getExecutor();
1✔
1105
      this.callOptions = callOptions.withExecutor(callExecutor);
1✔
1106
      this.context = Context.current();
1✔
1107
    }
1✔
1108

1109
    @Override
1110
    protected ClientCall<ReqT, RespT> delegate() {
1111
      return delegate;
1✔
1112
    }
1113

1114
    @SuppressWarnings("unchecked")
1115
    @Override
1116
    public void start(Listener<RespT> observer, Metadata headers) {
1117
      PickSubchannelArgs args =
1✔
1118
          new PickSubchannelArgsImpl(method, headers, callOptions, NOOP_PICK_DETAILS_CONSUMER);
1✔
1119
      InternalConfigSelector.Result result = configSelector.selectConfig(args);
1✔
1120
      Status status = result.getStatus();
1✔
1121
      if (!status.isOk()) {
1✔
1122
        executeCloseObserverInContext(observer,
1✔
1123
            GrpcUtil.replaceInappropriateControlPlaneStatus(status));
1✔
1124
        delegate = (ClientCall<ReqT, RespT>) NOOP_CALL;
1✔
1125
        return;
1✔
1126
      }
1127
      ClientInterceptor interceptor = result.getInterceptor();
1✔
1128
      ManagedChannelServiceConfig config = (ManagedChannelServiceConfig) result.getConfig();
1✔
1129
      MethodInfo methodInfo = config.getMethodConfig(method);
1✔
1130
      if (methodInfo != null) {
1✔
1131
        callOptions = callOptions.withOption(MethodInfo.KEY, methodInfo);
1✔
1132
      }
1133
      if (interceptor != null) {
1✔
1134
        delegate = interceptor.interceptCall(method, callOptions, channel);
1✔
1135
      } else {
1136
        delegate = channel.newCall(method, callOptions);
×
1137
      }
1138
      delegate.start(observer, headers);
1✔
1139
    }
1✔
1140

1141
    private void executeCloseObserverInContext(
1142
        final Listener<RespT> observer, final Status status) {
1143
      class CloseInContext extends ContextRunnable {
1144
        CloseInContext() {
1✔
1145
          super(context);
1✔
1146
        }
1✔
1147

1148
        @Override
1149
        public void runInContext() {
1150
          observer.onClose(status, new Metadata());
1✔
1151
        }
1✔
1152
      }
1153

1154
      callExecutor.execute(new CloseInContext());
1✔
1155
    }
1✔
1156

1157
    @Override
1158
    public void cancel(@Nullable String message, @Nullable Throwable cause) {
1159
      if (delegate != null) {
×
1160
        delegate.cancel(message, cause);
×
1161
      }
1162
    }
×
1163
  }
1164

1165
  private static final ClientCall<Object, Object> NOOP_CALL = new ClientCall<Object, Object>() {
1✔
1166
    @Override
1167
    public void start(Listener<Object> responseListener, Metadata headers) {}
×
1168

1169
    @Override
1170
    public void request(int numMessages) {}
1✔
1171

1172
    @Override
1173
    public void cancel(String message, Throwable cause) {}
×
1174

1175
    @Override
1176
    public void halfClose() {}
×
1177

1178
    @Override
1179
    public void sendMessage(Object message) {}
×
1180

1181
    // Always returns {@code false}, since this is only used when the startup of the call fails.
1182
    @Override
1183
    public boolean isReady() {
1184
      return false;
×
1185
    }
1186
  };
1187

1188
  /**
1189
   * Terminate the channel if termination conditions are met.
1190
   */
1191
  // Must be run from syncContext
1192
  private void maybeTerminateChannel() {
1193
    if (terminated) {
1✔
1194
      return;
×
1195
    }
1196
    if (shutdown.get() && subchannels.isEmpty() && oobChannels.isEmpty()) {
1✔
1197
      channelLogger.log(ChannelLogLevel.INFO, "Terminated");
1✔
1198
      channelz.removeRootChannel(this);
1✔
1199
      executorPool.returnObject(executor);
1✔
1200
      balancerRpcExecutorHolder.release();
1✔
1201
      offloadExecutorHolder.release();
1✔
1202
      // Release the transport factory so that it can deallocate any resources.
1203
      transportFactory.close();
1✔
1204

1205
      terminated = true;
1✔
1206
      terminatedLatch.countDown();
1✔
1207
    }
1208
  }
1✔
1209

1210
  // Must be called from syncContext
1211
  private void handleInternalSubchannelState(ConnectivityStateInfo newState) {
1212
    if (newState.getState() == TRANSIENT_FAILURE || newState.getState() == IDLE) {
1✔
1213
      refreshNameResolution();
1✔
1214
    }
1215
  }
1✔
1216

1217
  @Override
1218
  @SuppressWarnings("deprecation")
1219
  public ConnectivityState getState(boolean requestConnection) {
1220
    ConnectivityState savedChannelState = channelStateManager.getState();
1✔
1221
    if (requestConnection && savedChannelState == IDLE) {
1✔
1222
      final class RequestConnection implements Runnable {
1✔
1223
        @Override
1224
        public void run() {
1225
          exitIdleMode();
1✔
1226
          if (subchannelPicker != null) {
1✔
1227
            subchannelPicker.requestConnection();
1✔
1228
          }
1229
          if (lbHelper != null) {
1✔
1230
            lbHelper.lb.requestConnection();
1✔
1231
          }
1232
        }
1✔
1233
      }
1234

1235
      syncContext.execute(new RequestConnection());
1✔
1236
    }
1237
    return savedChannelState;
1✔
1238
  }
1239

1240
  @Override
1241
  public void notifyWhenStateChanged(final ConnectivityState source, final Runnable callback) {
1242
    final class NotifyStateChanged implements Runnable {
1✔
1243
      @Override
1244
      public void run() {
1245
        channelStateManager.notifyWhenStateChanged(callback, executor, source);
1✔
1246
      }
1✔
1247
    }
1248

1249
    syncContext.execute(new NotifyStateChanged());
1✔
1250
  }
1✔
1251

1252
  @Override
1253
  public void resetConnectBackoff() {
1254
    final class ResetConnectBackoff implements Runnable {
1✔
1255
      @Override
1256
      public void run() {
1257
        if (shutdown.get()) {
1✔
1258
          return;
1✔
1259
        }
1260
        if (nameResolverStarted) {
1✔
1261
          refreshNameResolution();
1✔
1262
        }
1263
        for (InternalSubchannel subchannel : subchannels) {
1✔
1264
          subchannel.resetConnectBackoff();
1✔
1265
        }
1✔
1266
        for (OobChannel oobChannel : oobChannels) {
1✔
1267
          oobChannel.resetConnectBackoff();
×
1268
        }
×
1269
      }
1✔
1270
    }
1271

1272
    syncContext.execute(new ResetConnectBackoff());
1✔
1273
  }
1✔
1274

1275
  @Override
1276
  public void enterIdle() {
1277
    final class PrepareToLoseNetworkRunnable implements Runnable {
1✔
1278
      @Override
1279
      public void run() {
1280
        if (shutdown.get() || lbHelper == null) {
1✔
1281
          return;
1✔
1282
        }
1283
        cancelIdleTimer(/* permanent= */ false);
1✔
1284
        enterIdleMode();
1✔
1285
      }
1✔
1286
    }
1287

1288
    syncContext.execute(new PrepareToLoseNetworkRunnable());
1✔
1289
  }
1✔
1290

1291
  /**
1292
   * A registry that prevents channel shutdown from killing existing retry attempts that are in
1293
   * backoff.
1294
   */
1295
  private final class UncommittedRetriableStreamsRegistry {
1✔
1296
    // TODO(zdapeng): This means we would acquire a lock for each new retry-able stream,
1297
    // it's worthwhile to look for a lock-free approach.
1298
    final Object lock = new Object();
1✔
1299

1300
    @GuardedBy("lock")
1✔
1301
    Collection<ClientStream> uncommittedRetriableStreams = new HashSet<>();
1302

1303
    @GuardedBy("lock")
1304
    Status shutdownStatus;
1305

1306
    void onShutdown(Status reason) {
1307
      boolean shouldShutdownDelayedTransport = false;
1✔
1308
      synchronized (lock) {
1✔
1309
        if (shutdownStatus != null) {
1✔
1310
          return;
1✔
1311
        }
1312
        shutdownStatus = reason;
1✔
1313
        // Keep the delayedTransport open until there is no more uncommitted streams, b/c those
1314
        // retriable streams, which may be in backoff and not using any transport, are already
1315
        // started RPCs.
1316
        if (uncommittedRetriableStreams.isEmpty()) {
1✔
1317
          shouldShutdownDelayedTransport = true;
1✔
1318
        }
1319
      }
1✔
1320

1321
      if (shouldShutdownDelayedTransport) {
1✔
1322
        delayedTransport.shutdown(reason);
1✔
1323
      }
1324
    }
1✔
1325

1326
    void onShutdownNow(Status reason) {
1327
      onShutdown(reason);
1✔
1328
      Collection<ClientStream> streams;
1329

1330
      synchronized (lock) {
1✔
1331
        streams = new ArrayList<>(uncommittedRetriableStreams);
1✔
1332
      }
1✔
1333

1334
      for (ClientStream stream : streams) {
1✔
1335
        stream.cancel(reason);
1✔
1336
      }
1✔
1337
      delayedTransport.shutdownNow(reason);
1✔
1338
    }
1✔
1339

1340
    /**
1341
     * Registers a RetriableStream and return null if not shutdown, otherwise just returns the
1342
     * shutdown Status.
1343
     */
1344
    @Nullable
1345
    Status add(RetriableStream<?> retriableStream) {
1346
      synchronized (lock) {
1✔
1347
        if (shutdownStatus != null) {
1✔
1348
          return shutdownStatus;
1✔
1349
        }
1350
        uncommittedRetriableStreams.add(retriableStream);
1✔
1351
        return null;
1✔
1352
      }
1353
    }
1354

1355
    void remove(RetriableStream<?> retriableStream) {
1356
      Status shutdownStatusCopy = null;
1✔
1357

1358
      synchronized (lock) {
1✔
1359
        uncommittedRetriableStreams.remove(retriableStream);
1✔
1360
        if (uncommittedRetriableStreams.isEmpty()) {
1✔
1361
          shutdownStatusCopy = shutdownStatus;
1✔
1362
          // Because retriable transport is long-lived, we take this opportunity to down-size the
1363
          // hashmap.
1364
          uncommittedRetriableStreams = new HashSet<>();
1✔
1365
        }
1366
      }
1✔
1367

1368
      if (shutdownStatusCopy != null) {
1✔
1369
        delayedTransport.shutdown(shutdownStatusCopy);
1✔
1370
      }
1371
    }
1✔
1372
  }
1373

1374
  private final class LbHelperImpl extends LoadBalancer.Helper {
1✔
1375
    AutoConfiguredLoadBalancer lb;
1376

1377
    @Override
1378
    public AbstractSubchannel createSubchannel(CreateSubchannelArgs args) {
1379
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1380
      // No new subchannel should be created after load balancer has been shutdown.
1381
      checkState(!terminating, "Channel is being terminated");
1✔
1382
      return new SubchannelImpl(args);
1✔
1383
    }
1384

1385
    @Override
1386
    public void updateBalancingState(
1387
        final ConnectivityState newState, final SubchannelPicker newPicker) {
1388
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1389
      checkNotNull(newState, "newState");
1✔
1390
      checkNotNull(newPicker, "newPicker");
1✔
1391

1392
      if (LbHelperImpl.this != lbHelper || panicMode) {
1✔
1393
        return;
1✔
1394
      }
1395
      updateSubchannelPicker(newPicker);
1✔
1396
      // It's not appropriate to report SHUTDOWN state from lb.
1397
      // Ignore the case of newState == SHUTDOWN for now.
1398
      if (newState != SHUTDOWN) {
1✔
1399
        channelLogger.log(
1✔
1400
            ChannelLogLevel.INFO, "Entering {0} state with picker: {1}", newState, newPicker);
1401
        channelStateManager.gotoState(newState);
1✔
1402
      }
1403
    }
1✔
1404

1405
    @Override
1406
    public void refreshNameResolution() {
1407
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1408
      final class LoadBalancerRefreshNameResolution implements Runnable {
1✔
1409
        @Override
1410
        public void run() {
1411
          ManagedChannelImpl.this.refreshNameResolution();
1✔
1412
        }
1✔
1413
      }
1414

1415
      syncContext.execute(new LoadBalancerRefreshNameResolution());
1✔
1416
    }
1✔
1417

1418
    @Override
1419
    public ManagedChannel createOobChannel(EquivalentAddressGroup addressGroup, String authority) {
1420
      return createOobChannel(Collections.singletonList(addressGroup), authority);
×
1421
    }
1422

1423
    @Override
1424
    public ManagedChannel createOobChannel(List<EquivalentAddressGroup> addressGroup,
1425
        String authority) {
1426
      // TODO(ejona): can we be even stricter? Like terminating?
1427
      checkState(!terminated, "Channel is terminated");
1✔
1428
      long oobChannelCreationTime = timeProvider.currentTimeNanos();
1✔
1429
      InternalLogId oobLogId = InternalLogId.allocate("OobChannel", /*details=*/ null);
1✔
1430
      InternalLogId subchannelLogId =
1✔
1431
          InternalLogId.allocate("Subchannel-OOB", /*details=*/ authority);
1✔
1432
      ChannelTracer oobChannelTracer =
1✔
1433
          new ChannelTracer(
1434
              oobLogId, maxTraceEvents, oobChannelCreationTime,
1✔
1435
              "OobChannel for " + addressGroup);
1436
      final OobChannel oobChannel = new OobChannel(
1✔
1437
          authority, balancerRpcExecutorPool, oobTransportFactory.getScheduledExecutorService(),
1✔
1438
          syncContext, callTracerFactory.create(), oobChannelTracer, channelz, timeProvider);
1✔
1439
      channelTracer.reportEvent(new ChannelTrace.Event.Builder()
1✔
1440
          .setDescription("Child OobChannel created")
1✔
1441
          .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
1✔
1442
          .setTimestampNanos(oobChannelCreationTime)
1✔
1443
          .setChannelRef(oobChannel)
1✔
1444
          .build());
1✔
1445
      ChannelTracer subchannelTracer =
1✔
1446
          new ChannelTracer(subchannelLogId, maxTraceEvents, oobChannelCreationTime,
1✔
1447
              "Subchannel for " + addressGroup);
1448
      ChannelLogger subchannelLogger = new ChannelLoggerImpl(subchannelTracer, timeProvider);
1✔
1449
      final class ManagedOobChannelCallback extends InternalSubchannel.Callback {
1✔
1450
        @Override
1451
        void onTerminated(InternalSubchannel is) {
1452
          oobChannels.remove(oobChannel);
1✔
1453
          channelz.removeSubchannel(is);
1✔
1454
          oobChannel.handleSubchannelTerminated();
1✔
1455
          maybeTerminateChannel();
1✔
1456
        }
1✔
1457

1458
        @Override
1459
        void onStateChange(InternalSubchannel is, ConnectivityStateInfo newState) {
1460
          // TODO(chengyuanzhang): change to let LB policies explicitly manage OOB channel's
1461
          //  state and refresh name resolution if necessary.
1462
          handleInternalSubchannelState(newState);
1✔
1463
          oobChannel.handleSubchannelStateChange(newState);
1✔
1464
        }
1✔
1465
      }
1466

1467
      final InternalSubchannel internalSubchannel = new InternalSubchannel(
1✔
1468
          CreateSubchannelArgs.newBuilder().setAddresses(addressGroup).build(),
1✔
1469
          authority, userAgent, backoffPolicyProvider, oobTransportFactory,
1✔
1470
          oobTransportFactory.getScheduledExecutorService(), stopwatchSupplier, syncContext,
1✔
1471
          // All callback methods are run from syncContext
1472
          new ManagedOobChannelCallback(),
1473
          channelz,
1✔
1474
          callTracerFactory.create(),
1✔
1475
          subchannelTracer,
1476
          subchannelLogId,
1477
          subchannelLogger,
1478
          transportFilters);
1✔
1479
      oobChannelTracer.reportEvent(new ChannelTrace.Event.Builder()
1✔
1480
          .setDescription("Child Subchannel created")
1✔
1481
          .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
1✔
1482
          .setTimestampNanos(oobChannelCreationTime)
1✔
1483
          .setSubchannelRef(internalSubchannel)
1✔
1484
          .build());
1✔
1485
      channelz.addSubchannel(oobChannel);
1✔
1486
      channelz.addSubchannel(internalSubchannel);
1✔
1487
      oobChannel.setSubchannel(internalSubchannel);
1✔
1488
      final class AddOobChannel implements Runnable {
1✔
1489
        @Override
1490
        public void run() {
1491
          if (terminating) {
1✔
1492
            oobChannel.shutdown();
×
1493
          }
1494
          if (!terminated) {
1✔
1495
            // If channel has not terminated, it will track the subchannel and block termination
1496
            // for it.
1497
            oobChannels.add(oobChannel);
1✔
1498
          }
1499
        }
1✔
1500
      }
1501

1502
      syncContext.execute(new AddOobChannel());
1✔
1503
      return oobChannel;
1✔
1504
    }
1505

1506
    @Deprecated
1507
    @Override
1508
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
1509
      return createResolvingOobChannelBuilder(target, new DefaultChannelCreds())
1✔
1510
          // Override authority to keep the old behavior.
1511
          // createResolvingOobChannelBuilder(String target) will be deleted soon.
1512
          .overrideAuthority(getAuthority());
1✔
1513
    }
1514

1515
    // TODO(creamsoup) prevent main channel to shutdown if oob channel is not terminated
1516
    // TODO(zdapeng) register the channel as a subchannel of the parent channel in channelz.
1517
    @Override
1518
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1519
        final String target, final ChannelCredentials channelCreds) {
1520
      checkNotNull(channelCreds, "channelCreds");
1✔
1521

1522
      final class ResolvingOobChannelBuilder
1523
          extends ForwardingChannelBuilder2<ResolvingOobChannelBuilder> {
1524
        final ManagedChannelBuilder<?> delegate;
1525

1526
        ResolvingOobChannelBuilder() {
1✔
1527
          final ClientTransportFactory transportFactory;
1528
          CallCredentials callCredentials;
1529
          if (channelCreds instanceof DefaultChannelCreds) {
1✔
1530
            transportFactory = originalTransportFactory;
1✔
1531
            callCredentials = null;
1✔
1532
          } else {
1533
            SwapChannelCredentialsResult swapResult =
1✔
1534
                originalTransportFactory.swapChannelCredentials(channelCreds);
1✔
1535
            if (swapResult == null) {
1✔
1536
              delegate = Grpc.newChannelBuilder(target, channelCreds);
×
1537
              return;
×
1538
            } else {
1539
              transportFactory = swapResult.transportFactory;
1✔
1540
              callCredentials = swapResult.callCredentials;
1✔
1541
            }
1542
          }
1543
          ClientTransportFactoryBuilder transportFactoryBuilder =
1✔
1544
              new ClientTransportFactoryBuilder() {
1✔
1545
                @Override
1546
                public ClientTransportFactory buildClientTransportFactory() {
1547
                  return transportFactory;
1✔
1548
                }
1549
              };
1550
          delegate = new ManagedChannelImplBuilder(
1✔
1551
              target,
1552
              channelCreds,
1553
              callCredentials,
1554
              transportFactoryBuilder,
1555
              new FixedPortProvider(nameResolverArgs.getDefaultPort()))
1✔
1556
              .nameResolverRegistry(nameResolverRegistry);
1✔
1557
        }
1✔
1558

1559
        @Override
1560
        protected ManagedChannelBuilder<?> delegate() {
1561
          return delegate;
1✔
1562
        }
1563
      }
1564

1565
      checkState(!terminated, "Channel is terminated");
1✔
1566

1567
      @SuppressWarnings("deprecation")
1568
      ResolvingOobChannelBuilder builder = new ResolvingOobChannelBuilder();
1✔
1569

1570
      return builder
1✔
1571
          // TODO(zdapeng): executors should not outlive the parent channel.
1572
          .executor(executor)
1✔
1573
          .offloadExecutor(offloadExecutorHolder.getExecutor())
1✔
1574
          .maxTraceEvents(maxTraceEvents)
1✔
1575
          .proxyDetector(nameResolverArgs.getProxyDetector())
1✔
1576
          .userAgent(userAgent);
1✔
1577
    }
1578

1579
    @Override
1580
    public ChannelCredentials getUnsafeChannelCredentials() {
1581
      if (originalChannelCreds == null) {
1✔
1582
        return new DefaultChannelCreds();
1✔
1583
      }
1584
      return originalChannelCreds;
×
1585
    }
1586

1587
    @Override
1588
    public void updateOobChannelAddresses(ManagedChannel channel, EquivalentAddressGroup eag) {
1589
      updateOobChannelAddresses(channel, Collections.singletonList(eag));
×
1590
    }
×
1591

1592
    @Override
1593
    public void updateOobChannelAddresses(ManagedChannel channel,
1594
        List<EquivalentAddressGroup> eag) {
1595
      checkArgument(channel instanceof OobChannel,
1✔
1596
          "channel must have been returned from createOobChannel");
1597
      ((OobChannel) channel).updateAddresses(eag);
1✔
1598
    }
1✔
1599

1600
    @Override
1601
    public String getAuthority() {
1602
      return ManagedChannelImpl.this.authority();
1✔
1603
    }
1604

1605
    @Override
1606
    public String getChannelTarget() {
1607
      return targetUri.toString();
1✔
1608
    }
1609

1610
    @Override
1611
    public SynchronizationContext getSynchronizationContext() {
1612
      return syncContext;
1✔
1613
    }
1614

1615
    @Override
1616
    public ScheduledExecutorService getScheduledExecutorService() {
1617
      return scheduledExecutor;
1✔
1618
    }
1619

1620
    @Override
1621
    public ChannelLogger getChannelLogger() {
1622
      return channelLogger;
1✔
1623
    }
1624

1625
    @Override
1626
    public NameResolver.Args getNameResolverArgs() {
1627
      return nameResolverArgs;
1✔
1628
    }
1629

1630
    @Override
1631
    public NameResolverRegistry getNameResolverRegistry() {
1632
      return nameResolverRegistry;
1✔
1633
    }
1634

1635
    @Override
1636
    public MetricRecorder getMetricRecorder() {
1637
      return metricRecorder;
1✔
1638
    }
1639

1640
    /**
1641
     * A placeholder for channel creds if user did not specify channel creds for the channel.
1642
     */
1643
    // TODO(zdapeng): get rid of this class and let all ChannelBuilders always provide a non-null
1644
    //     channel creds.
1645
    final class DefaultChannelCreds extends ChannelCredentials {
1✔
1646
      @Override
1647
      public ChannelCredentials withoutBearerTokens() {
1648
        return this;
×
1649
      }
1650
    }
1651
  }
1652

1653
  final class NameResolverListener extends NameResolver.Listener2 {
1654
    final LbHelperImpl helper;
1655
    final NameResolver resolver;
1656

1657
    NameResolverListener(LbHelperImpl helperImpl, NameResolver resolver) {
1✔
1658
      this.helper = checkNotNull(helperImpl, "helperImpl");
1✔
1659
      this.resolver = checkNotNull(resolver, "resolver");
1✔
1660
    }
1✔
1661

1662
    @Override
1663
    public void onResult(final ResolutionResult resolutionResult) {
1664
      final class NamesResolved implements Runnable {
1✔
1665

1666
        @Override
1667
        public void run() {
1668
          Status status = onResult2(resolutionResult);
1✔
1669
          ResolutionResultListener resolutionResultListener = resolutionResult.getAttributes()
1✔
1670
              .get(RetryingNameResolver.RESOLUTION_RESULT_LISTENER_KEY);
1✔
1671
          resolutionResultListener.resolutionAttempted(status);
1✔
1672
        }
1✔
1673
      }
1674

1675
      syncContext.execute(new NamesResolved());
1✔
1676
    }
1✔
1677

1678
    @SuppressWarnings("ReferenceEquality")
1679
    @Override
1680
    public Status onResult2(final ResolutionResult resolutionResult) {
1681
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1682
      if (ManagedChannelImpl.this.nameResolver != resolver) {
1✔
1683
        return Status.OK;
1✔
1684
      }
1685

1686
      StatusOr<List<EquivalentAddressGroup>> serversOrError =
1✔
1687
          resolutionResult.getAddressesOrError();
1✔
1688
      if (!serversOrError.hasValue()) {
1✔
1689
        handleErrorInSyncContext(serversOrError.getStatus());
1✔
1690
        return serversOrError.getStatus();
1✔
1691
      }
1692
      List<EquivalentAddressGroup> servers = serversOrError.getValue();
1✔
1693
      channelLogger.log(
1✔
1694
          ChannelLogLevel.DEBUG,
1695
          "Resolved address: {0}, config={1}",
1696
          servers,
1697
          resolutionResult.getAttributes());
1✔
1698

1699
      if (lastResolutionState != ResolutionState.SUCCESS) {
1✔
1700
        channelLogger.log(ChannelLogLevel.INFO, "Address resolved: {0}",
1✔
1701
            servers);
1702
        lastResolutionState = ResolutionState.SUCCESS;
1✔
1703
      }
1704
      ConfigOrError configOrError = resolutionResult.getServiceConfig();
1✔
1705
      InternalConfigSelector resolvedConfigSelector =
1✔
1706
          resolutionResult.getAttributes().get(InternalConfigSelector.KEY);
1✔
1707
      ManagedChannelServiceConfig validServiceConfig =
1708
          configOrError != null && configOrError.getConfig() != null
1✔
1709
              ? (ManagedChannelServiceConfig) configOrError.getConfig()
1✔
1710
              : null;
1✔
1711
      Status serviceConfigError = configOrError != null ? configOrError.getError() : null;
1✔
1712

1713
      ManagedChannelServiceConfig effectiveServiceConfig;
1714
      if (!lookUpServiceConfig) {
1✔
1715
        if (validServiceConfig != null) {
1✔
1716
          channelLogger.log(
1✔
1717
              ChannelLogLevel.INFO,
1718
              "Service config from name resolver discarded by channel settings");
1719
        }
1720
        effectiveServiceConfig =
1721
            defaultServiceConfig == null ? EMPTY_SERVICE_CONFIG : defaultServiceConfig;
1✔
1722
        if (resolvedConfigSelector != null) {
1✔
1723
          channelLogger.log(
1✔
1724
              ChannelLogLevel.INFO,
1725
              "Config selector from name resolver discarded by channel settings");
1726
        }
1727
        realChannel.updateConfigSelector(effectiveServiceConfig.getDefaultConfigSelector());
1✔
1728
      } else {
1729
        // Try to use config if returned from name resolver
1730
        // Otherwise, try to use the default config if available
1731
        if (validServiceConfig != null) {
1✔
1732
          effectiveServiceConfig = validServiceConfig;
1✔
1733
          if (resolvedConfigSelector != null) {
1✔
1734
            realChannel.updateConfigSelector(resolvedConfigSelector);
1✔
1735
            if (effectiveServiceConfig.getDefaultConfigSelector() != null) {
1✔
1736
              channelLogger.log(
×
1737
                  ChannelLogLevel.DEBUG,
1738
                  "Method configs in service config will be discarded due to presence of"
1739
                      + "config-selector");
1740
            }
1741
          } else {
1742
            realChannel.updateConfigSelector(effectiveServiceConfig.getDefaultConfigSelector());
1✔
1743
          }
1744
        } else if (defaultServiceConfig != null) {
1✔
1745
          effectiveServiceConfig = defaultServiceConfig;
1✔
1746
          realChannel.updateConfigSelector(effectiveServiceConfig.getDefaultConfigSelector());
1✔
1747
          channelLogger.log(
1✔
1748
              ChannelLogLevel.INFO,
1749
              "Received no service config, using default service config");
1750
        } else if (serviceConfigError != null) {
1✔
1751
          if (!serviceConfigUpdated) {
1✔
1752
            // First DNS lookup has invalid service config, and cannot fall back to default
1753
            channelLogger.log(
1✔
1754
                ChannelLogLevel.INFO,
1755
                "Fallback to error due to invalid first service config without default config");
1756
            // This error could be an "inappropriate" control plane error that should not bleed
1757
            // through to client code using gRPC. We let them flow through here to the LB as
1758
            // we later check for these error codes when investigating pick results in
1759
            // GrpcUtil.getTransportFromPickResult().
1760
            onError(configOrError.getError());
1✔
1761
            return configOrError.getError();
1✔
1762
          } else {
1763
            effectiveServiceConfig = lastServiceConfig;
1✔
1764
          }
1765
        } else {
1766
          effectiveServiceConfig = EMPTY_SERVICE_CONFIG;
1✔
1767
          realChannel.updateConfigSelector(null);
1✔
1768
        }
1769
        if (!effectiveServiceConfig.equals(lastServiceConfig)) {
1✔
1770
          channelLogger.log(
1✔
1771
              ChannelLogLevel.INFO,
1772
              "Service config changed{0}",
1773
              effectiveServiceConfig == EMPTY_SERVICE_CONFIG ? " to empty" : "");
1✔
1774
          lastServiceConfig = effectiveServiceConfig;
1✔
1775
          transportProvider.throttle = effectiveServiceConfig.getRetryThrottling();
1✔
1776
        }
1777

1778
        try {
1779
          // TODO(creamsoup): when `serversOrError` is empty and lastResolutionStateCopy == SUCCESS
1780
          //  and lbNeedAddress, it shouldn't call the handleServiceConfigUpdate. But,
1781
          //  lbNeedAddress is not deterministic
1782
          serviceConfigUpdated = true;
1✔
1783
        } catch (RuntimeException re) {
×
1784
          logger.log(
×
1785
              Level.WARNING,
1786
              "[" + getLogId() + "] Unexpected exception from parsing service config",
×
1787
              re);
1788
        }
1✔
1789
      }
1790

1791
      Attributes effectiveAttrs = resolutionResult.getAttributes();
1✔
1792
      // Call LB only if it's not shutdown.  If LB is shutdown, lbHelper won't match.
1793
      if (NameResolverListener.this.helper == ManagedChannelImpl.this.lbHelper) {
1✔
1794
        Attributes.Builder attrBuilder =
1✔
1795
            effectiveAttrs.toBuilder().discard(InternalConfigSelector.KEY);
1✔
1796
        Map<String, ?> healthCheckingConfig =
1✔
1797
            effectiveServiceConfig.getHealthCheckingConfig();
1✔
1798
        if (healthCheckingConfig != null) {
1✔
1799
          attrBuilder
1✔
1800
              .set(LoadBalancer.ATTR_HEALTH_CHECKING_CONFIG, healthCheckingConfig)
1✔
1801
              .build();
1✔
1802
        }
1803
        Attributes attributes = attrBuilder.build();
1✔
1804

1805
        ResolvedAddresses.Builder resolvedAddresses = ResolvedAddresses.newBuilder()
1✔
1806
            .setAddresses(serversOrError.getValue())
1✔
1807
            .setAttributes(attributes)
1✔
1808
            .setLoadBalancingPolicyConfig(effectiveServiceConfig.getLoadBalancingConfig());
1✔
1809
        Status addressAcceptanceStatus = helper.lb.tryAcceptResolvedAddresses(
1✔
1810
            resolvedAddresses.build());
1✔
1811
        return addressAcceptanceStatus;
1✔
1812
      }
1813
      return Status.OK;
×
1814
    }
1815

1816
    @Override
1817
    public void onError(final Status error) {
1818
      checkArgument(!error.isOk(), "the error status must not be OK");
1✔
1819
      final class NameResolverErrorHandler implements Runnable {
1✔
1820
        @Override
1821
        public void run() {
1822
          handleErrorInSyncContext(error);
1✔
1823
        }
1✔
1824
      }
1825

1826
      syncContext.execute(new NameResolverErrorHandler());
1✔
1827
    }
1✔
1828

1829
    private void handleErrorInSyncContext(Status error) {
1830
      logger.log(Level.WARNING, "[{0}] Failed to resolve name. status={1}",
1✔
1831
          new Object[] {getLogId(), error});
1✔
1832
      realChannel.onConfigError();
1✔
1833
      if (lastResolutionState != ResolutionState.ERROR) {
1✔
1834
        channelLogger.log(ChannelLogLevel.WARNING, "Failed to resolve name: {0}", error);
1✔
1835
        lastResolutionState = ResolutionState.ERROR;
1✔
1836
      }
1837
      // Call LB only if it's not shutdown.  If LB is shutdown, lbHelper won't match.
1838
      if (NameResolverListener.this.helper != ManagedChannelImpl.this.lbHelper) {
1✔
1839
        return;
1✔
1840
      }
1841

1842
      helper.lb.handleNameResolutionError(error);
1✔
1843
    }
1✔
1844
  }
1845

1846
  private final class SubchannelImpl extends AbstractSubchannel {
1847
    final CreateSubchannelArgs args;
1848
    final InternalLogId subchannelLogId;
1849
    final ChannelLoggerImpl subchannelLogger;
1850
    final ChannelTracer subchannelTracer;
1851
    List<EquivalentAddressGroup> addressGroups;
1852
    InternalSubchannel subchannel;
1853
    boolean started;
1854
    boolean shutdown;
1855
    ScheduledHandle delayedShutdownTask;
1856

1857
    SubchannelImpl(CreateSubchannelArgs args) {
1✔
1858
      checkNotNull(args, "args");
1✔
1859
      addressGroups = args.getAddresses();
1✔
1860
      if (authorityOverride != null) {
1✔
1861
        List<EquivalentAddressGroup> eagsWithoutOverrideAttr =
1✔
1862
            stripOverrideAuthorityAttributes(args.getAddresses());
1✔
1863
        args = args.toBuilder().setAddresses(eagsWithoutOverrideAttr).build();
1✔
1864
      }
1865
      this.args = args;
1✔
1866
      subchannelLogId = InternalLogId.allocate("Subchannel", /*details=*/ authority());
1✔
1867
      subchannelTracer = new ChannelTracer(
1✔
1868
          subchannelLogId, maxTraceEvents, timeProvider.currentTimeNanos(),
1✔
1869
          "Subchannel for " + args.getAddresses());
1✔
1870
      subchannelLogger = new ChannelLoggerImpl(subchannelTracer, timeProvider);
1✔
1871
    }
1✔
1872

1873
    @Override
1874
    public void start(final SubchannelStateListener listener) {
1875
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1876
      checkState(!started, "already started");
1✔
1877
      checkState(!shutdown, "already shutdown");
1✔
1878
      checkState(!terminating, "Channel is being terminated");
1✔
1879
      started = true;
1✔
1880
      final class ManagedInternalSubchannelCallback extends InternalSubchannel.Callback {
1✔
1881
        // All callbacks are run in syncContext
1882
        @Override
1883
        void onTerminated(InternalSubchannel is) {
1884
          subchannels.remove(is);
1✔
1885
          channelz.removeSubchannel(is);
1✔
1886
          maybeTerminateChannel();
1✔
1887
        }
1✔
1888

1889
        @Override
1890
        void onStateChange(InternalSubchannel is, ConnectivityStateInfo newState) {
1891
          checkState(listener != null, "listener is null");
1✔
1892
          listener.onSubchannelState(newState);
1✔
1893
        }
1✔
1894

1895
        @Override
1896
        void onInUse(InternalSubchannel is) {
1897
          inUseStateAggregator.updateObjectInUse(is, true);
1✔
1898
        }
1✔
1899

1900
        @Override
1901
        void onNotInUse(InternalSubchannel is) {
1902
          inUseStateAggregator.updateObjectInUse(is, false);
1✔
1903
        }
1✔
1904
      }
1905

1906
      final InternalSubchannel internalSubchannel = new InternalSubchannel(
1✔
1907
          args,
1908
          authority(),
1✔
1909
          userAgent,
1✔
1910
          backoffPolicyProvider,
1✔
1911
          transportFactory,
1✔
1912
          transportFactory.getScheduledExecutorService(),
1✔
1913
          stopwatchSupplier,
1✔
1914
          syncContext,
1915
          new ManagedInternalSubchannelCallback(),
1916
          channelz,
1✔
1917
          callTracerFactory.create(),
1✔
1918
          subchannelTracer,
1919
          subchannelLogId,
1920
          subchannelLogger,
1921
          transportFilters);
1✔
1922

1923
      channelTracer.reportEvent(new ChannelTrace.Event.Builder()
1✔
1924
          .setDescription("Child Subchannel started")
1✔
1925
          .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
1✔
1926
          .setTimestampNanos(timeProvider.currentTimeNanos())
1✔
1927
          .setSubchannelRef(internalSubchannel)
1✔
1928
          .build());
1✔
1929

1930
      this.subchannel = internalSubchannel;
1✔
1931
      channelz.addSubchannel(internalSubchannel);
1✔
1932
      subchannels.add(internalSubchannel);
1✔
1933
    }
1✔
1934

1935
    @Override
1936
    InternalInstrumented<ChannelStats> getInstrumentedInternalSubchannel() {
1937
      checkState(started, "not started");
1✔
1938
      return subchannel;
1✔
1939
    }
1940

1941
    @Override
1942
    public void shutdown() {
1943
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1944
      if (subchannel == null) {
1✔
1945
        // start() was not successful
1946
        shutdown = true;
×
1947
        return;
×
1948
      }
1949
      if (shutdown) {
1✔
1950
        if (terminating && delayedShutdownTask != null) {
1✔
1951
          // shutdown() was previously called when terminating == false, thus a delayed shutdown()
1952
          // was scheduled.  Now since terminating == true, We should expedite the shutdown.
1953
          delayedShutdownTask.cancel();
×
1954
          delayedShutdownTask = null;
×
1955
          // Will fall through to the subchannel.shutdown() at the end.
1956
        } else {
1957
          return;
1✔
1958
        }
1959
      } else {
1960
        shutdown = true;
1✔
1961
      }
1962
      // Add a delay to shutdown to deal with the race between 1) a transport being picked and
1963
      // newStream() being called on it, and 2) its Subchannel is shut down by LoadBalancer (e.g.,
1964
      // because of address change, or because LoadBalancer is shutdown by Channel entering idle
1965
      // mode). If (2) wins, the app will see a spurious error. We work around this by delaying
1966
      // shutdown of Subchannel for a few seconds here.
1967
      //
1968
      // TODO(zhangkun83): consider a better approach
1969
      // (https://github.com/grpc/grpc-java/issues/2562).
1970
      if (!terminating) {
1✔
1971
        final class ShutdownSubchannel implements Runnable {
1✔
1972
          @Override
1973
          public void run() {
1974
            subchannel.shutdown(SUBCHANNEL_SHUTDOWN_STATUS);
1✔
1975
          }
1✔
1976
        }
1977

1978
        delayedShutdownTask = syncContext.schedule(
1✔
1979
            new LogExceptionRunnable(new ShutdownSubchannel()),
1980
            SUBCHANNEL_SHUTDOWN_DELAY_SECONDS, TimeUnit.SECONDS,
1981
            transportFactory.getScheduledExecutorService());
1✔
1982
        return;
1✔
1983
      }
1984
      // When terminating == true, no more real streams will be created. It's safe and also
1985
      // desirable to shutdown timely.
1986
      subchannel.shutdown(SHUTDOWN_STATUS);
1✔
1987
    }
1✔
1988

1989
    @Override
1990
    public void requestConnection() {
1991
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1992
      checkState(started, "not started");
1✔
1993
      subchannel.obtainActiveTransport();
1✔
1994
    }
1✔
1995

1996
    @Override
1997
    public List<EquivalentAddressGroup> getAllAddresses() {
1998
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1999
      checkState(started, "not started");
1✔
2000
      return addressGroups;
1✔
2001
    }
2002

2003
    @Override
2004
    public Attributes getAttributes() {
2005
      return args.getAttributes();
1✔
2006
    }
2007

2008
    @Override
2009
    public String toString() {
2010
      return subchannelLogId.toString();
1✔
2011
    }
2012

2013
    @Override
2014
    public Channel asChannel() {
2015
      checkState(started, "not started");
1✔
2016
      return new SubchannelChannel(
1✔
2017
          subchannel, balancerRpcExecutorHolder.getExecutor(),
1✔
2018
          transportFactory.getScheduledExecutorService(),
1✔
2019
          callTracerFactory.create(),
1✔
2020
          new AtomicReference<InternalConfigSelector>(null));
2021
    }
2022

2023
    @Override
2024
    public Object getInternalSubchannel() {
2025
      checkState(started, "Subchannel is not started");
1✔
2026
      return subchannel;
1✔
2027
    }
2028

2029
    @Override
2030
    public ChannelLogger getChannelLogger() {
2031
      return subchannelLogger;
1✔
2032
    }
2033

2034
    @Override
2035
    public void updateAddresses(List<EquivalentAddressGroup> addrs) {
2036
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
2037
      addressGroups = addrs;
1✔
2038
      if (authorityOverride != null) {
1✔
2039
        addrs = stripOverrideAuthorityAttributes(addrs);
1✔
2040
      }
2041
      subchannel.updateAddresses(addrs);
1✔
2042
    }
1✔
2043

2044
    @Override
2045
    public Attributes getConnectedAddressAttributes() {
2046
      return subchannel.getConnectedAddressAttributes();
1✔
2047
    }
2048

2049
    private List<EquivalentAddressGroup> stripOverrideAuthorityAttributes(
2050
        List<EquivalentAddressGroup> eags) {
2051
      List<EquivalentAddressGroup> eagsWithoutOverrideAttr = new ArrayList<>();
1✔
2052
      for (EquivalentAddressGroup eag : eags) {
1✔
2053
        EquivalentAddressGroup eagWithoutOverrideAttr = new EquivalentAddressGroup(
1✔
2054
            eag.getAddresses(),
1✔
2055
            eag.getAttributes().toBuilder().discard(ATTR_AUTHORITY_OVERRIDE).build());
1✔
2056
        eagsWithoutOverrideAttr.add(eagWithoutOverrideAttr);
1✔
2057
      }
1✔
2058
      return Collections.unmodifiableList(eagsWithoutOverrideAttr);
1✔
2059
    }
2060
  }
2061

2062
  @Override
2063
  public String toString() {
2064
    return MoreObjects.toStringHelper(this)
1✔
2065
        .add("logId", logId.getId())
1✔
2066
        .add("target", target)
1✔
2067
        .toString();
1✔
2068
  }
2069

2070
  /**
2071
   * Called from syncContext.
2072
   */
2073
  private final class DelayedTransportListener implements ManagedClientTransport.Listener {
1✔
2074
    @Override
2075
    public void transportShutdown(Status s) {
2076
      checkState(shutdown.get(), "Channel must have been shut down");
1✔
2077
    }
1✔
2078

2079
    @Override
2080
    public void transportReady() {
2081
      // Don't care
2082
    }
×
2083

2084
    @Override
2085
    public Attributes filterTransport(Attributes attributes) {
2086
      return attributes;
×
2087
    }
2088

2089
    @Override
2090
    public void transportInUse(final boolean inUse) {
2091
      inUseStateAggregator.updateObjectInUse(delayedTransport, inUse);
1✔
2092
      if (inUse) {
1✔
2093
        // It's possible to be in idle mode while inUseStateAggregator is in-use, if one of the
2094
        // subchannels is in use. But we should never be in idle mode when delayed transport is in
2095
        // use.
2096
        exitIdleMode();
1✔
2097
      }
2098
    }
1✔
2099

2100
    @Override
2101
    public void transportTerminated() {
2102
      checkState(shutdown.get(), "Channel must have been shut down");
1✔
2103
      terminating = true;
1✔
2104
      shutdownNameResolverAndLoadBalancer(false);
1✔
2105
      // No need to call channelStateManager since we are already in SHUTDOWN state.
2106
      // Until LoadBalancer is shutdown, it may still create new subchannels.  We catch them
2107
      // here.
2108
      maybeShutdownNowSubchannels();
1✔
2109
      maybeTerminateChannel();
1✔
2110
    }
1✔
2111
  }
2112

2113
  /**
2114
   * Must be accessed from syncContext.
2115
   */
2116
  private final class IdleModeStateAggregator extends InUseStateAggregator<Object> {
1✔
2117
    @Override
2118
    protected void handleInUse() {
2119
      exitIdleMode();
1✔
2120
    }
1✔
2121

2122
    @Override
2123
    protected void handleNotInUse() {
2124
      if (shutdown.get()) {
1✔
2125
        return;
1✔
2126
      }
2127
      rescheduleIdleTimer();
1✔
2128
    }
1✔
2129
  }
2130

2131
  /**
2132
   * Lazily request for Executor from an executor pool.
2133
   * Also act as an Executor directly to simply run a cmd
2134
   */
2135
  @VisibleForTesting
2136
  static final class ExecutorHolder implements Executor {
2137
    private final ObjectPool<? extends Executor> pool;
2138
    private Executor executor;
2139

2140
    ExecutorHolder(ObjectPool<? extends Executor> executorPool) {
1✔
2141
      this.pool = checkNotNull(executorPool, "executorPool");
1✔
2142
    }
1✔
2143

2144
    synchronized Executor getExecutor() {
2145
      if (executor == null) {
1✔
2146
        executor = checkNotNull(pool.getObject(), "%s.getObject()", executor);
1✔
2147
      }
2148
      return executor;
1✔
2149
    }
2150

2151
    synchronized void release() {
2152
      if (executor != null) {
1✔
2153
        executor = pool.returnObject(executor);
1✔
2154
      }
2155
    }
1✔
2156

2157
    @Override
2158
    public void execute(Runnable command) {
2159
      getExecutor().execute(command);
1✔
2160
    }
1✔
2161
  }
2162

2163
  private static final class RestrictedScheduledExecutor implements ScheduledExecutorService {
2164
    final ScheduledExecutorService delegate;
2165

2166
    private RestrictedScheduledExecutor(ScheduledExecutorService delegate) {
1✔
2167
      this.delegate = checkNotNull(delegate, "delegate");
1✔
2168
    }
1✔
2169

2170
    @Override
2171
    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
2172
      return delegate.schedule(callable, delay, unit);
×
2173
    }
2174

2175
    @Override
2176
    public ScheduledFuture<?> schedule(Runnable cmd, long delay, TimeUnit unit) {
2177
      return delegate.schedule(cmd, delay, unit);
1✔
2178
    }
2179

2180
    @Override
2181
    public ScheduledFuture<?> scheduleAtFixedRate(
2182
        Runnable command, long initialDelay, long period, TimeUnit unit) {
2183
      return delegate.scheduleAtFixedRate(command, initialDelay, period, unit);
1✔
2184
    }
2185

2186
    @Override
2187
    public ScheduledFuture<?> scheduleWithFixedDelay(
2188
        Runnable command, long initialDelay, long delay, TimeUnit unit) {
2189
      return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
×
2190
    }
2191

2192
    @Override
2193
    public boolean awaitTermination(long timeout, TimeUnit unit)
2194
        throws InterruptedException {
2195
      return delegate.awaitTermination(timeout, unit);
×
2196
    }
2197

2198
    @Override
2199
    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
2200
        throws InterruptedException {
2201
      return delegate.invokeAll(tasks);
×
2202
    }
2203

2204
    @Override
2205
    public <T> List<Future<T>> invokeAll(
2206
        Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2207
        throws InterruptedException {
2208
      return delegate.invokeAll(tasks, timeout, unit);
×
2209
    }
2210

2211
    @Override
2212
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
2213
        throws InterruptedException, ExecutionException {
2214
      return delegate.invokeAny(tasks);
×
2215
    }
2216

2217
    @Override
2218
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2219
        throws InterruptedException, ExecutionException, TimeoutException {
2220
      return delegate.invokeAny(tasks, timeout, unit);
×
2221
    }
2222

2223
    @Override
2224
    public boolean isShutdown() {
2225
      return delegate.isShutdown();
×
2226
    }
2227

2228
    @Override
2229
    public boolean isTerminated() {
2230
      return delegate.isTerminated();
×
2231
    }
2232

2233
    @Override
2234
    public void shutdown() {
2235
      throw new UnsupportedOperationException("Restricted: shutdown() is not allowed");
1✔
2236
    }
2237

2238
    @Override
2239
    public List<Runnable> shutdownNow() {
2240
      throw new UnsupportedOperationException("Restricted: shutdownNow() is not allowed");
1✔
2241
    }
2242

2243
    @Override
2244
    public <T> Future<T> submit(Callable<T> task) {
2245
      return delegate.submit(task);
×
2246
    }
2247

2248
    @Override
2249
    public Future<?> submit(Runnable task) {
2250
      return delegate.submit(task);
×
2251
    }
2252

2253
    @Override
2254
    public <T> Future<T> submit(Runnable task, T result) {
2255
      return delegate.submit(task, result);
×
2256
    }
2257

2258
    @Override
2259
    public void execute(Runnable command) {
2260
      delegate.execute(command);
×
2261
    }
×
2262
  }
2263

2264
  /**
2265
   * A ResolutionState indicates the status of last name resolution.
2266
   */
2267
  enum ResolutionState {
1✔
2268
    NO_RESOLUTION,
1✔
2269
    SUCCESS,
1✔
2270
    ERROR
1✔
2271
  }
2272
}
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

© 2026 Coveralls, Inc