idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
33,000
public INode [ ] getExistingPathINodes ( String path ) { byte [ ] [ ] components = getPathComponents ( path ) ; INode [ ] inodes = new INode [ components . length ] ; this . getExistingPathINodes ( components , inodes ) ; return inodes ; }
Retrieve the existing INodes along the given path . The first INode always exist and is this INode .
33,001
int nextChild ( byte [ ] name ) { if ( name . length == 0 ) { return 0 ; } int nextPos = Collections . binarySearch ( children , name ) + 1 ; if ( nextPos >= 0 ) { return nextPos ; } return - nextPos ; }
Search all children for the first child whose name is greater than the given name .
33,002
< T extends INode > T addNode ( String path , T newNode , boolean inheritPermission ) throws FileNotFoundException { byte [ ] [ ] pathComponents = getPathComponents ( path ) ; if ( addToParent ( pathComponents , newNode , inheritPermission , true ) == null ) return null ; return newNode ; }
Add new INode to the file tree . Find the parent and insert
33,003
private long [ ] computeContentSummary ( long [ ] summary , Set < Long > visitedCtx ) { if ( children != null ) { for ( INode child : children ) { if ( child . isDirectory ( ) ) { ( ( INodeDirectory ) child ) . computeContentSummary ( summary , visitedCtx ) ; } else { if ( child instanceof INodeHardLinkFile ) { long ha...
Compute the content summary and skip calculating the visited hard link file .
33,004
public void countItems ( ) { itemCounts = new ItemCounts ( ) ; itemCounts . startTime = System . currentTimeMillis ( ) ; itemCounts . numDirectories = 1 ; itemCounts . numFiles = 0 ; itemCounts . numBlocks = 0 ; if ( children != null ) { for ( INode child : children ) { countItemsRecursively ( child ) ; } } itemCounts ...
Count items under the current directory
33,005
static String stringifySolution ( int size , List < List < ColumnName > > solution ) { int [ ] [ ] picture = new int [ size ] [ size ] ; StringBuffer result = new StringBuffer ( ) ; for ( List < ColumnName > row : solution ) { int x = - 1 ; int y = - 1 ; int num = - 1 ; for ( ColumnName item : row ) { if ( item instanc...
A string containing a representation of the solution .
33,006
private boolean [ ] generateRow ( boolean [ ] rowValues , int x , int y , int num ) { for ( int i = 0 ; i < rowValues . length ; ++ i ) { rowValues [ i ] = false ; } int xBox = ( int ) x / squareXSize ; int yBox = ( int ) y / squareYSize ; rowValues [ x * size + num - 1 ] = true ; rowValues [ size * size + y * size + n...
Create a row that places num in cell x y .
33,007
public static void main ( String [ ] args ) throws IOException { if ( args . length == 0 ) { System . out . println ( "Include a puzzle on the command line." ) ; } for ( int i = 0 ; i < args . length ; ++ i ) { Sudoku problem = new Sudoku ( new FileInputStream ( args [ i ] ) ) ; System . out . println ( "Solving " + ar...
Solves a set of sudoku puzzles .
33,008
public boolean delete ( Path path , boolean recursive ) throws IOException { Path absolute = makeAbsolute ( path ) ; String srep = absolute . toUri ( ) . getPath ( ) ; if ( kfsImpl . isFile ( srep ) ) return kfsImpl . remove ( srep ) == 0 ; FileStatus [ ] dirEntries = listStatus ( absolute ) ; if ( ( ! recursive ) && (...
recursively delete the directory and its contents
33,009
public BlockLocation [ ] getFileBlockLocations ( FileStatus file , long start , long len ) throws IOException { if ( file == null ) { return null ; } String srep = makeAbsolute ( file . getPath ( ) ) . toUri ( ) . getPath ( ) ; String [ ] [ ] hints = kfsImpl . getDataLocation ( srep , start , len ) ; if ( hints == null...
Return null if the file doesn t exist ; otherwise get the locations of the various chunks of the file file from KFS .
33,010
void verifyQuota ( long nsDelta , long dsDelta ) throws QuotaExceededException { long newCount = nsCount + nsDelta ; long newDiskspace = diskspace + dsDelta ; if ( nsDelta > 0 || dsDelta > 0 ) { if ( nsQuota >= 0 && nsQuota < newCount ) { throw new NSQuotaExceededException ( nsQuota , newCount ) ; } if ( dsQuota >= 0 &...
Verify if the namespace count disk space satisfies the quota restriction
33,011
public static void checkVersionUpgradable ( int oldVersion ) throws IOException { if ( oldVersion > LAST_UPGRADABLE_LAYOUT_VERSION ) { String msg = "*********** Upgrade is not supported from this older" + " version of storage to the current version." + " Please upgrade to " + LAST_UPGRADABLE_HADOOP_VERSION + " or a lat...
Checks if the upgrade from the given old version is supported . If no upgrade is supported it throws IncorrectVersionException .
33,012
protected void getFields ( Properties props , StorageDirectory sd ) throws IOException { String sv , st , sid , sct ; sv = props . getProperty ( LAYOUT_VERSION ) ; st = props . getProperty ( STORAGE_TYPE ) ; sid = props . getProperty ( NAMESPACE_ID ) ; sct = props . getProperty ( CHECK_TIME ) ; if ( sv == null || st ==...
Get common storage fields . Should be overloaded if additional fields need to be get .
33,013
public void writeAll ( ) throws IOException { this . layoutVersion = FSConstants . LAYOUT_VERSION ; for ( Iterator < StorageDirectory > it = storageDirs . iterator ( ) ; it . hasNext ( ) ; ) { it . next ( ) . write ( ) ; } }
Write all data storage files .
33,014
public void unlockAll ( ) throws IOException { for ( Iterator < StorageDirectory > it = storageDirs . iterator ( ) ; it . hasNext ( ) ; ) { it . next ( ) . unlock ( ) ; } }
Unlock all storage directories .
33,015
public boolean isLockSupported ( int idx ) throws IOException { StorageDirectory sd = storageDirs . get ( idx ) ; FileLock firstLock = null ; FileLock secondLock = null ; try { firstLock = sd . lock ; if ( firstLock == null ) { firstLock = sd . tryLock ( ) ; if ( firstLock == null ) return true ; } secondLock = sd . tr...
Check whether underlying file system supports file locking .
33,016
public void write ( JsonGenerator jsonGenerator ) throws IOException { jsonGenerator . writeStartObject ( ) ; int totalSessionsToCtx = 0 , totalDeletedSessions = 0 ; for ( int i = 0 ; i < numNotifierThreads ; i ++ ) { totalSessionsToCtx += notifierThreads [ i ] . sessionsToCtx . size ( ) ; totalDeletedSessions += notif...
Used to write the state of the SessionNotifier instance to disk when we are persisting the state of the ClusterManager
33,017
public void restoreAfterSafeModeRestart ( ) { for ( Map . Entry < String , SessionNotificationCtx > entry : sessionsToCtxFromDisk . entrySet ( ) ) { entry . getValue ( ) . setConf ( conf ) ; handleToNotifier ( entry . getKey ( ) ) . sessionsToCtx . put ( entry . getKey ( ) , entry . getValue ( ) ) ; sessionsToCtxFromDi...
This method rebuilds members related to the SessionNotifier instance which were not directly persisted themselves .
33,018
public static void checkSuperuserPrivilege ( UserGroupInformation owner , String supergroup ) throws AccessControlException { PermissionChecker checker = new PermissionChecker ( owner . getUserName ( ) , supergroup ) ; if ( ! checker . isSuper ) { throw new AccessControlException ( "Access denied for user " + checker ....
Verify if the caller has the required permission . This will result into an exception if the caller is not allowed to access the resource .
33,019
public int getMaxSlots ( TaskTrackerStatus status , TaskType type ) { return ( type == TaskType . MAP ) ? status . getMaxMapSlots ( ) : status . getMaxReduceSlots ( ) ; }
Obtain the overall number of the slots limit of a tasktracker
33,020
public static void rename ( FileSystem fs , String oldName , String newName ) throws IOException { Path oldDir = new Path ( oldName ) ; Path newDir = new Path ( newName ) ; if ( ! fs . rename ( oldDir , newDir ) ) { throw new IOException ( "Could not rename " + oldDir + " to " + newDir ) ; } }
Renames an existing map directory .
33,021
public static void delete ( FileSystem fs , String name ) throws IOException { Path dir = new Path ( name ) ; Path data = new Path ( dir , DATA_FILE_NAME ) ; Path index = new Path ( dir , INDEX_FILE_NAME ) ; fs . delete ( data , true ) ; fs . delete ( index , true ) ; fs . delete ( dir , true ) ; }
Deletes the named map file .
33,022
public static long fix ( FileSystem fs , Path dir , Class < ? extends Writable > keyClass , Class < ? extends Writable > valueClass , boolean dryrun , Configuration conf ) throws Exception { String dr = ( dryrun ? "[DRY RUN ] " : "" ) ; Path data = new Path ( dir , DATA_FILE_NAME ) ; Path index = new Path ( dir , INDEX...
This method attempts to fix a corrupt MapFile by re - creating its index .
33,023
private void findConfigFiles ( ) { if ( configFileName == null ) { String jsonConfigFileString = conf . getConfigFile ( ) . replace ( CoronaConf . DEFAULT_CONFIG_FILE , Configuration . MATERIALIZEDJSON ) ; File jsonConfigFile = new File ( jsonConfigFileString ) ; String jsonConfigFileName = null ; if ( jsonConfigFile ....
Find the configuration files as set file names or in the classpath .
33,024
public synchronized double getWeight ( PoolInfo poolInfo ) { Double weight = ( poolInfoToWeight == null ) ? null : poolInfoToWeight . get ( poolInfo ) ; return weight == null ? 1.0 : weight ; }
Get the weight for the pool
33,025
public synchronized int getPriority ( PoolInfo poolInfo ) { Integer priority = ( poolInfoToPriority == null ) ? null : poolInfoToPriority . get ( poolInfo ) ; return priority == null ? 0 : priority ; }
Get the priority for the pool
33,026
public synchronized ScheduleComparator getPoolComparator ( PoolInfo poolInfo ) { ScheduleComparator comparator = ( poolInfoToComparator == null ) ? null : poolInfoToComparator . get ( poolInfo ) ; return comparator == null ? defaultPoolComparator : comparator ; }
Get the comparator to use for scheduling sessions within a pool
33,027
public synchronized long getLocalityWait ( ResourceType type , LocalityLevel level ) { if ( level == LocalityLevel . ANY ) { return 0L ; } Long wait = level == LocalityLevel . NODE ? typeToNodeWait . get ( type ) : typeToRackWait . get ( type ) ; if ( wait == null ) { throw new IllegalArgumentException ( "Unknown type:...
Get the locality wait to be used by the scheduler for a given ResourceType on a given LocalityLevel
33,028
public String generatePoolsConfigIfClassSet ( ) { if ( poolsConfigDocumentGenerator == null ) { return null ; } Document document = poolsConfigDocumentGenerator . generatePoolsDocument ( ) ; if ( document == null ) { LOG . warn ( "generatePoolsConfig: Did not generate a valid pools xml file" ) ; return null ; } File te...
Generate the new pools configuration using the configuration generator . The generated configuration is written to a temporary file and then atomically renamed to the specified destination file . This function may be called concurrently and it is safe to do so because of the atomic rename to the destination file .
33,029
public synchronized boolean reloadAllConfig ( boolean init ) throws IOException , SAXException , ParserConfigurationException , JSONException { if ( ! isConfigChanged ( init ) ) { return false ; } reloadConfig ( ) ; reloadPoolsConfig ( ) ; this . lastSuccessfulReload = ClusterManager . clock . getTime ( ) ; return true...
Reload all the configuration files if the config changed and set the last successful reload time . Synchronized due to potential conflict from a fetch pools config http request .
33,030
private boolean isConfigChanged ( boolean init ) throws IOException { if ( init && ( configFileName == null || ( poolsConfigFileName == null && conf . onlyAllowConfiguredPools ( ) ) ) ) { throw new IOException ( "ClusterManager needs a config and a " + "pools file to start" ) ; } if ( configFileName == null && poolsCon...
Check if the config files have changed since they were last read
33,031
private Element getRootElement ( String fileName ) throws IOException , SAXException , ParserConfigurationException { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; docBuilderFactory . setIgnoringComments ( true ) ; DocumentBuilder builder = docBuilderFactory . newDocumentBuilder ...
Get the root element of the XML document
33,032
private static String getText ( Element element ) { if ( element . getFirstChild ( ) == null ) { return "" ; } return ( ( Text ) element . getFirstChild ( ) ) . getData ( ) . trim ( ) ; }
Get the text inside of the Xml element
33,033
public synchronized void incrementLoad ( ResourceType type ) { Integer load = typeToTotalLoad . get ( type ) ; assert ( load != null ) ; typeToTotalLoad . put ( type , load + 1 ) ; }
Increment the number of running resources of a given type .
33,034
private Pair < String , String > readBalancedLine ( ) throws IOException { String line = readCountedLine ( ) ; if ( line == null ) { return null ; } while ( line . indexOf ( '\f' ) > 0 ) { line = line . substring ( line . indexOf ( '\f' ) ) ; } if ( line . length ( ) != 0 && line . charAt ( 0 ) == '\f' ) { String subje...
no more input .
33,035
public Configuration initializeConf ( String [ ] keys , Configuration conf , FileSystem fs ) throws IOException { Configuration newConf = new Configuration ( conf ) ; if ( fs == null ) { fs = FileSystem . get ( conf ) ; } String suffix = fs . getUri ( ) . getAuthority ( ) ; for ( String key : keys ) { String value = co...
Initialize the config based on the given Filesystem
33,036
public void go ( EditsVisitor visitor ) throws IOException { setEditsLoader ( EditsLoader . LoaderFactory . getLoader ( visitor ) ) ; editsLoader . loadEdits ( ) ; }
Process EditLog file .
33,037
private void printHelp ( ) { String summary = "Usage: bin/hdfs oev [OPTIONS] -i INPUT_FILE -o OUTPUT_FILE\n" + "Offline edits viewer\n" + "Parse a Hadoop edits log file INPUT_FILE and save results\n" + "in OUTPUT_FILE.\n" + "Required command line arguments:\n" + "-i,--inputFile <arg> edits file to process, xml (case\...
Print help .
33,038
public static PrintWriter initHTML ( ServletResponse response , String title ) throws IOException { response . setContentType ( "text/html" ) ; PrintWriter out = response . getWriter ( ) ; out . println ( "<html>\n" + "<link rel='stylesheet' type='text/css' href='/static/hadoop.css'>\n" + "<title>" + title + "</title>\...
Initial HTML header
33,039
public static String getParameter ( ServletRequest request , String name ) { String s = request . getParameter ( name ) ; if ( s == null ) { return null ; } s = s . trim ( ) ; return s . length ( ) == 0 ? null : s ; }
Get a parameter from a ServletRequest . Return null if the parameter contains only white spaces .
33,040
public static String percentageGraph ( int perc , int width ) throws IOException { assert perc >= 0 ; assert perc <= 100 ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<table border=\"1px\" width=\"" ) ; builder . append ( width ) ; builder . append ( "px\"><tr>" ) ; if ( perc > 0 ) { builder . a...
Generate the percentage graph and returns HTML representation string of the same .
33,041
public void write ( JsonGenerator jsonGenerator ) throws IOException { jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeStringField ( "handle" , handle ) ; jsonGenerator . writeStringField ( "host" , host ) ; jsonGenerator . writeNumberField ( "port" , port ) ; jsonGenerator . writeNumberField ( "numPendingC...
Used to write the state of the SessionNotificationCtx instance to disk when we are persisting the state of the ClusterManager
33,042
public boolean makeCalls ( long now ) { if ( now < nextDispatchTime ) return true ; while ( ! pendingCalls . isEmpty ( ) ) { TBase call = pendingCalls . get ( 0 ) ; try { init ( ) ; dispatchCall ( call ) ; nextDispatchTime = - 1 ; numRetries = 0 ; currentRetryInterval = retryIntervalStart ; pendingCalls . remove ( 0 ) ...
make callbacks to the sessiondriver . if the function returns false then the session should be discarded
33,043
public static List < Class < ? extends CompressionCodec > > getCodecClasses ( Configuration conf ) { String codecsString = conf . get ( "io.compression.codecs" ) ; if ( codecsString != null ) { List < Class < ? extends CompressionCodec > > result = new ArrayList < Class < ? extends CompressionCodec > > ( ) ; StringToke...
Get the list of codecs listed in the configuration
33,044
public static void setCodecClasses ( Configuration conf , List < Class > classes ) { StringBuffer buf = new StringBuffer ( ) ; Iterator < Class > itr = classes . iterator ( ) ; if ( itr . hasNext ( ) ) { Class cls = itr . next ( ) ; buf . append ( cls . getName ( ) ) ; while ( itr . hasNext ( ) ) { buf . append ( ',' )...
Sets a list of codec classes in the configuration .
33,045
public CompressionCodec getCodec ( Path file ) { CompressionCodec result = null ; if ( codecs != null ) { String filename = file . getName ( ) ; String reversedFilename = new StringBuffer ( filename ) . reverse ( ) . toString ( ) ; SortedMap < String , CompressionCodec > subMap = codecs . headMap ( reversedFilename ) ;...
Find the relevant compression codec for the given file based on its filename suffix .
33,046
public CompressionCodec getCodecByClassName ( String classname ) { if ( codecsByClassName == null ) { return null ; } return codecsByClassName . get ( classname ) ; }
Find the relevant compression codec for the codec s canonical class name .
33,047
public static String removeSuffix ( String filename , String suffix ) { if ( filename . endsWith ( suffix ) ) { return filename . substring ( 0 , filename . length ( ) - suffix . length ( ) ) ; } return filename ; }
Removes a suffix from a filename if it has it .
33,048
public static void main ( String [ ] args ) throws Exception { Configuration conf = new Configuration ( ) ; CompressionCodecFactory factory = new CompressionCodecFactory ( conf ) ; boolean encode = false ; for ( int i = 0 ; i < args . length ; ++ i ) { if ( "-in" . equals ( args [ i ] ) ) { encode = true ; } else if ( ...
A little test program .
33,049
public void setInsert ( Document doc ) { this . op = Op . INSERT ; this . doc = doc ; this . term = null ; }
Set the instance to be an insert operation .
33,050
public void setDelete ( Term term ) { this . op = Op . DELETE ; this . doc = null ; this . term = term ; }
Set the instance to be a delete operation .
33,051
public void setUpdate ( Document doc , Term term ) { this . op = Op . UPDATE ; this . doc = doc ; this . term = term ; }
Set the instance to be an update operation .
33,052
public static < T extends VersionedProtocol > ProtocolProxy < T > getProtocolProxy ( Class < T > protocol , long clientVersion , InetSocketAddress addr , Configuration conf , SocketFactory factory ) throws IOException { UserGroupInformation ugi = null ; try { ugi = UserGroupInformation . login ( conf ) ; } catch ( Logi...
Construct a client - side protocol proxy that contains a set of server methods and a proxy object implementing the named protocol talking to a server at the named address .
33,053
@ SuppressWarnings ( "unchecked" ) public static < T extends VersionedProtocol > ProtocolProxy < T > getProtocolProxy ( Class < T > protocol , long clientVersion , InetSocketAddress addr , UserGroupInformation ticket , Configuration conf , SocketFactory factory , int rpcTimeout ) throws IOException { T proxy = ( T ) Pr...
Construct a client - side proxy that implements the named protocol talking to a server at the named address .
33,054
public boolean reportChecksumFailure ( Path p , FSDataInputStream in , long inPos , FSDataInputStream sums , long sumsPos ) { try { File f = ( ( RawLocalFileSystem ) fs ) . pathToFile ( p ) . getCanonicalFile ( ) ; String device = new DF ( f , getConf ( ) ) . getMount ( ) ; File parent = f . getParentFile ( ) ; File di...
Moves files to a bad file directory on the same device so that their storage will not be reused .
33,055
public IndexRecord getIndex ( int partition ) { final int pos = partition * MapTask . MAP_OUTPUT_INDEX_RECORD_LENGTH / 8 ; return new IndexRecord ( entries . get ( pos ) , entries . get ( pos + 1 ) , entries . get ( pos + 2 ) ) ; }
Get spill offsets for given partition .
33,056
public void putIndex ( IndexRecord rec , int partition ) { final int pos = partition * MapTask . MAP_OUTPUT_INDEX_RECORD_LENGTH / 8 ; entries . put ( pos , rec . startOffset ) ; entries . put ( pos + 1 , rec . rawLength ) ; entries . put ( pos + 2 , rec . partLength ) ; }
Set spill offsets for given partition .
33,057
public void writeToFile ( Path loc , JobConf job ) throws IOException { writeToFile ( loc , job , new PureJavaCrc32 ( ) ) ; }
Write this spill record to the location provided .
33,058
static void printFilterInfo ( PrintWriter out , String poolFilter , String userFilter , String showAllLink ) { if ( userFilter != null || poolFilter != null ) { StringBuilder customizedInfo = new StringBuilder ( "Only showing " ) ; if ( poolFilter != null ) { customizedInfo . append ( "pool(s) " + poolFilter ) ; } if (...
Print the filter information for pools and users
33,059
private void showAdminFormPreemption ( PrintWriter out , boolean advancedView ) { out . print ( "<h2>Task Preemption</h2>\n" ) ; String advParam = advancedView ? "&advanced" : "" ; out . print ( generateSelect ( Arrays . asList ( "On,Off" . split ( "," ) ) , scheduler . isPreemptionEnabled ( ) ? "On" : "Off" , "/fairsc...
Print the administration form for preemption
33,060
private void showAdminFormMemBasedLoadMgr ( PrintWriter out , boolean advancedView ) { if ( ! ( loadMgr instanceof MemBasedLoadManager ) ) { return ; } out . print ( "<h2>Memory Based Scheduling</h2>\n" ) ; MemBasedLoadManager memLoadMgr = ( MemBasedLoadManager ) loadMgr ; Collection < String > possibleThresholds = Arr...
Print the administration form for the MemBasedLoadManager
33,061
static void showCluster ( PrintWriter out , boolean advancedView , JobTracker jobTracker ) { String cluster = "" ; try { cluster = JSPUtil . generateClusterResTable ( jobTracker ) ; if ( cluster . equals ( "" ) ) { return ; } } catch ( IOException e ) { return ; } out . print ( "<h2>Cluster Resource</h2>\n" ) ; out . p...
Print the cluster resource utilization
33,062
private void showNumTaskPerHeartBeatOption ( PrintWriter out , boolean advancedView ) { out . print ( "<h2>Number of Assigned Tasks Per HeartBeat</h2>\n" ) ; out . printf ( "<p>Number of map tasks assigned per heartbeat:%s" , generateSelect ( Arrays . asList ( "1,2,3,4,5,6,7,8,9,10" . split ( "," ) ) , scheduler . getM...
Print the UI that allows us to change the number of tasks assigned per heartbeat .
33,063
private Collection < JobInProgress > getInitedJobs ( ) { Collection < JobInProgress > runningJobs = jobTracker . getRunningJobs ( ) ; for ( Iterator < JobInProgress > it = runningJobs . iterator ( ) ; it . hasNext ( ) ; ) { JobInProgress job = it . next ( ) ; if ( ! job . inited ( ) ) { it . remove ( ) ; } } return run...
Obtained all initialized jobs
33,064
private static void setIfUnset ( JobConf conf , String key , String value ) { if ( conf . get ( key ) == null ) { conf . set ( key , value ) ; } }
Set the configuration if it doesn t already have a value for the given key .
33,065
public static void main ( String [ ] args ) throws Exception { int exitCode = new Submitter ( ) . run ( args ) ; System . exit ( exitCode ) ; }
Submit a pipes job based on the command line arguments .
33,066
private void loadEnabledPermissionCheckingDirs ( Configuration conf ) throws IOException { if ( this . isPermissionEnabled ) { String [ ] permissionCheckingDirs = conf . getStrings ( "dfs.permissions.checking.paths" , "/" ) ; int numDirs = permissionCheckingDirs . length ; if ( numDirs == 0 ) { return ; } this . permis...
Load the predefined paths that should enable permission checking each of which represents the root of a subtree whose nodes should check permission
33,067
private boolean isPermissionCheckingEnabled ( INode [ ] pathNodes ) { if ( this . isPermissionEnabled ) { if ( permissionEnabled == null ) { return false ; } for ( INode enableDir : this . permissionEnabled ) { for ( INode pathNode : pathNodes ) { if ( pathNode == enableDir ) { return true ; } } } return false ; } retu...
Check if a path is predefined to enable permission checking
33,068
private void setHeartbeatInterval ( long heartbeatInterval , long heartbeatRecheckInterval ) { this . heartbeatInterval = heartbeatInterval ; this . heartbeatRecheckInterval = heartbeatRecheckInterval ; this . heartbeatExpireInterval = 2 * heartbeatRecheckInterval + 10 * heartbeatInterval ; ReplicationConfigKeys . bloc...
Set parameters derived from heartbeat interval .
33,069
public void stopLeaseMonitor ( ) throws InterruptedException { if ( lmmonitor != null ) { lmmonitor . stop ( ) ; InjectionHandler . processEvent ( InjectionEvent . FSNAMESYSTEM_STOP_LEASEMANAGER ) ; } if ( lmthread != null ) { writeLock ( ) ; try { lmthread . interrupt ( ) ; } finally { writeUnlock ( ) ; } lmthread . j...
Stops lease monitor thread .
33,070
public void close ( ) { fsRunning = false ; try { if ( pendingReplications != null ) { pendingReplications . stop ( ) ; } if ( hbthread != null ) { hbthread . interrupt ( ) ; } if ( underreplthread != null ) { underreplthread . interrupt ( ) ; } if ( overreplthread != null ) { overreplthread . interrupt ( ) ; } if ( ra...
Close down this file system manager . Causes heartbeat and lease daemons to stop ; waits briefly for them to finish but a short timeout returns control back to caller .
33,071
void metaSave ( String filename ) throws IOException { readLock ( ) ; try { checkSuperuserPrivilege ( ) ; File file = new File ( System . getProperty ( "hadoop.log.dir" ) , filename ) ; PrintWriter out = new PrintWriter ( new BufferedWriter ( new FileWriter ( file , true ) ) ) ; synchronized ( neededReplications ) { ou...
Dump all metadata into specified file
33,072
private long addBlock ( Block block , List < BlockWithLocations > results ) { ArrayList < String > machineSet = new ArrayList < String > ( blocksMap . numNodes ( block ) ) ; for ( Iterator < DatanodeDescriptor > it = blocksMap . nodeIterator ( block ) ; it . hasNext ( ) ; ) { String storageID = it . next ( ) . getStora...
Get all valid locations of the block & add the block to results return the length of the added block ; 0 if the block is not added
33,073
public void setPermission ( String src , FsPermission permission ) throws IOException { INode [ ] inodes = null ; writeLock ( ) ; try { if ( isInSafeMode ( ) ) { throw new SafeModeException ( "Cannot set permission for " + src , safeMode ) ; } inodes = dir . getExistingPathINodes ( src ) ; if ( isPermissionCheckingEnab...
Set permissions for an existing file .
33,074
public void setOwner ( String src , String username , String group ) throws IOException { INode [ ] inodes = null ; writeLock ( ) ; try { if ( isInSafeMode ( ) ) { throw new SafeModeException ( "Cannot set permission for " + src , safeMode ) ; } inodes = dir . getExistingPathINodes ( src ) ; if ( isPermissionCheckingEn...
Set owner for an existing file .
33,075
LocatedBlocksWithMetaInfo updateDatanodeInfo ( LocatedBlocks locatedBlocks ) throws IOException { if ( locatedBlocks . getLocatedBlocks ( ) . size ( ) == 0 ) return new LocatedBlocksWithMetaInfo ( locatedBlocks . getFileLength ( ) , locatedBlocks . getLocatedBlocks ( ) , false , DataTransferProtocol . DATA_TRANSFER_VER...
Updates DatanodeInfo for each LocatedBlock in locatedBlocks .
33,076
public void setTimes ( String src , long mtime , long atime ) throws IOException { if ( ! accessTimeTouchable && atime != - 1 ) { throw new AccessTimeException ( "setTimes is not allowed for accessTime" ) ; } setTimesInternal ( src , mtime , atime ) ; getEditLog ( ) . logSync ( false ) ; }
stores the modification and access time for this inode . The access time is precise upto an hour . The transaction if needed is written to the edits log but is not flushed .
33,077
private void verifyReplication ( String src , short replication , String clientName ) throws IOException { String text = "file " + src + ( ( clientName != null ) ? " on client " + clientName : "" ) + ".\n" + "Requested replication " + replication ; if ( replication > maxReplication ) { throw new IOException ( text + " ...
Check whether the replication parameter is within the range determined by system configuration .
33,078
void startFile ( String src , PermissionStatus permissions , String holder , String clientMachine , boolean overwrite , boolean createParent , short replication , long blockSize ) throws IOException { INodeFileUnderConstruction file = startFileInternal ( src , permissions , holder , clientMachine , overwrite , false , ...
Create a new file entry in the namespace .
33,079
boolean recoverLease ( String src , String holder , String clientMachine , boolean discardLastBlock ) throws IOException { byte [ ] [ ] components = INodeDirectory . getPathComponents ( src ) ; writeLock ( ) ; try { if ( isInSafeMode ( ) ) { throw new SafeModeException ( "Cannot recover the lease of " + src , safeMode ...
Recover lease ; Immediately revoke the lease of the current lease holder and start lease recovery so that the file can be forced to be closed .
33,080
public LocatedBlock getAdditionalBlock ( String src , String clientName ) throws IOException { return getAdditionalBlock ( src , clientName , null ) ; }
Stub for old callers pre - HDFS - 630
33,081
private DatanodeDescriptor [ ] findBestDatanodeInCluster ( List < DatanodeInfo > infos , int replication ) throws IOException { int targetReplication = Math . min ( infos . size ( ) , replication ) ; DatanodeDescriptor [ ] dns = new DatanodeDescriptor [ targetReplication ] ; boolean [ ] changedRacks = new boolean [ tar...
Given information about an array of datanodes returns an array of DatanodeDescriptors for the same or if it doesn t find the datanode it looks for a machine local and then rack local datanode if a rack local datanode is not possible either it returns the DatanodeDescriptor of any random node in the cluster .
33,082
private void setLastBlockSize ( INodeFileUnderConstruction pendingFile ) { Block block = pendingFile . getLastBlock ( ) ; if ( block != null ) { block . setNumBytes ( pendingFile . getPreferredBlockSize ( ) ) ; } }
Set last block s block size to be the file s default block size
33,083
private void replicateLastBlock ( String src , INodeFileUnderConstruction file ) { BlockInfo [ ] blks = file . getBlocks ( ) ; if ( blks == null || blks . length == 0 ) return ; BlockInfo block = blks [ blks . length - 1 ] ; DatanodeDescriptor [ ] targets = file . getValidTargets ( ) ; final int numOfTargets = targets ...
Check last block of the file under construction Replicate it if it is under replicated
33,084
public boolean abandonBlock ( Block b , String src , String holder ) throws IOException { writeLock ( ) ; try { if ( NameNode . stateChangeLog . isDebugEnabled ( ) ) { NameNode . stateChangeLog . debug ( "BLOCK* NameSystem.abandonBlock: " + b + "of file " + src ) ; } if ( isInSafeMode ( ) ) { throw new SafeModeExceptio...
The client would like to let go of the given block
33,085
private INodeFileUnderConstruction checkLease ( String src , String holder ) throws IOException { INodeFile file = dir . getFileINode ( src ) ; return checkLease ( src , holder , file ) ; }
make sure that we still have the lease on this file .
33,086
private Block allocateBlock ( String src , INode [ ] inodes ) throws IOException { Block b = new Block ( generateBlockId ( ) , 0 , 0 ) ; while ( isValidBlock ( b ) ) { b . setBlockId ( generateBlockId ( ) ) ; } b . setGenerationStamp ( getGenerationStamp ( ) ) ; b = dir . addBlock ( src , inodes , b ) ; return b ; }
Allocate a block at the given pending filename
33,087
private Block [ ] allocateParityBlocks ( int numParityBlocks ) throws IOException { Block [ ] blocks = new Block [ numParityBlocks ] ; for ( int i = 0 ; i < numParityBlocks ; i ++ ) { Block b = new Block ( generateBlockId ( ) , 0 , 0 ) ; while ( isValidBlock ( b ) ) { b . setBlockId ( generateBlockId ( ) ) ; } b . setG...
Allocate a number of parity blocks Require a write lock
33,088
boolean checkFileProgress ( INodeFile v , boolean checkall ) throws IOException { INode . enforceRegularStorageINode ( v , "checkFileProgress is not supported for non-regular files" ) ; if ( checkall ) { int closeFileReplicationMin = Math . min ( v . getReplication ( ) , this . minCloseReplication ) ; for ( Block block...
Check that the indicated file s blocks are present and replicated . If not return false . If checkall is true then check all blocks otherwise check only penultimate block .
33,089
void removeFromInvalidates ( String storageID ) { LightWeightHashSet < Block > blocks = recentInvalidateSets . remove ( storageID ) ; if ( blocks != null ) { pendingDeletionBlocksCount -= blocks . size ( ) ; } }
Remove a datanode from the invalidatesSet
33,090
void addToInvalidates ( Block b , DatanodeInfo n , boolean ackRequired ) { addToInvalidatesNoLog ( b , n , ackRequired ) ; if ( isInitialized && ! isInSafeModeInternal ( ) ) { NameNode . stateChangeLog . info ( "BLOCK* NameSystem.addToInvalidates: " + b . getBlockName ( ) + " is added to invalidSet of " + n . getName (...
Adds block to list of blocks which will be invalidated on specified datanode and log the move
33,091
void addToInvalidatesNoLog ( Block b , DatanodeInfo n , boolean ackRequired ) { if ( this . getNameNode ( ) . shouldRetryAbsentBlocks ( ) ) { return ; } LightWeightHashSet < Block > invalidateSet = recentInvalidateSets . get ( n . getStorageID ( ) ) ; if ( invalidateSet == null ) { invalidateSet = new LightWeightHashSe...
Adds block to list of blocks which will be invalidated on specified datanode
33,092
private void addToInvalidates ( Block b , boolean ackRequired ) { StringBuilder sb = new StringBuilder ( ) ; for ( Iterator < DatanodeDescriptor > it = blocksMap . nodeIterator ( b ) ; it . hasNext ( ) ; ) { DatanodeDescriptor node = it . next ( ) ; addToInvalidatesNoLog ( b , node , ackRequired ) ; sb . append ( node ...
Adds block to list of blocks which will be invalidated on all its datanodes .
33,093
public void markBlockAsCorrupt ( Block blk , DatanodeInfo dn , final boolean parallelInitialBlockReport ) throws IOException { if ( ! parallelInitialBlockReport ) { writeLock ( ) ; } lockParallelBRLock ( parallelInitialBlockReport ) ; try { DatanodeDescriptor node = getDatanode ( dn ) ; if ( node == null ) { throw new ...
Mark the block belonging to datanode as corrupt
33,094
private void invalidateBlock ( Block blk , DatanodeInfo dn , boolean ackRequired ) throws IOException { NameNode . stateChangeLog . info ( "DIR* NameSystem.invalidateBlock: " + blk + " on " + dn . getName ( ) ) ; DatanodeDescriptor node = getDatanode ( dn ) ; if ( node == null ) { throw new IOException ( "Cannot invali...
Invalidates the given block on the given datanode .
33,095
public boolean hardLinkTo ( String src , String dst ) throws IOException { INode dstNode = hardLinkToInternal ( src , dst ) ; getEditLog ( ) . logSync ( false ) ; if ( dstNode != null && auditLog . isInfoEnabled ( ) ) { logAuditEvent ( getCurrentUGI ( ) , Server . getRemoteIp ( ) , "hardlink" , src , dst , dstNode ) ; ...
Create the hard link from src file to the dest file .
33,096
boolean deleteInternal ( String src , INode [ ] inodes , boolean recursive , boolean enforcePermission ) throws IOException { ArrayList < BlockInfo > collectedBlocks = new ArrayList < BlockInfo > ( ) ; INode targetNode = null ; byte [ ] [ ] components = inodes == null ? INodeDirectory . getPathComponents ( src ) : null...
Remove the indicated filename from the namespace . This may invalidate some blocks that make up the file .
33,097
private void removeBlocks ( List < BlockInfo > blocks ) { if ( blocks == null ) { return ; } for ( BlockInfo b : blocks ) { removeFromExcessReplicateMap ( b ) ; neededReplications . remove ( b , - 1 ) ; corruptReplicas . removeFromCorruptReplicasMap ( b ) ; if ( pendingReplications != null ) { int replicas = pendingRep...
From the given list incrementally remove the blocks . Add the blocks to invalidates and set a flag that explicit ACK from DataNode is not required . This function should be used only for deleting entire files .
33,098
void removePathAndBlocks ( String src , List < BlockInfo > blocks ) throws IOException { assert ( ! nameNode . isRpcServerRunning ( ) || hasWriteLock ( ) ) ; leaseManager . removeLeaseWithPrefixPath ( src ) ; removeBlocks ( blocks ) ; }
Remove the blocks from the given list . Also remove the path . Add the blocks to invalidates and set a flag that explicit ACK from DataNode is not required . This function should be used only for deleting entire files .
33,099
void fsync ( String src , String clientName ) throws IOException { NameNode . stateChangeLog . info ( "BLOCK* NameSystem.fsync: file " + src + " for " + clientName ) ; writeLock ( ) ; try { if ( isInSafeMode ( ) ) { throw new SafeModeException ( "Cannot fsync file " + src , safeMode ) ; } INodeFileUnderConstruction pen...
Persist all metadata about this file .