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

grpc / grpc-java / #19818

22 May 2025 10:41PM UTC coverage: 88.564% (+0.01%) from 88.551%
#19818

push

github

web-flow
Rename PSM interop fallback test suite to light (#12095)

33689 of 38039 relevant lines covered (88.56%)

0.89 hits per line

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

93.92
/../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 io.grpc.Attributes;
36
import io.grpc.CallCredentials;
37
import io.grpc.CallOptions;
38
import io.grpc.Channel;
39
import io.grpc.ChannelCredentials;
40
import io.grpc.ChannelLogger;
41
import io.grpc.ChannelLogger.ChannelLogLevel;
42
import io.grpc.ClientCall;
43
import io.grpc.ClientInterceptor;
44
import io.grpc.ClientInterceptors;
45
import io.grpc.ClientStreamTracer;
46
import io.grpc.ClientTransportFilter;
47
import io.grpc.CompressorRegistry;
48
import io.grpc.ConnectivityState;
49
import io.grpc.ConnectivityStateInfo;
50
import io.grpc.Context;
51
import io.grpc.Deadline;
52
import io.grpc.DecompressorRegistry;
53
import io.grpc.EquivalentAddressGroup;
54
import io.grpc.ForwardingChannelBuilder2;
55
import io.grpc.ForwardingClientCall;
56
import io.grpc.Grpc;
57
import io.grpc.InternalChannelz;
58
import io.grpc.InternalChannelz.ChannelStats;
59
import io.grpc.InternalChannelz.ChannelTrace;
60
import io.grpc.InternalConfigSelector;
61
import io.grpc.InternalInstrumented;
62
import io.grpc.InternalLogId;
63
import io.grpc.InternalWithLogId;
64
import io.grpc.LoadBalancer;
65
import io.grpc.LoadBalancer.CreateSubchannelArgs;
66
import io.grpc.LoadBalancer.PickResult;
67
import io.grpc.LoadBalancer.PickSubchannelArgs;
68
import io.grpc.LoadBalancer.ResolvedAddresses;
69
import io.grpc.LoadBalancer.SubchannelPicker;
70
import io.grpc.LoadBalancer.SubchannelStateListener;
71
import io.grpc.ManagedChannel;
72
import io.grpc.ManagedChannelBuilder;
73
import io.grpc.Metadata;
74
import io.grpc.MethodDescriptor;
75
import io.grpc.MetricInstrumentRegistry;
76
import io.grpc.MetricRecorder;
77
import io.grpc.NameResolver;
78
import io.grpc.NameResolver.ConfigOrError;
79
import io.grpc.NameResolver.ResolutionResult;
80
import io.grpc.NameResolverProvider;
81
import io.grpc.NameResolverRegistry;
82
import io.grpc.ProxyDetector;
83
import io.grpc.Status;
84
import io.grpc.StatusOr;
85
import io.grpc.SynchronizationContext;
86
import io.grpc.SynchronizationContext.ScheduledHandle;
87
import io.grpc.internal.AutoConfiguredLoadBalancerFactory.AutoConfiguredLoadBalancer;
88
import io.grpc.internal.ClientCallImpl.ClientStreamProvider;
89
import io.grpc.internal.ClientTransportFactory.SwapChannelCredentialsResult;
90
import io.grpc.internal.ManagedChannelImplBuilder.ClientTransportFactoryBuilder;
91
import io.grpc.internal.ManagedChannelImplBuilder.FixedPortProvider;
92
import io.grpc.internal.ManagedChannelServiceConfig.MethodInfo;
93
import io.grpc.internal.ManagedChannelServiceConfig.ServiceConfigConvertedSelector;
94
import io.grpc.internal.RetriableStream.ChannelBufferMeter;
95
import io.grpc.internal.RetriableStream.Throttle;
96
import io.grpc.internal.RetryingNameResolver.ResolutionResultListener;
97
import java.net.URI;
98
import java.util.ArrayList;
99
import java.util.Collection;
100
import java.util.Collections;
101
import java.util.HashSet;
102
import java.util.LinkedHashSet;
103
import java.util.List;
104
import java.util.Map;
105
import java.util.Set;
106
import java.util.concurrent.Callable;
107
import java.util.concurrent.CountDownLatch;
108
import java.util.concurrent.ExecutionException;
109
import java.util.concurrent.Executor;
110
import java.util.concurrent.Future;
111
import java.util.concurrent.ScheduledExecutorService;
112
import java.util.concurrent.ScheduledFuture;
113
import java.util.concurrent.TimeUnit;
114
import java.util.concurrent.TimeoutException;
115
import java.util.concurrent.atomic.AtomicBoolean;
116
import java.util.concurrent.atomic.AtomicReference;
117
import java.util.logging.Level;
118
import java.util.logging.Logger;
119
import javax.annotation.Nullable;
120
import javax.annotation.concurrent.GuardedBy;
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());
×
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
      final class UpdateBalancingState implements Runnable {
1✔
1392
        @Override
1393
        public void run() {
1394
          if (LbHelperImpl.this != lbHelper || panicMode) {
1✔
1395
            return;
1✔
1396
          }
1397
          updateSubchannelPicker(newPicker);
1✔
1398
          // It's not appropriate to report SHUTDOWN state from lb.
1399
          // Ignore the case of newState == SHUTDOWN for now.
1400
          if (newState != SHUTDOWN) {
1✔
1401
            channelLogger.log(
1✔
1402
                ChannelLogLevel.INFO, "Entering {0} state with picker: {1}", newState, newPicker);
1403
            channelStateManager.gotoState(newState);
1✔
1404
          }
1405
        }
1✔
1406
      }
1407

1408
      syncContext.execute(new UpdateBalancingState());
1✔
1409
    }
1✔
1410

1411
    @Override
1412
    public void refreshNameResolution() {
1413
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1414
      final class LoadBalancerRefreshNameResolution implements Runnable {
1✔
1415
        @Override
1416
        public void run() {
1417
          ManagedChannelImpl.this.refreshNameResolution();
1✔
1418
        }
1✔
1419
      }
1420

1421
      syncContext.execute(new LoadBalancerRefreshNameResolution());
1✔
1422
    }
1✔
1423

1424
    @Override
1425
    public ManagedChannel createOobChannel(EquivalentAddressGroup addressGroup, String authority) {
1426
      return createOobChannel(Collections.singletonList(addressGroup), authority);
×
1427
    }
1428

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

1464
        @Override
1465
        void onStateChange(InternalSubchannel is, ConnectivityStateInfo newState) {
1466
          // TODO(chengyuanzhang): change to let LB policies explicitly manage OOB channel's
1467
          //  state and refresh name resolution if necessary.
1468
          handleInternalSubchannelState(newState);
1✔
1469
          oobChannel.handleSubchannelStateChange(newState);
1✔
1470
        }
1✔
1471
      }
1472

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

1508
      syncContext.execute(new AddOobChannel());
1✔
1509
      return oobChannel;
1✔
1510
    }
1511

1512
    @Deprecated
1513
    @Override
1514
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
1515
      return createResolvingOobChannelBuilder(target, new DefaultChannelCreds())
1✔
1516
          // Override authority to keep the old behavior.
1517
          // createResolvingOobChannelBuilder(String target) will be deleted soon.
1518
          .overrideAuthority(getAuthority());
1✔
1519
    }
1520

1521
    // TODO(creamsoup) prevent main channel to shutdown if oob channel is not terminated
1522
    // TODO(zdapeng) register the channel as a subchannel of the parent channel in channelz.
1523
    @Override
1524
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1525
        final String target, final ChannelCredentials channelCreds) {
1526
      checkNotNull(channelCreds, "channelCreds");
1✔
1527

1528
      final class ResolvingOobChannelBuilder
1529
          extends ForwardingChannelBuilder2<ResolvingOobChannelBuilder> {
1530
        final ManagedChannelBuilder<?> delegate;
1531

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

1565
        @Override
1566
        protected ManagedChannelBuilder<?> delegate() {
1567
          return delegate;
1✔
1568
        }
1569
      }
1570

1571
      checkState(!terminated, "Channel is terminated");
1✔
1572

1573
      @SuppressWarnings("deprecation")
1574
      ResolvingOobChannelBuilder builder = new ResolvingOobChannelBuilder();
1✔
1575

1576
      return builder
1✔
1577
          // TODO(zdapeng): executors should not outlive the parent channel.
1578
          .executor(executor)
1✔
1579
          .offloadExecutor(offloadExecutorHolder.getExecutor())
1✔
1580
          .maxTraceEvents(maxTraceEvents)
1✔
1581
          .proxyDetector(nameResolverArgs.getProxyDetector())
1✔
1582
          .userAgent(userAgent);
1✔
1583
    }
1584

1585
    @Override
1586
    public ChannelCredentials getUnsafeChannelCredentials() {
1587
      if (originalChannelCreds == null) {
1✔
1588
        return new DefaultChannelCreds();
1✔
1589
      }
1590
      return originalChannelCreds;
×
1591
    }
1592

1593
    @Override
1594
    public void updateOobChannelAddresses(ManagedChannel channel, EquivalentAddressGroup eag) {
1595
      updateOobChannelAddresses(channel, Collections.singletonList(eag));
×
1596
    }
×
1597

1598
    @Override
1599
    public void updateOobChannelAddresses(ManagedChannel channel,
1600
        List<EquivalentAddressGroup> eag) {
1601
      checkArgument(channel instanceof OobChannel,
1✔
1602
          "channel must have been returned from createOobChannel");
1603
      ((OobChannel) channel).updateAddresses(eag);
1✔
1604
    }
1✔
1605

1606
    @Override
1607
    public String getAuthority() {
1608
      return ManagedChannelImpl.this.authority();
1✔
1609
    }
1610

1611
    @Override
1612
    public String getChannelTarget() {
1613
      return targetUri.toString();
1✔
1614
    }
1615

1616
    @Override
1617
    public SynchronizationContext getSynchronizationContext() {
1618
      return syncContext;
1✔
1619
    }
1620

1621
    @Override
1622
    public ScheduledExecutorService getScheduledExecutorService() {
1623
      return scheduledExecutor;
1✔
1624
    }
1625

1626
    @Override
1627
    public ChannelLogger getChannelLogger() {
1628
      return channelLogger;
1✔
1629
    }
1630

1631
    @Override
1632
    public NameResolver.Args getNameResolverArgs() {
1633
      return nameResolverArgs;
1✔
1634
    }
1635

1636
    @Override
1637
    public NameResolverRegistry getNameResolverRegistry() {
1638
      return nameResolverRegistry;
1✔
1639
    }
1640

1641
    @Override
1642
    public MetricRecorder getMetricRecorder() {
1643
      return metricRecorder;
1✔
1644
    }
1645

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

1659
  final class NameResolverListener extends NameResolver.Listener2 {
1660
    final LbHelperImpl helper;
1661
    final NameResolver resolver;
1662

1663
    NameResolverListener(LbHelperImpl helperImpl, NameResolver resolver) {
1✔
1664
      this.helper = checkNotNull(helperImpl, "helperImpl");
1✔
1665
      this.resolver = checkNotNull(resolver, "resolver");
1✔
1666
    }
1✔
1667

1668
    @Override
1669
    public void onResult(final ResolutionResult resolutionResult) {
1670
      final class NamesResolved implements Runnable {
1✔
1671

1672
        @Override
1673
        public void run() {
1674
          Status status = onResult2(resolutionResult);
1✔
1675
          ResolutionResultListener resolutionResultListener = resolutionResult.getAttributes()
1✔
1676
              .get(RetryingNameResolver.RESOLUTION_RESULT_LISTENER_KEY);
1✔
1677
          resolutionResultListener.resolutionAttempted(status);
1✔
1678
        }
1✔
1679
      }
1680

1681
      syncContext.execute(new NamesResolved());
1✔
1682
    }
1✔
1683

1684
    @SuppressWarnings("ReferenceEquality")
1685
    @Override
1686
    public Status onResult2(final ResolutionResult resolutionResult) {
1687
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1688
      if (ManagedChannelImpl.this.nameResolver != resolver) {
1✔
1689
        return Status.OK;
1✔
1690
      }
1691

1692
      StatusOr<List<EquivalentAddressGroup>> serversOrError =
1✔
1693
          resolutionResult.getAddressesOrError();
1✔
1694
      if (!serversOrError.hasValue()) {
1✔
1695
        handleErrorInSyncContext(serversOrError.getStatus());
1✔
1696
        return serversOrError.getStatus();
1✔
1697
      }
1698
      List<EquivalentAddressGroup> servers = serversOrError.getValue();
1✔
1699
      channelLogger.log(
1✔
1700
          ChannelLogLevel.DEBUG,
1701
          "Resolved address: {0}, config={1}",
1702
          servers,
1703
          resolutionResult.getAttributes());
1✔
1704

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

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

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

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

1811
        ResolvedAddresses.Builder resolvedAddresses = ResolvedAddresses.newBuilder()
1✔
1812
            .setAddresses(serversOrError.getValue())
1✔
1813
            .setAttributes(attributes)
1✔
1814
            .setLoadBalancingPolicyConfig(effectiveServiceConfig.getLoadBalancingConfig());
1✔
1815
        Status addressAcceptanceStatus = helper.lb.tryAcceptResolvedAddresses(
1✔
1816
            resolvedAddresses.build());
1✔
1817
        return addressAcceptanceStatus;
1✔
1818
      }
1819
      return Status.OK;
×
1820
    }
1821

1822
    @Override
1823
    public void onError(final Status error) {
1824
      checkArgument(!error.isOk(), "the error status must not be OK");
1✔
1825
      final class NameResolverErrorHandler implements Runnable {
1✔
1826
        @Override
1827
        public void run() {
1828
          handleErrorInSyncContext(error);
1✔
1829
        }
1✔
1830
      }
1831

1832
      syncContext.execute(new NameResolverErrorHandler());
1✔
1833
    }
1✔
1834

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

1848
      helper.lb.handleNameResolutionError(error);
1✔
1849
    }
1✔
1850
  }
1851

1852
  private final class SubchannelImpl extends AbstractSubchannel {
1853
    final CreateSubchannelArgs args;
1854
    final InternalLogId subchannelLogId;
1855
    final ChannelLoggerImpl subchannelLogger;
1856
    final ChannelTracer subchannelTracer;
1857
    List<EquivalentAddressGroup> addressGroups;
1858
    InternalSubchannel subchannel;
1859
    boolean started;
1860
    boolean shutdown;
1861
    ScheduledHandle delayedShutdownTask;
1862

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

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

1895
        @Override
1896
        void onStateChange(InternalSubchannel is, ConnectivityStateInfo newState) {
1897
          checkState(listener != null, "listener is null");
1✔
1898
          listener.onSubchannelState(newState);
1✔
1899
        }
1✔
1900

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

1906
        @Override
1907
        void onNotInUse(InternalSubchannel is) {
1908
          inUseStateAggregator.updateObjectInUse(is, false);
1✔
1909
        }
1✔
1910
      }
1911

1912
      final InternalSubchannel internalSubchannel = new InternalSubchannel(
1✔
1913
          args,
1914
          authority(),
1✔
1915
          userAgent,
1✔
1916
          backoffPolicyProvider,
1✔
1917
          transportFactory,
1✔
1918
          transportFactory.getScheduledExecutorService(),
1✔
1919
          stopwatchSupplier,
1✔
1920
          syncContext,
1921
          new ManagedInternalSubchannelCallback(),
1922
          channelz,
1✔
1923
          callTracerFactory.create(),
1✔
1924
          subchannelTracer,
1925
          subchannelLogId,
1926
          subchannelLogger,
1927
          transportFilters);
1✔
1928

1929
      channelTracer.reportEvent(new ChannelTrace.Event.Builder()
1✔
1930
          .setDescription("Child Subchannel started")
1✔
1931
          .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
1✔
1932
          .setTimestampNanos(timeProvider.currentTimeNanos())
1✔
1933
          .setSubchannelRef(internalSubchannel)
1✔
1934
          .build());
1✔
1935

1936
      this.subchannel = internalSubchannel;
1✔
1937
      channelz.addSubchannel(internalSubchannel);
1✔
1938
      subchannels.add(internalSubchannel);
1✔
1939
    }
1✔
1940

1941
    @Override
1942
    InternalInstrumented<ChannelStats> getInstrumentedInternalSubchannel() {
1943
      checkState(started, "not started");
1✔
1944
      return subchannel;
1✔
1945
    }
1946

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

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

1995
    @Override
1996
    public void requestConnection() {
1997
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1998
      checkState(started, "not started");
1✔
1999
      subchannel.obtainActiveTransport();
1✔
2000
    }
1✔
2001

2002
    @Override
2003
    public List<EquivalentAddressGroup> getAllAddresses() {
2004
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
2005
      checkState(started, "not started");
1✔
2006
      return addressGroups;
1✔
2007
    }
2008

2009
    @Override
2010
    public Attributes getAttributes() {
2011
      return args.getAttributes();
1✔
2012
    }
2013

2014
    @Override
2015
    public String toString() {
2016
      return subchannelLogId.toString();
1✔
2017
    }
2018

2019
    @Override
2020
    public Channel asChannel() {
2021
      checkState(started, "not started");
1✔
2022
      return new SubchannelChannel(
1✔
2023
          subchannel, balancerRpcExecutorHolder.getExecutor(),
1✔
2024
          transportFactory.getScheduledExecutorService(),
1✔
2025
          callTracerFactory.create(),
1✔
2026
          new AtomicReference<InternalConfigSelector>(null));
2027
    }
2028

2029
    @Override
2030
    public Object getInternalSubchannel() {
2031
      checkState(started, "Subchannel is not started");
1✔
2032
      return subchannel;
1✔
2033
    }
2034

2035
    @Override
2036
    public ChannelLogger getChannelLogger() {
2037
      return subchannelLogger;
1✔
2038
    }
2039

2040
    @Override
2041
    public void updateAddresses(List<EquivalentAddressGroup> addrs) {
2042
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
2043
      addressGroups = addrs;
1✔
2044
      if (authorityOverride != null) {
1✔
2045
        addrs = stripOverrideAuthorityAttributes(addrs);
1✔
2046
      }
2047
      subchannel.updateAddresses(addrs);
1✔
2048
    }
1✔
2049

2050
    @Override
2051
    public Attributes getConnectedAddressAttributes() {
2052
      return subchannel.getConnectedAddressAttributes();
1✔
2053
    }
2054

2055
    private List<EquivalentAddressGroup> stripOverrideAuthorityAttributes(
2056
        List<EquivalentAddressGroup> eags) {
2057
      List<EquivalentAddressGroup> eagsWithoutOverrideAttr = new ArrayList<>();
1✔
2058
      for (EquivalentAddressGroup eag : eags) {
1✔
2059
        EquivalentAddressGroup eagWithoutOverrideAttr = new EquivalentAddressGroup(
1✔
2060
            eag.getAddresses(),
1✔
2061
            eag.getAttributes().toBuilder().discard(ATTR_AUTHORITY_OVERRIDE).build());
1✔
2062
        eagsWithoutOverrideAttr.add(eagWithoutOverrideAttr);
1✔
2063
      }
1✔
2064
      return Collections.unmodifiableList(eagsWithoutOverrideAttr);
1✔
2065
    }
2066
  }
2067

2068
  @Override
2069
  public String toString() {
2070
    return MoreObjects.toStringHelper(this)
1✔
2071
        .add("logId", logId.getId())
1✔
2072
        .add("target", target)
1✔
2073
        .toString();
1✔
2074
  }
2075

2076
  /**
2077
   * Called from syncContext.
2078
   */
2079
  private final class DelayedTransportListener implements ManagedClientTransport.Listener {
1✔
2080
    @Override
2081
    public void transportShutdown(Status s) {
2082
      checkState(shutdown.get(), "Channel must have been shut down");
1✔
2083
    }
1✔
2084

2085
    @Override
2086
    public void transportReady() {
2087
      // Don't care
2088
    }
×
2089

2090
    @Override
2091
    public Attributes filterTransport(Attributes attributes) {
2092
      return attributes;
×
2093
    }
2094

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

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

2119
  /**
2120
   * Must be accessed from syncContext.
2121
   */
2122
  private final class IdleModeStateAggregator extends InUseStateAggregator<Object> {
1✔
2123
    @Override
2124
    protected void handleInUse() {
2125
      exitIdleMode();
1✔
2126
    }
1✔
2127

2128
    @Override
2129
    protected void handleNotInUse() {
2130
      if (shutdown.get()) {
1✔
2131
        return;
1✔
2132
      }
2133
      rescheduleIdleTimer();
1✔
2134
    }
1✔
2135
  }
2136

2137
  /**
2138
   * Lazily request for Executor from an executor pool.
2139
   * Also act as an Executor directly to simply run a cmd
2140
   */
2141
  @VisibleForTesting
2142
  static final class ExecutorHolder implements Executor {
2143
    private final ObjectPool<? extends Executor> pool;
2144
    private Executor executor;
2145

2146
    ExecutorHolder(ObjectPool<? extends Executor> executorPool) {
1✔
2147
      this.pool = checkNotNull(executorPool, "executorPool");
1✔
2148
    }
1✔
2149

2150
    synchronized Executor getExecutor() {
2151
      if (executor == null) {
1✔
2152
        executor = checkNotNull(pool.getObject(), "%s.getObject()", executor);
1✔
2153
      }
2154
      return executor;
1✔
2155
    }
2156

2157
    synchronized void release() {
2158
      if (executor != null) {
1✔
2159
        executor = pool.returnObject(executor);
1✔
2160
      }
2161
    }
1✔
2162

2163
    @Override
2164
    public void execute(Runnable command) {
2165
      getExecutor().execute(command);
1✔
2166
    }
1✔
2167
  }
2168

2169
  private static final class RestrictedScheduledExecutor implements ScheduledExecutorService {
2170
    final ScheduledExecutorService delegate;
2171

2172
    private RestrictedScheduledExecutor(ScheduledExecutorService delegate) {
1✔
2173
      this.delegate = checkNotNull(delegate, "delegate");
1✔
2174
    }
1✔
2175

2176
    @Override
2177
    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
2178
      return delegate.schedule(callable, delay, unit);
×
2179
    }
2180

2181
    @Override
2182
    public ScheduledFuture<?> schedule(Runnable cmd, long delay, TimeUnit unit) {
2183
      return delegate.schedule(cmd, delay, unit);
1✔
2184
    }
2185

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

2192
    @Override
2193
    public ScheduledFuture<?> scheduleWithFixedDelay(
2194
        Runnable command, long initialDelay, long delay, TimeUnit unit) {
2195
      return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
×
2196
    }
2197

2198
    @Override
2199
    public boolean awaitTermination(long timeout, TimeUnit unit)
2200
        throws InterruptedException {
2201
      return delegate.awaitTermination(timeout, unit);
×
2202
    }
2203

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

2210
    @Override
2211
    public <T> List<Future<T>> invokeAll(
2212
        Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2213
        throws InterruptedException {
2214
      return delegate.invokeAll(tasks, timeout, unit);
×
2215
    }
2216

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

2223
    @Override
2224
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2225
        throws InterruptedException, ExecutionException, TimeoutException {
2226
      return delegate.invokeAny(tasks, timeout, unit);
×
2227
    }
2228

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

2234
    @Override
2235
    public boolean isTerminated() {
2236
      return delegate.isTerminated();
×
2237
    }
2238

2239
    @Override
2240
    public void shutdown() {
2241
      throw new UnsupportedOperationException("Restricted: shutdown() is not allowed");
1✔
2242
    }
2243

2244
    @Override
2245
    public List<Runnable> shutdownNow() {
2246
      throw new UnsupportedOperationException("Restricted: shutdownNow() is not allowed");
1✔
2247
    }
2248

2249
    @Override
2250
    public <T> Future<T> submit(Callable<T> task) {
2251
      return delegate.submit(task);
×
2252
    }
2253

2254
    @Override
2255
    public Future<?> submit(Runnable task) {
2256
      return delegate.submit(task);
×
2257
    }
2258

2259
    @Override
2260
    public <T> Future<T> submit(Runnable task, T result) {
2261
      return delegate.submit(task, result);
×
2262
    }
2263

2264
    @Override
2265
    public void execute(Runnable command) {
2266
      delegate.execute(command);
×
2267
    }
×
2268
  }
2269

2270
  /**
2271
   * A ResolutionState indicates the status of last name resolution.
2272
   */
2273
  enum ResolutionState {
1✔
2274
    NO_RESOLUTION,
1✔
2275
    SUCCESS,
1✔
2276
    ERROR
1✔
2277
  }
2278
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc