idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
18,600
private static Runnable asRunnable ( final ClientTransport . PingCallback callback , final Throwable failureCause ) { return new Runnable ( ) { public void run ( ) { callback . onFailure ( failureCause ) ; } } ; }
Returns a runnable that when run invokes the given callback providing the given cause of failure .
18,601
private boolean readRequiredBytes ( ) { int totalBytesRead = 0 ; int deflatedBytesRead = 0 ; try { if ( nextFrame == null ) { nextFrame = new CompositeReadableBuffer ( ) ; } int missingBytes ; while ( ( missingBytes = requiredLength - nextFrame . readableBytes ( ) ) > 0 ) { if ( fullStreamDecompressor != null ) { try { if ( inflatedBuffer == null || inflatedIndex == inflatedBuffer . length ) { inflatedBuffer = new byte [ Math . min ( missingBytes , MAX_BUFFER_SIZE ) ] ; inflatedIndex = 0 ; } int bytesToRead = Math . min ( missingBytes , inflatedBuffer . length - inflatedIndex ) ; int n = fullStreamDecompressor . inflateBytes ( inflatedBuffer , inflatedIndex , bytesToRead ) ; totalBytesRead += fullStreamDecompressor . getAndResetBytesConsumed ( ) ; deflatedBytesRead += fullStreamDecompressor . getAndResetDeflatedBytesConsumed ( ) ; if ( n == 0 ) { return false ; } nextFrame . addBuffer ( ReadableBuffers . wrap ( inflatedBuffer , inflatedIndex , n ) ) ; inflatedIndex += n ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( DataFormatException e ) { throw new RuntimeException ( e ) ; } } else { if ( unprocessed . readableBytes ( ) == 0 ) { return false ; } int toRead = Math . min ( missingBytes , unprocessed . readableBytes ( ) ) ; totalBytesRead += toRead ; nextFrame . addBuffer ( unprocessed . readBytes ( toRead ) ) ; } } return true ; } finally { if ( totalBytesRead > 0 ) { listener . bytesRead ( totalBytesRead ) ; if ( state == State . BODY ) { if ( fullStreamDecompressor != null ) { statsTraceCtx . inboundWireSize ( deflatedBytesRead ) ; inboundBodyWireSize += deflatedBytesRead ; } else { statsTraceCtx . inboundWireSize ( totalBytesRead ) ; inboundBodyWireSize += totalBytesRead ; } } } } }
Attempts to read the required bytes into nextFrame .
18,602
private void processHeader ( ) { int type = nextFrame . readUnsignedByte ( ) ; if ( ( type & RESERVED_MASK ) != 0 ) { throw Status . INTERNAL . withDescription ( "gRPC frame header malformed: reserved bits not zero" ) . asRuntimeException ( ) ; } compressedFlag = ( type & COMPRESSED_FLAG_MASK ) != 0 ; requiredLength = nextFrame . readInt ( ) ; if ( requiredLength < 0 || requiredLength > maxInboundMessageSize ) { throw Status . RESOURCE_EXHAUSTED . withDescription ( String . format ( "gRPC message exceeds maximum size %d: %d" , maxInboundMessageSize , requiredLength ) ) . asRuntimeException ( ) ; } currentMessageSeqNo ++ ; statsTraceCtx . inboundMessage ( currentMessageSeqNo ) ; transportTracer . reportMessageReceived ( ) ; state = State . BODY ; }
Processes the GRPC compression header which is composed of the compression flag and the outer frame length .
18,603
private void processBody ( ) { statsTraceCtx . inboundMessageRead ( currentMessageSeqNo , inboundBodyWireSize , - 1 ) ; inboundBodyWireSize = 0 ; InputStream stream = compressedFlag ? getCompressedBody ( ) : getUncompressedBody ( ) ; nextFrame = null ; listener . messagesAvailable ( new SingleMessageProducer ( stream ) ) ; state = State . HEADER ; requiredLength = HEADER_LENGTH ; }
Processes the GRPC message body which depending on frame header flags may be compressed .
18,604
private static InetSocketAddress overrideProxy ( String proxyHostPort ) { if ( proxyHostPort == null ) { return null ; } String [ ] parts = proxyHostPort . split ( ":" , 2 ) ; int port = 80 ; if ( parts . length > 1 ) { port = Integer . parseInt ( parts [ 1 ] ) ; } log . warning ( "Detected GRPC_PROXY_EXP and will honor it, but this feature will " + "be removed in a future release. Use the JVM flags " + "\"-Dhttps.proxyHost=HOST -Dhttps.proxyPort=PORT\" to set the https proxy for " + "this JVM." ) ; return new InetSocketAddress ( parts [ 0 ] , port ) ; }
GRPC_PROXY_EXP is deprecated but let s maintain compatibility for now .
18,605
@ Setup ( Level . Trial ) public void setup ( ) throws Exception { super . setup ( ExecutorType . DIRECT , ExecutorType . DIRECT , MessageSize . SMALL , MessageSize . SMALL , FlowWindowSize . MEDIUM , ChannelType . NIO , 1 , 1 ) ; }
Setup with direct executors small payloads and the default flow control window .
18,606
public Object blockingUnary ( ) throws Exception { return ClientCalls . blockingUnaryCall ( channels [ 0 ] . newCall ( unaryMethod , CallOptions . DEFAULT ) , Unpooled . EMPTY_BUFFER ) ; }
Issue a unary call and wait for the response .
18,607
public ServerMethodDefinition < ReqT , RespT > withServerCallHandler ( ServerCallHandler < ReqT , RespT > handler ) { return new ServerMethodDefinition < > ( method , handler ) ; }
Create a new method definition with a different call handler .
18,608
private static List < Subchannel > filterNonFailingSubchannels ( Collection < Subchannel > subchannels ) { List < Subchannel > readySubchannels = new ArrayList < > ( subchannels . size ( ) ) ; for ( Subchannel subchannel : subchannels ) { if ( isReady ( subchannel ) ) { readySubchannels . add ( subchannel ) ; } } return readySubchannels ; }
Filters out non - ready subchannels .
18,609
@ Setup ( Level . Trial ) public void setup ( ) throws Exception { super . setup ( ExecutorType . DIRECT , ExecutorType . DIRECT , MessageSize . SMALL , MessageSize . SMALL , FlowWindowSize . LARGE , ChannelType . NIO , maxConcurrentStreams , channelCount ) ; callCounter = new AtomicLong ( ) ; completed = new AtomicBoolean ( ) ; startUnaryCalls ( maxConcurrentStreams , callCounter , completed , 1 ) ; }
Setup with direct executors small payloads and a large flow control window .
18,610
public CallOptions withoutWaitForReady ( ) { CallOptions newOptions = new CallOptions ( this ) ; newOptions . waitForReady = Boolean . FALSE ; return newOptions ; }
Disables wait for ready feature for the call . This method should be rarely used because the default is without wait for ready .
18,611
public < T > CallOptions withOption ( Key < T > key , T value ) { Preconditions . checkNotNull ( key , "key" ) ; Preconditions . checkNotNull ( value , "value" ) ; CallOptions newOptions = new CallOptions ( this ) ; int existingIdx = - 1 ; for ( int i = 0 ; i < customOptions . length ; i ++ ) { if ( key . equals ( customOptions [ i ] [ 0 ] ) ) { existingIdx = i ; break ; } } newOptions . customOptions = new Object [ customOptions . length + ( existingIdx == - 1 ? 1 : 0 ) ] [ 2 ] ; System . arraycopy ( customOptions , 0 , newOptions . customOptions , 0 , customOptions . length ) ; if ( existingIdx == - 1 ) { newOptions . customOptions [ customOptions . length ] = new Object [ ] { key , value } ; } else { newOptions . customOptions [ existingIdx ] = new Object [ ] { key , value } ; } return newOptions ; }
Sets a custom option . Any existing value for the key is overwritten .
18,612
@ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/1869" ) @ SuppressWarnings ( "unchecked" ) public < T > T getOption ( Key < T > key ) { Preconditions . checkNotNull ( key , "key" ) ; for ( int i = 0 ; i < customOptions . length ; i ++ ) { if ( key . equals ( customOptions [ i ] [ 0 ] ) ) { return ( T ) customOptions [ i ] [ 1 ] ; } } return key . defaultValue ; }
Get the value for a custom option or its inherent default .
18,613
@ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/2563" ) public CallOptions withMaxOutboundMessageSize ( int maxSize ) { checkArgument ( maxSize >= 0 , "invalid maxsize %s" , maxSize ) ; CallOptions newOptions = new CallOptions ( this ) ; newOptions . maxOutboundMessageSize = maxSize ; return newOptions ; }
Sets the maximum allowed message size acceptable sent to the remote peer .
18,614
public boolean processBytesFromPeer ( ByteBuffer bytes ) throws GeneralSecurityException { if ( outputFrame == null && isClient ) { return true ; } if ( outputFrame != null && outputFrame . hasRemaining ( ) ) { return true ; } int remaining = bytes . remaining ( ) ; if ( outputFrame == null ) { checkState ( ! isClient , "Client handshaker should not process any frame at the beginning." ) ; outputFrame = handshaker . startServerHandshake ( bytes ) ; } else { outputFrame = handshaker . next ( bytes ) ; } if ( handshaker . isFinished ( ) || outputFrame . hasRemaining ( ) ) { return true ; } if ( ! bytes . hasRemaining ( ) ) { return false ; } checkState ( bytes . remaining ( ) < remaining , "Handshaker did not consume any bytes." ) ; return processBytesFromPeer ( bytes ) ; }
Process the bytes received from the peer .
18,615
public static TsiHandshaker newClient ( HandshakerServiceStub stub , AltsHandshakerOptions options ) { return new AltsTsiHandshaker ( true , stub , options ) ; }
Creates a new TsiHandshaker for use by the client .
18,616
public static TsiHandshaker newServer ( HandshakerServiceStub stub , AltsHandshakerOptions options ) { return new AltsTsiHandshaker ( false , stub , options ) ; }
Creates a new TsiHandshaker for use by the server .
18,617
public void getBytesToSendToPeer ( ByteBuffer bytes ) throws GeneralSecurityException { if ( outputFrame == null ) { if ( isClient ) { outputFrame = handshaker . startClientHandshake ( ) ; } else { return ; } } ByteBuffer outputFrameAlias = outputFrame ; if ( outputFrame . remaining ( ) > bytes . remaining ( ) ) { outputFrameAlias = outputFrame . duplicate ( ) ; outputFrameAlias . limit ( outputFrameAlias . position ( ) + bytes . remaining ( ) ) ; } bytes . put ( outputFrameAlias ) ; outputFrame . position ( outputFrameAlias . position ( ) ) ; }
Gets bytes that need to be sent to the peer .
18,618
@ Setup ( Level . Trial ) public void setup ( ) throws Exception { super . setup ( ExecutorType . DIRECT , ExecutorType . DIRECT , MessageSize . SMALL , responseSize , clientInboundFlowWindow , ChannelType . NIO , maxConcurrentStreams , 1 ) ; callCounter = new AtomicLong ( ) ; completed = new AtomicBoolean ( ) ; record = new AtomicBoolean ( ) ; latch = startFlowControlledStreamingCalls ( maxConcurrentStreams , callCounter , record , completed , responseSize . bytes ( ) ) ; }
Setup with direct executors and one channel .
18,619
public void getServers ( GetServersRequest request , StreamObserver < GetServersResponse > responseObserver ) { ServerList servers = channelz . getServers ( request . getStartServerId ( ) , maxPageSize ) ; GetServersResponse resp ; try { resp = ChannelzProtoUtil . toGetServersResponse ( servers ) ; } catch ( StatusRuntimeException e ) { responseObserver . onError ( e ) ; return ; } responseObserver . onNext ( resp ) ; responseObserver . onCompleted ( ) ; }
Returns servers .
18,620
public void getSubchannel ( GetSubchannelRequest request , StreamObserver < GetSubchannelResponse > responseObserver ) { InternalInstrumented < ChannelStats > s = channelz . getSubchannel ( request . getSubchannelId ( ) ) ; if ( s == null ) { responseObserver . onError ( Status . NOT_FOUND . withDescription ( "Can't find subchannel " + request . getSubchannelId ( ) ) . asRuntimeException ( ) ) ; return ; } GetSubchannelResponse resp ; try { resp = GetSubchannelResponse . newBuilder ( ) . setSubchannel ( ChannelzProtoUtil . toSubchannel ( s ) ) . build ( ) ; } catch ( StatusRuntimeException e ) { responseObserver . onError ( e ) ; return ; } responseObserver . onNext ( resp ) ; responseObserver . onCompleted ( ) ; }
Returns a subchannel .
18,621
public synchronized void onDataReceived ( ) { stopwatch . reset ( ) . start ( ) ; if ( state == State . PING_SCHEDULED ) { state = State . PING_DELAYED ; } else if ( state == State . PING_SENT || state == State . IDLE_AND_PING_SENT ) { if ( shutdownFuture != null ) { shutdownFuture . cancel ( false ) ; } if ( state == State . IDLE_AND_PING_SENT ) { state = State . IDLE ; return ; } state = State . PING_SCHEDULED ; checkState ( pingFuture == null , "There should be no outstanding pingFuture" ) ; pingFuture = scheduler . schedule ( sendPing , keepAliveTimeInNanos , TimeUnit . NANOSECONDS ) ; } }
Transport has received some data so that we can delay sending keepalives .
18,622
public synchronized void onTransportActive ( ) { if ( state == State . IDLE ) { state = State . PING_SCHEDULED ; if ( pingFuture == null ) { pingFuture = scheduler . schedule ( sendPing , keepAliveTimeInNanos - stopwatch . elapsed ( TimeUnit . NANOSECONDS ) , TimeUnit . NANOSECONDS ) ; } } else if ( state == State . IDLE_AND_PING_SENT ) { state = State . PING_SENT ; } }
Transport has active streams . Start sending keepalives if necessary .
18,623
public synchronized void onTransportIdle ( ) { if ( keepAliveDuringTransportIdle ) { return ; } if ( state == State . PING_SCHEDULED || state == State . PING_DELAYED ) { state = State . IDLE ; } if ( state == State . PING_SENT ) { state = State . IDLE_AND_PING_SENT ; } }
Transport has finished all streams .
18,624
public synchronized void onTransportTermination ( ) { if ( state != State . DISCONNECTED ) { state = State . DISCONNECTED ; if ( shutdownFuture != null ) { shutdownFuture . cancel ( false ) ; } if ( pingFuture != null ) { pingFuture . cancel ( false ) ; pingFuture = null ; } } }
Transport is being terminated . We no longer need to do keepalives .
18,625
public void sendMessage ( View view ) { ( ( InputMethodManager ) getSystemService ( Context . INPUT_METHOD_SERVICE ) ) . hideSoftInputFromWindow ( hostEdit . getWindowToken ( ) , 0 ) ; sendButton . setEnabled ( false ) ; resultText . setText ( "" ) ; new GrpcTask ( this , cache ) . execute ( hostEdit . getText ( ) . toString ( ) , messageEdit . getText ( ) . toString ( ) , portEdit . getText ( ) . toString ( ) , getCheckBox . isChecked ( ) , noCacheCheckBox . isChecked ( ) , onlyIfCachedCheckBox . isChecked ( ) ) ; }
Sends RPC . Invoked when app button is pressed .
18,626
void notifyWhenStateChanged ( Runnable callback , Executor executor , ConnectivityState source ) { checkNotNull ( callback , "callback" ) ; checkNotNull ( executor , "executor" ) ; checkNotNull ( source , "source" ) ; Listener stateChangeListener = new Listener ( callback , executor ) ; if ( state != source ) { stateChangeListener . runInExecutor ( ) ; } else { listeners . add ( stateChangeListener ) ; } }
Adds a listener for state change event .
18,627
public static < T extends Message > Metadata . Key < T > keyForProto ( T instance ) { return Metadata . Key . of ( instance . getDescriptorForType ( ) . getFullName ( ) + Metadata . BINARY_HEADER_SUFFIX , metadataMarshaller ( instance ) ) ; }
Produce a metadata key for a generated protobuf type .
18,628
public HandshakerResp send ( HandshakerReq req ) throws InterruptedException , IOException { maybeThrowIoException ( ) ; if ( ! responseQueue . isEmpty ( ) ) { throw new IOException ( "Received an unexpected response." ) ; } writer . onNext ( req ) ; Optional < HandshakerResp > result = responseQueue . take ( ) ; if ( ! result . isPresent ( ) ) { maybeThrowIoException ( ) ; } return result . get ( ) ; }
Send a handshaker request and return the handshaker response .
18,629
private int writeKnownLengthUncompressed ( InputStream message , int messageLength ) throws IOException { if ( maxOutboundMessageSize >= 0 && messageLength > maxOutboundMessageSize ) { throw Status . RESOURCE_EXHAUSTED . withDescription ( String . format ( "message too large %d > %d" , messageLength , maxOutboundMessageSize ) ) . asRuntimeException ( ) ; } ByteBuffer header = ByteBuffer . wrap ( headerScratch ) ; header . put ( UNCOMPRESSED ) ; header . putInt ( messageLength ) ; if ( buffer == null ) { buffer = bufferAllocator . allocate ( header . position ( ) + messageLength ) ; } writeRaw ( headerScratch , 0 , header . position ( ) ) ; return writeToOutputStream ( message , outputStreamAdapter ) ; }
Write an unserialized message with a known length uncompressed .
18,630
private void writeBufferChain ( BufferChainOutputStream bufferChain , boolean compressed ) { ByteBuffer header = ByteBuffer . wrap ( headerScratch ) ; header . put ( compressed ? COMPRESSED : UNCOMPRESSED ) ; int messageLength = bufferChain . readableBytes ( ) ; header . putInt ( messageLength ) ; WritableBuffer writeableHeader = bufferAllocator . allocate ( HEADER_LENGTH ) ; writeableHeader . write ( headerScratch , 0 , header . position ( ) ) ; if ( messageLength == 0 ) { buffer = writeableHeader ; return ; } sink . deliverFrame ( writeableHeader , false , false , messagesBuffered - 1 ) ; messagesBuffered = 1 ; List < WritableBuffer > bufferList = bufferChain . bufferList ; for ( int i = 0 ; i < bufferList . size ( ) - 1 ; i ++ ) { sink . deliverFrame ( bufferList . get ( i ) , false , false , 0 ) ; } buffer = bufferList . get ( bufferList . size ( ) - 1 ) ; currentMessageWireSize = messageLength ; }
Write a message that has been serialized to a sequence of buffers .
18,631
public void close ( ) { if ( ! isClosed ( ) ) { closed = true ; if ( buffer != null && buffer . readableBytes ( ) == 0 ) { releaseBuffer ( ) ; } commitToSink ( true , true ) ; } }
Flushes and closes the framer and releases any buffers . After the framer is closed or disposed additional calls to this method will have no affect .
18,632
private void setStartClientFields ( HandshakerReq . Builder req ) { StartClientHandshakeReq . Builder startClientReq = StartClientHandshakeReq . newBuilder ( ) . setHandshakeSecurityProtocol ( HandshakeProtocol . ALTS ) . addApplicationProtocols ( APPLICATION_PROTOCOL ) . addRecordProtocols ( RECORD_PROTOCOL ) ; if ( handshakerOptions . getRpcProtocolVersions ( ) != null ) { startClientReq . setRpcVersions ( handshakerOptions . getRpcProtocolVersions ( ) ) ; } if ( handshakerOptions instanceof AltsClientOptions ) { AltsClientOptions clientOptions = ( AltsClientOptions ) handshakerOptions ; if ( ! Strings . isNullOrEmpty ( clientOptions . getTargetName ( ) ) ) { startClientReq . setTargetName ( clientOptions . getTargetName ( ) ) ; } for ( String serviceAccount : clientOptions . getTargetServiceAccounts ( ) ) { startClientReq . addTargetIdentitiesBuilder ( ) . setServiceAccount ( serviceAccount ) ; } } req . setClientStart ( startClientReq ) ; }
Sets the start client fields for the passed handshake request .
18,633
private void setStartServerFields ( HandshakerReq . Builder req , ByteBuffer inBytes ) { ServerHandshakeParameters serverParameters = ServerHandshakeParameters . newBuilder ( ) . addRecordProtocols ( RECORD_PROTOCOL ) . build ( ) ; StartServerHandshakeReq . Builder startServerReq = StartServerHandshakeReq . newBuilder ( ) . addApplicationProtocols ( APPLICATION_PROTOCOL ) . putHandshakeParameters ( HandshakeProtocol . ALTS . getNumber ( ) , serverParameters ) . setInBytes ( ByteString . copyFrom ( inBytes . duplicate ( ) ) ) ; if ( handshakerOptions . getRpcProtocolVersions ( ) != null ) { startServerReq . setRpcVersions ( handshakerOptions . getRpcProtocolVersions ( ) ) ; } req . setServerStart ( startServerReq ) ; }
Sets the start server fields for the passed handshake request .
18,634
public boolean isFinished ( ) { if ( result != null ) { return true ; } if ( status != null && status . getCode ( ) != Status . Code . OK . value ( ) ) { return true ; } return false ; }
Returns true if the handshake is complete .
18,635
public byte [ ] getKey ( ) { if ( result == null ) { return null ; } if ( result . getKeyData ( ) . size ( ) < KEY_LENGTH ) { throw new IllegalStateException ( "Could not get enough key data from the handshake." ) ; } byte [ ] key = new byte [ KEY_LENGTH ] ; result . getKeyData ( ) . copyTo ( key , 0 , 0 , KEY_LENGTH ) ; return key ; }
Returns the resulting key of the handshake if the handshake is completed . Note that the key data returned from the handshake may be more than the key length required for the record protocol thus we need to truncate to the right size .
18,636
private void handleResponse ( HandshakerResp resp ) throws GeneralSecurityException { status = resp . getStatus ( ) ; if ( resp . hasResult ( ) ) { result = resp . getResult ( ) ; close ( ) ; } if ( status . getCode ( ) != Status . Code . OK . value ( ) ) { String error = "Handshaker service error: " + status . getDetails ( ) ; logger . log ( Level . INFO , error ) ; close ( ) ; throw new GeneralSecurityException ( error ) ; } }
Parses a handshake response setting the status result and closing the handshaker as needed .
18,637
public static CronetChannelBuilder forAddress ( String host , int port , CronetEngine cronetEngine ) { Preconditions . checkNotNull ( cronetEngine , "cronetEngine" ) ; return new CronetChannelBuilder ( host , port , cronetEngine ) ; }
Creates a new builder for the given server host port and CronetEngine .
18,638
public void start ( ) throws IOException { server . start ( ) ; logger . info ( "Server started, listening on " + port ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { System . err . println ( "*** shutting down gRPC server since JVM is shutting down" ) ; RouteGuideServer . this . stop ( ) ; System . err . println ( "*** server shut down" ) ; } } ) ; }
Start serving requests .
18,639
public static void main ( String [ ] args ) throws Exception { RouteGuideServer server = new RouteGuideServer ( 8980 ) ; server . start ( ) ; server . blockUntilShutdown ( ) ; }
Main method . This comment makes the linter happy .
18,640
private NettyServerHandler createHandler ( ServerTransportListener transportListener , ChannelPromise channelUnused ) { return NettyServerHandler . newHandler ( transportListener , channelUnused , streamTracerFactories , transportTracer , maxStreams , flowControlWindow , maxHeaderListSize , maxMessageSize , keepAliveTimeInNanos , keepAliveTimeoutInNanos , maxConnectionIdleInNanos , maxConnectionAgeInNanos , maxConnectionAgeGraceInNanos , permitKeepAliveWithoutCalls , permitKeepAliveTimeInNanos ) ; }
Creates the Netty handler to be used in the channel pipeline .
18,641
void recordDroppedRequest ( String category ) { AtomicLong counter = dropCounters . get ( category ) ; if ( counter == null ) { counter = dropCounters . putIfAbsent ( category , new AtomicLong ( ) ) ; if ( counter == null ) { counter = dropCounters . get ( category ) ; } } counter . getAndIncrement ( ) ; }
Record that a request has been dropped by drop overload policy with the provided category instructed by the remote balancer .
18,642
void handleAddresses ( List < LbAddressGroup > newLbAddressGroups , List < EquivalentAddressGroup > newBackendServers ) { if ( newLbAddressGroups . isEmpty ( ) ) { shutdownLbComm ( ) ; syncContext . execute ( new FallbackModeTask ( ) ) ; } else { LbAddressGroup newLbAddressGroup = flattenLbAddressGroups ( newLbAddressGroups ) ; startLbComm ( newLbAddressGroup ) ; if ( lbStream == null ) { startLbRpc ( ) ; } if ( fallbackTimer == null ) { fallbackTimer = syncContext . schedule ( new FallbackModeTask ( ) , FALLBACK_TIMEOUT_MS , TimeUnit . MILLISECONDS , timerService ) ; } } fallbackBackendList = newBackendServers ; if ( usingFallbackBackends ) { useFallbackBackends ( ) ; } maybeUpdatePicker ( ) ; }
Handle new addresses of the balancer and backends from the resolver and create connection if not yet connected .
18,643
private void useFallbackBackends ( ) { usingFallbackBackends = true ; logger . log ( ChannelLogLevel . INFO , "Using fallback backends" ) ; List < DropEntry > newDropList = new ArrayList < > ( ) ; List < BackendAddressGroup > newBackendAddrList = new ArrayList < > ( ) ; for ( EquivalentAddressGroup eag : fallbackBackendList ) { newDropList . add ( null ) ; newBackendAddrList . add ( new BackendAddressGroup ( eag , null ) ) ; } useRoundRobinLists ( newDropList , newBackendAddrList , null ) ; }
Populate the round - robin lists with the fallback backends .
18,644
private void maybeUpdatePicker ( ) { List < RoundRobinEntry > pickList ; ConnectivityState state ; switch ( mode ) { case ROUND_ROBIN : pickList = new ArrayList < > ( backendList . size ( ) ) ; Status error = null ; boolean hasIdle = false ; for ( BackendEntry entry : backendList ) { Subchannel subchannel = entry . subchannel ; Attributes attrs = subchannel . getAttributes ( ) ; ConnectivityStateInfo stateInfo = attrs . get ( STATE_INFO ) . get ( ) ; if ( stateInfo . getState ( ) == READY ) { pickList . add ( entry ) ; } else if ( stateInfo . getState ( ) == TRANSIENT_FAILURE ) { error = stateInfo . getStatus ( ) ; } else if ( stateInfo . getState ( ) == IDLE ) { hasIdle = true ; } } if ( pickList . isEmpty ( ) ) { if ( error != null && ! hasIdle ) { pickList . add ( new ErrorEntry ( error ) ) ; state = TRANSIENT_FAILURE ; } else { pickList . add ( BUFFER_ENTRY ) ; state = CONNECTING ; } } else { state = READY ; } break ; case PICK_FIRST : if ( backendList . isEmpty ( ) ) { pickList = Collections . singletonList ( BUFFER_ENTRY ) ; state = CONNECTING ; } else { checkState ( backendList . size ( ) == 1 , "Excessive backend entries: %s" , backendList ) ; BackendEntry onlyEntry = backendList . get ( 0 ) ; ConnectivityStateInfo stateInfo = onlyEntry . subchannel . getAttributes ( ) . get ( STATE_INFO ) . get ( ) ; state = stateInfo . getState ( ) ; switch ( state ) { case READY : pickList = Collections . < RoundRobinEntry > singletonList ( onlyEntry ) ; break ; case TRANSIENT_FAILURE : pickList = Collections . < RoundRobinEntry > singletonList ( new ErrorEntry ( stateInfo . getStatus ( ) ) ) ; break ; case CONNECTING : pickList = Collections . singletonList ( BUFFER_ENTRY ) ; break ; default : pickList = Collections . < RoundRobinEntry > singletonList ( new IdleSubchannelEntry ( onlyEntry . subchannel ) ) ; } } break ; default : throw new AssertionError ( "Missing case for " + mode ) ; } maybeUpdatePicker ( state , new RoundRobinPicker ( dropList , pickList ) ) ; }
Make and use a picker out of the current lists and the states of subchannels if they have changed since the last picker created .
18,645
private void maybeUpdatePicker ( ConnectivityState state , RoundRobinPicker picker ) { if ( picker . dropList . equals ( currentPicker . dropList ) && picker . pickList . equals ( currentPicker . pickList ) ) { return ; } currentPicker = picker ; logger . log ( ChannelLogLevel . INFO , "{0}: picks={1}, drops={2}" , state , picker . pickList , picker . dropList ) ; helper . updateBalancingState ( state , picker ) ; }
Update the given picker to the helper if it s different from the current one .
18,646
private static EquivalentAddressGroup flattenEquivalentAddressGroup ( List < EquivalentAddressGroup > groupList , Attributes attrs ) { List < SocketAddress > addrs = new ArrayList < > ( ) ; for ( EquivalentAddressGroup group : groupList ) { addrs . addAll ( group . getAddresses ( ) ) ; } return new EquivalentAddressGroup ( addrs , attrs ) ; }
Flattens list of EquivalentAddressGroup objects into one EquivalentAddressGroup object .
18,647
void cancel ( boolean permanent ) { enabled = false ; if ( permanent && wakeUp != null ) { wakeUp . cancel ( false ) ; wakeUp = null ; } }
must be called from channel executor
18,648
private static InetAddress buildBenchmarkAddr ( ) { InetAddress tmp = null ; try { Enumeration < NetworkInterface > networkInterfaces = NetworkInterface . getNetworkInterfaces ( ) ; outer : while ( networkInterfaces . hasMoreElements ( ) ) { NetworkInterface networkInterface = networkInterfaces . nextElement ( ) ; if ( ! networkInterface . isLoopback ( ) ) { continue ; } Enumeration < NetworkInterface > subInterfaces = networkInterface . getSubInterfaces ( ) ; while ( subInterfaces . hasMoreElements ( ) ) { NetworkInterface subLoopback = subInterfaces . nextElement ( ) ; if ( subLoopback . getDisplayName ( ) . contains ( "benchmark" ) ) { tmp = subLoopback . getInetAddresses ( ) . nextElement ( ) ; System . out . println ( "\nResolved benchmark address to " + tmp + " on " + subLoopback . getDisplayName ( ) + "\n\n" ) ; break outer ; } } } } catch ( SocketException se ) { System . out . println ( "\nWARNING: Error trying to resolve benchmark interface \n" + se ) ; } if ( tmp == null ) { try { System . out . println ( "\nWARNING: Unable to resolve benchmark interface, defaulting to localhost" ) ; tmp = InetAddress . getLocalHost ( ) ; } catch ( UnknownHostException uhe ) { throw new RuntimeException ( uhe ) ; } } return tmp ; }
Resolve the address bound to the benchmark interface . Currently we assume it s a child interface of the loopback interface with the term benchmark in its name .
18,649
protected void teardown ( ) throws Exception { logger . fine ( "shutting down channels" ) ; for ( ManagedChannel channel : channels ) { channel . shutdown ( ) ; } logger . fine ( "shutting down server" ) ; server . shutdown ( ) ; if ( ! server . awaitTermination ( 5 , TimeUnit . SECONDS ) ) { logger . warning ( "Failed to shutdown server" ) ; } logger . fine ( "server shut down" ) ; for ( ManagedChannel channel : channels ) { if ( ! channel . awaitTermination ( 1 , TimeUnit . SECONDS ) ) { logger . warning ( "Failed to shutdown client" ) ; } } logger . fine ( "channels shut down" ) ; }
Shutdown all the client channels and then shutdown the server .
18,650
void onTransportIdle ( ) { isActive = false ; if ( shutdownFuture == null ) { return ; } if ( shutdownFuture . isDone ( ) ) { shutdownDelayed = false ; shutdownFuture = scheduler . schedule ( shutdownTask , maxConnectionIdleInNanos , TimeUnit . NANOSECONDS ) ; } else { nextIdleMonitorTime = ticker . nanoTime ( ) + maxConnectionIdleInNanos ; } }
There are no outstanding RPCs on the transport .
18,651
public void start ( final Listener listener ) { if ( listener instanceof Observer ) { start ( ( Observer ) listener ) ; } else { start ( new Observer ( ) { public void onError ( Status error ) { listener . onError ( error ) ; } public void onResult ( ResolutionResult resolutionResult ) { listener . onAddresses ( resolutionResult . getAddresses ( ) , resolutionResult . getAttributes ( ) ) ; } } ) ; } }
Starts the resolution .
18,652
public void addServer ( InternalInstrumented < ServerStats > server ) { ServerSocketMap prev = perServerSockets . put ( id ( server ) , new ServerSocketMap ( ) ) ; assert prev == null ; add ( servers , server ) ; }
Adds a server .
18,653
public void addServerSocket ( InternalInstrumented < ServerStats > server , InternalInstrumented < SocketStats > socket ) { ServerSocketMap serverSockets = perServerSockets . get ( id ( server ) ) ; assert serverSockets != null ; add ( serverSockets , socket ) ; }
Adds a server socket .
18,654
public void removeServer ( InternalInstrumented < ServerStats > server ) { remove ( servers , server ) ; ServerSocketMap prev = perServerSockets . remove ( id ( server ) ) ; assert prev != null ; assert prev . isEmpty ( ) ; }
Removes a server .
18,655
public void removeServerSocket ( InternalInstrumented < ServerStats > server , InternalInstrumented < SocketStats > socket ) { ServerSocketMap socketsOfServer = perServerSockets . get ( id ( server ) ) ; assert socketsOfServer != null ; remove ( socketsOfServer , socket ) ; }
Removes a server socket .
18,656
public ServerList getServers ( long fromId , int maxPageSize ) { List < InternalInstrumented < ServerStats > > serverList = new ArrayList < > ( maxPageSize ) ; Iterator < InternalInstrumented < ServerStats > > iterator = servers . tailMap ( fromId ) . values ( ) . iterator ( ) ; while ( iterator . hasNext ( ) && serverList . size ( ) < maxPageSize ) { serverList . add ( iterator . next ( ) ) ; } return new ServerList ( serverList , ! iterator . hasNext ( ) ) ; }
Returns a server list .
18,657
public ServerSocketsList getServerSockets ( long serverId , long fromId , int maxPageSize ) { ServerSocketMap serverSockets = perServerSockets . get ( serverId ) ; if ( serverSockets == null ) { return null ; } List < InternalWithLogId > socketList = new ArrayList < > ( maxPageSize ) ; Iterator < InternalInstrumented < SocketStats > > iterator = serverSockets . tailMap ( fromId ) . values ( ) . iterator ( ) ; while ( socketList . size ( ) < maxPageSize && iterator . hasNext ( ) ) { socketList . add ( iterator . next ( ) ) ; } return new ServerSocketsList ( socketList , ! iterator . hasNext ( ) ) ; }
Returns socket refs for a server .
18,658
public PersistentHashArrayMappedTrie < K , V > put ( K key , V value ) { if ( root == null ) { return new PersistentHashArrayMappedTrie < > ( new Leaf < > ( key , value ) ) ; } else { return new PersistentHashArrayMappedTrie < > ( root . put ( key , value , key . hashCode ( ) , 0 ) ) ; } }
Returns a new trie where the key is set to the specified value .
18,659
public static String generateFullMethodName ( String fullServiceName , String methodName ) { return checkNotNull ( fullServiceName , "fullServiceName" ) + "/" + checkNotNull ( methodName , "methodName" ) ; }
Generate the fully qualified method name . This matches the name
18,660
public < NewReqT , NewRespT > Builder < NewReqT , NewRespT > toBuilder ( Marshaller < NewReqT > requestMarshaller , Marshaller < NewRespT > responseMarshaller ) { return MethodDescriptor . < NewReqT , NewRespT > newBuilder ( ) . setRequestMarshaller ( requestMarshaller ) . setResponseMarshaller ( responseMarshaller ) . setType ( type ) . setFullMethodName ( fullMethodName ) . setIdempotent ( idempotent ) . setSafe ( safe ) . setSampledToLocalTracing ( sampledToLocalTracing ) . setSchemaDescriptor ( schemaDescriptor ) ; }
Turns this descriptor into a builder replacing the request and response marshallers .
18,661
public static AltsServerBuilder forPort ( int port ) { NettyServerBuilder nettyDelegate = NettyServerBuilder . forAddress ( new InetSocketAddress ( port ) ) ; return new AltsServerBuilder ( nettyDelegate ) ; }
Creates a gRPC server builder for the given port .
18,662
static String makeTargetStringForDirectAddress ( SocketAddress address ) { try { return new URI ( DIRECT_ADDRESS_SCHEME , "" , "/" + address , null ) . toString ( ) ; } catch ( URISyntaxException e ) { throw new RuntimeException ( e ) ; } }
Returns a target string for the SocketAddress . It is only used as a placeholder because DirectAddressNameResolverFactory will not actually try to use it . However it must be a valid URI .
18,663
ClientStream returnStream ( ) { synchronized ( lock ) { if ( returnedStream == null ) { delayedStream = new DelayedStream ( ) ; return returnedStream = delayedStream ; } else { return returnedStream ; } } }
Return a stream on which the RPC will run on .
18,664
@ Setup ( Level . Trial ) public void setup ( ) throws Exception { super . setup ( clientExecutor , ExecutorType . DIRECT , MessageSize . SMALL , responseSize , FlowWindowSize . MEDIUM , ChannelType . NIO , maxConcurrentStreams , channelCount ) ; callCounter = new AtomicLong ( ) ; completed = new AtomicBoolean ( ) ; record = new AtomicBoolean ( ) ; latch = startFlowControlledStreamingCalls ( maxConcurrentStreams , callCounter , record , completed , 1 ) ; }
Setup with direct executors small payloads and the default flow - control window .
18,665
@ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/1704" ) public Set < String > getAdvertisedMessageEncodings ( ) { Set < String > advertisedDecompressors = new HashSet < > ( decompressors . size ( ) ) ; for ( Entry < String , DecompressorInfo > entry : decompressors . entrySet ( ) ) { if ( entry . getValue ( ) . advertised ) { advertisedDecompressors . add ( entry . getKey ( ) ) ; } } return Collections . unmodifiableSet ( advertisedDecompressors ) ; }
Provides a list of all message encodings that have decompressors available and should be advertised .
18,666
@ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public ByteBuf encodeClientHeaders ( ) throws Exception { scratchBuffer . clear ( ) ; Http2Headers headers = Utils . convertClientHeaders ( metadata , scheme , defaultPath , authority , Utils . HTTP_METHOD , userAgent ) ; headersEncoder . encodeHeaders ( 1 , headers , scratchBuffer ) ; return scratchBuffer ; }
This will encode the random metadata fields and repeatedly lookup the default other headers .
18,667
private void sendInitialConnectionWindow ( ) throws Http2Exception { if ( ctx . channel ( ) . isActive ( ) && initialConnectionWindow > 0 ) { Http2Stream connectionStream = connection ( ) . connectionStream ( ) ; int currentSize = connection ( ) . local ( ) . flowController ( ) . windowSize ( connectionStream ) ; int delta = initialConnectionWindow - currentSize ; decoder ( ) . flowController ( ) . incrementWindowSize ( connectionStream , delta ) ; initialConnectionWindow = - 1 ; ctx . flush ( ) ; } }
Sends initial connection window to the remote endpoint if necessary .
18,668
Stats . ClientStats getStats ( ) { Histogram intervalHistogram = recorder . getIntervalHistogram ( ) ; Stats . ClientStats . Builder statsBuilder = Stats . ClientStats . newBuilder ( ) ; Stats . HistogramData . Builder latenciesBuilder = statsBuilder . getLatenciesBuilder ( ) ; double resolution = 1.0 + Math . max ( config . getHistogramParams ( ) . getResolution ( ) , 0.01 ) ; LogarithmicIterator logIterator = new LogarithmicIterator ( intervalHistogram , 1 , resolution ) ; double base = 1 ; while ( logIterator . hasNext ( ) ) { latenciesBuilder . addBucket ( ( int ) logIterator . next ( ) . getCountAddedInThisIterationStep ( ) ) ; base = base * resolution ; } while ( base < config . getHistogramParams ( ) . getMaxPossible ( ) ) { latenciesBuilder . addBucket ( 0 ) ; base = base * resolution ; } latenciesBuilder . setMaxSeen ( intervalHistogram . getMaxValue ( ) ) ; latenciesBuilder . setMinSeen ( intervalHistogram . getMinNonZeroValue ( ) ) ; latenciesBuilder . setCount ( intervalHistogram . getTotalCount ( ) ) ; latenciesBuilder . setSum ( intervalHistogram . getMean ( ) * intervalHistogram . getTotalCount ( ) ) ; statsBuilder . setTimeElapsed ( ( intervalHistogram . getEndTimeStamp ( ) - intervalHistogram . getStartTimeStamp ( ) ) / 1000.0 ) ; if ( osBean != null ) { long nowCpu = osBean . getProcessCpuTime ( ) ; statsBuilder . setTimeUser ( ( ( double ) nowCpu - lastMarkCpuTime ) / 1000000000.0 ) ; lastMarkCpuTime = nowCpu ; } return statsBuilder . build ( ) ; }
Take a snapshot of the statistics which can be returned to the driver .
18,669
void delay ( long alreadyElapsed ) { recorder . recordValue ( alreadyElapsed ) ; if ( distribution != null ) { long nextPermitted = Math . round ( distribution . sample ( ) * 1000000000.0 ) ; if ( nextPermitted > alreadyElapsed ) { LockSupport . parkNanos ( nextPermitted - alreadyElapsed ) ; } } }
Record the event elapsed time to the histogram and delay initiation of the next event based on the load distribution .
18,670
public void getFeature ( int lat , int lon ) { info ( "*** GetFeature: lat={0} lon={1}" , lat , lon ) ; Point request = Point . newBuilder ( ) . setLatitude ( lat ) . setLongitude ( lon ) . build ( ) ; Feature feature ; try { feature = blockingStub . getFeature ( request ) ; if ( testHelper != null ) { testHelper . onMessage ( feature ) ; } } catch ( StatusRuntimeException e ) { warning ( "RPC failed: {0}" , e . getStatus ( ) ) ; if ( testHelper != null ) { testHelper . onRpcError ( e ) ; } return ; } if ( RouteGuideUtil . exists ( feature ) ) { info ( "Found feature called \"{0}\" at {1}, {2}" , feature . getName ( ) , RouteGuideUtil . getLatitude ( feature . getLocation ( ) ) , RouteGuideUtil . getLongitude ( feature . getLocation ( ) ) ) ; } else { info ( "Found no feature at {0}, {1}" , RouteGuideUtil . getLatitude ( feature . getLocation ( ) ) , RouteGuideUtil . getLongitude ( feature . getLocation ( ) ) ) ; } }
Blocking unary call example . Calls getFeature and prints the response .
18,671
public void listFeatures ( int lowLat , int lowLon , int hiLat , int hiLon ) { info ( "*** ListFeatures: lowLat={0} lowLon={1} hiLat={2} hiLon={3}" , lowLat , lowLon , hiLat , hiLon ) ; Rectangle request = Rectangle . newBuilder ( ) . setLo ( Point . newBuilder ( ) . setLatitude ( lowLat ) . setLongitude ( lowLon ) . build ( ) ) . setHi ( Point . newBuilder ( ) . setLatitude ( hiLat ) . setLongitude ( hiLon ) . build ( ) ) . build ( ) ; Iterator < Feature > features ; try { features = blockingStub . listFeatures ( request ) ; for ( int i = 1 ; features . hasNext ( ) ; i ++ ) { Feature feature = features . next ( ) ; info ( "Result #" + i + ": {0}" , feature ) ; if ( testHelper != null ) { testHelper . onMessage ( feature ) ; } } } catch ( StatusRuntimeException e ) { warning ( "RPC failed: {0}" , e . getStatus ( ) ) ; if ( testHelper != null ) { testHelper . onRpcError ( e ) ; } } }
Blocking server - streaming example . Calls listFeatures with a rectangle of interest . Prints each response feature as it arrives .
18,672
public CountDownLatch routeChat ( ) { info ( "*** RouteChat" ) ; final CountDownLatch finishLatch = new CountDownLatch ( 1 ) ; StreamObserver < RouteNote > requestObserver = asyncStub . routeChat ( new StreamObserver < RouteNote > ( ) { public void onNext ( RouteNote note ) { info ( "Got message \"{0}\" at {1}, {2}" , note . getMessage ( ) , note . getLocation ( ) . getLatitude ( ) , note . getLocation ( ) . getLongitude ( ) ) ; if ( testHelper != null ) { testHelper . onMessage ( note ) ; } } public void onError ( Throwable t ) { warning ( "RouteChat Failed: {0}" , Status . fromThrowable ( t ) ) ; if ( testHelper != null ) { testHelper . onRpcError ( t ) ; } finishLatch . countDown ( ) ; } public void onCompleted ( ) { info ( "Finished RouteChat" ) ; finishLatch . countDown ( ) ; } } ) ; try { RouteNote [ ] requests = { newNote ( "First message" , 0 , 0 ) , newNote ( "Second message" , 0 , 1 ) , newNote ( "Third message" , 1 , 0 ) , newNote ( "Fourth message" , 1 , 1 ) } ; for ( RouteNote request : requests ) { info ( "Sending message \"{0}\" at {1}, {2}" , request . getMessage ( ) , request . getLocation ( ) . getLatitude ( ) , request . getLocation ( ) . getLongitude ( ) ) ; requestObserver . onNext ( request ) ; } } catch ( RuntimeException e ) { requestObserver . onError ( e ) ; throw e ; } requestObserver . onCompleted ( ) ; return finishLatch ; }
Bi - directional example which can only be asynchronous . Send some chat messages and print any chat messages that are sent from the server .
18,673
public static void main ( String [ ] args ) throws InterruptedException { List < Feature > features ; try { features = RouteGuideUtil . parseFeatures ( RouteGuideUtil . getDefaultFeaturesFile ( ) ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; return ; } RouteGuideClient client = new RouteGuideClient ( "localhost" , 8980 ) ; try { client . getFeature ( 409146138 , - 746188906 ) ; client . getFeature ( 0 , 0 ) ; client . listFeatures ( 400000000 , - 750000000 , 420000000 , - 730000000 ) ; client . recordRoute ( features , 10 ) ; CountDownLatch finishLatch = client . routeChat ( ) ; if ( ! finishLatch . await ( 1 , TimeUnit . MINUTES ) ) { client . warning ( "routeChat can not finish within 1 minutes" ) ; } } finally { client . shutdown ( ) ; } }
Issues several different requests and then exits .
18,674
private void handleServiceConfigUpdate ( ) { waitingForServiceConfig = false ; serviceConfigInterceptor . handleUpdate ( lastServiceConfig ) ; if ( retryEnabled ) { throttle = ServiceConfigUtil . getThrottlePolicy ( lastServiceConfig ) ; } }
May only be called in constructor or syncContext
18,675
public ManagedChannelImpl shutdown ( ) { channelLogger . log ( ChannelLogLevel . DEBUG , "shutdown() called" ) ; if ( ! shutdown . compareAndSet ( false , true ) ) { return this ; } final class Shutdown implements Runnable { public void run ( ) { channelLogger . log ( ChannelLogLevel . INFO , "Entering SHUTDOWN state" ) ; channelStateManager . gotoState ( SHUTDOWN ) ; } } syncContext . executeLater ( new Shutdown ( ) ) ; uncommittedRetriableStreamsRegistry . onShutdown ( SHUTDOWN_STATUS ) ; final class CancelIdleTimer implements Runnable { public void run ( ) { cancelIdleTimer ( true ) ; } } syncContext . execute ( new CancelIdleTimer ( ) ) ; return this ; }
Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately cancelled .
18,676
public static List < Feature > parseFeatures ( URL file ) throws IOException { InputStream input = file . openStream ( ) ; try { Reader reader = new InputStreamReader ( input , Charset . forName ( "UTF-8" ) ) ; try { FeatureDatabase . Builder database = FeatureDatabase . newBuilder ( ) ; JsonFormat . parser ( ) . merge ( reader , database ) ; return database . getFeatureList ( ) ; } finally { reader . close ( ) ; } } finally { input . close ( ) ; } }
Parses the JSON input file containing the list of features .
18,677
public TransportStats getStats ( ) { long localFlowControlWindow = flowControlWindowReader == null ? - 1 : flowControlWindowReader . read ( ) . localBytes ; long remoteFlowControlWindow = flowControlWindowReader == null ? - 1 : flowControlWindowReader . read ( ) . remoteBytes ; return new TransportStats ( streamsStarted , lastLocalStreamCreatedTimeNanos , lastRemoteStreamCreatedTimeNanos , streamsSucceeded , streamsFailed , messagesSent , messagesReceived . value ( ) , keepAlivesSent , lastMessageSentTimeNanos , lastMessageReceivedTimeNanos , localFlowControlWindow , remoteFlowControlWindow ) ; }
Returns a read only set of current stats .
18,678
public static void main ( String [ ] args ) throws Exception { CustomHeaderClient client = new CustomHeaderClient ( "localhost" , 50051 ) ; try { String user = "world" ; if ( args . length > 0 ) { user = args [ 0 ] ; } client . greet ( user ) ; } finally { client . shutdown ( ) ; } }
Main start the client from the command line .
18,679
public static void asyncUnimplementedUnaryCall ( MethodDescriptor < ? , ? > methodDescriptor , StreamObserver < ? > responseObserver ) { checkNotNull ( methodDescriptor , "methodDescriptor" ) ; checkNotNull ( responseObserver , "responseObserver" ) ; responseObserver . onError ( Status . UNIMPLEMENTED . withDescription ( String . format ( "Method %s is unimplemented" , methodDescriptor . getFullMethodName ( ) ) ) . asRuntimeException ( ) ) ; }
Sets unimplemented status for method on given response stream for unary call .
18,680
public static < T > StreamObserver < T > asyncUnimplementedStreamingCall ( MethodDescriptor < ? , ? > methodDescriptor , StreamObserver < ? > responseObserver ) { asyncUnimplementedUnaryCall ( methodDescriptor , responseObserver ) ; return new NoopStreamObserver < > ( ) ; }
Sets unimplemented status for streaming call .
18,681
public ScheduledFuture < ? > runOnExpiration ( Runnable task , ScheduledExecutorService scheduler ) { checkNotNull ( task , "task" ) ; checkNotNull ( scheduler , "scheduler" ) ; return scheduler . schedule ( task , deadlineNanos - ticker . read ( ) , TimeUnit . NANOSECONDS ) ; }
Schedule a task to be run when the deadline expires .
18,682
private void sendHandshake ( ChannelHandlerContext ctx ) { boolean needToFlush = false ; while ( true ) { buffer = getOrCreateBuffer ( ctx . alloc ( ) ) ; try { handshaker . getBytesToSendToPeer ( buffer ) ; } catch ( GeneralSecurityException e ) { throw new RuntimeException ( e ) ; } if ( ! buffer . isReadable ( ) ) { break ; } needToFlush = true ; @ SuppressWarnings ( "unused" ) Future < ? > possiblyIgnoredError = ctx . write ( buffer ) ; buffer = null ; } if ( needToFlush ) { ctx . flush ( ) ; } }
Sends as many bytes as are available from the handshaker to the remote peer .
18,683
public static < T > T release ( final Resource < T > resource , final T instance ) { return holder . releaseInternal ( resource , instance ) ; }
Releases an instance of the given resource .
18,684
public final OkHttpChannelBuilder enableKeepAlive ( boolean enable ) { if ( enable ) { return keepAliveTime ( DEFAULT_KEEPALIVE_TIME_NANOS , TimeUnit . NANOSECONDS ) ; } else { return keepAliveTime ( KEEPALIVE_TIME_NANOS_DISABLED , TimeUnit . NANOSECONDS ) ; } }
Enable keepalive with default delay and timeout .
18,685
public final OkHttpChannelBuilder connectionSpec ( com . squareup . okhttp . ConnectionSpec connectionSpec ) { Preconditions . checkArgument ( connectionSpec . isTls ( ) , "plaintext ConnectionSpec is not accepted" ) ; this . connectionSpec = Utils . convertSpec ( connectionSpec ) ; return this ; }
For secure connection provides a ConnectionSpec to specify Cipher suite and TLS versions .
18,686
void data ( boolean outFinished , int streamId , Buffer source , boolean flush ) { Preconditions . checkNotNull ( source , "source" ) ; OkHttpClientStream stream = transport . getStream ( streamId ) ; if ( stream == null ) { return ; } OutboundFlowState state = state ( stream ) ; int window = state . writableWindow ( ) ; boolean framesAlreadyQueued = state . hasPendingData ( ) ; int size = ( int ) source . size ( ) ; if ( ! framesAlreadyQueued && window >= size ) { state . write ( source , size , outFinished ) ; } else { if ( ! framesAlreadyQueued && window > 0 ) { state . write ( source , window , false ) ; } state . enqueue ( source , ( int ) source . size ( ) , outFinished ) ; } if ( flush ) { flush ( ) ; } }
Must be called with holding transport lock .
18,687
void writeStreams ( ) { OkHttpClientStream [ ] streams = transport . getActiveStreams ( ) ; int connectionWindow = connectionState . window ( ) ; for ( int numStreams = streams . length ; numStreams > 0 && connectionWindow > 0 ; ) { int nextNumStreams = 0 ; int windowSlice = ( int ) ceil ( connectionWindow / ( float ) numStreams ) ; for ( int index = 0 ; index < numStreams && connectionWindow > 0 ; ++ index ) { OkHttpClientStream stream = streams [ index ] ; OutboundFlowState state = state ( stream ) ; int bytesForStream = min ( connectionWindow , min ( state . unallocatedBytes ( ) , windowSlice ) ) ; if ( bytesForStream > 0 ) { state . allocateBytes ( bytesForStream ) ; connectionWindow -= bytesForStream ; } if ( state . unallocatedBytes ( ) > 0 ) { streams [ nextNumStreams ++ ] = stream ; } } numStreams = nextNumStreams ; } WriteStatus writeStatus = new WriteStatus ( ) ; for ( OkHttpClientStream stream : transport . getActiveStreams ( ) ) { OutboundFlowState state = state ( stream ) ; state . writeBytes ( state . allocatedBytes ( ) , writeStatus ) ; state . clearAllocatedBytes ( ) ; } if ( writeStatus . hasWritten ( ) ) { flush ( ) ; } }
Writes as much data for all the streams as possible given the current flow control windows .
18,688
static String generateTraceSpanName ( boolean isServer , String fullMethodName ) { String prefix = isServer ? "Recv" : "Sent" ; return prefix + "." + fullMethodName . replace ( '/' , '.' ) ; }
Convert a full method name to a tracing span name .
18,689
private void advanceBufferIfNecessary ( ) { ReadableBuffer buffer = buffers . peek ( ) ; if ( buffer . readableBytes ( ) == 0 ) { buffers . remove ( ) . close ( ) ; } }
If the current buffer is exhausted removes and closes it .
18,690
public ServerImpl start ( ) throws IOException { synchronized ( lock ) { checkState ( ! started , "Already started" ) ; checkState ( ! shutdown , "Shutting down" ) ; ServerListenerImpl listener = new ServerListenerImpl ( ) ; for ( InternalServer ts : transportServers ) { ts . start ( listener ) ; activeTransportServers ++ ; } executor = Preconditions . checkNotNull ( executorPool . getObject ( ) , "executor" ) ; started = true ; return this ; } }
Bind and start the server .
18,691
public ServerImpl shutdown ( ) { boolean shutdownTransportServers ; synchronized ( lock ) { if ( shutdown ) { return this ; } shutdown = true ; shutdownTransportServers = started ; if ( ! shutdownTransportServers ) { transportServersTerminated = true ; checkForTermination ( ) ; } } if ( shutdownTransportServers ) { for ( InternalServer ts : transportServers ) { ts . shutdown ( ) ; } } return this ; }
Initiates an orderly shutdown in which preexisting calls continue but new calls are rejected .
18,692
private void transportClosed ( ServerTransport transport ) { synchronized ( lock ) { if ( ! transports . remove ( transport ) ) { throw new AssertionError ( "Transport already removed" ) ; } channelz . removeServerSocket ( ServerImpl . this , transport ) ; checkForTermination ( ) ; } }
Remove transport service from accounting collection and notify of complete shutdown if necessary .
18,693
private void checkForTermination ( ) { synchronized ( lock ) { if ( shutdown && transports . isEmpty ( ) && transportServersTerminated ) { if ( terminated ) { throw new AssertionError ( "Server already terminated" ) ; } terminated = true ; channelz . removeServer ( this ) ; if ( executor != null ) { executor = executorPool . returnObject ( executor ) ; } lock . notifyAll ( ) ; } } }
Notify of complete shutdown if necessary .
18,694
public static ProtocolNegotiator serverPlaintext ( ) { return new ProtocolNegotiator ( ) { public ChannelHandler newHandler ( final GrpcHttp2ConnectionHandler handler ) { class PlaintextHandler extends ChannelHandlerAdapter { public void handlerAdded ( ChannelHandlerContext ctx ) throws Exception { handler . handleProtocolNegotiationCompleted ( Attributes . newBuilder ( ) . set ( Grpc . TRANSPORT_ATTR_REMOTE_ADDR , ctx . channel ( ) . remoteAddress ( ) ) . set ( Grpc . TRANSPORT_ATTR_LOCAL_ADDR , ctx . channel ( ) . localAddress ( ) ) . build ( ) , null ) ; ctx . pipeline ( ) . replace ( this , null , handler ) ; } } return new PlaintextHandler ( ) ; } public void close ( ) { } public AsciiString scheme ( ) { return Utils . HTTP ; } } ; }
Create a server plaintext handler for gRPC .
18,695
void enqueue ( Runnable runnable , boolean flush ) { queue . add ( new RunnableCommand ( runnable ) ) ; if ( flush ) { scheduleFlush ( ) ; } }
Enqueue the runnable . It is not safe for another thread to queue an Runnable directly to the event loop because it will be out - of - order with writes . This method allows the Runnable to be processed in - order with writes .
18,696
private void flush ( ) { try { QueuedCommand cmd ; int i = 0 ; boolean flushedOnce = false ; while ( ( cmd = queue . poll ( ) ) != null ) { cmd . run ( channel ) ; if ( ++ i == DEQUE_CHUNK_SIZE ) { i = 0 ; channel . flush ( ) ; flushedOnce = true ; } } if ( i != 0 || ! flushedOnce ) { channel . flush ( ) ; } } finally { scheduled . set ( false ) ; if ( ! queue . isEmpty ( ) ) { scheduleFlush ( ) ; } } }
Process the queue of commands and dispatch them to the stream . This method is only called in the event loop
18,697
@ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Context doWrite ( ContextState state , Blackhole bh ) { return state . context . withValues ( state . key1 , state . val , state . key2 , state . val , state . key3 , state . val , state . key4 , state . val ) ; }
Perform the write operation .
18,698
public void pingPong ( AdditionalCounters counters ) throws Exception { record . set ( true ) ; Thread . sleep ( 1001 ) ; record . set ( false ) ; }
Measure throughput of unary calls . The calls are already running we just observe a counter of received responses .
18,699
public final void shutdownNow ( Status status ) { shutdown ( status ) ; Collection < PendingStream > savedPendingStreams ; Runnable savedReportTransportTerminated ; synchronized ( lock ) { savedPendingStreams = pendingStreams ; savedReportTransportTerminated = reportTransportTerminated ; reportTransportTerminated = null ; if ( ! pendingStreams . isEmpty ( ) ) { pendingStreams = Collections . emptyList ( ) ; } } if ( savedReportTransportTerminated != null ) { for ( PendingStream stream : savedPendingStreams ) { stream . cancel ( status ) ; } syncContext . execute ( savedReportTransportTerminated ) ; } }
Shuts down this transport and cancels all streams that it owns hence immediately terminates this transport .