idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
32,100
public synchronized void close ( ) throws IOException { if ( clientRunning ) { leasechecker . close ( ) ; leasechecker . closeRenewal ( ) ; if ( blockLocationRenewal != null ) { blockLocationRenewal . stop ( ) ; } clientRunning = false ; try { leasechecker . interruptAndJoin ( ) ; if ( blockLocationRenewal != null ) { ...
Close the file system abandoning all of the leases and files being created and close connections to the namenode .
32,101
public BlockLocation [ ] getBlockLocations ( String src , long start , long length ) throws IOException { LocatedBlocks blocks = callGetBlockLocations ( namenode , src , start , length , isMetaInfoSuppoted ( namenodeProtocolProxy ) ) ; return DFSUtil . locatedBlocks2Locations ( blocks ) ; }
Get block location info about file
32,102
DFSInputStream open ( String src , int buffersize , boolean verifyChecksum , FileSystem . Statistics stats , boolean clearOsBuffer , ReadOptions options ) throws IOException { checkOpen ( ) ; incFileReadToStats ( ) ; DFSInputStream stream = new DFSInputStream ( this , src , buffersize , verifyChecksum , clearOsBuffer ,...
Create an input stream that obtains a nodelist from the namenode and then reads from all the right places . Creates inner subclass of InputStream that does the right out - of - band work .
32,103
public OutputStream create ( String src , boolean overwrite ) throws IOException { return create ( src , overwrite , defaultReplication , defaultBlockSize , null ) ; }
Create a new dfs file and return an output stream for writing into it .
32,104
public OutputStream create ( String src , boolean overwrite , short replication , long blockSize ) throws IOException { return create ( src , overwrite , replication , blockSize , null ) ; }
Create a new dfs file with the specified block replication and return an output stream for writing into the file .
32,105
public boolean raidFile ( String source , String codecId , short expectedSourceRepl ) throws IOException { checkOpen ( ) ; try { return namenode . raidFile ( source , codecId , expectedSourceRepl ) ; } catch ( RemoteException re ) { throw re . unwrapRemoteException ( AccessControlException . class , NSQuotaExceededExce...
Raid a file with given codec No guarantee file will be raided when the call returns . Namenode will schedule raiding asynchronously . If raiding is done when raidFile is called again namenode will set replication of source blocks to expectedSourceRepl
32,106
boolean recoverLease ( String src , boolean discardLastBlock ) throws IOException { checkOpen ( ) ; leasechecker . remove ( src ) ; if ( this . namenodeProtocolProxy == null ) { return versionBasedRecoverLease ( src ) ; } return methodBasedRecoverLease ( src , discardLastBlock ) ; }
Recover a file s lease
32,107
private boolean versionBasedRecoverLease ( String src ) throws IOException { if ( namenodeVersion < ClientProtocol . RECOVER_LEASE_VERSION ) { OutputStream out ; try { out = append ( src , conf . getInt ( "io.file.buffer.size" , 4096 ) , null ) ; } catch ( RemoteException re ) { IOException e = re . unwrapRemoteExcepti...
recover lease based on version
32,108
private boolean methodBasedRecoverLease ( String src , boolean discardLastBlock ) throws IOException { if ( namenodeProtocolProxy . isMethodSupported ( "closeRecoverLease" , String . class , String . class , boolean . class ) ) { try { return namenode . closeRecoverLease ( src , clientName , discardLastBlock ) ; } catc...
recover lease based on method name
32,109
OutputStream append ( String src , int buffersize , Progressable progress ) throws IOException { checkOpen ( ) ; clearFileStatusCache ( ) ; FileStatus stat = null ; LocatedBlock lastBlock = null ; boolean success = false ; try { stat = getFileInfo ( src ) ; if ( namenodeProtocolProxy != null && namenodeProtocolProxy . ...
Append to an existing HDFS file .
32,110
public boolean setReplication ( String src , short replication ) throws IOException { try { return namenode . setReplication ( src , replication ) ; } catch ( RemoteException re ) { throw re . unwrapRemoteException ( AccessControlException . class , NSQuotaExceededException . class , DSQuotaExceededException . class ) ...
Set replication for an existing file .
32,111
public void merge ( String parity , String source , String codecId , int [ ] checksums ) throws IOException { checkOpen ( ) ; try { namenode . merge ( parity , source , codecId , checksums ) ; } catch ( RemoteException re ) { throw re . unwrapRemoteException ( AccessControlException . class , NSQuotaExceededException ....
Merge parity file and source file together into a raided file
32,112
public boolean delete ( String src , boolean recursive ) throws IOException { checkOpen ( ) ; clearFileStatusCache ( ) ; try { return namenode . delete ( src , recursive ) ; } catch ( RemoteException re ) { throw re . unwrapRemoteException ( AccessControlException . class ) ; } }
delete file or directory . delete contents of the directory if non empty and recursive set to true
32,113
public FileStatus [ ] listPaths ( String src ) throws IOException { checkOpen ( ) ; metrics . incLsCalls ( ) ; try { if ( namenodeProtocolProxy == null ) { return versionBasedListPath ( src ) ; } return methodBasedListPath ( src ) ; } catch ( RemoteException re ) { throw re . unwrapRemoteException ( AccessControlExcept...
Get a listing of the indicated directory
32,114
private RemoteIterator < LocatedFileStatus > versionBasedListPathWithLocation ( final String src ) throws IOException { if ( namenodeVersion >= ClientProtocol . BULK_BLOCK_LOCATIONS_VERSION ) { return iteratorListing ( src ) ; } else { return arrayListing ( src ) ; } }
List a directory with location based on version
32,115
private RemoteIterator < LocatedFileStatus > methodBasedListPathWithLocation ( final String src ) throws IOException { if ( namenodeProtocolProxy . isMethodSupported ( "getLocatedPartialListing" , String . class , byte [ ] . class ) ) { return iteratorListing ( src ) ; } else { return arrayListing ( src ) ; } }
List a directory with location based on method
32,116
private RemoteIterator < LocatedFileStatus > arrayListing ( final String src ) throws IOException { return new RemoteIterator < LocatedFileStatus > ( ) { private FileStatus [ ] stats ; private int i = 0 ; { stats = listPaths ( src ) ; if ( stats == null ) { throw new FileNotFoundException ( "File " + src + " does not e...
create the iterator from an array of file status
32,117
private RemoteIterator < LocatedFileStatus > iteratorListing ( final String src ) throws IOException { return new RemoteIterator < LocatedFileStatus > ( ) { private LocatedDirectoryListing thisListing ; private int i ; { thisListing = namenode . getLocatedPartialListing ( src , HdfsFileStatus . EMPTY_NAME ) ; if ( this...
create the iterator from the iterative listing with block locations
32,118
private FileStatus [ ] iterativeListing ( String src ) throws IOException { DirectoryListing thisListing = namenode . getPartialListing ( src , HdfsFileStatus . EMPTY_NAME ) ; if ( thisListing == null ) { return null ; } HdfsFileStatus [ ] partialListing = thisListing . getPartialListing ( ) ; if ( ! thisListing . hasM...
List the given path iteratively if the directory is large
32,119
int getFileCrc ( String src ) throws IOException { checkOpen ( ) ; return getFileCrc ( dataTransferVersion , src , namenode , namenodeProtocolProxy , socketFactory , socketTimeout ) ; }
Get the CRC32 Checksum of a file .
32,120
public void setPermission ( String src , FsPermission permission ) throws IOException { checkOpen ( ) ; clearFileStatusCache ( ) ; try { namenode . setPermission ( src , permission ) ; } catch ( RemoteException re ) { throw re . unwrapRemoteException ( AccessControlException . class , FileNotFoundException . class ) ; ...
Set permissions to a file or directory .
32,121
public void setOwner ( String src , String username , String groupname ) throws IOException { checkOpen ( ) ; clearFileStatusCache ( ) ; try { namenode . setOwner ( src , username , groupname ) ; } catch ( RemoteException re ) { throw re . unwrapRemoteException ( AccessControlException . class , FileNotFoundException ....
Set file or directory owner .
32,122
private CorruptFileBlocks versionBasedListCorruptFileBlocks ( String path , String cookie ) throws IOException { if ( namenodeVersion < ClientProtocol . LIST_CORRUPT_FILEBLOCKS_VERSION ) { LOG . info ( "NameNode version is " + namenodeVersion + " Using older version of getCorruptFiles." ) ; if ( cookie != null ) { retu...
Version based list corrupt file blocks
32,123
private CorruptFileBlocks methodBasedListCorruptFileBlocks ( String path , String cookie ) throws IOException { if ( ! namenodeProtocolProxy . isMethodSupported ( "listCorruptFileBlocks" , String . class , String . class ) ) { LOG . info ( "NameNode version is " + namenodeVersion + " Using older version of getCorruptFi...
Method based listCorruptFileBlocks
32,124
private void versionBasedSaveNamespace ( boolean force , boolean uncompressed ) throws AccessControlException , IOException { if ( namenodeVersion >= ClientProtocol . SAVENAMESPACE_FORCE ) { namenode . saveNamespace ( force , uncompressed ) ; } else { namenode . saveNamespace ( ) ; } }
Version - based save namespace
32,125
private void methodBasedSaveNamespace ( boolean force , boolean uncompressed ) throws AccessControlException , IOException { if ( namenodeProtocolProxy . isMethodSupported ( "saveNamespace" , boolean . class , boolean . class ) ) { namenode . saveNamespace ( force , uncompressed ) ; } else { namenode . saveNamespace ( ...
Method - based save namespace
32,126
void setQuota ( String src , long namespaceQuota , long diskspaceQuota ) throws IOException { if ( ( namespaceQuota <= 0 && namespaceQuota != FSConstants . QUOTA_DONT_SET && namespaceQuota != FSConstants . QUOTA_RESET ) || ( diskspaceQuota <= 0 && diskspaceQuota != FSConstants . QUOTA_DONT_SET && diskspaceQuota != FSCo...
Sets or resets quotas for a directory .
32,127
public void setTimes ( String src , long mtime , long atime ) throws IOException { checkOpen ( ) ; clearFileStatusCache ( ) ; try { namenode . setTimes ( src , mtime , atime ) ; } catch ( RemoteException re ) { throw re . unwrapRemoteException ( AccessControlException . class , FileNotFoundException . class ) ; } }
set the modification and access time of a file
32,128
static void checkBlockRange ( List < LocatedBlock > blockRange , long offset , long length ) throws IOException { boolean isValid = false ; if ( ! blockRange . isEmpty ( ) ) { int numBlocks = blockRange . size ( ) ; LocatedBlock firstBlock = blockRange . get ( 0 ) ; LocatedBlock lastBlock = blockRange . get ( numBlocks...
Checks that the given block range covers the given file segment and consists of contiguous blocks . This function assumes that the length of the queried segment is non - zero and a non - empty block list is expected .
32,129
void reportChecksumFailure ( String file , LocatedBlock lblocks [ ] ) { try { reportBadBlocks ( lblocks ) ; } catch ( IOException ie ) { LOG . info ( "Found corruption while reading " + file + ". Error repairing corrupt blocks. Bad blocks remain. " + StringUtils . stringifyException ( ie ) ) ; } }
just reports checksum failure and ignores any exception during the report .
32,130
public int getDataTransferProtocolVersion ( ) throws IOException { synchronized ( dataTransferVersion ) { if ( dataTransferVersion == - 1 ) { try { int remoteDataTransferVersion = namenode . getDataTransferProtocolVersion ( ) ; updateDataTransferProtocolVersionIfNeeded ( remoteDataTransferVersion ) ; } catch ( RemoteEx...
Get the data transfer protocol version supported in the cluster assuming all the datanodes have the same version .
32,131
public boolean isInLocalRack ( InetSocketAddress addr ) { if ( dnsToSwitchMapping == null || this . localhostNetworkLocation == null ) { return false ; } ArrayList < String > tempList = new ArrayList < String > ( ) ; tempList . add ( addr . getAddress ( ) . getHostAddress ( ) ) ; List < String > retList = dnsToSwitchMa...
Determine whether the input address is in the same rack as local machine
32,132
int getTotalCount ( ) { int ret = 0 ; for ( RaidMissingBlocksPerCodec queue : queues . values ( ) ) { ret += queue . getTotalCount ( ) ; } return ret ; }
Get the total count of the missing blocks
32,133
boolean remove ( BlockInfo blockInfo , RaidCodec codec ) { if ( queues . get ( codec ) . remove ( blockInfo ) ) { if ( NameNode . stateChangeLog . isDebugEnabled ( ) ) { NameNode . stateChangeLog . debug ( "BLOCK* NameSystem.RaidMissingBlocks.remove:" + blockInfo + " file " + blockInfo . getINode ( ) + " codec " + code...
Remove a missing Raided block from its codec queue .
32,134
public synchronized void initTasks ( ) throws IOException { boolean loggingEnabled = LOG . isDebugEnabled ( ) ; if ( loggingEnabled ) { LOG . debug ( "(initTasks@SJIP) Starting Initialization for " + jobId ) ; } numMapTasks = jobStory . getNumberMaps ( ) ; numReduceTasks = jobStory . getNumberReduces ( ) ; JobHistory ....
for initTasks update information from JobStory object
32,135
@ SuppressWarnings ( "deprecation" ) private synchronized TaskAttemptInfo getMapTaskAttemptInfo ( TaskTracker taskTracker , TaskAttemptID taskAttemptID ) { assert ( taskAttemptID . isMap ( ) ) ; JobID jobid = ( JobID ) taskAttemptID . getJobID ( ) ; assert ( jobid == getJobID ( ) ) ; RawSplit split = splits [ taskAttem...
Given the map taskAttemptID returns the TaskAttemptInfo . Deconstructs the map s taskAttemptID and looks up the jobStory with the parts taskType id of task id of task attempt .
32,136
private TaskAttemptInfo getReduceTaskAttemptInfo ( TaskTracker taskTracker , TaskAttemptID taskAttemptID ) { assert ( ! taskAttemptID . isMap ( ) ) ; TaskID taskId = taskAttemptID . getTaskID ( ) ; TaskType taskType ; if ( taskAttemptID . isMap ( ) ) { taskType = TaskType . MAP ; } else { taskType = TaskType . REDUCE ;...
Given the reduce taskAttemptID returns the TaskAttemptInfo . Deconstructs the reduce taskAttemptID and looks up the jobStory with the parts taskType id of task id of task attempt .
32,137
public static void alignDatanodes ( DatanodeInfo [ ] dstLocs , DatanodeInfo [ ] srcLocs ) { for ( int i = 0 ; i < dstLocs . length ; i ++ ) { for ( int j = 0 ; j < srcLocs . length ; j ++ ) { if ( i == j ) continue ; if ( dstLocs [ i ] . equals ( srcLocs [ j ] ) ) { if ( i < j ) { swap ( i , j , srcLocs ) ; } else { sw...
Aligns the source and destination locations such that common locations appear at the same index .
32,138
public void shutdown ( ) throws IOException { Iterator < ClientDatanodeProtocol > connections = datanodeMap . values ( ) . iterator ( ) ; while ( connections . hasNext ( ) ) { ClientDatanodeProtocol cnxn = connections . next ( ) ; RPC . stopProxy ( cnxn ) ; } datanodeMap . clear ( ) ; executor . shutdownNow ( ) ; synch...
Tears down all RPC connections you MUST call this once you are done .
32,139
public void copy ( List < FastFileCopyRequest > requests ) throws Exception { List < Future < CopyResult > > results = new ArrayList < Future < CopyResult > > ( ) ; for ( FastFileCopyRequest r : requests ) { Callable < CopyResult > fastFileCopy = new FastFileCopy ( r . getSrc ( ) , r . getDestination ( ) , r . srcFs , ...
Performs fast copy for a list of fast file copy requests . Uses a thread pool to perform fast file copy in parallel .
32,140
private static void getDirectoryListing ( FileStatus root , FileSystem fs , List < CopyPath > result , Path dstPath ) throws IOException { if ( ! root . isDir ( ) ) { result . add ( new CopyPath ( root . getPath ( ) , dstPath ) ) ; return ; } for ( FileStatus child : fs . listStatus ( root . getPath ( ) ) ) { getDirect...
Recursively lists out all the files under a given path .
32,141
private static List < CopyPath > expandDirectories ( FileSystem fs , List < Path > paths , Path dstPath ) throws IOException { List < CopyPath > newList = new ArrayList < CopyPath > ( ) ; FileSystem dstFs = dstPath . getFileSystem ( defaultConf ) ; boolean isDstFile = false ; try { FileStatus dstPathStatus = dstFs . ge...
Get the listing of all files under the given directories .
32,142
private static List < CopyPath > expandSingle ( Path src , Path dstPath ) throws IOException { List < Path > expandedPaths = new ArrayList < Path > ( ) ; FileSystem fs = src . getFileSystem ( defaultConf ) ; FileStatus [ ] stats = fs . globStatus ( src ) ; if ( stats == null || stats . length == 0 ) { throw new IOExcep...
Expand a single file if its a file pattern list out all files matching the pattern if its a directory return all files under the directory .
32,143
private static List < CopyPath > expandSrcs ( List < Path > srcs , Path dstPath ) throws IOException { List < CopyPath > expandedSrcs = new ArrayList < CopyPath > ( ) ; for ( Path src : srcs ) { expandedSrcs . addAll ( expandSingle ( src , dstPath ) ) ; } return expandedSrcs ; }
Expands all sources if they are file pattern expand to list out all files matching the pattern if they are a directory expand to list out all files under the directory .
32,144
public float getProgress ( ) throws IOException { if ( end == start ) { return 0.0f ; } else { return Math . min ( 1.0f , ( in . getPosition ( ) - start ) / ( float ) ( end - start ) ) ; } }
Return the progress within the input split
32,145
protected String findPattern ( String strPattern , String text , int grp ) { Pattern pattern = Pattern . compile ( strPattern , Pattern . MULTILINE ) ; Matcher matcher = pattern . matcher ( text ) ; if ( matcher . find ( 0 ) ) return matcher . group ( grp ) ; return null ; }
Find the first occurence ofa pattern in a piece of text and return a specific group .
32,146
protected String findAll ( String strPattern , String text , int grp , String separator ) { String retval = "" ; boolean firstTime = true ; Pattern pattern = Pattern . compile ( strPattern ) ; Matcher matcher = pattern . matcher ( text ) ; while ( matcher . find ( ) ) { retval += ( firstTime ? "" : separator ) + matche...
Finds all occurences of a pattern in a piece of text and returns the matching groups .
32,147
private int renderMBeans ( JsonGenerator jg , String [ ] mBeanNames ) throws IOException , MalformedObjectNameException { jg . writeStartObject ( ) ; Set < ObjectName > nameQueries , queriedObjects ; nameQueries = new HashSet < ObjectName > ( ) ; queriedObjects = new HashSet < ObjectName > ( ) ; if ( mBeanNames == null...
Renders MBean attributes to jg . The queries parameter allows selection of a subset of mbeans .
32,148
private void renderMBean ( JsonGenerator jg , ObjectName objectName ) throws IOException { MBeanInfo beanInfo ; String className ; jg . writeObjectFieldStart ( objectName . toString ( ) ) ; jg . writeStringField ( "beanName" , objectName . toString ( ) ) ; try { beanInfo = mBeanServer . getMBeanInfo ( objectName ) ; cl...
Render a particular MBean s attributes to jg .
32,149
public DatanodeCommand [ ] sendHeartbeat ( DatanodeRegistration registration , long capacity , long dfsUsed , long remaining , long namespaceUsed , int xmitsInProgress , int xceiverCount ) throws IOException { throw new IOException ( "sendHeartbeat" + errMessage ) ; }
This method should not be invoked on the composite DatanodeProtocols object . You can call these on the individual DatanodeProcol objects .
32,150
void setPolicyInfo ( Collection < PolicyInfo > all ) throws IOException { this . all = all ; this . pathToPolicy . clear ( ) ; for ( PolicyInfo pinfo : all ) { pathToPolicy . add ( new PathToPolicy ( pinfo . getSrcPath ( ) , pinfo ) ) ; for ( PathInfo d : pinfo . getDestPaths ( ) ) { pathToPolicy . add ( new PathToPoli...
The list of all configured policies .
32,151
public void run ( ) { while ( running ) { try { LOG . info ( "FileFixer continuing to run..." ) ; doFindFiles ( ) ; } catch ( Exception e ) { LOG . error ( StringUtils . stringifyException ( e ) ) ; } catch ( Error err ) { LOG . error ( "Exiting after encountering " + StringUtils . stringifyException ( err ) ) ; shutdo...
A singleton thread that finds corrupted files and then schedules blocks to be copied . This thread talks only to NameNodes and does not talk to any datanodes .
32,152
static ClientDatanodeProtocol createClientDatanodeProtocolProxy ( DatanodeInfo datanodeid , Configuration conf ) throws IOException { InetSocketAddress addr = NetUtils . createSocketAddr ( datanodeid . getHost ( ) + ":" + datanodeid . getIpcPort ( ) ) ; if ( ClientDatanodeProtocol . LOG . isDebugEnabled ( ) ) { ClientD...
Setup a session with the specified datanode
32,153
public static GaloisField getInstance ( int fieldSize , int primitivePolynomial ) { int key = ( ( fieldSize << 16 ) & 0xFFFF0000 ) + ( primitivePolynomial & 0x0000FFFF ) ; GaloisField gf ; synchronized ( instances ) { gf = instances . get ( key ) ; if ( gf == null ) { gf = new GaloisField ( fieldSize , primitivePolynom...
Get the object performs Galois field arithmetics
32,154
public int add ( int x , int y ) { assert ( x >= 0 && x < getFieldSize ( ) && y >= 0 && y < getFieldSize ( ) ) ; return x ^ y ; }
Compute the sum of two fields
32,155
public int multiply ( int x , int y ) { assert ( x >= 0 && x < getFieldSize ( ) && y >= 0 && y < getFieldSize ( ) ) ; return mulTable [ x ] [ y ] ; }
Compute the multiplication of two fields
32,156
public int divide ( int x , int y ) { assert ( x >= 0 && x < getFieldSize ( ) && y > 0 && y < getFieldSize ( ) ) ; return divTable [ x ] [ y ] ; }
Compute the division of two fields
32,157
public int power ( int x , int n ) { assert ( x >= 0 && x < getFieldSize ( ) ) ; if ( n == 0 ) { return 1 ; } if ( x == 0 ) { return 0 ; } x = logTable [ x ] * n ; if ( x < primitivePeriod ) { return powTable [ x ] ; } x = x % primitivePeriod ; return powTable [ x ] ; }
Compute power n of a field
32,158
public void solveVandermondeSystem ( int [ ] x , byte [ ] [ ] y , int len , int dataStart , int dataLen ) { assert ( x . length <= len && y . length <= len ) ; int dataEnd = dataStart + dataLen ; for ( int i = 0 ; i < len - 1 ; i ++ ) { for ( int j = len - 1 ; j > i ; j -- ) { for ( int k = dataStart ; k < dataEnd ; k ...
A bulk version of the solveVandermondeSystem
32,159
public void substitute ( byte [ ] [ ] p , byte [ ] q , int x ) { substitute ( p , q , x , 0 , p [ 0 ] . length ) ; }
A bulk version of the substitute . Tends to be 2X faster than the int substitute in a loop .
32,160
private void snapshotConfig ( ) { synchronized ( configManager ) { maximum = configManager . getPoolMaximum ( poolInfo , getType ( ) ) ; minimum = configManager . getPoolMinimum ( poolInfo , getType ( ) ) ; weight = configManager . getWeight ( poolInfo ) ; priority = configManager . getPriority ( poolInfo ) ; preemptab...
Get the snapshot of the configuration from the configuration manager . Synchronized on config manager to ensure that config is atomically updated per pool .
32,161
public void addSession ( String id , Session session ) { synchronized ( session ) { SessionSchedulable schedulable = new SessionSchedulable ( session , getType ( ) ) ; idToSession . put ( id , schedulable ) ; } }
Add a session to the pool
32,162
public Queue < SessionSchedulable > getScheduleQueue ( ) { if ( scheduleQueue == null ) { scheduleQueue = createSessionQueue ( configManager . getPoolComparator ( poolInfo ) ) ; } return scheduleQueue ; }
Get the queue of sessions sorted for scheduling
32,163
public Queue < SessionSchedulable > getPreemptQueue ( ) { if ( preemptQueue == null ) { ScheduleComparator comparator = null ; switch ( configManager . getPoolComparator ( poolInfo ) ) { case FIFO : comparator = ScheduleComparator . FIFO_PREEMPT ; break ; case FAIR : comparator = ScheduleComparator . FAIR_PREEMPT ; bre...
Get the queue of sessions sorted for preemption
32,164
public Queue < SessionSchedulable > createSessionQueue ( ScheduleComparator comparator ) { int initCapacity = snapshotSessions . size ( ) == 0 ? 1 : snapshotSessions . size ( ) ; Queue < SessionSchedulable > sessionQueue = new PriorityQueue < SessionSchedulable > ( initCapacity , comparator ) ; sessionQueue . addAll ( ...
Get the queue of sessions in the pool sorted by comparator
32,165
public boolean isStarving ( long now ) { double starvingShare = getShare ( ) * shareStarvingRatio ; if ( getGranted ( ) >= Math . ceil ( starvingShare ) ) { lastTimeAboveStarvingShare = now ; } if ( getGranted ( ) >= Math . min ( getShare ( ) , getMinimum ( ) ) ) { lastTimeAboveMinimum = now ; } if ( now - lastPreemptT...
Check if the pool is starving now or not
32,166
public long getStarvingTime ( long now ) { long starvingTime = Math . max ( getMinimumStarvingTime ( now ) , getShareStarvingTime ( now ) ) ; return starvingTime ; }
Get the amount of time the pool was starving for either its min share or its share
32,167
private static int getMapCount ( int srcCount , int numNodes ) { int numMaps = ( int ) ( srcCount / OP_PER_MAP ) ; numMaps = Math . min ( numMaps , numNodes * MAX_MAPS_PER_NODE ) ; return Math . max ( numMaps , 1 ) ; }
Calculate how many maps to run .
32,168
public synchronized void registerPrimarySsId ( String address , Long ssid ) throws IOException { String node = getSsIdNode ( address ) ; zkCreateRecursively ( node , SerializableUtils . toBytes ( ssid ) , true , ssid . toString ( ) ) ; }
Creates a node in zookeeper denoting the current session id of the primary avatarnode of the cluster . The primary avatarnode always syncs this information to zookeeper when it starts .
32,169
public synchronized void registerLastTxId ( String address , ZookeeperTxId lastTxid ) throws IOException { String node = getLastTxIdNode ( address ) ; zkCreateRecursively ( node , lastTxid . toBytes ( ) , true , lastTxid . toString ( ) ) ; }
Creates a node in zookeeper denoting the current session id and the last transaction id processed by the primary avatarnode . This is used by the primary avatarnode when it shuts down cleanly .
32,170
public Long getPrimarySsId ( String address , boolean sync ) throws IOException , KeeperException , InterruptedException , ClassNotFoundException { Stat stat = new Stat ( ) ; String node = getSsIdNode ( address ) ; byte [ ] data = getNodeData ( node , stat , false , sync ) ; if ( data == null ) { return null ; } return...
Retrieves the current session id for the cluster from zookeeper .
32,171
public ZookeeperTxId getPrimaryLastTxId ( String address , boolean sync ) throws IOException , KeeperException , InterruptedException , ClassNotFoundException { Stat stat = new Stat ( ) ; String node = getLastTxIdNode ( address ) ; byte [ ] data = getNodeData ( node , stat , false , sync ) ; if ( data == null ) { retur...
Retrieves the last transaction id of the primary from zookeeper .
32,172
public String getPrimaryAvatarAddress ( String address , Stat stat , boolean retry ) throws IOException , KeeperException , InterruptedException { return getPrimaryAvatarAddress ( address , stat , retry , false ) ; }
Retrieves the primary address for the cluster this does not perform a sync before it reads the znode .
32,173
private void addJobJarToClassPath ( String localJarFile , StringBuffer classPath ) { File jobCacheDir = new File ( new Path ( localJarFile ) . getParent ( ) . toString ( ) ) ; File [ ] libs = new File ( jobCacheDir , "lib" ) . listFiles ( ) ; String sep = System . getProperty ( "path.separator" ) ; if ( libs != null ) ...
Given the path to the localized job jar file add it s constituents to the classpath
32,174
private static void appendSystemClasspath ( JobConf conf , String pathSeparator , StringBuffer classPath ) { String debugRuntime = conf . get ( "mapred.task.debug.runtime.classpath" ) ; if ( debugRuntime != null ) { classPath . append ( pathSeparator ) ; classPath . append ( debugRuntime ) ; } String systemClasspath = ...
Add the system class path to a class path
32,175
public synchronized void setNewWindows ( ArrayList < Long > newWindows ) throws IOException { if ( newWindows . size ( ) != windows . size ( ) ) { throw new IOException ( "Number of new windows need to be the same as that of old ones" ) ; } Collections . sort ( newWindows ) ; for ( int i = 0 ; i < newWindows . size ( )...
Only for testing
32,176
private void reorderJobs ( JobInProgress job , JobSchedulingInfo oldInfo , QueueInfo qi ) { if ( qi . removeWaitingJob ( oldInfo ) != null ) { qi . addWaitingJob ( job ) ; } if ( qi . removeRunningJob ( oldInfo ) != null ) { qi . addRunningJob ( job ) ; } }
because of the change in the job priority or job start - time .
32,177
private void makeJobRunning ( JobInProgress job , JobSchedulingInfo oldInfo , QueueInfo qi ) { qi . addRunningJob ( job ) ; }
This is used to move a job from the waiting queue to the running queue .
32,178
private void jobStateChanged ( JobStatusChangeEvent event , QueueInfo qi ) { JobInProgress job = event . getJobInProgress ( ) ; JobSchedulingInfo oldJobStateInfo = new JobSchedulingInfo ( event . getOldStatus ( ) ) ; if ( event . getEventType ( ) == EventType . PRIORITY_CHANGED || event . getEventType ( ) == EventType ...
Update the scheduler as job s state has changed
32,179
void splitKeyVal ( byte [ ] line , int length , Text key , Text val ) throws IOException { int numKeyFields = getNumOfKeyFields ( ) ; byte [ ] separator = getFieldSeparator ( ) ; int pos = UTF8ByteArrayUtils . findBytes ( line , 0 , length , separator ) ; for ( int k = 1 ; k < numKeyFields && pos != - 1 ; k ++ ) { pos ...
Split a line into key and value .
32,180
void write ( Object value ) throws IOException { if ( clientInputSerializer != null ) { clientInputSerializer . serialize ( value ) ; return ; } byte [ ] bval ; int valSize ; if ( value instanceof BytesWritable ) { BytesWritable val = ( BytesWritable ) value ; bval = val . getBytes ( ) ; valSize = val . getLength ( ) ;...
Write a value to the output stream using UTF - 8 encoding
32,181
private void writeTag ( String tag , String value ) throws IOException { printIndents ( ) ; if ( value . length ( ) > 0 ) { write ( "<" + tag + ">" + value + "</" + tag + ">\n" ) ; } else { write ( "<" + tag + "/>\n" ) ; } }
Write an XML tag
32,182
void updateLeasedFiles ( SnapshotStorage ssStore ) throws IOException { FSNamesystem fsNamesys = ssStore . getFSNamesystem ( ) ; List < Block > blocksForNN = new ArrayList < Block > ( ) ; leaseUpdateThreadPool = new ThreadPoolExecutor ( 1 , maxLeaseUpdateThreads , 60 , TimeUnit . SECONDS , new LinkedBlockingQueue < Run...
Tries to get the most up to date lengths of files under construction .
32,183
void downloadSnapshotFiles ( SnapshotStorage ssStore ) throws IOException { CheckpointSignature start = namenode . getCheckpointSignature ( ) ; ssStore . storage . setStorageInfo ( start ) ; CheckpointSignature end = null ; boolean success ; do { prepareDownloadDirs ( ) ; File [ ] srcNames = ssStore . getImageFiles ( )...
Download fsimage edits and edits . new files from the name - node . Files will be downloaded in CURRENT_DIR
32,184
synchronized Lease reassignLease ( Lease lease , String src , String newHolder ) { assert newHolder != null : "new lease holder is null" ; LeaseOpenTime leaseOpenTime = null ; if ( lease != null ) { leaseOpenTime = removeLease ( lease , src ) ; } return addLease ( newHolder , src , leaseOpenTime != null ? leaseOpenTime...
Reassign lease for file src to the new holder .
32,185
synchronized String findPath ( INodeFileUnderConstruction pendingFile ) throws IOException { Lease lease = getLease ( pendingFile . getClientName ( ) ) ; if ( lease != null ) { String src = lease . findPath ( pendingFile ) ; if ( src != null ) { return src ; } } throw new IOException ( "pendingFile (=" + pendingFile + ...
Find the pathname for the specified pendingFile
32,186
synchronized LeaseOpenTime removeLease ( Lease lease , String src ) { LeaseOpenTime leaseOpenTime = sortedLeasesByPath . remove ( src ) ; if ( ! lease . removePath ( src ) ) { LOG . error ( src + " not found in lease.paths (=" + lease . paths + ")" ) ; } if ( ! lease . hasPath ( ) ) { leases . remove ( lease . holder )...
Remove the specified lease and src .
32,187
synchronized void removeLease ( String holder , String src ) { Lease lease = getLease ( holder ) ; if ( lease != null ) { removeLease ( lease , src ) ; } }
Remove the lease for the specified holder and src
32,188
synchronized void checkLeases ( ) { int numPathsChecked = 0 ; for ( ; sortedLeases . size ( ) > 0 ; ) { final Lease oldest = sortedLeases . first ( ) ; if ( ! oldest . expiredHardLimit ( ) ) { return ; } String [ ] leasePaths = new String [ oldest . getPaths ( ) . size ( ) ] ; oldest . getPaths ( ) . toArray ( leasePat...
Check the leases beginning from the oldest .
32,189
public Progress addPhase ( String status ) { Progress phase = addPhase ( ) ; phase . setStatus ( status ) ; return phase ; }
Adds a named node to the tree .
32,190
public void complete ( ) { Progress myParent ; synchronized ( this ) { progress = 1.0f ; myParent = parent ; } if ( myParent != null ) { myParent . startNextPhase ( ) ; } }
Completes this node moving the parent node to its next child .
32,191
public synchronized float get ( ) { Progress node = this ; while ( node . parent != null ) { node = parent ; } return node . getInternal ( ) ; }
and the node s parent never changes . Still it doesn t hurt .
32,192
private synchronized float getInternal ( ) { int phaseCount = phases . size ( ) ; if ( phaseCount != 0 ) { float subProgress = currentPhase < phaseCount ? phase ( ) . getInternal ( ) : 0.0f ; return progressPerPhase * ( currentPhase + subProgress ) ; } else { return progress ; } }
Computes progress in this node .
32,193
private synchronized void reloadLocations ( ) { map . clear ( ) ; for ( HadoopServer location : ServerRegistry . getInstance ( ) . getServers ( ) ) map . put ( location , new DFSLocation ( provider , location ) ) ; }
Recompute the map of Hadoop locations
32,194
public static void incrLogMetrics ( Map < String , Long > incrMetrics ) { if ( incrMetrics == null || incrMetrics . size ( ) == 0 ) { return ; } MetricsRegistry registry = RaidNodeMetrics . getInstance ( RaidNodeMetrics . DEFAULT_NAMESPACE_ID ) . getMetricsRegistry ( ) ; Map < String , MetricsTimeVaryingLong > logMetri...
Increase logMetrics in the Raidnode metrics
32,195
static java . net . InetAddress getLocalAddress ( ) throws IOException { try { return java . net . InetAddress . getLocalHost ( ) ; } catch ( java . net . UnknownHostException e ) { throw new IOException ( e ) ; } }
A helper function to get the local address of the machine
32,196
private ServerSocket initializeServer ( CoronaConf conf ) throws IOException { ServerSocket sessionServerSocket = new ServerSocket ( 0 , 0 , getLocalAddress ( ) ) ; TServerSocket tServerSocket = new TServerSocket ( sessionServerSocket , conf . getCMSoTimeout ( ) ) ; TFactoryBasedThreadPoolServer . Args args = new TFact...
Start the SessionDriver callback server
32,197
public void setName ( String name ) throws IOException { if ( failException != null ) { throw failException ; } if ( name == null || name . length ( ) == 0 ) { return ; } sessionInfo . name = name ; SessionInfo newInfo = new SessionInfo ( sessionInfo ) ; cmNotifier . addCall ( new ClusterManagerService . sessionUpdateI...
Set the name for this session in the ClusterManager
32,198
public void setPriority ( SessionPriority prio ) throws IOException { if ( failException != null ) { throw failException ; } sessionInfo . priority = prio ; SessionInfo newInfo = new SessionInfo ( sessionInfo ) ; cmNotifier . addCall ( new ClusterManagerService . sessionUpdateInfo_args ( sessionId , newInfo ) ) ; }
Set the priority for this session in the ClusterManager
32,199
public void setDeadline ( long sessionDeadline ) throws IOException { if ( failException != null ) { throw failException ; } sessionInfo . deadline = sessionDeadline ; SessionInfo newInfo = new SessionInfo ( sessionInfo ) ; cmNotifier . addCall ( new ClusterManagerService . sessionUpdateInfo_args ( sessionId , newInfo ...
Set the deadline for this session in the ClusterManager