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 class
ManagedChannelImpl.ChannelStreamProvider
(package private) static class
ManagedChannelImpl.ConfigSelectingClientCall<ReqT,RespT>
A client call for a given channel that applies a given config selector when it starts.private class
ManagedChannelImpl.DelayedTransportListener
Called from syncContext.(package private) static class
ManagedChannelImpl.ExecutorHolder
Lazily request for Executor from an executor pool.private class
ManagedChannelImpl.IdleModeStateAggregator
Must be accessed from syncContext.private class
ManagedChannelImpl.IdleModeTimer
private class
ManagedChannelImpl.LbHelperImpl
(package private) class
ManagedChannelImpl.NameResolverListener
private class
ManagedChannelImpl.RealChannel
(package private) static class
ManagedChannelImpl.ResolutionState
A ResolutionState indicates the status of last name resolution.private static class
ManagedChannelImpl.RestrictedScheduledExecutor
private class
ManagedChannelImpl.SubchannelImpl
private class
ManagedChannelImpl.UncommittedRetriableStreamsRegistry
A 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.String
authority()
The authority of the destination this channel connects to.boolean
awaitTermination(long timeout, java.util.concurrent.TimeUnit unit)
Waits for the channel to become terminated, giving up if the timeout is reached.private void
cancelIdleTimer(boolean permanent)
void
enterIdle()
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 void
enterIdleMode()
(package private) void
exitIdleMode()
Make the channel exit idle mode, if it's in it.private java.util.concurrent.Executor
getCallExecutor(CallOptions callOptions)
(package private) InternalConfigSelector
getConfigSelector()
InternalLogId
getLogId()
Returns an ID that is primarily used in debug logs.(package private) static NameResolver
getNameResolver(java.net.URI targetUri, java.lang.String overrideAuthority, NameResolverProvider provider, NameResolver.Args nameResolverArgs)
ConnectivityState
getState(boolean requestConnection)
Gets the current connectivity state.com.google.common.util.concurrent.ListenableFuture<InternalChannelz.ChannelStats>
getStats()
Returns the stats object.private void
handleInternalSubchannelState(ConnectivityStateInfo newState)
(package private) boolean
hasThrottle()
(package private) boolean
isInPanicMode()
boolean
isShutdown()
Returns whether the channel is shutdown.boolean
isTerminated()
Returns whether the channel is terminated.private void
maybeShutdownNowSubchannels()
private void
maybeTerminateChannel()
Terminate the channel if termination conditions are met.<ReqT,RespT>
ClientCall<ReqT,RespT>newCall(MethodDescriptor<ReqT,RespT> method, CallOptions callOptions)
Create aClientCall
to the remote operation specified by the givenMethodDescriptor
.void
notifyWhenStateChanged(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) void
panic(java.lang.Throwable t)
private void
refreshNameResolution()
Force name resolution refresh to happen immediately.private void
rescheduleIdleTimer()
void
resetConnectBackoff()
For subchannels that are in TRANSIENT_FAILURE state, short-circuit the backoff timer and make them reconnect immediately.ManagedChannelImpl
shutdown()
Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately cancelled.private void
shutdownNameResolverAndLoadBalancer(boolean channelIsActive)
ManagedChannelImpl
shutdownNow()
Initiates a forceful shutdown in which preexisting and new calls are cancelled.java.lang.String
toString()
private void
updateSubchannelPicker(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 theBinaryLog
isnull
then 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:InternalInstrumented
Returns the stats object.- Specified by:
getStats
in interfaceInternalInstrumented<InternalChannelz.ChannelStats>
-
getLogId
public InternalLogId getLogId()
Description copied from interface:InternalWithLogId
Returns 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:
getLogId
in 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:
shutdown
in 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 returnfalse
immediately after this method returns.- Specified by:
shutdownNow
in 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:ManagedChannel
Returns whether the channel is shutdown. Shutdown channels immediately cancel any new calls, but may still have some calls being processed.- Specified by:
isShutdown
in classManagedChannel
- See Also:
ManagedChannel.shutdown()
,ManagedChannel.isTerminated()
-
awaitTermination
public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) throws java.lang.InterruptedException
Description copied from class:ManagedChannel
Waits for the channel to become terminated, giving up if the timeout is reached.- Specified by:
awaitTermination
in 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:ManagedChannel
Returns whether the channel is terminated. Terminated channels have no running calls and relevant resources released (like TCP connections).- Specified by:
isTerminated
in classManagedChannel
- See Also:
ManagedChannel.isShutdown()
-
newCall
public <ReqT,RespT> ClientCall<ReqT,RespT> newCall(MethodDescriptor<ReqT,RespT> method, CallOptions callOptions)
Description copied from class:Channel
Create aClientCall
to the remote operation specified by the givenMethodDescriptor
. The returnedClientCall
does not trigger any remote behavior untilClientCall.start(ClientCall.Listener, Metadata)
is invoked.- Specified by:
newCall
in 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
ClientCall
bound to the specified method.
-
authority
public java.lang.String authority()
Description copied from class:Channel
The 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:ManagedChannel
Gets 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:
getState
in 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:ManagedChannel
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)
. 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
callback
and 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:
notifyWhenStateChanged
in 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:ManagedChannel
For 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:
resetConnectBackoff
in classManagedChannel
-
enterIdle
public void enterIdle()
Description copied from class:ManagedChannel
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. 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:
enterIdle
in classManagedChannel
-
toString
public java.lang.String toString()
- Overrides:
toString
in classjava.lang.Object
-
-