id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
18,400
Alluxio/alluxio
core/common/src/main/java/alluxio/util/ShellUtils.java
ShellUtils.getUnixMountInfo
public static List<UnixMountInfo> getUnixMountInfo() throws IOException { Preconditions.checkState(OSUtils.isLinux() || OSUtils.isMacOS()); String output = execCommand(MOUNT_COMMAND); List<UnixMountInfo> mountInfo = new ArrayList<>(); for (String line : output.split("\n")) { mountInfo.add(parseMountInfo(line)); } return mountInfo; }
java
public static List<UnixMountInfo> getUnixMountInfo() throws IOException { Preconditions.checkState(OSUtils.isLinux() || OSUtils.isMacOS()); String output = execCommand(MOUNT_COMMAND); List<UnixMountInfo> mountInfo = new ArrayList<>(); for (String line : output.split("\n")) { mountInfo.add(parseMountInfo(line)); } return mountInfo; }
[ "public", "static", "List", "<", "UnixMountInfo", ">", "getUnixMountInfo", "(", ")", "throws", "IOException", "{", "Preconditions", ".", "checkState", "(", "OSUtils", ".", "isLinux", "(", ")", "||", "OSUtils", ".", "isMacOS", "(", ")", ")", ";", "String", "output", "=", "execCommand", "(", "MOUNT_COMMAND", ")", ";", "List", "<", "UnixMountInfo", ">", "mountInfo", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "line", ":", "output", ".", "split", "(", "\"\\n\"", ")", ")", "{", "mountInfo", ".", "add", "(", "parseMountInfo", "(", "line", ")", ")", ";", "}", "return", "mountInfo", ";", "}" ]
Gets system mount information. This method should only be attempted on Unix systems. @return system mount information
[ "Gets", "system", "mount", "information", ".", "This", "method", "should", "only", "be", "attempted", "on", "Unix", "systems", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/ShellUtils.java#L80-L88
18,401
Alluxio/alluxio
underfs/oss/src/main/java/alluxio/underfs/oss/OSSOutputStream.java
OSSOutputStream.close
@Override public void close() throws IOException { if (mClosed.getAndSet(true)) { return; } mLocalOutputStream.close(); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(mFile))) { ObjectMetadata objMeta = new ObjectMetadata(); objMeta.setContentLength(mFile.length()); if (mHash != null) { byte[] hashBytes = mHash.digest(); objMeta.setContentMD5(new String(Base64.encodeBase64(hashBytes))); } mOssClient.putObject(mBucketName, mKey, in, objMeta); } catch (ServiceException e) { LOG.error("Failed to upload {}. Temporary file @ {}", mKey, mFile.getPath()); throw new IOException(e); } mFile.delete(); }
java
@Override public void close() throws IOException { if (mClosed.getAndSet(true)) { return; } mLocalOutputStream.close(); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(mFile))) { ObjectMetadata objMeta = new ObjectMetadata(); objMeta.setContentLength(mFile.length()); if (mHash != null) { byte[] hashBytes = mHash.digest(); objMeta.setContentMD5(new String(Base64.encodeBase64(hashBytes))); } mOssClient.putObject(mBucketName, mKey, in, objMeta); } catch (ServiceException e) { LOG.error("Failed to upload {}. Temporary file @ {}", mKey, mFile.getPath()); throw new IOException(e); } mFile.delete(); }
[ "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "if", "(", "mClosed", ".", "getAndSet", "(", "true", ")", ")", "{", "return", ";", "}", "mLocalOutputStream", ".", "close", "(", ")", ";", "try", "(", "BufferedInputStream", "in", "=", "new", "BufferedInputStream", "(", "new", "FileInputStream", "(", "mFile", ")", ")", ")", "{", "ObjectMetadata", "objMeta", "=", "new", "ObjectMetadata", "(", ")", ";", "objMeta", ".", "setContentLength", "(", "mFile", ".", "length", "(", ")", ")", ";", "if", "(", "mHash", "!=", "null", ")", "{", "byte", "[", "]", "hashBytes", "=", "mHash", ".", "digest", "(", ")", ";", "objMeta", ".", "setContentMD5", "(", "new", "String", "(", "Base64", ".", "encodeBase64", "(", "hashBytes", ")", ")", ")", ";", "}", "mOssClient", ".", "putObject", "(", "mBucketName", ",", "mKey", ",", "in", ",", "objMeta", ")", ";", "}", "catch", "(", "ServiceException", "e", ")", "{", "LOG", ".", "error", "(", "\"Failed to upload {}. Temporary file @ {}\"", ",", "mKey", ",", "mFile", ".", "getPath", "(", ")", ")", ";", "throw", "new", "IOException", "(", "e", ")", ";", "}", "mFile", ".", "delete", "(", ")", ";", "}" ]
Closes this output stream. When an output stream is closed, the local temporary file is uploaded to OSS Service. Once the file is uploaded, the temporary file is deleted.
[ "Closes", "this", "output", "stream", ".", "When", "an", "output", "stream", "is", "closed", "the", "local", "temporary", "file", "is", "uploaded", "to", "OSS", "Service", ".", "Once", "the", "file", "is", "uploaded", "the", "temporary", "file", "is", "deleted", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/oss/src/main/java/alluxio/underfs/oss/OSSOutputStream.java#L146-L165
18,402
Alluxio/alluxio
core/common/src/main/java/alluxio/util/IdUtils.java
IdUtils.createFileId
public static long createFileId(long containerId) { long id = BlockId.createBlockId(containerId, BlockId.getMaxSequenceNumber()); if (id == INVALID_FILE_ID) { // Right now, there's not much we can do if the file id we're returning is -1, since the file // id is completely determined by the container id passed in. However, by the current // algorithm, -1 will be the last file id generated, so the chances somebody will get to that // are slim. For now we just log it. LOG.warn("Created file id -1, which is invalid"); } return id; }
java
public static long createFileId(long containerId) { long id = BlockId.createBlockId(containerId, BlockId.getMaxSequenceNumber()); if (id == INVALID_FILE_ID) { // Right now, there's not much we can do if the file id we're returning is -1, since the file // id is completely determined by the container id passed in. However, by the current // algorithm, -1 will be the last file id generated, so the chances somebody will get to that // are slim. For now we just log it. LOG.warn("Created file id -1, which is invalid"); } return id; }
[ "public", "static", "long", "createFileId", "(", "long", "containerId", ")", "{", "long", "id", "=", "BlockId", ".", "createBlockId", "(", "containerId", ",", "BlockId", ".", "getMaxSequenceNumber", "(", ")", ")", ";", "if", "(", "id", "==", "INVALID_FILE_ID", ")", "{", "// Right now, there's not much we can do if the file id we're returning is -1, since the file", "// id is completely determined by the container id passed in. However, by the current", "// algorithm, -1 will be the last file id generated, so the chances somebody will get to that", "// are slim. For now we just log it.", "LOG", ".", "warn", "(", "\"Created file id -1, which is invalid\"", ")", ";", "}", "return", "id", ";", "}" ]
Creates an id for a file based on the given id of the container. @param containerId the id of the container @return a file id based on the given container id
[ "Creates", "an", "id", "for", "a", "file", "based", "on", "the", "given", "id", "of", "the", "container", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/IdUtils.java#L47-L57
18,403
Alluxio/alluxio
core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java
HeartbeatScheduler.clearTimer
public static void clearTimer(String name) { try (LockResource r = new LockResource(sLock)) { sTimers.remove(name); } }
java
public static void clearTimer(String name) { try (LockResource r = new LockResource(sLock)) { sTimers.remove(name); } }
[ "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. @param name the name to clear
[ "Removes", "a", "timer", "name", "from", "the", "scheduler", "if", "it", "exists", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java#L73-L77
18,404
Alluxio/alluxio
core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java
HeartbeatScheduler.removeTimer
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"); } }
java
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"); } }
[ "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. This method will fail if the timer is not in the scheduler. @param timer the timer to remove
[ "Removes", "a", "timer", "from", "the", "scheduler", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java#L86-L94
18,405
Alluxio/alluxio
core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java
HeartbeatScheduler.schedule
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(); } }
java
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(); } }
[ "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. @param threadName a name of the thread for which heartbeat is to be executed
[ "Schedules", "execution", "of", "a", "heartbeat", "for", "the", "given", "thread", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java#L110-L118
18,406
Alluxio/alluxio
core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java
HeartbeatScheduler.await
public static void await(String name) throws InterruptedException { try (LockResource r = new LockResource(sLock)) { while (!sTimers.containsKey(name)) { sCondition.await(); } } }
java
public static void await(String name) throws InterruptedException { try (LockResource r = new LockResource(sLock)) { while (!sTimers.containsKey(name)) { sCondition.await(); } } }
[ "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. @param name a name of the thread to wait for @throws InterruptedException if the waiting thread is interrupted
[ "Waits", "for", "the", "given", "thread", "to", "be", "ready", "to", "be", "scheduled", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java#L126-L132
18,407
Alluxio/alluxio
core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java
HeartbeatScheduler.await
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"); } } } }
java
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"); } } } }
[ "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. @param name a name of the thread to wait for @param time the maximum time to wait @param unit the time unit of the {@code time} argument @throws InterruptedException if the waiting thread is interrupted
[ "Waits", "until", "the", "given", "thread", "can", "be", "executed", "throwing", "an", "unchecked", "exception", "of", "the", "given", "timeout", "expires", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java#L143-L152
18,408
Alluxio/alluxio
core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java
HeartbeatScheduler.execute
public static void execute(String name) throws InterruptedException { await(name); schedule(name); await(name); }
java
public static void execute(String name) throws InterruptedException { await(name); schedule(name); await(name); }
[ "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. @param name the name of the heartbeat to execute @throws InterruptedException if the waiting thread is interrupted
[ "Convenience", "method", "for", "executing", "a", "heartbeat", "and", "waiting", "for", "it", "to", "complete", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/heartbeat/HeartbeatScheduler.java#L160-L164
18,409
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/ChmodCommand.java
ChmodCommand.chmod
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())); }
java
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())); }
[ "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. @param path The {@link AlluxioURI} path as the input of the command @param modeStr The new permission to be updated to the file or directory @param recursive Whether change the permission recursively
[ "Changes", "the", "permissions", "of", "directory", "or", "file", "with", "the", "path", "specified", "in", "args", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/ChmodCommand.java#L82-L90
18,410
Alluxio/alluxio
integration/mesos/src/main/java/alluxio/mesos/AlluxioWorkerExecutor.java
AlluxioWorkerExecutor.main
public static void main(String[] args) throws Exception { MesosExecutorDriver driver = new MesosExecutorDriver(new AlluxioWorkerExecutor()); System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1); }
java
public static void main(String[] args) throws Exception { MesosExecutorDriver driver = new MesosExecutorDriver(new AlluxioWorkerExecutor()); System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1); }
[ "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. @param args command-line arguments
[ "Starts", "the", "Alluxio", "worker", "executor", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/mesos/src/main/java/alluxio/mesos/AlluxioWorkerExecutor.java#L118-L121
18,411
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/UfsSyncChecker.java
UfsSyncChecker.checkDirectory
public void checkDirectory(InodeDirectory inode, AlluxioURI alluxioUri) throws FileDoesNotExistException, InvalidPathException, IOException { Preconditions.checkArgument(inode.isPersisted()); UfsStatus[] ufsChildren = getChildrenInUFS(alluxioUri); // Filter out temporary files 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) { // Directory is in sync mSyncedDirectories.put(alluxioUri, inode); } else { // Invalidate ancestor directories if not a mount point 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]); } }
java
public void checkDirectory(InodeDirectory inode, AlluxioURI alluxioUri) throws FileDoesNotExistException, InvalidPathException, IOException { Preconditions.checkArgument(inode.isPersisted()); UfsStatus[] ufsChildren = getChildrenInUFS(alluxioUri); // Filter out temporary files 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) { // Directory is in sync mSyncedDirectories.put(alluxioUri, inode); } else { // Invalidate ancestor directories if not a mount point 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]); } }
[ "public", "void", "checkDirectory", "(", "InodeDirectory", "inode", ",", "AlluxioURI", "alluxioUri", ")", "throws", "FileDoesNotExistException", ",", "InvalidPathException", ",", "IOException", "{", "Preconditions", ".", "checkArgument", "(", "inode", ".", "isPersisted", "(", ")", ")", ";", "UfsStatus", "[", "]", "ufsChildren", "=", "getChildrenInUFS", "(", "alluxioUri", ")", ";", "// Filter out temporary files", "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", ")", "{", "// Directory is in sync", "mSyncedDirectories", ".", "put", "(", "alluxioUri", ",", "inode", ")", ";", "}", "else", "{", "// Invalidate ancestor directories if not a mount point", "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. @param inode read-locked directory to check @param alluxioUri path of directory to to check
[ "Check", "if", "immediate", "children", "of", "directory", "are", "in", "sync", "with", "UFS", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/UfsSyncChecker.java#L81-L119
18,412
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/UfsSyncChecker.java
UfsSyncChecker.getChildrenInUFS
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)); // Assumption: multiple mounted UFSs cannot have the same ufsUri if (children == null) { return EMPTY_CHILDREN; } mListedDirectories.put(ufsUri.toString(), children); return trimIndirect(children); } }
java
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)); // Assumption: multiple mounted UFSs cannot have the same ufsUri if (children == null) { return EMPTY_CHILDREN; } mListedDirectories.put(ufsUri.toString(), children); return trimIndirect(children); } }
[ "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", ")", ")", ";", "// Assumption: multiple mounted UFSs cannot have the same ufsUri", "if", "(", "children", "==", "null", ")", "{", "return", "EMPTY_CHILDREN", ";", "}", "mListedDirectories", ".", "put", "(", "ufsUri", ".", "toString", "(", ")", ",", "children", ")", ";", "return", "trimIndirect", "(", "children", ")", ";", "}", "}" ]
Get the children in under storage for given alluxio path. @param alluxioUri alluxio path @return the list of children in under storage @throws InvalidPathException if aluxioUri is invalid @throws IOException if a non-alluxio error occurs
[ "Get", "the", "children", "in", "under", "storage", "for", "given", "alluxio", "path", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/UfsSyncChecker.java#L141-L173
18,413
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/UfsSyncChecker.java
UfsSyncChecker.trimIndirect
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()]); }
java
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()]); }
[ "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. @param children list from recursive listing @return trimmed list, null if input is null
[ "Remove", "indirect", "children", "from", "children", "list", "returned", "from", "recursive", "listing", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/UfsSyncChecker.java#L181-L190
18,414
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/meta/AlluxioMasterRestServiceHandler.java
AlluxioMasterRestServiceHandler.getWebUIConfiguration
@GET @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()); }
java
@GET @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()); }
[ "@", "GET", "@", "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. @return the response object
[ "Gets", "Web", "UI", "ServerConfiguration", "page", "data", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/meta/AlluxioMasterRestServiceHandler.java#L773-L798
18,415
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/meta/AlluxioMasterRestServiceHandler.java
AlluxioMasterRestServiceHandler.getWebUIWorkers
@GET @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()); }
java
@GET @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()); }
[ "@", "GET", "@", "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. @return the response object
[ "Gets", "Web", "UI", "workers", "page", "data", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/meta/AlluxioMasterRestServiceHandler.java#L805-L824
18,416
Alluxio/alluxio
core/common/src/main/java/alluxio/security/login/AppLoginModule.java
AppLoginModule.logout
@Override 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; }
java
@Override 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; }
[ "@", "Override", "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 <p> The implementation removes the User associated with the Subject. @return true in all cases @throws LoginException if logout fails
[ "Logs", "out", "the", "user" ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/security/login/AppLoginModule.java#L132-L143
18,417
Alluxio/alluxio
core/server/common/src/main/java/alluxio/cli/validation/Utils.java
Utils.isAddressReachable
public static boolean isAddressReachable(String hostname, int port) { try (Socket socket = new Socket(hostname, port)) { return true; } catch (IOException e) { return false; } }
java
public static boolean isAddressReachable(String hostname, int port) { try (Socket socket = new Socket(hostname, port)) { return true; } catch (IOException e) { return false; } }
[ "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. @param hostname host name of the network address @param port port of the network address @return whether the network address is reachable
[ "Validates", "whether", "a", "network", "address", "is", "reachable", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/cli/validation/Utils.java#L46-L52
18,418
Alluxio/alluxio
core/server/common/src/main/java/alluxio/cli/validation/Utils.java
Utils.isAlluxioRunning
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; } }
java
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; } }
[ "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. @param className class name of the Alluxio service @return whether the Alluxio service is running
[ "Checks", "whether", "an", "Alluxio", "service", "is", "running", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/cli/validation/Utils.java#L60-L75
18,419
Alluxio/alluxio
core/server/common/src/main/java/alluxio/cli/validation/Utils.java
Utils.isMountingPoint
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; }
java
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; }
[ "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. @param path a string represents the path to be checked @param fsTypes an array of strings represents expected file system type @return true if the path is the mounting point of volume with one of the given fsTypes, false otherwise @throws IOException if the function fails to get the mount information of the system
[ "Checks", "whether", "a", "path", "is", "the", "mounting", "point", "of", "a", "RAM", "disk", "volume", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/cli/validation/Utils.java#L115-L129
18,420
Alluxio/alluxio
core/server/common/src/main/java/alluxio/cli/validation/Utils.java
Utils.getResultFromProcess
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()); } }
java
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()); } }
[ "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. @param args array representation of the command to execute @return {@link ProcessExecutionResult} including the process's exit value, output and error
[ "Executes", "a", "command", "in", "another", "process", "and", "check", "for", "its", "execution", "result", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/cli/validation/Utils.java#L137-L169
18,421
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/SpaceReserver.java
SpaceReserver.updateStorageInfo
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 { // High watermark defines when to start the space reserving process 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); // Low watermark defines when to stop the space reserving process if started 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; // On each tier, we reserve no more than its capacity lastTierReservedBytes = (lastTierReservedBytes <= tierCapacity) ? lastTierReservedBytes : tierCapacity; mReservedSpaces.put(tierAlias, lastTierReservedBytes); } }
java
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 { // High watermark defines when to start the space reserving process 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); // Low watermark defines when to stop the space reserving process if started 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; // On each tier, we reserve no more than its capacity lastTierReservedBytes = (lastTierReservedBytes <= tierCapacity) ? lastTierReservedBytes : tierCapacity; mReservedSpaces.put(tierAlias, lastTierReservedBytes); } }
[ "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", "{", "// High watermark defines when to start the space reserving process", "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", ")", ";", "// Low watermark defines when to stop the space reserving process if started", "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", ";", "// On each tier, we reserve no more than its capacity", "lastTierReservedBytes", "=", "(", "lastTierReservedBytes", "<=", "tierCapacity", ")", "?", "lastTierReservedBytes", ":", "tierCapacity", ";", "mReservedSpaces", ".", "put", "(", "tierAlias", ",", "lastTierReservedBytes", ")", ";", "}", "}" ]
Re-calculates storage spaces and watermarks.
[ "Re", "-", "calculates", "storage", "spaces", "and", "watermarks", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/SpaceReserver.java#L71-L119
18,422
Alluxio/alluxio
core/common/src/main/java/alluxio/util/ModeUtils.java
ModeUtils.applyFileUMask
public static Mode applyFileUMask(Mode mode, String authUmask) { mode = applyUMask(mode, getUMask(authUmask)); mode = applyUMask(mode, FILE_UMASK); return mode; }
java
public static Mode applyFileUMask(Mode mode, String authUmask) { mode = applyUMask(mode, getUMask(authUmask)); mode = applyUMask(mode, FILE_UMASK); return mode; }
[ "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. @param mode the mode to update @param authUmask the umask to apply on the file @return the updated object
[ "Applies", "the", "default", "umask", "for", "newly", "created", "files", "to", "this", "mode", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/ModeUtils.java#L39-L43
18,423
Alluxio/alluxio
core/common/src/main/java/alluxio/util/ModeUtils.java
ModeUtils.applyDirectoryUMask
public static Mode applyDirectoryUMask(Mode mode, String authUmask) { return applyUMask(mode, getUMask(authUmask)); }
java
public static Mode applyDirectoryUMask(Mode mode, String authUmask) { return applyUMask(mode, getUMask(authUmask)); }
[ "public", "static", "Mode", "applyDirectoryUMask", "(", "Mode", "mode", ",", "String", "authUmask", ")", "{", "return", "applyUMask", "(", "mode", ",", "getUMask", "(", "authUmask", ")", ")", ";", "}" ]
Applies the default umask for newly created directories to this mode. @param mode the mode to update @param authUmask the umask to apply on the directory @return the updated object
[ "Applies", "the", "default", "umask", "for", "newly", "created", "directories", "to", "this", "mode", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/ModeUtils.java#L52-L54
18,424
Alluxio/alluxio
underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java
KodoClient.uploadFile
public void uploadFile(String Key, File File) throws QiniuException { com.qiniu.http.Response response = mUploadManager.put(File, Key, mAuth.uploadToken(mBucketName, Key)); response.close(); }
java
public void uploadFile(String Key, File File) throws QiniuException { com.qiniu.http.Response response = mUploadManager.put(File, Key, mAuth.uploadToken(mBucketName, Key)); response.close(); }
[ "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. @param Key Object key for kodo @param File Alluxio File
[ "Puts", "Object", "to", "Qiniu", "kodo", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java#L133-L137
18,425
Alluxio/alluxio
underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java
KodoClient.copyObject
public void copyObject(String src, String dst) throws QiniuException { mBucketManager.copy(mBucketName, src, mBucketName, dst); }
java
public void copyObject(String src, String dst) throws QiniuException { mBucketManager.copy(mBucketName, src, mBucketName, dst); }
[ "public", "void", "copyObject", "(", "String", "src", ",", "String", "dst", ")", "throws", "QiniuException", "{", "mBucketManager", ".", "copy", "(", "mBucketName", ",", "src", ",", "mBucketName", ",", "dst", ")", ";", "}" ]
Copys object in Qiniu kodo. @param src source Object key @param dst destination Object Key
[ "Copys", "object", "in", "Qiniu", "kodo", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java#L143-L145
18,426
Alluxio/alluxio
underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java
KodoClient.createEmptyObject
public void createEmptyObject(String key) throws QiniuException { com.qiniu.http.Response response = mUploadManager.put(new byte[0], key, mAuth.uploadToken(mBucketName, key)); response.close(); }
java
public void createEmptyObject(String key) throws QiniuException { com.qiniu.http.Response response = mUploadManager.put(new byte[0], key, mAuth.uploadToken(mBucketName, key)); response.close(); }
[ "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. @param key empty Object key
[ "Creates", "empty", "Object", "in", "Qiniu", "kodo", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java#L150-L154
18,427
Alluxio/alluxio
underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java
KodoClient.deleteObject
public void deleteObject(String key) throws QiniuException { com.qiniu.http.Response response = mBucketManager.delete(mBucketName, key); response.close(); }
java
public void deleteObject(String key) throws QiniuException { com.qiniu.http.Response response = mBucketManager.delete(mBucketName, key); response.close(); }
[ "public", "void", "deleteObject", "(", "String", "key", ")", "throws", "QiniuException", "{", "com", ".", "qiniu", ".", "http", ".", "Response", "response", "=", "mBucketManager", ".", "delete", "(", "mBucketName", ",", "key", ")", ";", "response", ".", "close", "(", ")", ";", "}" ]
Deletes Object in Qiniu kodo. @param key Object key
[ "Deletes", "Object", "in", "Qiniu", "kodo", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java#L159-L162
18,428
Alluxio/alluxio
underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java
KodoClient.listFiles
public FileListing listFiles(String prefix, String marker, int limit, String delimiter) throws QiniuException { return mBucketManager.listFiles(mBucketName, prefix, marker, limit, delimiter); }
java
public FileListing listFiles(String prefix, String marker, int limit, String delimiter) throws QiniuException { return mBucketManager.listFiles(mBucketName, prefix, marker, limit, delimiter); }
[ "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. @param prefix prefix for bucket @param marker Marker returned the last time a file list was obtained @param limit Length limit for each iteration, Max. 1000 @param delimiter Specifies a directory separator that lists all common prefixes (simulated listing directory effects). The default is an empty string @return result for list
[ "Lists", "object", "for", "Qiniu", "kodo", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/kodo/src/main/java/alluxio/underfs/kodo/KodoClient.java#L172-L175
18,429
Alluxio/alluxio
integration/yarn/src/main/java/alluxio/yarn/YarnUtils.java
YarnUtils.getNodeHosts
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(); }
java
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(); }
[ "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. @param yarnClient the client to use to look up node information @return the set of host names
[ "Returns", "the", "host", "names", "for", "all", "nodes", "in", "yarnClient", "s", "YARN", "cluster", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/yarn/src/main/java/alluxio/yarn/YarnUtils.java#L67-L73
18,430
Alluxio/alluxio
integration/yarn/src/main/java/alluxio/yarn/YarnUtils.java
YarnUtils.createLocalResourceOfFile
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; }
java
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; }
[ "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. @param yarnConf YARN configuration @param resource the path to a resource file on HDFS @return the created local resource
[ "Creates", "a", "local", "resource", "for", "a", "file", "on", "HDFS", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/yarn/src/main/java/alluxio/yarn/YarnUtils.java#L82-L95
18,431
Alluxio/alluxio
integration/yarn/src/main/java/alluxio/yarn/YarnUtils.java
YarnUtils.buildCommand
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()); } // Redirect stdout and stderr to yarn log files commandBuilder.addArg("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout"); commandBuilder.addArg("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stderr"); return commandBuilder.toString(); }
java
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()); } // Redirect stdout and stderr to yarn log files commandBuilder.addArg("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout"); commandBuilder.addArg("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stderr"); return commandBuilder.toString(); }
[ "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", "(", ")", ")", ";", "}", "// Redirect stdout and stderr to yarn log files", "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. @param containerType the type of container to build the command for @param args arguments to pass to to the setup script @return the built command string
[ "Creates", "a", "command", "string", "for", "running", "the", "Alluxio", "yarn", "setup", "script", "for", "the", "given", "type", "of", "yarn", "container", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/yarn/src/main/java/alluxio/yarn/YarnUtils.java#L139-L149
18,432
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/evictor/EvictionDirCandidates.java
EvictionDirCandidates.add
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; } }
java
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; } }
[ "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. @param dir the dir where the block resides @param blockId blockId of the block @param blockSizeBytes block size in bytes
[ "Adds", "the", "block", "in", "the", "directory", "to", "this", "collection", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/evictor/EvictionDirCandidates.java#L57-L75
18,433
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/HelpCommand.java
HelpCommand.printCommandInfo
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) { // In case the terminal factory failed to decide terminal type, use default width } 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()); } }
java
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) { // In case the terminal factory failed to decide terminal type, use default width } 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()); } }
[ "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", ")", "{", "// In case the terminal factory failed to decide terminal type, use default width", "}", "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. @param command command to print info @param pw where to print the info
[ "Prints", "the", "info", "about", "a", "command", "to", "the", "given", "print", "writer", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/HelpCommand.java#L46-L62
18,434
Alluxio/alluxio
minicluster/src/main/java/alluxio/multi/process/ExternalProcess.java
ExternalProcess.start
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(); }
java
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(); }
[ "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.
[ "Starts", "the", "process", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/minicluster/src/main/java/alluxio/multi/process/ExternalProcess.java#L54-L67
18,435
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fsadmin/report/UfsCommand.java
UfsCommand.run
public int run() throws IOException { Map<String, MountPointInfo> mountTable = mFileSystemMasterClient.getMountTable(); System.out.println("Alluxio under storage system information:"); printMountInfo(mountTable); return 0; }
java
public int run() throws IOException { Map<String, MountPointInfo> mountTable = mFileSystemMasterClient.getMountTable(); System.out.println("Alluxio under storage system information:"); printMountInfo(mountTable); return 0; }
[ "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. @return 0 on success, 1 otherwise
[ "Runs", "report", "ufs", "command", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fsadmin/report/UfsCommand.java#L42-L47
18,436
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fsadmin/report/UfsCommand.java
UfsCommand.printMountInfo
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() + ")"); } }
java
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() + ")"); } }
[ "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. @param mountTable the mount table to get information from
[ "Prints", "mount", "information", "for", "a", "mount", "table", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fsadmin/report/UfsCommand.java#L54-L77
18,437
Alluxio/alluxio
core/common/src/main/java/alluxio/security/login/AlluxioLoginModule.java
AlluxioLoginModule.getPrincipalUser
private Principal getPrincipalUser(String className) throws LoginException { // load the principal class ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } Class<? extends Principal> clazz; try { // Declare a temp variable so that we can suppress warnings locally @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()); } // find corresponding user based on the principal 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; }
java
private Principal getPrincipalUser(String className) throws LoginException { // load the principal class ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } Class<? extends Principal> clazz; try { // Declare a temp variable so that we can suppress warnings locally @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()); } // find corresponding user based on the principal 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; }
[ "private", "Principal", "getPrincipalUser", "(", "String", "className", ")", "throws", "LoginException", "{", "// load the principal class", "ClassLoader", "loader", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "if", "(", "loader", "==", "null", ")", "{", "loader", "=", "ClassLoader", ".", "getSystemClassLoader", "(", ")", ";", "}", "Class", "<", "?", "extends", "Principal", ">", "clazz", ";", "try", "{", "// Declare a temp variable so that we can suppress warnings locally", "@", "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", "(", ")", ")", ";", "}", "// find corresponding user based on the principal", "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. @param className the name of class extending Principal @return a user extending a specified Principal @throws LoginException if the specified class can not be found, or there are are more than one instance of Principal
[ "Gets", "a", "principal", "user", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/security/login/AlluxioLoginModule.java#L138-L165
18,438
Alluxio/alluxio
core/common/src/main/java/alluxio/resource/ResourcePool.java
ResourcePool.release
@Override public void release(T resource) { if (resource != null) { mResources.add(resource); try (LockResource r = new LockResource(mTakeLock)) { mNotEmpty.signal(); } } }
java
@Override public void release(T resource) { if (resource != null) { mResources.add(resource); try (LockResource r = new LockResource(mTakeLock)) { mNotEmpty.signal(); } } }
[ "@", "Override", "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. @param resource the resource to be released, it should not be reused after calling this method
[ "Releases", "an", "object", "of", "type", "T", "this", "must", "be", "called", "after", "the", "thread", "is", "done", "using", "a", "resource", "obtained", "by", "acquire", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/resource/ResourcePool.java#L157-L165
18,439
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/grpc/DataMessageServerStreamObserver.java
DataMessageServerStreamObserver.onNext
public void onNext(DataMessage<T, DataBuffer> value) { DataBuffer buffer = value.getBuffer(); if (buffer != null) { mBufferRepository.offerBuffer(buffer, value.getMessage()); } mObserver.onNext(value.getMessage()); }
java
public void onNext(DataMessage<T, DataBuffer> value) { DataBuffer buffer = value.getBuffer(); if (buffer != null) { mBufferRepository.offerBuffer(buffer, value.getMessage()); } mObserver.onNext(value.getMessage()); }
[ "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. @param value the value passed to the stream
[ "Receives", "a", "message", "with", "data", "buffer", "from", "the", "stream", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/grpc/DataMessageServerStreamObserver.java#L49-L55
18,440
Alluxio/alluxio
core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java
UnderFileSystemUtils.deleteDirIfExists
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."); } }
java
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."); } }
[ "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. @param ufs instance of {@link UnderFileSystem} @param path path to the directory
[ "Deletes", "the", "directory", "at", "the", "given", "path", "if", "it", "exists", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java#L36-L41
18,441
Alluxio/alluxio
core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java
UnderFileSystemUtils.mkdirIfNotExists
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); } } }
java
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); } } }
[ "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. @param ufs instance of {@link UnderFileSystem} @param path path to the directory
[ "Attempts", "to", "create", "the", "directory", "if", "it", "does", "not", "already", "exist", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java#L49-L55
18,442
Alluxio/alluxio
core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java
UnderFileSystemUtils.touch
public static void touch(UnderFileSystem ufs, String path) throws IOException { OutputStream os = ufs.create(path); os.close(); }
java
public static void touch(UnderFileSystem ufs, String path) throws IOException { OutputStream os = ufs.create(path); os.close(); }
[ "public", "static", "void", "touch", "(", "UnderFileSystem", "ufs", ",", "String", "path", ")", "throws", "IOException", "{", "OutputStream", "os", "=", "ufs", ".", "create", "(", "path", ")", ";", "os", ".", "close", "(", ")", ";", "}" ]
Creates an empty file. @param ufs instance of {@link UnderFileSystem} @param path path to the file
[ "Creates", "an", "empty", "file", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java#L63-L66
18,443
Alluxio/alluxio
core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java
UnderFileSystemUtils.deleteFileIfExists
public static void deleteFileIfExists(UnderFileSystem ufs, String path) { try { if (ufs.isFile(path)) { ufs.deleteFile(path); } } catch (IOException e) { throw new RuntimeException(e); } }
java
public static void deleteFileIfExists(UnderFileSystem ufs, String path) { try { if (ufs.isFile(path)) { ufs.deleteFile(path); } } catch (IOException e) { throw new RuntimeException(e); } }
[ "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. @param ufs instance of {@link UnderFileSystem} @param path the path to delete
[ "Deletes", "the", "specified", "path", "from", "the", "specified", "under", "file", "system", "if", "it", "is", "a", "file", "and", "exists", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java#L74-L82
18,444
Alluxio/alluxio
core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java
UnderFileSystemUtils.approximateContentHash
public static String approximateContentHash(long length, long modTime) { // approximating the content hash with the file length and 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(); }
java
public static String approximateContentHash(long length, long modTime) { // approximating the content hash with the file length and 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(); }
[ "public", "static", "String", "approximateContentHash", "(", "long", "length", ",", "long", "modTime", ")", "{", "// approximating the content hash with the file length and 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. @param length the content length @param modTime the content last modification time @return the content hash
[ "Returns", "an", "approximate", "content", "hash", "using", "the", "length", "and", "modification", "time", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java#L147-L158
18,445
Alluxio/alluxio
core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java
ObjectUnderFileSystem.convertToFolderName
protected String convertToFolderName(String key) { // Strips the slash if it is the end of the key string. This is because the slash at // the end of the string is not part of the Object key. key = CommonUtils.stripSuffixIfPresent(key, PATH_SEPARATOR); return key + getFolderSuffix(); }
java
protected String convertToFolderName(String key) { // Strips the slash if it is the end of the key string. This is because the slash at // the end of the string is not part of the Object key. key = CommonUtils.stripSuffixIfPresent(key, PATH_SEPARATOR); return key + getFolderSuffix(); }
[ "protected", "String", "convertToFolderName", "(", "String", "key", ")", "{", "// Strips the slash if it is the end of the key string. This is because the slash at", "// the end of the string is not part of the Object key.", "key", "=", "CommonUtils", ".", "stripSuffixIfPresent", "(", "key", ",", "PATH_SEPARATOR", ")", ";", "return", "key", "+", "getFolderSuffix", "(", ")", ";", "}" ]
Appends the directory suffix to the key. @param key the key to convert @return key as a directory path
[ "Appends", "the", "directory", "suffix", "to", "the", "key", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java#L778-L783
18,446
Alluxio/alluxio
core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java
ObjectUnderFileSystem.deleteObjects
protected List<String> deleteObjects(List<String> keys) throws IOException { List<String> result = new ArrayList<>(); for (String key : keys) { boolean status = deleteObject(key); // If key is a directory, it is possible that it was not created through Alluxio and no // zero-byte breadcrumb exists if (status || key.endsWith(getFolderSuffix())) { result.add(key); } } return result; }
java
protected List<String> deleteObjects(List<String> keys) throws IOException { List<String> result = new ArrayList<>(); for (String key : keys) { boolean status = deleteObject(key); // If key is a directory, it is possible that it was not created through Alluxio and no // zero-byte breadcrumb exists if (status || key.endsWith(getFolderSuffix())) { result.add(key); } } return result; }
[ "protected", "List", "<", "String", ">", "deleteObjects", "(", "List", "<", "String", ">", "keys", ")", "throws", "IOException", "{", "List", "<", "String", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "key", ":", "keys", ")", "{", "boolean", "status", "=", "deleteObject", "(", "key", ")", ";", "// If key is a directory, it is possible that it was not created through Alluxio and no", "// zero-byte breadcrumb exists", "if", "(", "status", "||", "key", ".", "endsWith", "(", "getFolderSuffix", "(", ")", ")", ")", "{", "result", ".", "add", "(", "key", ")", ";", "}", "}", "return", "result", ";", "}" ]
Internal function to delete a list of keys. @param keys the list of keys to delete @return list of successfully deleted keys
[ "Internal", "function", "to", "delete", "a", "list", "of", "keys", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java#L808-L819
18,447
Alluxio/alluxio
core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java
ObjectUnderFileSystem.getListingChunkLength
protected int getListingChunkLength(AlluxioConfiguration conf) { return conf.getInt(PropertyKey.UNDERFS_LISTING_LENGTH) > getListingChunkLengthMax() ? getListingChunkLengthMax() : conf.getInt(PropertyKey.UNDERFS_LISTING_LENGTH); }
java
protected int getListingChunkLength(AlluxioConfiguration conf) { return conf.getInt(PropertyKey.UNDERFS_LISTING_LENGTH) > getListingChunkLengthMax() ? getListingChunkLengthMax() : conf.getInt(PropertyKey.UNDERFS_LISTING_LENGTH); }
[ "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. @return length of each list request
[ "The", "number", "of", "items", "to", "query", "in", "a", "single", "listing", "chunk", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java#L842-L845
18,448
Alluxio/alluxio
core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java
ObjectUnderFileSystem.getParentPath
@Nullable protected String getParentPath(String path) { // Root does not have a parent. if (isRoot(path)) { return null; } int separatorIndex = path.lastIndexOf(PATH_SEPARATOR); if (separatorIndex < 0) { return null; } return path.substring(0, separatorIndex); }
java
@Nullable protected String getParentPath(String path) { // Root does not have a parent. if (isRoot(path)) { return null; } int separatorIndex = path.lastIndexOf(PATH_SEPARATOR); if (separatorIndex < 0) { return null; } return path.substring(0, separatorIndex); }
[ "@", "Nullable", "protected", "String", "getParentPath", "(", "String", "path", ")", "{", "// Root does not have a parent.", "if", "(", "isRoot", "(", "path", ")", ")", "{", "return", "null", ";", "}", "int", "separatorIndex", "=", "path", ".", "lastIndexOf", "(", "PATH_SEPARATOR", ")", ";", "if", "(", "separatorIndex", "<", "0", ")", "{", "return", "null", ";", "}", "return", "path", ".", "substring", "(", "0", ",", "separatorIndex", ")", ";", "}" ]
Get parent path. @param path ufs path including scheme and bucket @return the parent path, or null if the parent does not exist
[ "Get", "parent", "path", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java#L863-L874
18,449
Alluxio/alluxio
core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java
ObjectUnderFileSystem.isRoot
protected boolean isRoot(String path) { return PathUtils.normalizePath(path, PATH_SEPARATOR).equals( PathUtils.normalizePath(getRootKey(), PATH_SEPARATOR)); }
java
protected boolean isRoot(String path) { return PathUtils.normalizePath(path, PATH_SEPARATOR).equals( PathUtils.normalizePath(getRootKey(), PATH_SEPARATOR)); }
[ "protected", "boolean", "isRoot", "(", "String", "path", ")", "{", "return", "PathUtils", ".", "normalizePath", "(", "path", ",", "PATH_SEPARATOR", ")", ".", "equals", "(", "PathUtils", ".", "normalizePath", "(", "getRootKey", "(", ")", ",", "PATH_SEPARATOR", ")", ")", ";", "}" ]
Checks if the path is the root. @param path ufs path including scheme and bucket @return true if the path is the root, false otherwise
[ "Checks", "if", "the", "path", "is", "the", "root", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java#L882-L885
18,450
Alluxio/alluxio
core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java
ObjectUnderFileSystem.getChildName
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)); }
java
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)); }
[ "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. @param child the key of the child @param parent the key of the parent @return the child key with the parent prefix removed
[ "Gets", "the", "child", "name", "based", "on", "the", "parent", "name", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java#L894-L899
18,451
Alluxio/alluxio
core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java
ObjectUnderFileSystem.parentExists
protected boolean parentExists(String path) throws IOException { // Assume root always has a parent if (isRoot(path)) { return true; } String parentKey = getParentPath(path); return parentKey != null && isDirectory(parentKey); }
java
protected boolean parentExists(String path) throws IOException { // Assume root always has a parent if (isRoot(path)) { return true; } String parentKey = getParentPath(path); return parentKey != null && isDirectory(parentKey); }
[ "protected", "boolean", "parentExists", "(", "String", "path", ")", "throws", "IOException", "{", "// Assume root always has a parent", "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. @param path the path to check @return true if the parent exists or if the path is root, false otherwise
[ "Treating", "the", "object", "store", "as", "a", "file", "system", "checks", "if", "the", "parent", "directory", "exists", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java#L1089-L1096
18,452
Alluxio/alluxio
core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java
ObjectUnderFileSystem.retryOnException
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; }
java
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; }
[ "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. @param op the object store operation to retry @param description the description regarding the operation @return the operation result if operation succeed
[ "Retries", "the", "given", "object", "store", "operation", "when", "it", "throws", "exceptions", "to", "resolve", "eventual", "consistency", "issue", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java#L1136-L1150
18,453
Alluxio/alluxio
core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java
ObjectUnderFileSystem.retryOnFalse
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; }
java
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; }
[ "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. @param op the object store operation to retry @param description the description regarding the operation @return the operation result if operation returned true
[ "Retries", "the", "given", "object", "store", "operation", "when", "it", "returns", "false", "to", "resolve", "eventual", "consistency", "issue", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/underfs/ObjectUnderFileSystem.java#L1160-L1172
18,454
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java
StorageDir.removeBlockMeta
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); }
java
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); }
[ "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. @param blockMeta the metadata of the block @throws BlockDoesNotExistException if no block is found
[ "Removes", "a", "block", "from", "this", "storage", "dir", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java#L329-L337
18,455
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java
StorageDir.removeTempBlockMeta
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); }
java
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); }
[ "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. @param tempBlockMeta the metadata of the temp block to remove @throws BlockDoesNotExistException if no temp block is found
[ "Removes", "a", "temp", "block", "from", "this", "storage", "dir", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java#L345-L363
18,456
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java
StorageDir.resizeTempBlockMeta
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!"); } }
java
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!"); } }
[ "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. @param tempBlockMeta the metadata of the temp block to resize @param newSize the new size after change in bytes @throws InvalidWorkerStateException when newSize is smaller than oldSize
[ "Changes", "the", "size", "of", "a", "temp", "block", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java#L372-L381
18,457
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java
StorageDir.cleanupSessionTempBlocks
public void cleanupSessionTempBlocks(long sessionId, List<Long> tempBlockIds) { Set<Long> sessionTempBlocks = mSessionIdToTempBlockIdsMap.get(sessionId); // The session's temporary blocks have already been removed. if (sessionTempBlocks == null) { return; } for (Long tempBlockId : tempBlockIds) { if (!mBlockIdToTempBlockMap.containsKey(tempBlockId)) { // This temp block does not exist in this dir, this is expected for some blocks since the // input list is across all dirs 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 { // This may happen if the client comes back during clean up and creates more blocks or some // temporary blocks failed to be deleted LOG.warn("Blocks still owned by session {} after cleanup.", sessionId); } }
java
public void cleanupSessionTempBlocks(long sessionId, List<Long> tempBlockIds) { Set<Long> sessionTempBlocks = mSessionIdToTempBlockIdsMap.get(sessionId); // The session's temporary blocks have already been removed. if (sessionTempBlocks == null) { return; } for (Long tempBlockId : tempBlockIds) { if (!mBlockIdToTempBlockMap.containsKey(tempBlockId)) { // This temp block does not exist in this dir, this is expected for some blocks since the // input list is across all dirs 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 { // This may happen if the client comes back during clean up and creates more blocks or some // temporary blocks failed to be deleted LOG.warn("Blocks still owned by session {} after cleanup.", sessionId); } }
[ "public", "void", "cleanupSessionTempBlocks", "(", "long", "sessionId", ",", "List", "<", "Long", ">", "tempBlockIds", ")", "{", "Set", "<", "Long", ">", "sessionTempBlocks", "=", "mSessionIdToTempBlockIdsMap", ".", "get", "(", "sessionId", ")", ";", "// The session's temporary blocks have already been removed.", "if", "(", "sessionTempBlocks", "==", "null", ")", "{", "return", ";", "}", "for", "(", "Long", "tempBlockId", ":", "tempBlockIds", ")", "{", "if", "(", "!", "mBlockIdToTempBlockMap", ".", "containsKey", "(", "tempBlockId", ")", ")", "{", "// This temp block does not exist in this dir, this is expected for some blocks since the", "// input list is across all dirs", "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", "{", "// This may happen if the client comes back during clean up and creates more blocks or some", "// temporary blocks failed to be deleted", "LOG", ".", "warn", "(", "\"Blocks still owned by session {} after cleanup.\"", ",", "sessionId", ")", ";", "}", "}" ]
Cleans up the temp block metadata for each block id passed in. @param sessionId the id of the client associated with the temporary blocks @param tempBlockIds the list of temporary blocks to clean up, non temporary blocks or nonexistent blocks will be ignored
[ "Cleans", "up", "the", "temp", "block", "metadata", "for", "each", "block", "id", "passed", "in", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java#L390-L417
18,458
Alluxio/alluxio
underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java
SupportedHdfsActiveSyncProvider.initNextWindow
private void initNextWindow() { for (String syncPoint : mActivity.keySet()) { mActivity.put(syncPoint, mActivity.get(syncPoint).intValue() / 10); mAge.put(syncPoint, mAge.get(syncPoint).intValue() + 1); } }
java
private void initNextWindow() { for (String syncPoint : mActivity.keySet()) { mActivity.put(syncPoint, mActivity.get(syncPoint).intValue() / 10); mAge.put(syncPoint, mAge.get(syncPoint).intValue() + 1); } }
[ "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. This includes increasing the age of the unsynced syncpoints and decrease the activity of unsynced syncpoints.
[ "Start", "the", "accounting", "for", "the", "next", "window", "of", "events", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java#L115-L120
18,459
Alluxio/alluxio
underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java
SupportedHdfsActiveSyncProvider.startSync
@Override public void startSync(AlluxioURI ufsUri) { LOG.debug("Add {} as a sync point", ufsUri.toString()); mUfsUriList.add(ufsUri); }
java
@Override public void startSync(AlluxioURI ufsUri) { LOG.debug("Add {} as a sync point", ufsUri.toString()); mUfsUriList.add(ufsUri); }
[ "@", "Override", "public", "void", "startSync", "(", "AlluxioURI", "ufsUri", ")", "{", "LOG", ".", "debug", "(", "\"Add {} as a sync point\"", ",", "ufsUri", ".", "toString", "(", ")", ")", ";", "mUfsUriList", ".", "add", "(", "ufsUri", ")", ";", "}" ]
startSync on a ufs uri. @param ufsUri the ufs uri to monitor for sync
[ "startSync", "on", "a", "ufs", "uri", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java#L239-L243
18,460
Alluxio/alluxio
underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java
SupportedHdfsActiveSyncProvider.stopSync
@Override public void stopSync(AlluxioURI ufsUri) { LOG.debug("attempt to remove {} from sync point list", ufsUri.toString()); mUfsUriList.remove(ufsUri); }
java
@Override public void stopSync(AlluxioURI ufsUri) { LOG.debug("attempt to remove {} from sync point list", ufsUri.toString()); mUfsUriList.remove(ufsUri); }
[ "@", "Override", "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. @param ufsUri the ufs uri to stop monitoring for sync
[ "stop", "sync", "on", "a", "ufs", "uri", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java#L250-L254
18,461
Alluxio/alluxio
underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java
SupportedHdfsActiveSyncProvider.pollEvent
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; // need to sync all syncpoints at this point } catch (InterruptedException e) { LOG.warn("InterruptedException during polling {}", e); return; } } }
java
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; // need to sync all syncpoints at this point } catch (InterruptedException e) { LOG.warn("InterruptedException during polling {}", e); return; } } }
[ "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", ";", "// need to sync all syncpoints at this point", "}", "catch", "(", "InterruptedException", "e", ")", "{", "LOG", ".", "warn", "(", "\"InterruptedException during polling {}\"", ",", "e", ")", ";", "return", ";", "}", "}", "}" ]
Fetch and process events. @param eventStream event stream
[ "Fetch", "and", "process", "events", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java#L260-L308
18,462
Alluxio/alluxio
underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java
SupportedHdfsActiveSyncProvider.getActivitySyncInfo
public SyncInfo getActivitySyncInfo() { // The overview of this method is // 1. setup a source of event // 2. Filter based on the paths associated with this mountId // 3. Build History for each of the syncPoint // 4. If heurstics function returns sync, then we sync the syncPoint 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) { // force sync every syncpoint 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 the activity level is below the threshold or the sync point is too old, we sync 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; }
java
public SyncInfo getActivitySyncInfo() { // The overview of this method is // 1. setup a source of event // 2. Filter based on the paths associated with this mountId // 3. Build History for each of the syncPoint // 4. If heurstics function returns sync, then we sync the syncPoint 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) { // force sync every syncpoint 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 the activity level is below the threshold or the sync point is too old, we sync 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; }
[ "public", "SyncInfo", "getActivitySyncInfo", "(", ")", "{", "// The overview of this method is", "// 1. setup a source of event", "// 2. Filter based on the paths associated with this mountId", "// 3. Build History for each of the syncPoint", "// 4. If heurstics function returns sync, then we sync the syncPoint", "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", ")", "{", "// force sync every syncpoint", "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 the activity level is below the threshold or the sync point is too old, we sync", "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. @return SyncInfo object which encapsulates the necessary information about changes
[ "Get", "the", "activity", "sync", "info", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/hdfs/src/main/java/alluxio/underfs/hdfs/activesync/SupportedHdfsActiveSyncProvider.java#L323-L368
18,463
Alluxio/alluxio
core/common/src/main/java/alluxio/grpc/GrpcServerBuilder.java
GrpcServerBuilder.keepAliveTime
public GrpcServerBuilder keepAliveTime(long keepAliveTime, TimeUnit timeUnit) { mNettyServerBuilder = mNettyServerBuilder.keepAliveTime(keepAliveTime, timeUnit); return this; }
java
public GrpcServerBuilder keepAliveTime(long keepAliveTime, TimeUnit timeUnit) { mNettyServerBuilder = mNettyServerBuilder.keepAliveTime(keepAliveTime, timeUnit); return this; }
[ "public", "GrpcServerBuilder", "keepAliveTime", "(", "long", "keepAliveTime", ",", "TimeUnit", "timeUnit", ")", "{", "mNettyServerBuilder", "=", "mNettyServerBuilder", ".", "keepAliveTime", "(", "keepAliveTime", ",", "timeUnit", ")", ";", "return", "this", ";", "}" ]
Sets the keep alive time. @param keepAliveTime the time to wait after idle before pinging client @param timeUnit unit of the time @return an updated instance of this {@link GrpcServerBuilder}
[ "Sets", "the", "keep", "alive", "time", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/grpc/GrpcServerBuilder.java#L122-L125
18,464
Alluxio/alluxio
core/common/src/main/java/alluxio/grpc/GrpcServerBuilder.java
GrpcServerBuilder.keepAliveTimeout
public GrpcServerBuilder keepAliveTimeout(long keepAliveTimeout, TimeUnit timeUnit) { mNettyServerBuilder = mNettyServerBuilder.keepAliveTimeout(keepAliveTimeout, timeUnit); return this; }
java
public GrpcServerBuilder keepAliveTimeout(long keepAliveTimeout, TimeUnit timeUnit) { mNettyServerBuilder = mNettyServerBuilder.keepAliveTimeout(keepAliveTimeout, timeUnit); return this; }
[ "public", "GrpcServerBuilder", "keepAliveTimeout", "(", "long", "keepAliveTimeout", ",", "TimeUnit", "timeUnit", ")", "{", "mNettyServerBuilder", "=", "mNettyServerBuilder", ".", "keepAliveTimeout", "(", "keepAliveTimeout", ",", "timeUnit", ")", ";", "return", "this", ";", "}" ]
Sets the keep alive timeout. @param keepAliveTimeout time to wait after pinging client before closing the connection @param timeUnit unit of the timeout @return an updated instance of this {@link GrpcServerBuilder}
[ "Sets", "the", "keep", "alive", "timeout", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/grpc/GrpcServerBuilder.java#L134-L137
18,465
Alluxio/alluxio
core/common/src/main/java/alluxio/grpc/GrpcServerBuilder.java
GrpcServerBuilder.withChildOption
public <T> GrpcServerBuilder withChildOption(ChannelOption<T> option, T value) { mNettyServerBuilder = mNettyServerBuilder.withChildOption(option, value); return this; }
java
public <T> GrpcServerBuilder withChildOption(ChannelOption<T> option, T value) { mNettyServerBuilder = mNettyServerBuilder.withChildOption(option, value); return this; }
[ "public", "<", "T", ">", "GrpcServerBuilder", "withChildOption", "(", "ChannelOption", "<", "T", ">", "option", ",", "T", "value", ")", "{", "mNettyServerBuilder", "=", "mNettyServerBuilder", ".", "withChildOption", "(", "option", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets a netty channel option. @param <T> channel option type @param option the option to be set @param value the new value @return an updated instance of this {@link GrpcServerBuilder}
[ "Sets", "a", "netty", "channel", "option", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/grpc/GrpcServerBuilder.java#L158-L161
18,466
Alluxio/alluxio
core/common/src/main/java/alluxio/grpc/GrpcServerBuilder.java
GrpcServerBuilder.build
public GrpcServer build() { addService(new GrpcService(new ServiceVersionClientServiceHandler(mServices)) .disableAuthentication()); return new GrpcServer(mNettyServerBuilder.build(), mConfiguration.getMs(PropertyKey.MASTER_GRPC_SERVER_SHUTDOWN_TIMEOUT)); }
java
public GrpcServer build() { addService(new GrpcService(new ServiceVersionClientServiceHandler(mServices)) .disableAuthentication()); return new GrpcServer(mNettyServerBuilder.build(), mConfiguration.getMs(PropertyKey.MASTER_GRPC_SERVER_SHUTDOWN_TIMEOUT)); }
[ "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. @return the built {@link GrpcServer}
[ "Build", "the", "server", ".", "It", "attaches", "required", "services", "and", "interceptors", "for", "authentication", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/grpc/GrpcServerBuilder.java#L242-L247
18,467
Alluxio/alluxio
job/server/src/main/java/alluxio/master/AlluxioJobMaster.java
AlluxioJobMaster.main
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); // Exit to stop any non-daemon threads. System.exit(-1); throw t; } ProcessUtils.run(process); }
java
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); // Exit to stop any non-daemon threads. System.exit(-1); throw t; } ProcessUtils.run(process); }
[ "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", ")", ";", "// Exit to stop any non-daemon threads.", "System", ".", "exit", "(", "-", "1", ")", ";", "throw", "t", ";", "}", "ProcessUtils", ".", "run", "(", "process", ")", ";", "}" ]
Starts the Alluxio job master. @param args command line arguments, should be empty
[ "Starts", "the", "Alluxio", "job", "master", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/master/AlluxioJobMaster.java#L35-L53
18,468
Alluxio/alluxio
core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournalGarbageCollector.java
UfsJournalGarbageCollector.gc
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; // Checkpoint. List<UfsJournalFile> checkpoints = snapshot.getCheckpoints(); if (!checkpoints.isEmpty()) { checkpointSequenceNumber = checkpoints.get(checkpoints.size() - 1).getEnd(); } for (int i = 0; i < checkpoints.size() - 1; i++) { // Only keep at most 2 checkpoints. if (i < checkpoints.size() - 2) { deleteNoException(checkpoints.get(i).getLocation()); } // For the the second last checkpoint. Check whether it has been there for a long time. gcFileIfStale(checkpoints.get(i), checkpointSequenceNumber); } for (UfsJournalFile log : snapshot.getLogs()) { gcFileIfStale(log, checkpointSequenceNumber); } for (UfsJournalFile tmpCheckpoint : snapshot.getTemporaryCheckpoints()) { gcFileIfStale(tmpCheckpoint, checkpointSequenceNumber); } }
java
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; // Checkpoint. List<UfsJournalFile> checkpoints = snapshot.getCheckpoints(); if (!checkpoints.isEmpty()) { checkpointSequenceNumber = checkpoints.get(checkpoints.size() - 1).getEnd(); } for (int i = 0; i < checkpoints.size() - 1; i++) { // Only keep at most 2 checkpoints. if (i < checkpoints.size() - 2) { deleteNoException(checkpoints.get(i).getLocation()); } // For the the second last checkpoint. Check whether it has been there for a long time. gcFileIfStale(checkpoints.get(i), checkpointSequenceNumber); } for (UfsJournalFile log : snapshot.getLogs()) { gcFileIfStale(log, checkpointSequenceNumber); } for (UfsJournalFile tmpCheckpoint : snapshot.getTemporaryCheckpoints()) { gcFileIfStale(tmpCheckpoint, checkpointSequenceNumber); } }
[ "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", ";", "// Checkpoint.", "List", "<", "UfsJournalFile", ">", "checkpoints", "=", "snapshot", ".", "getCheckpoints", "(", ")", ";", "if", "(", "!", "checkpoints", ".", "isEmpty", "(", ")", ")", "{", "checkpointSequenceNumber", "=", "checkpoints", ".", "get", "(", "checkpoints", ".", "size", "(", ")", "-", "1", ")", ".", "getEnd", "(", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "checkpoints", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")", "{", "// Only keep at most 2 checkpoints.", "if", "(", "i", "<", "checkpoints", ".", "size", "(", ")", "-", "2", ")", "{", "deleteNoException", "(", "checkpoints", ".", "get", "(", "i", ")", ".", "getLocation", "(", ")", ")", ";", "}", "// For the the second last checkpoint. Check whether it has been there for a long time.", "gcFileIfStale", "(", "checkpoints", ".", "get", "(", "i", ")", ",", "checkpointSequenceNumber", ")", ";", "}", "for", "(", "UfsJournalFile", "log", ":", "snapshot", ".", "getLogs", "(", ")", ")", "{", "gcFileIfStale", "(", "log", ",", "checkpointSequenceNumber", ")", ";", "}", "for", "(", "UfsJournalFile", "tmpCheckpoint", ":", "snapshot", ".", "getTemporaryCheckpoints", "(", ")", ")", "{", "gcFileIfStale", "(", "tmpCheckpoint", ",", "checkpointSequenceNumber", ")", ";", "}", "}" ]
Deletes unneeded snapshots.
[ "Deletes", "unneeded", "snapshots", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournalGarbageCollector.java#L79-L110
18,469
Alluxio/alluxio
core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournalGarbageCollector.java
UfsJournalGarbageCollector.gcFileIfStale
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()); } }
java
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()); } }
[ "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. @param file the file @param checkpointSequenceNumber the first sequence number that has not been checkpointed
[ "Garbage", "collects", "a", "file", "if", "necessary", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournalGarbageCollector.java#L118-L138
18,470
Alluxio/alluxio
core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournalGarbageCollector.java
UfsJournalGarbageCollector.deleteNoException
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); } }
java
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); } }
[ "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. @param location the file location
[ "Deletes", "a", "file", "and", "swallows", "the", "exception", "by", "logging", "it", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournalGarbageCollector.java#L145-L152
18,471
Alluxio/alluxio
job/server/src/main/java/alluxio/master/job/command/CommandManager.java
CommandManager.submitRunTaskCommand
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) { // TODO(yupeng) better exception handling 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()); }
java
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) { // TODO(yupeng) better exception handling 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()); }
[ "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", ")", "{", "// TODO(yupeng) better exception handling", "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. @param jobId the id of the job @param taskId the id of the task @param jobConfig the job configuration @param taskArgs the arguments passed to the executor on the worker @param workerId the id of the worker
[ "Submits", "a", "run", "-", "task", "command", "to", "a", "specified", "worker", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/master/job/command/CommandManager.java#L57-L78
18,472
Alluxio/alluxio
job/server/src/main/java/alluxio/master/job/command/CommandManager.java
CommandManager.submitCancelTaskCommand
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()); }
java
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()); }
[ "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. @param jobId the job id @param taskId the task id @param workerId the worker id
[ "Submits", "a", "cancel", "-", "task", "command", "to", "a", "specified", "worker", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/master/job/command/CommandManager.java#L87-L97
18,473
Alluxio/alluxio
job/server/src/main/java/alluxio/master/job/command/CommandManager.java
CommandManager.pollAllPendingCommands
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; }
java
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; }
[ "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. @param workerId id of the worker to send the commands to @return the list of the commends polled
[ "Polls", "all", "the", "pending", "commands", "to", "a", "worker", "and", "removes", "the", "commands", "from", "the", "queue", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/master/job/command/CommandManager.java#L105-L113
18,474
Alluxio/alluxio
core/base/src/main/java/alluxio/security/authorization/AclActions.java
AclActions.updateByModeBits
public void updateByModeBits(Mode.Bits bits) { // Each index equals to corresponding AclAction's ordinal. // E.g. Mode.Bits.READ corresponds to AclAction.READ, the former has index 0 in indexedBits, // the later has ordinal 0 in AclAction. 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); } } }
java
public void updateByModeBits(Mode.Bits bits) { // Each index equals to corresponding AclAction's ordinal. // E.g. Mode.Bits.READ corresponds to AclAction.READ, the former has index 0 in indexedBits, // the later has ordinal 0 in AclAction. 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); } } }
[ "public", "void", "updateByModeBits", "(", "Mode", ".", "Bits", "bits", ")", "{", "// Each index equals to corresponding AclAction's ordinal.", "// E.g. Mode.Bits.READ corresponds to AclAction.READ, the former has index 0 in indexedBits,", "// the later has ordinal 0 in AclAction.", "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. For example, if bits imply READ, then READ is added to permitted actions, otherwise, READ is removed from permitted actions. Same logic applies to WRITE and EXECUTE. @param bits the mode bits
[ "Updates", "permitted", "actions", "based", "on", "the", "mode", "bits", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/base/src/main/java/alluxio/security/authorization/AclActions.java#L90-L104
18,475
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/AlluxioMaster.java
AlluxioMaster.main
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"); // fatalError will exit, so we shouldn't reach here. throw t; } // Register a shutdown hook for master, so that master closes the journal files when it // receives SIGTERM. ProcessUtils.stopProcessOnShutdown(process); ProcessUtils.run(process); }
java
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"); // fatalError will exit, so we shouldn't reach here. throw t; } // Register a shutdown hook for master, so that master closes the journal files when it // receives SIGTERM. ProcessUtils.stopProcessOnShutdown(process); ProcessUtils.run(process); }
[ "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\"", ")", ";", "// fatalError will exit, so we shouldn't reach here.", "throw", "t", ";", "}", "// Register a shutdown hook for master, so that master closes the journal files when it", "// receives SIGTERM.", "ProcessUtils", ".", "stopProcessOnShutdown", "(", "process", ")", ";", "ProcessUtils", ".", "run", "(", "process", ")", ";", "}" ]
Starts the Alluxio master. @param args command line arguments, should be empty
[ "Starts", "the", "Alluxio", "master", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/AlluxioMaster.java#L35-L56
18,476
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/DefaultPermissionChecker.java
DefaultPermissionChecker.checkOwner
private void checkOwner(LockedInodePath inodePath) throws AccessControlException, InvalidPathException { // collects inodes info on the path List<InodeView> inodeList = inodePath.getInodeViewList(); // collects user and groups 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); }
java
private void checkOwner(LockedInodePath inodePath) throws AccessControlException, InvalidPathException { // collects inodes info on the path List<InodeView> inodeList = inodePath.getInodeViewList(); // collects user and groups 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); }
[ "private", "void", "checkOwner", "(", "LockedInodePath", "inodePath", ")", "throws", "AccessControlException", ",", "InvalidPathException", "{", "// collects inodes info on the path", "List", "<", "InodeView", ">", "inodeList", "=", "inodePath", ".", "getInodeViewList", "(", ")", ";", "// collects user and groups", "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. @param inodePath path to be checked on @throws AccessControlException if permission checking fails @throws InvalidPathException if the path is invalid
[ "Checks", "whether", "the", "client", "user", "is", "the", "owner", "of", "the", "path", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/DefaultPermissionChecker.java#L164-L178
18,477
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/DefaultPermissionChecker.java
DefaultPermissionChecker.checkSuperUser
private void checkSuperUser() throws AccessControlException { // collects user and groups 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")); } }
java
private void checkSuperUser() throws AccessControlException { // collects user and groups 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")); } }
[ "private", "void", "checkSuperUser", "(", ")", "throws", "AccessControlException", "{", "// collects user and groups", "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. @throws AccessControlException if the user is not a super user
[ "Checks", "whether", "the", "user", "is", "a", "super", "user", "or", "in", "super", "group", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/DefaultPermissionChecker.java#L185-L193
18,478
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/DefaultPermissionChecker.java
DefaultPermissionChecker.checkInode
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))); } } }
java
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))); } } }
[ "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. @param user who requests access permission @param groups in which user belongs to @param inode whose attributes used for permission check logic @param bits requested {@link Mode.Bits} by user @param path the path to check permission on @throws AccessControlException if permission checking fails
[ "This", "method", "checks", "requested", "permission", "on", "a", "given", "inode", "represented", "by", "its", "fileInfo", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/DefaultPermissionChecker.java#L246-L257
18,479
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/DefaultPermissionChecker.java
DefaultPermissionChecker.getPermissionInternal
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); // bypass checking permission for super user or super group of Alluxio file system. if (isPrivilegedUser(user, groups)) { return Mode.Bits.ALL; } // traverses from root to the parent dir to all inodes included by this path are executable 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(); }
java
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); // bypass checking permission for super user or super group of Alluxio file system. if (isPrivilegedUser(user, groups)) { return Mode.Bits.ALL; } // traverses from root to the parent dir to all inodes included by this path are executable 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(); }
[ "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", ")", ";", "// bypass checking permission for super user or super group of Alluxio file system.", "if", "(", "isPrivilegedUser", "(", "user", ",", "groups", ")", ")", "{", "return", "Mode", ".", "Bits", ".", "ALL", ";", "}", "// traverses from root to the parent dir to all inodes included by this path are executable", "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. @param user the user @param groups the groups this user belongs to @param path the inode path @param inodeList the list of inodes in the path @return the permission
[ "Gets", "the", "permission", "to", "access", "an", "inode", "path", "given", "a", "user", "and", "its", "groups", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/DefaultPermissionChecker.java#L268-L294
18,480
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/UfsSyncUtils.java
UfsSyncUtils.computeSyncPlan
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) { // Inode is already synced. if (inode.isDirectory() && inode.isPersisted()) { // Both Alluxio and UFS are directories, so sync the children of the directory. syncPlan.setSyncChildren(); } return syncPlan; } // One of the metadata or content is not in sync if (inode.isDirectory() && (containsMountPoint || ufsIsDir)) { // Instead of deleting and then loading metadata to update, try to update directly // - mount points (or paths with mount point descendants) should not be deleted // - directory permissions can be updated without removing the inode if (inode.getParentId() != InodeTree.NO_PARENT) { // Only update the inode if it is not the root directory. The root directory is a special // case, since it is expected to be owned by the process that starts the master, and not // the owner on UFS. syncPlan.setUpdateMetadata(); } syncPlan.setSyncChildren(); return syncPlan; } // One of metadata or content is not in sync and it is a file // The only way for a directory to reach this point, is that the ufs with the same path is not // a directory. That requires a deletion and reload as well. if (!isContentSynced) { // update inode, by deleting and then optionally loading metadata syncPlan.setDelete(); if (ufsExists) { // UFS exists, so load metadata later. syncPlan.setLoadMetadata(); } } else { syncPlan.setUpdateMetadata(); } return syncPlan; }
java
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) { // Inode is already synced. if (inode.isDirectory() && inode.isPersisted()) { // Both Alluxio and UFS are directories, so sync the children of the directory. syncPlan.setSyncChildren(); } return syncPlan; } // One of the metadata or content is not in sync if (inode.isDirectory() && (containsMountPoint || ufsIsDir)) { // Instead of deleting and then loading metadata to update, try to update directly // - mount points (or paths with mount point descendants) should not be deleted // - directory permissions can be updated without removing the inode if (inode.getParentId() != InodeTree.NO_PARENT) { // Only update the inode if it is not the root directory. The root directory is a special // case, since it is expected to be owned by the process that starts the master, and not // the owner on UFS. syncPlan.setUpdateMetadata(); } syncPlan.setSyncChildren(); return syncPlan; } // One of metadata or content is not in sync and it is a file // The only way for a directory to reach this point, is that the ufs with the same path is not // a directory. That requires a deletion and reload as well. if (!isContentSynced) { // update inode, by deleting and then optionally loading metadata syncPlan.setDelete(); if (ufsExists) { // UFS exists, so load metadata later. syncPlan.setLoadMetadata(); } } else { syncPlan.setUpdateMetadata(); } return syncPlan; }
[ "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", ")", "{", "// Inode is already synced.", "if", "(", "inode", ".", "isDirectory", "(", ")", "&&", "inode", ".", "isPersisted", "(", ")", ")", "{", "// Both Alluxio and UFS are directories, so sync the children of the directory.", "syncPlan", ".", "setSyncChildren", "(", ")", ";", "}", "return", "syncPlan", ";", "}", "// One of the metadata or content is not in sync", "if", "(", "inode", ".", "isDirectory", "(", ")", "&&", "(", "containsMountPoint", "||", "ufsIsDir", ")", ")", "{", "// Instead of deleting and then loading metadata to update, try to update directly", "// - mount points (or paths with mount point descendants) should not be deleted", "// - directory permissions can be updated without removing the inode", "if", "(", "inode", ".", "getParentId", "(", ")", "!=", "InodeTree", ".", "NO_PARENT", ")", "{", "// Only update the inode if it is not the root directory. The root directory is a special", "// case, since it is expected to be owned by the process that starts the master, and not", "// the owner on UFS.", "syncPlan", ".", "setUpdateMetadata", "(", ")", ";", "}", "syncPlan", ".", "setSyncChildren", "(", ")", ";", "return", "syncPlan", ";", "}", "// One of metadata or content is not in sync and it is a file", "// The only way for a directory to reach this point, is that the ufs with the same path is not", "// a directory. That requires a deletion and reload as well.", "if", "(", "!", "isContentSynced", ")", "{", "// update inode, by deleting and then optionally loading metadata", "syncPlan", ".", "setDelete", "(", ")", ";", "if", "(", "ufsExists", ")", "{", "// UFS exists, so load metadata later.", "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. @param inode the inode to sync @param ufsFingerprint the ufs fingerprint to check for the sync @param containsMountPoint true if this inode contains a mount point, false otherwise @return a {@link SyncPlan} describing how to sync the inode with the ufs
[ "Given", "an", "inode", "and", "ufs", "status", "returns", "a", "sync", "plan", "describing", "how", "to", "sync", "the", "inode", "with", "the", "ufs", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/UfsSyncUtils.java#L35-L84
18,481
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/UfsSyncUtils.java
UfsSyncUtils.inodeUfsIsContentSynced
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; }
java
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; }
[ "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. @param inode the inode to check for sync @param inodeFingerprint the inode's parsed fingerprint @param ufsFingerprint the ufs fingerprint to check for the sync @return true of the inode is synced with the ufs status
[ "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", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/UfsSyncUtils.java#L95-L106
18,482
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/UfsSyncUtils.java
UfsSyncUtils.inodeUfsIsMetadataSynced
public static boolean inodeUfsIsMetadataSynced(Inode inode, Fingerprint inodeFingerprint, Fingerprint ufsFingerprint) { return inodeFingerprint.isValid() && inodeFingerprint.matchMetadata(ufsFingerprint); }
java
public static boolean inodeUfsIsMetadataSynced(Inode inode, Fingerprint inodeFingerprint, Fingerprint ufsFingerprint) { return inodeFingerprint.isValid() && inodeFingerprint.matchMetadata(ufsFingerprint); }
[ "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. @param inode the inode to check for sync @param inodeFingerprint the inode's parsed fingerprint @param ufsFingerprint the ufs fingerprint to check for the sync @return true of the inode is synced with the ufs status
[ "Returns", "true", "if", "the", "given", "inode", "s", "metadata", "matches", "the", "ufs", "fingerprint", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/UfsSyncUtils.java#L116-L119
18,483
Alluxio/alluxio
core/common/src/main/java/alluxio/util/ThreadUtils.java
ThreadUtils.logAllThreads
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()); }
java
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()); }
[ "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.
[ "Logs", "a", "stack", "trace", "for", "all", "threads", "currently", "running", "in", "the", "JVM", "similar", "to", "jstack", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/ThreadUtils.java#L44-L50
18,484
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java
MasterWorkerInfo.register
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) { // If the storage aliases do not have strictly increasing ordinal value based on the total // ordering, throw an error 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); // validate the number of tiers 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"); } // defensive copy 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) { // This is a re-register of an existing worker. Assume the new block ownership data is more // up-to-date and update the existing block information. LOG.info("re-registering an existing workerId: {}", mId); // Compute the difference between the existing block data, and the new data. removedBlocks = Sets.difference(mBlocks, blocks); } else { removedBlocks = Collections.emptySet(); } // Set the new block information. mBlocks = new HashSet<>(blocks); mIsRegistered = true; return removedBlocks; }
java
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) { // If the storage aliases do not have strictly increasing ordinal value based on the total // ordering, throw an error 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); // validate the number of tiers 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"); } // defensive copy 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) { // This is a re-register of an existing worker. Assume the new block ownership data is more // up-to-date and update the existing block information. LOG.info("re-registering an existing workerId: {}", mId); // Compute the difference between the existing block data, and the new data. removedBlocks = Sets.difference(mBlocks, blocks); } else { removedBlocks = Collections.emptySet(); } // Set the new block information. mBlocks = new HashSet<>(blocks); mIsRegistered = true; return removedBlocks; }
[ "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", ")", "{", "// If the storage aliases do not have strictly increasing ordinal value based on the total", "// ordering, throw an error", "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", ")", ";", "// validate the number of tiers", "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\"", ")", ";", "}", "// defensive copy", "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", ")", "{", "// This is a re-register of an existing worker. Assume the new block ownership data is more", "// up-to-date and update the existing block information.", "LOG", ".", "info", "(", "\"re-registering an existing workerId: {}\"", ",", "mId", ")", ";", "// Compute the difference between the existing block data, and the new data.", "removedBlocks", "=", "Sets", ".", "difference", "(", "mBlocks", ",", "blocks", ")", ";", "}", "else", "{", "removedBlocks", "=", "Collections", ".", "emptySet", "(", ")", ";", "}", "// Set the new block information.", "mBlocks", "=", "new", "HashSet", "<>", "(", "blocks", ")", ";", "mIsRegistered", "=", "true", ";", "return", "removedBlocks", ";", "}" ]
Marks the worker as registered, while updating all of its metadata. @param globalStorageTierAssoc global mapping between storage aliases and ordinal position @param storageTierAliases list of storage tier aliases in order of their position in the hierarchy @param totalBytesOnTiers mapping from storage tier alias to total bytes @param usedBytesOnTiers mapping from storage tier alias to used byes @param blocks set of block ids on this worker @return A Set of blocks removed (or lost) from this worker
[ "Marks", "the", "worker", "as", "registered", "while", "updating", "all", "of", "its", "metadata", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java#L108-L161
18,485
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java
MasterWorkerInfo.addLostStorage
public void addLostStorage(String tierAlias, String dirPath) { List<String> paths = mLostStorage.getOrDefault(tierAlias, new ArrayList<>()); paths.add(dirPath); mLostStorage.put(tierAlias, paths); }
java
public void addLostStorage(String tierAlias, String dirPath) { List<String> paths = mLostStorage.getOrDefault(tierAlias, new ArrayList<>()); paths.add(dirPath); mLostStorage.put(tierAlias, paths); }
[ "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. @param tierAlias the tier alias @param dirPath the lost storage path
[ "Adds", "a", "new", "worker", "lost", "storage", "path", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java#L188-L192
18,486
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java
MasterWorkerInfo.addLostStorage
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); } }
java
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); } }
[ "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. @param lostStorage the lost storage to add
[ "Adds", "new", "worker", "lost", "storage", "paths", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java#L199-L205
18,487
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java
MasterWorkerInfo.generateWorkerInfo
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; }
java
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; }
[ "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. @param fieldRange the client selected fields @param isLiveWorker the worker is live or not @return generated worker information
[ "Gets", "the", "selected", "field", "information", "for", "this", "worker", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java#L214-L257
18,488
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java
MasterWorkerInfo.updateToRemovedBlock
public void updateToRemovedBlock(boolean add, long blockId) { if (add) { if (mBlocks.contains(blockId)) { mToRemoveBlocks.add(blockId); } } else { mToRemoveBlocks.remove(blockId); } }
java
public void updateToRemovedBlock(boolean add, long blockId) { if (add) { if (mBlocks.contains(blockId)) { mToRemoveBlocks.add(blockId); } } else { mToRemoveBlocks.remove(blockId); } }
[ "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. @param add true if to add, to remove otherwise @param blockId the id of the block to be added or removed
[ "Adds", "or", "removes", "a", "block", "from", "the", "to", "-", "be", "-", "removed", "blocks", "set", "of", "the", "worker", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java#L397-L405
18,489
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java
MasterWorkerInfo.updateCapacityBytes
public void updateCapacityBytes(Map<String, Long> capacityBytesOnTiers) { mCapacityBytes = 0; mTotalBytesOnTiers = capacityBytesOnTiers; for (long t : mTotalBytesOnTiers.values()) { mCapacityBytes += t; } }
java
public void updateCapacityBytes(Map<String, Long> capacityBytesOnTiers) { mCapacityBytes = 0; mTotalBytesOnTiers = capacityBytesOnTiers; for (long t : mTotalBytesOnTiers.values()) { mCapacityBytes += t; } }
[ "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. @param capacityBytesOnTiers used bytes on each storage tier
[ "Sets", "the", "capacity", "of", "the", "worker", "in", "bytes", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java#L412-L418
18,490
Alluxio/alluxio
core/common/src/main/java/alluxio/cli/AbstractShell.java
AbstractShell.run
public int run(String... argv) { if (argv.length == 0) { printUsage(); return -1; } // Sanity check on the number of arguments String cmd = argv[0]; Command command = mCommands.get(cmd); if (command == null) { String[] replacementCmd = getReplacementCmd(cmd); if (replacementCmd == null) { // Unknown command (we didn't find the cmd in our dict) System.err.println(String.format("%s is an unknown command.", cmd)); printUsage(); return -1; } else { // Handle command alias 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; } // Handle the command try { return command.run(cmdline); } catch (Exception e) { System.out.println(e.getMessage()); LOG.error("Error running " + StringUtils.join(argv, " "), e); return -1; } }
java
public int run(String... argv) { if (argv.length == 0) { printUsage(); return -1; } // Sanity check on the number of arguments String cmd = argv[0]; Command command = mCommands.get(cmd); if (command == null) { String[] replacementCmd = getReplacementCmd(cmd); if (replacementCmd == null) { // Unknown command (we didn't find the cmd in our dict) System.err.println(String.format("%s is an unknown command.", cmd)); printUsage(); return -1; } else { // Handle command alias 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; } // Handle the command try { return command.run(cmdline); } catch (Exception e) { System.out.println(e.getMessage()); LOG.error("Error running " + StringUtils.join(argv, " "), e); return -1; } }
[ "public", "int", "run", "(", "String", "...", "argv", ")", "{", "if", "(", "argv", ".", "length", "==", "0", ")", "{", "printUsage", "(", ")", ";", "return", "-", "1", ";", "}", "// Sanity check on the number of arguments", "String", "cmd", "=", "argv", "[", "0", "]", ";", "Command", "command", "=", "mCommands", ".", "get", "(", "cmd", ")", ";", "if", "(", "command", "==", "null", ")", "{", "String", "[", "]", "replacementCmd", "=", "getReplacementCmd", "(", "cmd", ")", ";", "if", "(", "replacementCmd", "==", "null", ")", "{", "// Unknown command (we didn't find the cmd in our dict)", "System", ".", "err", ".", "println", "(", "String", ".", "format", "(", "\"%s is an unknown command.\"", ",", "cmd", ")", ")", ";", "printUsage", "(", ")", ";", "return", "-", "1", ";", "}", "else", "{", "// Handle command alias", "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", ";", "}", "// Handle the command", "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. @param argv [] Array of arguments given by the user's input from the terminal @return 0 if command is successful, -1 if an error occurred
[ "Handles", "the", "specified", "shell", "command", "request", "displaying", "usage", "if", "the", "command", "format", "is", "invalid", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/cli/AbstractShell.java#L69-L120
18,491
Alluxio/alluxio
core/common/src/main/java/alluxio/cli/AbstractShell.java
AbstractShell.getReplacementCmd
@Nullable private String[] getReplacementCmd(String cmd) { if (mCommandAlias == null || !mCommandAlias.containsKey(cmd)) { return null; } return mCommandAlias.get(cmd); }
java
@Nullable private String[] getReplacementCmd(String cmd) { if (mCommandAlias == null || !mCommandAlias.containsKey(cmd)) { return null; } return mCommandAlias.get(cmd); }
[ "@", "Nullable", "private", "String", "[", "]", "getReplacementCmd", "(", "String", "cmd", ")", "{", "if", "(", "mCommandAlias", "==", "null", "||", "!", "mCommandAlias", ".", "containsKey", "(", "cmd", ")", ")", "{", "return", "null", ";", "}", "return", "mCommandAlias", ".", "get", "(", "cmd", ")", ";", "}" ]
Gets the replacement command for alias. @param cmd the name of the command @return replacement command if cmd is an alias
[ "Gets", "the", "replacement", "command", "for", "alias", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/cli/AbstractShell.java#L139-L145
18,492
Alluxio/alluxio
core/common/src/main/java/alluxio/cli/AbstractShell.java
AbstractShell.printUsage
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() + "]"); } }
java
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() + "]"); } }
[ "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.
[ "Prints", "usage", "for", "all", "commands", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/cli/AbstractShell.java#L162-L168
18,493
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockHeartbeatReporter.java
BlockHeartbeatReporter.generateReport
public BlockHeartbeatReport generateReport() { synchronized (mLock) { BlockHeartbeatReport report = new BlockHeartbeatReport(mAddedBlocks, mRemovedBlocks, mLostStorage); // Clear added and removed blocks mAddedBlocks.clear(); mRemovedBlocks.clear(); mLostStorage.clear(); return report; } }
java
public BlockHeartbeatReport generateReport() { synchronized (mLock) { BlockHeartbeatReport report = new BlockHeartbeatReport(mAddedBlocks, mRemovedBlocks, mLostStorage); // Clear added and removed blocks mAddedBlocks.clear(); mRemovedBlocks.clear(); mLostStorage.clear(); return report; } }
[ "public", "BlockHeartbeatReport", "generateReport", "(", ")", "{", "synchronized", "(", "mLock", ")", "{", "BlockHeartbeatReport", "report", "=", "new", "BlockHeartbeatReport", "(", "mAddedBlocks", ",", "mRemovedBlocks", ",", "mLostStorage", ")", ";", "// Clear added and removed blocks", "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. @return the block store delta report for the last heartbeat period
[ "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", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockHeartbeatReporter.java#L63-L73
18,494
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockHeartbeatReporter.java
BlockHeartbeatReporter.addBlockToAddedBlocks
private void addBlockToAddedBlocks(long blockId, String tierAlias) { if (mAddedBlocks.containsKey(tierAlias)) { mAddedBlocks.get(tierAlias).add(blockId); } else { mAddedBlocks.put(tierAlias, Lists.newArrayList(blockId)); } }
java
private void addBlockToAddedBlocks(long blockId, String tierAlias) { if (mAddedBlocks.containsKey(tierAlias)) { mAddedBlocks.get(tierAlias).add(blockId); } else { mAddedBlocks.put(tierAlias, Lists.newArrayList(blockId)); } }
[ "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. @param blockId the id of the block to add @param tierAlias alias of the storage tier containing the block
[ "Adds", "a", "block", "to", "the", "list", "of", "added", "blocks", "in", "this", "heartbeat", "period", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockHeartbeatReporter.java#L144-L150
18,495
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockHeartbeatReporter.java
BlockHeartbeatReporter.removeBlockFromAddedBlocks
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(); } // exit the loop when already find and remove block id from mAddedBlocks break; } } }
java
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(); } // exit the loop when already find and remove block id from mAddedBlocks break; } } }
[ "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", "(", ")", ";", "}", "// exit the loop when already find and remove block id from mAddedBlocks", "break", ";", "}", "}", "}" ]
Removes the block from the added blocks map, if it exists. @param blockId the block to remove
[ "Removes", "the", "block", "from", "the", "added", "blocks", "map", "if", "it", "exists", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockHeartbeatReporter.java#L157-L171
18,496
Alluxio/alluxio
integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java
AlluxioFuseFileSystem.flush
@Override 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; }
java
@Override 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; }
[ "@", "Override", "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. Called on explicit sync() operation or at close(). @param path The path on the FS of the file to close @param fi FileInfo data struct kept by FUSE @return 0 on success, a negative value on error
[ "Flushes", "cached", "data", "on", "Alluxio", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java#L282-L302
18,497
Alluxio/alluxio
integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java
AlluxioFuseFileSystem.getattr
@Override 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()) { // Always block waiting for file to be completed except when the file is writing // We do not want to block the writing process 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); // Sets block number to fulfill du command needs // `st_blksize` is ignored in `getattr` according to // https://github.com/libfuse/libfuse/blob/d4a7ba44b022e3b63fc215374d87ed9e930d9974/include/fuse.h#L302 // According to http://man7.org/linux/man-pages/man2/stat.2.html, // `st_blocks` is the number of 512B blocks allocated stat.st_blocks.set((int) Math.ceil((double) size / 512)); final long ctime_sec = status.getLastModificationTimeMs() / 1000; // Keeps only the "residual" nanoseconds not caputred in citme_sec 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) { // Translate the file owner/group to unix uid/gid // Show as uid==-1 (nobody) if owner does not exist in unix // Show as gid==-1 (nogroup) if group does not exist in unix 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; }
java
@Override 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()) { // Always block waiting for file to be completed except when the file is writing // We do not want to block the writing process 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); // Sets block number to fulfill du command needs // `st_blksize` is ignored in `getattr` according to // https://github.com/libfuse/libfuse/blob/d4a7ba44b022e3b63fc215374d87ed9e930d9974/include/fuse.h#L302 // According to http://man7.org/linux/man-pages/man2/stat.2.html, // `st_blocks` is the number of 512B blocks allocated stat.st_blocks.set((int) Math.ceil((double) size / 512)); final long ctime_sec = status.getLastModificationTimeMs() / 1000; // Keeps only the "residual" nanoseconds not caputred in citme_sec 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) { // Translate the file owner/group to unix uid/gid // Show as uid==-1 (nobody) if owner does not exist in unix // Show as gid==-1 (nogroup) if group does not exist in unix 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; }
[ "@", "Override", "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", "(", ")", ")", "{", "// Always block waiting for file to be completed except when the file is writing", "// We do not want to block the writing process", "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", ")", ";", "// Sets block number to fulfill du command needs", "// `st_blksize` is ignored in `getattr` according to", "// https://github.com/libfuse/libfuse/blob/d4a7ba44b022e3b63fc215374d87ed9e930d9974/include/fuse.h#L302", "// According to http://man7.org/linux/man-pages/man2/stat.2.html,", "// `st_blocks` is the number of 512B blocks allocated", "stat", ".", "st_blocks", ".", "set", "(", "(", "int", ")", "Math", ".", "ceil", "(", "(", "double", ")", "size", "/", "512", ")", ")", ";", "final", "long", "ctime_sec", "=", "status", ".", "getLastModificationTimeMs", "(", ")", "/", "1000", ";", "// Keeps only the \"residual\" nanoseconds not caputred in citme_sec", "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", ")", "{", "// Translate the file owner/group to unix uid/gid", "// Show as uid==-1 (nobody) if owner does not exist in unix", "// Show as gid==-1 (nogroup) if group does not exist in unix", "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. @param path The path on the FS of the file @param stat FUSE data structure to fill with file attrs @return 0 on success, negative value on error
[ "Retrieves", "file", "attributes", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java#L311-L372
18,498
Alluxio/alluxio
integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java
AlluxioFuseFileSystem.open
@Override public int open(String path, FuseFileInfo fi) { final AlluxioURI uri = mPathResolverCache.getUnchecked(path); // (see {@code man 2 open} for the structure of the flags bitfield) // File creation flags are the last two bits of flags 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); // Assuming I will never wrap around (2^64 open files are quite a lot anyway) 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; }
java
@Override public int open(String path, FuseFileInfo fi) { final AlluxioURI uri = mPathResolverCache.getUnchecked(path); // (see {@code man 2 open} for the structure of the flags bitfield) // File creation flags are the last two bits of flags 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); // Assuming I will never wrap around (2^64 open files are quite a lot anyway) 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; }
[ "@", "Override", "public", "int", "open", "(", "String", "path", ",", "FuseFileInfo", "fi", ")", "{", "final", "AlluxioURI", "uri", "=", "mPathResolverCache", ".", "getUnchecked", "(", "path", ")", ";", "// (see {@code man 2 open} for the structure of the flags bitfield)", "// File creation flags are the last two bits of flags", "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", ")", ";", "// Assuming I will never wrap around (2^64 open files are quite a lot anyway)", "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. Note that the opening an existing file would fail, because of Alluxio's write-once semantics. @param path the FS path of the file to open @param fi FileInfo data structure kept by FUSE @return 0 on success, a negative value on error
[ "Opens", "an", "existing", "file", "for", "reading", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java#L418-L459
18,499
Alluxio/alluxio
integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java
AlluxioFuseFileSystem.rename
@Override 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; }
java
@Override 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; }
[ "@", "Override", "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. @param oldPath the source path in the FS @param newPath the destination path in the FS @return 0 on success, a negative value on error
[ "Renames", "a", "path", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java#L595-L621