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

grpc / grpc-java / #20353

07 Jul 2026 10:24AM UTC coverage: 89.104% (-0.02%) from 89.122%
#20353

push

github

web-flow
enable child channel plugins (#12578)

Implements https://github.com/grpc/proposal/pull/529

38027 of 42677 relevant lines covered (89.1%)

0.89 hits per line

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

93.27
/../core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
1
/*
2
 * Copyright 2016 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc.internal;
18

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

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

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

131
  static final long IDLE_TIMEOUT_MILLIS_DISABLE = -1;
132

133
  static final long SUBCHANNEL_SHUTDOWN_DELAY_SECONDS = 5;
134

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

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

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

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

159
  /**
160
   * Retrieves the user-provided configuration function for internal child channels.
161
   *
162
   * <p>This is intended for use by gRPC internal components
163
   * that are responsible for creating auxiliary {@code ManagedChannel} instances.
164
   */
165
  private final ChannelConfigurator channelConfigurator;
166

167
  private final InternalLogId logId;
168
  private final String target;
169
  @Nullable
170
  private final String authorityOverride;
171
  private final NameResolverRegistry nameResolverRegistry;
172
  private final UriWrapper targetUri;
173
  private final NameResolverProvider nameResolverProvider;
174
  private final NameResolver.Args nameResolverArgs;
175
  private final LoadBalancerProvider loadBalancerFactory;
176
  private final ClientTransportFactory originalTransportFactory;
177
  @Nullable
178
  private final ChannelCredentials originalChannelCreds;
179
  private final ClientTransportFactory transportFactory;
180
  private final RestrictedScheduledExecutor scheduledExecutor;
181
  private final Executor executor;
182
  private final ObjectPool<? extends Executor> executorPool;
183
  private final ExecutorHolder balancerRpcExecutorHolder;
184
  private final ExecutorHolder offloadExecutorHolder;
185
  private final TimeProvider timeProvider;
186
  private final int maxTraceEvents;
187

188
  @VisibleForTesting
1✔
189
  final SynchronizationContext syncContext = new SynchronizationContext(
190
      new Thread.UncaughtExceptionHandler() {
1✔
191
        @Override
192
        public void uncaughtException(Thread t, Throwable e) {
193
          logger.log(
1✔
194
              Level.SEVERE,
195
              "[" + getLogId() + "] Uncaught exception in the SynchronizationContext. Panic!",
1✔
196
              e);
197
          try {
198
            panic(e);
1✔
199
          } catch (Throwable anotherT) {
×
200
            logger.log(
×
201
                Level.SEVERE, "[" + getLogId() + "] Uncaught exception while panicking", anotherT);
×
202
          }
1✔
203
        }
1✔
204
      });
205

206
  private boolean fullStreamDecompression;
207

208
  private final DecompressorRegistry decompressorRegistry;
209
  private final CompressorRegistry compressorRegistry;
210

211
  private final Supplier<Stopwatch> stopwatchSupplier;
212
  /** The timeout before entering idle mode. */
213
  private final long idleTimeoutMillis;
214

215
  private final ConnectivityStateManager channelStateManager = new ConnectivityStateManager();
1✔
216
  private final BackoffPolicy.Provider backoffPolicyProvider;
217

218
  /**
219
   * We delegate to this channel, so that we can have interceptors as necessary. If there aren't
220
   * any interceptors and the {@link io.grpc.BinaryLog} is {@code null} then this will just be a
221
   * {@link RealChannel}.
222
   */
223
  private final Channel interceptorChannel;
224

225
  private final List<ClientTransportFilter> transportFilters;
226
  @Nullable private final String userAgent;
227

228
  // Only null after channel is terminated. Must be assigned from the syncContext.
229
  private NameResolver nameResolver;
230

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

234
  // null when channel is in idle mode.  Must be assigned from syncContext.
235
  @Nullable
236
  private LbHelperImpl lbHelper;
237

238
  // Must be accessed from the syncContext
239
  private boolean panicMode;
240

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

246
  // Must be accessed from syncContext
247
  @Nullable
248
  private Collection<RealChannel.PendingCall<?, ?>> pendingCalls;
249
  private final Object pendingCallsInUseObject = new Object();
1✔
250

251
  // reprocess() must be run from syncContext
252
  private final DelayedClientTransport delayedTransport;
253
  private final UncommittedRetriableStreamsRegistry uncommittedRetriableStreamsRegistry
1✔
254
      = new UncommittedRetriableStreamsRegistry();
255

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

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

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

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

299
  // One instance per channel.
300
  private final ChannelBufferMeter channelBufferUsed = new ChannelBufferMeter();
1✔
301

302
  private final long perRpcBufferLimit;
303
  private final long channelBufferLimit;
304

305
  // Temporary false flag that can skip the retry code path.
306
  private final boolean retryEnabled;
307

308
  private final Deadline.Ticker ticker = Deadline.getSystemTicker();
1✔
309

310
  // Called from syncContext
311
  private final ManagedClientTransport.Listener delayedTransportListener =
1✔
312
      new DelayedTransportListener();
313

314
  // Must be called from syncContext
315
  private void maybeShutdownNowSubchannels() {
316
    if (shutdownNowed) {
1✔
317
      for (InternalSubchannel subchannel : subchannels) {
1✔
318
        subchannel.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
        builder.setSubchannels(children);
1✔
340
        ret.set(builder.build());
1✔
341
      }
1✔
342
    }
343

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

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

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

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

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

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

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

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

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

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

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

470
  private final class ChannelStreamProvider implements ClientStreamProvider {
1✔
471
    volatile Throttle throttle;
472

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

694
    if (overrideAuthority == null) {
1✔
695
      return usedNameResolver;
1✔
696
    }
697

698
    return new ForwardingNameResolver(usedNameResolver) {
1✔
699
      @Override
700
      public String getServiceAuthority() {
701
        return overrideAuthority;
1✔
702
      }
703
    };
704
  }
705

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

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

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

743
    syncContext.execute(new CancelIdleTimer());
1✔
744
    return this;
1✔
745
  }
746

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

768
    syncContext.execute(new ShutdownNow());
1✔
769
    return this;
1✔
770
  }
771

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

792
  @VisibleForTesting
793
  boolean isInPanicMode() {
794
    return panicMode;
1✔
795
  }
796

797
  // Called from syncContext
798
  private void updateSubchannelPicker(SubchannelPicker newPicker) {
799
    delayedTransport.reprocess(newPicker);
1✔
800
  }
1✔
801

802
  @Override
803
  public boolean isShutdown() {
804
    return shutdown.get();
1✔
805
  }
806

807
  @Override
808
  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
809
    return terminatedLatch.await(timeout, unit);
1✔
810
  }
811

812
  @Override
813
  public boolean isTerminated() {
814
    return terminated;
1✔
815
  }
816

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

826
  @Override
827
  public String authority() {
828
    return interceptorChannel.authority();
1✔
829
  }
830

831
  private Executor getCallExecutor(CallOptions callOptions) {
832
    Executor executor = callOptions.getExecutor();
1✔
833
    if (executor == null) {
1✔
834
      executor = this.executor;
1✔
835
    }
836
    return executor;
1✔
837
  }
838

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

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

865
      @Override
866
      public String authority() {
867
        return authority;
×
868
      }
869
    };
870

871
    private RealChannel(String authority) {
1✔
872
      this.authority =  checkNotNull(authority, "authority");
1✔
873
    }
1✔
874

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

901
          @Override public void request(int numMessages) {}
×
902

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

905
          @Override public void halfClose() {}
×
906

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

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

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

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

968
      syncContext.execute(new RealChannelShutdown());
1✔
969
    }
1✔
970

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

987
      syncContext.execute(new RealChannelShutdownNow());
1✔
988
    }
1✔
989

990
    @Override
991
    public String authority() {
992
      return authority;
1✔
993
    }
994

995
    private final class PendingCall<ReqT, RespT> extends DelayedClientCall<ReqT, RespT> {
996
      final Context context;
997
      final MethodDescriptor<ReqT, RespT> method;
998
      final CallOptions callOptions;
999
      private final long callCreationTime;
1000

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

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

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

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

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

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

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

1093
    private ClientCall<ReqT, RespT> delegate;
1094

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1209
  @Override
1210
  public ConnectivityState getState(boolean requestConnection) {
1211
    ConnectivityState savedChannelState = channelStateManager.getState();
1✔
1212
    if (requestConnection && savedChannelState == IDLE) {
1✔
1213
      final class RequestConnection implements Runnable {
1✔
1214
        @Override
1215
        public void run() {
1216
          exitIdleMode();
1✔
1217
          if (lbHelper != null) {
1✔
1218
            lbHelper.lb.requestConnection();
1✔
1219
          }
1220
        }
1✔
1221
      }
1222

1223
      syncContext.execute(new RequestConnection());
1✔
1224
    }
1225
    return savedChannelState;
1✔
1226
  }
1227

1228
  @Override
1229
  public void notifyWhenStateChanged(final ConnectivityState source, final Runnable callback) {
1230
    final class NotifyStateChanged implements Runnable {
1✔
1231
      @Override
1232
      public void run() {
1233
        channelStateManager.notifyWhenStateChanged(callback, executor, source);
1✔
1234
      }
1✔
1235
    }
1236

1237
    syncContext.execute(new NotifyStateChanged());
1✔
1238
  }
1✔
1239

1240
  @Override
1241
  public void resetConnectBackoff() {
1242
    final class ResetConnectBackoff implements Runnable {
1✔
1243
      @Override
1244
      public void run() {
1245
        if (shutdown.get()) {
1✔
1246
          return;
1✔
1247
        }
1248
        if (nameResolverStarted) {
1✔
1249
          refreshNameResolution();
1✔
1250
        }
1251
        for (InternalSubchannel subchannel : subchannels) {
1✔
1252
          subchannel.resetConnectBackoff();
1✔
1253
        }
1✔
1254
      }
1✔
1255
    }
1256

1257
    syncContext.execute(new ResetConnectBackoff());
1✔
1258
  }
1✔
1259

1260
  @Override
1261
  public void enterIdle() {
1262
    final class PrepareToLoseNetworkRunnable implements Runnable {
1✔
1263
      @Override
1264
      public void run() {
1265
        if (shutdown.get() || lbHelper == null) {
1✔
1266
          return;
1✔
1267
        }
1268
        cancelIdleTimer(/* permanent= */ false);
1✔
1269
        enterIdleMode();
1✔
1270
      }
1✔
1271
    }
1272

1273
    syncContext.execute(new PrepareToLoseNetworkRunnable());
1✔
1274
  }
1✔
1275

1276
  /**
1277
   * A registry that prevents channel shutdown from killing existing retry attempts that are in
1278
   * backoff.
1279
   */
1280
  private final class UncommittedRetriableStreamsRegistry {
1✔
1281
    // TODO(zdapeng): This means we would acquire a lock for each new retry-able stream,
1282
    // it's worthwhile to look for a lock-free approach.
1283
    final Object lock = new Object();
1✔
1284

1285
    @GuardedBy("lock")
1✔
1286
    Collection<ClientStream> uncommittedRetriableStreams = new HashSet<>();
1287

1288
    @GuardedBy("lock")
1289
    Status shutdownStatus;
1290

1291
    void onShutdown(Status reason) {
1292
      boolean shouldShutdownDelayedTransport = false;
1✔
1293
      synchronized (lock) {
1✔
1294
        if (shutdownStatus != null) {
1✔
1295
          return;
1✔
1296
        }
1297
        shutdownStatus = reason;
1✔
1298
        // Keep the delayedTransport open until there is no more uncommitted streams, b/c those
1299
        // retriable streams, which may be in backoff and not using any transport, are already
1300
        // started RPCs.
1301
        if (uncommittedRetriableStreams.isEmpty()) {
1✔
1302
          shouldShutdownDelayedTransport = true;
1✔
1303
        }
1304
      }
1✔
1305

1306
      if (shouldShutdownDelayedTransport) {
1✔
1307
        delayedTransport.shutdown(reason);
1✔
1308
      }
1309
    }
1✔
1310

1311
    void onShutdownNow(Status reason) {
1312
      onShutdown(reason);
1✔
1313
      Collection<ClientStream> streams;
1314

1315
      synchronized (lock) {
1✔
1316
        streams = new ArrayList<>(uncommittedRetriableStreams);
1✔
1317
      }
1✔
1318

1319
      for (ClientStream stream : streams) {
1✔
1320
        stream.cancel(reason);
1✔
1321
      }
1✔
1322
      delayedTransport.shutdownNow(reason);
1✔
1323
    }
1✔
1324

1325
    /**
1326
     * Registers a RetriableStream and return null if not shutdown, otherwise just returns the
1327
     * shutdown Status.
1328
     */
1329
    @Nullable
1330
    Status add(RetriableStream<?> retriableStream) {
1331
      synchronized (lock) {
1✔
1332
        if (shutdownStatus != null) {
1✔
1333
          return shutdownStatus;
1✔
1334
        }
1335
        uncommittedRetriableStreams.add(retriableStream);
1✔
1336
        return null;
1✔
1337
      }
1338
    }
1339

1340
    void remove(RetriableStream<?> retriableStream) {
1341
      Status shutdownStatusCopy = null;
1✔
1342

1343
      synchronized (lock) {
1✔
1344
        uncommittedRetriableStreams.remove(retriableStream);
1✔
1345
        if (uncommittedRetriableStreams.isEmpty()) {
1✔
1346
          shutdownStatusCopy = shutdownStatus;
1✔
1347
          // Because retriable transport is long-lived, we take this opportunity to down-size the
1348
          // hashmap.
1349
          uncommittedRetriableStreams = new HashSet<>();
1✔
1350
        }
1351
      }
1✔
1352

1353
      if (shutdownStatusCopy != null) {
1✔
1354
        delayedTransport.shutdown(shutdownStatusCopy);
1✔
1355
      }
1356
    }
1✔
1357
  }
1358

1359
  private final class LbHelperImpl extends LoadBalancer.Helper {
1✔
1360
    LoadBalancer lb;
1361

1362
    @Override
1363
    public AbstractSubchannel createSubchannel(CreateSubchannelArgs args) {
1364
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1365
      // No new subchannel should be created after load balancer has been shutdown.
1366
      checkState(!terminating, "Channel is being terminated");
1✔
1367
      return new SubchannelImpl(args);
1✔
1368
    }
1369

1370
    @Override
1371
    public void updateBalancingState(
1372
        final ConnectivityState newState, final SubchannelPicker newPicker) {
1373
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1374
      checkNotNull(newState, "newState");
1✔
1375
      checkNotNull(newPicker, "newPicker");
1✔
1376

1377
      if (LbHelperImpl.this != lbHelper || panicMode) {
1✔
1378
        return;
1✔
1379
      }
1380
      updateSubchannelPicker(newPicker);
1✔
1381
      // It's not appropriate to report SHUTDOWN state from lb.
1382
      // Ignore the case of newState == SHUTDOWN for now.
1383
      if (newState != SHUTDOWN) {
1✔
1384
        channelLogger.log(
1✔
1385
            ChannelLogLevel.INFO, "Entering {0} state with picker: {1}", newState, newPicker);
1386
        channelStateManager.gotoState(newState);
1✔
1387
      }
1388
    }
1✔
1389

1390
    @Override
1391
    public void refreshNameResolution() {
1392
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1393
      final class LoadBalancerRefreshNameResolution implements Runnable {
1✔
1394
        @Override
1395
        public void run() {
1396
          ManagedChannelImpl.this.refreshNameResolution();
1✔
1397
        }
1✔
1398
      }
1399

1400
      syncContext.execute(new LoadBalancerRefreshNameResolution());
1✔
1401
    }
1✔
1402

1403
    @Override
1404
    public ManagedChannel createOobChannel(EquivalentAddressGroup addressGroup, String authority) {
1405
      return createOobChannel(Collections.singletonList(addressGroup), authority);
×
1406
    }
1407

1408
    @Override
1409
    public ManagedChannel createOobChannel(List<EquivalentAddressGroup> addressGroup,
1410
        String authority) {
1411
      NameResolverRegistry nameResolverRegistry = new NameResolverRegistry();
1✔
1412
      OobNameResolverProvider resolverProvider =
1✔
1413
          new OobNameResolverProvider(authority, addressGroup, syncContext);
1414
      nameResolverRegistry.register(resolverProvider);
1✔
1415
      // We could use a hard-coded target, as the name resolver won't actually use this string.
1416
      // However, that would make debugging less clear, as we use the target to identify the
1417
      // channel.
1418
      String target;
1419
      try {
1420
        target = new URI("oob", "", "/" + authority, null, null).toString();
1✔
1421
      } catch (URISyntaxException ex) {
×
1422
        // Any special characters in the path will be percent encoded. So this should be impossible.
1423
        throw new AssertionError(ex);
×
1424
      }
1✔
1425
      ManagedChannel delegate = createResolvingOobChannelBuilder(
1✔
1426
          target, new DefaultChannelCreds(), nameResolverRegistry)
1427
          // TODO(zdapeng): executors should not outlive the parent channel.
1428
          .executor(balancerRpcExecutorHolder.getExecutor())
1✔
1429
          .idleTimeout(Integer.MAX_VALUE, TimeUnit.SECONDS)
1✔
1430
          .disableRetry()
1✔
1431
          .build();
1✔
1432
      return new OobChannel(delegate, resolverProvider);
1✔
1433
    }
1434

1435
    @Deprecated
1436
    @Override
1437
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
1438
      return createResolvingOobChannelBuilder(target, new DefaultChannelCreds())
1✔
1439
          // Override authority to keep the old behavior.
1440
          // createResolvingOobChannelBuilder(String target) will be deleted soon.
1441
          .overrideAuthority(getAuthority());
1✔
1442
    }
1443

1444
    @Override
1445
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1446
        final String target, final ChannelCredentials channelCreds) {
1447
      return createResolvingOobChannelBuilder(target, channelCreds, nameResolverRegistry);
1✔
1448
    }
1449

1450
    // TODO(creamsoup) prevent main channel to shutdown if oob channel is not terminated
1451
    // TODO(zdapeng) register the channel as a subchannel of the parent channel in channelz.
1452
    private ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1453
        final String target, final ChannelCredentials channelCreds,
1454
        NameResolverRegistry nameResolverRegistry) {
1455
      checkNotNull(channelCreds, "channelCreds");
1✔
1456

1457
      final class ResolvingOobChannelBuilder
1458
          extends ForwardingChannelBuilder2<ResolvingOobChannelBuilder> {
1459
        final ManagedChannelBuilder<?> delegate;
1460

1461
        ResolvingOobChannelBuilder() {
1✔
1462
          final ClientTransportFactory transportFactory;
1463
          CallCredentials callCredentials;
1464
          if (channelCreds instanceof DefaultChannelCreds) {
1✔
1465
            transportFactory = originalTransportFactory;
1✔
1466
            callCredentials = null;
1✔
1467
          } else {
1468
            SwapChannelCredentialsResult swapResult =
1✔
1469
                originalTransportFactory.swapChannelCredentials(channelCreds);
1✔
1470
            if (swapResult == null) {
1✔
1471
              delegate = Grpc.newChannelBuilder(target, channelCreds);
×
1472
              return;
×
1473
            } else {
1474
              transportFactory = swapResult.transportFactory;
1✔
1475
              callCredentials = swapResult.callCredentials;
1✔
1476
            }
1477
          }
1478
          ClientTransportFactoryBuilder transportFactoryBuilder =
1✔
1479
              new ClientTransportFactoryBuilder() {
1✔
1480
                @Override
1481
                public ClientTransportFactory buildClientTransportFactory() {
1482
                  return transportFactory;
1✔
1483
                }
1484
              };
1485
          delegate = new ManagedChannelImplBuilder(
1✔
1486
              target,
1487
              channelCreds,
1488
              callCredentials,
1489
              transportFactoryBuilder,
1490
              new FixedPortProvider(nameResolverArgs.getDefaultPort()))
1✔
1491
              .nameResolverRegistry(nameResolverRegistry);
1✔
1492
        }
1✔
1493

1494
        @Override
1495
        protected ManagedChannelBuilder<?> delegate() {
1496
          return delegate;
1✔
1497
        }
1498
      }
1499

1500
      checkState(!terminated, "Channel is terminated");
1✔
1501

1502
      ResolvingOobChannelBuilder builder = new ResolvingOobChannelBuilder();
1✔
1503

1504
      // Note that we follow the global configurator pattern and try to fuse the configurations as
1505
      // soon as the builder gets created
1506
      channelConfigurator.configureChannelBuilder(builder);
1✔
1507
      builder.childChannelConfigurator(channelConfigurator);
1✔
1508

1509
      return builder
1✔
1510
          // TODO(zdapeng): executors should not outlive the parent channel.
1511
          .executor(executor)
1✔
1512
          .offloadExecutor(offloadExecutorHolder.getExecutor())
1✔
1513
          .maxTraceEvents(maxTraceEvents)
1✔
1514
          .proxyDetector(nameResolverArgs.getProxyDetector())
1✔
1515
          .userAgent(userAgent);
1✔
1516
    }
1517

1518
    @Override
1519
    public ChannelCredentials getUnsafeChannelCredentials() {
1520
      if (originalChannelCreds == null) {
1✔
1521
        return new DefaultChannelCreds();
1✔
1522
      }
1523
      return originalChannelCreds;
×
1524
    }
1525

1526
    @Override
1527
    public void updateOobChannelAddresses(ManagedChannel channel, EquivalentAddressGroup eag) {
1528
      updateOobChannelAddresses(channel, Collections.singletonList(eag));
×
1529
    }
×
1530

1531
    @Override
1532
    public void updateOobChannelAddresses(ManagedChannel channel,
1533
        List<EquivalentAddressGroup> eag) {
1534
      checkArgument(channel instanceof OobChannel,
1✔
1535
          "channel must have been returned from createOobChannel");
1536
      ((OobChannel) channel).updateAddresses(eag);
1✔
1537
    }
1✔
1538

1539
    @Override
1540
    public String getAuthority() {
1541
      return ManagedChannelImpl.this.authority();
1✔
1542
    }
1543

1544
    @Override
1545
    public String getChannelTarget() {
1546
      return targetUri.toString();
1✔
1547
    }
1548

1549
    @Override
1550
    public SynchronizationContext getSynchronizationContext() {
1551
      return syncContext;
1✔
1552
    }
1553

1554
    @Override
1555
    public ScheduledExecutorService getScheduledExecutorService() {
1556
      return scheduledExecutor;
1✔
1557
    }
1558

1559
    @Override
1560
    public ChannelLogger getChannelLogger() {
1561
      return channelLogger;
1✔
1562
    }
1563

1564
    @Override
1565
    public NameResolver.Args getNameResolverArgs() {
1566
      return nameResolverArgs;
1✔
1567
    }
1568

1569
    @Override
1570
    public NameResolverRegistry getNameResolverRegistry() {
1571
      return nameResolverRegistry;
1✔
1572
    }
1573

1574
    @Override
1575
    public MetricRecorder getMetricRecorder() {
1576
      return metricRecorder;
1✔
1577
    }
1578

1579
    /**
1580
     * A placeholder for channel creds if user did not specify channel creds for the channel.
1581
     */
1582
    // TODO(zdapeng): get rid of this class and let all ChannelBuilders always provide a non-null
1583
    //     channel creds.
1584
    final class DefaultChannelCreds extends ChannelCredentials {
1✔
1585
      @Override
1586
      public ChannelCredentials withoutBearerTokens() {
1587
        return this;
×
1588
      }
1589
    }
1590
  }
1591

1592
  static final class OobChannel extends ForwardingManagedChannel {
1593
    private final OobNameResolverProvider resolverProvider;
1594

1595
    public OobChannel(ManagedChannel delegate, OobNameResolverProvider resolverProvider) {
1596
      super(delegate);
1✔
1597
      this.resolverProvider = checkNotNull(resolverProvider, "resolverProvider");
1✔
1598
    }
1✔
1599

1600
    public void updateAddresses(List<EquivalentAddressGroup> eags) {
1601
      resolverProvider.updateAddresses(eags);
1✔
1602
    }
1✔
1603
  }
1604

1605
  final class NameResolverListener extends NameResolver.Listener2 {
1606
    final LbHelperImpl helper;
1607
    final NameResolver resolver;
1608

1609
    NameResolverListener(LbHelperImpl helperImpl, NameResolver resolver) {
1✔
1610
      this.helper = checkNotNull(helperImpl, "helperImpl");
1✔
1611
      this.resolver = checkNotNull(resolver, "resolver");
1✔
1612
    }
1✔
1613

1614
    @Override
1615
    public void onResult(final ResolutionResult resolutionResult) {
1616
      syncContext.execute(() -> onResult2(resolutionResult));
×
1617
    }
×
1618

1619
    @SuppressWarnings("ReferenceEquality")
1620
    @Override
1621
    public Status onResult2(final ResolutionResult resolutionResult) {
1622
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1623
      if (ManagedChannelImpl.this.nameResolver != resolver) {
1✔
1624
        return Status.OK;
1✔
1625
      }
1626

1627
      StatusOr<List<EquivalentAddressGroup>> serversOrError =
1✔
1628
          resolutionResult.getAddressesOrError();
1✔
1629
      if (!serversOrError.hasValue()) {
1✔
1630
        handleErrorInSyncContext(serversOrError.getStatus());
1✔
1631
        return serversOrError.getStatus();
1✔
1632
      }
1633
      List<EquivalentAddressGroup> servers = serversOrError.getValue();
1✔
1634
      channelLogger.log(
1✔
1635
          ChannelLogLevel.DEBUG,
1636
          "Resolved address: {0}, config={1}",
1637
          servers,
1638
          resolutionResult.getAttributes());
1✔
1639

1640
      if (lastResolutionState != ResolutionState.SUCCESS) {
1✔
1641
        channelLogger.log(ChannelLogLevel.INFO, "Address resolved: {0}",
1✔
1642
            servers);
1643
        lastResolutionState = ResolutionState.SUCCESS;
1✔
1644
      }
1645
      ConfigOrError configOrError = resolutionResult.getServiceConfig();
1✔
1646
      InternalConfigSelector resolvedConfigSelector =
1✔
1647
          resolutionResult.getAttributes().get(InternalConfigSelector.KEY);
1✔
1648
      ManagedChannelServiceConfig validServiceConfig =
1649
          configOrError != null && configOrError.getConfig() != null
1✔
1650
              ? (ManagedChannelServiceConfig) configOrError.getConfig()
1✔
1651
              : null;
1✔
1652
      Status serviceConfigError = configOrError != null ? configOrError.getError() : null;
1✔
1653

1654
      ManagedChannelServiceConfig effectiveServiceConfig;
1655
      if (!lookUpServiceConfig) {
1✔
1656
        if (validServiceConfig != null) {
1✔
1657
          channelLogger.log(
1✔
1658
              ChannelLogLevel.INFO,
1659
              "Service config from name resolver discarded by channel settings");
1660
        }
1661
        effectiveServiceConfig =
1662
            defaultServiceConfig == null ? EMPTY_SERVICE_CONFIG : defaultServiceConfig;
1✔
1663
        if (resolvedConfigSelector != null) {
1✔
1664
          channelLogger.log(
1✔
1665
              ChannelLogLevel.INFO,
1666
              "Config selector from name resolver discarded by channel settings");
1667
        }
1668
        realChannel.updateConfigSelector(effectiveServiceConfig.getDefaultConfigSelector());
1✔
1669
      } else {
1670
        // Try to use config if returned from name resolver
1671
        // Otherwise, try to use the default config if available
1672
        if (validServiceConfig != null) {
1✔
1673
          effectiveServiceConfig = validServiceConfig;
1✔
1674
          if (resolvedConfigSelector != null) {
1✔
1675
            realChannel.updateConfigSelector(resolvedConfigSelector);
1✔
1676
            if (effectiveServiceConfig.getDefaultConfigSelector() != null) {
1✔
1677
              channelLogger.log(
×
1678
                  ChannelLogLevel.DEBUG,
1679
                  "Method configs in service config will be discarded due to presence of"
1680
                      + "config-selector");
1681
            }
1682
          } else {
1683
            realChannel.updateConfigSelector(effectiveServiceConfig.getDefaultConfigSelector());
1✔
1684
          }
1685
        } else if (defaultServiceConfig != null) {
1✔
1686
          effectiveServiceConfig = defaultServiceConfig;
1✔
1687
          realChannel.updateConfigSelector(effectiveServiceConfig.getDefaultConfigSelector());
1✔
1688
          channelLogger.log(
1✔
1689
              ChannelLogLevel.INFO,
1690
              "Received no service config, using default service config");
1691
        } else if (serviceConfigError != null) {
1✔
1692
          if (!serviceConfigUpdated) {
1✔
1693
            // First DNS lookup has invalid service config, and cannot fall back to default
1694
            channelLogger.log(
1✔
1695
                ChannelLogLevel.INFO,
1696
                "Fallback to error due to invalid first service config without default config");
1697
            // This error could be an "inappropriate" control plane error that should not bleed
1698
            // through to client code using gRPC. We let them flow through here to the LB as
1699
            // we later check for these error codes when investigating pick results in
1700
            // GrpcUtil.getTransportFromPickResult().
1701
            onError(configOrError.getError());
1✔
1702
            return configOrError.getError();
1✔
1703
          } else {
1704
            effectiveServiceConfig = lastServiceConfig;
1✔
1705
          }
1706
        } else {
1707
          effectiveServiceConfig = EMPTY_SERVICE_CONFIG;
1✔
1708
          realChannel.updateConfigSelector(null);
1✔
1709
        }
1710
        if (!effectiveServiceConfig.equals(lastServiceConfig)) {
1✔
1711
          channelLogger.log(
1✔
1712
              ChannelLogLevel.INFO,
1713
              "Service config changed{0}",
1714
              effectiveServiceConfig == EMPTY_SERVICE_CONFIG ? " to empty" : "");
1✔
1715
          lastServiceConfig = effectiveServiceConfig;
1✔
1716
          transportProvider.throttle = effectiveServiceConfig.getRetryThrottling();
1✔
1717
        }
1718

1719
        try {
1720
          // TODO(creamsoup): when `serversOrError` is empty and lastResolutionStateCopy == SUCCESS
1721
          //  and lbNeedAddress, it shouldn't call the handleServiceConfigUpdate. But,
1722
          //  lbNeedAddress is not deterministic
1723
          serviceConfigUpdated = true;
1✔
1724
        } catch (RuntimeException re) {
×
1725
          logger.log(
×
1726
              Level.WARNING,
1727
              "[" + getLogId() + "] Unexpected exception from parsing service config",
×
1728
              re);
1729
        }
1✔
1730
      }
1731

1732
      Attributes effectiveAttrs = resolutionResult.getAttributes();
1✔
1733
      // Call LB only if it's not shutdown.  If LB is shutdown, lbHelper won't match.
1734
      if (NameResolverListener.this.helper == ManagedChannelImpl.this.lbHelper) {
1✔
1735
        Attributes.Builder attrBuilder =
1✔
1736
            effectiveAttrs.toBuilder().discard(InternalConfigSelector.KEY);
1✔
1737
        Map<String, ?> healthCheckingConfig =
1✔
1738
            effectiveServiceConfig.getHealthCheckingConfig();
1✔
1739
        if (healthCheckingConfig != null) {
1✔
1740
          attrBuilder
1✔
1741
              .set(LoadBalancer.ATTR_HEALTH_CHECKING_CONFIG, healthCheckingConfig)
1✔
1742
              .build();
1✔
1743
        }
1744
        Attributes attributes = attrBuilder.build();
1✔
1745

1746
        ResolvedAddresses.Builder resolvedAddresses = ResolvedAddresses.newBuilder()
1✔
1747
            .setAddresses(serversOrError.getValue())
1✔
1748
            .setAttributes(attributes)
1✔
1749
            .setLoadBalancingPolicyConfig(effectiveServiceConfig.getLoadBalancingConfig());
1✔
1750
        Status addressAcceptanceStatus = helper.lb.acceptResolvedAddresses(
1✔
1751
            resolvedAddresses.build());
1✔
1752
        return addressAcceptanceStatus;
1✔
1753
      }
1754
      return Status.OK;
×
1755
    }
1756

1757
    @Override
1758
    public void onError(final Status error) {
1759
      checkArgument(!error.isOk(), "the error status must not be OK");
1✔
1760
      final class NameResolverErrorHandler implements Runnable {
1✔
1761
        @Override
1762
        public void run() {
1763
          handleErrorInSyncContext(error);
1✔
1764
        }
1✔
1765
      }
1766

1767
      syncContext.execute(new NameResolverErrorHandler());
1✔
1768
    }
1✔
1769

1770
    private void handleErrorInSyncContext(Status error) {
1771
      logger.log(Level.WARNING, "[{0}] Failed to resolve name. status={1}",
1✔
1772
          new Object[] {getLogId(), error});
1✔
1773
      realChannel.onConfigError();
1✔
1774
      if (lastResolutionState != ResolutionState.ERROR) {
1✔
1775
        channelLogger.log(ChannelLogLevel.WARNING, "Failed to resolve name: {0}", error);
1✔
1776
        lastResolutionState = ResolutionState.ERROR;
1✔
1777
      }
1778
      // Call LB only if it's not shutdown.  If LB is shutdown, lbHelper won't match.
1779
      if (NameResolverListener.this.helper != ManagedChannelImpl.this.lbHelper) {
1✔
1780
        return;
1✔
1781
      }
1782

1783
      helper.lb.handleNameResolutionError(error);
1✔
1784
    }
1✔
1785
  }
1786

1787
  private final class SubchannelImpl extends AbstractSubchannel {
1788
    final CreateSubchannelArgs args;
1789
    final InternalLogId subchannelLogId;
1790
    final ChannelLoggerImpl subchannelLogger;
1791
    final ChannelTracer subchannelTracer;
1792
    List<EquivalentAddressGroup> addressGroups;
1793
    InternalSubchannel subchannel;
1794
    boolean started;
1795
    boolean shutdown;
1796
    ScheduledHandle delayedShutdownTask;
1797

1798
    SubchannelImpl(CreateSubchannelArgs args) {
1✔
1799
      checkNotNull(args, "args");
1✔
1800
      addressGroups = args.getAddresses();
1✔
1801
      if (authorityOverride != null) {
1✔
1802
        List<EquivalentAddressGroup> eagsWithoutOverrideAttr =
1✔
1803
            stripOverrideAuthorityAttributes(args.getAddresses());
1✔
1804
        args = args.toBuilder().setAddresses(eagsWithoutOverrideAttr).build();
1✔
1805
      }
1806
      this.args = args;
1✔
1807
      subchannelLogId = InternalLogId.allocate("Subchannel", /*details=*/ authority());
1✔
1808
      subchannelTracer = new ChannelTracer(
1✔
1809
          subchannelLogId, maxTraceEvents, timeProvider.currentTimeNanos(),
1✔
1810
          "Subchannel for " + args.getAddresses());
1✔
1811
      subchannelLogger = new ChannelLoggerImpl(subchannelTracer, timeProvider);
1✔
1812
    }
1✔
1813

1814
    @Override
1815
    public void start(final SubchannelStateListener listener) {
1816
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1817
      checkState(!started, "already started");
1✔
1818
      checkState(!shutdown, "already shutdown");
1✔
1819
      checkState(!terminating, "Channel is being terminated");
1✔
1820
      started = true;
1✔
1821
      final class ManagedInternalSubchannelCallback extends InternalSubchannel.Callback {
1✔
1822
        // All callbacks are run in syncContext
1823
        @Override
1824
        void onTerminated(InternalSubchannel is) {
1825
          subchannels.remove(is);
1✔
1826
          channelz.removeSubchannel(is);
1✔
1827
          maybeTerminateChannel();
1✔
1828
        }
1✔
1829

1830
        @Override
1831
        void onStateChange(InternalSubchannel is, ConnectivityStateInfo newState) {
1832
          checkState(listener != null, "listener is null");
1✔
1833
          listener.onSubchannelState(newState);
1✔
1834
        }
1✔
1835

1836
        @Override
1837
        void onInUse(InternalSubchannel is) {
1838
          inUseStateAggregator.updateObjectInUse(is, true);
1✔
1839
        }
1✔
1840

1841
        @Override
1842
        void onNotInUse(InternalSubchannel is) {
1843
          inUseStateAggregator.updateObjectInUse(is, false);
1✔
1844
        }
1✔
1845
      }
1846

1847
      final InternalSubchannel internalSubchannel = new InternalSubchannel(
1✔
1848
          args,
1849
          authority(),
1✔
1850
          userAgent,
1✔
1851
          backoffPolicyProvider,
1✔
1852
          transportFactory,
1✔
1853
          transportFactory.getScheduledExecutorService(),
1✔
1854
          stopwatchSupplier,
1✔
1855
          syncContext,
1856
          new ManagedInternalSubchannelCallback(),
1857
          channelz,
1✔
1858
          callTracerFactory.create(),
1✔
1859
          subchannelTracer,
1860
          subchannelLogId,
1861
          subchannelLogger,
1862
          transportFilters, target,
1✔
1863
          lbHelper.getMetricRecorder());
1✔
1864

1865
      channelTracer.reportEvent(new ChannelTrace.Event.Builder()
1✔
1866
          .setDescription("Child Subchannel started")
1✔
1867
          .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
1✔
1868
          .setTimestampNanos(timeProvider.currentTimeNanos())
1✔
1869
          .setSubchannelRef(internalSubchannel)
1✔
1870
          .build());
1✔
1871

1872
      this.subchannel = internalSubchannel;
1✔
1873
      channelz.addSubchannel(internalSubchannel);
1✔
1874
      subchannels.add(internalSubchannel);
1✔
1875
    }
1✔
1876

1877
    @Override
1878
    InternalInstrumented<ChannelStats> getInstrumentedInternalSubchannel() {
1879
      checkState(started, "not started");
1✔
1880
      return subchannel;
1✔
1881
    }
1882

1883
    @Override
1884
    public void shutdown() {
1885
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1886
      if (subchannel == null) {
1✔
1887
        // start() was not successful
1888
        shutdown = true;
×
1889
        return;
×
1890
      }
1891
      if (shutdown) {
1✔
1892
        if (terminating && delayedShutdownTask != null) {
1✔
1893
          // shutdown() was previously called when terminating == false, thus a delayed shutdown()
1894
          // was scheduled.  Now since terminating == true, We should expedite the shutdown.
1895
          delayedShutdownTask.cancel();
×
1896
          delayedShutdownTask = null;
×
1897
          // Will fall through to the subchannel.shutdown() at the end.
1898
        } else {
1899
          return;
1✔
1900
        }
1901
      } else {
1902
        shutdown = true;
1✔
1903
      }
1904
      // Add a delay to shutdown to deal with the race between 1) a transport being picked and
1905
      // newStream() being called on it, and 2) its Subchannel is shut down by LoadBalancer (e.g.,
1906
      // because of address change, or because LoadBalancer is shutdown by Channel entering idle
1907
      // mode). If (2) wins, the app will see a spurious error. We work around this by delaying
1908
      // shutdown of Subchannel for a few seconds here.
1909
      //
1910
      // TODO(zhangkun83): consider a better approach
1911
      // (https://github.com/grpc/grpc-java/issues/2562).
1912
      if (!terminating) {
1✔
1913
        final class ShutdownSubchannel implements Runnable {
1✔
1914
          @Override
1915
          public void run() {
1916
            subchannel.shutdown(SUBCHANNEL_SHUTDOWN_STATUS);
1✔
1917
          }
1✔
1918
        }
1919

1920
        delayedShutdownTask = syncContext.schedule(
1✔
1921
            new LogExceptionRunnable(new ShutdownSubchannel()),
1922
            SUBCHANNEL_SHUTDOWN_DELAY_SECONDS, TimeUnit.SECONDS,
1923
            transportFactory.getScheduledExecutorService());
1✔
1924
        return;
1✔
1925
      }
1926
      // When terminating == true, no more real streams will be created. It's safe and also
1927
      // desirable to shutdown timely.
1928
      subchannel.shutdown(SHUTDOWN_STATUS);
1✔
1929
    }
1✔
1930

1931
    @Override
1932
    public void requestConnection() {
1933
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1934
      checkState(started, "not started");
1✔
1935
      if (shutdown) {
1✔
1936
        return;
1✔
1937
      }
1938
      subchannel.obtainActiveTransport();
1✔
1939
    }
1✔
1940

1941
    @Override
1942
    public List<EquivalentAddressGroup> getAllAddresses() {
1943
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1944
      checkState(started, "not started");
1✔
1945
      return addressGroups;
1✔
1946
    }
1947

1948
    @Override
1949
    public Attributes getAttributes() {
1950
      return args.getAttributes();
1✔
1951
    }
1952

1953
    @Override
1954
    public String toString() {
1955
      return subchannelLogId.toString();
1✔
1956
    }
1957

1958
    @Override
1959
    public Channel asChannel() {
1960
      checkState(started, "not started");
1✔
1961
      return new SubchannelChannel(
1✔
1962
          subchannel, balancerRpcExecutorHolder.getExecutor(),
1✔
1963
          transportFactory.getScheduledExecutorService(),
1✔
1964
          callTracerFactory.create(),
1✔
1965
          new AtomicReference<InternalConfigSelector>(null));
1966
    }
1967

1968
    @Override
1969
    public Object getInternalSubchannel() {
1970
      checkState(started, "Subchannel is not started");
1✔
1971
      return subchannel;
1✔
1972
    }
1973

1974
    @Override
1975
    public ChannelLogger getChannelLogger() {
1976
      return subchannelLogger;
1✔
1977
    }
1978

1979
    @Override
1980
    public void updateAddresses(List<EquivalentAddressGroup> addrs) {
1981
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1982
      addressGroups = addrs;
1✔
1983
      if (authorityOverride != null) {
1✔
1984
        addrs = stripOverrideAuthorityAttributes(addrs);
1✔
1985
      }
1986
      subchannel.updateAddresses(addrs);
1✔
1987
    }
1✔
1988

1989
    @Override
1990
    public Attributes getConnectedAddressAttributes() {
1991
      return subchannel.getConnectedAddressAttributes();
1✔
1992
    }
1993

1994
    private List<EquivalentAddressGroup> stripOverrideAuthorityAttributes(
1995
        List<EquivalentAddressGroup> eags) {
1996
      List<EquivalentAddressGroup> eagsWithoutOverrideAttr = new ArrayList<>();
1✔
1997
      for (EquivalentAddressGroup eag : eags) {
1✔
1998
        EquivalentAddressGroup eagWithoutOverrideAttr = new EquivalentAddressGroup(
1✔
1999
            eag.getAddresses(),
1✔
2000
            eag.getAttributes().toBuilder().discard(ATTR_AUTHORITY_OVERRIDE).build());
1✔
2001
        eagsWithoutOverrideAttr.add(eagWithoutOverrideAttr);
1✔
2002
      }
1✔
2003
      return Collections.unmodifiableList(eagsWithoutOverrideAttr);
1✔
2004
    }
2005
  }
2006

2007
  @Override
2008
  public String toString() {
2009
    return MoreObjects.toStringHelper(this)
1✔
2010
        .add("logId", logId.getId())
1✔
2011
        .add("target", target)
1✔
2012
        .toString();
1✔
2013
  }
2014

2015
  /**
2016
   * Called from syncContext.
2017
   */
2018
  private final class DelayedTransportListener implements ManagedClientTransport.Listener {
1✔
2019
    @Override
2020
    public void transportShutdown(Status s, DisconnectError e) {
2021
      checkState(shutdown.get(), "Channel must have been shut down");
1✔
2022
    }
1✔
2023

2024
    @Override
2025
    public void transportReady() {
2026
      // Don't care
2027
    }
×
2028

2029
    @Override
2030
    public Attributes filterTransport(Attributes attributes) {
2031
      return attributes;
×
2032
    }
2033

2034
    @Override
2035
    public void transportInUse(final boolean inUse) {
2036
      inUseStateAggregator.updateObjectInUse(delayedTransport, inUse);
1✔
2037
      if (inUse) {
1✔
2038
        // It's possible to be in idle mode while inUseStateAggregator is in-use, if one of the
2039
        // subchannels is in use. But we should never be in idle mode when delayed transport is in
2040
        // use.
2041
        exitIdleMode();
1✔
2042
      }
2043
    }
1✔
2044

2045
    @Override
2046
    public void transportTerminated() {
2047
      checkState(shutdown.get(), "Channel must have been shut down");
1✔
2048
      terminating = true;
1✔
2049
      shutdownNameResolverAndLoadBalancer(false);
1✔
2050
      // No need to call channelStateManager since we are already in SHUTDOWN state.
2051
      // Until LoadBalancer is shutdown, it may still create new subchannels.  We catch them
2052
      // here.
2053
      maybeShutdownNowSubchannels();
1✔
2054
      maybeTerminateChannel();
1✔
2055
    }
1✔
2056
  }
2057

2058
  /**
2059
   * Must be accessed from syncContext.
2060
   */
2061
  private final class IdleModeStateAggregator extends InUseStateAggregator<Object> {
1✔
2062
    @Override
2063
    protected void handleInUse() {
2064
      exitIdleMode();
1✔
2065
    }
1✔
2066

2067
    @Override
2068
    protected void handleNotInUse() {
2069
      if (shutdown.get()) {
1✔
2070
        return;
1✔
2071
      }
2072
      rescheduleIdleTimer();
1✔
2073
    }
1✔
2074
  }
2075

2076
  /**
2077
   * Lazily request for Executor from an executor pool.
2078
   * Also act as an Executor directly to simply run a cmd
2079
   */
2080
  @VisibleForTesting
2081
  static final class ExecutorHolder implements Executor {
2082
    private final ObjectPool<? extends Executor> pool;
2083
    private Executor executor;
2084

2085
    ExecutorHolder(ObjectPool<? extends Executor> executorPool) {
1✔
2086
      this.pool = checkNotNull(executorPool, "executorPool");
1✔
2087
    }
1✔
2088

2089
    synchronized Executor getExecutor() {
2090
      if (executor == null) {
1✔
2091
        executor = checkNotNull(pool.getObject(), "%s.getObject()", executor);
1✔
2092
      }
2093
      return executor;
1✔
2094
    }
2095

2096
    synchronized void release() {
2097
      if (executor != null) {
1✔
2098
        executor = pool.returnObject(executor);
1✔
2099
      }
2100
    }
1✔
2101

2102
    @Override
2103
    public void execute(Runnable command) {
2104
      getExecutor().execute(command);
1✔
2105
    }
1✔
2106
  }
2107

2108
  private static final class RestrictedScheduledExecutor implements ScheduledExecutorService {
2109
    final ScheduledExecutorService delegate;
2110

2111
    private RestrictedScheduledExecutor(ScheduledExecutorService delegate) {
1✔
2112
      this.delegate = checkNotNull(delegate, "delegate");
1✔
2113
    }
1✔
2114

2115
    @Override
2116
    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
2117
      return delegate.schedule(callable, delay, unit);
×
2118
    }
2119

2120
    @Override
2121
    public ScheduledFuture<?> schedule(Runnable cmd, long delay, TimeUnit unit) {
2122
      return delegate.schedule(cmd, delay, unit);
1✔
2123
    }
2124

2125
    @Override
2126
    public ScheduledFuture<?> scheduleAtFixedRate(
2127
        Runnable command, long initialDelay, long period, TimeUnit unit) {
2128
      return delegate.scheduleAtFixedRate(command, initialDelay, period, unit);
1✔
2129
    }
2130

2131
    @Override
2132
    public ScheduledFuture<?> scheduleWithFixedDelay(
2133
        Runnable command, long initialDelay, long delay, TimeUnit unit) {
2134
      return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
×
2135
    }
2136

2137
    @Override
2138
    public boolean awaitTermination(long timeout, TimeUnit unit)
2139
        throws InterruptedException {
2140
      return delegate.awaitTermination(timeout, unit);
×
2141
    }
2142

2143
    @Override
2144
    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
2145
        throws InterruptedException {
2146
      return delegate.invokeAll(tasks);
×
2147
    }
2148

2149
    @Override
2150
    public <T> List<Future<T>> invokeAll(
2151
        Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2152
        throws InterruptedException {
2153
      return delegate.invokeAll(tasks, timeout, unit);
×
2154
    }
2155

2156
    @Override
2157
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
2158
        throws InterruptedException, ExecutionException {
2159
      return delegate.invokeAny(tasks);
×
2160
    }
2161

2162
    @Override
2163
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2164
        throws InterruptedException, ExecutionException, TimeoutException {
2165
      return delegate.invokeAny(tasks, timeout, unit);
×
2166
    }
2167

2168
    @Override
2169
    public boolean isShutdown() {
2170
      return delegate.isShutdown();
×
2171
    }
2172

2173
    @Override
2174
    public boolean isTerminated() {
2175
      return delegate.isTerminated();
×
2176
    }
2177

2178
    @Override
2179
    public void shutdown() {
2180
      throw new UnsupportedOperationException("Restricted: shutdown() is not allowed");
1✔
2181
    }
2182

2183
    @Override
2184
    public List<Runnable> shutdownNow() {
2185
      throw new UnsupportedOperationException("Restricted: shutdownNow() is not allowed");
1✔
2186
    }
2187

2188
    @Override
2189
    public <T> Future<T> submit(Callable<T> task) {
2190
      return delegate.submit(task);
×
2191
    }
2192

2193
    @Override
2194
    public Future<?> submit(Runnable task) {
2195
      return delegate.submit(task);
×
2196
    }
2197

2198
    @Override
2199
    public <T> Future<T> submit(Runnable task, T result) {
2200
      return delegate.submit(task, result);
×
2201
    }
2202

2203
    @Override
2204
    public void execute(Runnable command) {
2205
      delegate.execute(command);
×
2206
    }
×
2207
  }
2208

2209
  /**
2210
   * A ResolutionState indicates the status of last name resolution.
2211
   */
2212
  enum ResolutionState {
1✔
2213
    NO_RESOLUTION,
1✔
2214
    SUCCESS,
1✔
2215
    ERROR
1✔
2216
  }
2217
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc