what-the-bank/sources/io/grpc/internal/ManagedChannelImpl.java

2135 lines
105 KiB
Java
Raw Permalink Normal View History

2024-07-27 18:17:47 +07:00
package io.grpc.internal;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.Attributes;
import io.grpc.CallCredentials;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ChannelCredentials;
import io.grpc.ChannelLogger;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ClientInterceptors;
import io.grpc.ClientStreamTracer;
import io.grpc.CompressorRegistry;
import io.grpc.ConnectivityState;
import io.grpc.ConnectivityStateInfo;
import io.grpc.Context;
import io.grpc.DecompressorRegistry;
import io.grpc.EquivalentAddressGroup;
import io.grpc.ForwardingChannelBuilder;
import io.grpc.ForwardingClientCall;
import io.grpc.Grpc;
import io.grpc.InternalChannelz;
import io.grpc.InternalConfigSelector;
import io.grpc.InternalInstrumented;
import io.grpc.InternalLogId;
import io.grpc.LoadBalancer;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.NameResolver;
import io.grpc.NameResolverRegistry;
import io.grpc.ProxyDetector;
import io.grpc.Status;
import io.grpc.SynchronizationContext;
import io.grpc.internal.AutoConfiguredLoadBalancerFactory;
import io.grpc.internal.BackoffPolicy;
import io.grpc.internal.CallTracer;
import io.grpc.internal.ClientCallImpl;
import io.grpc.internal.ClientTransportFactory;
import io.grpc.internal.InternalSubchannel;
import io.grpc.internal.ManagedChannelImplBuilder;
import io.grpc.internal.ManagedChannelServiceConfig;
import io.grpc.internal.ManagedClientTransport;
import io.grpc.internal.RetriableStream;
import java.lang.Thread;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public final class ManagedChannelImpl extends ManagedChannel implements InternalInstrumented<InternalChannelz.ChannelStats> {
static final long IDLE_TIMEOUT_MILLIS_DISABLE = -1;
static final long SUBCHANNEL_SHUTDOWN_DELAY_SECONDS = 5;
private final String authorityOverride;
private final BackoffPolicy.Provider backoffPolicyProvider;
private final ExecutorHolder balancerRpcExecutorHolder;
private final ObjectPool<? extends Executor> balancerRpcExecutorPool;
private final CallTracer.Factory callTracerFactory;
private final long channelBufferLimit;
private final RetriableStream.ChannelBufferMeter channelBufferUsed;
private final CallTracer channelCallTracer;
private final ChannelLogger channelLogger;
private final ConnectivityStateManager channelStateManager;
private final ChannelTracer channelTracer;
private final InternalChannelz channelz;
private final CompressorRegistry compressorRegistry;
private final DecompressorRegistry decompressorRegistry;
private final ManagedChannelServiceConfig defaultServiceConfig;
private final DelayedClientTransport delayedTransport;
private final ManagedClientTransport.Listener delayedTransportListener;
private final Executor executor;
private final ObjectPool<? extends Executor> executorPool;
private boolean fullStreamDecompression;
private final long idleTimeoutMillis;
private final Rescheduler idleTimer;
final InUseStateAggregator<Object> inUseStateAggregator;
private final Channel interceptorChannel;
private ResolutionState lastResolutionState;
private ManagedChannelServiceConfig lastServiceConfig;
private LbHelperImpl lbHelper;
private final AutoConfiguredLoadBalancerFactory loadBalancerFactory;
private final InternalLogId logId;
private final boolean lookUpServiceConfig;
private final int maxTraceEvents;
private NameResolver nameResolver;
private final NameResolver.Args nameResolverArgs;
private BackoffPolicy nameResolverBackoffPolicy;
private final NameResolver.Factory nameResolverFactory;
private final NameResolverRegistry nameResolverRegistry;
private boolean nameResolverStarted;
private final ExecutorHolder offloadExecutorHolder;
private final Set<OobChannel> oobChannels;
private final ClientTransportFactory oobTransportFactory;
private final ChannelCredentials originalChannelCreds;
private final ClientTransportFactory originalTransportFactory;
private boolean panicMode;
private Collection<RealChannel.PendingCall<?, ?>> pendingCalls;
private final Object pendingCallsInUseObject;
private final long perRpcBufferLimit;
private final RealChannel realChannel;
private final boolean retryEnabled;
private final RestrictedScheduledExecutor scheduledExecutor;
private SynchronizationContext.ScheduledHandle scheduledNameResolverRefresh;
private boolean serviceConfigUpdated;
private final AtomicBoolean shutdown;
private boolean shutdownNowed;
private final Supplier<Stopwatch> stopwatchSupplier;
private volatile LoadBalancer.SubchannelPicker subchannelPicker;
private final Set<InternalSubchannel> subchannels;
final SynchronizationContext syncContext;
private final String target;
private volatile boolean terminated;
private final CountDownLatch terminatedLatch;
private boolean terminating;
private final TimeProvider timeProvider;
private final ClientTransportFactory transportFactory;
private final ClientCallImpl.ClientStreamProvider transportProvider;
private final UncommittedRetriableStreamsRegistry uncommittedRetriableStreamsRegistry;
private final String userAgent;
static final Logger logger = Logger.getLogger(ManagedChannelImpl.class.getName());
static final Pattern URI_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9+.-]*:/.*");
static final Status SHUTDOWN_NOW_STATUS = Status.UNAVAILABLE.withDescription("Channel shutdownNow invoked");
static final Status SHUTDOWN_STATUS = Status.UNAVAILABLE.withDescription("Channel shutdown invoked");
static final Status SUBCHANNEL_SHUTDOWN_STATUS = Status.UNAVAILABLE.withDescription("Subchannel shutdown invoked");
private static final ManagedChannelServiceConfig EMPTY_SERVICE_CONFIG = ManagedChannelServiceConfig.empty();
private static final InternalConfigSelector INITIAL_PENDING_SELECTOR = new InternalConfigSelector() { // from class: io.grpc.internal.ManagedChannelImpl.1
@Override // io.grpc.InternalConfigSelector
public InternalConfigSelector.Result selectConfig(LoadBalancer.PickSubchannelArgs pickSubchannelArgs) {
throw new IllegalStateException("Resolution is pending");
}
};
private static final ClientCall<Object, Object> NOOP_CALL = new ClientCall<Object, Object>() { // from class: io.grpc.internal.ManagedChannelImpl.5
@Override // io.grpc.ClientCall
public void cancel(String str, Throwable th) {
}
@Override // io.grpc.ClientCall
public void halfClose() {
}
@Override // io.grpc.ClientCall
public boolean isReady() {
return false;
}
@Override // io.grpc.ClientCall
public void request(int i) {
}
@Override // io.grpc.ClientCall
public void sendMessage(Object obj) {
}
@Override // io.grpc.ClientCall
public void start(ClientCall.Listener<Object> listener, Metadata metadata) {
}
};
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public enum ResolutionState {
NO_RESOLUTION,
SUCCESS,
ERROR
}
/* JADX INFO: Access modifiers changed from: private */
public void maybeShutdownNowSubchannels() {
if (this.shutdownNowed) {
Iterator<InternalSubchannel> it = this.subchannels.iterator();
while (it.hasNext()) {
it.next().shutdownNow(SHUTDOWN_NOW_STATUS);
}
Iterator<OobChannel> it2 = this.oobChannels.iterator();
while (it2.hasNext()) {
it2.next().getInternalSubchannel().shutdownNow(SHUTDOWN_NOW_STATUS);
}
}
}
@Override // io.grpc.InternalInstrumented
public final ListenableFuture<InternalChannelz.ChannelStats> getStats() {
SettableFuture create = SettableFuture.create();
this.syncContext.execute(new Runnable(this, create) { // from class: io.grpc.internal.ManagedChannelImpl.1StatsFetcher
final ManagedChannelImpl this$0;
final SettableFuture val$ret;
{
this.this$0 = this;
this.val$ret = create;
}
@Override // java.lang.Runnable
public final void run() {
InternalChannelz.ChannelStats.Builder builder = new InternalChannelz.ChannelStats.Builder();
this.this$0.channelCallTracer.updateBuilder(builder);
this.this$0.channelTracer.updateBuilder(builder);
builder.setTarget(this.this$0.target).setState(this.this$0.channelStateManager.getState());
ArrayList arrayList = new ArrayList();
arrayList.addAll(this.this$0.subchannels);
arrayList.addAll(this.this$0.oobChannels);
builder.setSubchannels(arrayList);
this.val$ret.set(builder.build());
}
});
return create;
}
/* loaded from: classes6.dex */
class IdleModeTimer implements Runnable {
final ManagedChannelImpl this$0;
private IdleModeTimer(ManagedChannelImpl managedChannelImpl) {
this.this$0 = managedChannelImpl;
}
@Override // java.lang.Runnable
public void run() {
if (this.this$0.lbHelper == null) {
return;
}
this.this$0.enterIdleMode();
}
}
/* JADX INFO: Access modifiers changed from: private */
public void shutdownNameResolverAndLoadBalancer(boolean z) {
this.syncContext.throwIfNotInThisSynchronizationContext();
if (z) {
Preconditions.checkState(this.nameResolverStarted, "nameResolver is not started");
Preconditions.checkState(this.lbHelper != null, "lbHelper is null");
}
if (this.nameResolver != null) {
cancelNameResolverBackoff();
this.nameResolver.shutdown();
this.nameResolverStarted = false;
if (z) {
this.nameResolver = getNameResolver(this.target, this.authorityOverride, this.nameResolverFactory, this.nameResolverArgs);
} else {
this.nameResolver = null;
}
}
LbHelperImpl lbHelperImpl = this.lbHelper;
if (lbHelperImpl != null) {
lbHelperImpl.lb.shutdown();
this.lbHelper = null;
}
this.subchannelPicker = null;
}
final void exitIdleMode() {
this.syncContext.throwIfNotInThisSynchronizationContext();
if (this.shutdown.get() || this.panicMode) {
return;
}
if (this.inUseStateAggregator.isInUse()) {
cancelIdleTimer(false);
} else {
rescheduleIdleTimer();
}
if (this.lbHelper != null) {
return;
}
this.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Exiting idle mode");
LbHelperImpl lbHelperImpl = new LbHelperImpl();
lbHelperImpl.lb = this.loadBalancerFactory.newLoadBalancer(lbHelperImpl);
this.lbHelper = lbHelperImpl;
this.nameResolver.start((NameResolver.Listener2) new NameResolverListener(this, lbHelperImpl, this.nameResolver));
this.nameResolverStarted = true;
}
/* JADX INFO: Access modifiers changed from: private */
public void enterIdleMode() {
shutdownNameResolverAndLoadBalancer(true);
this.delayedTransport.reprocess(null);
this.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Entering IDLE state");
this.channelStateManager.gotoState(ConnectivityState.IDLE);
if (this.inUseStateAggregator.anyObjectInUse(this.pendingCallsInUseObject, this.delayedTransport)) {
exitIdleMode();
}
}
/* JADX INFO: Access modifiers changed from: private */
public void cancelIdleTimer(boolean z) {
this.idleTimer.cancel(z);
}
/* JADX INFO: Access modifiers changed from: private */
public void rescheduleIdleTimer() {
long j = this.idleTimeoutMillis;
if (j == -1) {
return;
}
this.idleTimer.reschedule(j, TimeUnit.MILLISECONDS);
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public class DelayedNameResolverRefresh implements Runnable {
final ManagedChannelImpl this$0;
DelayedNameResolverRefresh(ManagedChannelImpl managedChannelImpl) {
this.this$0 = managedChannelImpl;
}
@Override // java.lang.Runnable
public void run() {
this.this$0.scheduledNameResolverRefresh = null;
this.this$0.refreshNameResolution();
}
}
private void cancelNameResolverBackoff() {
this.syncContext.throwIfNotInThisSynchronizationContext();
SynchronizationContext.ScheduledHandle scheduledHandle = this.scheduledNameResolverRefresh;
if (scheduledHandle != null) {
scheduledHandle.cancel();
this.scheduledNameResolverRefresh = null;
this.nameResolverBackoffPolicy = null;
}
}
/* JADX INFO: Access modifiers changed from: private */
public void refreshAndResetNameResolution() {
this.syncContext.throwIfNotInThisSynchronizationContext();
cancelNameResolverBackoff();
refreshNameResolution();
}
/* JADX INFO: Access modifiers changed from: private */
public void refreshNameResolution() {
this.syncContext.throwIfNotInThisSynchronizationContext();
if (this.nameResolverStarted) {
this.nameResolver.refresh();
}
}
/* loaded from: classes6.dex */
final class ChannelStreamProvider implements ClientCallImpl.ClientStreamProvider {
final ManagedChannelImpl this$0;
private ChannelStreamProvider(ManagedChannelImpl managedChannelImpl) {
this.this$0 = managedChannelImpl;
}
/* JADX INFO: Access modifiers changed from: private */
public ClientTransport getTransport(LoadBalancer.PickSubchannelArgs pickSubchannelArgs) {
LoadBalancer.SubchannelPicker subchannelPicker = this.this$0.subchannelPicker;
if (this.this$0.shutdown.get()) {
return this.this$0.delayedTransport;
}
if (subchannelPicker == null) {
this.this$0.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.ChannelStreamProvider.1ExitIdleModeForTransport
final ChannelStreamProvider this$1;
{
this.this$1 = this;
}
@Override // java.lang.Runnable
public final void run() {
this.this$1.this$0.exitIdleMode();
}
});
return this.this$0.delayedTransport;
}
ClientTransport transportFromPickResult = GrpcUtil.getTransportFromPickResult(subchannelPicker.pickSubchannel(pickSubchannelArgs), pickSubchannelArgs.getCallOptions().isWaitForReady());
return transportFromPickResult != null ? transportFromPickResult : this.this$0.delayedTransport;
}
@Override // io.grpc.internal.ClientCallImpl.ClientStreamProvider
public final ClientStream newStream(MethodDescriptor<?, ?> methodDescriptor, CallOptions callOptions, Metadata metadata, Context context) {
if (this.this$0.retryEnabled) {
RetriableStream.Throttle retryThrottling = this.this$0.lastServiceConfig.getRetryThrottling();
ManagedChannelServiceConfig.MethodInfo methodInfo = (ManagedChannelServiceConfig.MethodInfo) callOptions.getOption(ManagedChannelServiceConfig.MethodInfo.KEY);
return new RetriableStream<ReqT>(this, methodDescriptor, metadata, callOptions, methodInfo == null ? null : methodInfo.retryPolicy, methodInfo == null ? null : methodInfo.hedgingPolicy, retryThrottling, context) { // from class: io.grpc.internal.ManagedChannelImpl.ChannelStreamProvider.1RetryStream
final ChannelStreamProvider this$1;
final CallOptions val$callOptions;
final Context val$context;
final Metadata val$headers;
final HedgingPolicy val$hedgingPolicy;
final MethodDescriptor val$method;
final RetryPolicy val$retryPolicy;
final RetriableStream.Throttle val$throttle;
/* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
{
super(methodDescriptor, metadata, this.this$0.channelBufferUsed, this.this$0.perRpcBufferLimit, this.this$0.channelBufferLimit, this.this$0.getCallExecutor(callOptions), this.this$0.transportFactory.getScheduledExecutorService(), r20, r21, retryThrottling);
this.this$1 = this;
this.val$method = methodDescriptor;
this.val$headers = metadata;
this.val$callOptions = callOptions;
this.val$retryPolicy = r20;
this.val$hedgingPolicy = r21;
this.val$throttle = retryThrottling;
this.val$context = context;
}
@Override // io.grpc.internal.RetriableStream
final Status prestart() {
return this.this$1.this$0.uncommittedRetriableStreamsRegistry.add(this);
}
@Override // io.grpc.internal.RetriableStream
final void postCommit() {
this.this$1.this$0.uncommittedRetriableStreamsRegistry.remove(this);
}
@Override // io.grpc.internal.RetriableStream
final ClientStream newSubstream(Metadata metadata2, ClientStreamTracer.Factory factory, int i, boolean z) {
CallOptions withStreamTracerFactory = this.val$callOptions.withStreamTracerFactory(factory);
ClientStreamTracer[] clientStreamTracers = GrpcUtil.getClientStreamTracers(withStreamTracerFactory, metadata2, i, z);
ClientTransport transport = this.this$1.getTransport(new PickSubchannelArgsImpl(this.val$method, metadata2, withStreamTracerFactory));
Context attach = this.val$context.attach();
try {
return transport.newStream(this.val$method, metadata2, withStreamTracerFactory, clientStreamTracers);
} finally {
this.val$context.detach(attach);
}
}
};
}
ClientTransport transport = getTransport(new PickSubchannelArgsImpl(methodDescriptor, metadata, callOptions));
Context attach = context.attach();
try {
return transport.newStream(methodDescriptor, metadata, callOptions, GrpcUtil.getClientStreamTracers(callOptions, metadata, 0, false));
} finally {
context.detach(attach);
}
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* JADX WARN: Multi-variable type inference failed */
/* JADX WARN: Type inference failed for: r6v17, types: [io.grpc.Channel] */
public ManagedChannelImpl(ManagedChannelImplBuilder managedChannelImplBuilder, ClientTransportFactory clientTransportFactory, BackoffPolicy.Provider provider, ObjectPool<? extends Executor> objectPool, Supplier<Stopwatch> supplier, List<ClientInterceptor> list, TimeProvider timeProvider) {
AnonymousClass1 anonymousClass1;
SynchronizationContext synchronizationContext = new SynchronizationContext(new Thread.UncaughtExceptionHandler(this) { // from class: io.grpc.internal.ManagedChannelImpl.2
final ManagedChannelImpl this$0;
{
this.this$0 = this;
}
@Override // java.lang.Thread.UncaughtExceptionHandler
public void uncaughtException(Thread thread, Throwable th) {
Logger logger2 = ManagedChannelImpl.logger;
Level level = Level.SEVERE;
StringBuilder sb = new StringBuilder("[");
sb.append(this.this$0.getLogId());
sb.append("] Uncaught exception in the SynchronizationContext. Panic!");
logger2.log(level, sb.toString(), th);
this.this$0.panic(th);
}
});
this.syncContext = synchronizationContext;
this.channelStateManager = new ConnectivityStateManager();
this.subchannels = new HashSet(16, 0.75f);
this.pendingCallsInUseObject = new Object();
this.oobChannels = new HashSet(1, 0.75f);
this.uncommittedRetriableStreamsRegistry = new UncommittedRetriableStreamsRegistry();
this.shutdown = new AtomicBoolean(false);
this.terminatedLatch = new CountDownLatch(1);
this.lastResolutionState = ResolutionState.NO_RESOLUTION;
this.lastServiceConfig = EMPTY_SERVICE_CONFIG;
this.serviceConfigUpdated = false;
this.channelBufferUsed = new RetriableStream.ChannelBufferMeter();
DelayedTransportListener delayedTransportListener = new DelayedTransportListener();
this.delayedTransportListener = delayedTransportListener;
this.inUseStateAggregator = new IdleModeStateAggregator();
this.transportProvider = new ChannelStreamProvider();
String str = (String) Preconditions.checkNotNull(managedChannelImplBuilder.target, "target");
this.target = str;
InternalLogId allocate = InternalLogId.allocate("Channel", str);
this.logId = allocate;
this.timeProvider = (TimeProvider) Preconditions.checkNotNull(timeProvider, "timeProvider");
ObjectPool<? extends Executor> objectPool2 = (ObjectPool) Preconditions.checkNotNull(managedChannelImplBuilder.executorPool, "executorPool");
this.executorPool = objectPool2;
Executor executor = (Executor) Preconditions.checkNotNull(objectPool2.getObject(), "executor");
this.executor = executor;
this.originalChannelCreds = managedChannelImplBuilder.channelCredentials;
this.originalTransportFactory = clientTransportFactory;
CallCredentialsApplyingTransportFactory callCredentialsApplyingTransportFactory = new CallCredentialsApplyingTransportFactory(clientTransportFactory, managedChannelImplBuilder.callCredentials, executor);
this.transportFactory = callCredentialsApplyingTransportFactory;
this.oobTransportFactory = new CallCredentialsApplyingTransportFactory(clientTransportFactory, null, executor);
RestrictedScheduledExecutor restrictedScheduledExecutor = new RestrictedScheduledExecutor(callCredentialsApplyingTransportFactory.getScheduledExecutorService());
this.scheduledExecutor = restrictedScheduledExecutor;
this.maxTraceEvents = managedChannelImplBuilder.maxTraceEvents;
int i = managedChannelImplBuilder.maxTraceEvents;
long currentTimeNanos = timeProvider.currentTimeNanos();
StringBuilder sb = new StringBuilder("Channel for '");
sb.append(str);
sb.append("'");
ChannelTracer channelTracer = new ChannelTracer(allocate, i, currentTimeNanos, sb.toString());
this.channelTracer = channelTracer;
ChannelLoggerImpl channelLoggerImpl = new ChannelLoggerImpl(channelTracer, timeProvider);
this.channelLogger = channelLoggerImpl;
ProxyDetector proxyDetector = managedChannelImplBuilder.proxyDetector != null ? managedChannelImplBuilder.proxyDetector : GrpcUtil.DEFAULT_PROXY_DETECTOR;
boolean z = managedChannelImplBuilder.retryEnabled;
this.retryEnabled = z;
AutoConfiguredLoadBalancerFactory autoConfiguredLoadBalancerFactory = new AutoConfiguredLoadBalancerFactory(managedChannelImplBuilder.defaultLbPolicy);
this.loadBalancerFactory = autoConfiguredLoadBalancerFactory;
this.offloadExecutorHolder = new ExecutorHolder((ObjectPool) Preconditions.checkNotNull(managedChannelImplBuilder.offloadExecutorPool, "offloadExecutorPool"));
this.nameResolverRegistry = managedChannelImplBuilder.nameResolverRegistry;
ScParser scParser = new ScParser(z, managedChannelImplBuilder.maxRetryAttempts, managedChannelImplBuilder.maxHedgedAttempts, autoConfiguredLoadBalancerFactory);
NameResolver.Args build = NameResolver.Args.newBuilder().setDefaultPort(managedChannelImplBuilder.getDefaultPort()).setProxyDetector(proxyDetector).setSynchronizationContext(synchronizationContext).setScheduledExecutorService(restrictedScheduledExecutor).setServiceConfigParser(scParser).setChannelLogger(channelLoggerImpl).setOffloadExecutor(new Executor(this) { // from class: io.grpc.internal.ManagedChannelImpl.3
final ManagedChannelImpl this$0;
{
this.this$0 = this;
}
@Override // java.util.concurrent.Executor
public void execute(Runnable runnable) {
this.this$0.offloadExecutorHolder.getExecutor().execute(runnable);
}
}).build();
this.nameResolverArgs = build;
String str2 = managedChannelImplBuilder.authorityOverride;
this.authorityOverride = str2;
NameResolver.Factory factory = managedChannelImplBuilder.nameResolverFactory;
this.nameResolverFactory = factory;
this.nameResolver = getNameResolver(str, str2, factory, build);
this.balancerRpcExecutorPool = (ObjectPool) Preconditions.checkNotNull(objectPool, "balancerRpcExecutorPool");
this.balancerRpcExecutorHolder = new ExecutorHolder(objectPool);
DelayedClientTransport delayedClientTransport = new DelayedClientTransport(executor, synchronizationContext);
this.delayedTransport = delayedClientTransport;
delayedClientTransport.start(delayedTransportListener);
this.backoffPolicyProvider = provider;
if (managedChannelImplBuilder.defaultServiceConfig != null) {
NameResolver.ConfigOrError parseServiceConfig = scParser.parseServiceConfig(managedChannelImplBuilder.defaultServiceConfig);
Preconditions.checkState(parseServiceConfig.getError() == null, "Default config is invalid: %s", parseServiceConfig.getError());
ManagedChannelServiceConfig managedChannelServiceConfig = (ManagedChannelServiceConfig) parseServiceConfig.getConfig();
this.defaultServiceConfig = managedChannelServiceConfig;
this.lastServiceConfig = managedChannelServiceConfig;
anonymousClass1 = null;
} else {
anonymousClass1 = null;
this.defaultServiceConfig = null;
}
boolean z2 = managedChannelImplBuilder.lookUpServiceConfig;
this.lookUpServiceConfig = z2;
RealChannel realChannel = new RealChannel(this.nameResolver.getServiceAuthority());
this.realChannel = realChannel;
this.interceptorChannel = ClientInterceptors.intercept(managedChannelImplBuilder.binlog != null ? managedChannelImplBuilder.binlog.wrapChannel(realChannel) : realChannel, list);
this.stopwatchSupplier = (Supplier) Preconditions.checkNotNull(supplier, "stopwatchSupplier");
if (managedChannelImplBuilder.idleTimeoutMillis == -1) {
this.idleTimeoutMillis = managedChannelImplBuilder.idleTimeoutMillis;
} else {
Preconditions.checkArgument(managedChannelImplBuilder.idleTimeoutMillis >= ManagedChannelImplBuilder.IDLE_MODE_MIN_TIMEOUT_MILLIS, "invalid idleTimeoutMillis %s", managedChannelImplBuilder.idleTimeoutMillis);
this.idleTimeoutMillis = managedChannelImplBuilder.idleTimeoutMillis;
}
this.idleTimer = new Rescheduler(new IdleModeTimer(), synchronizationContext, callCredentialsApplyingTransportFactory.getScheduledExecutorService(), supplier.get());
this.fullStreamDecompression = managedChannelImplBuilder.fullStreamDecompression;
this.decompressorRegistry = (DecompressorRegistry) Preconditions.checkNotNull(managedChannelImplBuilder.decompressorRegistry, "decompressorRegistry");
this.compressorRegistry = (CompressorRegistry) Preconditions.checkNotNull(managedChannelImplBuilder.compressorRegistry, "compressorRegistry");
this.userAgent = managedChannelImplBuilder.userAgent;
this.channelBufferLimit = managedChannelImplBuilder.retryBufferSize;
this.perRpcBufferLimit = managedChannelImplBuilder.perRpcBufferLimit;
CallTracer.Factory factory2 = new CallTracer.Factory(this, timeProvider) { // from class: io.grpc.internal.ManagedChannelImpl.1ChannelCallTracerFactory
final ManagedChannelImpl this$0;
final TimeProvider val$timeProvider;
{
this.this$0 = this;
this.val$timeProvider = timeProvider;
}
@Override // io.grpc.internal.CallTracer.Factory
public final CallTracer create() {
return new CallTracer(this.val$timeProvider);
}
};
this.callTracerFactory = factory2;
this.channelCallTracer = factory2.create();
InternalChannelz internalChannelz = (InternalChannelz) Preconditions.checkNotNull(managedChannelImplBuilder.channelz);
this.channelz = internalChannelz;
internalChannelz.addRootChannel(this);
if (z2) {
return;
}
if (this.defaultServiceConfig != null) {
channelLoggerImpl.log(ChannelLogger.ChannelLogLevel.INFO, "Service config look-up disabled, using default service config");
}
this.serviceConfigUpdated = true;
}
private static NameResolver getNameResolver(String str, NameResolver.Factory factory, NameResolver.Args args) {
URI uri;
NameResolver newNameResolver;
StringBuilder sb = new StringBuilder();
try {
uri = new URI(str);
} catch (URISyntaxException e) {
sb.append(e.getMessage());
uri = null;
}
if (uri != null && (newNameResolver = factory.newNameResolver(uri, args)) != null) {
return newNameResolver;
}
String str2 = "";
if (!URI_PATTERN.matcher(str).matches()) {
try {
String defaultScheme = factory.getDefaultScheme();
StringBuilder sb2 = new StringBuilder("/");
sb2.append(str);
NameResolver newNameResolver2 = factory.newNameResolver(new URI(defaultScheme, "", sb2.toString(), null), args);
if (newNameResolver2 != null) {
return newNameResolver2;
}
} catch (URISyntaxException e2) {
throw new IllegalArgumentException(e2);
}
}
Object[] objArr = new Object[2];
objArr[0] = str;
if (sb.length() > 0) {
StringBuilder sb3 = new StringBuilder(" (");
sb3.append((Object) sb);
sb3.append(")");
str2 = sb3.toString();
}
objArr[1] = str2;
throw new IllegalArgumentException(String.format("cannot find a NameResolver for %s%s", objArr));
}
static NameResolver getNameResolver(String str, String str2, NameResolver.Factory factory, NameResolver.Args args) {
NameResolver nameResolver = getNameResolver(str, factory, args);
return str2 == null ? nameResolver : new ForwardingNameResolver(nameResolver, str2) { // from class: io.grpc.internal.ManagedChannelImpl.4
final String val$overrideAuthority;
{
this.val$overrideAuthority = str2;
}
@Override // io.grpc.internal.ForwardingNameResolver, io.grpc.NameResolver
public String getServiceAuthority() {
return this.val$overrideAuthority;
}
};
}
final InternalConfigSelector getConfigSelector() {
return (InternalConfigSelector) this.realChannel.configSelector.get();
}
@Override // io.grpc.ManagedChannel
public final ManagedChannelImpl shutdown() {
this.channelLogger.log(ChannelLogger.ChannelLogLevel.DEBUG, "shutdown() called");
if (!this.shutdown.compareAndSet(false, true)) {
return this;
}
this.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.1Shutdown
final ManagedChannelImpl this$0;
{
this.this$0 = this;
}
@Override // java.lang.Runnable
public final void run() {
this.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Entering SHUTDOWN state");
this.this$0.channelStateManager.gotoState(ConnectivityState.SHUTDOWN);
}
});
this.realChannel.shutdown();
this.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.1CancelIdleTimer
final ManagedChannelImpl this$0;
{
this.this$0 = this;
}
@Override // java.lang.Runnable
public final void run() {
this.this$0.cancelIdleTimer(true);
}
});
return this;
}
@Override // io.grpc.ManagedChannel
public final ManagedChannelImpl shutdownNow() {
this.channelLogger.log(ChannelLogger.ChannelLogLevel.DEBUG, "shutdownNow() called");
shutdown();
this.realChannel.shutdownNow();
this.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.1ShutdownNow
final ManagedChannelImpl this$0;
{
this.this$0 = this;
}
@Override // java.lang.Runnable
public final void run() {
if (this.this$0.shutdownNowed) {
return;
}
this.this$0.shutdownNowed = true;
this.this$0.maybeShutdownNowSubchannels();
}
});
return this;
}
final void panic(Throwable th) {
if (this.panicMode) {
return;
}
this.panicMode = true;
cancelIdleTimer(true);
shutdownNameResolverAndLoadBalancer(false);
updateSubchannelPicker(new LoadBalancer.SubchannelPicker(this, th) { // from class: io.grpc.internal.ManagedChannelImpl.1PanicSubchannelPicker
private final LoadBalancer.PickResult panicPickResult;
final ManagedChannelImpl this$0;
final Throwable val$t;
{
this.this$0 = this;
this.val$t = th;
this.panicPickResult = LoadBalancer.PickResult.withDrop(Status.INTERNAL.withDescription("Panic! This is a bug!").withCause(th));
}
public final String toString() {
return MoreObjects.toStringHelper((Class<?>) C1PanicSubchannelPicker.class).add("panicPickResult", this.panicPickResult).toString();
}
@Override // io.grpc.LoadBalancer.SubchannelPicker
public final LoadBalancer.PickResult pickSubchannel(LoadBalancer.PickSubchannelArgs pickSubchannelArgs) {
return this.panicPickResult;
}
});
this.channelLogger.log(ChannelLogger.ChannelLogLevel.ERROR, "PANIC! Entering TRANSIENT_FAILURE");
this.channelStateManager.gotoState(ConnectivityState.TRANSIENT_FAILURE);
}
/* JADX INFO: Access modifiers changed from: private */
public void updateSubchannelPicker(LoadBalancer.SubchannelPicker subchannelPicker) {
this.subchannelPicker = subchannelPicker;
this.delayedTransport.reprocess(subchannelPicker);
}
@Override // io.grpc.ManagedChannel
public final boolean isShutdown() {
return this.shutdown.get();
}
@Override // io.grpc.ManagedChannel
public final boolean awaitTermination(long j, TimeUnit timeUnit) throws InterruptedException {
return this.terminatedLatch.await(j, timeUnit);
}
@Override // io.grpc.Channel
public final <ReqT, RespT> ClientCall<ReqT, RespT> newCall(MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
return this.interceptorChannel.newCall(methodDescriptor, callOptions);
}
@Override // io.grpc.Channel
public final String authority() {
return this.interceptorChannel.authority();
}
/* JADX INFO: Access modifiers changed from: private */
public Executor getCallExecutor(CallOptions callOptions) {
Executor executor = callOptions.getExecutor();
return executor == null ? this.executor : executor;
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public class RealChannel extends Channel {
private final String authority;
private final Channel clientCallImplChannel;
private final AtomicReference<InternalConfigSelector> configSelector;
final ManagedChannelImpl this$0;
private RealChannel(ManagedChannelImpl managedChannelImpl, String str) {
this.this$0 = managedChannelImpl;
this.configSelector = new AtomicReference<>(ManagedChannelImpl.INITIAL_PENDING_SELECTOR);
this.clientCallImplChannel = new Channel(this) { // from class: io.grpc.internal.ManagedChannelImpl.RealChannel.1
final RealChannel this$1;
{
this.this$1 = this;
}
@Override // io.grpc.Channel
public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) {
return new ClientCallImpl(methodDescriptor, this.this$1.this$0.getCallExecutor(callOptions), callOptions, this.this$1.this$0.transportProvider, this.this$1.this$0.terminated ? null : this.this$1.this$0.transportFactory.getScheduledExecutorService(), this.this$1.this$0.channelCallTracer, null).setFullStreamDecompression(this.this$1.this$0.fullStreamDecompression).setDecompressorRegistry(this.this$1.this$0.decompressorRegistry).setCompressorRegistry(this.this$1.this$0.compressorRegistry);
}
@Override // io.grpc.Channel
public String authority() {
return this.this$1.authority;
}
};
this.authority = (String) Preconditions.checkNotNull(str, "authority");
}
@Override // io.grpc.Channel
public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
if (this.configSelector.get() != ManagedChannelImpl.INITIAL_PENDING_SELECTOR) {
return newClientCall(methodDescriptor, callOptions);
}
this.this$0.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.RealChannel.2
final RealChannel this$1;
{
this.this$1 = this;
}
@Override // java.lang.Runnable
public void run() {
this.this$1.this$0.exitIdleMode();
}
});
if (this.configSelector.get() == ManagedChannelImpl.INITIAL_PENDING_SELECTOR) {
if (this.this$0.shutdown.get()) {
return new ClientCall<ReqT, RespT>(this) { // from class: io.grpc.internal.ManagedChannelImpl.RealChannel.3
final RealChannel this$1;
@Override // io.grpc.ClientCall
public void cancel(String str, Throwable th) {
}
@Override // io.grpc.ClientCall
public void halfClose() {
}
@Override // io.grpc.ClientCall
public void request(int i) {
}
@Override // io.grpc.ClientCall
public void sendMessage(ReqT reqt) {
}
{
this.this$1 = this;
}
@Override // io.grpc.ClientCall
public void start(ClientCall.Listener<RespT> listener, Metadata metadata) {
listener.onClose(ManagedChannelImpl.SHUTDOWN_STATUS, new Metadata());
}
};
}
PendingCall pendingCall = new PendingCall(this, Context.current(), methodDescriptor, callOptions);
this.this$0.syncContext.execute(new Runnable(this, pendingCall) { // from class: io.grpc.internal.ManagedChannelImpl.RealChannel.4
final RealChannel this$1;
final PendingCall val$pendingCall;
{
this.this$1 = this;
this.val$pendingCall = pendingCall;
}
@Override // java.lang.Runnable
public void run() {
if (this.this$1.configSelector.get() == ManagedChannelImpl.INITIAL_PENDING_SELECTOR) {
if (this.this$1.this$0.pendingCalls == null) {
this.this$1.this$0.pendingCalls = new LinkedHashSet();
this.this$1.this$0.inUseStateAggregator.updateObjectInUse(this.this$1.this$0.pendingCallsInUseObject, true);
}
this.this$1.this$0.pendingCalls.add(this.val$pendingCall);
return;
}
this.val$pendingCall.reprocess();
}
});
return pendingCall;
}
return newClientCall(methodDescriptor, callOptions);
}
void updateConfigSelector(InternalConfigSelector internalConfigSelector) {
InternalConfigSelector internalConfigSelector2 = this.configSelector.get();
this.configSelector.set(internalConfigSelector);
if (internalConfigSelector2 != ManagedChannelImpl.INITIAL_PENDING_SELECTOR || this.this$0.pendingCalls == null) {
return;
}
Iterator it = this.this$0.pendingCalls.iterator();
while (it.hasNext()) {
((PendingCall) it.next()).reprocess();
}
}
void onConfigError() {
if (this.configSelector.get() == ManagedChannelImpl.INITIAL_PENDING_SELECTOR) {
updateConfigSelector(null);
}
}
void shutdown() {
this.this$0.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.RealChannel.1RealChannelShutdown
final RealChannel this$1;
{
this.this$1 = this;
}
@Override // java.lang.Runnable
public final void run() {
if (this.this$1.this$0.pendingCalls == null) {
if (this.this$1.configSelector.get() == ManagedChannelImpl.INITIAL_PENDING_SELECTOR) {
this.this$1.configSelector.set(null);
}
this.this$1.this$0.uncommittedRetriableStreamsRegistry.onShutdown(ManagedChannelImpl.SHUTDOWN_STATUS);
}
}
});
}
void shutdownNow() {
this.this$0.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.RealChannel.1RealChannelShutdownNow
final RealChannel this$1;
{
this.this$1 = this;
}
@Override // java.lang.Runnable
public final void run() {
if (this.this$1.configSelector.get() == ManagedChannelImpl.INITIAL_PENDING_SELECTOR) {
this.this$1.configSelector.set(null);
}
if (this.this$1.this$0.pendingCalls != null) {
Iterator it = this.this$1.this$0.pendingCalls.iterator();
while (it.hasNext()) {
((PendingCall) it.next()).cancel("Channel is forcefully shutdown", (Throwable) null);
}
}
this.this$1.this$0.uncommittedRetriableStreamsRegistry.onShutdownNow(ManagedChannelImpl.SHUTDOWN_NOW_STATUS);
}
});
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public final class PendingCall<ReqT, RespT> extends DelayedClientCall<ReqT, RespT> {
final CallOptions callOptions;
final Context context;
final MethodDescriptor<ReqT, RespT> method;
final RealChannel this$1;
/* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
PendingCall(RealChannel realChannel, Context context, MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
super(realChannel.this$0.getCallExecutor(callOptions), realChannel.this$0.scheduledExecutor, callOptions.getDeadline());
this.this$1 = realChannel;
this.context = context;
this.method = methodDescriptor;
this.callOptions = callOptions;
}
final void reprocess() {
this.this$1.this$0.getCallExecutor(this.callOptions).execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.RealChannel.PendingCall.1
final PendingCall this$2;
{
this.this$2 = this;
}
@Override // java.lang.Runnable
public void run() {
Context attach = this.this$2.context.attach();
try {
ClientCall<ReqT, RespT> newClientCall = this.this$2.this$1.newClientCall(this.this$2.method, this.this$2.callOptions);
this.this$2.context.detach(attach);
this.this$2.setCall(newClientCall);
this.this$2.this$1.this$0.syncContext.execute(new PendingCallRemoval(this.this$2));
} catch (Throwable th) {
this.this$2.context.detach(attach);
throw th;
}
}
});
}
/* JADX INFO: Access modifiers changed from: protected */
@Override // io.grpc.internal.DelayedClientCall
public final void callCancelled() {
super.callCancelled();
this.this$1.this$0.syncContext.execute(new PendingCallRemoval(this));
}
/* loaded from: classes6.dex */
final class PendingCallRemoval implements Runnable {
final PendingCall this$2;
PendingCallRemoval(PendingCall pendingCall) {
this.this$2 = pendingCall;
}
@Override // java.lang.Runnable
public final void run() {
if (this.this$2.this$1.this$0.pendingCalls != null) {
this.this$2.this$1.this$0.pendingCalls.remove(this.this$2);
if (this.this$2.this$1.this$0.pendingCalls.isEmpty()) {
this.this$2.this$1.this$0.inUseStateAggregator.updateObjectInUse(this.this$2.this$1.this$0.pendingCallsInUseObject, false);
this.this$2.this$1.this$0.pendingCalls = null;
if (this.this$2.this$1.this$0.shutdown.get()) {
this.this$2.this$1.this$0.uncommittedRetriableStreamsRegistry.onShutdown(ManagedChannelImpl.SHUTDOWN_STATUS);
}
}
}
}
}
}
/* JADX INFO: Access modifiers changed from: private */
public <ReqT, RespT> ClientCall<ReqT, RespT> newClientCall(MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
InternalConfigSelector internalConfigSelector = this.configSelector.get();
if (internalConfigSelector == null) {
return this.clientCallImplChannel.newCall(methodDescriptor, callOptions);
}
if (internalConfigSelector instanceof ManagedChannelServiceConfig.ServiceConfigConvertedSelector) {
ManagedChannelServiceConfig.MethodInfo methodConfig = ((ManagedChannelServiceConfig.ServiceConfigConvertedSelector) internalConfigSelector).config.getMethodConfig(methodDescriptor);
if (methodConfig != null) {
callOptions = callOptions.withOption(ManagedChannelServiceConfig.MethodInfo.KEY, methodConfig);
}
return this.clientCallImplChannel.newCall(methodDescriptor, callOptions);
}
return new ConfigSelectingClientCall(internalConfigSelector, this.clientCallImplChannel, this.this$0.executor, methodDescriptor, callOptions);
}
@Override // io.grpc.Channel
public String authority() {
return this.authority;
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public static final class ConfigSelectingClientCall<ReqT, RespT> extends ForwardingClientCall<ReqT, RespT> {
private final Executor callExecutor;
private CallOptions callOptions;
private final Channel channel;
private final InternalConfigSelector configSelector;
private final Context context;
private ClientCall<ReqT, RespT> delegate;
private final MethodDescriptor<ReqT, RespT> method;
ConfigSelectingClientCall(InternalConfigSelector internalConfigSelector, Channel channel, Executor executor, MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
this.configSelector = internalConfigSelector;
this.channel = channel;
this.method = methodDescriptor;
executor = callOptions.getExecutor() != null ? callOptions.getExecutor() : executor;
this.callExecutor = executor;
this.callOptions = callOptions.withExecutor(executor);
this.context = Context.current();
}
@Override // io.grpc.ForwardingClientCall, io.grpc.ClientCall
public final void start(ClientCall.Listener<RespT> listener, Metadata metadata) {
InternalConfigSelector.Result selectConfig = this.configSelector.selectConfig(new PickSubchannelArgsImpl(this.method, metadata, this.callOptions));
Status status = selectConfig.getStatus();
if (!status.isOk()) {
executeCloseObserverInContext(listener, status);
this.delegate = ManagedChannelImpl.NOOP_CALL;
return;
}
ClientInterceptor interceptor = selectConfig.getInterceptor();
ManagedChannelServiceConfig.MethodInfo methodConfig = ((ManagedChannelServiceConfig) selectConfig.getConfig()).getMethodConfig(this.method);
if (methodConfig != null) {
this.callOptions = this.callOptions.withOption(ManagedChannelServiceConfig.MethodInfo.KEY, methodConfig);
}
if (interceptor != null) {
this.delegate = interceptor.interceptCall(this.method, this.callOptions, this.channel);
} else {
this.delegate = this.channel.newCall(this.method, this.callOptions);
}
this.delegate.start(listener, metadata);
}
private void executeCloseObserverInContext(ClientCall.Listener<RespT> listener, Status status) {
this.callExecutor.execute(new ContextRunnable(this, listener, status) { // from class: io.grpc.internal.ManagedChannelImpl.ConfigSelectingClientCall.1CloseInContext
final ConfigSelectingClientCall this$0;
final ClientCall.Listener val$observer;
final Status val$status;
/* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
{
super(this.context);
this.this$0 = this;
this.val$observer = listener;
this.val$status = status;
}
@Override // io.grpc.internal.ContextRunnable
public void runInContext() {
this.val$observer.onClose(this.val$status, new Metadata());
}
});
}
@Override // io.grpc.ForwardingClientCall, io.grpc.PartialForwardingClientCall, io.grpc.ClientCall
public final void cancel(String str, Throwable th) {
ClientCall<ReqT, RespT> clientCall = this.delegate;
if (clientCall != null) {
clientCall.cancel(str, th);
}
}
@Override // io.grpc.ForwardingClientCall, io.grpc.PartialForwardingClientCall
public final ClientCall<ReqT, RespT> delegate() {
return this.delegate;
}
}
/* JADX INFO: Access modifiers changed from: private */
public void maybeTerminateChannel() {
if (!this.terminated && this.shutdown.get() && this.subchannels.isEmpty() && this.oobChannels.isEmpty()) {
this.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Terminated");
this.channelz.removeRootChannel(this);
this.executorPool.returnObject(this.executor);
this.balancerRpcExecutorHolder.release();
this.offloadExecutorHolder.release();
this.transportFactory.close();
this.terminated = true;
this.terminatedLatch.countDown();
}
}
/* JADX INFO: Access modifiers changed from: private */
public void handleInternalSubchannelState(ConnectivityStateInfo connectivityStateInfo) {
if (connectivityStateInfo.getState() == ConnectivityState.TRANSIENT_FAILURE || connectivityStateInfo.getState() == ConnectivityState.IDLE) {
refreshAndResetNameResolution();
}
}
@Override // io.grpc.ManagedChannel
public final ConnectivityState getState(boolean z) {
ConnectivityState state = this.channelStateManager.getState();
if (z && state == ConnectivityState.IDLE) {
this.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.1RequestConnection
final ManagedChannelImpl this$0;
{
this.this$0 = this;
}
@Override // java.lang.Runnable
public final void run() {
this.this$0.exitIdleMode();
if (this.this$0.subchannelPicker != null) {
this.this$0.subchannelPicker.requestConnection();
}
if (this.this$0.lbHelper != null) {
this.this$0.lbHelper.lb.requestConnection();
}
}
});
}
return state;
}
@Override // io.grpc.ManagedChannel
public final void notifyWhenStateChanged(ConnectivityState connectivityState, Runnable runnable) {
this.syncContext.execute(new Runnable(this, runnable, connectivityState) { // from class: io.grpc.internal.ManagedChannelImpl.1NotifyStateChanged
final ManagedChannelImpl this$0;
final Runnable val$callback;
final ConnectivityState val$source;
{
this.this$0 = this;
this.val$callback = runnable;
this.val$source = connectivityState;
}
@Override // java.lang.Runnable
public final void run() {
this.this$0.channelStateManager.notifyWhenStateChanged(this.val$callback, this.this$0.executor, this.val$source);
}
});
}
@Override // io.grpc.ManagedChannel
public final void resetConnectBackoff() {
this.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.1ResetConnectBackoff
final ManagedChannelImpl this$0;
{
this.this$0 = this;
}
@Override // java.lang.Runnable
public final void run() {
if (this.this$0.shutdown.get()) {
return;
}
if (this.this$0.scheduledNameResolverRefresh != null && this.this$0.scheduledNameResolverRefresh.isPending()) {
Preconditions.checkState(this.this$0.nameResolverStarted, "name resolver must be started");
this.this$0.refreshAndResetNameResolution();
}
Iterator it = this.this$0.subchannels.iterator();
while (it.hasNext()) {
((InternalSubchannel) it.next()).resetConnectBackoff();
}
Iterator it2 = this.this$0.oobChannels.iterator();
while (it2.hasNext()) {
((OobChannel) it2.next()).resetConnectBackoff();
}
}
});
}
@Override // io.grpc.ManagedChannel
public final void enterIdle() {
this.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.1PrepareToLoseNetworkRunnable
final ManagedChannelImpl this$0;
{
this.this$0 = this;
}
@Override // java.lang.Runnable
public final void run() {
if (this.this$0.shutdown.get() || this.this$0.lbHelper == null) {
return;
}
this.this$0.cancelIdleTimer(false);
this.this$0.enterIdleMode();
}
});
}
/* loaded from: classes6.dex */
final class UncommittedRetriableStreamsRegistry {
final Object lock;
Status shutdownStatus;
final ManagedChannelImpl this$0;
Collection<ClientStream> uncommittedRetriableStreams;
private UncommittedRetriableStreamsRegistry(ManagedChannelImpl managedChannelImpl) {
this.this$0 = managedChannelImpl;
this.lock = new Object();
this.uncommittedRetriableStreams = new HashSet();
}
final void onShutdown(Status status) {
synchronized (this.lock) {
if (this.shutdownStatus != null) {
return;
}
this.shutdownStatus = status;
boolean isEmpty = this.uncommittedRetriableStreams.isEmpty();
if (isEmpty) {
this.this$0.delayedTransport.shutdown(status);
}
}
}
final void onShutdownNow(Status status) {
ArrayList arrayList;
onShutdown(status);
synchronized (this.lock) {
arrayList = new ArrayList(this.uncommittedRetriableStreams);
}
Iterator it = arrayList.iterator();
while (it.hasNext()) {
((ClientStream) it.next()).cancel(status);
}
this.this$0.delayedTransport.shutdownNow(status);
}
final Status add(RetriableStream<?> retriableStream) {
synchronized (this.lock) {
Status status = this.shutdownStatus;
if (status != null) {
return status;
}
this.uncommittedRetriableStreams.add(retriableStream);
return null;
}
}
final void remove(RetriableStream<?> retriableStream) {
Status status;
synchronized (this.lock) {
this.uncommittedRetriableStreams.remove(retriableStream);
if (this.uncommittedRetriableStreams.isEmpty()) {
status = this.shutdownStatus;
this.uncommittedRetriableStreams = new HashSet();
} else {
status = null;
}
}
if (status != null) {
this.this$0.delayedTransport.shutdown(status);
}
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public final class LbHelperImpl extends LoadBalancer.Helper {
boolean ignoreRefreshNsCheck;
AutoConfiguredLoadBalancerFactory.AutoConfiguredLoadBalancer lb;
boolean nsRefreshedByLb;
final ManagedChannelImpl this$0;
private LbHelperImpl(ManagedChannelImpl managedChannelImpl) {
this.this$0 = managedChannelImpl;
}
@Override // io.grpc.LoadBalancer.Helper
public final AbstractSubchannel createSubchannel(LoadBalancer.CreateSubchannelArgs createSubchannelArgs) {
this.this$0.syncContext.throwIfNotInThisSynchronizationContext();
Preconditions.checkState(!this.this$0.terminating, "Channel is being terminated");
return new SubchannelImpl(this.this$0, createSubchannelArgs, this);
}
@Override // io.grpc.LoadBalancer.Helper
public final void updateBalancingState(ConnectivityState connectivityState, LoadBalancer.SubchannelPicker subchannelPicker) {
this.this$0.syncContext.throwIfNotInThisSynchronizationContext();
Preconditions.checkNotNull(connectivityState, "newState");
Preconditions.checkNotNull(subchannelPicker, "newPicker");
this.this$0.syncContext.execute(new Runnable(this, subchannelPicker, connectivityState) { // from class: io.grpc.internal.ManagedChannelImpl.LbHelperImpl.1UpdateBalancingState
final LbHelperImpl this$1;
final LoadBalancer.SubchannelPicker val$newPicker;
final ConnectivityState val$newState;
{
this.this$1 = this;
this.val$newPicker = subchannelPicker;
this.val$newState = connectivityState;
}
@Override // java.lang.Runnable
public final void run() {
LbHelperImpl lbHelperImpl = this.this$1;
if (lbHelperImpl != lbHelperImpl.this$0.lbHelper) {
return;
}
this.this$1.this$0.updateSubchannelPicker(this.val$newPicker);
if (this.val$newState != ConnectivityState.SHUTDOWN) {
this.this$1.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Entering {0} state with picker: {1}", this.val$newState, this.val$newPicker);
this.this$1.this$0.channelStateManager.gotoState(this.val$newState);
}
}
});
}
@Override // io.grpc.LoadBalancer.Helper
public final void refreshNameResolution() {
this.this$0.syncContext.throwIfNotInThisSynchronizationContext();
this.nsRefreshedByLb = true;
this.this$0.syncContext.execute(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.LbHelperImpl.1LoadBalancerRefreshNameResolution
final LbHelperImpl this$1;
{
this.this$1 = this;
}
@Override // java.lang.Runnable
public final void run() {
this.this$1.this$0.refreshAndResetNameResolution();
}
});
}
@Override // io.grpc.LoadBalancer.Helper
public final ManagedChannel createOobChannel(EquivalentAddressGroup equivalentAddressGroup, String str) {
return createOobChannel(Collections.singletonList(equivalentAddressGroup), str);
}
@Override // io.grpc.LoadBalancer.Helper
public final ManagedChannel createOobChannel(List<EquivalentAddressGroup> list, String str) {
Preconditions.checkState(!this.this$0.terminated, "Channel is terminated");
long currentTimeNanos = this.this$0.timeProvider.currentTimeNanos();
InternalLogId allocate = InternalLogId.allocate("OobChannel", (String) null);
InternalLogId allocate2 = InternalLogId.allocate("Subchannel-OOB", str);
ChannelTracer channelTracer = new ChannelTracer(allocate, this.this$0.maxTraceEvents, currentTimeNanos, "OobChannel for ".concat(String.valueOf(list)));
OobChannel oobChannel = new OobChannel(str, this.this$0.balancerRpcExecutorPool, this.this$0.oobTransportFactory.getScheduledExecutorService(), this.this$0.syncContext, this.this$0.callTracerFactory.create(), channelTracer, this.this$0.channelz, this.this$0.timeProvider);
this.this$0.channelTracer.reportEvent(new InternalChannelz.ChannelTrace.Event.Builder().setDescription("Child OobChannel created").setSeverity(InternalChannelz.ChannelTrace.Event.Severity.CT_INFO).setTimestampNanos(currentTimeNanos).setChannelRef(oobChannel).build());
ChannelTracer channelTracer2 = new ChannelTracer(allocate2, this.this$0.maxTraceEvents, currentTimeNanos, "Subchannel for ".concat(String.valueOf(list)));
InternalSubchannel internalSubchannel = new InternalSubchannel(list, str, this.this$0.userAgent, this.this$0.backoffPolicyProvider, this.this$0.oobTransportFactory, this.this$0.oobTransportFactory.getScheduledExecutorService(), this.this$0.stopwatchSupplier, this.this$0.syncContext, new InternalSubchannel.Callback(this, oobChannel) { // from class: io.grpc.internal.ManagedChannelImpl.LbHelperImpl.1ManagedOobChannelCallback
final LbHelperImpl this$1;
final OobChannel val$oobChannel;
{
this.this$1 = this;
this.val$oobChannel = oobChannel;
}
@Override // io.grpc.internal.InternalSubchannel.Callback
final void onTerminated(InternalSubchannel internalSubchannel2) {
this.this$1.this$0.oobChannels.remove(this.val$oobChannel);
this.this$1.this$0.channelz.removeSubchannel(internalSubchannel2);
this.val$oobChannel.handleSubchannelTerminated();
this.this$1.this$0.maybeTerminateChannel();
}
@Override // io.grpc.internal.InternalSubchannel.Callback
final void onStateChange(InternalSubchannel internalSubchannel2, ConnectivityStateInfo connectivityStateInfo) {
this.this$1.this$0.handleInternalSubchannelState(connectivityStateInfo);
this.val$oobChannel.handleSubchannelStateChange(connectivityStateInfo);
}
}, this.this$0.channelz, this.this$0.callTracerFactory.create(), channelTracer2, allocate2, new ChannelLoggerImpl(channelTracer2, this.this$0.timeProvider));
channelTracer.reportEvent(new InternalChannelz.ChannelTrace.Event.Builder().setDescription("Child Subchannel created").setSeverity(InternalChannelz.ChannelTrace.Event.Severity.CT_INFO).setTimestampNanos(currentTimeNanos).setSubchannelRef(internalSubchannel).build());
this.this$0.channelz.addSubchannel(oobChannel);
this.this$0.channelz.addSubchannel(internalSubchannel);
oobChannel.setSubchannel(internalSubchannel);
this.this$0.syncContext.execute(new Runnable(this, oobChannel) { // from class: io.grpc.internal.ManagedChannelImpl.LbHelperImpl.1AddOobChannel
final LbHelperImpl this$1;
final OobChannel val$oobChannel;
{
this.this$1 = this;
this.val$oobChannel = oobChannel;
}
@Override // java.lang.Runnable
public final void run() {
if (this.this$1.this$0.terminating) {
this.val$oobChannel.shutdown();
}
if (this.this$1.this$0.terminated) {
return;
}
this.this$1.this$0.oobChannels.add(this.val$oobChannel);
}
});
return oobChannel;
}
/* JADX WARN: Type inference failed for: r2v2, types: [io.grpc.ManagedChannelBuilder, io.grpc.ManagedChannelBuilder<?>] */
@Override // io.grpc.LoadBalancer.Helper
@Deprecated
public final ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String str) {
return createResolvingOobChannelBuilder(str, new DefaultChannelCreds(this)).overrideAuthority(getAuthority());
}
@Override // io.grpc.LoadBalancer.Helper
public final ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String str, ChannelCredentials channelCredentials) {
Preconditions.checkNotNull(channelCredentials, "channelCreds");
Preconditions.checkState(!this.this$0.terminated, "Channel is terminated");
return new ForwardingChannelBuilder<C1ResolvingOobChannelBuilder>(this, channelCredentials, str) { // from class: io.grpc.internal.ManagedChannelImpl.LbHelperImpl.1ResolvingOobChannelBuilder
final ManagedChannelBuilder<?> delegate;
final LbHelperImpl this$1;
final ChannelCredentials val$channelCreds;
final String val$target;
{
CallCredentials callCredentials;
ClientTransportFactory clientTransportFactory;
this.this$1 = this;
this.val$channelCreds = channelCredentials;
this.val$target = str;
if (channelCredentials instanceof DefaultChannelCreds) {
clientTransportFactory = this.this$0.originalTransportFactory;
callCredentials = null;
} else {
ClientTransportFactory.SwapChannelCredentialsResult swapChannelCredentials = this.this$0.originalTransportFactory.swapChannelCredentials(channelCredentials);
if (swapChannelCredentials == null) {
this.delegate = Grpc.newChannelBuilder(str, channelCredentials);
return;
} else {
ClientTransportFactory clientTransportFactory2 = swapChannelCredentials.transportFactory;
callCredentials = swapChannelCredentials.callCredentials;
clientTransportFactory = clientTransportFactory2;
}
}
this.delegate = new ManagedChannelImplBuilder(str, channelCredentials, callCredentials, new ManagedChannelImplBuilder.ClientTransportFactoryBuilder(this, this, clientTransportFactory) { // from class: io.grpc.internal.ManagedChannelImpl.LbHelperImpl.1ResolvingOobChannelBuilder.1
final C1ResolvingOobChannelBuilder this$2;
final LbHelperImpl val$this$1;
final ClientTransportFactory val$transportFactory;
{
this.this$2 = this;
this.val$this$1 = this;
this.val$transportFactory = clientTransportFactory;
}
@Override // io.grpc.internal.ManagedChannelImplBuilder.ClientTransportFactoryBuilder
public ClientTransportFactory buildClientTransportFactory() {
return this.val$transportFactory;
}
}, new ManagedChannelImplBuilder.FixedPortProvider(this.this$0.nameResolverArgs.getDefaultPort()));
}
@Override // io.grpc.ForwardingChannelBuilder
public final ManagedChannelBuilder<?> delegate() {
return this.delegate;
}
}.nameResolverFactory(this.this$0.nameResolverFactory).executor(this.this$0.executor).offloadExecutor(this.this$0.offloadExecutorHolder.getExecutor()).maxTraceEvents(this.this$0.maxTraceEvents).proxyDetector(this.this$0.nameResolverArgs.getProxyDetector()).userAgent(this.this$0.userAgent);
}
@Override // io.grpc.LoadBalancer.Helper
public final ChannelCredentials getUnsafeChannelCredentials() {
if (this.this$0.originalChannelCreds != null) {
return this.this$0.originalChannelCreds;
}
return new DefaultChannelCreds(this);
}
@Override // io.grpc.LoadBalancer.Helper
public final void updateOobChannelAddresses(ManagedChannel managedChannel, EquivalentAddressGroup equivalentAddressGroup) {
updateOobChannelAddresses(managedChannel, Collections.singletonList(equivalentAddressGroup));
}
@Override // io.grpc.LoadBalancer.Helper
public final void updateOobChannelAddresses(ManagedChannel managedChannel, List<EquivalentAddressGroup> list) {
Preconditions.checkArgument(managedChannel instanceof OobChannel, "channel must have been returned from createOobChannel");
((OobChannel) managedChannel).updateAddresses(list);
}
@Override // io.grpc.LoadBalancer.Helper
public final String getAuthority() {
return this.this$0.authority();
}
@Override // io.grpc.LoadBalancer.Helper
public final SynchronizationContext getSynchronizationContext() {
return this.this$0.syncContext;
}
@Override // io.grpc.LoadBalancer.Helper
public final ScheduledExecutorService getScheduledExecutorService() {
return this.this$0.scheduledExecutor;
}
@Override // io.grpc.LoadBalancer.Helper
public final ChannelLogger getChannelLogger() {
return this.this$0.channelLogger;
}
@Override // io.grpc.LoadBalancer.Helper
public final NameResolver.Args getNameResolverArgs() {
return this.this$0.nameResolverArgs;
}
@Override // io.grpc.LoadBalancer.Helper
public final NameResolverRegistry getNameResolverRegistry() {
return this.this$0.nameResolverRegistry;
}
/* loaded from: classes6.dex */
final class DefaultChannelCreds extends ChannelCredentials {
final LbHelperImpl this$1;
@Override // io.grpc.ChannelCredentials
public final ChannelCredentials withoutBearerTokens() {
return this;
}
DefaultChannelCreds(LbHelperImpl lbHelperImpl) {
this.this$1 = lbHelperImpl;
}
}
@Override // io.grpc.LoadBalancer.Helper
public final void ignoreRefreshNameResolutionCheck() {
this.ignoreRefreshNsCheck = true;
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public final class NameResolverListener extends NameResolver.Listener2 {
final LbHelperImpl helper;
final NameResolver resolver;
final ManagedChannelImpl this$0;
NameResolverListener(ManagedChannelImpl managedChannelImpl, LbHelperImpl lbHelperImpl, NameResolver nameResolver) {
this.this$0 = managedChannelImpl;
this.helper = (LbHelperImpl) Preconditions.checkNotNull(lbHelperImpl, "helperImpl");
this.resolver = (NameResolver) Preconditions.checkNotNull(nameResolver, "resolver");
}
@Override // io.grpc.NameResolver.Listener2
public final void onResult(NameResolver.ResolutionResult resolutionResult) {
this.this$0.syncContext.execute(new Runnable(this, resolutionResult) { // from class: io.grpc.internal.ManagedChannelImpl.NameResolverListener.1NamesResolved
final NameResolverListener this$1;
final NameResolver.ResolutionResult val$resolutionResult;
{
this.this$1 = this;
this.val$resolutionResult = resolutionResult;
}
@Override // java.lang.Runnable
public final void run() {
ManagedChannelServiceConfig managedChannelServiceConfig;
List<EquivalentAddressGroup> addresses = this.val$resolutionResult.getAddresses();
this.this$1.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.DEBUG, "Resolved address: {0}, config={1}", addresses, this.val$resolutionResult.getAttributes());
if (this.this$1.this$0.lastResolutionState != ResolutionState.SUCCESS) {
this.this$1.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Address resolved: {0}", addresses);
this.this$1.this$0.lastResolutionState = ResolutionState.SUCCESS;
}
this.this$1.this$0.nameResolverBackoffPolicy = null;
NameResolver.ConfigOrError serviceConfig = this.val$resolutionResult.getServiceConfig();
InternalConfigSelector internalConfigSelector = (InternalConfigSelector) this.val$resolutionResult.getAttributes().get(InternalConfigSelector.KEY);
ManagedChannelServiceConfig managedChannelServiceConfig2 = (serviceConfig == null || serviceConfig.getConfig() == null) ? null : (ManagedChannelServiceConfig) serviceConfig.getConfig();
Status error = serviceConfig != null ? serviceConfig.getError() : null;
if (!this.this$1.this$0.lookUpServiceConfig) {
if (managedChannelServiceConfig2 != null) {
this.this$1.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Service config from name resolver discarded by channel settings");
}
if (this.this$1.this$0.defaultServiceConfig != null) {
managedChannelServiceConfig = this.this$1.this$0.defaultServiceConfig;
} else {
managedChannelServiceConfig = ManagedChannelImpl.EMPTY_SERVICE_CONFIG;
}
if (internalConfigSelector != null) {
this.this$1.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Config selector from name resolver discarded by channel settings");
}
this.this$1.this$0.realChannel.updateConfigSelector(managedChannelServiceConfig.getDefaultConfigSelector());
} else {
if (managedChannelServiceConfig2 != null) {
if (internalConfigSelector != null) {
this.this$1.this$0.realChannel.updateConfigSelector(internalConfigSelector);
if (managedChannelServiceConfig2.getDefaultConfigSelector() != null) {
this.this$1.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.DEBUG, "Method configs in service config will be discarded due to presence ofconfig-selector");
}
} else {
this.this$1.this$0.realChannel.updateConfigSelector(managedChannelServiceConfig2.getDefaultConfigSelector());
}
} else if (this.this$1.this$0.defaultServiceConfig != null) {
managedChannelServiceConfig2 = this.this$1.this$0.defaultServiceConfig;
this.this$1.this$0.realChannel.updateConfigSelector(managedChannelServiceConfig2.getDefaultConfigSelector());
this.this$1.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Received no service config, using default service config");
} else if (error != null) {
if (!this.this$1.this$0.serviceConfigUpdated) {
this.this$1.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.INFO, "Fallback to error due to invalid first service config without default config");
this.this$1.onError(serviceConfig.getError());
return;
}
managedChannelServiceConfig2 = this.this$1.this$0.lastServiceConfig;
} else {
managedChannelServiceConfig2 = ManagedChannelImpl.EMPTY_SERVICE_CONFIG;
this.this$1.this$0.realChannel.updateConfigSelector(null);
}
if (!managedChannelServiceConfig2.equals(this.this$1.this$0.lastServiceConfig)) {
ChannelLogger channelLogger = this.this$1.this$0.channelLogger;
ChannelLogger.ChannelLogLevel channelLogLevel = ChannelLogger.ChannelLogLevel.INFO;
Object[] objArr = new Object[1];
objArr[0] = managedChannelServiceConfig2 == ManagedChannelImpl.EMPTY_SERVICE_CONFIG ? " to empty" : "";
channelLogger.log(channelLogLevel, "Service config changed{0}", objArr);
this.this$1.this$0.lastServiceConfig = managedChannelServiceConfig2;
}
try {
this.this$1.this$0.serviceConfigUpdated = true;
} catch (RuntimeException e) {
Logger logger = ManagedChannelImpl.logger;
Level level = Level.WARNING;
StringBuilder sb = new StringBuilder("[");
sb.append(this.this$1.this$0.getLogId());
sb.append("] Unexpected exception from parsing service config");
logger.log(level, sb.toString(), (Throwable) e);
}
managedChannelServiceConfig = managedChannelServiceConfig2;
}
Attributes attributes = this.val$resolutionResult.getAttributes();
if (this.this$1.helper == this.this$1.this$0.lbHelper) {
Attributes.Builder discard = attributes.toBuilder().discard(InternalConfigSelector.KEY);
Map<String, ?> healthCheckingConfig = managedChannelServiceConfig.getHealthCheckingConfig();
if (healthCheckingConfig != null) {
discard.set(LoadBalancer.ATTR_HEALTH_CHECKING_CONFIG, healthCheckingConfig).build();
}
Status tryHandleResolvedAddresses = this.this$1.helper.lb.tryHandleResolvedAddresses(LoadBalancer.ResolvedAddresses.newBuilder().setAddresses(addresses).setAttributes(discard.build()).setLoadBalancingPolicyConfig(managedChannelServiceConfig.getLoadBalancingConfig()).build());
if (tryHandleResolvedAddresses.isOk()) {
return;
}
NameResolverListener nameResolverListener = this.this$1;
StringBuilder sb2 = new StringBuilder();
sb2.append(this.this$1.resolver);
sb2.append(" was used");
nameResolverListener.handleErrorInSyncContext(tryHandleResolvedAddresses.augmentDescription(sb2.toString()));
}
}
});
}
@Override // io.grpc.NameResolver.Listener2, io.grpc.NameResolver.Listener
public final void onError(Status status) {
Preconditions.checkArgument(!status.isOk(), "the error status must not be OK");
this.this$0.syncContext.execute(new Runnable(this, status) { // from class: io.grpc.internal.ManagedChannelImpl.NameResolverListener.1NameResolverErrorHandler
final NameResolverListener this$1;
final Status val$error;
{
this.this$1 = this;
this.val$error = status;
}
@Override // java.lang.Runnable
public final void run() {
this.this$1.handleErrorInSyncContext(this.val$error);
}
});
}
/* JADX INFO: Access modifiers changed from: private */
public void handleErrorInSyncContext(Status status) {
ManagedChannelImpl.logger.log(Level.WARNING, "[{0}] Failed to resolve name. status={1}", new Object[]{this.this$0.getLogId(), status});
this.this$0.realChannel.onConfigError();
if (this.this$0.lastResolutionState != ResolutionState.ERROR) {
this.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.WARNING, "Failed to resolve name: {0}", status);
this.this$0.lastResolutionState = ResolutionState.ERROR;
}
if (this.helper != this.this$0.lbHelper) {
return;
}
this.helper.lb.handleNameResolutionError(status);
scheduleExponentialBackOffInSyncContext();
}
private void scheduleExponentialBackOffInSyncContext() {
if (this.this$0.scheduledNameResolverRefresh == null || !this.this$0.scheduledNameResolverRefresh.isPending()) {
if (this.this$0.nameResolverBackoffPolicy == null) {
ManagedChannelImpl managedChannelImpl = this.this$0;
managedChannelImpl.nameResolverBackoffPolicy = managedChannelImpl.backoffPolicyProvider.get();
}
long nextBackoffNanos = this.this$0.nameResolverBackoffPolicy.nextBackoffNanos();
this.this$0.channelLogger.log(ChannelLogger.ChannelLogLevel.DEBUG, "Scheduling DNS resolution backoff for {0} ns", Long.valueOf(nextBackoffNanos));
ManagedChannelImpl managedChannelImpl2 = this.this$0;
managedChannelImpl2.scheduledNameResolverRefresh = managedChannelImpl2.syncContext.schedule(new DelayedNameResolverRefresh(this.this$0), nextBackoffNanos, TimeUnit.NANOSECONDS, this.this$0.transportFactory.getScheduledExecutorService());
}
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public final class SubchannelImpl extends AbstractSubchannel {
List<EquivalentAddressGroup> addressGroups;
final LoadBalancer.CreateSubchannelArgs args;
SynchronizationContext.ScheduledHandle delayedShutdownTask;
final LbHelperImpl helper;
boolean shutdown;
boolean started;
InternalSubchannel subchannel;
final InternalLogId subchannelLogId;
final ChannelLoggerImpl subchannelLogger;
final ChannelTracer subchannelTracer;
final ManagedChannelImpl this$0;
SubchannelImpl(ManagedChannelImpl managedChannelImpl, LoadBalancer.CreateSubchannelArgs createSubchannelArgs, LbHelperImpl lbHelperImpl) {
this.this$0 = managedChannelImpl;
this.addressGroups = createSubchannelArgs.getAddresses();
if (managedChannelImpl.authorityOverride != null) {
createSubchannelArgs = createSubchannelArgs.toBuilder().setAddresses(stripOverrideAuthorityAttributes(createSubchannelArgs.getAddresses())).build();
}
this.args = (LoadBalancer.CreateSubchannelArgs) Preconditions.checkNotNull(createSubchannelArgs, "args");
this.helper = (LbHelperImpl) Preconditions.checkNotNull(lbHelperImpl, "helper");
InternalLogId allocate = InternalLogId.allocate("Subchannel", managedChannelImpl.authority());
this.subchannelLogId = allocate;
int i = managedChannelImpl.maxTraceEvents;
long currentTimeNanos = managedChannelImpl.timeProvider.currentTimeNanos();
StringBuilder sb = new StringBuilder("Subchannel for ");
sb.append(createSubchannelArgs.getAddresses());
ChannelTracer channelTracer = new ChannelTracer(allocate, i, currentTimeNanos, sb.toString());
this.subchannelTracer = channelTracer;
this.subchannelLogger = new ChannelLoggerImpl(channelTracer, managedChannelImpl.timeProvider);
}
@Override // io.grpc.LoadBalancer.Subchannel
public final void start(LoadBalancer.SubchannelStateListener subchannelStateListener) {
this.this$0.syncContext.throwIfNotInThisSynchronizationContext();
Preconditions.checkState(!this.started, "already started");
Preconditions.checkState(!this.shutdown, "already shutdown");
Preconditions.checkState(!this.this$0.terminating, "Channel is being terminated");
this.started = true;
InternalSubchannel internalSubchannel = new InternalSubchannel(this.args.getAddresses(), this.this$0.authority(), this.this$0.userAgent, this.this$0.backoffPolicyProvider, this.this$0.transportFactory, this.this$0.transportFactory.getScheduledExecutorService(), this.this$0.stopwatchSupplier, this.this$0.syncContext, new InternalSubchannel.Callback(this, subchannelStateListener) { // from class: io.grpc.internal.ManagedChannelImpl.SubchannelImpl.1ManagedInternalSubchannelCallback
final SubchannelImpl this$1;
final LoadBalancer.SubchannelStateListener val$listener;
{
this.this$1 = this;
this.val$listener = subchannelStateListener;
}
@Override // io.grpc.internal.InternalSubchannel.Callback
final void onTerminated(InternalSubchannel internalSubchannel2) {
this.this$1.this$0.subchannels.remove(internalSubchannel2);
this.this$1.this$0.channelz.removeSubchannel(internalSubchannel2);
this.this$1.this$0.maybeTerminateChannel();
}
@Override // io.grpc.internal.InternalSubchannel.Callback
final void onStateChange(InternalSubchannel internalSubchannel2, ConnectivityStateInfo connectivityStateInfo) {
Preconditions.checkState(this.val$listener != null, "listener is null");
this.val$listener.onSubchannelState(connectivityStateInfo);
if ((connectivityStateInfo.getState() != ConnectivityState.TRANSIENT_FAILURE && connectivityStateInfo.getState() != ConnectivityState.IDLE) || this.this$1.helper.ignoreRefreshNsCheck || this.this$1.helper.nsRefreshedByLb) {
return;
}
ManagedChannelImpl.logger.log(Level.WARNING, "LoadBalancer should call Helper.refreshNameResolution() to refresh name resolution if subchannel state becomes TRANSIENT_FAILURE or IDLE. This will no longer happen automatically in the future releases");
this.this$1.this$0.refreshAndResetNameResolution();
this.this$1.helper.nsRefreshedByLb = true;
}
@Override // io.grpc.internal.InternalSubchannel.Callback
final void onInUse(InternalSubchannel internalSubchannel2) {
this.this$1.this$0.inUseStateAggregator.updateObjectInUse(internalSubchannel2, true);
}
@Override // io.grpc.internal.InternalSubchannel.Callback
final void onNotInUse(InternalSubchannel internalSubchannel2) {
this.this$1.this$0.inUseStateAggregator.updateObjectInUse(internalSubchannel2, false);
}
}, this.this$0.channelz, this.this$0.callTracerFactory.create(), this.subchannelTracer, this.subchannelLogId, this.subchannelLogger);
this.this$0.channelTracer.reportEvent(new InternalChannelz.ChannelTrace.Event.Builder().setDescription("Child Subchannel started").setSeverity(InternalChannelz.ChannelTrace.Event.Severity.CT_INFO).setTimestampNanos(this.this$0.timeProvider.currentTimeNanos()).setSubchannelRef(internalSubchannel).build());
this.subchannel = internalSubchannel;
this.this$0.channelz.addSubchannel(internalSubchannel);
this.this$0.subchannels.add(internalSubchannel);
}
@Override // io.grpc.internal.AbstractSubchannel
final InternalInstrumented<InternalChannelz.ChannelStats> getInstrumentedInternalSubchannel() {
Preconditions.checkState(this.started, "not started");
return this.subchannel;
}
@Override // io.grpc.LoadBalancer.Subchannel
public final void shutdown() {
SynchronizationContext.ScheduledHandle scheduledHandle;
this.this$0.syncContext.throwIfNotInThisSynchronizationContext();
if (this.subchannel == null) {
this.shutdown = true;
return;
}
if (!this.shutdown) {
this.shutdown = true;
} else {
if (!this.this$0.terminating || (scheduledHandle = this.delayedShutdownTask) == null) {
return;
}
scheduledHandle.cancel();
this.delayedShutdownTask = null;
}
if (!this.this$0.terminating) {
this.delayedShutdownTask = this.this$0.syncContext.schedule(new LogExceptionRunnable(new Runnable(this) { // from class: io.grpc.internal.ManagedChannelImpl.SubchannelImpl.1ShutdownSubchannel
final SubchannelImpl this$1;
{
this.this$1 = this;
}
@Override // java.lang.Runnable
public final void run() {
this.this$1.subchannel.shutdown(ManagedChannelImpl.SUBCHANNEL_SHUTDOWN_STATUS);
}
}), ManagedChannelImpl.SUBCHANNEL_SHUTDOWN_DELAY_SECONDS, TimeUnit.SECONDS, this.this$0.transportFactory.getScheduledExecutorService());
} else {
this.subchannel.shutdown(ManagedChannelImpl.SHUTDOWN_STATUS);
}
}
@Override // io.grpc.LoadBalancer.Subchannel
public final void requestConnection() {
this.this$0.syncContext.throwIfNotInThisSynchronizationContext();
Preconditions.checkState(this.started, "not started");
this.subchannel.obtainActiveTransport();
}
@Override // io.grpc.LoadBalancer.Subchannel
public final List<EquivalentAddressGroup> getAllAddresses() {
this.this$0.syncContext.throwIfNotInThisSynchronizationContext();
Preconditions.checkState(this.started, "not started");
return this.addressGroups;
}
@Override // io.grpc.LoadBalancer.Subchannel
public final Attributes getAttributes() {
return this.args.getAttributes();
}
public final String toString() {
return this.subchannelLogId.toString();
}
@Override // io.grpc.LoadBalancer.Subchannel
public final Channel asChannel() {
Preconditions.checkState(this.started, "not started");
return new SubchannelChannel(this.subchannel, this.this$0.balancerRpcExecutorHolder.getExecutor(), this.this$0.transportFactory.getScheduledExecutorService(), this.this$0.callTracerFactory.create(), new AtomicReference(null));
}
@Override // io.grpc.LoadBalancer.Subchannel
public final Object getInternalSubchannel() {
Preconditions.checkState(this.started, "Subchannel is not started");
return this.subchannel;
}
@Override // io.grpc.LoadBalancer.Subchannel
public final void updateAddresses(List<EquivalentAddressGroup> list) {
this.this$0.syncContext.throwIfNotInThisSynchronizationContext();
this.addressGroups = list;
if (this.this$0.authorityOverride != null) {
list = stripOverrideAuthorityAttributes(list);
}
this.subchannel.updateAddresses(list);
}
private List<EquivalentAddressGroup> stripOverrideAuthorityAttributes(List<EquivalentAddressGroup> list) {
ArrayList arrayList = new ArrayList();
for (EquivalentAddressGroup equivalentAddressGroup : list) {
arrayList.add(new EquivalentAddressGroup(equivalentAddressGroup.getAddresses(), equivalentAddressGroup.getAttributes().toBuilder().discard(EquivalentAddressGroup.ATTR_AUTHORITY_OVERRIDE).build()));
}
return Collections.unmodifiableList(arrayList);
}
@Override // io.grpc.LoadBalancer.Subchannel
public final ChannelLogger getChannelLogger() {
return this.subchannelLogger;
}
}
public final String toString() {
return MoreObjects.toStringHelper(this).add("logId", this.logId.getId()).add("target", this.target).toString();
}
/* loaded from: classes6.dex */
final class DelayedTransportListener implements ManagedClientTransport.Listener {
final ManagedChannelImpl this$0;
@Override // io.grpc.internal.ManagedClientTransport.Listener
public final void transportReady() {
}
private DelayedTransportListener(ManagedChannelImpl managedChannelImpl) {
this.this$0 = managedChannelImpl;
}
@Override // io.grpc.internal.ManagedClientTransport.Listener
public final void transportShutdown(Status status) {
Preconditions.checkState(this.this$0.shutdown.get(), "Channel must have been shut down");
}
@Override // io.grpc.internal.ManagedClientTransport.Listener
public final void transportInUse(boolean z) {
this.this$0.inUseStateAggregator.updateObjectInUse(this.this$0.delayedTransport, z);
}
@Override // io.grpc.internal.ManagedClientTransport.Listener
public final void transportTerminated() {
Preconditions.checkState(this.this$0.shutdown.get(), "Channel must have been shut down");
this.this$0.terminating = true;
this.this$0.shutdownNameResolverAndLoadBalancer(false);
this.this$0.maybeShutdownNowSubchannels();
this.this$0.maybeTerminateChannel();
}
}
/* loaded from: classes6.dex */
final class IdleModeStateAggregator extends InUseStateAggregator<Object> {
final ManagedChannelImpl this$0;
private IdleModeStateAggregator(ManagedChannelImpl managedChannelImpl) {
this.this$0 = managedChannelImpl;
}
@Override // io.grpc.internal.InUseStateAggregator
protected final void handleInUse() {
this.this$0.exitIdleMode();
}
@Override // io.grpc.internal.InUseStateAggregator
protected final void handleNotInUse() {
if (this.this$0.shutdown.get()) {
return;
}
this.this$0.rescheduleIdleTimer();
}
}
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes6.dex */
public static final class ExecutorHolder {
private Executor executor;
private final ObjectPool<? extends Executor> pool;
ExecutorHolder(ObjectPool<? extends Executor> objectPool) {
this.pool = (ObjectPool) Preconditions.checkNotNull(objectPool, "executorPool");
}
final Executor getExecutor() {
Executor executor;
synchronized (this) {
if (this.executor == null) {
this.executor = (Executor) Preconditions.checkNotNull(this.pool.getObject(), "%s.getObject()", this.executor);
}
executor = this.executor;
}
return executor;
}
final void release() {
synchronized (this) {
Executor executor = this.executor;
if (executor != null) {
this.executor = this.pool.returnObject(executor);
}
}
}
}
/* loaded from: classes6.dex */
static final class RestrictedScheduledExecutor implements ScheduledExecutorService {
final ScheduledExecutorService delegate;
private RestrictedScheduledExecutor(ScheduledExecutorService scheduledExecutorService) {
this.delegate = (ScheduledExecutorService) Preconditions.checkNotNull(scheduledExecutorService, "delegate");
}
@Override // java.util.concurrent.ScheduledExecutorService
public final <V> ScheduledFuture<V> schedule(Callable<V> callable, long j, TimeUnit timeUnit) {
return this.delegate.schedule(callable, j, timeUnit);
}
@Override // java.util.concurrent.ScheduledExecutorService
public final ScheduledFuture<?> schedule(Runnable runnable, long j, TimeUnit timeUnit) {
return this.delegate.schedule(runnable, j, timeUnit);
}
@Override // java.util.concurrent.ScheduledExecutorService
public final ScheduledFuture<?> scheduleAtFixedRate(Runnable runnable, long j, long j2, TimeUnit timeUnit) {
return this.delegate.scheduleAtFixedRate(runnable, j, j2, timeUnit);
}
@Override // java.util.concurrent.ScheduledExecutorService
public final ScheduledFuture<?> scheduleWithFixedDelay(Runnable runnable, long j, long j2, TimeUnit timeUnit) {
return this.delegate.scheduleWithFixedDelay(runnable, j, j2, timeUnit);
}
@Override // java.util.concurrent.ExecutorService
public final boolean awaitTermination(long j, TimeUnit timeUnit) throws InterruptedException {
return this.delegate.awaitTermination(j, timeUnit);
}
@Override // java.util.concurrent.ExecutorService
public final <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> collection) throws InterruptedException {
return this.delegate.invokeAll(collection);
}
@Override // java.util.concurrent.ExecutorService
public final <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> collection, long j, TimeUnit timeUnit) throws InterruptedException {
return this.delegate.invokeAll(collection, j, timeUnit);
}
@Override // java.util.concurrent.ExecutorService
public final <T> T invokeAny(Collection<? extends Callable<T>> collection) throws InterruptedException, ExecutionException {
return (T) this.delegate.invokeAny(collection);
}
@Override // java.util.concurrent.ExecutorService
public final <T> T invokeAny(Collection<? extends Callable<T>> collection, long j, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
return (T) this.delegate.invokeAny(collection, j, timeUnit);
}
@Override // java.util.concurrent.ExecutorService
public final boolean isShutdown() {
return this.delegate.isShutdown();
}
@Override // java.util.concurrent.ExecutorService
public final boolean isTerminated() {
return this.delegate.isTerminated();
}
@Override // java.util.concurrent.ExecutorService
public final void shutdown() {
throw new UnsupportedOperationException("Restricted: shutdown() is not allowed");
}
@Override // java.util.concurrent.ExecutorService
public final List<Runnable> shutdownNow() {
throw new UnsupportedOperationException("Restricted: shutdownNow() is not allowed");
}
@Override // java.util.concurrent.ExecutorService
public final <T> Future<T> submit(Callable<T> callable) {
return this.delegate.submit(callable);
}
@Override // java.util.concurrent.ExecutorService
public final Future<?> submit(Runnable runnable) {
return this.delegate.submit(runnable);
}
@Override // java.util.concurrent.ExecutorService
public final <T> Future<T> submit(Runnable runnable, T t) {
return this.delegate.submit(runnable, t);
}
@Override // java.util.concurrent.Executor
public final void execute(Runnable runnable) {
this.delegate.execute(runnable);
}
}
@Override // io.grpc.ManagedChannel
public final boolean isTerminated() {
return this.terminated;
}
final boolean isInPanicMode() {
return this.panicMode;
}
@Override // io.grpc.InternalWithLogId
public final InternalLogId getLogId() {
return this.logId;
}
}