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

grpc / grpc-java / #19996

24 Sep 2025 12:08AM UTC coverage: 88.575% (+0.03%) from 88.543%
#19996

push

github

web-flow
Implement otel retry metrics (#12064)

implements [A96](https://github.com/grpc/proposal/pull/488/files)

34731 of 39211 relevant lines covered (88.57%)

0.89 hits per line

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

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

17
package io.grpc.internal;
18

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

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

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

129
  static final long IDLE_TIMEOUT_MILLIS_DISABLE = -1;
130

131
  static final long SUBCHANNEL_SHUTDOWN_DELAY_SECONDS = 5;
132

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

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

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

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

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

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

198
  private boolean fullStreamDecompression;
199

200
  private final DecompressorRegistry decompressorRegistry;
201
  private final CompressorRegistry compressorRegistry;
202

203
  private final Supplier<Stopwatch> stopwatchSupplier;
204
  /** The timeout before entering idle mode. */
205
  private final long idleTimeoutMillis;
206

207
  private final ConnectivityStateManager channelStateManager = new ConnectivityStateManager();
1✔
208
  private final BackoffPolicy.Provider backoffPolicyProvider;
209

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

217
  private final List<ClientTransportFilter> transportFilters;
218
  @Nullable private final String userAgent;
219

220
  // Only null after channel is terminated. Must be assigned from the syncContext.
221
  private NameResolver nameResolver;
222

223
  // Must be accessed from the syncContext.
224
  private boolean nameResolverStarted;
225

226
  // null when channel is in idle mode.  Must be assigned from syncContext.
227
  @Nullable
228
  private LbHelperImpl lbHelper;
229

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

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

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

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

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

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

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

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

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

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

297
  private final long perRpcBufferLimit;
298
  private final long channelBufferLimit;
299

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

303
  private final Deadline.Ticker ticker = Deadline.getSystemTicker();
1✔
304

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

692
    if (overrideAuthority == null) {
1✔
693
      return usedNameResolver;
1✔
694
    }
695

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

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

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

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

741
    syncContext.execute(new CancelIdleTimer());
1✔
742
    return this;
1✔
743
  }
744

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

766
    syncContext.execute(new ShutdownNow());
1✔
767
    return this;
1✔
768
  }
769

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

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

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

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

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

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

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

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

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

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

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

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

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

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

899
          @Override public void request(int numMessages) {}
×
900

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

903
          @Override public void halfClose() {}
×
904

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

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

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

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

966
      syncContext.execute(new RealChannelShutdown());
1✔
967
    }
1✔
968

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

985
      syncContext.execute(new RealChannelShutdownNow());
1✔
986
    }
1✔
987

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

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

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

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

1033
      @Override
1034
      protected void callCancelled() {
1035
        super.callCancelled();
1✔
1036
        syncContext.execute(new PendingCallRemoval());
1✔
1037
      }
1✔
1038

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

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

1075
  /**
1076
   * A client call for a given channel that applies a given config selector when it starts.
1077
   */
1078
  static final class ConfigSelectingClientCall<ReqT, RespT>
1079
      extends ForwardingClientCall<ReqT, RespT> {
1080

1081
    private final InternalConfigSelector configSelector;
1082
    private final Channel channel;
1083
    private final Executor callExecutor;
1084
    private final MethodDescriptor<ReqT, RespT> method;
1085
    private final Context context;
1086
    private CallOptions callOptions;
1087

1088
    private ClientCall<ReqT, RespT> delegate;
1089

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

1103
    @Override
1104
    protected ClientCall<ReqT, RespT> delegate() {
1105
      return delegate;
1✔
1106
    }
1107

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

1135
    private void executeCloseObserverInContext(
1136
        final Listener<RespT> observer, final Status status) {
1137
      class CloseInContext extends ContextRunnable {
1138
        CloseInContext() {
1✔
1139
          super(context);
1✔
1140
        }
1✔
1141

1142
        @Override
1143
        public void runInContext() {
1144
          observer.onClose(status, new Metadata());
1✔
1145
        }
1✔
1146
      }
1147

1148
      callExecutor.execute(new CloseInContext());
1✔
1149
    }
1✔
1150

1151
    @Override
1152
    public void cancel(@Nullable String message, @Nullable Throwable cause) {
1153
      if (delegate != null) {
×
1154
        delegate.cancel(message, cause);
×
1155
      }
1156
    }
×
1157
  }
1158

1159
  private static final ClientCall<Object, Object> NOOP_CALL = new ClientCall<Object, Object>() {
1✔
1160
    @Override
1161
    public void start(Listener<Object> responseListener, Metadata headers) {}
×
1162

1163
    @Override
1164
    public void request(int numMessages) {}
1✔
1165

1166
    @Override
1167
    public void cancel(String message, Throwable cause) {}
×
1168

1169
    @Override
1170
    public void halfClose() {}
×
1171

1172
    @Override
1173
    public void sendMessage(Object message) {}
×
1174

1175
    // Always returns {@code false}, since this is only used when the startup of the call fails.
1176
    @Override
1177
    public boolean isReady() {
1178
      return false;
×
1179
    }
1180
  };
1181

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

1199
      terminated = true;
1✔
1200
      terminatedLatch.countDown();
1✔
1201
    }
1202
  }
1✔
1203

1204
  // Must be called from syncContext
1205
  private void handleInternalSubchannelState(ConnectivityStateInfo newState) {
1206
    if (newState.getState() == TRANSIENT_FAILURE || newState.getState() == IDLE) {
1✔
1207
      refreshNameResolution();
1✔
1208
    }
1209
  }
1✔
1210

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

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

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

1239
    syncContext.execute(new NotifyStateChanged());
1✔
1240
  }
1✔
1241

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

1262
    syncContext.execute(new ResetConnectBackoff());
1✔
1263
  }
1✔
1264

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

1278
    syncContext.execute(new PrepareToLoseNetworkRunnable());
1✔
1279
  }
1✔
1280

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

1290
    @GuardedBy("lock")
1✔
1291
    Collection<ClientStream> uncommittedRetriableStreams = new HashSet<>();
1292

1293
    @GuardedBy("lock")
1294
    Status shutdownStatus;
1295

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

1311
      if (shouldShutdownDelayedTransport) {
1✔
1312
        delayedTransport.shutdown(reason);
1✔
1313
      }
1314
    }
1✔
1315

1316
    void onShutdownNow(Status reason) {
1317
      onShutdown(reason);
1✔
1318
      Collection<ClientStream> streams;
1319

1320
      synchronized (lock) {
1✔
1321
        streams = new ArrayList<>(uncommittedRetriableStreams);
1✔
1322
      }
1✔
1323

1324
      for (ClientStream stream : streams) {
1✔
1325
        stream.cancel(reason);
1✔
1326
      }
1✔
1327
      delayedTransport.shutdownNow(reason);
1✔
1328
    }
1✔
1329

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

1345
    void remove(RetriableStream<?> retriableStream) {
1346
      Status shutdownStatusCopy = null;
1✔
1347

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

1358
      if (shutdownStatusCopy != null) {
1✔
1359
        delayedTransport.shutdown(shutdownStatusCopy);
1✔
1360
      }
1361
    }
1✔
1362
  }
1363

1364
  private final class LbHelperImpl extends LoadBalancer.Helper {
1✔
1365
    AutoConfiguredLoadBalancer lb;
1366

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

1375
    @Override
1376
    public void updateBalancingState(
1377
        final ConnectivityState newState, final SubchannelPicker newPicker) {
1378
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1379
      checkNotNull(newState, "newState");
1✔
1380
      checkNotNull(newPicker, "newPicker");
1✔
1381

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

1395
    @Override
1396
    public void refreshNameResolution() {
1397
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1398
      final class LoadBalancerRefreshNameResolution implements Runnable {
1✔
1399
        @Override
1400
        public void run() {
1401
          ManagedChannelImpl.this.refreshNameResolution();
1✔
1402
        }
1✔
1403
      }
1404

1405
      syncContext.execute(new LoadBalancerRefreshNameResolution());
1✔
1406
    }
1✔
1407

1408
    @Override
1409
    public ManagedChannel createOobChannel(EquivalentAddressGroup addressGroup, String authority) {
1410
      return createOobChannel(Collections.singletonList(addressGroup), authority);
×
1411
    }
1412

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

1448
        @Override
1449
        void onStateChange(InternalSubchannel is, ConnectivityStateInfo newState) {
1450
          // TODO(chengyuanzhang): change to let LB policies explicitly manage OOB channel's
1451
          //  state and refresh name resolution if necessary.
1452
          handleInternalSubchannelState(newState);
1✔
1453
          oobChannel.handleSubchannelStateChange(newState);
1✔
1454
        }
1✔
1455
      }
1456

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

1494
      syncContext.execute(new AddOobChannel());
1✔
1495
      return oobChannel;
1✔
1496
    }
1497

1498
    @Deprecated
1499
    @Override
1500
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
1501
      return createResolvingOobChannelBuilder(target, new DefaultChannelCreds())
1✔
1502
          // Override authority to keep the old behavior.
1503
          // createResolvingOobChannelBuilder(String target) will be deleted soon.
1504
          .overrideAuthority(getAuthority());
1✔
1505
    }
1506

1507
    // TODO(creamsoup) prevent main channel to shutdown if oob channel is not terminated
1508
    // TODO(zdapeng) register the channel as a subchannel of the parent channel in channelz.
1509
    @Override
1510
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1511
        final String target, final ChannelCredentials channelCreds) {
1512
      checkNotNull(channelCreds, "channelCreds");
1✔
1513

1514
      final class ResolvingOobChannelBuilder
1515
          extends ForwardingChannelBuilder2<ResolvingOobChannelBuilder> {
1516
        final ManagedChannelBuilder<?> delegate;
1517

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

1551
        @Override
1552
        protected ManagedChannelBuilder<?> delegate() {
1553
          return delegate;
1✔
1554
        }
1555
      }
1556

1557
      checkState(!terminated, "Channel is terminated");
1✔
1558

1559
      ResolvingOobChannelBuilder builder = new ResolvingOobChannelBuilder();
1✔
1560

1561
      return builder
1✔
1562
          // TODO(zdapeng): executors should not outlive the parent channel.
1563
          .executor(executor)
1✔
1564
          .offloadExecutor(offloadExecutorHolder.getExecutor())
1✔
1565
          .maxTraceEvents(maxTraceEvents)
1✔
1566
          .proxyDetector(nameResolverArgs.getProxyDetector())
1✔
1567
          .userAgent(userAgent);
1✔
1568
    }
1569

1570
    @Override
1571
    public ChannelCredentials getUnsafeChannelCredentials() {
1572
      if (originalChannelCreds == null) {
1✔
1573
        return new DefaultChannelCreds();
1✔
1574
      }
1575
      return originalChannelCreds;
×
1576
    }
1577

1578
    @Override
1579
    public void updateOobChannelAddresses(ManagedChannel channel, EquivalentAddressGroup eag) {
1580
      updateOobChannelAddresses(channel, Collections.singletonList(eag));
×
1581
    }
×
1582

1583
    @Override
1584
    public void updateOobChannelAddresses(ManagedChannel channel,
1585
        List<EquivalentAddressGroup> eag) {
1586
      checkArgument(channel instanceof OobChannel,
1✔
1587
          "channel must have been returned from createOobChannel");
1588
      ((OobChannel) channel).updateAddresses(eag);
1✔
1589
    }
1✔
1590

1591
    @Override
1592
    public String getAuthority() {
1593
      return ManagedChannelImpl.this.authority();
1✔
1594
    }
1595

1596
    @Override
1597
    public String getChannelTarget() {
1598
      return targetUri.toString();
1✔
1599
    }
1600

1601
    @Override
1602
    public SynchronizationContext getSynchronizationContext() {
1603
      return syncContext;
1✔
1604
    }
1605

1606
    @Override
1607
    public ScheduledExecutorService getScheduledExecutorService() {
1608
      return scheduledExecutor;
1✔
1609
    }
1610

1611
    @Override
1612
    public ChannelLogger getChannelLogger() {
1613
      return channelLogger;
1✔
1614
    }
1615

1616
    @Override
1617
    public NameResolver.Args getNameResolverArgs() {
1618
      return nameResolverArgs;
1✔
1619
    }
1620

1621
    @Override
1622
    public NameResolverRegistry getNameResolverRegistry() {
1623
      return nameResolverRegistry;
1✔
1624
    }
1625

1626
    @Override
1627
    public MetricRecorder getMetricRecorder() {
1628
      return metricRecorder;
1✔
1629
    }
1630

1631
    /**
1632
     * A placeholder for channel creds if user did not specify channel creds for the channel.
1633
     */
1634
    // TODO(zdapeng): get rid of this class and let all ChannelBuilders always provide a non-null
1635
    //     channel creds.
1636
    final class DefaultChannelCreds extends ChannelCredentials {
1✔
1637
      @Override
1638
      public ChannelCredentials withoutBearerTokens() {
1639
        return this;
×
1640
      }
1641
    }
1642
  }
1643

1644
  final class NameResolverListener extends NameResolver.Listener2 {
1645
    final LbHelperImpl helper;
1646
    final NameResolver resolver;
1647

1648
    NameResolverListener(LbHelperImpl helperImpl, NameResolver resolver) {
1✔
1649
      this.helper = checkNotNull(helperImpl, "helperImpl");
1✔
1650
      this.resolver = checkNotNull(resolver, "resolver");
1✔
1651
    }
1✔
1652

1653
    @Override
1654
    public void onResult(final ResolutionResult resolutionResult) {
1655
      syncContext.execute(() -> onResult2(resolutionResult));
×
1656
    }
×
1657

1658
    @SuppressWarnings("ReferenceEquality")
1659
    @Override
1660
    public Status onResult2(final ResolutionResult resolutionResult) {
1661
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1662
      if (ManagedChannelImpl.this.nameResolver != resolver) {
1✔
1663
        return Status.OK;
1✔
1664
      }
1665

1666
      StatusOr<List<EquivalentAddressGroup>> serversOrError =
1✔
1667
          resolutionResult.getAddressesOrError();
1✔
1668
      if (!serversOrError.hasValue()) {
1✔
1669
        handleErrorInSyncContext(serversOrError.getStatus());
1✔
1670
        return serversOrError.getStatus();
1✔
1671
      }
1672
      List<EquivalentAddressGroup> servers = serversOrError.getValue();
1✔
1673
      channelLogger.log(
1✔
1674
          ChannelLogLevel.DEBUG,
1675
          "Resolved address: {0}, config={1}",
1676
          servers,
1677
          resolutionResult.getAttributes());
1✔
1678

1679
      if (lastResolutionState != ResolutionState.SUCCESS) {
1✔
1680
        channelLogger.log(ChannelLogLevel.INFO, "Address resolved: {0}",
1✔
1681
            servers);
1682
        lastResolutionState = ResolutionState.SUCCESS;
1✔
1683
      }
1684
      ConfigOrError configOrError = resolutionResult.getServiceConfig();
1✔
1685
      InternalConfigSelector resolvedConfigSelector =
1✔
1686
          resolutionResult.getAttributes().get(InternalConfigSelector.KEY);
1✔
1687
      ManagedChannelServiceConfig validServiceConfig =
1688
          configOrError != null && configOrError.getConfig() != null
1✔
1689
              ? (ManagedChannelServiceConfig) configOrError.getConfig()
1✔
1690
              : null;
1✔
1691
      Status serviceConfigError = configOrError != null ? configOrError.getError() : null;
1✔
1692

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

1758
        try {
1759
          // TODO(creamsoup): when `serversOrError` is empty and lastResolutionStateCopy == SUCCESS
1760
          //  and lbNeedAddress, it shouldn't call the handleServiceConfigUpdate. But,
1761
          //  lbNeedAddress is not deterministic
1762
          serviceConfigUpdated = true;
1✔
1763
        } catch (RuntimeException re) {
×
1764
          logger.log(
×
1765
              Level.WARNING,
1766
              "[" + getLogId() + "] Unexpected exception from parsing service config",
×
1767
              re);
1768
        }
1✔
1769
      }
1770

1771
      Attributes effectiveAttrs = resolutionResult.getAttributes();
1✔
1772
      // Call LB only if it's not shutdown.  If LB is shutdown, lbHelper won't match.
1773
      if (NameResolverListener.this.helper == ManagedChannelImpl.this.lbHelper) {
1✔
1774
        Attributes.Builder attrBuilder =
1✔
1775
            effectiveAttrs.toBuilder().discard(InternalConfigSelector.KEY);
1✔
1776
        Map<String, ?> healthCheckingConfig =
1✔
1777
            effectiveServiceConfig.getHealthCheckingConfig();
1✔
1778
        if (healthCheckingConfig != null) {
1✔
1779
          attrBuilder
1✔
1780
              .set(LoadBalancer.ATTR_HEALTH_CHECKING_CONFIG, healthCheckingConfig)
1✔
1781
              .build();
1✔
1782
        }
1783
        Attributes attributes = attrBuilder.build();
1✔
1784

1785
        ResolvedAddresses.Builder resolvedAddresses = ResolvedAddresses.newBuilder()
1✔
1786
            .setAddresses(serversOrError.getValue())
1✔
1787
            .setAttributes(attributes)
1✔
1788
            .setLoadBalancingPolicyConfig(effectiveServiceConfig.getLoadBalancingConfig());
1✔
1789
        Status addressAcceptanceStatus = helper.lb.tryAcceptResolvedAddresses(
1✔
1790
            resolvedAddresses.build());
1✔
1791
        return addressAcceptanceStatus;
1✔
1792
      }
1793
      return Status.OK;
×
1794
    }
1795

1796
    @Override
1797
    public void onError(final Status error) {
1798
      checkArgument(!error.isOk(), "the error status must not be OK");
1✔
1799
      final class NameResolverErrorHandler implements Runnable {
1✔
1800
        @Override
1801
        public void run() {
1802
          handleErrorInSyncContext(error);
1✔
1803
        }
1✔
1804
      }
1805

1806
      syncContext.execute(new NameResolverErrorHandler());
1✔
1807
    }
1✔
1808

1809
    private void handleErrorInSyncContext(Status error) {
1810
      logger.log(Level.WARNING, "[{0}] Failed to resolve name. status={1}",
1✔
1811
          new Object[] {getLogId(), error});
1✔
1812
      realChannel.onConfigError();
1✔
1813
      if (lastResolutionState != ResolutionState.ERROR) {
1✔
1814
        channelLogger.log(ChannelLogLevel.WARNING, "Failed to resolve name: {0}", error);
1✔
1815
        lastResolutionState = ResolutionState.ERROR;
1✔
1816
      }
1817
      // Call LB only if it's not shutdown.  If LB is shutdown, lbHelper won't match.
1818
      if (NameResolverListener.this.helper != ManagedChannelImpl.this.lbHelper) {
1✔
1819
        return;
1✔
1820
      }
1821

1822
      helper.lb.handleNameResolutionError(error);
1✔
1823
    }
1✔
1824
  }
1825

1826
  private final class SubchannelImpl extends AbstractSubchannel {
1827
    final CreateSubchannelArgs args;
1828
    final InternalLogId subchannelLogId;
1829
    final ChannelLoggerImpl subchannelLogger;
1830
    final ChannelTracer subchannelTracer;
1831
    List<EquivalentAddressGroup> addressGroups;
1832
    InternalSubchannel subchannel;
1833
    boolean started;
1834
    boolean shutdown;
1835
    ScheduledHandle delayedShutdownTask;
1836

1837
    SubchannelImpl(CreateSubchannelArgs args) {
1✔
1838
      checkNotNull(args, "args");
1✔
1839
      addressGroups = args.getAddresses();
1✔
1840
      if (authorityOverride != null) {
1✔
1841
        List<EquivalentAddressGroup> eagsWithoutOverrideAttr =
1✔
1842
            stripOverrideAuthorityAttributes(args.getAddresses());
1✔
1843
        args = args.toBuilder().setAddresses(eagsWithoutOverrideAttr).build();
1✔
1844
      }
1845
      this.args = args;
1✔
1846
      subchannelLogId = InternalLogId.allocate("Subchannel", /*details=*/ authority());
1✔
1847
      subchannelTracer = new ChannelTracer(
1✔
1848
          subchannelLogId, maxTraceEvents, timeProvider.currentTimeNanos(),
1✔
1849
          "Subchannel for " + args.getAddresses());
1✔
1850
      subchannelLogger = new ChannelLoggerImpl(subchannelTracer, timeProvider);
1✔
1851
    }
1✔
1852

1853
    @Override
1854
    public void start(final SubchannelStateListener listener) {
1855
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1856
      checkState(!started, "already started");
1✔
1857
      checkState(!shutdown, "already shutdown");
1✔
1858
      checkState(!terminating, "Channel is being terminated");
1✔
1859
      started = true;
1✔
1860
      final class ManagedInternalSubchannelCallback extends InternalSubchannel.Callback {
1✔
1861
        // All callbacks are run in syncContext
1862
        @Override
1863
        void onTerminated(InternalSubchannel is) {
1864
          subchannels.remove(is);
1✔
1865
          channelz.removeSubchannel(is);
1✔
1866
          maybeTerminateChannel();
1✔
1867
        }
1✔
1868

1869
        @Override
1870
        void onStateChange(InternalSubchannel is, ConnectivityStateInfo newState) {
1871
          checkState(listener != null, "listener is null");
1✔
1872
          listener.onSubchannelState(newState);
1✔
1873
        }
1✔
1874

1875
        @Override
1876
        void onInUse(InternalSubchannel is) {
1877
          inUseStateAggregator.updateObjectInUse(is, true);
1✔
1878
        }
1✔
1879

1880
        @Override
1881
        void onNotInUse(InternalSubchannel is) {
1882
          inUseStateAggregator.updateObjectInUse(is, false);
1✔
1883
        }
1✔
1884
      }
1885

1886
      final InternalSubchannel internalSubchannel = new InternalSubchannel(
1✔
1887
          args,
1888
          authority(),
1✔
1889
          userAgent,
1✔
1890
          backoffPolicyProvider,
1✔
1891
          transportFactory,
1✔
1892
          transportFactory.getScheduledExecutorService(),
1✔
1893
          stopwatchSupplier,
1✔
1894
          syncContext,
1895
          new ManagedInternalSubchannelCallback(),
1896
          channelz,
1✔
1897
          callTracerFactory.create(),
1✔
1898
          subchannelTracer,
1899
          subchannelLogId,
1900
          subchannelLogger,
1901
          transportFilters, target,
1✔
1902
          lbHelper.getMetricRecorder());
1✔
1903

1904
      channelTracer.reportEvent(new ChannelTrace.Event.Builder()
1✔
1905
          .setDescription("Child Subchannel started")
1✔
1906
          .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
1✔
1907
          .setTimestampNanos(timeProvider.currentTimeNanos())
1✔
1908
          .setSubchannelRef(internalSubchannel)
1✔
1909
          .build());
1✔
1910

1911
      this.subchannel = internalSubchannel;
1✔
1912
      channelz.addSubchannel(internalSubchannel);
1✔
1913
      subchannels.add(internalSubchannel);
1✔
1914
    }
1✔
1915

1916
    @Override
1917
    InternalInstrumented<ChannelStats> getInstrumentedInternalSubchannel() {
1918
      checkState(started, "not started");
1✔
1919
      return subchannel;
1✔
1920
    }
1921

1922
    @Override
1923
    public void shutdown() {
1924
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1925
      if (subchannel == null) {
1✔
1926
        // start() was not successful
1927
        shutdown = true;
×
1928
        return;
×
1929
      }
1930
      if (shutdown) {
1✔
1931
        if (terminating && delayedShutdownTask != null) {
1✔
1932
          // shutdown() was previously called when terminating == false, thus a delayed shutdown()
1933
          // was scheduled.  Now since terminating == true, We should expedite the shutdown.
1934
          delayedShutdownTask.cancel();
×
1935
          delayedShutdownTask = null;
×
1936
          // Will fall through to the subchannel.shutdown() at the end.
1937
        } else {
1938
          return;
1✔
1939
        }
1940
      } else {
1941
        shutdown = true;
1✔
1942
      }
1943
      // Add a delay to shutdown to deal with the race between 1) a transport being picked and
1944
      // newStream() being called on it, and 2) its Subchannel is shut down by LoadBalancer (e.g.,
1945
      // because of address change, or because LoadBalancer is shutdown by Channel entering idle
1946
      // mode). If (2) wins, the app will see a spurious error. We work around this by delaying
1947
      // shutdown of Subchannel for a few seconds here.
1948
      //
1949
      // TODO(zhangkun83): consider a better approach
1950
      // (https://github.com/grpc/grpc-java/issues/2562).
1951
      if (!terminating) {
1✔
1952
        final class ShutdownSubchannel implements Runnable {
1✔
1953
          @Override
1954
          public void run() {
1955
            subchannel.shutdown(SUBCHANNEL_SHUTDOWN_STATUS);
1✔
1956
          }
1✔
1957
        }
1958

1959
        delayedShutdownTask = syncContext.schedule(
1✔
1960
            new LogExceptionRunnable(new ShutdownSubchannel()),
1961
            SUBCHANNEL_SHUTDOWN_DELAY_SECONDS, TimeUnit.SECONDS,
1962
            transportFactory.getScheduledExecutorService());
1✔
1963
        return;
1✔
1964
      }
1965
      // When terminating == true, no more real streams will be created. It's safe and also
1966
      // desirable to shutdown timely.
1967
      subchannel.shutdown(SHUTDOWN_STATUS);
1✔
1968
    }
1✔
1969

1970
    @Override
1971
    public void requestConnection() {
1972
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1973
      checkState(started, "not started");
1✔
1974
      if (shutdown) {
1✔
1975
        return;
1✔
1976
      }
1977
      subchannel.obtainActiveTransport();
1✔
1978
    }
1✔
1979

1980
    @Override
1981
    public List<EquivalentAddressGroup> getAllAddresses() {
1982
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1983
      checkState(started, "not started");
1✔
1984
      return addressGroups;
1✔
1985
    }
1986

1987
    @Override
1988
    public Attributes getAttributes() {
1989
      return args.getAttributes();
1✔
1990
    }
1991

1992
    @Override
1993
    public String toString() {
1994
      return subchannelLogId.toString();
1✔
1995
    }
1996

1997
    @Override
1998
    public Channel asChannel() {
1999
      checkState(started, "not started");
1✔
2000
      return new SubchannelChannel(
1✔
2001
          subchannel, balancerRpcExecutorHolder.getExecutor(),
1✔
2002
          transportFactory.getScheduledExecutorService(),
1✔
2003
          callTracerFactory.create(),
1✔
2004
          new AtomicReference<InternalConfigSelector>(null));
2005
    }
2006

2007
    @Override
2008
    public Object getInternalSubchannel() {
2009
      checkState(started, "Subchannel is not started");
1✔
2010
      return subchannel;
1✔
2011
    }
2012

2013
    @Override
2014
    public ChannelLogger getChannelLogger() {
2015
      return subchannelLogger;
1✔
2016
    }
2017

2018
    @Override
2019
    public void updateAddresses(List<EquivalentAddressGroup> addrs) {
2020
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
2021
      addressGroups = addrs;
1✔
2022
      if (authorityOverride != null) {
1✔
2023
        addrs = stripOverrideAuthorityAttributes(addrs);
1✔
2024
      }
2025
      subchannel.updateAddresses(addrs);
1✔
2026
    }
1✔
2027

2028
    @Override
2029
    public Attributes getConnectedAddressAttributes() {
2030
      return subchannel.getConnectedAddressAttributes();
1✔
2031
    }
2032

2033
    private List<EquivalentAddressGroup> stripOverrideAuthorityAttributes(
2034
        List<EquivalentAddressGroup> eags) {
2035
      List<EquivalentAddressGroup> eagsWithoutOverrideAttr = new ArrayList<>();
1✔
2036
      for (EquivalentAddressGroup eag : eags) {
1✔
2037
        EquivalentAddressGroup eagWithoutOverrideAttr = new EquivalentAddressGroup(
1✔
2038
            eag.getAddresses(),
1✔
2039
            eag.getAttributes().toBuilder().discard(ATTR_AUTHORITY_OVERRIDE).build());
1✔
2040
        eagsWithoutOverrideAttr.add(eagWithoutOverrideAttr);
1✔
2041
      }
1✔
2042
      return Collections.unmodifiableList(eagsWithoutOverrideAttr);
1✔
2043
    }
2044
  }
2045

2046
  @Override
2047
  public String toString() {
2048
    return MoreObjects.toStringHelper(this)
1✔
2049
        .add("logId", logId.getId())
1✔
2050
        .add("target", target)
1✔
2051
        .toString();
1✔
2052
  }
2053

2054
  /**
2055
   * Called from syncContext.
2056
   */
2057
  private final class DelayedTransportListener implements ManagedClientTransport.Listener {
1✔
2058
    @Override
2059
    public void transportShutdown(Status s) {
2060
      checkState(shutdown.get(), "Channel must have been shut down");
1✔
2061
    }
1✔
2062

2063
    @Override
2064
    public void transportReady() {
2065
      // Don't care
2066
    }
×
2067

2068
    @Override
2069
    public Attributes filterTransport(Attributes attributes) {
2070
      return attributes;
×
2071
    }
2072

2073
    @Override
2074
    public void transportInUse(final boolean inUse) {
2075
      inUseStateAggregator.updateObjectInUse(delayedTransport, inUse);
1✔
2076
      if (inUse) {
1✔
2077
        // It's possible to be in idle mode while inUseStateAggregator is in-use, if one of the
2078
        // subchannels is in use. But we should never be in idle mode when delayed transport is in
2079
        // use.
2080
        exitIdleMode();
1✔
2081
      }
2082
    }
1✔
2083

2084
    @Override
2085
    public void transportTerminated() {
2086
      checkState(shutdown.get(), "Channel must have been shut down");
1✔
2087
      terminating = true;
1✔
2088
      shutdownNameResolverAndLoadBalancer(false);
1✔
2089
      // No need to call channelStateManager since we are already in SHUTDOWN state.
2090
      // Until LoadBalancer is shutdown, it may still create new subchannels.  We catch them
2091
      // here.
2092
      maybeShutdownNowSubchannels();
1✔
2093
      maybeTerminateChannel();
1✔
2094
    }
1✔
2095
  }
2096

2097
  /**
2098
   * Must be accessed from syncContext.
2099
   */
2100
  private final class IdleModeStateAggregator extends InUseStateAggregator<Object> {
1✔
2101
    @Override
2102
    protected void handleInUse() {
2103
      exitIdleMode();
1✔
2104
    }
1✔
2105

2106
    @Override
2107
    protected void handleNotInUse() {
2108
      if (shutdown.get()) {
1✔
2109
        return;
1✔
2110
      }
2111
      rescheduleIdleTimer();
1✔
2112
    }
1✔
2113
  }
2114

2115
  /**
2116
   * Lazily request for Executor from an executor pool.
2117
   * Also act as an Executor directly to simply run a cmd
2118
   */
2119
  @VisibleForTesting
2120
  static final class ExecutorHolder implements Executor {
2121
    private final ObjectPool<? extends Executor> pool;
2122
    private Executor executor;
2123

2124
    ExecutorHolder(ObjectPool<? extends Executor> executorPool) {
1✔
2125
      this.pool = checkNotNull(executorPool, "executorPool");
1✔
2126
    }
1✔
2127

2128
    synchronized Executor getExecutor() {
2129
      if (executor == null) {
1✔
2130
        executor = checkNotNull(pool.getObject(), "%s.getObject()", executor);
1✔
2131
      }
2132
      return executor;
1✔
2133
    }
2134

2135
    synchronized void release() {
2136
      if (executor != null) {
1✔
2137
        executor = pool.returnObject(executor);
1✔
2138
      }
2139
    }
1✔
2140

2141
    @Override
2142
    public void execute(Runnable command) {
2143
      getExecutor().execute(command);
1✔
2144
    }
1✔
2145
  }
2146

2147
  private static final class RestrictedScheduledExecutor implements ScheduledExecutorService {
2148
    final ScheduledExecutorService delegate;
2149

2150
    private RestrictedScheduledExecutor(ScheduledExecutorService delegate) {
1✔
2151
      this.delegate = checkNotNull(delegate, "delegate");
1✔
2152
    }
1✔
2153

2154
    @Override
2155
    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
2156
      return delegate.schedule(callable, delay, unit);
×
2157
    }
2158

2159
    @Override
2160
    public ScheduledFuture<?> schedule(Runnable cmd, long delay, TimeUnit unit) {
2161
      return delegate.schedule(cmd, delay, unit);
1✔
2162
    }
2163

2164
    @Override
2165
    public ScheduledFuture<?> scheduleAtFixedRate(
2166
        Runnable command, long initialDelay, long period, TimeUnit unit) {
2167
      return delegate.scheduleAtFixedRate(command, initialDelay, period, unit);
1✔
2168
    }
2169

2170
    @Override
2171
    public ScheduledFuture<?> scheduleWithFixedDelay(
2172
        Runnable command, long initialDelay, long delay, TimeUnit unit) {
2173
      return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
×
2174
    }
2175

2176
    @Override
2177
    public boolean awaitTermination(long timeout, TimeUnit unit)
2178
        throws InterruptedException {
2179
      return delegate.awaitTermination(timeout, unit);
×
2180
    }
2181

2182
    @Override
2183
    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
2184
        throws InterruptedException {
2185
      return delegate.invokeAll(tasks);
×
2186
    }
2187

2188
    @Override
2189
    public <T> List<Future<T>> invokeAll(
2190
        Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2191
        throws InterruptedException {
2192
      return delegate.invokeAll(tasks, timeout, unit);
×
2193
    }
2194

2195
    @Override
2196
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
2197
        throws InterruptedException, ExecutionException {
2198
      return delegate.invokeAny(tasks);
×
2199
    }
2200

2201
    @Override
2202
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2203
        throws InterruptedException, ExecutionException, TimeoutException {
2204
      return delegate.invokeAny(tasks, timeout, unit);
×
2205
    }
2206

2207
    @Override
2208
    public boolean isShutdown() {
2209
      return delegate.isShutdown();
×
2210
    }
2211

2212
    @Override
2213
    public boolean isTerminated() {
2214
      return delegate.isTerminated();
×
2215
    }
2216

2217
    @Override
2218
    public void shutdown() {
2219
      throw new UnsupportedOperationException("Restricted: shutdown() is not allowed");
1✔
2220
    }
2221

2222
    @Override
2223
    public List<Runnable> shutdownNow() {
2224
      throw new UnsupportedOperationException("Restricted: shutdownNow() is not allowed");
1✔
2225
    }
2226

2227
    @Override
2228
    public <T> Future<T> submit(Callable<T> task) {
2229
      return delegate.submit(task);
×
2230
    }
2231

2232
    @Override
2233
    public Future<?> submit(Runnable task) {
2234
      return delegate.submit(task);
×
2235
    }
2236

2237
    @Override
2238
    public <T> Future<T> submit(Runnable task, T result) {
2239
      return delegate.submit(task, result);
×
2240
    }
2241

2242
    @Override
2243
    public void execute(Runnable command) {
2244
      delegate.execute(command);
×
2245
    }
×
2246
  }
2247

2248
  /**
2249
   * A ResolutionState indicates the status of last name resolution.
2250
   */
2251
  enum ResolutionState {
1✔
2252
    NO_RESOLUTION,
1✔
2253
    SUCCESS,
1✔
2254
    ERROR
1✔
2255
  }
2256
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc