idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
12,100 | public static void clearTimer ( String name ) { try ( LockResource r = new LockResource ( sLock ) ) { sTimers . remove ( name ) ; } } | Removes a timer name from the scheduler if it exists . |
12,101 | public static void removeTimer ( ScheduledTimer timer ) { Preconditions . checkNotNull ( timer , "timer" ) ; try ( LockResource r = new LockResource ( sLock ) ) { ScheduledTimer removedTimer = sTimers . remove ( timer . getThreadName ( ) ) ; Preconditions . checkNotNull ( removedTimer , "sTimers should contain %s" , timer . getThreadName ( ) ) ; Preconditions . checkState ( removedTimer == timer , "sTimers should contain the timer being removed" ) ; } } | Removes a timer from the scheduler . |
12,102 | public static void schedule ( String threadName ) { try ( LockResource r = new LockResource ( sLock ) ) { ScheduledTimer timer = sTimers . get ( threadName ) ; if ( timer == null ) { throw new RuntimeException ( "Timer for thread " + threadName + " not found." ) ; } timer . schedule ( ) ; } } | Schedules execution of a heartbeat for the given thread . |
12,103 | public static void await ( String name ) throws InterruptedException { try ( LockResource r = new LockResource ( sLock ) ) { while ( ! sTimers . containsKey ( name ) ) { sCondition . await ( ) ; } } } | Waits for the given thread to be ready to be scheduled . |
12,104 | public static void await ( String name , long time , TimeUnit unit ) throws InterruptedException { try ( LockResource r = new LockResource ( sLock ) ) { while ( ! sTimers . containsKey ( name ) ) { if ( ! sCondition . await ( time , unit ) ) { throw new RuntimeException ( "Timed out waiting for thread " + name + " to be ready for scheduling" ) ; } } } } | Waits until the given thread can be executed throwing an unchecked exception of the given timeout expires . |
12,105 | public static void execute ( String name ) throws InterruptedException { await ( name ) ; schedule ( name ) ; await ( name ) ; } | Convenience method for executing a heartbeat and waiting for it to complete . |
12,106 | private void chmod ( AlluxioURI path , String modeStr , boolean recursive ) throws AlluxioException , IOException { Mode mode = ModeParser . parse ( modeStr ) ; SetAttributePOptions options = SetAttributePOptions . newBuilder ( ) . setMode ( mode . toProto ( ) ) . setRecursive ( recursive ) . build ( ) ; mFileSystem . setAttribute ( path , options ) ; System . out . println ( "Changed permission of " + path + " to " + Integer . toOctalString ( mode . toShort ( ) ) ) ; } | Changes the permissions of directory or file with the path specified in args . |
12,107 | public static void main ( String [ ] args ) throws Exception { MesosExecutorDriver driver = new MesosExecutorDriver ( new AlluxioWorkerExecutor ( ) ) ; System . exit ( driver . run ( ) == Protos . Status . DRIVER_STOPPED ? 0 : 1 ) ; } | Starts the Alluxio worker executor . |
12,108 | public void checkDirectory ( InodeDirectory inode , AlluxioURI alluxioUri ) throws FileDoesNotExistException , InvalidPathException , IOException { Preconditions . checkArgument ( inode . isPersisted ( ) ) ; UfsStatus [ ] ufsChildren = getChildrenInUFS ( alluxioUri ) ; ufsChildren = Arrays . stream ( ufsChildren ) . filter ( ufsStatus -> ! PathUtils . isTemporaryFileName ( ufsStatus . getName ( ) ) ) . toArray ( UfsStatus [ ] :: new ) ; Arrays . sort ( ufsChildren , Comparator . comparing ( UfsStatus :: getName ) ) ; Inode [ ] alluxioChildren = Iterables . toArray ( mInodeStore . getChildren ( inode ) , Inode . class ) ; Arrays . sort ( alluxioChildren ) ; int ufsPos = 0 ; for ( Inode alluxioInode : alluxioChildren ) { if ( ufsPos >= ufsChildren . length ) { break ; } String ufsName = ufsChildren [ ufsPos ] . getName ( ) ; if ( ufsName . endsWith ( AlluxioURI . SEPARATOR ) ) { ufsName = ufsName . substring ( 0 , ufsName . length ( ) - 1 ) ; } if ( ufsName . equals ( alluxioInode . getName ( ) ) ) { ufsPos ++ ; } } if ( ufsPos == ufsChildren . length ) { mSyncedDirectories . put ( alluxioUri , inode ) ; } else { AlluxioURI currentPath = alluxioUri ; while ( currentPath . getParent ( ) != null && ! mMountTable . isMountPoint ( currentPath ) && mSyncedDirectories . containsKey ( currentPath . getParent ( ) ) ) { mSyncedDirectories . remove ( currentPath . getParent ( ) ) ; currentPath = currentPath . getParent ( ) ; } LOG . debug ( "Ufs file {} does not match any file in Alluxio" , ufsChildren [ ufsPos ] ) ; } } | Check if immediate children of directory are in sync with UFS . |
12,109 | private UfsStatus [ ] getChildrenInUFS ( AlluxioURI alluxioUri ) throws InvalidPathException , IOException { MountTable . Resolution resolution = mMountTable . resolve ( alluxioUri ) ; AlluxioURI ufsUri = resolution . getUri ( ) ; try ( CloseableResource < UnderFileSystem > ufsResource = resolution . acquireUfsResource ( ) ) { UnderFileSystem ufs = ufsResource . get ( ) ; AlluxioURI curUri = ufsUri ; while ( curUri != null ) { if ( mListedDirectories . containsKey ( curUri . toString ( ) ) ) { List < UfsStatus > childrenList = new ArrayList < > ( ) ; for ( UfsStatus childStatus : mListedDirectories . get ( curUri . toString ( ) ) ) { String childPath = PathUtils . concatPath ( curUri , childStatus . getName ( ) ) ; String prefix = PathUtils . normalizePath ( ufsUri . toString ( ) , AlluxioURI . SEPARATOR ) ; if ( childPath . startsWith ( prefix ) && childPath . length ( ) > prefix . length ( ) ) { UfsStatus newStatus = childStatus . copy ( ) ; newStatus . setName ( childPath . substring ( prefix . length ( ) ) ) ; childrenList . add ( newStatus ) ; } } return trimIndirect ( childrenList . toArray ( new UfsStatus [ childrenList . size ( ) ] ) ) ; } curUri = curUri . getParent ( ) ; } UfsStatus [ ] children = ufs . listStatus ( ufsUri . toString ( ) , ListOptions . defaults ( ) . setRecursive ( true ) ) ; if ( children == null ) { return EMPTY_CHILDREN ; } mListedDirectories . put ( ufsUri . toString ( ) , children ) ; return trimIndirect ( children ) ; } } | Get the children in under storage for given alluxio path . |
12,110 | private UfsStatus [ ] trimIndirect ( UfsStatus [ ] children ) { List < UfsStatus > childrenList = new ArrayList < > ( ) ; for ( UfsStatus child : children ) { int index = child . getName ( ) . indexOf ( AlluxioURI . SEPARATOR ) ; if ( index < 0 || index == child . getName ( ) . length ( ) ) { childrenList . add ( child ) ; } } return childrenList . toArray ( new UfsStatus [ childrenList . size ( ) ] ) ; } | Remove indirect children from children list returned from recursive listing . |
12,111 | @ Path ( WEBUI_CONFIG ) @ ReturnType ( "alluxio.wire.MasterWebUIConfiguration" ) public Response getWebUIConfiguration ( ) { return RestUtils . call ( ( ) -> { MasterWebUIConfiguration response = new MasterWebUIConfiguration ( ) ; response . setWhitelist ( mFileSystemMaster . getWhiteList ( ) ) ; TreeSet < Triple < String , String , String > > sortedProperties = new TreeSet < > ( ) ; Set < String > alluxioConfExcludes = Sets . newHashSet ( PropertyKey . MASTER_WHITELIST . toString ( ) ) ; for ( ConfigProperty configProperty : mMetaMaster . getConfiguration ( GetConfigurationPOptions . newBuilder ( ) . setRawValue ( true ) . build ( ) ) ) { String confName = configProperty . getName ( ) ; if ( ! alluxioConfExcludes . contains ( confName ) ) { sortedProperties . add ( new ImmutableTriple < > ( confName , ConfigurationUtils . valueAsString ( configProperty . getValue ( ) ) , configProperty . getSource ( ) ) ) ; } } response . setConfiguration ( sortedProperties ) ; return response ; } , ServerConfiguration . global ( ) ) ; } | Gets Web UI ServerConfiguration page data . |
12,112 | @ Path ( WEBUI_WORKERS ) @ ReturnType ( "alluxio.wire.MasterWebUIWorkers" ) public Response getWebUIWorkers ( ) { return RestUtils . call ( ( ) -> { MasterWebUIWorkers response = new MasterWebUIWorkers ( ) ; response . setDebug ( ServerConfiguration . getBoolean ( PropertyKey . DEBUG ) ) ; List < WorkerInfo > workerInfos = mBlockMaster . getWorkerInfoList ( ) ; NodeInfo [ ] normalNodeInfos = WebUtils . generateOrderedNodeInfos ( workerInfos ) ; response . setNormalNodeInfos ( normalNodeInfos ) ; List < WorkerInfo > lostWorkerInfos = mBlockMaster . getLostWorkersInfoList ( ) ; NodeInfo [ ] failedNodeInfos = WebUtils . generateOrderedNodeInfos ( lostWorkerInfos ) ; response . setFailedNodeInfos ( failedNodeInfos ) ; return response ; } , ServerConfiguration . global ( ) ) ; } | Gets Web UI workers page data . |
12,113 | public boolean logout ( ) throws LoginException { if ( mSubject . isReadOnly ( ) ) { throw new LoginException ( "logout Failed: Subject is Readonly." ) ; } if ( mUser != null ) { mSubject . getPrincipals ( ) . remove ( mUser ) ; } return true ; } | Logs out the user |
12,114 | public static boolean isAddressReachable ( String hostname , int port ) { try ( Socket socket = new Socket ( hostname , port ) ) { return true ; } catch ( IOException e ) { return false ; } } | Validates whether a network address is reachable . |
12,115 | public static boolean isAlluxioRunning ( String className ) { String [ ] command = { "bash" , "-c" , "ps -Aww -o command | grep -i \"[j]ava\" | grep " + className } ; try { Process p = Runtime . getRuntime ( ) . exec ( command ) ; try ( InputStreamReader input = new InputStreamReader ( p . getInputStream ( ) ) ) { if ( input . read ( ) >= 0 ) { return true ; } } return false ; } catch ( IOException e ) { System . err . format ( "Unable to check Alluxio status: %s.%n" , e . getMessage ( ) ) ; return false ; } } | Checks whether an Alluxio service is running . |
12,116 | public static boolean isMountingPoint ( String path , String [ ] fsTypes ) throws IOException { List < UnixMountInfo > infoList = ShellUtils . getUnixMountInfo ( ) ; for ( UnixMountInfo info : infoList ) { Optional < String > mountPoint = info . getMountPoint ( ) ; Optional < String > fsType = info . getFsType ( ) ; if ( mountPoint . isPresent ( ) && mountPoint . get ( ) . equals ( path ) && fsType . isPresent ( ) ) { for ( String expectedType : fsTypes ) { if ( fsType . get ( ) . equalsIgnoreCase ( expectedType ) ) { return true ; } } } } return false ; } | Checks whether a path is the mounting point of a RAM disk volume . |
12,117 | public static ProcessExecutionResult getResultFromProcess ( String [ ] args ) { try { Process process = Runtime . getRuntime ( ) . exec ( args ) ; StringBuilder outputSb = new StringBuilder ( ) ; try ( BufferedReader processOutputReader = new BufferedReader ( new InputStreamReader ( process . getInputStream ( ) ) ) ) { String line ; while ( ( line = processOutputReader . readLine ( ) ) != null ) { outputSb . append ( line ) ; outputSb . append ( LINE_SEPARATOR ) ; } } StringBuilder errorSb = new StringBuilder ( ) ; try ( BufferedReader processErrorReader = new BufferedReader ( new InputStreamReader ( process . getErrorStream ( ) ) ) ) { String line ; while ( ( line = processErrorReader . readLine ( ) ) != null ) { errorSb . append ( line ) ; errorSb . append ( LINE_SEPARATOR ) ; } } process . waitFor ( ) ; return new ProcessExecutionResult ( process . exitValue ( ) , outputSb . toString ( ) . trim ( ) , errorSb . toString ( ) . trim ( ) ) ; } catch ( IOException e ) { System . err . println ( "Failed to execute command." ) ; return new ProcessExecutionResult ( 1 , "" , e . getMessage ( ) ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; System . err . println ( "Interrupted." ) ; return new ProcessExecutionResult ( 1 , "" , e . getMessage ( ) ) ; } } | Executes a command in another process and check for its execution result . |
12,118 | public synchronized void updateStorageInfo ( ) { Map < String , Long > tierCapacities = mBlockWorker . getStoreMeta ( ) . getCapacityBytesOnTiers ( ) ; long lastTierReservedBytes = 0 ; for ( int ordinal = 0 ; ordinal < mStorageTierAssoc . size ( ) ; ordinal ++ ) { String tierAlias = mStorageTierAssoc . getAlias ( ordinal ) ; long tierCapacity = tierCapacities . get ( tierAlias ) ; long reservedSpace ; PropertyKey tierReservedSpaceProp = PropertyKey . Template . WORKER_TIERED_STORE_LEVEL_RESERVED_RATIO . format ( ordinal ) ; if ( ServerConfiguration . isSet ( tierReservedSpaceProp ) ) { LOG . warn ( "The property reserved.ratio is deprecated, use high/low watermark instead." ) ; reservedSpace = ( long ) ( tierCapacity * ServerConfiguration . getDouble ( tierReservedSpaceProp ) ) ; } else { PropertyKey tierHighWatermarkProp = PropertyKey . Template . WORKER_TIERED_STORE_LEVEL_HIGH_WATERMARK_RATIO . format ( ordinal ) ; double tierHighWatermarkConf = ServerConfiguration . getDouble ( tierHighWatermarkProp ) ; Preconditions . checkArgument ( tierHighWatermarkConf > 0 , "The high watermark of tier %s should be positive, but is %s" , Integer . toString ( ordinal ) , tierHighWatermarkConf ) ; Preconditions . checkArgument ( tierHighWatermarkConf < 1 , "The high watermark of tier %s should be less than 1.0, but is %s" , Integer . toString ( ordinal ) , tierHighWatermarkConf ) ; long highWatermark = ( long ) ( tierCapacity * ServerConfiguration . getDouble ( tierHighWatermarkProp ) ) ; mHighWatermarks . put ( tierAlias , highWatermark ) ; PropertyKey tierLowWatermarkProp = PropertyKey . Template . WORKER_TIERED_STORE_LEVEL_LOW_WATERMARK_RATIO . format ( ordinal ) ; double tierLowWatermarkConf = ServerConfiguration . getDouble ( tierLowWatermarkProp ) ; Preconditions . checkArgument ( tierLowWatermarkConf >= 0 , "The low watermark of tier %s should not be negative, but is %s" , Integer . toString ( ordinal ) , tierLowWatermarkConf ) ; Preconditions . checkArgument ( tierLowWatermarkConf < tierHighWatermarkConf , "The low watermark (%s) of tier %d should not be smaller than the high watermark (%s)" , tierLowWatermarkConf , ordinal , tierHighWatermarkConf ) ; reservedSpace = ( long ) ( tierCapacity - tierCapacity * ServerConfiguration . getDouble ( tierLowWatermarkProp ) ) ; } lastTierReservedBytes += reservedSpace ; lastTierReservedBytes = ( lastTierReservedBytes <= tierCapacity ) ? lastTierReservedBytes : tierCapacity ; mReservedSpaces . put ( tierAlias , lastTierReservedBytes ) ; } } | Re - calculates storage spaces and watermarks . |
12,119 | public static Mode applyFileUMask ( Mode mode , String authUmask ) { mode = applyUMask ( mode , getUMask ( authUmask ) ) ; mode = applyUMask ( mode , FILE_UMASK ) ; return mode ; } | Applies the default umask for newly created files to this mode . |
12,120 | public static Mode applyDirectoryUMask ( Mode mode , String authUmask ) { return applyUMask ( mode , getUMask ( authUmask ) ) ; } | Applies the default umask for newly created directories to this mode . |
12,121 | public void uploadFile ( String Key , File File ) throws QiniuException { com . qiniu . http . Response response = mUploadManager . put ( File , Key , mAuth . uploadToken ( mBucketName , Key ) ) ; response . close ( ) ; } | Puts Object to Qiniu kodo . |
12,122 | public void copyObject ( String src , String dst ) throws QiniuException { mBucketManager . copy ( mBucketName , src , mBucketName , dst ) ; } | Copys object in Qiniu kodo . |
12,123 | public void createEmptyObject ( String key ) throws QiniuException { com . qiniu . http . Response response = mUploadManager . put ( new byte [ 0 ] , key , mAuth . uploadToken ( mBucketName , key ) ) ; response . close ( ) ; } | Creates empty Object in Qiniu kodo . |
12,124 | public void deleteObject ( String key ) throws QiniuException { com . qiniu . http . Response response = mBucketManager . delete ( mBucketName , key ) ; response . close ( ) ; } | Deletes Object in Qiniu kodo . |
12,125 | public FileListing listFiles ( String prefix , String marker , int limit , String delimiter ) throws QiniuException { return mBucketManager . listFiles ( mBucketName , prefix , marker , limit , delimiter ) ; } | Lists object for Qiniu kodo . |
12,126 | public static Set < String > getNodeHosts ( YarnClient yarnClient ) throws YarnException , IOException { ImmutableSet . Builder < String > nodeHosts = ImmutableSet . builder ( ) ; for ( NodeReport runningNode : yarnClient . getNodeReports ( USABLE_NODE_STATES ) ) { nodeHosts . add ( runningNode . getNodeId ( ) . getHost ( ) ) ; } return nodeHosts . build ( ) ; } | Returns the host names for all nodes in yarnClient s YARN cluster . |
12,127 | public static LocalResource createLocalResourceOfFile ( YarnConfiguration yarnConf , String resource ) throws IOException { LocalResource localResource = Records . newRecord ( LocalResource . class ) ; Path resourcePath = new Path ( resource ) ; FileStatus jarStat = FileSystem . get ( resourcePath . toUri ( ) , yarnConf ) . getFileStatus ( resourcePath ) ; localResource . setResource ( ConverterUtils . getYarnUrlFromPath ( resourcePath ) ) ; localResource . setSize ( jarStat . getLen ( ) ) ; localResource . setTimestamp ( jarStat . getModificationTime ( ) ) ; localResource . setType ( LocalResourceType . FILE ) ; localResource . setVisibility ( LocalResourceVisibility . PUBLIC ) ; return localResource ; } | Creates a local resource for a file on HDFS . |
12,128 | public static String buildCommand ( YarnContainerType containerType , Map < String , String > args ) { CommandBuilder commandBuilder = new CommandBuilder ( "./" + ALLUXIO_SETUP_SCRIPT ) . addArg ( containerType . getName ( ) ) ; for ( Entry < String , String > argsEntry : args . entrySet ( ) ) { commandBuilder . addArg ( argsEntry . getKey ( ) , argsEntry . getValue ( ) ) ; } commandBuilder . addArg ( "1>" + ApplicationConstants . LOG_DIR_EXPANSION_VAR + "/stdout" ) ; commandBuilder . addArg ( "2>" + ApplicationConstants . LOG_DIR_EXPANSION_VAR + "/stderr" ) ; return commandBuilder . toString ( ) ; } | Creates a command string for running the Alluxio yarn setup script for the given type of yarn container . |
12,129 | public void add ( StorageDirView dir , long blockId , long blockSizeBytes ) { Pair < List < Long > , Long > candidate ; if ( mDirCandidates . containsKey ( dir ) ) { candidate = mDirCandidates . get ( dir ) ; } else { candidate = new Pair < List < Long > , Long > ( new ArrayList < Long > ( ) , 0L ) ; mDirCandidates . put ( dir , candidate ) ; } candidate . getFirst ( ) . add ( blockId ) ; long blockBytes = candidate . getSecond ( ) + blockSizeBytes ; candidate . setSecond ( blockBytes ) ; long sum = blockBytes + dir . getAvailableBytes ( ) ; if ( mMaxBytes < sum ) { mMaxBytes = sum ; mDirWithMaxBytes = dir ; } } | Adds the block in the directory to this collection . |
12,130 | public static void printCommandInfo ( Command command , PrintWriter pw ) { String description = String . format ( "%s: %s" , command . getCommandName ( ) , command . getDescription ( ) ) ; int width = 80 ; try { width = TerminalFactory . get ( ) . getWidth ( ) ; } catch ( Exception e ) { } HELP_FORMATTER . printWrapped ( pw , width , description ) ; HELP_FORMATTER . printUsage ( pw , width , command . getUsage ( ) ) ; if ( command . getOptions ( ) . getOptions ( ) . size ( ) > 0 ) { HELP_FORMATTER . printOptions ( pw , width , command . getOptions ( ) , HELP_FORMATTER . getLeftPadding ( ) , HELP_FORMATTER . getDescPadding ( ) ) ; } } | Prints the info about a command to the given print writer . |
12,131 | public synchronized void start ( ) throws IOException { Preconditions . checkState ( mProcess == null , "Process is already running" ) ; String java = PathUtils . concatPath ( System . getProperty ( "java.home" ) , "bin" , "java" ) ; String classpath = System . getProperty ( "java.class.path" ) ; List < String > args = new ArrayList < > ( Arrays . asList ( java , "-cp" , classpath ) ) ; for ( Entry < PropertyKey , String > entry : mConf . entrySet ( ) ) { args . add ( String . format ( "-D%s=%s" , entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ) ; } args . add ( mClazz . getCanonicalName ( ) ) ; ProcessBuilder pb = new ProcessBuilder ( args ) ; pb . redirectError ( mOutFile ) ; pb . redirectOutput ( mOutFile ) ; mProcess = pb . start ( ) ; } | Starts the process . |
12,132 | public int run ( ) throws IOException { Map < String , MountPointInfo > mountTable = mFileSystemMasterClient . getMountTable ( ) ; System . out . println ( "Alluxio under storage system information:" ) ; printMountInfo ( mountTable ) ; return 0 ; } | Runs report ufs command . |
12,133 | public static void printMountInfo ( Map < String , MountPointInfo > mountTable ) { for ( Map . Entry < String , MountPointInfo > entry : mountTable . entrySet ( ) ) { String mMountPoint = entry . getKey ( ) ; MountPointInfo mountPointInfo = entry . getValue ( ) ; long capacityBytes = mountPointInfo . getUfsCapacityBytes ( ) ; long usedBytes = mountPointInfo . getUfsUsedBytes ( ) ; String usedPercentageInfo = "" ; if ( capacityBytes > 0 ) { int usedPercentage = ( int ) ( 100L * usedBytes / capacityBytes ) ; usedPercentageInfo = String . format ( "(%s%%)" , usedPercentage ) ; } String leftAlignFormat = getAlignFormat ( mountTable ) ; System . out . format ( leftAlignFormat , mountPointInfo . getUfsUri ( ) , mMountPoint , mountPointInfo . getUfsType ( ) , FormatUtils . getSizeFromBytes ( capacityBytes ) , FormatUtils . getSizeFromBytes ( usedBytes ) + usedPercentageInfo , mountPointInfo . getReadOnly ( ) ? "" : "not " , mountPointInfo . getShared ( ) ? "" : "not " ) ; System . out . println ( "properties=" + mountPointInfo . getProperties ( ) + ")" ) ; } } | Prints mount information for a mount table . |
12,134 | private Principal getPrincipalUser ( String className ) throws LoginException { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( loader == null ) { loader = ClassLoader . getSystemClassLoader ( ) ; } Class < ? extends Principal > clazz ; try { @ SuppressWarnings ( "unchecked" ) Class < ? extends Principal > tmpClazz = ( Class < ? extends Principal > ) loader . loadClass ( className ) ; clazz = tmpClazz ; } catch ( ClassNotFoundException e ) { throw new LoginException ( "Unable to find JAAS principal class:" + e . getMessage ( ) ) ; } Set < ? extends Principal > userSet = mSubject . getPrincipals ( clazz ) ; if ( ! userSet . isEmpty ( ) ) { if ( userSet . size ( ) == 1 ) { return userSet . iterator ( ) . next ( ) ; } throw new LoginException ( "More than one instance of Principal " + className + " is found" ) ; } return null ; } | Gets a principal user . |
12,135 | public void release ( T resource ) { if ( resource != null ) { mResources . add ( resource ) ; try ( LockResource r = new LockResource ( mTakeLock ) ) { mNotEmpty . signal ( ) ; } } } | Releases an object of type T this must be called after the thread is done using a resource obtained by acquire . |
12,136 | public void onNext ( DataMessage < T , DataBuffer > value ) { DataBuffer buffer = value . getBuffer ( ) ; if ( buffer != null ) { mBufferRepository . offerBuffer ( buffer , value . getMessage ( ) ) ; } mObserver . onNext ( value . getMessage ( ) ) ; } | Receives a message with data buffer from the stream . |
12,137 | public static void deleteDirIfExists ( UnderFileSystem ufs , String path ) throws IOException { if ( ufs . isDirectory ( path ) && ! ufs . deleteDirectory ( path , DeleteOptions . defaults ( ) . setRecursive ( true ) ) ) { throw new IOException ( "Folder " + path + " already exists but can not be deleted." ) ; } } | Deletes the directory at the given path if it exists . |
12,138 | public static void mkdirIfNotExists ( UnderFileSystem ufs , String path ) throws IOException { if ( ! ufs . isDirectory ( path ) ) { if ( ! ufs . mkdirs ( path ) ) { throw new IOException ( "Failed to make folder: " + path ) ; } } } | Attempts to create the directory if it does not already exist . |
12,139 | public static void touch ( UnderFileSystem ufs , String path ) throws IOException { OutputStream os = ufs . create ( path ) ; os . close ( ) ; } | Creates an empty file . |
12,140 | public static void deleteFileIfExists ( UnderFileSystem ufs , String path ) { try { if ( ufs . isFile ( path ) ) { ufs . deleteFile ( path ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Deletes the specified path from the specified under file system if it is a file and exists . |
12,141 | public static String approximateContentHash ( long length , long modTime ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( '(' ) ; sb . append ( "len:" ) ; sb . append ( length ) ; sb . append ( ", " ) ; sb . append ( "modtime:" ) ; sb . append ( modTime ) ; sb . append ( ')' ) ; return sb . toString ( ) ; } | Returns an approximate content hash using the length and modification time . |
12,142 | protected String convertToFolderName ( String key ) { key = CommonUtils . stripSuffixIfPresent ( key , PATH_SEPARATOR ) ; return key + getFolderSuffix ( ) ; } | Appends the directory suffix to the key . |
12,143 | protected List < String > deleteObjects ( List < String > keys ) throws IOException { List < String > result = new ArrayList < > ( ) ; for ( String key : keys ) { boolean status = deleteObject ( key ) ; if ( status || key . endsWith ( getFolderSuffix ( ) ) ) { result . add ( key ) ; } } return result ; } | Internal function to delete a list of keys . |
12,144 | protected int getListingChunkLength ( AlluxioConfiguration conf ) { return conf . getInt ( PropertyKey . UNDERFS_LISTING_LENGTH ) > getListingChunkLengthMax ( ) ? getListingChunkLengthMax ( ) : conf . getInt ( PropertyKey . UNDERFS_LISTING_LENGTH ) ; } | The number of items to query in a single listing chunk . |
12,145 | protected String getParentPath ( String path ) { if ( isRoot ( path ) ) { return null ; } int separatorIndex = path . lastIndexOf ( PATH_SEPARATOR ) ; if ( separatorIndex < 0 ) { return null ; } return path . substring ( 0 , separatorIndex ) ; } | Get parent path . |
12,146 | protected boolean isRoot ( String path ) { return PathUtils . normalizePath ( path , PATH_SEPARATOR ) . equals ( PathUtils . normalizePath ( getRootKey ( ) , PATH_SEPARATOR ) ) ; } | Checks if the path is the root . |
12,147 | protected String getChildName ( String child , String parent ) throws IOException { if ( child . startsWith ( parent ) ) { return child . substring ( parent . length ( ) ) ; } throw new IOException ( ExceptionMessage . INVALID_PREFIX . getMessage ( parent , child ) ) ; } | Gets the child name based on the parent name . |
12,148 | protected boolean parentExists ( String path ) throws IOException { if ( isRoot ( path ) ) { return true ; } String parentKey = getParentPath ( path ) ; return parentKey != null && isDirectory ( parentKey ) ; } | Treating the object store as a file system checks if the parent directory exists . |
12,149 | private < T > T retryOnException ( ObjectStoreOperation < T > op , Supplier < String > description ) throws IOException { RetryPolicy retryPolicy = getRetryPolicy ( ) ; IOException thrownException = null ; while ( retryPolicy . attempt ( ) ) { try { return op . apply ( ) ; } catch ( IOException e ) { LOG . debug ( "Attempt {} to {} failed with exception : {}" , retryPolicy . getAttemptCount ( ) , description . get ( ) , e . toString ( ) ) ; thrownException = e ; } } throw thrownException ; } | Retries the given object store operation when it throws exceptions to resolve eventual consistency issue . |
12,150 | private boolean retryOnFalse ( ObjectStoreOperation < Boolean > op , Supplier < String > description ) throws IOException { RetryPolicy retryPolicy = getRetryPolicy ( ) ; while ( retryPolicy . attempt ( ) ) { if ( op . apply ( ) ) { return true ; } else { LOG . debug ( "Failed in attempt {} to {} " , retryPolicy . getAttemptCount ( ) , description . get ( ) ) ; } } return false ; } | Retries the given object store operation when it returns false to resolve eventual consistency issue . |
12,151 | public void removeBlockMeta ( BlockMeta blockMeta ) throws BlockDoesNotExistException { Preconditions . checkNotNull ( blockMeta , "blockMeta" ) ; long blockId = blockMeta . getBlockId ( ) ; BlockMeta deletedBlockMeta = mBlockIdToBlockMap . remove ( blockId ) ; if ( deletedBlockMeta == null ) { throw new BlockDoesNotExistException ( ExceptionMessage . BLOCK_META_NOT_FOUND , blockId ) ; } reclaimSpace ( blockMeta . getBlockSize ( ) , true ) ; } | Removes a block from this storage dir . |
12,152 | public void removeTempBlockMeta ( TempBlockMeta tempBlockMeta ) throws BlockDoesNotExistException { Preconditions . checkNotNull ( tempBlockMeta , "tempBlockMeta" ) ; final long blockId = tempBlockMeta . getBlockId ( ) ; final long sessionId = tempBlockMeta . getSessionId ( ) ; TempBlockMeta deletedTempBlockMeta = mBlockIdToTempBlockMap . remove ( blockId ) ; if ( deletedTempBlockMeta == null ) { throw new BlockDoesNotExistException ( ExceptionMessage . BLOCK_META_NOT_FOUND , blockId ) ; } Set < Long > sessionBlocks = mSessionIdToTempBlockIdsMap . get ( sessionId ) ; if ( sessionBlocks == null || ! sessionBlocks . contains ( blockId ) ) { throw new BlockDoesNotExistException ( ExceptionMessage . BLOCK_NOT_FOUND_FOR_SESSION , blockId , mTier . getTierAlias ( ) , sessionId ) ; } Preconditions . checkState ( sessionBlocks . remove ( blockId ) ) ; if ( sessionBlocks . isEmpty ( ) ) { mSessionIdToTempBlockIdsMap . remove ( sessionId ) ; } reclaimSpace ( tempBlockMeta . getBlockSize ( ) , false ) ; } | Removes a temp block from this storage dir . |
12,153 | public void resizeTempBlockMeta ( TempBlockMeta tempBlockMeta , long newSize ) throws InvalidWorkerStateException { long oldSize = tempBlockMeta . getBlockSize ( ) ; if ( newSize > oldSize ) { reserveSpace ( newSize - oldSize , false ) ; tempBlockMeta . setBlockSize ( newSize ) ; } else if ( newSize < oldSize ) { throw new InvalidWorkerStateException ( "Shrinking block, not supported!" ) ; } } | Changes the size of a temp block . |
12,154 | public void cleanupSessionTempBlocks ( long sessionId , List < Long > tempBlockIds ) { Set < Long > sessionTempBlocks = mSessionIdToTempBlockIdsMap . get ( sessionId ) ; if ( sessionTempBlocks == null ) { return ; } for ( Long tempBlockId : tempBlockIds ) { if ( ! mBlockIdToTempBlockMap . containsKey ( tempBlockId ) ) { continue ; } sessionTempBlocks . remove ( tempBlockId ) ; TempBlockMeta tempBlockMeta = mBlockIdToTempBlockMap . remove ( tempBlockId ) ; if ( tempBlockMeta != null ) { reclaimSpace ( tempBlockMeta . getBlockSize ( ) , false ) ; } else { LOG . error ( "Cannot find blockId {} when cleanup sessionId {}" , tempBlockId , sessionId ) ; } } if ( sessionTempBlocks . isEmpty ( ) ) { mSessionIdToTempBlockIdsMap . remove ( sessionId ) ; } else { LOG . warn ( "Blocks still owned by session {} after cleanup." , sessionId ) ; } } | Cleans up the temp block metadata for each block id passed in . |
12,155 | private void initNextWindow ( ) { for ( String syncPoint : mActivity . keySet ( ) ) { mActivity . put ( syncPoint , mActivity . get ( syncPoint ) . intValue ( ) / 10 ) ; mAge . put ( syncPoint , mAge . get ( syncPoint ) . intValue ( ) + 1 ) ; } } | Start the accounting for the next window of events . |
12,156 | public void startSync ( AlluxioURI ufsUri ) { LOG . debug ( "Add {} as a sync point" , ufsUri . toString ( ) ) ; mUfsUriList . add ( ufsUri ) ; } | startSync on a ufs uri . |
12,157 | public void stopSync ( AlluxioURI ufsUri ) { LOG . debug ( "attempt to remove {} from sync point list" , ufsUri . toString ( ) ) ; mUfsUriList . remove ( ufsUri ) ; } | stop sync on a ufs uri . |
12,158 | public void pollEvent ( DFSInotifyEventInputStream eventStream ) { EventBatch batch ; LOG . debug ( "Polling thread starting, with timeout {} ms" , mActiveUfsPollTimeoutMs ) ; int count = 0 ; long start = System . currentTimeMillis ( ) ; long behind = eventStream . getTxidsBehindEstimate ( ) ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { try { batch = eventStream . poll ( mActiveUfsPollTimeoutMs , TimeUnit . MILLISECONDS ) ; if ( batch != null ) { long txId = batch . getTxid ( ) ; count ++ ; for ( Event event : batch . getEvents ( ) ) { processEvent ( event , mUfsUriList , txId ) ; } } long end = System . currentTimeMillis ( ) ; if ( end > ( start + mActiveUfsSyncEventRateInterval ) ) { long currentlyBehind = eventStream . getTxidsBehindEstimate ( ) ; LOG . info ( "HDFS generated {} events in {} ms, at a rate of {} rps" , count + currentlyBehind - behind , end - start , String . format ( "%.2f" , ( count + currentlyBehind - behind ) * 1000.0 / ( end - start ) ) ) ; LOG . info ( "processed {} events in {} ms, at a rate of {} rps" , count , end - start , String . format ( "%.2f" , count * 1000.0 / ( end - start ) ) ) ; LOG . info ( "Currently TxidsBehindEstimate by {}" , currentlyBehind ) ; behind = currentlyBehind ; start = end ; count = 0 ; } } catch ( IOException e ) { LOG . warn ( "IOException occured during polling inotify {}" , e ) ; if ( e . getCause ( ) instanceof InterruptedException ) { return ; } } catch ( MissingEventsException e ) { LOG . warn ( "MissingEventException during polling {}" , e ) ; mEventMissed = true ; } catch ( InterruptedException e ) { LOG . warn ( "InterruptedException during polling {}" , e ) ; return ; } } } | Fetch and process events . |
12,159 | public SyncInfo getActivitySyncInfo ( ) { if ( mPollingThread == null ) { return SyncInfo . emptyInfo ( ) ; } Map < AlluxioURI , Set < AlluxioURI > > syncPointFiles = new HashMap < > ( ) ; long txId = 0 ; try ( LockResource r = new LockResource ( mWriteLock ) ) { initNextWindow ( ) ; if ( mEventMissed ) { for ( AlluxioURI uri : mUfsUriList ) { syncPointFiles . put ( uri , null ) ; syncSyncPoint ( uri . toString ( ) ) ; } mEventMissed = false ; LOG . debug ( "Missed event, syncing all sync points\n{}" , Arrays . toString ( syncPointFiles . keySet ( ) . toArray ( ) ) ) ; SyncInfo syncInfo = new SyncInfo ( syncPointFiles , true , getLastTxId ( ) ) ; return syncInfo ; } for ( String syncPoint : mActivity . keySet ( ) ) { AlluxioURI syncPointURI = new AlluxioURI ( syncPoint ) ; if ( mActivity . get ( syncPoint ) < mActiveUfsSyncMaxActivity || mAge . get ( syncPoint ) > mActiveUfsSyncMaxAge ) { if ( ! syncPointFiles . containsKey ( syncPointURI ) ) { syncPointFiles . put ( syncPointURI , mChangedFiles . get ( syncPoint ) ) ; } syncSyncPoint ( syncPoint ) ; } } txId = getLastTxId ( ) ; } LOG . debug ( "Syncing {} files" , syncPointFiles . size ( ) ) ; LOG . debug ( "Last transaction id {}" , txId ) ; SyncInfo syncInfo = new SyncInfo ( syncPointFiles , false , txId ) ; return syncInfo ; } | Get the activity sync info . |
12,160 | public GrpcServerBuilder keepAliveTime ( long keepAliveTime , TimeUnit timeUnit ) { mNettyServerBuilder = mNettyServerBuilder . keepAliveTime ( keepAliveTime , timeUnit ) ; return this ; } | Sets the keep alive time . |
12,161 | public GrpcServerBuilder keepAliveTimeout ( long keepAliveTimeout , TimeUnit timeUnit ) { mNettyServerBuilder = mNettyServerBuilder . keepAliveTimeout ( keepAliveTimeout , timeUnit ) ; return this ; } | Sets the keep alive timeout . |
12,162 | public < T > GrpcServerBuilder withChildOption ( ChannelOption < T > option , T value ) { mNettyServerBuilder = mNettyServerBuilder . withChildOption ( option , value ) ; return this ; } | Sets a netty channel option . |
12,163 | public GrpcServer build ( ) { addService ( new GrpcService ( new ServiceVersionClientServiceHandler ( mServices ) ) . disableAuthentication ( ) ) ; return new GrpcServer ( mNettyServerBuilder . build ( ) , mConfiguration . getMs ( PropertyKey . MASTER_GRPC_SERVER_SHUTDOWN_TIMEOUT ) ) ; } | Build the server . It attaches required services and interceptors for authentication . |
12,164 | public static void main ( String [ ] args ) { if ( args . length != 0 ) { LOG . info ( "java -cp {} {}" , RuntimeConstants . ALLUXIO_JAR , AlluxioJobMaster . class . getCanonicalName ( ) ) ; System . exit ( - 1 ) ; } CommonUtils . PROCESS_TYPE . set ( alluxio . util . CommonUtils . ProcessType . JOB_MASTER ) ; AlluxioJobMasterProcess process ; try { process = AlluxioJobMasterProcess . Factory . create ( ) ; } catch ( Throwable t ) { LOG . error ( "Failed to create job master process" , t ) ; System . exit ( - 1 ) ; throw t ; } ProcessUtils . run ( process ) ; } | Starts the Alluxio job master . |
12,165 | void gc ( ) { UfsJournalSnapshot snapshot ; try { snapshot = UfsJournalSnapshot . getSnapshot ( mJournal ) ; } catch ( IOException e ) { LOG . warn ( "Failed to get journal snapshot with error {}." , e . getMessage ( ) ) ; return ; } long checkpointSequenceNumber = 0 ; List < UfsJournalFile > checkpoints = snapshot . getCheckpoints ( ) ; if ( ! checkpoints . isEmpty ( ) ) { checkpointSequenceNumber = checkpoints . get ( checkpoints . size ( ) - 1 ) . getEnd ( ) ; } for ( int i = 0 ; i < checkpoints . size ( ) - 1 ; i ++ ) { if ( i < checkpoints . size ( ) - 2 ) { deleteNoException ( checkpoints . get ( i ) . getLocation ( ) ) ; } gcFileIfStale ( checkpoints . get ( i ) , checkpointSequenceNumber ) ; } for ( UfsJournalFile log : snapshot . getLogs ( ) ) { gcFileIfStale ( log , checkpointSequenceNumber ) ; } for ( UfsJournalFile tmpCheckpoint : snapshot . getTemporaryCheckpoints ( ) ) { gcFileIfStale ( tmpCheckpoint , checkpointSequenceNumber ) ; } } | Deletes unneeded snapshots . |
12,166 | private void gcFileIfStale ( UfsJournalFile file , long checkpointSequenceNumber ) { if ( file . getEnd ( ) > checkpointSequenceNumber && ! file . isTmpCheckpoint ( ) ) { return ; } long lastModifiedTimeMs ; try { lastModifiedTimeMs = mUfs . getFileStatus ( file . getLocation ( ) . toString ( ) ) . getLastModifiedTime ( ) ; } catch ( IOException e ) { LOG . warn ( "Failed to get the last modified time for {}." , file . getLocation ( ) ) ; return ; } long thresholdMs = file . isTmpCheckpoint ( ) ? ServerConfiguration . getMs ( PropertyKey . MASTER_JOURNAL_TEMPORARY_FILE_GC_THRESHOLD_MS ) : ServerConfiguration . getMs ( PropertyKey . MASTER_JOURNAL_GC_THRESHOLD_MS ) ; if ( System . currentTimeMillis ( ) - lastModifiedTimeMs > thresholdMs ) { deleteNoException ( file . getLocation ( ) ) ; } } | Garbage collects a file if necessary . |
12,167 | private void deleteNoException ( URI location ) { try { mUfs . deleteFile ( location . toString ( ) ) ; LOG . info ( "Garbage collected journal file {}." , location ) ; } catch ( IOException e ) { LOG . warn ( "Failed to garbage collect journal file {}." , location ) ; } } | Deletes a file and swallows the exception by logging it . |
12,168 | public synchronized void submitRunTaskCommand ( long jobId , int taskId , JobConfig jobConfig , Object taskArgs , long workerId ) { RunTaskCommand . Builder runTaskCommand = RunTaskCommand . newBuilder ( ) ; runTaskCommand . setJobId ( jobId ) ; runTaskCommand . setTaskId ( taskId ) ; try { runTaskCommand . setJobConfig ( ByteString . copyFrom ( SerializationUtils . serialize ( jobConfig ) ) ) ; if ( taskArgs != null ) { runTaskCommand . setTaskArgs ( ByteString . copyFrom ( SerializationUtils . serialize ( taskArgs ) ) ) ; } } catch ( IOException e ) { LOG . info ( "Failed to serialize the run task command:" + e ) ; return ; } JobCommand . Builder command = JobCommand . newBuilder ( ) ; command . setRunTaskCommand ( runTaskCommand ) ; if ( ! mWorkerIdToPendingCommands . containsKey ( workerId ) ) { mWorkerIdToPendingCommands . put ( workerId , Lists . < JobCommand > newArrayList ( ) ) ; } mWorkerIdToPendingCommands . get ( workerId ) . add ( command . build ( ) ) ; } | Submits a run - task command to a specified worker . |
12,169 | public synchronized void submitCancelTaskCommand ( long jobId , int taskId , long workerId ) { CancelTaskCommand . Builder cancelTaskCommand = CancelTaskCommand . newBuilder ( ) ; cancelTaskCommand . setJobId ( jobId ) ; cancelTaskCommand . setTaskId ( taskId ) ; JobCommand . Builder command = JobCommand . newBuilder ( ) ; command . setCancelTaskCommand ( cancelTaskCommand ) ; if ( ! mWorkerIdToPendingCommands . containsKey ( workerId ) ) { mWorkerIdToPendingCommands . put ( workerId , Lists . < JobCommand > newArrayList ( ) ) ; } mWorkerIdToPendingCommands . get ( workerId ) . add ( command . build ( ) ) ; } | Submits a cancel - task command to a specified worker . |
12,170 | public synchronized List < alluxio . grpc . JobCommand > pollAllPendingCommands ( long workerId ) { if ( ! mWorkerIdToPendingCommands . containsKey ( workerId ) ) { return Lists . newArrayList ( ) ; } List < JobCommand > commands = Lists . newArrayList ( mWorkerIdToPendingCommands . get ( workerId ) ) ; mWorkerIdToPendingCommands . get ( workerId ) . clear ( ) ; return commands ; } | Polls all the pending commands to a worker and removes the commands from the queue . |
12,171 | public void updateByModeBits ( Mode . Bits bits ) { Mode . Bits [ ] indexedBits = new Mode . Bits [ ] { Mode . Bits . READ , Mode . Bits . WRITE , Mode . Bits . EXECUTE } ; for ( int i = 0 ; i < 3 ; i ++ ) { if ( bits . imply ( indexedBits [ i ] ) ) { mActions . set ( i ) ; } else { mActions . clear ( i ) ; } } } | Updates permitted actions based on the mode bits . |
12,172 | public static void main ( String [ ] args ) { if ( args . length != 0 ) { LOG . info ( "java -cp {} {}" , RuntimeConstants . ALLUXIO_JAR , AlluxioMaster . class . getCanonicalName ( ) ) ; System . exit ( - 1 ) ; } CommonUtils . PROCESS_TYPE . set ( CommonUtils . ProcessType . MASTER ) ; MasterProcess process ; try { process = AlluxioMasterProcess . Factory . create ( ) ; } catch ( Throwable t ) { ProcessUtils . fatalError ( LOG , t , "Failed to create master process" ) ; throw t ; } ProcessUtils . stopProcessOnShutdown ( process ) ; ProcessUtils . run ( process ) ; } | Starts the Alluxio master . |
12,173 | private void checkOwner ( LockedInodePath inodePath ) throws AccessControlException , InvalidPathException { List < InodeView > inodeList = inodePath . getInodeViewList ( ) ; String user = AuthenticatedClientUser . getClientUser ( ServerConfiguration . global ( ) ) ; List < String > groups = getGroups ( user ) ; if ( isPrivilegedUser ( user , groups ) ) { return ; } checkInodeList ( user , groups , null , inodePath . getUri ( ) . getPath ( ) , inodeList , true ) ; } | Checks whether the client user is the owner of the path . |
12,174 | private void checkSuperUser ( ) throws AccessControlException { String user = AuthenticatedClientUser . getClientUser ( ServerConfiguration . global ( ) ) ; List < String > groups = getGroups ( user ) ; if ( ! isPrivilegedUser ( user , groups ) ) { throw new AccessControlException ( ExceptionMessage . PERMISSION_DENIED . getMessage ( user + " is not a super user or in super group" ) ) ; } } | Checks whether the user is a super user or in super group . |
12,175 | private void checkInode ( String user , List < String > groups , InodeView inode , Mode . Bits bits , String path ) throws AccessControlException { if ( inode == null ) { return ; } for ( AclAction action : bits . toAclActionSet ( ) ) { if ( ! inode . checkPermission ( user , groups , action ) ) { throw new AccessControlException ( ExceptionMessage . PERMISSION_DENIED . getMessage ( toExceptionMessage ( user , bits , path , inode ) ) ) ; } } } | This method checks requested permission on a given inode represented by its fileInfo . |
12,176 | private Mode . Bits getPermissionInternal ( String user , List < String > groups , String path , List < InodeView > inodeList ) { int size = inodeList . size ( ) ; Preconditions . checkArgument ( size > 0 , PreconditionMessage . EMPTY_FILE_INFO_LIST_FOR_PERMISSION_CHECK ) ; if ( isPrivilegedUser ( user , groups ) ) { return Mode . Bits . ALL ; } for ( int i = 0 ; i < size - 1 ; i ++ ) { try { checkInode ( user , groups , inodeList . get ( i ) , Mode . Bits . EXECUTE , path ) ; } catch ( AccessControlException e ) { return Mode . Bits . NONE ; } } InodeView inode = inodeList . get ( inodeList . size ( ) - 1 ) ; if ( inode == null ) { return Mode . Bits . NONE ; } return inode . getPermission ( user , groups ) . toModeBits ( ) ; } | Gets the permission to access an inode path given a user and its groups . |
12,177 | public static SyncPlan computeSyncPlan ( Inode inode , Fingerprint ufsFingerprint , boolean containsMountPoint ) { Fingerprint inodeFingerprint = Fingerprint . parse ( inode . getUfsFingerprint ( ) ) ; boolean isContentSynced = inodeUfsIsContentSynced ( inode , inodeFingerprint , ufsFingerprint ) ; boolean isMetadataSynced = inodeUfsIsMetadataSynced ( inode , inodeFingerprint , ufsFingerprint ) ; boolean ufsExists = ufsFingerprint . isValid ( ) ; boolean ufsIsDir = ufsFingerprint != null && Fingerprint . Type . DIRECTORY . name ( ) . equals ( ufsFingerprint . getTag ( Fingerprint . Tag . TYPE ) ) ; UfsSyncUtils . SyncPlan syncPlan = new UfsSyncUtils . SyncPlan ( ) ; if ( isContentSynced && isMetadataSynced ) { if ( inode . isDirectory ( ) && inode . isPersisted ( ) ) { syncPlan . setSyncChildren ( ) ; } return syncPlan ; } if ( inode . isDirectory ( ) && ( containsMountPoint || ufsIsDir ) ) { if ( inode . getParentId ( ) != InodeTree . NO_PARENT ) { syncPlan . setUpdateMetadata ( ) ; } syncPlan . setSyncChildren ( ) ; return syncPlan ; } if ( ! isContentSynced ) { syncPlan . setDelete ( ) ; if ( ufsExists ) { syncPlan . setLoadMetadata ( ) ; } } else { syncPlan . setUpdateMetadata ( ) ; } return syncPlan ; } | Given an inode and ufs status returns a sync plan describing how to sync the inode with the ufs . |
12,178 | public static boolean inodeUfsIsContentSynced ( Inode inode , Fingerprint inodeFingerprint , Fingerprint ufsFingerprint ) { boolean isSyncedUnpersisted = ! inode . isPersisted ( ) && ! ufsFingerprint . isValid ( ) ; boolean isSyncedPersisted ; isSyncedPersisted = inode . isPersisted ( ) && inodeFingerprint . matchContent ( ufsFingerprint ) && inodeFingerprint . isValid ( ) ; return isSyncedPersisted || isSyncedUnpersisted ; } | Returns true if the given inode s content is synced with the ufs status . This is a single inode check so for directory inodes this does not consider the children inodes . |
12,179 | public static boolean inodeUfsIsMetadataSynced ( Inode inode , Fingerprint inodeFingerprint , Fingerprint ufsFingerprint ) { return inodeFingerprint . isValid ( ) && inodeFingerprint . matchMetadata ( ufsFingerprint ) ; } | Returns true if the given inode s metadata matches the ufs fingerprint . |
12,180 | public static void logAllThreads ( ) { StringBuilder sb = new StringBuilder ( "Dumping all threads:\n" ) ; for ( Thread t : Thread . getAllStackTraces ( ) . keySet ( ) ) { sb . append ( formatStackTrace ( t ) ) ; } LOG . info ( sb . toString ( ) ) ; } | Logs a stack trace for all threads currently running in the JVM similar to jstack . |
12,181 | public Set < Long > register ( final StorageTierAssoc globalStorageTierAssoc , final List < String > storageTierAliases , final Map < String , Long > totalBytesOnTiers , final Map < String , Long > usedBytesOnTiers , final Set < Long > blocks ) { for ( int i = 0 ; i < storageTierAliases . size ( ) - 1 ; i ++ ) { if ( globalStorageTierAssoc . getOrdinal ( storageTierAliases . get ( i ) ) >= globalStorageTierAssoc . getOrdinal ( storageTierAliases . get ( i + 1 ) ) ) { throw new IllegalArgumentException ( "Worker cannot place storage tier " + storageTierAliases . get ( i ) + " above " + storageTierAliases . get ( i + 1 ) + " in the hierarchy" ) ; } } mStorageTierAssoc = new WorkerStorageTierAssoc ( storageTierAliases ) ; if ( mStorageTierAssoc . size ( ) != totalBytesOnTiers . size ( ) || mStorageTierAssoc . size ( ) != usedBytesOnTiers . size ( ) ) { throw new IllegalArgumentException ( "totalBytesOnTiers and usedBytesOnTiers should have the same number of tiers as " + "storageTierAliases, but storageTierAliases has " + mStorageTierAssoc . size ( ) + " tiers, while totalBytesOnTiers has " + totalBytesOnTiers . size ( ) + " tiers and usedBytesOnTiers has " + usedBytesOnTiers . size ( ) + " tiers" ) ; } mTotalBytesOnTiers = new HashMap < > ( totalBytesOnTiers ) ; mUsedBytesOnTiers = new HashMap < > ( usedBytesOnTiers ) ; mCapacityBytes = 0 ; for ( long bytes : mTotalBytesOnTiers . values ( ) ) { mCapacityBytes += bytes ; } mUsedBytes = 0 ; for ( long bytes : mUsedBytesOnTiers . values ( ) ) { mUsedBytes += bytes ; } Set < Long > removedBlocks ; if ( mIsRegistered ) { LOG . info ( "re-registering an existing workerId: {}" , mId ) ; removedBlocks = Sets . difference ( mBlocks , blocks ) ; } else { removedBlocks = Collections . emptySet ( ) ; } mBlocks = new HashSet < > ( blocks ) ; mIsRegistered = true ; return removedBlocks ; } | Marks the worker as registered while updating all of its metadata . |
12,182 | public void addLostStorage ( String tierAlias , String dirPath ) { List < String > paths = mLostStorage . getOrDefault ( tierAlias , new ArrayList < > ( ) ) ; paths . add ( dirPath ) ; mLostStorage . put ( tierAlias , paths ) ; } | Adds a new worker lost storage path . |
12,183 | public void addLostStorage ( Map < String , StorageList > lostStorage ) { for ( Map . Entry < String , StorageList > entry : lostStorage . entrySet ( ) ) { List < String > paths = mLostStorage . getOrDefault ( entry . getKey ( ) , new ArrayList < > ( ) ) ; paths . addAll ( entry . getValue ( ) . getStorageList ( ) ) ; mLostStorage . put ( entry . getKey ( ) , paths ) ; } } | Adds new worker lost storage paths . |
12,184 | public WorkerInfo generateWorkerInfo ( Set < WorkerInfoField > fieldRange , boolean isLiveWorker ) { WorkerInfo info = new WorkerInfo ( ) ; Set < WorkerInfoField > checkedFieldRange = fieldRange != null ? fieldRange : new HashSet < > ( Arrays . asList ( WorkerInfoField . values ( ) ) ) ; for ( WorkerInfoField field : checkedFieldRange ) { switch ( field ) { case ADDRESS : info . setAddress ( mWorkerAddress ) ; break ; case WORKER_CAPACITY_BYTES : info . setCapacityBytes ( mCapacityBytes ) ; break ; case WORKER_CAPACITY_BYTES_ON_TIERS : info . setCapacityBytesOnTiers ( mTotalBytesOnTiers ) ; break ; case ID : info . setId ( mId ) ; break ; case LAST_CONTACT_SEC : info . setLastContactSec ( ( int ) ( ( CommonUtils . getCurrentMs ( ) - mLastUpdatedTimeMs ) / Constants . SECOND_MS ) ) ; break ; case START_TIME_MS : info . setStartTimeMs ( mStartTimeMs ) ; break ; case STATE : if ( isLiveWorker ) { info . setState ( LIVE_WORKER_STATE ) ; } else { info . setState ( LOST_WORKER_STATE ) ; } break ; case WORKER_USED_BYTES : info . setUsedBytes ( mUsedBytes ) ; break ; case WORKER_USED_BYTES_ON_TIERS : info . setUsedBytesOnTiers ( mUsedBytesOnTiers ) ; break ; default : LOG . warn ( "Unrecognized worker info field: " + field ) ; } } return info ; } | Gets the selected field information for this worker . |
12,185 | public void updateToRemovedBlock ( boolean add , long blockId ) { if ( add ) { if ( mBlocks . contains ( blockId ) ) { mToRemoveBlocks . add ( blockId ) ; } } else { mToRemoveBlocks . remove ( blockId ) ; } } | Adds or removes a block from the to - be - removed blocks set of the worker . |
12,186 | public void updateCapacityBytes ( Map < String , Long > capacityBytesOnTiers ) { mCapacityBytes = 0 ; mTotalBytesOnTiers = capacityBytesOnTiers ; for ( long t : mTotalBytesOnTiers . values ( ) ) { mCapacityBytes += t ; } } | Sets the capacity of the worker in bytes . |
12,187 | public int run ( String ... argv ) { if ( argv . length == 0 ) { printUsage ( ) ; return - 1 ; } String cmd = argv [ 0 ] ; Command command = mCommands . get ( cmd ) ; if ( command == null ) { String [ ] replacementCmd = getReplacementCmd ( cmd ) ; if ( replacementCmd == null ) { System . err . println ( String . format ( "%s is an unknown command." , cmd ) ) ; printUsage ( ) ; return - 1 ; } else { if ( mUnstableAlias != null && mUnstableAlias . contains ( cmd ) ) { String deprecatedMsg = String . format ( "WARNING: %s is not a stable CLI command. It may be removed in the " + "future. Use with caution in scripts. You may use '%s' instead." , cmd , StringUtils . join ( replacementCmd , " " ) ) ; System . out . println ( deprecatedMsg ) ; } String [ ] replacementArgv = ( String [ ] ) ArrayUtils . addAll ( replacementCmd , ArrayUtils . subarray ( argv , 1 , argv . length ) ) ; return run ( replacementArgv ) ; } } String [ ] args = Arrays . copyOfRange ( argv , 1 , argv . length ) ; CommandLine cmdline ; try { cmdline = command . parseAndValidateArgs ( args ) ; } catch ( InvalidArgumentException e ) { System . out . println ( "Usage: " + command . getUsage ( ) ) ; LOG . error ( "Invalid arguments for command {}:" , command . getCommandName ( ) , e ) ; return - 1 ; } try { return command . run ( cmdline ) ; } catch ( Exception e ) { System . out . println ( e . getMessage ( ) ) ; LOG . error ( "Error running " + StringUtils . join ( argv , " " ) , e ) ; return - 1 ; } } | Handles the specified shell command request displaying usage if the command format is invalid . |
12,188 | private String [ ] getReplacementCmd ( String cmd ) { if ( mCommandAlias == null || ! mCommandAlias . containsKey ( cmd ) ) { return null ; } return mCommandAlias . get ( cmd ) ; } | Gets the replacement command for alias . |
12,189 | protected void printUsage ( ) { System . out . println ( "Usage: alluxio " + getShellName ( ) + " [generic options]" ) ; SortedSet < String > sortedCmds = new TreeSet < > ( mCommands . keySet ( ) ) ; for ( String cmd : sortedCmds ) { System . out . format ( "%-60s%n" , "\t [" + mCommands . get ( cmd ) . getUsage ( ) + "]" ) ; } } | Prints usage for all commands . |
12,190 | public BlockHeartbeatReport generateReport ( ) { synchronized ( mLock ) { BlockHeartbeatReport report = new BlockHeartbeatReport ( mAddedBlocks , mRemovedBlocks , mLostStorage ) ; mAddedBlocks . clear ( ) ; mRemovedBlocks . clear ( ) ; mLostStorage . clear ( ) ; return report ; } } | Generates the report of the block store delta in the last heartbeat period . Calling this method marks the end of a period and the start of a new heartbeat period . |
12,191 | private void addBlockToAddedBlocks ( long blockId , String tierAlias ) { if ( mAddedBlocks . containsKey ( tierAlias ) ) { mAddedBlocks . get ( tierAlias ) . add ( blockId ) ; } else { mAddedBlocks . put ( tierAlias , Lists . newArrayList ( blockId ) ) ; } } | Adds a block to the list of added blocks in this heartbeat period . |
12,192 | private void removeBlockFromAddedBlocks ( long blockId ) { Iterator < Entry < String , List < Long > > > iterator = mAddedBlocks . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Entry < String , List < Long > > entry = iterator . next ( ) ; List < Long > blockList = entry . getValue ( ) ; if ( blockList . contains ( blockId ) ) { blockList . remove ( blockId ) ; if ( blockList . isEmpty ( ) ) { iterator . remove ( ) ; } break ; } } } | Removes the block from the added blocks map if it exists . |
12,193 | public int flush ( String path , FuseFileInfo fi ) { LOG . trace ( "flush({})" , path ) ; final long fd = fi . fh . get ( ) ; OpenFileEntry oe = mOpenFiles . getFirstByField ( ID_INDEX , fd ) ; if ( oe == null ) { LOG . error ( "Cannot find fd for {} in table" , path ) ; return - ErrorCodes . EBADFD ( ) ; } if ( oe . getOut ( ) != null ) { try { oe . getOut ( ) . flush ( ) ; } catch ( IOException e ) { LOG . error ( "Failed to flush {}" , path , e ) ; return - ErrorCodes . EIO ( ) ; } } else { LOG . debug ( "Not flushing: {} was not open for writing" , path ) ; } return 0 ; } | Flushes cached data on Alluxio . |
12,194 | public int getattr ( String path , FileStat stat ) { final AlluxioURI turi = mPathResolverCache . getUnchecked ( path ) ; LOG . trace ( "getattr({}) [Alluxio: {}]" , path , turi ) ; try { URIStatus status = mFileSystem . getStatus ( turi ) ; if ( ! status . isCompleted ( ) ) { if ( ! mOpenFiles . contains ( PATH_INDEX , path ) && ! waitForFileCompleted ( turi ) ) { LOG . error ( "File {} is not completed" , path ) ; } status = mFileSystem . getStatus ( turi ) ; } long size = status . getLength ( ) ; stat . st_size . set ( size ) ; stat . st_blocks . set ( ( int ) Math . ceil ( ( double ) size / 512 ) ) ; final long ctime_sec = status . getLastModificationTimeMs ( ) / 1000 ; final long ctime_nsec = ( status . getLastModificationTimeMs ( ) % 1000 ) * 1000 ; stat . st_ctim . tv_sec . set ( ctime_sec ) ; stat . st_ctim . tv_nsec . set ( ctime_nsec ) ; stat . st_mtim . tv_sec . set ( ctime_sec ) ; stat . st_mtim . tv_nsec . set ( ctime_nsec ) ; if ( mIsUserGroupTranslation ) { stat . st_uid . set ( AlluxioFuseUtils . getUid ( status . getOwner ( ) ) ) ; stat . st_gid . set ( AlluxioFuseUtils . getGidFromGroupName ( status . getGroup ( ) ) ) ; } else { stat . st_uid . set ( UID ) ; stat . st_gid . set ( GID ) ; } int mode = status . getMode ( ) ; if ( status . isFolder ( ) ) { mode |= FileStat . S_IFDIR ; } else { mode |= FileStat . S_IFREG ; } stat . st_mode . set ( mode ) ; stat . st_nlink . set ( 1 ) ; } catch ( FileDoesNotExistException | InvalidPathException e ) { LOG . debug ( "Failed to get info of {}, path does not exist or is invalid" , path ) ; return - ErrorCodes . ENOENT ( ) ; } catch ( Throwable t ) { LOG . error ( "Failed to get info of {}" , path , t ) ; return AlluxioFuseUtils . getErrorCode ( t ) ; } return 0 ; } | Retrieves file attributes . |
12,195 | public int open ( String path , FuseFileInfo fi ) { final AlluxioURI uri = mPathResolverCache . getUnchecked ( path ) ; final int flags = fi . flags . get ( ) ; LOG . trace ( "open({}, 0x{}) [Alluxio: {}]" , path , Integer . toHexString ( flags ) , uri ) ; try { final URIStatus status = mFileSystem . getStatus ( uri ) ; if ( status . isFolder ( ) ) { LOG . error ( "Cannot open folder {}" , path ) ; return - ErrorCodes . EISDIR ( ) ; } if ( ! status . isCompleted ( ) && ! waitForFileCompleted ( uri ) ) { LOG . error ( "Cannot open incomplete folder {}" , path ) ; return - ErrorCodes . EFAULT ( ) ; } if ( mOpenFiles . size ( ) >= MAX_OPEN_FILES ) { LOG . error ( "Cannot open {}: too many open files (MAX_OPEN_FILES: {})" , path , MAX_OPEN_FILES ) ; return ErrorCodes . EMFILE ( ) ; } FileInStream is = mFileSystem . openFile ( uri ) ; synchronized ( mOpenFiles ) { mOpenFiles . add ( new OpenFileEntry ( mNextOpenFileId , path , is , null ) ) ; fi . fh . set ( mNextOpenFileId ) ; mNextOpenFileId += 1 ; } } catch ( FileDoesNotExistException | InvalidPathException e ) { LOG . debug ( "Failed to open file {}, path does not exist or is invalid" , path ) ; return - ErrorCodes . ENOENT ( ) ; } catch ( Throwable t ) { LOG . error ( "Failed to open file {}" , path , t ) ; return AlluxioFuseUtils . getErrorCode ( t ) ; } return 0 ; } | Opens an existing file for reading . |
12,196 | public int rename ( String oldPath , String newPath ) { final AlluxioURI oldUri = mPathResolverCache . getUnchecked ( oldPath ) ; final AlluxioURI newUri = mPathResolverCache . getUnchecked ( newPath ) ; LOG . trace ( "rename({}, {}) [Alluxio: {}, {}]" , oldPath , newPath , oldUri , newUri ) ; try { mFileSystem . rename ( oldUri , newUri ) ; synchronized ( mOpenFiles ) { if ( mOpenFiles . contains ( PATH_INDEX , oldPath ) ) { OpenFileEntry oe = mOpenFiles . getFirstByField ( PATH_INDEX , oldPath ) ; oe . setPath ( newPath ) ; } } } catch ( FileDoesNotExistException e ) { LOG . debug ( "Failed to rename {} to {}, file {} does not exist" , oldPath , newPath , oldPath ) ; return - ErrorCodes . ENOENT ( ) ; } catch ( FileAlreadyExistsException e ) { LOG . debug ( "Failed to rename {} to {}, file {} already exists" , oldPath , newPath , newPath ) ; return - ErrorCodes . EEXIST ( ) ; } catch ( Throwable t ) { LOG . error ( "Failed to rename {} to {}" , oldPath , newPath , t ) ; return AlluxioFuseUtils . getErrorCode ( t ) ; } return 0 ; } | Renames a path . |
12,197 | public int truncate ( String path , long size ) { LOG . error ( "Truncate is not supported {}" , path ) ; return - ErrorCodes . EOPNOTSUPP ( ) ; } | Changes the size of a file . This operation would not succeed because of Alluxio s write - once model . |
12,198 | private int rmInternal ( String path ) { final AlluxioURI turi = mPathResolverCache . getUnchecked ( path ) ; try { mFileSystem . delete ( turi ) ; } catch ( FileDoesNotExistException | InvalidPathException e ) { LOG . debug ( "Failed to remove {}, file does not exist or is invalid" , path ) ; return - ErrorCodes . ENOENT ( ) ; } catch ( Throwable t ) { LOG . error ( "Failed to remove {}" , path , t ) ; return AlluxioFuseUtils . getErrorCode ( t ) ; } return 0 ; } | Convenience internal method to remove files or non - empty directories . |
12,199 | private boolean waitForFileCompleted ( AlluxioURI uri ) { try { CommonUtils . waitFor ( "file completed" , ( ) -> { try { return mFileSystem . getStatus ( uri ) . isCompleted ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } , WaitForOptions . defaults ( ) . setTimeoutMs ( MAX_OPEN_WAITTIME_MS ) ) ; return true ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; return false ; } catch ( TimeoutException te ) { return false ; } } | Waits for the file to complete before opening it . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.