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

grpc / grpc-java / #19486

01 Oct 2024 05:51AM UTC coverage: 84.589% (+0.02%) from 84.565%
#19486

push

github

web-flow
Make address resolution error use the default service config (#11577)

Fixes #11040.

33659 of 39791 relevant lines covered (84.59%)

0.85 hits per line

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

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

17
package io.grpc.internal;
18

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

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

193
  private boolean fullStreamDecompression;
194

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

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

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

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

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

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

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

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

225
  // Must ONLY be assigned from updateSubchannelPicker(), which is called from syncContext.
226
  // null if channel is in idle mode.
227
  @Nullable
228
  private volatile SubchannelPicker subchannelPicker;
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 subchannelPicker <- null
257
  //   1c delayedTransport.shutdown()
258
  // 2. delayedTransport terminated: stop stream-creation functionality
259
  //   2a terminating <- true
260
  //   2b loadBalancer.shutdown()
261
  //     * LoadBalancer will shutdown subchannels and OOB channels
262
  //   2c loadBalancer <- null
263
  //   2d nameResolver.shutdown()
264
  //   2e nameResolver <- null
265
  // 3. All subchannels and OOB channels terminated: Channel considered terminated
266

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

547
  ManagedChannelImpl(
548
      ManagedChannelImplBuilder builder,
549
      ClientTransportFactory clientTransportFactory,
550
      URI targetUri,
551
      NameResolverProvider nameResolverProvider,
552
      BackoffPolicy.Provider backoffPolicyProvider,
553
      ObjectPool<? extends Executor> balancerRpcExecutorPool,
554
      Supplier<Stopwatch> stopwatchSupplier,
555
      List<ClientInterceptor> interceptors,
556
      final TimeProvider timeProvider) {
1✔
557
    this.target = checkNotNull(builder.target, "target");
1✔
558
    this.logId = InternalLogId.allocate("Channel", target);
1✔
559
    this.timeProvider = checkNotNull(timeProvider, "timeProvider");
1✔
560
    this.executorPool = checkNotNull(builder.executorPool, "executorPool");
1✔
561
    this.executor = checkNotNull(executorPool.getObject(), "executor");
1✔
562
    this.originalChannelCreds = builder.channelCredentials;
1✔
563
    this.originalTransportFactory = clientTransportFactory;
1✔
564
    this.offloadExecutorHolder =
1✔
565
        new ExecutorHolder(checkNotNull(builder.offloadExecutorPool, "offloadExecutorPool"));
1✔
566
    this.transportFactory = new CallCredentialsApplyingTransportFactory(
1✔
567
        clientTransportFactory, builder.callCredentials, this.offloadExecutorHolder);
568
    this.oobTransportFactory = new CallCredentialsApplyingTransportFactory(
1✔
569
        clientTransportFactory, null, this.offloadExecutorHolder);
570
    this.scheduledExecutor =
1✔
571
        new RestrictedScheduledExecutor(transportFactory.getScheduledExecutorService());
1✔
572
    maxTraceEvents = builder.maxTraceEvents;
1✔
573
    channelTracer = new ChannelTracer(
1✔
574
        logId, builder.maxTraceEvents, timeProvider.currentTimeNanos(),
1✔
575
        "Channel for '" + target + "'");
576
    channelLogger = new ChannelLoggerImpl(channelTracer, timeProvider);
1✔
577
    ProxyDetector proxyDetector =
578
        builder.proxyDetector != null ? builder.proxyDetector : GrpcUtil.DEFAULT_PROXY_DETECTOR;
1✔
579
    this.retryEnabled = builder.retryEnabled;
1✔
580
    this.loadBalancerFactory = new AutoConfiguredLoadBalancerFactory(builder.defaultLbPolicy);
1✔
581
    this.nameResolverRegistry = builder.nameResolverRegistry;
1✔
582
    this.targetUri = checkNotNull(targetUri, "targetUri");
1✔
583
    this.nameResolverProvider = checkNotNull(nameResolverProvider, "nameResolverProvider");
1✔
584
    ScParser serviceConfigParser =
1✔
585
        new ScParser(
586
            retryEnabled,
587
            builder.maxRetryAttempts,
588
            builder.maxHedgedAttempts,
589
            loadBalancerFactory);
590
    this.authorityOverride = builder.authorityOverride;
1✔
591
    this.nameResolverArgs =
1✔
592
        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
            .build();
1✔
602
    this.nameResolver = getNameResolver(
1✔
603
        targetUri, authorityOverride, nameResolverProvider, nameResolverArgs);
604
    this.balancerRpcExecutorPool = checkNotNull(balancerRpcExecutorPool, "balancerRpcExecutorPool");
1✔
605
    this.balancerRpcExecutorHolder = new ExecutorHolder(balancerRpcExecutorPool);
1✔
606
    this.delayedTransport = new DelayedClientTransport(this.executor, this.syncContext);
1✔
607
    this.delayedTransport.start(delayedTransportListener);
1✔
608
    this.backoffPolicyProvider = backoffPolicyProvider;
1✔
609

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

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

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

661
    this.callTracerFactory = new ChannelCallTracerFactory();
1✔
662
    channelCallTracer = callTracerFactory.create();
1✔
663
    this.channelz = checkNotNull(builder.channelz);
1✔
664
    channelz.addRootChannel(this);
1✔
665

666
    if (!lookUpServiceConfig) {
1✔
667
      if (defaultServiceConfig != null) {
1✔
668
        channelLogger.log(
1✔
669
            ChannelLogLevel.INFO, "Service config look-up disabled, using default service config");
670
      }
671
      serviceConfigUpdated = true;
1✔
672
    }
673
    this.metricRecorder = new MetricRecorderImpl(builder.metricSinks,
1✔
674
        MetricInstrumentRegistry.getDefaultRegistry());
1✔
675
  }
1✔
676

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

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

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

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

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

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

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

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

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

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

773
  // Called from syncContext
774
  @VisibleForTesting
775
  void panic(final Throwable t) {
776
    if (panicMode) {
1✔
777
      // Preserve the first panic information
778
      return;
×
779
    }
780
    panicMode = true;
1✔
781
    cancelIdleTimer(/* permanent= */ true);
1✔
782
    shutdownNameResolverAndLoadBalancer(false);
1✔
783
    final class PanicSubchannelPicker extends SubchannelPicker {
1✔
784
      private final PickResult panicPickResult =
1✔
785
          PickResult.withDrop(
1✔
786
              Status.INTERNAL.withDescription("Panic! This is a bug!").withCause(t));
1✔
787

788
      @Override
789
      public PickResult pickSubchannel(PickSubchannelArgs args) {
790
        return panicPickResult;
1✔
791
      }
792

793
      @Override
794
      public String toString() {
795
        return MoreObjects.toStringHelper(PanicSubchannelPicker.class)
×
796
            .add("panicPickResult", panicPickResult)
×
797
            .toString();
×
798
      }
799
    }
800

801
    updateSubchannelPicker(new PanicSubchannelPicker());
1✔
802
    realChannel.updateConfigSelector(null);
1✔
803
    channelLogger.log(ChannelLogLevel.ERROR, "PANIC! Entering TRANSIENT_FAILURE");
1✔
804
    channelStateManager.gotoState(TRANSIENT_FAILURE);
1✔
805
  }
1✔
806

807
  @VisibleForTesting
808
  boolean isInPanicMode() {
809
    return panicMode;
1✔
810
  }
811

812
  // Called from syncContext
813
  private void updateSubchannelPicker(SubchannelPicker newPicker) {
814
    subchannelPicker = newPicker;
1✔
815
    delayedTransport.reprocess(newPicker);
1✔
816
  }
1✔
817

818
  @Override
819
  public boolean isShutdown() {
820
    return shutdown.get();
1✔
821
  }
822

823
  @Override
824
  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
825
    return terminatedLatch.await(timeout, unit);
1✔
826
  }
827

828
  @Override
829
  public boolean isTerminated() {
830
    return terminated;
1✔
831
  }
832

833
  /*
834
   * Creates a new outgoing call on the channel.
835
   */
836
  @Override
837
  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(MethodDescriptor<ReqT, RespT> method,
838
      CallOptions callOptions) {
839
    return interceptorChannel.newCall(method, callOptions);
1✔
840
  }
841

842
  @Override
843
  public String authority() {
844
    return interceptorChannel.authority();
1✔
845
  }
846

847
  private Executor getCallExecutor(CallOptions callOptions) {
848
    Executor executor = callOptions.getExecutor();
1✔
849
    if (executor == null) {
1✔
850
      executor = this.executor;
1✔
851
    }
852
    return executor;
1✔
853
  }
854

855
  private class RealChannel extends Channel {
856
    // Reference to null if no config selector is available from resolution result
857
    // Reference must be set() from syncContext
858
    private final AtomicReference<InternalConfigSelector> configSelector =
1✔
859
        new AtomicReference<>(INITIAL_PENDING_SELECTOR);
1✔
860
    // Set when the NameResolver is initially created. When we create a new NameResolver for the
861
    // same target, the new instance must have the same value.
862
    private final String authority;
863

864
    private final Channel clientCallImplChannel = new Channel() {
1✔
865
      @Override
866
      public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(
867
          MethodDescriptor<RequestT, ResponseT> method, CallOptions callOptions) {
868
        return new ClientCallImpl<>(
1✔
869
            method,
870
            getCallExecutor(callOptions),
1✔
871
            callOptions,
872
            transportProvider,
1✔
873
            terminated ? null : transportFactory.getScheduledExecutorService(),
1✔
874
            channelCallTracer,
1✔
875
            null)
876
            .setFullStreamDecompression(fullStreamDecompression)
1✔
877
            .setDecompressorRegistry(decompressorRegistry)
1✔
878
            .setCompressorRegistry(compressorRegistry);
1✔
879
      }
880

881
      @Override
882
      public String authority() {
883
        return authority;
×
884
      }
885
    };
886

887
    private RealChannel(String authority) {
1✔
888
      this.authority =  checkNotNull(authority, "authority");
1✔
889
    }
1✔
890

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

917
          @Override public void request(int numMessages) {}
×
918

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

921
          @Override public void halfClose() {}
×
922

923
          @Override public void sendMessage(ReqT message) {}
×
924
        };
925
      }
926
      Context context = Context.current();
1✔
927
      final PendingCall<ReqT, RespT> pendingCall = new PendingCall<>(context, method, callOptions);
1✔
928
      syncContext.execute(new Runnable() {
1✔
929
        @Override
930
        public void run() {
931
          if (configSelector.get() == INITIAL_PENDING_SELECTOR) {
1✔
932
            if (pendingCalls == null) {
1✔
933
              pendingCalls = new LinkedHashSet<>();
1✔
934
              inUseStateAggregator.updateObjectInUse(pendingCallsInUseObject, true);
1✔
935
            }
936
            pendingCalls.add(pendingCall);
1✔
937
          } else {
938
            pendingCall.reprocess();
1✔
939
          }
940
        }
1✔
941
      });
942
      return pendingCall;
1✔
943
    }
944

945
    // Must run in SynchronizationContext.
946
    void updateConfigSelector(@Nullable InternalConfigSelector config) {
947
      InternalConfigSelector prevConfig = configSelector.get();
1✔
948
      configSelector.set(config);
1✔
949
      if (prevConfig == INITIAL_PENDING_SELECTOR && pendingCalls != null) {
1✔
950
        for (RealChannel.PendingCall<?, ?> pendingCall : pendingCalls) {
1✔
951
          pendingCall.reprocess();
1✔
952
        }
1✔
953
      }
954
    }
1✔
955

956
    // Must run in SynchronizationContext.
957
    void onConfigError() {
958
      if (configSelector.get() == INITIAL_PENDING_SELECTOR) {
1✔
959
        // Apply Default Service Config if initial name resolution fails.
960
        if (defaultServiceConfig != null) {
1✔
961
          updateConfigSelector(defaultServiceConfig.getDefaultConfigSelector());
1✔
962
          lastServiceConfig = defaultServiceConfig;
1✔
963
          channelLogger.log(ChannelLogLevel.ERROR,
1✔
964
              "Initial Name Resolution error, using default service config");
965
        } else {
966
          updateConfigSelector(null);
1✔
967
        }
968
      }
969
    }
1✔
970

971
    void shutdown() {
972
      final class RealChannelShutdown implements Runnable {
1✔
973
        @Override
974
        public void run() {
975
          if (pendingCalls == null) {
1✔
976
            if (configSelector.get() == INITIAL_PENDING_SELECTOR) {
1✔
977
              configSelector.set(null);
1✔
978
            }
979
            uncommittedRetriableStreamsRegistry.onShutdown(SHUTDOWN_STATUS);
1✔
980
          }
981
        }
1✔
982
      }
983

984
      syncContext.execute(new RealChannelShutdown());
1✔
985
    }
1✔
986

987
    void shutdownNow() {
988
      final class RealChannelShutdownNow implements Runnable {
1✔
989
        @Override
990
        public void run() {
991
          if (configSelector.get() == INITIAL_PENDING_SELECTOR) {
1✔
992
            configSelector.set(null);
1✔
993
          }
994
          if (pendingCalls != null) {
1✔
995
            for (RealChannel.PendingCall<?, ?> pendingCall : pendingCalls) {
1✔
996
              pendingCall.cancel("Channel is forcefully shutdown", null);
1✔
997
            }
1✔
998
          }
999
          uncommittedRetriableStreamsRegistry.onShutdownNow(SHUTDOWN_NOW_STATUS);
1✔
1000
        }
1✔
1001
      }
1002

1003
      syncContext.execute(new RealChannelShutdownNow());
1✔
1004
    }
1✔
1005

1006
    @Override
1007
    public String authority() {
1008
      return authority;
1✔
1009
    }
1010

1011
    private final class PendingCall<ReqT, RespT> extends DelayedClientCall<ReqT, RespT> {
1012
      final Context context;
1013
      final MethodDescriptor<ReqT, RespT> method;
1014
      final CallOptions callOptions;
1015
      private final long callCreationTime;
1016

1017
      PendingCall(
1018
          Context context, MethodDescriptor<ReqT, RespT> method, CallOptions callOptions) {
1✔
1019
        super(getCallExecutor(callOptions), scheduledExecutor, callOptions.getDeadline());
1✔
1020
        this.context = context;
1✔
1021
        this.method = method;
1✔
1022
        this.callOptions = callOptions;
1✔
1023
        this.callCreationTime = ticker.nanoTime();
1✔
1024
      }
1✔
1025

1026
      /** Called when it's ready to create a real call and reprocess the pending call. */
1027
      void reprocess() {
1028
        ClientCall<ReqT, RespT> realCall;
1029
        Context previous = context.attach();
1✔
1030
        try {
1031
          CallOptions delayResolutionOption = callOptions.withOption(NAME_RESOLUTION_DELAYED,
1✔
1032
              ticker.nanoTime() - callCreationTime);
1✔
1033
          realCall = newClientCall(method, delayResolutionOption);
1✔
1034
        } finally {
1035
          context.detach(previous);
1✔
1036
        }
1037
        Runnable toRun = setCall(realCall);
1✔
1038
        if (toRun == null) {
1✔
1039
          syncContext.execute(new PendingCallRemoval());
1✔
1040
        } else {
1041
          getCallExecutor(callOptions).execute(new Runnable() {
1✔
1042
            @Override
1043
            public void run() {
1044
              toRun.run();
1✔
1045
              syncContext.execute(new PendingCallRemoval());
1✔
1046
            }
1✔
1047
          });
1048
        }
1049
      }
1✔
1050

1051
      @Override
1052
      protected void callCancelled() {
1053
        super.callCancelled();
1✔
1054
        syncContext.execute(new PendingCallRemoval());
1✔
1055
      }
1✔
1056

1057
      final class PendingCallRemoval implements Runnable {
1✔
1058
        @Override
1059
        public void run() {
1060
          if (pendingCalls != null) {
1✔
1061
            pendingCalls.remove(PendingCall.this);
1✔
1062
            if (pendingCalls.isEmpty()) {
1✔
1063
              inUseStateAggregator.updateObjectInUse(pendingCallsInUseObject, false);
1✔
1064
              pendingCalls = null;
1✔
1065
              if (shutdown.get()) {
1✔
1066
                uncommittedRetriableStreamsRegistry.onShutdown(SHUTDOWN_STATUS);
1✔
1067
              }
1068
            }
1069
          }
1070
        }
1✔
1071
      }
1072
    }
1073

1074
    private <ReqT, RespT> ClientCall<ReqT, RespT> newClientCall(
1075
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions) {
1076
      InternalConfigSelector selector = configSelector.get();
1✔
1077
      if (selector == null) {
1✔
1078
        return clientCallImplChannel.newCall(method, callOptions);
1✔
1079
      }
1080
      if (selector instanceof ServiceConfigConvertedSelector) {
1✔
1081
        MethodInfo methodInfo =
1✔
1082
            ((ServiceConfigConvertedSelector) selector).config.getMethodConfig(method);
1✔
1083
        if (methodInfo != null) {
1✔
1084
          callOptions = callOptions.withOption(MethodInfo.KEY, methodInfo);
1✔
1085
        }
1086
        return clientCallImplChannel.newCall(method, callOptions);
1✔
1087
      }
1088
      return new ConfigSelectingClientCall<>(
1✔
1089
          selector, clientCallImplChannel, executor, method, callOptions);
1✔
1090
    }
1091
  }
1092

1093
  /**
1094
   * A client call for a given channel that applies a given config selector when it starts.
1095
   */
1096
  static final class ConfigSelectingClientCall<ReqT, RespT>
1097
      extends ForwardingClientCall<ReqT, RespT> {
1098

1099
    private final InternalConfigSelector configSelector;
1100
    private final Channel channel;
1101
    private final Executor callExecutor;
1102
    private final MethodDescriptor<ReqT, RespT> method;
1103
    private final Context context;
1104
    private CallOptions callOptions;
1105

1106
    private ClientCall<ReqT, RespT> delegate;
1107

1108
    ConfigSelectingClientCall(
1109
        InternalConfigSelector configSelector, Channel channel, Executor channelExecutor,
1110
        MethodDescriptor<ReqT, RespT> method,
1111
        CallOptions callOptions) {
1✔
1112
      this.configSelector = configSelector;
1✔
1113
      this.channel = channel;
1✔
1114
      this.method = method;
1✔
1115
      this.callExecutor =
1✔
1116
          callOptions.getExecutor() == null ? channelExecutor : callOptions.getExecutor();
1✔
1117
      this.callOptions = callOptions.withExecutor(callExecutor);
1✔
1118
      this.context = Context.current();
1✔
1119
    }
1✔
1120

1121
    @Override
1122
    protected ClientCall<ReqT, RespT> delegate() {
1123
      return delegate;
1✔
1124
    }
1125

1126
    @SuppressWarnings("unchecked")
1127
    @Override
1128
    public void start(Listener<RespT> observer, Metadata headers) {
1129
      PickSubchannelArgs args =
1✔
1130
          new PickSubchannelArgsImpl(method, headers, callOptions, NOOP_PICK_DETAILS_CONSUMER);
1✔
1131
      InternalConfigSelector.Result result = configSelector.selectConfig(args);
1✔
1132
      Status status = result.getStatus();
1✔
1133
      if (!status.isOk()) {
1✔
1134
        executeCloseObserverInContext(observer,
1✔
1135
            GrpcUtil.replaceInappropriateControlPlaneStatus(status));
1✔
1136
        delegate = (ClientCall<ReqT, RespT>) NOOP_CALL;
1✔
1137
        return;
1✔
1138
      }
1139
      ClientInterceptor interceptor = result.getInterceptor();
1✔
1140
      ManagedChannelServiceConfig config = (ManagedChannelServiceConfig) result.getConfig();
1✔
1141
      MethodInfo methodInfo = config.getMethodConfig(method);
1✔
1142
      if (methodInfo != null) {
1✔
1143
        callOptions = callOptions.withOption(MethodInfo.KEY, methodInfo);
1✔
1144
      }
1145
      if (interceptor != null) {
1✔
1146
        delegate = interceptor.interceptCall(method, callOptions, channel);
1✔
1147
      } else {
1148
        delegate = channel.newCall(method, callOptions);
×
1149
      }
1150
      delegate.start(observer, headers);
1✔
1151
    }
1✔
1152

1153
    private void executeCloseObserverInContext(
1154
        final Listener<RespT> observer, final Status status) {
1155
      class CloseInContext extends ContextRunnable {
1156
        CloseInContext() {
1✔
1157
          super(context);
1✔
1158
        }
1✔
1159

1160
        @Override
1161
        public void runInContext() {
1162
          observer.onClose(status, new Metadata());
1✔
1163
        }
1✔
1164
      }
1165

1166
      callExecutor.execute(new CloseInContext());
1✔
1167
    }
1✔
1168

1169
    @Override
1170
    public void cancel(@Nullable String message, @Nullable Throwable cause) {
1171
      if (delegate != null) {
×
1172
        delegate.cancel(message, cause);
×
1173
      }
1174
    }
×
1175
  }
1176

1177
  private static final ClientCall<Object, Object> NOOP_CALL = new ClientCall<Object, Object>() {
1✔
1178
    @Override
1179
    public void start(Listener<Object> responseListener, Metadata headers) {}
×
1180

1181
    @Override
1182
    public void request(int numMessages) {}
1✔
1183

1184
    @Override
1185
    public void cancel(String message, Throwable cause) {}
×
1186

1187
    @Override
1188
    public void halfClose() {}
×
1189

1190
    @Override
1191
    public void sendMessage(Object message) {}
×
1192

1193
    // Always returns {@code false}, since this is only used when the startup of the call fails.
1194
    @Override
1195
    public boolean isReady() {
1196
      return false;
×
1197
    }
1198
  };
1199

1200
  /**
1201
   * Terminate the channel if termination conditions are met.
1202
   */
1203
  // Must be run from syncContext
1204
  private void maybeTerminateChannel() {
1205
    if (terminated) {
1✔
1206
      return;
×
1207
    }
1208
    if (shutdown.get() && subchannels.isEmpty() && oobChannels.isEmpty()) {
1✔
1209
      channelLogger.log(ChannelLogLevel.INFO, "Terminated");
1✔
1210
      channelz.removeRootChannel(this);
1✔
1211
      executorPool.returnObject(executor);
1✔
1212
      balancerRpcExecutorHolder.release();
1✔
1213
      offloadExecutorHolder.release();
1✔
1214
      // Release the transport factory so that it can deallocate any resources.
1215
      transportFactory.close();
1✔
1216

1217
      terminated = true;
1✔
1218
      terminatedLatch.countDown();
1✔
1219
    }
1220
  }
1✔
1221

1222
  // Must be called from syncContext
1223
  private void handleInternalSubchannelState(ConnectivityStateInfo newState) {
1224
    if (newState.getState() == TRANSIENT_FAILURE || newState.getState() == IDLE) {
1✔
1225
      refreshNameResolution();
1✔
1226
    }
1227
  }
1✔
1228

1229
  @Override
1230
  @SuppressWarnings("deprecation")
1231
  public ConnectivityState getState(boolean requestConnection) {
1232
    ConnectivityState savedChannelState = channelStateManager.getState();
1✔
1233
    if (requestConnection && savedChannelState == IDLE) {
1✔
1234
      final class RequestConnection implements Runnable {
1✔
1235
        @Override
1236
        public void run() {
1237
          exitIdleMode();
1✔
1238
          if (subchannelPicker != null) {
1✔
1239
            subchannelPicker.requestConnection();
1✔
1240
          }
1241
          if (lbHelper != null) {
1✔
1242
            lbHelper.lb.requestConnection();
1✔
1243
          }
1244
        }
1✔
1245
      }
1246

1247
      syncContext.execute(new RequestConnection());
1✔
1248
    }
1249
    return savedChannelState;
1✔
1250
  }
1251

1252
  @Override
1253
  public void notifyWhenStateChanged(final ConnectivityState source, final Runnable callback) {
1254
    final class NotifyStateChanged implements Runnable {
1✔
1255
      @Override
1256
      public void run() {
1257
        channelStateManager.notifyWhenStateChanged(callback, executor, source);
1✔
1258
      }
1✔
1259
    }
1260

1261
    syncContext.execute(new NotifyStateChanged());
1✔
1262
  }
1✔
1263

1264
  @Override
1265
  public void resetConnectBackoff() {
1266
    final class ResetConnectBackoff implements Runnable {
1✔
1267
      @Override
1268
      public void run() {
1269
        if (shutdown.get()) {
1✔
1270
          return;
1✔
1271
        }
1272
        if (nameResolverStarted) {
1✔
1273
          refreshNameResolution();
1✔
1274
        }
1275
        for (InternalSubchannel subchannel : subchannels) {
1✔
1276
          subchannel.resetConnectBackoff();
1✔
1277
        }
1✔
1278
        for (OobChannel oobChannel : oobChannels) {
1✔
1279
          oobChannel.resetConnectBackoff();
×
1280
        }
×
1281
      }
1✔
1282
    }
1283

1284
    syncContext.execute(new ResetConnectBackoff());
1✔
1285
  }
1✔
1286

1287
  @Override
1288
  public void enterIdle() {
1289
    final class PrepareToLoseNetworkRunnable implements Runnable {
1✔
1290
      @Override
1291
      public void run() {
1292
        if (shutdown.get() || lbHelper == null) {
1✔
1293
          return;
1✔
1294
        }
1295
        cancelIdleTimer(/* permanent= */ false);
1✔
1296
        enterIdleMode();
1✔
1297
      }
1✔
1298
    }
1299

1300
    syncContext.execute(new PrepareToLoseNetworkRunnable());
1✔
1301
  }
1✔
1302

1303
  /**
1304
   * A registry that prevents channel shutdown from killing existing retry attempts that are in
1305
   * backoff.
1306
   */
1307
  private final class UncommittedRetriableStreamsRegistry {
1✔
1308
    // TODO(zdapeng): This means we would acquire a lock for each new retry-able stream,
1309
    // it's worthwhile to look for a lock-free approach.
1310
    final Object lock = new Object();
1✔
1311

1312
    @GuardedBy("lock")
1✔
1313
    Collection<ClientStream> uncommittedRetriableStreams = new HashSet<>();
1314

1315
    @GuardedBy("lock")
1316
    Status shutdownStatus;
1317

1318
    void onShutdown(Status reason) {
1319
      boolean shouldShutdownDelayedTransport = false;
1✔
1320
      synchronized (lock) {
1✔
1321
        if (shutdownStatus != null) {
1✔
1322
          return;
1✔
1323
        }
1324
        shutdownStatus = reason;
1✔
1325
        // Keep the delayedTransport open until there is no more uncommitted streams, b/c those
1326
        // retriable streams, which may be in backoff and not using any transport, are already
1327
        // started RPCs.
1328
        if (uncommittedRetriableStreams.isEmpty()) {
1✔
1329
          shouldShutdownDelayedTransport = true;
1✔
1330
        }
1331
      }
1✔
1332

1333
      if (shouldShutdownDelayedTransport) {
1✔
1334
        delayedTransport.shutdown(reason);
1✔
1335
      }
1336
    }
1✔
1337

1338
    void onShutdownNow(Status reason) {
1339
      onShutdown(reason);
1✔
1340
      Collection<ClientStream> streams;
1341

1342
      synchronized (lock) {
1✔
1343
        streams = new ArrayList<>(uncommittedRetriableStreams);
1✔
1344
      }
1✔
1345

1346
      for (ClientStream stream : streams) {
1✔
1347
        stream.cancel(reason);
1✔
1348
      }
1✔
1349
      delayedTransport.shutdownNow(reason);
1✔
1350
    }
1✔
1351

1352
    /**
1353
     * Registers a RetriableStream and return null if not shutdown, otherwise just returns the
1354
     * shutdown Status.
1355
     */
1356
    @Nullable
1357
    Status add(RetriableStream<?> retriableStream) {
1358
      synchronized (lock) {
1✔
1359
        if (shutdownStatus != null) {
1✔
1360
          return shutdownStatus;
1✔
1361
        }
1362
        uncommittedRetriableStreams.add(retriableStream);
1✔
1363
        return null;
1✔
1364
      }
1365
    }
1366

1367
    void remove(RetriableStream<?> retriableStream) {
1368
      Status shutdownStatusCopy = null;
1✔
1369

1370
      synchronized (lock) {
1✔
1371
        uncommittedRetriableStreams.remove(retriableStream);
1✔
1372
        if (uncommittedRetriableStreams.isEmpty()) {
1✔
1373
          shutdownStatusCopy = shutdownStatus;
1✔
1374
          // Because retriable transport is long-lived, we take this opportunity to down-size the
1375
          // hashmap.
1376
          uncommittedRetriableStreams = new HashSet<>();
1✔
1377
        }
1378
      }
1✔
1379

1380
      if (shutdownStatusCopy != null) {
1✔
1381
        delayedTransport.shutdown(shutdownStatusCopy);
1✔
1382
      }
1383
    }
1✔
1384
  }
1385

1386
  private final class LbHelperImpl extends LoadBalancer.Helper {
1✔
1387
    AutoConfiguredLoadBalancer lb;
1388

1389
    @Override
1390
    public AbstractSubchannel createSubchannel(CreateSubchannelArgs args) {
1391
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1392
      // No new subchannel should be created after load balancer has been shutdown.
1393
      checkState(!terminating, "Channel is being terminated");
1✔
1394
      return new SubchannelImpl(args);
1✔
1395
    }
1396

1397
    @Override
1398
    public void updateBalancingState(
1399
        final ConnectivityState newState, final SubchannelPicker newPicker) {
1400
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1401
      checkNotNull(newState, "newState");
1✔
1402
      checkNotNull(newPicker, "newPicker");
1✔
1403
      final class UpdateBalancingState implements Runnable {
1✔
1404
        @Override
1405
        public void run() {
1406
          if (LbHelperImpl.this != lbHelper) {
1✔
1407
            return;
1✔
1408
          }
1409
          updateSubchannelPicker(newPicker);
1✔
1410
          // It's not appropriate to report SHUTDOWN state from lb.
1411
          // Ignore the case of newState == SHUTDOWN for now.
1412
          if (newState != SHUTDOWN) {
1✔
1413
            channelLogger.log(
1✔
1414
                ChannelLogLevel.INFO, "Entering {0} state with picker: {1}", newState, newPicker);
1415
            channelStateManager.gotoState(newState);
1✔
1416
          }
1417
        }
1✔
1418
      }
1419

1420
      syncContext.execute(new UpdateBalancingState());
1✔
1421
    }
1✔
1422

1423
    @Override
1424
    public void refreshNameResolution() {
1425
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1426
      final class LoadBalancerRefreshNameResolution implements Runnable {
1✔
1427
        @Override
1428
        public void run() {
1429
          ManagedChannelImpl.this.refreshNameResolution();
1✔
1430
        }
1✔
1431
      }
1432

1433
      syncContext.execute(new LoadBalancerRefreshNameResolution());
1✔
1434
    }
1✔
1435

1436
    @Override
1437
    public ManagedChannel createOobChannel(EquivalentAddressGroup addressGroup, String authority) {
1438
      return createOobChannel(Collections.singletonList(addressGroup), authority);
×
1439
    }
1440

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

1476
        @Override
1477
        void onStateChange(InternalSubchannel is, ConnectivityStateInfo newState) {
1478
          // TODO(chengyuanzhang): change to let LB policies explicitly manage OOB channel's
1479
          //  state and refresh name resolution if necessary.
1480
          handleInternalSubchannelState(newState);
1✔
1481
          oobChannel.handleSubchannelStateChange(newState);
1✔
1482
        }
1✔
1483
      }
1484

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

1520
      syncContext.execute(new AddOobChannel());
1✔
1521
      return oobChannel;
1✔
1522
    }
1523

1524
    @Deprecated
1525
    @Override
1526
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
1527
      return createResolvingOobChannelBuilder(target, new DefaultChannelCreds())
1✔
1528
          // Override authority to keep the old behavior.
1529
          // createResolvingOobChannelBuilder(String target) will be deleted soon.
1530
          .overrideAuthority(getAuthority());
1✔
1531
    }
1532

1533
    // TODO(creamsoup) prevent main channel to shutdown if oob channel is not terminated
1534
    // TODO(zdapeng) register the channel as a subchannel of the parent channel in channelz.
1535
    @Override
1536
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1537
        final String target, final ChannelCredentials channelCreds) {
1538
      checkNotNull(channelCreds, "channelCreds");
1✔
1539

1540
      final class ResolvingOobChannelBuilder
1541
          extends ForwardingChannelBuilder2<ResolvingOobChannelBuilder> {
1542
        final ManagedChannelBuilder<?> delegate;
1543

1544
        ResolvingOobChannelBuilder() {
1✔
1545
          final ClientTransportFactory transportFactory;
1546
          CallCredentials callCredentials;
1547
          if (channelCreds instanceof DefaultChannelCreds) {
1✔
1548
            transportFactory = originalTransportFactory;
1✔
1549
            callCredentials = null;
1✔
1550
          } else {
1551
            SwapChannelCredentialsResult swapResult =
1✔
1552
                originalTransportFactory.swapChannelCredentials(channelCreds);
1✔
1553
            if (swapResult == null) {
1✔
1554
              delegate = Grpc.newChannelBuilder(target, channelCreds);
×
1555
              return;
×
1556
            } else {
1557
              transportFactory = swapResult.transportFactory;
1✔
1558
              callCredentials = swapResult.callCredentials;
1✔
1559
            }
1560
          }
1561
          ClientTransportFactoryBuilder transportFactoryBuilder =
1✔
1562
              new ClientTransportFactoryBuilder() {
1✔
1563
                @Override
1564
                public ClientTransportFactory buildClientTransportFactory() {
1565
                  return transportFactory;
1✔
1566
                }
1567
              };
1568
          delegate = new ManagedChannelImplBuilder(
1✔
1569
              target,
1570
              channelCreds,
1571
              callCredentials,
1572
              transportFactoryBuilder,
1573
              new FixedPortProvider(nameResolverArgs.getDefaultPort()))
1✔
1574
              .nameResolverRegistry(nameResolverRegistry);
1✔
1575
        }
1✔
1576

1577
        @Override
1578
        protected ManagedChannelBuilder<?> delegate() {
1579
          return delegate;
1✔
1580
        }
1581
      }
1582

1583
      checkState(!terminated, "Channel is terminated");
1✔
1584

1585
      @SuppressWarnings("deprecation")
1586
      ResolvingOobChannelBuilder builder = new ResolvingOobChannelBuilder();
1✔
1587

1588
      return builder
1✔
1589
          // TODO(zdapeng): executors should not outlive the parent channel.
1590
          .executor(executor)
1✔
1591
          .offloadExecutor(offloadExecutorHolder.getExecutor())
1✔
1592
          .maxTraceEvents(maxTraceEvents)
1✔
1593
          .proxyDetector(nameResolverArgs.getProxyDetector())
1✔
1594
          .userAgent(userAgent);
1✔
1595
    }
1596

1597
    @Override
1598
    public ChannelCredentials getUnsafeChannelCredentials() {
1599
      if (originalChannelCreds == null) {
1✔
1600
        return new DefaultChannelCreds();
1✔
1601
      }
1602
      return originalChannelCreds;
×
1603
    }
1604

1605
    @Override
1606
    public void updateOobChannelAddresses(ManagedChannel channel, EquivalentAddressGroup eag) {
1607
      updateOobChannelAddresses(channel, Collections.singletonList(eag));
×
1608
    }
×
1609

1610
    @Override
1611
    public void updateOobChannelAddresses(ManagedChannel channel,
1612
        List<EquivalentAddressGroup> eag) {
1613
      checkArgument(channel instanceof OobChannel,
1✔
1614
          "channel must have been returned from createOobChannel");
1615
      ((OobChannel) channel).updateAddresses(eag);
1✔
1616
    }
1✔
1617

1618
    @Override
1619
    public String getAuthority() {
1620
      return ManagedChannelImpl.this.authority();
1✔
1621
    }
1622

1623
    @Override
1624
    public String getChannelTarget() {
1625
      return targetUri.toString();
1✔
1626
    }
1627

1628
    @Override
1629
    public SynchronizationContext getSynchronizationContext() {
1630
      return syncContext;
1✔
1631
    }
1632

1633
    @Override
1634
    public ScheduledExecutorService getScheduledExecutorService() {
1635
      return scheduledExecutor;
1✔
1636
    }
1637

1638
    @Override
1639
    public ChannelLogger getChannelLogger() {
1640
      return channelLogger;
1✔
1641
    }
1642

1643
    @Override
1644
    public NameResolver.Args getNameResolverArgs() {
1645
      return nameResolverArgs;
1✔
1646
    }
1647

1648
    @Override
1649
    public NameResolverRegistry getNameResolverRegistry() {
1650
      return nameResolverRegistry;
1✔
1651
    }
1652

1653
    @Override
1654
    public MetricRecorder getMetricRecorder() {
1655
      return metricRecorder;
1✔
1656
    }
1657

1658
    /**
1659
     * A placeholder for channel creds if user did not specify channel creds for the channel.
1660
     */
1661
    // TODO(zdapeng): get rid of this class and let all ChannelBuilders always provide a non-null
1662
    //     channel creds.
1663
    final class DefaultChannelCreds extends ChannelCredentials {
1✔
1664
      @Override
1665
      public ChannelCredentials withoutBearerTokens() {
1666
        return this;
×
1667
      }
1668
    }
1669
  }
1670

1671
  final class NameResolverListener extends NameResolver.Listener2 {
1672
    final LbHelperImpl helper;
1673
    final NameResolver resolver;
1674

1675
    NameResolverListener(LbHelperImpl helperImpl, NameResolver resolver) {
1✔
1676
      this.helper = checkNotNull(helperImpl, "helperImpl");
1✔
1677
      this.resolver = checkNotNull(resolver, "resolver");
1✔
1678
    }
1✔
1679

1680
    @Override
1681
    public void onResult(final ResolutionResult resolutionResult) {
1682
      final class NamesResolved implements Runnable {
1✔
1683

1684
        @Override
1685
        public void run() {
1686
          Status status = onResult2(resolutionResult);
1✔
1687
          ResolutionResultListener resolutionResultListener = resolutionResult.getAttributes()
1✔
1688
              .get(RetryingNameResolver.RESOLUTION_RESULT_LISTENER_KEY);
1✔
1689
          resolutionResultListener.resolutionAttempted(status);
1✔
1690
        }
1✔
1691
      }
1692

1693
      syncContext.execute(new NamesResolved());
1✔
1694
    }
1✔
1695

1696
    @SuppressWarnings("ReferenceEquality")
1697
    @Override
1698
    public Status onResult2(final ResolutionResult resolutionResult) {
1699
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
1700
      if (ManagedChannelImpl.this.nameResolver != resolver) {
1✔
1701
        return Status.OK;
1✔
1702
      }
1703

1704
      List<EquivalentAddressGroup> servers = resolutionResult.getAddresses();
1✔
1705
      channelLogger.log(
1✔
1706
          ChannelLogLevel.DEBUG,
1707
          "Resolved address: {0}, config={1}",
1708
          servers,
1709
          resolutionResult.getAttributes());
1✔
1710

1711
      if (lastResolutionState != ResolutionState.SUCCESS) {
1✔
1712
        channelLogger.log(ChannelLogLevel.INFO, "Address resolved: {0}", servers);
1✔
1713
        lastResolutionState = ResolutionState.SUCCESS;
1✔
1714
      }
1715

1716
      ConfigOrError configOrError = resolutionResult.getServiceConfig();
1✔
1717
      InternalConfigSelector resolvedConfigSelector =
1✔
1718
          resolutionResult.getAttributes().get(InternalConfigSelector.KEY);
1✔
1719
      ManagedChannelServiceConfig validServiceConfig =
1720
          configOrError != null && configOrError.getConfig() != null
1✔
1721
              ? (ManagedChannelServiceConfig) configOrError.getConfig()
1✔
1722
              : null;
1✔
1723
      Status serviceConfigError = configOrError != null ? configOrError.getError() : null;
1✔
1724

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

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

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

1817
        return helper.lb.tryAcceptResolvedAddresses(
1✔
1818
            ResolvedAddresses.newBuilder()
1✔
1819
                .setAddresses(servers)
1✔
1820
                .setAttributes(attributes)
1✔
1821
                .setLoadBalancingPolicyConfig(effectiveServiceConfig.getLoadBalancingConfig())
1✔
1822
                .build());
1✔
1823
      }
1824
      return Status.OK;
×
1825
    }
1826

1827
    @Override
1828
    public void onError(final Status error) {
1829
      checkArgument(!error.isOk(), "the error status must not be OK");
1✔
1830
      final class NameResolverErrorHandler implements Runnable {
1✔
1831
        @Override
1832
        public void run() {
1833
          handleErrorInSyncContext(error);
1✔
1834
        }
1✔
1835
      }
1836

1837
      syncContext.execute(new NameResolverErrorHandler());
1✔
1838
    }
1✔
1839

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

1853
      helper.lb.handleNameResolutionError(error);
1✔
1854
    }
1✔
1855
  }
1856

1857
  private final class SubchannelImpl extends AbstractSubchannel {
1858
    final CreateSubchannelArgs args;
1859
    final InternalLogId subchannelLogId;
1860
    final ChannelLoggerImpl subchannelLogger;
1861
    final ChannelTracer subchannelTracer;
1862
    List<EquivalentAddressGroup> addressGroups;
1863
    InternalSubchannel subchannel;
1864
    boolean started;
1865
    boolean shutdown;
1866
    ScheduledHandle delayedShutdownTask;
1867

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

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

1900
        @Override
1901
        void onStateChange(InternalSubchannel is, ConnectivityStateInfo newState) {
1902
          checkState(listener != null, "listener is null");
1✔
1903
          listener.onSubchannelState(newState);
1✔
1904
        }
1✔
1905

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

1911
        @Override
1912
        void onNotInUse(InternalSubchannel is) {
1913
          inUseStateAggregator.updateObjectInUse(is, false);
1✔
1914
        }
1✔
1915
      }
1916

1917
      final InternalSubchannel internalSubchannel = new InternalSubchannel(
1✔
1918
          args.getAddresses(),
1✔
1919
          authority(),
1✔
1920
          userAgent,
1✔
1921
          backoffPolicyProvider,
1✔
1922
          transportFactory,
1✔
1923
          transportFactory.getScheduledExecutorService(),
1✔
1924
          stopwatchSupplier,
1✔
1925
          syncContext,
1926
          new ManagedInternalSubchannelCallback(),
1927
          channelz,
1✔
1928
          callTracerFactory.create(),
1✔
1929
          subchannelTracer,
1930
          subchannelLogId,
1931
          subchannelLogger,
1932
          transportFilters);
1✔
1933

1934
      channelTracer.reportEvent(new ChannelTrace.Event.Builder()
1✔
1935
          .setDescription("Child Subchannel started")
1✔
1936
          .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
1✔
1937
          .setTimestampNanos(timeProvider.currentTimeNanos())
1✔
1938
          .setSubchannelRef(internalSubchannel)
1✔
1939
          .build());
1✔
1940

1941
      this.subchannel = internalSubchannel;
1✔
1942
      channelz.addSubchannel(internalSubchannel);
1✔
1943
      subchannels.add(internalSubchannel);
1✔
1944
    }
1✔
1945

1946
    @Override
1947
    InternalInstrumented<ChannelStats> getInstrumentedInternalSubchannel() {
1948
      checkState(started, "not started");
1✔
1949
      return subchannel;
1✔
1950
    }
1951

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

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

2000
    @Override
2001
    public void requestConnection() {
2002
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
2003
      checkState(started, "not started");
1✔
2004
      subchannel.obtainActiveTransport();
1✔
2005
    }
1✔
2006

2007
    @Override
2008
    public List<EquivalentAddressGroup> getAllAddresses() {
2009
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
2010
      checkState(started, "not started");
1✔
2011
      return addressGroups;
1✔
2012
    }
2013

2014
    @Override
2015
    public Attributes getAttributes() {
2016
      return args.getAttributes();
1✔
2017
    }
2018

2019
    @Override
2020
    public String toString() {
2021
      return subchannelLogId.toString();
1✔
2022
    }
2023

2024
    @Override
2025
    public Channel asChannel() {
2026
      checkState(started, "not started");
1✔
2027
      return new SubchannelChannel(
1✔
2028
          subchannel, balancerRpcExecutorHolder.getExecutor(),
1✔
2029
          transportFactory.getScheduledExecutorService(),
1✔
2030
          callTracerFactory.create(),
1✔
2031
          new AtomicReference<InternalConfigSelector>(null));
2032
    }
2033

2034
    @Override
2035
    public Object getInternalSubchannel() {
2036
      checkState(started, "Subchannel is not started");
1✔
2037
      return subchannel;
1✔
2038
    }
2039

2040
    @Override
2041
    public ChannelLogger getChannelLogger() {
2042
      return subchannelLogger;
1✔
2043
    }
2044

2045
    @Override
2046
    public void updateAddresses(List<EquivalentAddressGroup> addrs) {
2047
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
2048
      addressGroups = addrs;
1✔
2049
      if (authorityOverride != null) {
1✔
2050
        addrs = stripOverrideAuthorityAttributes(addrs);
1✔
2051
      }
2052
      subchannel.updateAddresses(addrs);
1✔
2053
    }
1✔
2054

2055
    @Override
2056
    public Attributes getConnectedAddressAttributes() {
2057
      return subchannel.getConnectedAddressAttributes();
1✔
2058
    }
2059

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

2073
  @Override
2074
  public String toString() {
2075
    return MoreObjects.toStringHelper(this)
1✔
2076
        .add("logId", logId.getId())
1✔
2077
        .add("target", target)
1✔
2078
        .toString();
1✔
2079
  }
2080

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

2090
    @Override
2091
    public void transportReady() {
2092
      // Don't care
2093
    }
×
2094

2095
    @Override
2096
    public Attributes filterTransport(Attributes attributes) {
2097
      return attributes;
×
2098
    }
2099

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

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

2124
  /**
2125
   * Must be accessed from syncContext.
2126
   */
2127
  private final class IdleModeStateAggregator extends InUseStateAggregator<Object> {
1✔
2128
    @Override
2129
    protected void handleInUse() {
2130
      exitIdleMode();
1✔
2131
    }
1✔
2132

2133
    @Override
2134
    protected void handleNotInUse() {
2135
      if (shutdown.get()) {
1✔
2136
        return;
1✔
2137
      }
2138
      rescheduleIdleTimer();
1✔
2139
    }
1✔
2140
  }
2141

2142
  /**
2143
   * Lazily request for Executor from an executor pool.
2144
   * Also act as an Executor directly to simply run a cmd
2145
   */
2146
  @VisibleForTesting
2147
  static final class ExecutorHolder implements Executor {
2148
    private final ObjectPool<? extends Executor> pool;
2149
    private Executor executor;
2150

2151
    ExecutorHolder(ObjectPool<? extends Executor> executorPool) {
1✔
2152
      this.pool = checkNotNull(executorPool, "executorPool");
1✔
2153
    }
1✔
2154

2155
    synchronized Executor getExecutor() {
2156
      if (executor == null) {
1✔
2157
        executor = checkNotNull(pool.getObject(), "%s.getObject()", executor);
1✔
2158
      }
2159
      return executor;
1✔
2160
    }
2161

2162
    synchronized void release() {
2163
      if (executor != null) {
1✔
2164
        executor = pool.returnObject(executor);
1✔
2165
      }
2166
    }
1✔
2167

2168
    @Override
2169
    public void execute(Runnable command) {
2170
      getExecutor().execute(command);
1✔
2171
    }
1✔
2172
  }
2173

2174
  private static final class RestrictedScheduledExecutor implements ScheduledExecutorService {
2175
    final ScheduledExecutorService delegate;
2176

2177
    private RestrictedScheduledExecutor(ScheduledExecutorService delegate) {
1✔
2178
      this.delegate = checkNotNull(delegate, "delegate");
1✔
2179
    }
1✔
2180

2181
    @Override
2182
    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
2183
      return delegate.schedule(callable, delay, unit);
×
2184
    }
2185

2186
    @Override
2187
    public ScheduledFuture<?> schedule(Runnable cmd, long delay, TimeUnit unit) {
2188
      return delegate.schedule(cmd, delay, unit);
1✔
2189
    }
2190

2191
    @Override
2192
    public ScheduledFuture<?> scheduleAtFixedRate(
2193
        Runnable command, long initialDelay, long period, TimeUnit unit) {
2194
      return delegate.scheduleAtFixedRate(command, initialDelay, period, unit);
1✔
2195
    }
2196

2197
    @Override
2198
    public ScheduledFuture<?> scheduleWithFixedDelay(
2199
        Runnable command, long initialDelay, long delay, TimeUnit unit) {
2200
      return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
×
2201
    }
2202

2203
    @Override
2204
    public boolean awaitTermination(long timeout, TimeUnit unit)
2205
        throws InterruptedException {
2206
      return delegate.awaitTermination(timeout, unit);
×
2207
    }
2208

2209
    @Override
2210
    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
2211
        throws InterruptedException {
2212
      return delegate.invokeAll(tasks);
×
2213
    }
2214

2215
    @Override
2216
    public <T> List<Future<T>> invokeAll(
2217
        Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2218
        throws InterruptedException {
2219
      return delegate.invokeAll(tasks, timeout, unit);
×
2220
    }
2221

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

2228
    @Override
2229
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
2230
        throws InterruptedException, ExecutionException, TimeoutException {
2231
      return delegate.invokeAny(tasks, timeout, unit);
×
2232
    }
2233

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

2239
    @Override
2240
    public boolean isTerminated() {
2241
      return delegate.isTerminated();
×
2242
    }
2243

2244
    @Override
2245
    public void shutdown() {
2246
      throw new UnsupportedOperationException("Restricted: shutdown() is not allowed");
1✔
2247
    }
2248

2249
    @Override
2250
    public List<Runnable> shutdownNow() {
2251
      throw new UnsupportedOperationException("Restricted: shutdownNow() is not allowed");
1✔
2252
    }
2253

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

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

2264
    @Override
2265
    public <T> Future<T> submit(Runnable task, T result) {
2266
      return delegate.submit(task, result);
×
2267
    }
2268

2269
    @Override
2270
    public void execute(Runnable command) {
2271
      delegate.execute(command);
×
2272
    }
×
2273
  }
2274

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

© 2026 Coveralls, Inc