Class ManagedChannelImpl
- java.lang.Object
-
- io.grpc.Channel
-
- io.grpc.ManagedChannel
-
- io.grpc.internal.ManagedChannelImpl
-
- All Implemented Interfaces:
InternalInstrumented<InternalChannelz.ChannelStats>,InternalWithLogId
@ThreadSafe final class ManagedChannelImpl extends ManagedChannel implements InternalInstrumented<InternalChannelz.ChannelStats>
A communication channel for making outgoing RPCs.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private classManagedChannelImpl.ChannelStreamProvider(package private) static classManagedChannelImpl.ConfigSelectingClientCall<ReqT,RespT>A client call for a given channel that applies a given config selector when it starts.private classManagedChannelImpl.DelayedTransportListenerCalled from syncContext.(package private) static classManagedChannelImpl.ExecutorHolderLazily request for Executor from an executor pool.private classManagedChannelImpl.IdleModeStateAggregatorMust be accessed from syncContext.private classManagedChannelImpl.IdleModeTimerprivate classManagedChannelImpl.LbHelperImpl(package private) classManagedChannelImpl.NameResolverListenerprivate classManagedChannelImpl.RealChannel(package private) static classManagedChannelImpl.ResolutionStateA ResolutionState indicates the status of last name resolution.private static classManagedChannelImpl.RestrictedScheduledExecutorprivate classManagedChannelImpl.SubchannelImplprivate classManagedChannelImpl.UncommittedRetriableStreamsRegistryA registry that prevents channel shutdown from killing existing retry attempts that are in backoff.
-
Field Summary
-
Constructor Summary
Constructors Constructor Description ManagedChannelImpl(ManagedChannelImplBuilder builder, ClientTransportFactory clientTransportFactory, java.net.URI targetUri, NameResolverProvider nameResolverProvider, BackoffPolicy.Provider backoffPolicyProvider, ObjectPool<? extends java.util.concurrent.Executor> balancerRpcExecutorPool, com.google.common.base.Supplier<com.google.common.base.Stopwatch> stopwatchSupplier, java.util.List<ClientInterceptor> interceptors, TimeProvider timeProvider)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description java.lang.Stringauthority()The authority of the destination this channel connects to.booleanawaitTermination(long timeout, java.util.concurrent.TimeUnit unit)Waits for the channel to become terminated, giving up if the timeout is reached.private voidcancelIdleTimer(boolean permanent)voidenterIdle()Invoking this method moves the channel into the IDLE state and triggers tear-down of the channel's name resolver and load balancer, while still allowing on-going RPCs on the channel to continue.private voidenterIdleMode()(package private) voidexitIdleMode()Make the channel exit idle mode, if it's in it.private java.util.concurrent.ExecutorgetCallExecutor(CallOptions callOptions)(package private) InternalConfigSelectorgetConfigSelector()InternalLogIdgetLogId()Returns an ID that is primarily used in debug logs.(package private) static NameResolvergetNameResolver(java.net.URI targetUri, java.lang.String overrideAuthority, NameResolverProvider provider, NameResolver.Args nameResolverArgs)ConnectivityStategetState(boolean requestConnection)Gets the current connectivity state.com.google.common.util.concurrent.ListenableFuture<InternalChannelz.ChannelStats>getStats()Returns the stats object.private voidhandleInternalSubchannelState(ConnectivityStateInfo newState)(package private) booleanhasThrottle()(package private) booleanisInPanicMode()booleanisShutdown()Returns whether the channel is shutdown.booleanisTerminated()Returns whether the channel is terminated.private voidmaybeShutdownNowSubchannels()private voidmaybeTerminateChannel()Terminate the channel if termination conditions are met.<ReqT,RespT>
ClientCall<ReqT,RespT>newCall(MethodDescriptor<ReqT,RespT> method, CallOptions callOptions)Create aClientCallto the remote operation specified by the givenMethodDescriptor.voidnotifyWhenStateChanged(ConnectivityState source, java.lang.Runnable callback)Registers a one-off callback that will be run if the connectivity state of the channel diverges from the givensource, which is typically what has just been returned byManagedChannel.getState(boolean).(package private) voidpanic(java.lang.Throwable t)private voidrefreshNameResolution()Force name resolution refresh to happen immediately.private voidrescheduleIdleTimer()voidresetConnectBackoff()For subchannels that are in TRANSIENT_FAILURE state, short-circuit the backoff timer and make them reconnect immediately.ManagedChannelImplshutdown()Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately cancelled.private voidshutdownNameResolverAndLoadBalancer(boolean channelIsActive)ManagedChannelImplshutdownNow()Initiates a forceful shutdown in which preexisting and new calls are cancelled.java.lang.StringtoString()private voidupdateSubchannelPicker(LoadBalancer.SubchannelPicker newPicker)
-
-
-
Field Detail
-
logger
static final java.util.logging.Logger logger
-
IDLE_TIMEOUT_MILLIS_DISABLE
static final long IDLE_TIMEOUT_MILLIS_DISABLE
- See Also:
- Constant Field Values
-
SUBCHANNEL_SHUTDOWN_DELAY_SECONDS
static final long SUBCHANNEL_SHUTDOWN_DELAY_SECONDS
- See Also:
- Constant Field Values
-
SHUTDOWN_NOW_STATUS
static final Status SHUTDOWN_NOW_STATUS
-
SHUTDOWN_STATUS
static final Status SHUTDOWN_STATUS
-
SUBCHANNEL_SHUTDOWN_STATUS
static final Status SUBCHANNEL_SHUTDOWN_STATUS
-
EMPTY_SERVICE_CONFIG
private static final ManagedChannelServiceConfig EMPTY_SERVICE_CONFIG
-
INITIAL_PENDING_SELECTOR
private static final InternalConfigSelector INITIAL_PENDING_SELECTOR
-
NOOP_PICK_DETAILS_CONSUMER
private static final LoadBalancer.PickDetailsConsumer NOOP_PICK_DETAILS_CONSUMER
-
logId
private final InternalLogId logId
-
target
private final java.lang.String target
-
authorityOverride
@Nullable private final java.lang.String authorityOverride
-
nameResolverRegistry
private final NameResolverRegistry nameResolverRegistry
-
targetUri
private final java.net.URI targetUri
-
nameResolverProvider
private final NameResolverProvider nameResolverProvider
-
nameResolverArgs
private final NameResolver.Args nameResolverArgs
-
loadBalancerFactory
private final AutoConfiguredLoadBalancerFactory loadBalancerFactory
-
originalTransportFactory
private final ClientTransportFactory originalTransportFactory
-
originalChannelCreds
@Nullable private final ChannelCredentials originalChannelCreds
-
transportFactory
private final ClientTransportFactory transportFactory
-
oobTransportFactory
private final ClientTransportFactory oobTransportFactory
-
scheduledExecutor
private final ManagedChannelImpl.RestrictedScheduledExecutor scheduledExecutor
-
executor
private final java.util.concurrent.Executor executor
-
executorPool
private final ObjectPool<? extends java.util.concurrent.Executor> executorPool
-
balancerRpcExecutorPool
private final ObjectPool<? extends java.util.concurrent.Executor> balancerRpcExecutorPool
-
balancerRpcExecutorHolder
private final ManagedChannelImpl.ExecutorHolder balancerRpcExecutorHolder
-
offloadExecutorHolder
private final ManagedChannelImpl.ExecutorHolder offloadExecutorHolder
-
timeProvider
private final TimeProvider timeProvider
-
maxTraceEvents
private final int maxTraceEvents
-
syncContext
final SynchronizationContext syncContext
-
fullStreamDecompression
private boolean fullStreamDecompression
-
decompressorRegistry
private final DecompressorRegistry decompressorRegistry
-
compressorRegistry
private final CompressorRegistry compressorRegistry
-
stopwatchSupplier
private final com.google.common.base.Supplier<com.google.common.base.Stopwatch> stopwatchSupplier
-
idleTimeoutMillis
private final long idleTimeoutMillis
The timeout before entering idle mode.
-
channelStateManager
private final ConnectivityStateManager channelStateManager
-
backoffPolicyProvider
private final BackoffPolicy.Provider backoffPolicyProvider
-
interceptorChannel
private final Channel interceptorChannel
We delegate to this channel, so that we can have interceptors as necessary. If there aren't any interceptors and theBinaryLogisnullthen this will just be aManagedChannelImpl.RealChannel.
-
transportFilters
private final java.util.List<ClientTransportFilter> transportFilters
-
userAgent
@Nullable private final java.lang.String userAgent
-
nameResolver
private NameResolver nameResolver
-
nameResolverStarted
private boolean nameResolverStarted
-
lbHelper
@Nullable private ManagedChannelImpl.LbHelperImpl lbHelper
-
subchannelPicker
@Nullable private volatile LoadBalancer.SubchannelPicker subchannelPicker
-
panicMode
private boolean panicMode
-
subchannels
private final java.util.Set<InternalSubchannel> subchannels
-
pendingCalls
@Nullable private java.util.Collection<ManagedChannelImpl.RealChannel.PendingCall<?,?>> pendingCalls
-
pendingCallsInUseObject
private final java.lang.Object pendingCallsInUseObject
-
oobChannels
private final java.util.Set<OobChannel> oobChannels
-
delayedTransport
private final DelayedClientTransport delayedTransport
-
uncommittedRetriableStreamsRegistry
private final ManagedChannelImpl.UncommittedRetriableStreamsRegistry uncommittedRetriableStreamsRegistry
-
shutdown
private final java.util.concurrent.atomic.AtomicBoolean shutdown
-
shutdownNowed
private boolean shutdownNowed
-
terminating
private boolean terminating
-
terminated
private volatile boolean terminated
-
terminatedLatch
private final java.util.concurrent.CountDownLatch terminatedLatch
-
callTracerFactory
private final CallTracer.Factory callTracerFactory
-
channelCallTracer
private final CallTracer channelCallTracer
-
channelTracer
private final ChannelTracer channelTracer
-
channelLogger
private final ChannelLogger channelLogger
-
channelz
private final InternalChannelz channelz
-
realChannel
private final ManagedChannelImpl.RealChannel realChannel
-
lastResolutionState
private ManagedChannelImpl.ResolutionState lastResolutionState
-
lastServiceConfig
private ManagedChannelServiceConfig lastServiceConfig
-
defaultServiceConfig
@Nullable private final ManagedChannelServiceConfig defaultServiceConfig
-
serviceConfigUpdated
private boolean serviceConfigUpdated
-
lookUpServiceConfig
private final boolean lookUpServiceConfig
-
channelBufferUsed
private final RetriableStream.ChannelBufferMeter channelBufferUsed
-
perRpcBufferLimit
private final long perRpcBufferLimit
-
channelBufferLimit
private final long channelBufferLimit
-
retryEnabled
private final boolean retryEnabled
-
ticker
private final Deadline.Ticker ticker
-
delayedTransportListener
private final ManagedClientTransport.Listener delayedTransportListener
-
inUseStateAggregator
final InUseStateAggregator<java.lang.Object> inUseStateAggregator
-
transportProvider
private final ManagedChannelImpl.ChannelStreamProvider transportProvider
-
idleTimer
private final Rescheduler idleTimer
-
metricRecorder
private final MetricRecorder metricRecorder
-
NOOP_CALL
private static final ClientCall<java.lang.Object,java.lang.Object> NOOP_CALL
-
-
Constructor Detail
-
ManagedChannelImpl
ManagedChannelImpl(ManagedChannelImplBuilder builder, ClientTransportFactory clientTransportFactory, java.net.URI targetUri, NameResolverProvider nameResolverProvider, BackoffPolicy.Provider backoffPolicyProvider, ObjectPool<? extends java.util.concurrent.Executor> balancerRpcExecutorPool, com.google.common.base.Supplier<com.google.common.base.Stopwatch> stopwatchSupplier, java.util.List<ClientInterceptor> interceptors, TimeProvider timeProvider)
-
-
Method Detail
-
maybeShutdownNowSubchannels
private void maybeShutdownNowSubchannels()
-
getStats
public com.google.common.util.concurrent.ListenableFuture<InternalChannelz.ChannelStats> getStats()
Description copied from interface:InternalInstrumentedReturns the stats object.- Specified by:
getStatsin interfaceInternalInstrumented<InternalChannelz.ChannelStats>
-
getLogId
public InternalLogId getLogId()
Description copied from interface:InternalWithLogIdReturns an ID that is primarily used in debug logs. It usually contains the class name and a numeric ID that is unique among the instances.The subclasses of this interface usually want to include the log ID in their
Object.toString()results.- Specified by:
getLogIdin interfaceInternalWithLogId
-
shutdownNameResolverAndLoadBalancer
private void shutdownNameResolverAndLoadBalancer(boolean channelIsActive)
-
exitIdleMode
void exitIdleMode()
Make the channel exit idle mode, if it's in it.Must be called from syncContext
-
enterIdleMode
private void enterIdleMode()
-
cancelIdleTimer
private void cancelIdleTimer(boolean permanent)
-
rescheduleIdleTimer
private void rescheduleIdleTimer()
-
refreshNameResolution
private void refreshNameResolution()
Force name resolution refresh to happen immediately. Must be run from syncContext.
-
getNameResolver
static NameResolver getNameResolver(java.net.URI targetUri, @Nullable java.lang.String overrideAuthority, NameResolverProvider provider, NameResolver.Args nameResolverArgs)
-
getConfigSelector
InternalConfigSelector getConfigSelector()
-
hasThrottle
boolean hasThrottle()
-
shutdown
public ManagedChannelImpl shutdown()
Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately cancelled.- Specified by:
shutdownin classManagedChannel- Returns:
- this
-
shutdownNow
public ManagedChannelImpl shutdownNow()
Initiates a forceful shutdown in which preexisting and new calls are cancelled. Although forceful, the shutdown process is still not instantaneous;isTerminated()will likely returnfalseimmediately after this method returns.- Specified by:
shutdownNowin classManagedChannel- Returns:
- this
-
panic
void panic(java.lang.Throwable t)
-
isInPanicMode
boolean isInPanicMode()
-
updateSubchannelPicker
private void updateSubchannelPicker(LoadBalancer.SubchannelPicker newPicker)
-
isShutdown
public boolean isShutdown()
Description copied from class:ManagedChannelReturns whether the channel is shutdown. Shutdown channels immediately cancel any new calls, but may still have some calls being processed.- Specified by:
isShutdownin classManagedChannel- See Also:
ManagedChannel.shutdown(),ManagedChannel.isTerminated()
-
awaitTermination
public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) throws java.lang.InterruptedExceptionDescription copied from class:ManagedChannelWaits for the channel to become terminated, giving up if the timeout is reached.- Specified by:
awaitTerminationin classManagedChannel- Returns:
- whether the channel is terminated, as would be done by
ManagedChannel.isTerminated(). - Throws:
java.lang.InterruptedException
-
isTerminated
public boolean isTerminated()
Description copied from class:ManagedChannelReturns whether the channel is terminated. Terminated channels have no running calls and relevant resources released (like TCP connections).- Specified by:
isTerminatedin classManagedChannel- See Also:
ManagedChannel.isShutdown()
-
newCall
public <ReqT,RespT> ClientCall<ReqT,RespT> newCall(MethodDescriptor<ReqT,RespT> method, CallOptions callOptions)
Description copied from class:ChannelCreate aClientCallto the remote operation specified by the givenMethodDescriptor. The returnedClientCalldoes not trigger any remote behavior untilClientCall.start(ClientCall.Listener, Metadata)is invoked.- Specified by:
newCallin classChannel- Parameters:
method- describes the name and parameter types of the operation to call.callOptions- runtime options to be applied to this call.- Returns:
- a
ClientCallbound to the specified method.
-
authority
public java.lang.String authority()
Description copied from class:ChannelThe authority of the destination this channel connects to. Typically this is in the formathost:port.
-
getCallExecutor
private java.util.concurrent.Executor getCallExecutor(CallOptions callOptions)
-
maybeTerminateChannel
private void maybeTerminateChannel()
Terminate the channel if termination conditions are met.
-
handleInternalSubchannelState
private void handleInternalSubchannelState(ConnectivityStateInfo newState)
-
getState
public ConnectivityState getState(boolean requestConnection)
Description copied from class:ManagedChannelGets the current connectivity state. Note the result may soon become outdated.Note that the core library did not provide an implementation of this method until v1.6.1.
- Overrides:
getStatein classManagedChannel- Parameters:
requestConnection- iftrue, the channel will try to make a connection if it is currently IDLE
-
notifyWhenStateChanged
public void notifyWhenStateChanged(ConnectivityState source, java.lang.Runnable callback)
Description copied from class:ManagedChannelRegisters a one-off callback that will be run if the connectivity state of the channel diverges from the givensource, which is typically what has just been returned byManagedChannel.getState(boolean). If the states are already different, the callback will be called immediately. The callback is run in the same executor that runs Call listeners.There is an inherent race between the notification to
callbackand any call togetState(). There is a similar race betweengetState()and a call tonotifyWhenStateChanged(). The state can change during those races, so there is not a way to see every state transition. "Transitions" to the same state are possible, because intermediate states may not have been observed. The API is only reliable in tracking the current state.Note that the core library did not provide an implementation of this method until v1.6.1.
- Overrides:
notifyWhenStateChangedin classManagedChannel- Parameters:
source- the assumed current state, typically just returned byManagedChannel.getState(boolean)callback- the one-off callback
-
resetConnectBackoff
public void resetConnectBackoff()
Description copied from class:ManagedChannelFor subchannels that are in TRANSIENT_FAILURE state, short-circuit the backoff timer and make them reconnect immediately. May also attempt to invokeNameResolver.refresh().This is primarily intended for Android users, where the network may experience frequent temporary drops. Rather than waiting for gRPC's name resolution and reconnect timers to elapse before reconnecting, the app may use this method as a mechanism to notify gRPC that the network is now available and a reconnection attempt may occur immediately.
No-op if not supported by the implementation.
- Overrides:
resetConnectBackoffin classManagedChannel
-
enterIdle
public void enterIdle()
Description copied from class:ManagedChannelInvoking this method moves the channel into the IDLE state and triggers tear-down of the channel's name resolver and load balancer, while still allowing on-going RPCs on the channel to continue. New RPCs on the channel will trigger creation of a new connection.This is primarily intended for Android users when a device is transitioning from a cellular to a wifi connection. The OS will issue a notification that a new network (wifi) has been made the default, but for approximately 30 seconds the device will maintain both the cellular and wifi connections. Apps may invoke this method to ensure that new RPCs are created using the new default wifi network, rather than the soon-to-be-disconnected cellular network.
No-op if not supported by implementation.
- Overrides:
enterIdlein classManagedChannel
-
toString
public java.lang.String toString()
- Overrides:
toStringin classjava.lang.Object
-
-