idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
13,100
public static Message buildQueryReply ( String leader ) { QueryReply reply = QueryReply . newBuilder ( ) . setLeader ( leader ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . QUERY_LEADER_REPLY ) . setReply ( reply ) . build ( ) ; }
Creates a QUERY_REPLY message .
13,101
public static Message buildJoin ( Zxid lastZxid ) { ZabMessage . Zxid zxid = toProtoZxid ( lastZxid ) ; ZabMessage . Join join = ZabMessage . Join . newBuilder ( ) . setLastZxid ( zxid ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . JOIN ) . setJoin ( join ) . build ( ) ; }
Creates a JOIN message .
13,102
public static ZabMessage . ClusterConfiguration buildConfig ( ClusterConfiguration config ) { ZabMessage . Zxid version = toProtoZxid ( config . getVersion ( ) ) ; return ZabMessage . ClusterConfiguration . newBuilder ( ) . setVersion ( version ) . addAllServers ( config . getPeers ( ) ) . build ( ) ; }
Creates a ZabMessage . ClusterConfiguration object .
13,103
public static Message buildSyncEnd ( ClusterConfiguration config ) { ZabMessage . Zxid version = toProtoZxid ( config . getVersion ( ) ) ; ZabMessage . ClusterConfiguration zConfig = ZabMessage . ClusterConfiguration . newBuilder ( ) . setVersion ( version ) . addAllServers ( config . getPeers ( ) ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . SYNC_END ) . setConfig ( zConfig ) . build ( ) ; }
Creates a SYNC_END message .
13,104
public static Message buildRemove ( String serverId ) { Remove remove = Remove . newBuilder ( ) . setServerId ( serverId ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . REMOVE ) . setRemove ( remove ) . build ( ) ; }
Creates a REMOVE message .
13,105
public static Message buildDelivered ( Zxid deliveredZxid ) { ZabMessage . Zxid zxid = toProtoZxid ( deliveredZxid ) ; ZabMessage . Delivered delivered = ZabMessage . Delivered . newBuilder ( ) . setZxid ( zxid ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . DELIVERED ) . setDelivered ( delivered ) . build ( ) ; }
Creates a DELIVERED message .
13,106
public static Message buildFileHeader ( long length ) { ZabMessage . FileHeader header = ZabMessage . FileHeader . newBuilder ( ) . setLength ( length ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . FILE_HEADER ) . setFileHeader ( header ) . build ( ) ; }
Creates a FILE_HEADER message .
13,107
public static Message buildFileReceived ( String fullPath ) { ZabMessage . FileReceived received = ZabMessage . FileReceived . newBuilder ( ) . setFullPath ( fullPath ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . FILE_RECEIVED ) . setFileReceived ( received ) . build ( ) ; }
Creates a FILE_RECEIVED message .
13,108
public static Message buildFlushRequest ( ByteBuffer body ) { ZabMessage . FlushRequest flushReq = ZabMessage . FlushRequest . newBuilder ( ) . setBody ( ByteString . copyFrom ( body ) ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . FLUSH_REQ ) . setFlushRequest ( flushReq ) . build ( ) ; }
Creates a FLUSH_REQ message .
13,109
public static Message buildFlush ( Zxid lastProposedZxid , ByteBuffer body ) { ZabMessage . Zxid zxid = toProtoZxid ( lastProposedZxid ) ; ZabMessage . Flush flush = ZabMessage . Flush . newBuilder ( ) . setZxid ( zxid ) . setBody ( ByteString . copyFrom ( body ) ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . FLUSH ) . setFlush ( flush ) . build ( ) ; }
Creates a FLUSH message .
13,110
public static Message buildSyncHistory ( Zxid lastZxid ) { ZabMessage . Zxid zxid = toProtoZxid ( lastZxid ) ; ZabMessage . SyncHistory sync = ZabMessage . SyncHistory . newBuilder ( ) . setLastZxid ( zxid ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . SYNC_HISTORY ) . setSyncHistory ( sync ) . build ( ) ; }
Creates a SYNC_HISTORY message . Leader will synchronize everything it has to follower after receiving this message .
13,111
public static Message buildSyncHistoryReply ( int timeout ) { ZabMessage . SyncHistoryReply reply = ZabMessage . SyncHistoryReply . newBuilder ( ) . setSyncTimeout ( timeout ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . SYNC_HISTORY_REPLY ) . setSyncHistoryReply ( reply ) . build ( ) ; }
Creates the SYNC_HISTORY_REPLY message . It s the first time to tell the joiner the synchronization timeout .
13,112
public static Message buildElectionInfo ( String vote , Zxid lastZxid , long ackEpoch , long round , boolean electing ) { ZabMessage . Zxid zxid = toProtoZxid ( lastZxid ) ; ZabMessage . ElectionInfo ei = ZabMessage . ElectionInfo . newBuilder ( ) . setVote ( vote ) . setZxid ( zxid ) . setAckEpoch ( ackEpoch ) . setIsElecting ( electing ) . setRound ( round ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . ELECTION_INFO ) . setElectionInfo ( ei ) . build ( ) ; }
Creates the ELECTION_INFO message .
13,113
public static Message buildSnapshotDone ( String filePath ) { ZabMessage . SnapshotDone done = ZabMessage . SnapshotDone . newBuilder ( ) . setFilePath ( filePath ) . build ( ) ; return Message . newBuilder ( ) . setType ( MessageType . SNAPSHOT_DONE ) . setSnapshotDone ( done ) . build ( ) ; }
Creates the SNAPSHOT_DONE message .
13,114
void deliverPendingFlushes ( Zxid zxid ) { if ( ! flushQueue . isEmpty ( ) ) { while ( flushQueue . peek ( ) != null ) { PendingFlush flush = flushQueue . peek ( ) ; if ( flush . getWaitZxid ( ) . compareTo ( zxid ) <= 0 ) { Tuple tp = pendings . pendingFlushes . remove ( 0 ) ; if ( tp == null ) { throw new RuntimeException ( "There's no element in " + "pendingFlushes." ) ; } Object ctx = tp . ctx ; stateMachine . flushed ( flush . getWaitZxid ( ) , flush . getBody ( ) , ctx ) ; flushQueue . remove ( ) ; } else { break ; } } } }
given zxid .
13,115
public void join ( String peer ) throws Exception { try { List < String > peers = new ArrayList < String > ( ) ; peers . add ( this . serverId ) ; ClusterConfiguration cnf = new ClusterConfiguration ( new Zxid ( 0 , 0 ) , peers , this . serverId ) ; persistence . setLastSeenConfig ( cnf ) ; ByteBuffer cop = cnf . toByteBuffer ( ) ; Transaction txn = new Transaction ( cnf . getVersion ( ) , ProposalType . COP_VALUE , cop ) ; persistence . getLog ( ) . append ( txn ) ; persistence . setProposedEpoch ( 0 ) ; persistence . setAckEpoch ( 0 ) ; this . election . specifyLeader ( this . serverId ) ; changePhase ( Phase . BROADCASTING ) ; broadcasting ( ) ; } catch ( InterruptedException e ) { LOG . debug ( "Participant is canceled by user." ) ; throw e ; } catch ( TimeoutException e ) { LOG . debug ( "Didn't hear message from peers for {} milliseconds. Going" + " back to leader election." , this . config . getTimeoutMs ( ) ) ; } catch ( BackToElectionException e ) { LOG . debug ( "Got GO_BACK message from queue, going back to electing." ) ; } catch ( LeftCluster e ) { LOG . debug ( "Exit running : {}" , e . getMessage ( ) ) ; throw e ; } catch ( Exception e ) { LOG . error ( "Caught exception" , e ) ; throw e ; } finally { changePhase ( Phase . FINALIZING ) ; } }
Starts from joining leader itself .
13,116
void waitProposedEpochFromQuorum ( ) throws InterruptedException , TimeoutException , IOException { ClusterConfiguration currentConfig = persistence . getLastSeenConfig ( ) ; long acknowledgedEpoch = persistence . getAckEpoch ( ) ; while ( this . quorumMap . size ( ) < getQuorumSize ( ) - 1 ) { MessageTuple tuple = filter . getExpectedMessage ( MessageType . PROPOSED_EPOCH , null , config . getTimeoutMs ( ) ) ; Message msg = tuple . getMessage ( ) ; String source = tuple . getServerId ( ) ; ZabMessage . ProposedEpoch epoch = msg . getProposedEpoch ( ) ; ClusterConfiguration peerConfig = ClusterConfiguration . fromProto ( epoch . getConfig ( ) , source ) ; long peerProposedEpoch = epoch . getProposedEpoch ( ) ; long peerAckedEpoch = epoch . getCurrentEpoch ( ) ; int syncTimeoutMs = epoch . getSyncTimeout ( ) ; Zxid peerVersion = peerConfig . getVersion ( ) ; Zxid selfVersion = currentConfig . getVersion ( ) ; if ( ! peerVersion . equals ( selfVersion ) ) { LOG . debug ( "{}'s config version {} is different with leader's {}" , peerVersion , selfVersion ) ; if ( peerAckedEpoch > acknowledgedEpoch || ( peerAckedEpoch == acknowledgedEpoch && peerVersion . compareTo ( selfVersion ) > 0 ) ) { LOG . debug ( "{} probably has right configuration, go back to " + "leader election." , source ) ; throw new BackToElectionException ( ) ; } } if ( ! currentConfig . contains ( source ) ) { LOG . debug ( "Current configuration doesn't contain {}, ignores it." , source ) ; continue ; } if ( this . quorumMap . containsKey ( source ) ) { throw new RuntimeException ( "Quorum set has already contained " + source + ", probably a bug?" ) ; } LOG . debug ( "Got PROPOSED_EPOCH from {}" , source ) ; PeerHandler ph = new PeerHandler ( source , transport , config . getTimeoutMs ( ) / 3 ) ; ph . setLastProposedEpoch ( peerProposedEpoch ) ; ph . setSyncTimeoutMs ( syncTimeoutMs ) ; this . quorumMap . put ( source , ph ) ; } LOG . debug ( "Got proposed epoch from a quorum." ) ; }
Waits until receives the CEPOCH message from the quorum .
13,117
void proposeNewEpoch ( ) throws IOException { long maxEpoch = persistence . getProposedEpoch ( ) ; int maxSyncTimeoutMs = getSyncTimeoutMs ( ) ; for ( PeerHandler ph : this . quorumMap . values ( ) ) { if ( ph . getLastProposedEpoch ( ) > maxEpoch ) { maxEpoch = ph . getLastProposedEpoch ( ) ; } if ( ph . getSyncTimeoutMs ( ) > maxSyncTimeoutMs ) { maxSyncTimeoutMs = ph . getSyncTimeoutMs ( ) ; } } long newEpoch = maxEpoch + 1 ; persistence . setProposedEpoch ( newEpoch ) ; setSyncTimeoutMs ( maxSyncTimeoutMs ) ; LOG . debug ( "Begins proposing new epoch {} with sync timeout {} ms" , newEpoch , getSyncTimeoutMs ( ) ) ; broadcast ( this . quorumMap . keySet ( ) . iterator ( ) , MessageBuilder . buildNewEpochMessage ( newEpoch , getSyncTimeoutMs ( ) ) ) ; }
Finds an epoch number which is higher than any proposed epoch in quorum set and propose the epoch to them .
13,118
void broadcast ( Iterator < String > peers , Message message ) { transport . broadcast ( peers , message ) ; }
Broadcasts the message to all the peers .
13,119
void waitEpochAckFromQuorum ( ) throws InterruptedException , TimeoutException { int ackCount = 0 ; while ( ackCount < this . quorumMap . size ( ) ) { MessageTuple tuple = filter . getExpectedMessage ( MessageType . ACK_EPOCH , null , config . getTimeoutMs ( ) ) ; Message msg = tuple . getMessage ( ) ; String source = tuple . getServerId ( ) ; if ( ! this . quorumMap . containsKey ( source ) ) { LOG . warn ( "The Epoch ACK comes from {} who is not in quorum set, " + "possibly from previous epoch?" , source ) ; continue ; } ackCount ++ ; ZabMessage . AckEpoch ackEpoch = msg . getAckEpoch ( ) ; ZabMessage . Zxid zxid = ackEpoch . getLastZxid ( ) ; PeerHandler ph = this . quorumMap . get ( source ) ; ph . setLastAckedEpoch ( ackEpoch . getAcknowledgedEpoch ( ) ) ; ph . setLastZxid ( MessageBuilder . fromProtoZxid ( zxid ) ) ; } LOG . debug ( "Received ACKs from the quorum set of size {}." , this . quorumMap . size ( ) + 1 ) ; }
Waits until the new epoch is established .
13,120
String selectSyncHistoryOwner ( ) throws IOException { long ackEpoch = persistence . getAckEpoch ( ) ; Zxid zxid = persistence . getLatestZxid ( ) ; String peerId = this . serverId ; Iterator < Map . Entry < String , PeerHandler > > iter ; iter = this . quorumMap . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry < String , PeerHandler > entry = iter . next ( ) ; long fEpoch = entry . getValue ( ) . getLastAckedEpoch ( ) ; Zxid fZxid = entry . getValue ( ) . getLastZxid ( ) ; if ( fEpoch > ackEpoch || ( fEpoch == ackEpoch && fZxid . compareTo ( zxid ) > 0 ) ) { ackEpoch = fEpoch ; zxid = fZxid ; peerId = entry . getKey ( ) ; } } LOG . debug ( "{} has largest acknowledged epoch {} and longest history {}" , peerId , ackEpoch , zxid ) ; if ( this . stateChangeCallback != null ) { this . stateChangeCallback . initialHistoryOwner ( peerId , ackEpoch , zxid ) ; } return peerId ; }
Finds a server who has the largest acknowledged epoch and longest history .
13,121
void synchronizeFromFollower ( String peerId ) throws IOException , TimeoutException , InterruptedException { LOG . debug ( "Begins synchronizing from follower {}." , peerId ) ; Zxid lastZxid = persistence . getLatestZxid ( ) ; Message pullTxn = MessageBuilder . buildPullTxnReq ( lastZxid ) ; LOG . debug ( "Last zxid of {} is {}" , this . serverId , lastZxid ) ; sendMessage ( peerId , pullTxn ) ; waitForSync ( peerId ) ; }
Pulls the history from the server who has the best history .
13,122
void waitNewLeaderAckFromQuorum ( ) throws TimeoutException , InterruptedException , IOException { LOG . debug ( "Waiting for synchronization to followers complete." ) ; int completeCount = 0 ; Zxid lastZxid = persistence . getLatestZxid ( ) ; while ( completeCount < this . quorumMap . size ( ) ) { MessageTuple tuple = filter . getExpectedMessage ( MessageType . ACK , null , getSyncTimeoutMs ( ) ) ; ZabMessage . Ack ack = tuple . getMessage ( ) . getAck ( ) ; String source = tuple . getServerId ( ) ; Zxid zxid = MessageBuilder . fromProtoZxid ( ack . getZxid ( ) ) ; if ( ! this . quorumMap . containsKey ( source ) ) { LOG . warn ( "Quorum set doesn't contain {}, a bug?" , source ) ; continue ; } if ( zxid . compareTo ( lastZxid ) != 0 ) { LOG . error ( "The follower {} is not correctly synchronized." , source ) ; throw new RuntimeException ( "The synchronized follower's last zxid" + "doesn't match last zxid of current leader." ) ; } PeerHandler ph = this . quorumMap . get ( source ) ; ph . setLastAckedZxid ( zxid ) ; completeCount ++ ; } }
Waits for synchronization to followers complete .
13,123
void beginSynchronizing ( ) throws IOException { Zxid lastZxid = persistence . getLatestZxid ( ) ; ClusterConfiguration clusterConfig = persistence . getLastSeenConfig ( ) ; long proposedEpoch = persistence . getProposedEpoch ( ) ; for ( PeerHandler ph : this . quorumMap . values ( ) ) { ph . setSyncTask ( new SyncPeerTask ( ph . getServerId ( ) , ph . getLastZxid ( ) , lastZxid , clusterConfig ) , proposedEpoch ) ; ph . startSynchronizingTask ( ) ; } }
Starts synchronizing peers in background threads .
13,124
void broadcasting ( ) throws TimeoutException , InterruptedException , IOException , ExecutionException { broadcastingInit ( ) ; try { while ( this . quorumMap . size ( ) >= clusterConfig . getQuorumSize ( ) ) { MessageTuple tuple = filter . getMessage ( config . getTimeoutMs ( ) ) ; Message msg = tuple . getMessage ( ) ; String source = tuple . getServerId ( ) ; if ( msg . getType ( ) == MessageType . DISCONNECTED ) { String peerId = msg . getDisconnected ( ) . getServerId ( ) ; if ( quorumMap . containsKey ( peerId ) ) { onDisconnected ( tuple ) ; } else { this . transport . clear ( peerId ) ; } continue ; } if ( ! quorumMap . containsKey ( source ) ) { handleMessageOutsideQuorum ( tuple ) ; } else { handleMessageFromQuorum ( tuple ) ; PeerHandler ph = quorumMap . get ( source ) ; if ( ph != null ) { ph . updateHeartbeatTime ( ) ; } checkFollowerLiveness ( ) ; } } LOG . debug ( "Detects the size of the ensemble is less than the" + "quorum size {}, goes back to electing phase." , getQuorumSize ( ) ) ; } finally { ackProcessor . shutdown ( ) ; preProcessor . shutdown ( ) ; commitProcessor . shutdown ( ) ; syncProcessor . shutdown ( ) ; snapProcessor . shutdown ( ) ; this . lastDeliveredZxid = commitProcessor . getLastDeliveredZxid ( ) ; this . participantState . updateLastDeliveredZxid ( this . lastDeliveredZxid ) ; } }
Entering broadcasting phase leader broadcasts proposal to followers .
13,125
private Zxid getNextProposedZxid ( ) { if ( lastProposedZxid . getEpoch ( ) != establishedEpoch ) { lastProposedZxid = new Zxid ( establishedEpoch , - 1 ) ; } lastProposedZxid = new Zxid ( establishedEpoch , lastProposedZxid . getXid ( ) + 1 ) ; return lastProposedZxid ; }
Gets next proposed zxid for leader in broadcasting phase .
13,126
private static boolean isCompilationDisabledCondition ( Expression condition ) { Object conditionValue = condition . accept ( new ConditionalCompilationConditionEvaluator ( ) , null ) ; return Boolean . FALSE . equals ( conditionValue ) ; }
Is value of expression definitely false following conditional compilation rules?
13,127
private static void includeColumnRecursive ( List < OrcProto . Type > types , boolean [ ] result , int typeId ) { result [ typeId ] = true ; OrcProto . Type type = types . get ( typeId ) ; int children = type . getSubtypesCount ( ) ; for ( int i = 0 ; i < children ; ++ i ) { includeColumnRecursive ( types , result , type . getSubtypes ( i ) ) ; } }
Recurse down into a type subtree turning on all of the sub - columns .
13,128
private static boolean [ ] findIncludedColumns ( List < OrcProto . Type > types , Configuration conf ) { String includedStr = conf . get ( ColumnProjectionUtils . READ_COLUMN_IDS_CONF_STR ) ; if ( includedStr == null || includedStr . trim ( ) . length ( ) == 0 ) { return null ; } else { int numColumns = types . size ( ) ; boolean [ ] result = new boolean [ numColumns ] ; result [ 0 ] = true ; OrcProto . Type root = types . get ( 0 ) ; List < Integer > included = ColumnProjectionUtils . getReadColumnIDs ( conf ) ; for ( int i = 0 ; i < root . getSubtypesCount ( ) ; ++ i ) { if ( included . contains ( i ) ) { includeColumnRecursive ( types , result , root . getSubtypes ( i ) ) ; } } for ( boolean include : result ) { if ( ! include ) { return result ; } } return null ; } }
Take the configuration and figure out which columns we need to include .
13,129
public void shutdown ( ) throws InterruptedException { try { channel . close ( ) ; for ( Map . Entry < String , Sender > entry : senders . entrySet ( ) ) { entry . getValue ( ) . shutdown ( ) ; } senders . clear ( ) ; for ( Map . Entry < String , ChannelHandlerContext > entry : receivers . entrySet ( ) ) { entry . getValue ( ) . close ( ) ; } receivers . clear ( ) ; } finally { try { long quietPeriodSec = 0 ; long timeoutSec = 10 ; io . netty . util . concurrent . Future wf = workerGroup . shutdownGracefully ( quietPeriodSec , timeoutSec , TimeUnit . SECONDS ) ; io . netty . util . concurrent . Future bf = bossGroup . shutdownGracefully ( quietPeriodSec , timeoutSec , TimeUnit . SECONDS ) ; wf . await ( ) ; bf . await ( ) ; LOG . debug ( "Shutdown complete: {}" , hostPort ) ; } catch ( InterruptedException ex ) { LOG . debug ( "Interrupted while shutting down NioEventLoopGroup" , ex ) ; } } }
Destroys the transport .
13,130
private List < Map . Entry < StreamName , BufferedStream > > cleanUpStreams ( ) throws IOException { List < Map . Entry < StreamName , BufferedStream > > streamList = new ArrayList < Map . Entry < StreamName , BufferedStream > > ( streams . size ( ) ) ; Map < StreamName , Integer > indexMap = new HashMap < StreamName , Integer > ( streams . size ( ) ) ; int increment = 0 ; for ( Map . Entry < StreamName , BufferedStream > pair : streams . entrySet ( ) ) { if ( ! pair . getValue ( ) . isSuppressed ( ) ) { StreamName name = pair . getKey ( ) ; if ( name . getKind ( ) == Kind . LENGTH ) { Integer index = indexMap . get ( new StreamName ( name . getColumn ( ) , Kind . DICTIONARY_DATA ) ) ; if ( index != null ) { streamList . add ( index + increment , pair ) ; increment ++ ; continue ; } } indexMap . put ( name , new Integer ( streamList . size ( ) ) ) ; streamList . add ( pair ) ; } else { pair . getValue ( ) . clear ( ) ; } } return streamList ; }
read the data .
13,131
public Object next ( Object previous ) throws IOException { DoubleWritable result = null ; if ( valuePresent ) { result = createWritable ( previous , readDouble ( ) ) ; } return result ; }
Give the next double as a Writable object .
13,132
public void fill ( byte value ) { int offset = 0 ; int length = size ; long longValue = Longs . fromBytes ( value , value , value , value , value , value , value , value ) ; while ( length >= SizeOf . SIZE_OF_LONG ) { unsafe . putLong ( base , address + offset , longValue ) ; offset += SizeOf . SIZE_OF_LONG ; length -= SizeOf . SIZE_OF_LONG ; } while ( length > 0 ) { unsafe . putByte ( base , address + offset , value ) ; offset ++ ; length -- ; } }
Fill the slice with the specified value ;
13,133
public byte [ ] getBytes ( int index , int length ) { byte [ ] bytes = new byte [ length ] ; getBytes ( index , bytes , 0 , length ) ; return bytes ; }
Returns a copy of this buffer as a byte array .
13,134
public Slice slice ( int index , int length ) { if ( ( index == 0 ) && ( length == length ( ) ) ) { return this ; } checkIndexLength ( index , length ) ; if ( length == 0 ) { return Slices . EMPTY_SLICE ; } return new Slice ( base , address + index , length , reference ) ; }
Returns a slice of this buffer s sub - region . Modifying the content of the returned buffer or this buffer affects each other s content .
13,135
@ SuppressWarnings ( "ObjectEquality" ) public int compareTo ( int offset , int length , Slice that , int otherOffset , int otherLength ) { return compareTo ( offset , length , that . base , otherOffset , otherLength ) ; }
Compares a portion of this slice with a portion of the specified slice . Equality is solely based on the contents of the slice .
13,136
synchronized void addWriter ( final Path path , final long requestedAllocation , final Callback callback , final long initialAllocation ) throws IOException { WriterInfo oldVal = writerList . get ( path ) ; if ( oldVal == null ) { LOG . info ( "Registering writer for path " + path . toString ( ) ) ; oldVal = new WriterInfo ( requestedAllocation , callback ) ; writerList . put ( path , oldVal ) ; totalAllocation += requestedAllocation ; } else { totalAllocation += requestedAllocation - oldVal . allocation ; oldVal . setAllocation ( requestedAllocation ) ; oldVal . setCallback ( callback ) ; } updateScale ( true ) ; if ( ! lowMemoryMode && requestedAllocation * currentScale <= initialAllocation ) { lowMemoryMode = true ; LOG . info ( "ORC: Switching to low memory mode" ) ; for ( WriterInfo writer : writerList . values ( ) ) { writer . callback . enterLowMemoryMode ( ) ; } } }
Add a new writer s memory allocation to the pool . We use the path as a unique key to ensure that we don t get duplicates .
13,137
synchronized void removeWriter ( Path path ) throws IOException { WriterInfo val = writerList . get ( path ) ; if ( val != null ) { LOG . info ( "Unregeristering writer for path " + path . toString ( ) ) ; writerList . remove ( path ) ; totalAllocation -= val . allocation ; updateScale ( false ) ; } }
Remove the given writer from the pool .
13,138
private synchronized void notifyWriters ( ) throws IOException { LOG . debug ( "Notifying writers after " + rowsAddedSinceCheck ) ; for ( WriterInfo writer : writerList . values ( ) ) { if ( lowMemoryMode ) { if ( writer . flushedCount == 0 ) { writersForDeallocation . add ( writer ) ; } else if ( writer . flushedCount >= 2 ) { writersForAllocation . add ( writer ) ; } writer . resetFlushedCount ( ) ; } } if ( lowMemoryMode ) { reallocateMemory ( writersForAllocation , writersForDeallocation ) ; writersForDeallocation . clear ( ) ; writersForAllocation . clear ( ) ; } rowsAddedSinceCheck = 0 ; }
Notify all of the writers that they should check their memory usage .
13,139
protected void grow ( int index ) { if ( ( index * literalSize ) + ( literalSize - 1 ) >= data . length ( ) ) { int newSize = Math . max ( ( index * literalSize ) + defaultSize , 2 * data . length ( ) ) ; Slice newSlice = Slices . allocate ( newSize ) ; newSlice . setBytes ( 0 , data ) ; setData ( newSlice ) ; } }
Ensure that the given index is valid .
13,140
public static void read ( FSDataInputStream file , long fileOffset , byte [ ] array , int arrayOffset , int length ) throws IOException { file . seek ( fileOffset ) ; file . readFully ( array , arrayOffset , length ) ; }
reads at some point .
13,141
public static List < Method > findOverriddenMethods ( MethodDeclaration md ) { final List < Method > methods = new ArrayList < Method > ( ) ; collectOverriddenMethods ( md , methods ) ; return methods . isEmpty ( ) ? Collections . < Method > emptyList ( ) : Collections . unmodifiableList ( methods ) ; }
Returns the methods overridden by given method declaration
13,142
private static boolean collectOverriddenMethods ( MethodDeclaration md , List < Method > overriddenMethods ) { final MethodSymbolData sdata = md . getSymbolData ( ) ; if ( sdata == null || isStatic ( sdata . getMethod ( ) ) || isPrivate ( sdata . getMethod ( ) ) ) { return false ; } else { boolean result = false ; final Class < ? > declaringClass = sdata . getMethod ( ) . getDeclaringClass ( ) ; final Class < ? > parentClass = declaringClass . getSuperclass ( ) ; final Class < ? > [ ] interfaces = declaringClass . getInterfaces ( ) ; if ( parentClass != null || interfaces . length > 0 ) { final SymbolData [ ] args = getParameterSymbolData ( md ) ; List < Class < ? > > scopesToCheck = new LinkedList < Class < ? > > ( ) ; if ( parentClass != null ) { scopesToCheck . add ( parentClass ) ; } for ( int i = 0 ; i < interfaces . length ; i ++ ) { scopesToCheck . add ( interfaces [ i ] ) ; } final Iterator < Class < ? > > it = scopesToCheck . iterator ( ) ; while ( it . hasNext ( ) && ! result ) { final Class < ? > clazzToAnalyze = it . next ( ) ; final Method foundMethod = MethodInspector . findMethod ( clazzToAnalyze , args , md . getName ( ) ) ; if ( foundMethod != null ) { if ( foundMethod . getDeclaringClass ( ) . isAssignableFrom ( clazzToAnalyze ) ) { List < Type > types = ClassInspector . getInterfaceOrSuperclassImplementations ( declaringClass , clazzToAnalyze ) ; Class < ? > returnType = null ; if ( types != null && ! types . isEmpty ( ) ) { if ( types . get ( 0 ) instanceof Class ) { returnType = ( Class < ? > ) types . get ( 0 ) ; } } if ( matchesReturnAndParameters ( foundMethod , returnType , args ) ) { if ( overriddenMethods != null ) { overriddenMethods . add ( foundMethod ) ; } else { result = true ; } } } } } } return overriddenMethods != null ? ! overriddenMethods . isEmpty ( ) : result ; } }
Returns if any of the overriddenMethods overrides an specific method declaration .
13,143
private short readShort ( ) throws IOException { latestRead = ( short ) SerializationUtils . readIntegerType ( input , WriterImpl . SHORT_BYTE_SIZE , true , input . useVInts ( ) ) ; return latestRead ; }
Read a short value from the stream .
13,144
public void broadcast ( Iterator < String > peers , Message message ) { while ( peers . hasNext ( ) ) { send ( peers . next ( ) , message ) ; } }
Broadcasts a message to a set of peers .
13,145
private void addPreliminaryThis ( Scope scope , Symbol symbol , TypeDeclaration type ) { Symbol < TypeDeclaration > thisSymbol = new Symbol < TypeDeclaration > ( "this" , symbol . getType ( ) , type , ReferenceType . VARIABLE ) ; thisSymbol . setInnerScope ( scope ) ; scope . addSymbol ( thisSymbol ) ; }
preliminary this to allow depth first inheritance tree scope loading
13,146
protected MessageTuple getMessage ( int timeoutMs ) throws InterruptedException , TimeoutException { MessageTuple tuple = messageQueue . poll ( timeoutMs , TimeUnit . MILLISECONDS ) ; if ( tuple == null ) { throw new TimeoutException ( "Timeout while waiting for the message." ) ; } if ( tuple . getMessage ( ) . getType ( ) == MessageType . SHUT_DOWN ) { throw new LeftCluster ( "Left cluster" ) ; } return tuple ; }
Takes the filtered message from message queue . This method will be blocked until the message becomes available or timeout is detected .
13,147
protected MessageTuple getExpectedMessage ( MessageType type , String source , int timeoutMs ) throws TimeoutException , InterruptedException { int startTime = ( int ) ( System . nanoTime ( ) / 1000000 ) ; while ( true ) { MessageTuple tuple = getMessage ( timeoutMs ) ; String from = tuple . getServerId ( ) ; if ( tuple . getMessage ( ) . getType ( ) == type && ( source == null || source . equals ( from ) ) ) { return tuple ; } else { int curTime = ( int ) ( System . nanoTime ( ) / 1000000 ) ; if ( curTime - startTime >= timeoutMs ) { throw new TimeoutException ( "Timeout in getExpectedMessage." ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Got an unexpected message from {}: {}" , tuple . getServerId ( ) , TextFormat . shortDebugString ( tuple . getMessage ( ) ) ) ; } } } }
Takes the expected message from message queue . This method will be blocked until the expected message from the expected source becomes available or timeout is detected .
13,148
private int getSizeOfIntArrays ( ) { return ( offsets . length + hashcodes . length + nexts . length + counts . length + indexStrides . length ) * 4 ; }
Returns the size of the int arrays used by this class it s 4 times the length of the arrays
13,149
public void clear ( ) { memoryEstimate . decrementDictionaryMemory ( byteArray . size ( ) ) ; byteArray . clear ( ) ; memoryEstimate . incrementDictionaryMemory ( byteArray . size ( ) ) ; htDictionary . clear ( ) ; memoryEstimate . decrementTotalMemory ( getSizeOfIntArrays ( ) ) ; offsets = new int [ DynamicIntArray . DEFAULT_SIZE ] ; hashcodes = new int [ DynamicIntArray . DEFAULT_SIZE ] ; nexts = new int [ DynamicIntArray . DEFAULT_SIZE ] ; counts = new int [ DynamicIntArray . DEFAULT_SIZE ] ; indexStrides = new int [ DynamicIntArray . DEFAULT_SIZE ] ; memoryEstimate . incrementTotalMemory ( getSizeOfIntArrays ( ) ) ; numElements = 0 ; }
Reset the table to empty .
13,150
private void maybeIndexResource ( String relPath , URL delegate ) { if ( ! index . containsKey ( relPath ) ) { index . put ( relPath , delegate ) ; if ( relPath . endsWith ( File . separator ) ) { maybeIndexResource ( relPath . substring ( 0 , relPath . length ( ) - File . separator . length ( ) ) , delegate ) ; } } }
Callers may request the directory itself as a resource and may do so with or without trailing slashes . We do this in a while - loop in case the classpath element has multiple superfluous trailing slashes .
13,151
public static void writeLongToFile ( long value , File file ) throws IOException { File temp = File . createTempFile ( file . getName ( ) , null , file . getAbsoluteFile ( ) . getParentFile ( ) ) ; try ( FileOutputStream fos = new FileOutputStream ( temp ) ; OutputStreamWriter os = new OutputStreamWriter ( fos , Charset . forName ( "UTF-8" ) ) ; PrintWriter pw = new PrintWriter ( os ) ) { pw . print ( Long . toString ( value ) ) ; fos . getChannel ( ) . force ( true ) ; } atomicMove ( temp , file ) ; LOG . debug ( "Atomically moved {} to {}" , temp , file ) ; }
Atomically writes a long integer to a file .
13,152
public static void writePropertiesToFile ( Properties prop , File file ) throws IOException { File temp = File . createTempFile ( file . getName ( ) , null , file . getAbsoluteFile ( ) . getParentFile ( ) ) ; try ( FileOutputStream fos = new FileOutputStream ( temp ) ) { prop . store ( fos , "" ) ; fos . getChannel ( ) . force ( true ) ; } atomicMove ( temp , file ) ; LOG . debug ( "Atomically moved {} to {}" , temp , file ) ; }
Atomically writes properties to a file .
13,153
public static void atomicMove ( File source , File dest ) throws IOException { Files . move ( source . toPath ( ) , dest . toPath ( ) , ATOMIC_MOVE , REPLACE_EXISTING ) ; }
Atomically move one file to another file .
13,154
public void send ( ByteBuffer request , Object ctx ) throws InvalidPhase , TooManyPendingRequests { this . mainThread . send ( request , ctx ) ; }
Submits a request to Zab . Under the hood followers forward requests to the leader and the leader will be responsible for converting this request to idempotent transaction and broadcasting . If you send request in non - broadcasting phase the operation will fail .
13,155
public void flush ( ByteBuffer request , Object ctx ) throws InvalidPhase , TooManyPendingRequests { this . mainThread . flush ( request , ctx ) ; }
Flushes a request through pipeline . The flushed request will be delivered in order with other sending requests but it will not be convereted to idempotent transaction and will not be persisted in log . And it will only be delivered on the server who issued this request . The purpose of flush is to allow implementing a consistent read - after - write . If you send flush request in non - broadcasting phase the operation will fail .
13,156
public void remove ( String peerId , Object ctx ) throws InvalidPhase , TooManyPendingRequests { this . mainThread . remove ( peerId , ctx ) ; }
Removes a peer from the cluster . If you send remove request in non - broadcasting phase the operation will fail .
13,157
protected long countNonNulls ( long rows ) throws IOException { if ( present != null ) { long result = 0 ; for ( long c = 0 ; c < rows ; ++ c ) { if ( present . next ( ) == 1 ) { result += 1 ; } } return result ; } else { return rows ; } }
in the next rows values returns the number of values which are not null
13,158
public boolean nextIsNull ( long currentRow ) throws IOException { if ( present != null ) { seekToPresentRow ( currentRow ) ; valuePresent = present . next ( ) == 1 ; if ( valuePresent ) { numNonNulls ++ ; } else { if ( currentRow == previousRow + 1 ) { previousRow ++ ; } } } return ! valuePresent ; }
Returns whether or not the value corresponding to currentRow is null suitable for calling from outside
13,159
protected void seekToPresentRow ( long currentRow ) throws IOException { if ( currentRow != previousPresentRow + 1 ) { long rowInStripe = currentRow - rowBaseInStripe - 1 ; int rowIndexEntry = computeRowIndexEntry ( currentRow ) ; if ( rowIndexEntry != computeRowIndexEntry ( previousPresentRow ) || currentRow < previousPresentRow ) { seek ( rowIndexEntry , currentRow < previousPresentRow ) ; numNonNulls = countNonNulls ( rowInStripe - ( rowIndexEntry * rowIndexStride ) ) ; } else { numNonNulls += countNonNulls ( currentRow - previousPresentRow - 1 ) ; } } if ( ( currentRow - rowBaseInStripe - 1 ) % rowIndexStride == 0 ) { numNonNulls = 0 ; } previousPresentRow = currentRow ; }
Shifts only the present stream so that next will return the value for currentRow
13,160
public Object get ( long currentRow , Object previous ) throws IOException { seekToRow ( currentRow ) ; return next ( previous ) ; }
Returns the value corresponding to currentRow suitable for calling from outside
13,161
protected void seek ( int rowIndexEntry , boolean backwards ) throws IOException { if ( backwards || rowIndexEntry != computeRowIndexEntry ( previousRow ) ) { previousRowIndexEntry = rowIndexEntry ; if ( present != null && ( backwards || rowIndexEntry != computeRowIndexEntry ( previousPresentRow ) ) ) { present . seek ( rowIndexEntry ) ; previousPresentRow = rowBaseInStripe + rowIndexEntry * rowIndexStride - 1 ; } seek ( rowIndexEntry ) ; previousRow = rowBaseInStripe + rowIndexEntry * rowIndexStride - 1 ; } }
Adjust all streams to the beginning of the row index entry specified backwards means that a previous value is being read and forces the index entry to be restarted otherwise has no effect if we re already in the current index entry
13,162
protected boolean seekToRow ( long currentRow ) throws IOException { boolean seeked = false ; if ( currentRow != previousPresentRow ) { nextIsNull ( currentRow ) ; } if ( valuePresent ) { if ( currentRow != previousRow + 1 ) { numNonNulls -- ; long rowInStripe = currentRow - rowBaseInStripe - 1 ; int rowIndexEntry = computeRowIndexEntry ( currentRow ) ; if ( ( previousRow != rowIndexEntry * rowIndexStride - 1 && rowIndexEntry != computeRowIndexEntry ( previousRow ) ) || currentRow < previousRow ) { if ( present == null ) { previousRowIndexEntry = rowIndexEntry ; numNonNulls = countNonNulls ( rowInStripe - ( rowIndexEntry * rowIndexStride ) ) ; } seek ( rowIndexEntry , currentRow <= previousRow ) ; skipRows ( numNonNulls ) ; } else { if ( present == null ) { numNonNulls = currentRow - previousRow - 1 ; } skipRows ( numNonNulls ) ; } seeked = true ; } numNonNulls = 0 ; previousRow = currentRow ; } return seeked ; }
Adjusts all streams so that the next value returned corresponds to the value for currentRow suitable for calling from outside
13,163
public int loadIndeces ( List < RowIndexEntry > rowIndexEntries , int startIndex ) { if ( present != null ) { return present . loadIndeces ( rowIndexEntries , startIndex ) ; } else { return startIndex ; } }
Read any indeces that will be needed and return a startIndex after the values that have been read .
13,164
public int loadIndeces ( List < RowIndexEntry > rowIndexEntries , int startIndex ) { int updatedStartIndex = input . loadIndeces ( rowIndexEntries , startIndex ) ; int numIndeces = rowIndexEntries . size ( ) ; indeces = new int [ numIndeces + 1 ] ; int i = 0 ; for ( RowIndexEntry rowIndexEntry : rowIndexEntries ) { indeces [ i ] = ( int ) rowIndexEntry . getPositions ( updatedStartIndex ) ; i ++ ; } return updatedStartIndex + 1 ; }
Read in the number of bytes consumed at each index entry and store it also call loadIndeces on child stream and return the index of the next streams indexes .
13,165
public int add ( byte [ ] value , int valueOffset , int valueLength ) { grow ( length + valueLength ) ; data . setBytes ( length , value , valueOffset , valueLength ) ; int result = length ; length += valueLength ; return result ; }
Copy a slice of a byte array into our buffer .
13,166
public void readAll ( InputStream in ) throws IOException { int read = 0 ; do { grow ( length ) ; read = data . setBytes ( length , in , data . length ( ) - length ) ; if ( read > 0 ) { length += read ; } } while ( in . available ( ) > 0 ) ; }
Read the entire stream into this array .
13,167
public void read ( InputStream in , int lengthToRead ) throws IOException { int read = 0 ; do { grow ( length ) ; read = data . setBytes ( length , in , Math . min ( lengthToRead , data . length ( ) - length ) ) ; length += read ; lengthToRead -= read ; } while ( lengthToRead > 0 ) ; }
Read lengthToRead bytes from the input stream into this array
13,168
public int compare ( byte [ ] other , int otherOffset , int otherLength , int ourOffset , int ourLength ) { return 0 - data . compareTo ( ourOffset , ourLength , other , otherOffset , otherLength ) ; }
Byte compare a set of bytes against the bytes in this dynamic array .
13,169
public void setText ( Text result , int offset , int length ) { result . clear ( ) ; result . set ( data . getBytes ( ) , offset , length ) ; }
Set a text value from the bytes in this dynamic array .
13,170
public void write ( OutputStream out , int offset , int length ) throws IOException { data . getBytes ( offset , out , length ) ; }
Write out a range of this dynamic array to an output stream .
13,171
long getAckEpoch ( ) throws IOException { try { long ackEpoch = FileUtils . readLongFromFile ( this . fAckEpoch ) ; return ackEpoch ; } catch ( FileNotFoundException e ) { LOG . debug ( "File not exist, initialize acknowledged epoch to -1" ) ; return - 1 ; } catch ( IOException e ) { LOG . error ( "IOException encountered when access acknowledged epoch" ) ; throw e ; } }
Gets the last acknowledged epoch .
13,172
long getProposedEpoch ( ) throws IOException { try { long pEpoch = FileUtils . readLongFromFile ( this . fProposedEpoch ) ; return pEpoch ; } catch ( FileNotFoundException e ) { LOG . debug ( "File not exist, initialize acknowledged epoch to -1" ) ; return - 1 ; } catch ( IOException e ) { LOG . error ( "IOException encountered when access acknowledged epoch" ) ; throw e ; } }
Gets the last proposed epoch .
13,173
ClusterConfiguration getLastSeenConfig ( ) throws IOException { File file = getLatestFileWithPrefix ( this . rootDir , "cluster_config" ) ; if ( file == null ) { return null ; } try { Properties prop = FileUtils . readPropertiesFromFile ( file ) ; return ClusterConfiguration . fromProperties ( prop ) ; } catch ( FileNotFoundException e ) { LOG . debug ( "AckConfig file doesn't exist, probably it's the first time" + "bootup." ) ; } return null ; }
Gets last seen configuration .
13,174
ClusterConfiguration getLastConfigWithin ( Zxid zxid ) throws IOException { String pattern = "cluster_config\\.\\d+_-?\\d+" ; String zxidFileName = "cluster_config." + zxid . toSimpleString ( ) ; String lastFileName = null ; for ( File file : this . rootDir . listFiles ( ) ) { if ( ! file . isDirectory ( ) && file . getName ( ) . matches ( pattern ) ) { String fileName = file . getName ( ) ; if ( lastFileName == null && fileName . compareTo ( zxidFileName ) <= 0 ) { lastFileName = fileName ; } else if ( lastFileName != null && fileName . compareTo ( lastFileName ) > 0 && fileName . compareTo ( zxidFileName ) <= 0 ) { lastFileName = fileName ; } } } if ( lastFileName == null ) { return null ; } File file = new File ( this . rootDir , lastFileName ) ; try { Properties prop = FileUtils . readPropertiesFromFile ( file ) ; return ClusterConfiguration . fromProperties ( prop ) ; } catch ( FileNotFoundException e ) { LOG . debug ( "AckConfig file doesn't exist, probably it's the first time" + "bootup." ) ; } return null ; }
Gets the last configuration which has version equal or smaller than zxid .
13,175
void setLastSeenConfig ( ClusterConfiguration conf ) throws IOException { String version = conf . getVersion ( ) . toSimpleString ( ) ; File file = new File ( rootDir , String . format ( "cluster_config.%s" , version ) ) ; FileUtils . writePropertiesToFile ( conf . toProperties ( ) , file ) ; fsyncDirectory ( ) ; }
Updates the last seen configuration .
13,176
File setSnapshotFile ( File tempFile , Zxid zxid ) throws IOException { File snapshot = new File ( dataDir , String . format ( "snapshot.%s" , zxid . toSimpleString ( ) ) ) ; LOG . debug ( "Atomically move snapshot file to {}" , snapshot ) ; FileUtils . atomicMove ( tempFile , snapshot ) ; fsyncDirectory ( ) ; return snapshot ; }
Turns a temporary snapshot file into a valid snapshot file .
13,177
Zxid getSnapshotZxid ( ) { File snapshot = getSnapshotFile ( ) ; if ( snapshot == null ) { return Zxid . ZXID_NOT_EXIST ; } String fileName = snapshot . getName ( ) ; String strZxid = fileName . substring ( fileName . indexOf ( '.' ) + 1 ) ; return Zxid . fromSimpleString ( strZxid ) ; }
Gets the last zxid of transaction which is guaranteed in snapshot .
13,178
void endStateTransfer ( ) throws IOException { File nextDir = getNextDataDir ( ) ; FileUtils . atomicMove ( this . dataDir , nextDir ) ; this . dataDir = nextDir ; this . log = createLog ( dataDir ) ; fsyncDirectory ( ) ; this . isTransferring = false ; }
Ends state transferring mode after calling this function all the txns and snapshots persisted during the transferring mode will be visible from now .
13,179
File getNextDataDir ( ) { File latest = getLatestDataDir ( ) ; long newID ; if ( latest == null ) { newID = 0 ; } else { newID = Long . parseLong ( latest . getName ( ) . substring ( 4 ) ) + 1 ; } String suffix = String . format ( "%015d" , newID ) ; return new File ( this . rootDir , "data" + suffix ) ; }
Gets the next data directory .
13,180
void cleanupClusterConfigFiles ( ) throws IOException { Zxid latestZxid = getLatestZxid ( ) ; List < File > files = getFilesWithPrefix ( this . rootDir , "cluster_config" ) ; if ( files . isEmpty ( ) ) { LOG . error ( "There's no cluster_config files in log directory." ) ; throw new RuntimeException ( "There's no cluster_config files!" ) ; } Iterator < File > iter = files . iterator ( ) ; while ( iter . hasNext ( ) ) { File file = iter . next ( ) ; String fileName = file . getName ( ) ; String strZxid = fileName . substring ( fileName . indexOf ( '.' ) + 1 ) ; Zxid zxid = Zxid . fromSimpleString ( strZxid ) ; if ( zxid . compareTo ( latestZxid ) > 0 ) { file . delete ( ) ; iter . remove ( ) ; } } if ( files . isEmpty ( ) ) { LOG . error ( "There's no cluster_config files after cleaning up." ) ; throw new RuntimeException ( "There's no cluster_config files!" ) ; } fsyncDirectory ( ) ; }
cluster_config files .
13,181
public SymbolType withName ( String name ) { return clone ( marker , name , arrayCount , typeVariable , null , null ) ; }
Clones replacing the symbol type name .
13,182
public static SymbolType typeVariableOf ( final String typeVariable , final Class < Object > clazz ) { return new SymbolType ( clazz , typeVariable ) ; }
Builds a symbol for a type variable from a Java class .
13,183
public static SymbolType typeVariableOf ( final String typeVariable , List < SymbolType > upperBounds ) { return new SymbolType ( upperBounds , typeVariable ) ; }
Builds a symbol for a type variable from a list of upper bounds .
13,184
private static SymbolType typeVariableOf ( String typeVariable , final String name , final int arrayCount , final List < SymbolType > upperBounds , final List < SymbolType > lowerBounds ) { return new SymbolType ( name , arrayCount , upperBounds , lowerBounds , typeVariable ) ; }
Builds a symbol for a type variable .
13,185
public static SymbolType typeVariableOf ( TypeVariable < ? > typeVariable ) throws InvalidTypeException { return valueOf ( typeVariable , null ) . cloneAsTypeVariable ( typeVariable . getName ( ) ) ; }
Builds a symbol for a type variable from a TypeVariable .
13,186
public static SymbolType valueOf ( Type type , SymbolType arg , Map < String , SymbolType > updatedTypeMapping , Map < String , SymbolType > typeMapping ) throws InvalidTypeException { if ( typeMapping == null ) { typeMapping = Collections . emptyMap ( ) ; } SymbolType returnType = null ; if ( type instanceof Class < ? > ) { returnType = valueOfClass ( ( Class < ? > ) type , arg , updatedTypeMapping , typeMapping ) ; } else if ( type instanceof TypeVariable ) { return valueOfTypeVariable ( ( TypeVariable < ? > ) type , arg , updatedTypeMapping , typeMapping ) ; } else if ( type instanceof ParameterizedType ) { returnType = valueOfParameterizedType ( ( ParameterizedType ) type , arg , updatedTypeMapping , typeMapping ) ; } else if ( type instanceof GenericArrayType ) { returnType = valueOfGenericArrayType ( ( GenericArrayType ) type , arg , updatedTypeMapping , typeMapping ) ; } else if ( type instanceof WildcardType ) { returnType = valueOfWildcardType ( ( WildcardType ) type , arg , updatedTypeMapping , typeMapping ) ; } return returnType ; }
Builds a symbol type from a Java type .
13,187
public float nextFloat ( boolean readStream ) throws IOException , ValueNotPresentException { if ( ! readStream ) { return latestRead ; } if ( ! valuePresent ) { throw new ValueNotPresentException ( "Cannot materialize float.." ) ; } return readFloat ( ) ; }
Give the next float as a primitive .
13,188
public static List < ? extends Class < ? > > intersectRawTypes ( List < Class < ? > > classes1 , List < Class < ? > > classes2 ) { if ( classes1 . size ( ) == 1 && classes2 . size ( ) == 1 ) { return intersectRawTypes ( classes1 . get ( 0 ) , classes2 . get ( 0 ) ) ; } else { return list ( removeSubClasses ( intersection ( classesAndInterfaces ( classes1 ) , classesAndInterfaces ( classes2 ) ) ) ) ; } }
Returns the intersection of raw types of classes and all super classes and interfaces .
13,189
public static List < ? extends Class < ? > > intersectRawTypes ( Class < ? > clazz1 , Class < ? > clazz2 ) { if ( clazz2 == null ) { clazz2 = Object . class ; } if ( clazz1 == null ) { clazz1 = Object . class ; } if ( clazz1 . isPrimitive ( ) ) { clazz1 = Types . getWrapperClass ( clazz1 . getName ( ) ) ; } if ( clazz2 . isPrimitive ( ) ) { clazz2 = Types . getWrapperClass ( clazz2 . getName ( ) ) ; } if ( clazz1 . equals ( clazz2 ) ) { return singletonList ( clazz1 ) ; } if ( Types . isAssignable ( clazz2 , clazz1 ) ) { return singletonList ( clazz1 ) ; } if ( Types . isAssignable ( clazz1 , clazz2 ) ) { return singletonList ( clazz2 ) ; } final Set < Class < ? > > common = commonClasses ( clazz1 , clazz2 ) ; final List < Class < ? > > list = list ( removeSubClasses ( common ) ) ; return list . isEmpty ( ) ? LIST_OF_OBJECT_CLASS : list ; }
Looks for intersection of raw types of classes and all super classes and interfaces .
13,190
public void join ( String peer ) throws Exception { LOG . debug ( "Follower joins in." ) ; try { LOG . debug ( "Query leader from {}" , peer ) ; Message query = MessageBuilder . buildQueryLeader ( ) ; MessageTuple tuple = null ; while ( true ) { try { sendMessage ( peer , query ) ; tuple = filter . getExpectedMessage ( MessageType . QUERY_LEADER_REPLY , peer , config . getTimeoutMs ( ) ) ; break ; } catch ( TimeoutException ex ) { long retryInterval = 1 ; LOG . warn ( "Timeout while contacting leader, going to retry after {} " + "second." , retryInterval ) ; Thread . sleep ( retryInterval * 1000 ) ; } } this . electedLeader = tuple . getMessage ( ) . getReply ( ) . getLeader ( ) ; LOG . debug ( "Got current leader {}" , this . electedLeader ) ; while ( true ) { try { joinSynchronization ( ) ; break ; } catch ( TimeoutException | BackToElectionException ex ) { LOG . debug ( "Timeout({} ms) in synchronizing, retrying. Last zxid : {}" , getSyncTimeoutMs ( ) , persistence . getLatestZxid ( ) ) ; transport . clear ( electedLeader ) ; clearMessageQueue ( ) ; } } restoreFromSnapshot ( ) ; deliverUndeliveredTxns ( ) ; this . election . specifyLeader ( this . electedLeader ) ; changePhase ( Phase . BROADCASTING ) ; accepting ( ) ; } catch ( InterruptedException e ) { LOG . debug ( "Participant is canceled by user." ) ; throw e ; } catch ( TimeoutException e ) { LOG . debug ( "Didn't hear message from {} for {} milliseconds. Going" + " back to leader election." , this . electedLeader , this . config . getTimeoutMs ( ) ) ; if ( persistence . getLastSeenConfig ( ) == null ) { throw new JoinFailure ( "Fails to join cluster." ) ; } } catch ( BackToElectionException e ) { LOG . debug ( "Got GO_BACK message from queue, going back to electing." ) ; if ( persistence . getLastSeenConfig ( ) == null ) { throw new JoinFailure ( "Fails to join cluster." ) ; } } catch ( LeftCluster e ) { LOG . debug ( "Exit running : {}" , e . getMessage ( ) ) ; throw e ; } catch ( Exception e ) { LOG . error ( "Caught exception" , e ) ; throw e ; } finally { changePhase ( Phase . FINALIZING ) ; } }
Starts from joining some one who is in cluster ..
13,191
void sendProposedEpoch ( ) throws IOException { Message message = MessageBuilder . buildProposedEpoch ( persistence . getProposedEpoch ( ) , persistence . getAckEpoch ( ) , persistence . getLastSeenConfig ( ) , getSyncTimeoutMs ( ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Sends {} to leader {}" , TextFormat . shortDebugString ( message ) , this . electedLeader ) ; } sendMessage ( this . electedLeader , message ) ; }
Sends CEPOCH message to its prospective leader .
13,192
void waitForNewEpoch ( ) throws InterruptedException , TimeoutException , IOException { MessageTuple tuple = filter . getExpectedMessage ( MessageType . NEW_EPOCH , this . electedLeader , config . getTimeoutMs ( ) ) ; Message msg = tuple . getMessage ( ) ; String source = tuple . getServerId ( ) ; ZabMessage . NewEpoch epoch = msg . getNewEpoch ( ) ; if ( epoch . getNewEpoch ( ) < persistence . getProposedEpoch ( ) ) { LOG . error ( "New epoch {} from {} is smaller than last received " + "proposed epoch {}" , epoch . getNewEpoch ( ) , source , persistence . getProposedEpoch ( ) ) ; throw new RuntimeException ( "New epoch is smaller than current one." ) ; } persistence . setProposedEpoch ( epoch . getNewEpoch ( ) ) ; setSyncTimeoutMs ( epoch . getSyncTimeout ( ) ) ; LOG . debug ( "Received the new epoch proposal {} from {}." , epoch . getNewEpoch ( ) , source ) ; Zxid zxid = persistence . getLatestZxid ( ) ; sendMessage ( this . electedLeader , MessageBuilder . buildAckEpoch ( persistence . getAckEpoch ( ) , zxid ) ) ; }
Waits until receives the NEWEPOCH message from leader .
13,193
void waitForNewLeaderMessage ( ) throws TimeoutException , InterruptedException , IOException { LOG . debug ( "Waiting for New Leader message from {}." , this . electedLeader ) ; MessageTuple tuple = filter . getExpectedMessage ( MessageType . NEW_LEADER , this . electedLeader , config . getTimeoutMs ( ) ) ; Message msg = tuple . getMessage ( ) ; String source = tuple . getServerId ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Got message {} from {}." , TextFormat . shortDebugString ( msg ) , source ) ; } ZabMessage . NewLeader nl = msg . getNewLeader ( ) ; long epoch = nl . getEpoch ( ) ; Log log = persistence . getLog ( ) ; log . sync ( ) ; persistence . setAckEpoch ( epoch ) ; Message ack = MessageBuilder . buildAck ( persistence . getLatestZxid ( ) ) ; sendMessage ( source , ack ) ; }
Waits for NEW_LEADER message and sends back ACK and update ACK epoch .
13,194
void waitForCommitMessage ( ) throws TimeoutException , InterruptedException , IOException { LOG . debug ( "Waiting for commit message from {}" , this . electedLeader ) ; MessageTuple tuple = filter . getExpectedMessage ( MessageType . COMMIT , this . electedLeader , config . getTimeoutMs ( ) ) ; Zxid zxid = MessageBuilder . fromProtoZxid ( tuple . getMessage ( ) . getCommit ( ) . getZxid ( ) ) ; Zxid lastZxid = persistence . getLatestZxid ( ) ; if ( zxid . compareTo ( lastZxid ) != 0 ) { LOG . error ( "The ACK zxid {} doesn't match last zxid {} in log!" , zxid , lastZxid ) ; throw new RuntimeException ( "The ACK zxid doesn't match last zxid" ) ; } }
Wait for a commit message from the leader .
13,195
private void joinSynchronization ( ) throws IOException , TimeoutException , InterruptedException { Message sync = MessageBuilder . buildSyncHistory ( persistence . getLatestZxid ( ) ) ; sendMessage ( this . electedLeader , sync ) ; MessageTuple tuple = filter . getExpectedMessage ( MessageType . SYNC_HISTORY_REPLY , electedLeader , config . getTimeoutMs ( ) ) ; Message msg = tuple . getMessage ( ) ; setSyncTimeoutMs ( msg . getSyncHistoryReply ( ) . getSyncTimeout ( ) ) ; waitForSync ( this . electedLeader ) ; Zxid lastZxid = persistence . getLatestZxid ( ) ; LOG . debug ( "After first synchronization, the last zxid is {}" , lastZxid ) ; Message join = MessageBuilder . buildJoin ( lastZxid ) ; sendMessage ( this . electedLeader , join ) ; changePhase ( Phase . SYNCHRONIZING ) ; waitForSync ( this . electedLeader ) ; waitForNewLeaderMessage ( ) ; waitForCommitMessage ( ) ; persistence . setProposedEpoch ( persistence . getAckEpoch ( ) ) ; }
depends on the length of the synchronization .
13,196
public static Reader createReader ( FileSystem fs , Path path , Configuration conf ) throws IOException { return new ReaderImpl ( fs , path , conf ) ; }
Create an ORC file reader .
13,197
public static Writer createWriter ( FileSystem fs , Path path , Configuration conf , ObjectInspector inspector , long stripeSize , CompressionKind compress , int bufferSize , int rowIndexStride ) throws IOException { return new WriterImpl ( fs , path , conf , inspector , stripeSize , compress , bufferSize , rowIndexStride , getMemoryManager ( conf ) ) ; }
Create an ORC file streamFactory .
13,198
private int compareKinds ( Kind kind1 , Kind kind2 ) { if ( kind1 == Kind . LENGTH && kind2 == Kind . DATA ) { return - 1 ; } if ( kind1 == Kind . DATA && kind2 == Kind . LENGTH ) { return 1 ; } return kind1 . compareTo ( kind2 ) ; }
stuck with it this is just a hack to work around that .
13,199
protected void sendMessage ( String dest , Message message ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "Sends message {} to {}." , TextFormat . shortDebugString ( message ) , dest ) ; } this . transport . send ( dest , message ) ; }
Sends message to the specific destination .