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,700
Alluxio/alluxio
core/client/fs/src/main/java/alluxio/client/block/AlluxioBlockStore.java
AlluxioBlockStore.getOutStream
public BlockOutStream getOutStream(long blockId, long blockSize, WorkerNetAddress address, OutStreamOptions options) throws IOException { if (blockSize == -1) { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { blockSize = blockMasterClientResource.get().getBlockInfo(blockId).getLength(); } } // No specified location to write to. if (address == null) { throw new ResourceExhaustedException(ExceptionMessage.NO_SPACE_FOR_BLOCK_ON_WORKER .getMessage(FormatUtils.getSizeFromBytes(blockSize))); } LOG.debug("Create block outstream for {} of block size {} at address {}, using options: {}", blockId, blockSize, address, options); return BlockOutStream.create(mContext, blockId, blockSize, address, options); }
java
public BlockOutStream getOutStream(long blockId, long blockSize, WorkerNetAddress address, OutStreamOptions options) throws IOException { if (blockSize == -1) { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { blockSize = blockMasterClientResource.get().getBlockInfo(blockId).getLength(); } } // No specified location to write to. if (address == null) { throw new ResourceExhaustedException(ExceptionMessage.NO_SPACE_FOR_BLOCK_ON_WORKER .getMessage(FormatUtils.getSizeFromBytes(blockSize))); } LOG.debug("Create block outstream for {} of block size {} at address {}, using options: {}", blockId, blockSize, address, options); return BlockOutStream.create(mContext, blockId, blockSize, address, options); }
[ "public", "BlockOutStream", "getOutStream", "(", "long", "blockId", ",", "long", "blockSize", ",", "WorkerNetAddress", "address", ",", "OutStreamOptions", "options", ")", "throws", "IOException", "{", "if", "(", "blockSize", "==", "-", "1", ")", "{", "try", "(", "CloseableResource", "<", "BlockMasterClient", ">", "blockMasterClientResource", "=", "mContext", ".", "acquireBlockMasterClientResource", "(", ")", ")", "{", "blockSize", "=", "blockMasterClientResource", ".", "get", "(", ")", ".", "getBlockInfo", "(", "blockId", ")", ".", "getLength", "(", ")", ";", "}", "}", "// No specified location to write to.", "if", "(", "address", "==", "null", ")", "{", "throw", "new", "ResourceExhaustedException", "(", "ExceptionMessage", ".", "NO_SPACE_FOR_BLOCK_ON_WORKER", ".", "getMessage", "(", "FormatUtils", ".", "getSizeFromBytes", "(", "blockSize", ")", ")", ")", ";", "}", "LOG", ".", "debug", "(", "\"Create block outstream for {} of block size {} at address {}, using options: {}\"", ",", "blockId", ",", "blockSize", ",", "address", ",", "options", ")", ";", "return", "BlockOutStream", ".", "create", "(", "mContext", ",", "blockId", ",", "blockSize", ",", "address", ",", "options", ")", ";", "}" ]
Gets a stream to write data to a block. The stream can only be backed by Alluxio storage. @param blockId the block to write @param blockSize the standard block size to write, or -1 if the block already exists (and this stream is just storing the block in Alluxio again) @param address the address of the worker to write the block to, fails if the worker cannot serve the request @param options the output stream options @return an {@link BlockOutStream} which can be used to write data to the block in a streaming fashion
[ "Gets", "a", "stream", "to", "write", "data", "to", "a", "block", ".", "The", "stream", "can", "only", "be", "backed", "by", "Alluxio", "storage", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/fs/src/main/java/alluxio/client/block/AlluxioBlockStore.java#L275-L291
18,701
Alluxio/alluxio
core/client/fs/src/main/java/alluxio/client/block/AlluxioBlockStore.java
AlluxioBlockStore.getOutStream
public BlockOutStream getOutStream(long blockId, long blockSize, OutStreamOptions options) throws IOException { WorkerNetAddress address; BlockLocationPolicy locationPolicy = Preconditions.checkNotNull(options.getLocationPolicy(), PreconditionMessage.BLOCK_WRITE_LOCATION_POLICY_UNSPECIFIED); GetWorkerOptions workerOptions = GetWorkerOptions.defaults() .setBlockInfo(new BlockInfo().setBlockId(blockId).setLength(blockSize)) .setBlockWorkerInfos(new ArrayList<>(getEligibleWorkers())); // The number of initial copies depends on the write type: if ASYNC_THROUGH, it is the property // "alluxio.user.file.replication.durable" before data has been persisted; otherwise // "alluxio.user.file.replication.min" int initialReplicas = (options.getWriteType() == WriteType.ASYNC_THROUGH && options.getReplicationDurable() > options.getReplicationMin()) ? options.getReplicationDurable() : options.getReplicationMin(); if (initialReplicas <= 1) { address = locationPolicy.getWorker(workerOptions); if (address == null) { throw new UnavailableException( ExceptionMessage.NO_SPACE_FOR_BLOCK_ON_WORKER.getMessage(blockSize)); } return getOutStream(blockId, blockSize, address, options); } // Group different block workers by their hostnames Map<String, Set<BlockWorkerInfo>> blockWorkersByHost = new HashMap<>(); for (BlockWorkerInfo blockWorker : workerOptions.getBlockWorkerInfos()) { String hostName = blockWorker.getNetAddress().getHost(); if (blockWorkersByHost.containsKey(hostName)) { blockWorkersByHost.get(hostName).add(blockWorker); } else { blockWorkersByHost.put(hostName, com.google.common.collect.Sets.newHashSet(blockWorker)); } } // Select N workers on different hosts where N is the value of initialReplicas for this block List<WorkerNetAddress> workerAddressList = new ArrayList<>(); List<BlockWorkerInfo> updatedInfos = Lists.newArrayList(workerOptions.getBlockWorkerInfos()); for (int i = 0; i < initialReplicas; i++) { address = locationPolicy.getWorker(workerOptions); if (address == null) { break; } workerAddressList.add(address); updatedInfos.removeAll(blockWorkersByHost.get(address.getHost())); workerOptions.setBlockWorkerInfos(updatedInfos); } if (workerAddressList.size() < initialReplicas) { throw new alluxio.exception.status.ResourceExhaustedException(String.format( "Not enough workers for replications, %d workers selected but %d required", workerAddressList.size(), initialReplicas)); } return BlockOutStream .createReplicatedBlockOutStream(mContext, blockId, blockSize, workerAddressList, options); }
java
public BlockOutStream getOutStream(long blockId, long blockSize, OutStreamOptions options) throws IOException { WorkerNetAddress address; BlockLocationPolicy locationPolicy = Preconditions.checkNotNull(options.getLocationPolicy(), PreconditionMessage.BLOCK_WRITE_LOCATION_POLICY_UNSPECIFIED); GetWorkerOptions workerOptions = GetWorkerOptions.defaults() .setBlockInfo(new BlockInfo().setBlockId(blockId).setLength(blockSize)) .setBlockWorkerInfos(new ArrayList<>(getEligibleWorkers())); // The number of initial copies depends on the write type: if ASYNC_THROUGH, it is the property // "alluxio.user.file.replication.durable" before data has been persisted; otherwise // "alluxio.user.file.replication.min" int initialReplicas = (options.getWriteType() == WriteType.ASYNC_THROUGH && options.getReplicationDurable() > options.getReplicationMin()) ? options.getReplicationDurable() : options.getReplicationMin(); if (initialReplicas <= 1) { address = locationPolicy.getWorker(workerOptions); if (address == null) { throw new UnavailableException( ExceptionMessage.NO_SPACE_FOR_BLOCK_ON_WORKER.getMessage(blockSize)); } return getOutStream(blockId, blockSize, address, options); } // Group different block workers by their hostnames Map<String, Set<BlockWorkerInfo>> blockWorkersByHost = new HashMap<>(); for (BlockWorkerInfo blockWorker : workerOptions.getBlockWorkerInfos()) { String hostName = blockWorker.getNetAddress().getHost(); if (blockWorkersByHost.containsKey(hostName)) { blockWorkersByHost.get(hostName).add(blockWorker); } else { blockWorkersByHost.put(hostName, com.google.common.collect.Sets.newHashSet(blockWorker)); } } // Select N workers on different hosts where N is the value of initialReplicas for this block List<WorkerNetAddress> workerAddressList = new ArrayList<>(); List<BlockWorkerInfo> updatedInfos = Lists.newArrayList(workerOptions.getBlockWorkerInfos()); for (int i = 0; i < initialReplicas; i++) { address = locationPolicy.getWorker(workerOptions); if (address == null) { break; } workerAddressList.add(address); updatedInfos.removeAll(blockWorkersByHost.get(address.getHost())); workerOptions.setBlockWorkerInfos(updatedInfos); } if (workerAddressList.size() < initialReplicas) { throw new alluxio.exception.status.ResourceExhaustedException(String.format( "Not enough workers for replications, %d workers selected but %d required", workerAddressList.size(), initialReplicas)); } return BlockOutStream .createReplicatedBlockOutStream(mContext, blockId, blockSize, workerAddressList, options); }
[ "public", "BlockOutStream", "getOutStream", "(", "long", "blockId", ",", "long", "blockSize", ",", "OutStreamOptions", "options", ")", "throws", "IOException", "{", "WorkerNetAddress", "address", ";", "BlockLocationPolicy", "locationPolicy", "=", "Preconditions", ".", "checkNotNull", "(", "options", ".", "getLocationPolicy", "(", ")", ",", "PreconditionMessage", ".", "BLOCK_WRITE_LOCATION_POLICY_UNSPECIFIED", ")", ";", "GetWorkerOptions", "workerOptions", "=", "GetWorkerOptions", ".", "defaults", "(", ")", ".", "setBlockInfo", "(", "new", "BlockInfo", "(", ")", ".", "setBlockId", "(", "blockId", ")", ".", "setLength", "(", "blockSize", ")", ")", ".", "setBlockWorkerInfos", "(", "new", "ArrayList", "<>", "(", "getEligibleWorkers", "(", ")", ")", ")", ";", "// The number of initial copies depends on the write type: if ASYNC_THROUGH, it is the property", "// \"alluxio.user.file.replication.durable\" before data has been persisted; otherwise", "// \"alluxio.user.file.replication.min\"", "int", "initialReplicas", "=", "(", "options", ".", "getWriteType", "(", ")", "==", "WriteType", ".", "ASYNC_THROUGH", "&&", "options", ".", "getReplicationDurable", "(", ")", ">", "options", ".", "getReplicationMin", "(", ")", ")", "?", "options", ".", "getReplicationDurable", "(", ")", ":", "options", ".", "getReplicationMin", "(", ")", ";", "if", "(", "initialReplicas", "<=", "1", ")", "{", "address", "=", "locationPolicy", ".", "getWorker", "(", "workerOptions", ")", ";", "if", "(", "address", "==", "null", ")", "{", "throw", "new", "UnavailableException", "(", "ExceptionMessage", ".", "NO_SPACE_FOR_BLOCK_ON_WORKER", ".", "getMessage", "(", "blockSize", ")", ")", ";", "}", "return", "getOutStream", "(", "blockId", ",", "blockSize", ",", "address", ",", "options", ")", ";", "}", "// Group different block workers by their hostnames", "Map", "<", "String", ",", "Set", "<", "BlockWorkerInfo", ">", ">", "blockWorkersByHost", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "BlockWorkerInfo", "blockWorker", ":", "workerOptions", ".", "getBlockWorkerInfos", "(", ")", ")", "{", "String", "hostName", "=", "blockWorker", ".", "getNetAddress", "(", ")", ".", "getHost", "(", ")", ";", "if", "(", "blockWorkersByHost", ".", "containsKey", "(", "hostName", ")", ")", "{", "blockWorkersByHost", ".", "get", "(", "hostName", ")", ".", "add", "(", "blockWorker", ")", ";", "}", "else", "{", "blockWorkersByHost", ".", "put", "(", "hostName", ",", "com", ".", "google", ".", "common", ".", "collect", ".", "Sets", ".", "newHashSet", "(", "blockWorker", ")", ")", ";", "}", "}", "// Select N workers on different hosts where N is the value of initialReplicas for this block", "List", "<", "WorkerNetAddress", ">", "workerAddressList", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "BlockWorkerInfo", ">", "updatedInfos", "=", "Lists", ".", "newArrayList", "(", "workerOptions", ".", "getBlockWorkerInfos", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "initialReplicas", ";", "i", "++", ")", "{", "address", "=", "locationPolicy", ".", "getWorker", "(", "workerOptions", ")", ";", "if", "(", "address", "==", "null", ")", "{", "break", ";", "}", "workerAddressList", ".", "add", "(", "address", ")", ";", "updatedInfos", ".", "removeAll", "(", "blockWorkersByHost", ".", "get", "(", "address", ".", "getHost", "(", ")", ")", ")", ";", "workerOptions", ".", "setBlockWorkerInfos", "(", "updatedInfos", ")", ";", "}", "if", "(", "workerAddressList", ".", "size", "(", ")", "<", "initialReplicas", ")", "{", "throw", "new", "alluxio", ".", "exception", ".", "status", ".", "ResourceExhaustedException", "(", "String", ".", "format", "(", "\"Not enough workers for replications, %d workers selected but %d required\"", ",", "workerAddressList", ".", "size", "(", ")", ",", "initialReplicas", ")", ")", ";", "}", "return", "BlockOutStream", ".", "createReplicatedBlockOutStream", "(", "mContext", ",", "blockId", ",", "blockSize", ",", "workerAddressList", ",", "options", ")", ";", "}" ]
Gets a stream to write data to a block based on the options. The stream can only be backed by Alluxio storage. @param blockId the block to write @param blockSize the standard block size to write, or -1 if the block already exists (and this stream is just storing the block in Alluxio again) @param options the output stream option @return a {@link BlockOutStream} which can be used to write data to the block in a streaming fashion
[ "Gets", "a", "stream", "to", "write", "data", "to", "a", "block", "based", "on", "the", "options", ".", "The", "stream", "can", "only", "be", "backed", "by", "Alluxio", "storage", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/fs/src/main/java/alluxio/client/block/AlluxioBlockStore.java#L304-L358
18,702
Alluxio/alluxio
core/client/fs/src/main/java/alluxio/client/block/AlluxioBlockStore.java
AlluxioBlockStore.getCapacityBytes
public long getCapacityBytes() throws IOException { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { return blockMasterClientResource.get().getCapacityBytes(); } }
java
public long getCapacityBytes() throws IOException { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { return blockMasterClientResource.get().getCapacityBytes(); } }
[ "public", "long", "getCapacityBytes", "(", ")", "throws", "IOException", "{", "try", "(", "CloseableResource", "<", "BlockMasterClient", ">", "blockMasterClientResource", "=", "mContext", ".", "acquireBlockMasterClientResource", "(", ")", ")", "{", "return", "blockMasterClientResource", ".", "get", "(", ")", ".", "getCapacityBytes", "(", ")", ";", "}", "}" ]
Gets the total capacity of Alluxio's BlockStore. @return the capacity in bytes
[ "Gets", "the", "total", "capacity", "of", "Alluxio", "s", "BlockStore", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/fs/src/main/java/alluxio/client/block/AlluxioBlockStore.java#L365-L370
18,703
Alluxio/alluxio
core/client/fs/src/main/java/alluxio/client/block/AlluxioBlockStore.java
AlluxioBlockStore.getUsedBytes
public long getUsedBytes() throws IOException { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { return blockMasterClientResource.get().getUsedBytes(); } }
java
public long getUsedBytes() throws IOException { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { return blockMasterClientResource.get().getUsedBytes(); } }
[ "public", "long", "getUsedBytes", "(", ")", "throws", "IOException", "{", "try", "(", "CloseableResource", "<", "BlockMasterClient", ">", "blockMasterClientResource", "=", "mContext", ".", "acquireBlockMasterClientResource", "(", ")", ")", "{", "return", "blockMasterClientResource", ".", "get", "(", ")", ".", "getUsedBytes", "(", ")", ";", "}", "}" ]
Gets the used bytes of Alluxio's BlockStore. @return the used bytes of Alluxio's BlockStore
[ "Gets", "the", "used", "bytes", "of", "Alluxio", "s", "BlockStore", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/fs/src/main/java/alluxio/client/block/AlluxioBlockStore.java#L377-L382
18,704
Alluxio/alluxio
core/client/hdfs/src/main/java/alluxio/hadoop/HadoopUtils.java
HadoopUtils.addSwiftCredentials
public static void addSwiftCredentials(Configuration configuration) { PropertyKey[] propertyNames = {PropertyKey.SWIFT_API_KEY, PropertyKey.SWIFT_TENANT_KEY, PropertyKey.SWIFT_USER_KEY, PropertyKey.SWIFT_AUTH_URL_KEY, PropertyKey.SWIFT_AUTH_METHOD_KEY, PropertyKey.SWIFT_PASSWORD_KEY, PropertyKey.SWIFT_SIMULATION, PropertyKey.SWIFT_REGION_KEY}; setConfigurationFromSystemProperties(configuration, propertyNames); }
java
public static void addSwiftCredentials(Configuration configuration) { PropertyKey[] propertyNames = {PropertyKey.SWIFT_API_KEY, PropertyKey.SWIFT_TENANT_KEY, PropertyKey.SWIFT_USER_KEY, PropertyKey.SWIFT_AUTH_URL_KEY, PropertyKey.SWIFT_AUTH_METHOD_KEY, PropertyKey.SWIFT_PASSWORD_KEY, PropertyKey.SWIFT_SIMULATION, PropertyKey.SWIFT_REGION_KEY}; setConfigurationFromSystemProperties(configuration, propertyNames); }
[ "public", "static", "void", "addSwiftCredentials", "(", "Configuration", "configuration", ")", "{", "PropertyKey", "[", "]", "propertyNames", "=", "{", "PropertyKey", ".", "SWIFT_API_KEY", ",", "PropertyKey", ".", "SWIFT_TENANT_KEY", ",", "PropertyKey", ".", "SWIFT_USER_KEY", ",", "PropertyKey", ".", "SWIFT_AUTH_URL_KEY", ",", "PropertyKey", ".", "SWIFT_AUTH_METHOD_KEY", ",", "PropertyKey", ".", "SWIFT_PASSWORD_KEY", ",", "PropertyKey", ".", "SWIFT_SIMULATION", ",", "PropertyKey", ".", "SWIFT_REGION_KEY", "}", ";", "setConfigurationFromSystemProperties", "(", "configuration", ",", "propertyNames", ")", ";", "}" ]
Adds Swift keys to the given Hadoop Configuration object if the user has specified them using System properties, and they're not already set. This function is duplicated from {@code alluxio.underfs.hdfs.HdfsUnderFileSystemUtils}, to prevent the module alluxio-core-client-hdfs from depending on the module alluxio-underfs. @param configuration Hadoop configuration
[ "Adds", "Swift", "keys", "to", "the", "given", "Hadoop", "Configuration", "object", "if", "the", "user", "has", "specified", "them", "using", "System", "properties", "and", "they", "re", "not", "already", "set", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/hdfs/src/main/java/alluxio/hadoop/HadoopUtils.java#L148-L154
18,705
Alluxio/alluxio
core/client/hdfs/src/main/java/alluxio/hadoop/HadoopUtils.java
HadoopUtils.setConfigurationFromSystemProperties
private static void setConfigurationFromSystemProperties(Configuration configuration, PropertyKey[] propertyNames) { for (PropertyKey propertyName : propertyNames) { setConfigurationFromSystemProperty(configuration, propertyName.toString()); } }
java
private static void setConfigurationFromSystemProperties(Configuration configuration, PropertyKey[] propertyNames) { for (PropertyKey propertyName : propertyNames) { setConfigurationFromSystemProperty(configuration, propertyName.toString()); } }
[ "private", "static", "void", "setConfigurationFromSystemProperties", "(", "Configuration", "configuration", ",", "PropertyKey", "[", "]", "propertyNames", ")", "{", "for", "(", "PropertyKey", "propertyName", ":", "propertyNames", ")", "{", "setConfigurationFromSystemProperty", "(", "configuration", ",", "propertyName", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Set the System properties into Hadoop configuration. This method won't override existing properties even if they are set as System properties. @param configuration Hadoop configuration @param propertyNames the properties to be set
[ "Set", "the", "System", "properties", "into", "Hadoop", "configuration", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/hdfs/src/main/java/alluxio/hadoop/HadoopUtils.java#L164-L169
18,706
Alluxio/alluxio
core/client/hdfs/src/main/java/alluxio/hadoop/HadoopUtils.java
HadoopUtils.setConfigurationFromSystemProperty
private static void setConfigurationFromSystemProperty(Configuration configuration, String propertyName) { String propertyValue = System.getProperty(propertyName); if (propertyValue != null && configuration.get(propertyName) == null) { configuration.set(propertyName, propertyValue); } }
java
private static void setConfigurationFromSystemProperty(Configuration configuration, String propertyName) { String propertyValue = System.getProperty(propertyName); if (propertyValue != null && configuration.get(propertyName) == null) { configuration.set(propertyName, propertyValue); } }
[ "private", "static", "void", "setConfigurationFromSystemProperty", "(", "Configuration", "configuration", ",", "String", "propertyName", ")", "{", "String", "propertyValue", "=", "System", ".", "getProperty", "(", "propertyName", ")", ";", "if", "(", "propertyValue", "!=", "null", "&&", "configuration", ".", "get", "(", "propertyName", ")", "==", "null", ")", "{", "configuration", ".", "set", "(", "propertyName", ",", "propertyValue", ")", ";", "}", "}" ]
Set the System property into Hadoop configuration. This method won't override existing property even if it is set as System property. @param configuration Hadoop configuration @param propertyName the property to be set
[ "Set", "the", "System", "property", "into", "Hadoop", "configuration", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/hdfs/src/main/java/alluxio/hadoop/HadoopUtils.java#L179-L185
18,707
Alluxio/alluxio
core/server/common/src/main/java/alluxio/util/TarUtils.java
TarUtils.writeTarGz
public static void writeTarGz(Path dirPath, OutputStream output) throws IOException, InterruptedException { GzipCompressorOutputStream zipStream = new GzipCompressorOutputStream(output); TarArchiveOutputStream archiveStream = new TarArchiveOutputStream(zipStream); for (Path subPath : Files.walk(dirPath).collect(toList())) { if (Thread.interrupted()) { throw new InterruptedException(); } File file = subPath.toFile(); TarArchiveEntry entry = new TarArchiveEntry(file, dirPath.relativize(subPath).toString()); archiveStream.putArchiveEntry(entry); if (file.isFile()) { try (InputStream fileIn = Files.newInputStream(subPath)) { IOUtils.copy(fileIn, archiveStream); } } archiveStream.closeArchiveEntry(); } archiveStream.finish(); zipStream.finish(); }
java
public static void writeTarGz(Path dirPath, OutputStream output) throws IOException, InterruptedException { GzipCompressorOutputStream zipStream = new GzipCompressorOutputStream(output); TarArchiveOutputStream archiveStream = new TarArchiveOutputStream(zipStream); for (Path subPath : Files.walk(dirPath).collect(toList())) { if (Thread.interrupted()) { throw new InterruptedException(); } File file = subPath.toFile(); TarArchiveEntry entry = new TarArchiveEntry(file, dirPath.relativize(subPath).toString()); archiveStream.putArchiveEntry(entry); if (file.isFile()) { try (InputStream fileIn = Files.newInputStream(subPath)) { IOUtils.copy(fileIn, archiveStream); } } archiveStream.closeArchiveEntry(); } archiveStream.finish(); zipStream.finish(); }
[ "public", "static", "void", "writeTarGz", "(", "Path", "dirPath", ",", "OutputStream", "output", ")", "throws", "IOException", ",", "InterruptedException", "{", "GzipCompressorOutputStream", "zipStream", "=", "new", "GzipCompressorOutputStream", "(", "output", ")", ";", "TarArchiveOutputStream", "archiveStream", "=", "new", "TarArchiveOutputStream", "(", "zipStream", ")", ";", "for", "(", "Path", "subPath", ":", "Files", ".", "walk", "(", "dirPath", ")", ".", "collect", "(", "toList", "(", ")", ")", ")", "{", "if", "(", "Thread", ".", "interrupted", "(", ")", ")", "{", "throw", "new", "InterruptedException", "(", ")", ";", "}", "File", "file", "=", "subPath", ".", "toFile", "(", ")", ";", "TarArchiveEntry", "entry", "=", "new", "TarArchiveEntry", "(", "file", ",", "dirPath", ".", "relativize", "(", "subPath", ")", ".", "toString", "(", ")", ")", ";", "archiveStream", ".", "putArchiveEntry", "(", "entry", ")", ";", "if", "(", "file", ".", "isFile", "(", ")", ")", "{", "try", "(", "InputStream", "fileIn", "=", "Files", ".", "newInputStream", "(", "subPath", ")", ")", "{", "IOUtils", ".", "copy", "(", "fileIn", ",", "archiveStream", ")", ";", "}", "}", "archiveStream", ".", "closeArchiveEntry", "(", ")", ";", "}", "archiveStream", ".", "finish", "(", ")", ";", "zipStream", ".", "finish", "(", ")", ";", "}" ]
Creates a gzipped tar archive from the given path, streaming the data to the give output stream. @param dirPath the path to archive @param output the output stream to write the data to
[ "Creates", "a", "gzipped", "tar", "archive", "from", "the", "given", "path", "streaming", "the", "data", "to", "the", "give", "output", "stream", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/util/TarUtils.java#L42-L62
18,708
Alluxio/alluxio
core/server/common/src/main/java/alluxio/util/TarUtils.java
TarUtils.readTarGz
public static void readTarGz(Path dirPath, InputStream input) throws IOException { InputStream zipStream = new GzipCompressorInputStream(input); TarArchiveInputStream archiveStream = new TarArchiveInputStream(zipStream); TarArchiveEntry entry; while ((entry = (TarArchiveEntry) archiveStream.getNextEntry()) != null) { File outputFile = new File(dirPath.toFile(), entry.getName()); if (entry.isDirectory()) { outputFile.mkdirs(); } else { outputFile.getParentFile().mkdirs(); try (FileOutputStream fileOut = new FileOutputStream(outputFile)) { IOUtils.copy(archiveStream, fileOut); } } } }
java
public static void readTarGz(Path dirPath, InputStream input) throws IOException { InputStream zipStream = new GzipCompressorInputStream(input); TarArchiveInputStream archiveStream = new TarArchiveInputStream(zipStream); TarArchiveEntry entry; while ((entry = (TarArchiveEntry) archiveStream.getNextEntry()) != null) { File outputFile = new File(dirPath.toFile(), entry.getName()); if (entry.isDirectory()) { outputFile.mkdirs(); } else { outputFile.getParentFile().mkdirs(); try (FileOutputStream fileOut = new FileOutputStream(outputFile)) { IOUtils.copy(archiveStream, fileOut); } } } }
[ "public", "static", "void", "readTarGz", "(", "Path", "dirPath", ",", "InputStream", "input", ")", "throws", "IOException", "{", "InputStream", "zipStream", "=", "new", "GzipCompressorInputStream", "(", "input", ")", ";", "TarArchiveInputStream", "archiveStream", "=", "new", "TarArchiveInputStream", "(", "zipStream", ")", ";", "TarArchiveEntry", "entry", ";", "while", "(", "(", "entry", "=", "(", "TarArchiveEntry", ")", "archiveStream", ".", "getNextEntry", "(", ")", ")", "!=", "null", ")", "{", "File", "outputFile", "=", "new", "File", "(", "dirPath", ".", "toFile", "(", ")", ",", "entry", ".", "getName", "(", ")", ")", ";", "if", "(", "entry", ".", "isDirectory", "(", ")", ")", "{", "outputFile", ".", "mkdirs", "(", ")", ";", "}", "else", "{", "outputFile", ".", "getParentFile", "(", ")", ".", "mkdirs", "(", ")", ";", "try", "(", "FileOutputStream", "fileOut", "=", "new", "FileOutputStream", "(", "outputFile", ")", ")", "{", "IOUtils", ".", "copy", "(", "archiveStream", ",", "fileOut", ")", ";", "}", "}", "}", "}" ]
Reads a gzipped tar archive from a stream and writes it to the given path. @param dirPath the path to write the archive to @param input the input stream
[ "Reads", "a", "gzipped", "tar", "archive", "from", "a", "stream", "and", "writes", "it", "to", "the", "given", "path", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/util/TarUtils.java#L70-L85
18,709
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/AlluxioMasterProcess.java
AlluxioMasterProcess.startMasters
protected void startMasters(boolean isLeader) { try { if (isLeader) { if (ServerConfiguration.isSet(PropertyKey.MASTER_JOURNAL_INIT_FROM_BACKUP)) { AlluxioURI backup = new AlluxioURI(ServerConfiguration.get(PropertyKey.MASTER_JOURNAL_INIT_FROM_BACKUP)); if (mJournalSystem.isEmpty()) { initFromBackup(backup); } else { LOG.info("The journal system is not freshly formatted, skipping restoring backup from " + backup); } } mSafeModeManager.notifyPrimaryMasterStarted(); } else { startRejectingServers(); } mRegistry.start(isLeader); LOG.info("All masters started"); } catch (IOException e) { throw new RuntimeException(e); } }
java
protected void startMasters(boolean isLeader) { try { if (isLeader) { if (ServerConfiguration.isSet(PropertyKey.MASTER_JOURNAL_INIT_FROM_BACKUP)) { AlluxioURI backup = new AlluxioURI(ServerConfiguration.get(PropertyKey.MASTER_JOURNAL_INIT_FROM_BACKUP)); if (mJournalSystem.isEmpty()) { initFromBackup(backup); } else { LOG.info("The journal system is not freshly formatted, skipping restoring backup from " + backup); } } mSafeModeManager.notifyPrimaryMasterStarted(); } else { startRejectingServers(); } mRegistry.start(isLeader); LOG.info("All masters started"); } catch (IOException e) { throw new RuntimeException(e); } }
[ "protected", "void", "startMasters", "(", "boolean", "isLeader", ")", "{", "try", "{", "if", "(", "isLeader", ")", "{", "if", "(", "ServerConfiguration", ".", "isSet", "(", "PropertyKey", ".", "MASTER_JOURNAL_INIT_FROM_BACKUP", ")", ")", "{", "AlluxioURI", "backup", "=", "new", "AlluxioURI", "(", "ServerConfiguration", ".", "get", "(", "PropertyKey", ".", "MASTER_JOURNAL_INIT_FROM_BACKUP", ")", ")", ";", "if", "(", "mJournalSystem", ".", "isEmpty", "(", ")", ")", "{", "initFromBackup", "(", "backup", ")", ";", "}", "else", "{", "LOG", ".", "info", "(", "\"The journal system is not freshly formatted, skipping restoring backup from \"", "+", "backup", ")", ";", "}", "}", "mSafeModeManager", ".", "notifyPrimaryMasterStarted", "(", ")", ";", "}", "else", "{", "startRejectingServers", "(", ")", ";", "}", "mRegistry", ".", "start", "(", "isLeader", ")", ";", "LOG", ".", "info", "(", "\"All masters started\"", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Starts all masters, including block master, FileSystem master, and additional masters. @param isLeader if the Master is leader
[ "Starts", "all", "masters", "including", "block", "master", "FileSystem", "master", "and", "additional", "masters", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/AlluxioMasterProcess.java#L184-L206
18,710
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/AlluxioMasterProcess.java
AlluxioMasterProcess.startServingWebServer
protected void startServingWebServer() { stopRejectingWebServer(); mWebServer = new MasterWebServer(ServiceType.MASTER_WEB.getServiceName(), mWebBindAddress, this); // reset master web port // Add the metrics servlet to the web server. mWebServer.addHandler(mMetricsServlet.getHandler()); // Add the prometheus metrics servlet to the web server. mWebServer.addHandler(mPMetricsServlet.getHandler()); // start web ui mWebServer.start(); }
java
protected void startServingWebServer() { stopRejectingWebServer(); mWebServer = new MasterWebServer(ServiceType.MASTER_WEB.getServiceName(), mWebBindAddress, this); // reset master web port // Add the metrics servlet to the web server. mWebServer.addHandler(mMetricsServlet.getHandler()); // Add the prometheus metrics servlet to the web server. mWebServer.addHandler(mPMetricsServlet.getHandler()); // start web ui mWebServer.start(); }
[ "protected", "void", "startServingWebServer", "(", ")", "{", "stopRejectingWebServer", "(", ")", ";", "mWebServer", "=", "new", "MasterWebServer", "(", "ServiceType", ".", "MASTER_WEB", ".", "getServiceName", "(", ")", ",", "mWebBindAddress", ",", "this", ")", ";", "// reset master web port", "// Add the metrics servlet to the web server.", "mWebServer", ".", "addHandler", "(", "mMetricsServlet", ".", "getHandler", "(", ")", ")", ";", "// Add the prometheus metrics servlet to the web server.", "mWebServer", ".", "addHandler", "(", "mPMetricsServlet", ".", "getHandler", "(", ")", ")", ";", "// start web ui", "mWebServer", ".", "start", "(", ")", ";", "}" ]
Starts serving web ui server, resetting master web port, adding the metrics servlet to the web server and starting web ui.
[ "Starts", "serving", "web", "ui", "server", "resetting", "master", "web", "port", "adding", "the", "metrics", "servlet", "to", "the", "web", "server", "and", "starting", "web", "ui", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/AlluxioMasterProcess.java#L223-L234
18,711
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/AlluxioMasterProcess.java
AlluxioMasterProcess.startJvmMonitorProcess
protected void startJvmMonitorProcess() { if (ServerConfiguration.getBoolean(PropertyKey.MASTER_JVM_MONITOR_ENABLED)) { mJvmPauseMonitor = new JvmPauseMonitor( ServerConfiguration.getMs(PropertyKey.JVM_MONITOR_SLEEP_INTERVAL_MS), ServerConfiguration.getMs(PropertyKey.JVM_MONITOR_INFO_THRESHOLD_MS), ServerConfiguration.getMs(PropertyKey.JVM_MONITOR_WARN_THRESHOLD_MS)); mJvmPauseMonitor.start(); } }
java
protected void startJvmMonitorProcess() { if (ServerConfiguration.getBoolean(PropertyKey.MASTER_JVM_MONITOR_ENABLED)) { mJvmPauseMonitor = new JvmPauseMonitor( ServerConfiguration.getMs(PropertyKey.JVM_MONITOR_SLEEP_INTERVAL_MS), ServerConfiguration.getMs(PropertyKey.JVM_MONITOR_INFO_THRESHOLD_MS), ServerConfiguration.getMs(PropertyKey.JVM_MONITOR_WARN_THRESHOLD_MS)); mJvmPauseMonitor.start(); } }
[ "protected", "void", "startJvmMonitorProcess", "(", ")", "{", "if", "(", "ServerConfiguration", ".", "getBoolean", "(", "PropertyKey", ".", "MASTER_JVM_MONITOR_ENABLED", ")", ")", "{", "mJvmPauseMonitor", "=", "new", "JvmPauseMonitor", "(", "ServerConfiguration", ".", "getMs", "(", "PropertyKey", ".", "JVM_MONITOR_SLEEP_INTERVAL_MS", ")", ",", "ServerConfiguration", ".", "getMs", "(", "PropertyKey", ".", "JVM_MONITOR_INFO_THRESHOLD_MS", ")", ",", "ServerConfiguration", ".", "getMs", "(", "PropertyKey", ".", "JVM_MONITOR_WARN_THRESHOLD_MS", ")", ")", ";", "mJvmPauseMonitor", ".", "start", "(", ")", ";", "}", "}" ]
Starts jvm monitor process, to monitor jvm.
[ "Starts", "jvm", "monitor", "process", "to", "monitor", "jvm", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/AlluxioMasterProcess.java#L239-L247
18,712
Alluxio/alluxio
underfs/cos/src/main/java/alluxio/underfs/cos/COSUnderFileSystem.java
COSUnderFileSystem.getObjectListingChunk
private ObjectListing getObjectListingChunk(ListObjectsRequest request) { ObjectListing result; try { result = mClient.listObjects(request); } catch (CosClientException e) { LOG.error("Failed to list path {}", request.getPrefix(), e); result = null; } return result; }
java
private ObjectListing getObjectListingChunk(ListObjectsRequest request) { ObjectListing result; try { result = mClient.listObjects(request); } catch (CosClientException e) { LOG.error("Failed to list path {}", request.getPrefix(), e); result = null; } return result; }
[ "private", "ObjectListing", "getObjectListingChunk", "(", "ListObjectsRequest", "request", ")", "{", "ObjectListing", "result", ";", "try", "{", "result", "=", "mClient", ".", "listObjects", "(", "request", ")", ";", "}", "catch", "(", "CosClientException", "e", ")", "{", "LOG", ".", "error", "(", "\"Failed to list path {}\"", ",", "request", ".", "getPrefix", "(", ")", ",", "e", ")", ";", "result", "=", "null", ";", "}", "return", "result", ";", "}" ]
Get next chunk of listing result
[ "Get", "next", "chunk", "of", "listing", "result" ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/cos/src/main/java/alluxio/underfs/cos/COSUnderFileSystem.java#L196-L205
18,713
Alluxio/alluxio
core/common/src/main/java/alluxio/extensions/ExtensionFactoryRegistry.java
ExtensionFactoryRegistry.scanExtensions
private void scanExtensions(List<T> factories, String extensionsDir) { LOG.info("Loading extension jars from {}", extensionsDir); scan(Arrays.asList(ExtensionUtils.listExtensions(extensionsDir)), factories); }
java
private void scanExtensions(List<T> factories, String extensionsDir) { LOG.info("Loading extension jars from {}", extensionsDir); scan(Arrays.asList(ExtensionUtils.listExtensions(extensionsDir)), factories); }
[ "private", "void", "scanExtensions", "(", "List", "<", "T", ">", "factories", ",", "String", "extensionsDir", ")", "{", "LOG", ".", "info", "(", "\"Loading extension jars from {}\"", ",", "extensionsDir", ")", ";", "scan", "(", "Arrays", ".", "asList", "(", "ExtensionUtils", ".", "listExtensions", "(", "extensionsDir", ")", ")", ",", "factories", ")", ";", "}" ]
Finds all factory from the extensions directory. @param factories list of factories to add to
[ "Finds", "all", "factory", "from", "the", "extensions", "directory", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/extensions/ExtensionFactoryRegistry.java#L159-L162
18,714
Alluxio/alluxio
core/common/src/main/java/alluxio/extensions/ExtensionFactoryRegistry.java
ExtensionFactoryRegistry.scanLibs
private void scanLibs(List<T> factories, String libDir) { LOG.info("Loading core jars from {}", libDir); List<File> files = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(libDir), mExtensionPattern)) { for (Path entry : stream) { if (entry.toFile().isFile()) { files.add(entry.toFile()); } } } catch (IOException e) { LOG.warn("Failed to load libs: {}", e.toString()); } scan(files, factories); }
java
private void scanLibs(List<T> factories, String libDir) { LOG.info("Loading core jars from {}", libDir); List<File> files = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(libDir), mExtensionPattern)) { for (Path entry : stream) { if (entry.toFile().isFile()) { files.add(entry.toFile()); } } } catch (IOException e) { LOG.warn("Failed to load libs: {}", e.toString()); } scan(files, factories); }
[ "private", "void", "scanLibs", "(", "List", "<", "T", ">", "factories", ",", "String", "libDir", ")", "{", "LOG", ".", "info", "(", "\"Loading core jars from {}\"", ",", "libDir", ")", ";", "List", "<", "File", ">", "files", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "(", "DirectoryStream", "<", "Path", ">", "stream", "=", "Files", ".", "newDirectoryStream", "(", "Paths", ".", "get", "(", "libDir", ")", ",", "mExtensionPattern", ")", ")", "{", "for", "(", "Path", "entry", ":", "stream", ")", "{", "if", "(", "entry", ".", "toFile", "(", ")", ".", "isFile", "(", ")", ")", "{", "files", ".", "add", "(", "entry", ".", "toFile", "(", ")", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "warn", "(", "\"Failed to load libs: {}\"", ",", "e", ".", "toString", "(", ")", ")", ";", "}", "scan", "(", "files", ",", "factories", ")", ";", "}" ]
Finds all factory from the lib directory. @param factories list of factories to add to
[ "Finds", "all", "factory", "from", "the", "lib", "directory", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/extensions/ExtensionFactoryRegistry.java#L169-L183
18,715
Alluxio/alluxio
core/common/src/main/java/alluxio/extensions/ExtensionFactoryRegistry.java
ExtensionFactoryRegistry.scan
private void scan(List<File> files, List<T> factories) { for (File jar : files) { try { URL extensionURL = jar.toURI().toURL(); String jarPath = extensionURL.toString(); ClassLoader extensionsClassLoader = new ExtensionsClassLoader(new URL[] {extensionURL}, ClassLoader.getSystemClassLoader()); ServiceLoader<T> extensionServiceLoader = ServiceLoader.load(mFactoryClass, extensionsClassLoader); for (T factory : extensionServiceLoader) { LOG.debug("Discovered a factory implementation {} - {} in jar {}", factory.getClass(), factory, jarPath); register(factory, factories); } } catch (Throwable t) { LOG.warn("Failed to load jar {}: {}", jar, t.toString()); } } }
java
private void scan(List<File> files, List<T> factories) { for (File jar : files) { try { URL extensionURL = jar.toURI().toURL(); String jarPath = extensionURL.toString(); ClassLoader extensionsClassLoader = new ExtensionsClassLoader(new URL[] {extensionURL}, ClassLoader.getSystemClassLoader()); ServiceLoader<T> extensionServiceLoader = ServiceLoader.load(mFactoryClass, extensionsClassLoader); for (T factory : extensionServiceLoader) { LOG.debug("Discovered a factory implementation {} - {} in jar {}", factory.getClass(), factory, jarPath); register(factory, factories); } } catch (Throwable t) { LOG.warn("Failed to load jar {}: {}", jar, t.toString()); } } }
[ "private", "void", "scan", "(", "List", "<", "File", ">", "files", ",", "List", "<", "T", ">", "factories", ")", "{", "for", "(", "File", "jar", ":", "files", ")", "{", "try", "{", "URL", "extensionURL", "=", "jar", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ";", "String", "jarPath", "=", "extensionURL", ".", "toString", "(", ")", ";", "ClassLoader", "extensionsClassLoader", "=", "new", "ExtensionsClassLoader", "(", "new", "URL", "[", "]", "{", "extensionURL", "}", ",", "ClassLoader", ".", "getSystemClassLoader", "(", ")", ")", ";", "ServiceLoader", "<", "T", ">", "extensionServiceLoader", "=", "ServiceLoader", ".", "load", "(", "mFactoryClass", ",", "extensionsClassLoader", ")", ";", "for", "(", "T", "factory", ":", "extensionServiceLoader", ")", "{", "LOG", ".", "debug", "(", "\"Discovered a factory implementation {} - {} in jar {}\"", ",", "factory", ".", "getClass", "(", ")", ",", "factory", ",", "jarPath", ")", ";", "register", "(", "factory", ",", "factories", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "LOG", ".", "warn", "(", "\"Failed to load jar {}: {}\"", ",", "jar", ",", "t", ".", "toString", "(", ")", ")", ";", "}", "}", "}" ]
Class-loads jar files that have not been loaded. @param files jar files to class-load @param factories list of factories to add to
[ "Class", "-", "loads", "jar", "files", "that", "have", "not", "been", "loaded", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/extensions/ExtensionFactoryRegistry.java#L191-L210
18,716
Alluxio/alluxio
shell/src/main/java/alluxio/cli/ConfigurationDocGenerator.java
ConfigurationDocGenerator.writeCSVFile
@VisibleForTesting public static void writeCSVFile(Collection<? extends PropertyKey> defaultKeys, String filePath) throws IOException { if (defaultKeys.size() == 0) { return; } FileWriter fileWriter; Closer closer = Closer.create(); String[] fileNames = {"user-configuration.csv", "master-configuration.csv", "worker-configuration.csv", "security-configuration.csv", "common-configuration.csv", "cluster-management-configuration.csv"}; try { // HashMap for FileWriter per each category Map<String, FileWriter> fileWriterMap = new HashMap<>(); for (String fileName : fileNames) { fileWriter = new FileWriter(PathUtils.concatPath(filePath, fileName)); // Write the CSV file header and line separator after the header fileWriter.append(CSV_FILE_HEADER + "\n"); //put fileWriter String key = fileName.substring(0, fileName.indexOf("configuration") - 1); fileWriterMap.put(key, fileWriter); //register file writer closer.register(fileWriter); } // Sort defaultKeys List<PropertyKey> dfkeys = new ArrayList<>(defaultKeys); Collections.sort(dfkeys); for (PropertyKey propertyKey : dfkeys) { String pKey = propertyKey.toString(); String defaultDescription; if (propertyKey.getDefaultSupplier().get() == null) { defaultDescription = ""; } else { defaultDescription = propertyKey.getDefaultSupplier().getDescription(); } // Quote the whole description to escape characters such as commas. defaultDescription = String.format("\"%s\"", defaultDescription); // Write property key and default value to CSV String keyValueStr = pKey + "," + defaultDescription + "\n"; if (pKey.startsWith("alluxio.user.")) { fileWriter = fileWriterMap.get("user"); } else if (pKey.startsWith("alluxio.master.")) { fileWriter = fileWriterMap.get("master"); } else if (pKey.startsWith("alluxio.worker.")) { fileWriter = fileWriterMap.get("worker"); } else if (pKey.startsWith("alluxio.security.")) { fileWriter = fileWriterMap.get("security"); } else if (pKey.startsWith("alluxio.keyvalue.")) { fileWriter = fileWriterMap.get("key-value"); } else if (pKey.startsWith("alluxio.integration")) { fileWriter = fileWriterMap.get("cluster-management"); } else { fileWriter = fileWriterMap.get("common"); } fileWriter.append(keyValueStr); } LOG.info("Property Key CSV files were created successfully."); } catch (Exception e) { throw closer.rethrow(e); } finally { try { closer.close(); } catch (IOException e) { LOG.error("Error while flushing/closing Property Key CSV FileWriter", e); } } }
java
@VisibleForTesting public static void writeCSVFile(Collection<? extends PropertyKey> defaultKeys, String filePath) throws IOException { if (defaultKeys.size() == 0) { return; } FileWriter fileWriter; Closer closer = Closer.create(); String[] fileNames = {"user-configuration.csv", "master-configuration.csv", "worker-configuration.csv", "security-configuration.csv", "common-configuration.csv", "cluster-management-configuration.csv"}; try { // HashMap for FileWriter per each category Map<String, FileWriter> fileWriterMap = new HashMap<>(); for (String fileName : fileNames) { fileWriter = new FileWriter(PathUtils.concatPath(filePath, fileName)); // Write the CSV file header and line separator after the header fileWriter.append(CSV_FILE_HEADER + "\n"); //put fileWriter String key = fileName.substring(0, fileName.indexOf("configuration") - 1); fileWriterMap.put(key, fileWriter); //register file writer closer.register(fileWriter); } // Sort defaultKeys List<PropertyKey> dfkeys = new ArrayList<>(defaultKeys); Collections.sort(dfkeys); for (PropertyKey propertyKey : dfkeys) { String pKey = propertyKey.toString(); String defaultDescription; if (propertyKey.getDefaultSupplier().get() == null) { defaultDescription = ""; } else { defaultDescription = propertyKey.getDefaultSupplier().getDescription(); } // Quote the whole description to escape characters such as commas. defaultDescription = String.format("\"%s\"", defaultDescription); // Write property key and default value to CSV String keyValueStr = pKey + "," + defaultDescription + "\n"; if (pKey.startsWith("alluxio.user.")) { fileWriter = fileWriterMap.get("user"); } else if (pKey.startsWith("alluxio.master.")) { fileWriter = fileWriterMap.get("master"); } else if (pKey.startsWith("alluxio.worker.")) { fileWriter = fileWriterMap.get("worker"); } else if (pKey.startsWith("alluxio.security.")) { fileWriter = fileWriterMap.get("security"); } else if (pKey.startsWith("alluxio.keyvalue.")) { fileWriter = fileWriterMap.get("key-value"); } else if (pKey.startsWith("alluxio.integration")) { fileWriter = fileWriterMap.get("cluster-management"); } else { fileWriter = fileWriterMap.get("common"); } fileWriter.append(keyValueStr); } LOG.info("Property Key CSV files were created successfully."); } catch (Exception e) { throw closer.rethrow(e); } finally { try { closer.close(); } catch (IOException e) { LOG.error("Error while flushing/closing Property Key CSV FileWriter", e); } } }
[ "@", "VisibleForTesting", "public", "static", "void", "writeCSVFile", "(", "Collection", "<", "?", "extends", "PropertyKey", ">", "defaultKeys", ",", "String", "filePath", ")", "throws", "IOException", "{", "if", "(", "defaultKeys", ".", "size", "(", ")", "==", "0", ")", "{", "return", ";", "}", "FileWriter", "fileWriter", ";", "Closer", "closer", "=", "Closer", ".", "create", "(", ")", ";", "String", "[", "]", "fileNames", "=", "{", "\"user-configuration.csv\"", ",", "\"master-configuration.csv\"", ",", "\"worker-configuration.csv\"", ",", "\"security-configuration.csv\"", ",", "\"common-configuration.csv\"", ",", "\"cluster-management-configuration.csv\"", "}", ";", "try", "{", "// HashMap for FileWriter per each category", "Map", "<", "String", ",", "FileWriter", ">", "fileWriterMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "String", "fileName", ":", "fileNames", ")", "{", "fileWriter", "=", "new", "FileWriter", "(", "PathUtils", ".", "concatPath", "(", "filePath", ",", "fileName", ")", ")", ";", "// Write the CSV file header and line separator after the header", "fileWriter", ".", "append", "(", "CSV_FILE_HEADER", "+", "\"\\n\"", ")", ";", "//put fileWriter", "String", "key", "=", "fileName", ".", "substring", "(", "0", ",", "fileName", ".", "indexOf", "(", "\"configuration\"", ")", "-", "1", ")", ";", "fileWriterMap", ".", "put", "(", "key", ",", "fileWriter", ")", ";", "//register file writer", "closer", ".", "register", "(", "fileWriter", ")", ";", "}", "// Sort defaultKeys", "List", "<", "PropertyKey", ">", "dfkeys", "=", "new", "ArrayList", "<>", "(", "defaultKeys", ")", ";", "Collections", ".", "sort", "(", "dfkeys", ")", ";", "for", "(", "PropertyKey", "propertyKey", ":", "dfkeys", ")", "{", "String", "pKey", "=", "propertyKey", ".", "toString", "(", ")", ";", "String", "defaultDescription", ";", "if", "(", "propertyKey", ".", "getDefaultSupplier", "(", ")", ".", "get", "(", ")", "==", "null", ")", "{", "defaultDescription", "=", "\"\"", ";", "}", "else", "{", "defaultDescription", "=", "propertyKey", ".", "getDefaultSupplier", "(", ")", ".", "getDescription", "(", ")", ";", "}", "// Quote the whole description to escape characters such as commas.", "defaultDescription", "=", "String", ".", "format", "(", "\"\\\"%s\\\"\"", ",", "defaultDescription", ")", ";", "// Write property key and default value to CSV", "String", "keyValueStr", "=", "pKey", "+", "\",\"", "+", "defaultDescription", "+", "\"\\n\"", ";", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.user.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"user\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.master.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"master\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.worker.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"worker\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.security.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"security\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.keyvalue.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"key-value\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.integration\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"cluster-management\"", ")", ";", "}", "else", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"common\"", ")", ";", "}", "fileWriter", ".", "append", "(", "keyValueStr", ")", ";", "}", "LOG", ".", "info", "(", "\"Property Key CSV files were created successfully.\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "closer", ".", "rethrow", "(", "e", ")", ";", "}", "finally", "{", "try", "{", "closer", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Error while flushing/closing Property Key CSV FileWriter\"", ",", "e", ")", ";", "}", "}", "}" ]
Writes property key to csv files. @param defaultKeys Collection which is from PropertyKey DEFAULT_KEYS_MAP.values() @param filePath path for csv files
[ "Writes", "property", "key", "to", "csv", "files", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/ConfigurationDocGenerator.java#L53-L125
18,717
Alluxio/alluxio
shell/src/main/java/alluxio/cli/ConfigurationDocGenerator.java
ConfigurationDocGenerator.writeYMLFile
@VisibleForTesting public static void writeYMLFile(Collection<? extends PropertyKey> defaultKeys, String filePath) throws IOException { if (defaultKeys.size() == 0) { return; } FileWriter fileWriter; Closer closer = Closer.create(); String[] fileNames = {"user-configuration.yml", "master-configuration.yml", "worker-configuration.yml", "security-configuration.yml", "common-configuration.yml", "cluster-management-configuration.yml" }; try { // HashMap for FileWriter per each category Map<String, FileWriter> fileWriterMap = new HashMap<>(); for (String fileName : fileNames) { fileWriter = new FileWriter(PathUtils.concatPath(filePath, fileName)); //put fileWriter String key = fileName.substring(0, fileName.indexOf("configuration") - 1); fileWriterMap.put(key, fileWriter); //register file writer closer.register(fileWriter); } // Sort defaultKeys List<PropertyKey> dfkeys = new ArrayList<>(defaultKeys); Collections.sort(dfkeys); for (PropertyKey iteratorPK : dfkeys) { String pKey = iteratorPK.toString(); // Puts descriptions in single quotes to avoid having to escaping reserved characters. // Still needs to escape single quotes with double single quotes. String description = iteratorPK.getDescription().replace("'", "''"); // Write property key and default value to yml files if (iteratorPK.isIgnoredSiteProperty()) { description += " Note: This property must be specified as a JVM property; " + "it is not accepted in alluxio-site.properties."; } String keyValueStr = pKey + ":\n '" + description + "'\n"; if (pKey.startsWith("alluxio.user.")) { fileWriter = fileWriterMap.get("user"); } else if (pKey.startsWith("alluxio.master.")) { fileWriter = fileWriterMap.get("master"); } else if (pKey.startsWith("alluxio.worker.")) { fileWriter = fileWriterMap.get("worker"); } else if (pKey.startsWith("alluxio.security.")) { fileWriter = fileWriterMap.get("security"); } else if (pKey.startsWith("alluxio.keyvalue.")) { fileWriter = fileWriterMap.get("key-value"); } else if (pKey.startsWith("alluxio.integration.")) { fileWriter = fileWriterMap.get("cluster-management"); } else { fileWriter = fileWriterMap.get("common"); } fileWriter.append(keyValueStr); } LOG.info("YML files for description of Property Keys were created successfully."); } catch (Exception e) { throw closer.rethrow(e); } finally { try { closer.close(); } catch (IOException e) { LOG.error("Error while flushing/closing YML files for description of Property Keys " + "FileWriter", e); } } }
java
@VisibleForTesting public static void writeYMLFile(Collection<? extends PropertyKey> defaultKeys, String filePath) throws IOException { if (defaultKeys.size() == 0) { return; } FileWriter fileWriter; Closer closer = Closer.create(); String[] fileNames = {"user-configuration.yml", "master-configuration.yml", "worker-configuration.yml", "security-configuration.yml", "common-configuration.yml", "cluster-management-configuration.yml" }; try { // HashMap for FileWriter per each category Map<String, FileWriter> fileWriterMap = new HashMap<>(); for (String fileName : fileNames) { fileWriter = new FileWriter(PathUtils.concatPath(filePath, fileName)); //put fileWriter String key = fileName.substring(0, fileName.indexOf("configuration") - 1); fileWriterMap.put(key, fileWriter); //register file writer closer.register(fileWriter); } // Sort defaultKeys List<PropertyKey> dfkeys = new ArrayList<>(defaultKeys); Collections.sort(dfkeys); for (PropertyKey iteratorPK : dfkeys) { String pKey = iteratorPK.toString(); // Puts descriptions in single quotes to avoid having to escaping reserved characters. // Still needs to escape single quotes with double single quotes. String description = iteratorPK.getDescription().replace("'", "''"); // Write property key and default value to yml files if (iteratorPK.isIgnoredSiteProperty()) { description += " Note: This property must be specified as a JVM property; " + "it is not accepted in alluxio-site.properties."; } String keyValueStr = pKey + ":\n '" + description + "'\n"; if (pKey.startsWith("alluxio.user.")) { fileWriter = fileWriterMap.get("user"); } else if (pKey.startsWith("alluxio.master.")) { fileWriter = fileWriterMap.get("master"); } else if (pKey.startsWith("alluxio.worker.")) { fileWriter = fileWriterMap.get("worker"); } else if (pKey.startsWith("alluxio.security.")) { fileWriter = fileWriterMap.get("security"); } else if (pKey.startsWith("alluxio.keyvalue.")) { fileWriter = fileWriterMap.get("key-value"); } else if (pKey.startsWith("alluxio.integration.")) { fileWriter = fileWriterMap.get("cluster-management"); } else { fileWriter = fileWriterMap.get("common"); } fileWriter.append(keyValueStr); } LOG.info("YML files for description of Property Keys were created successfully."); } catch (Exception e) { throw closer.rethrow(e); } finally { try { closer.close(); } catch (IOException e) { LOG.error("Error while flushing/closing YML files for description of Property Keys " + "FileWriter", e); } } }
[ "@", "VisibleForTesting", "public", "static", "void", "writeYMLFile", "(", "Collection", "<", "?", "extends", "PropertyKey", ">", "defaultKeys", ",", "String", "filePath", ")", "throws", "IOException", "{", "if", "(", "defaultKeys", ".", "size", "(", ")", "==", "0", ")", "{", "return", ";", "}", "FileWriter", "fileWriter", ";", "Closer", "closer", "=", "Closer", ".", "create", "(", ")", ";", "String", "[", "]", "fileNames", "=", "{", "\"user-configuration.yml\"", ",", "\"master-configuration.yml\"", ",", "\"worker-configuration.yml\"", ",", "\"security-configuration.yml\"", ",", "\"common-configuration.yml\"", ",", "\"cluster-management-configuration.yml\"", "}", ";", "try", "{", "// HashMap for FileWriter per each category", "Map", "<", "String", ",", "FileWriter", ">", "fileWriterMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "String", "fileName", ":", "fileNames", ")", "{", "fileWriter", "=", "new", "FileWriter", "(", "PathUtils", ".", "concatPath", "(", "filePath", ",", "fileName", ")", ")", ";", "//put fileWriter", "String", "key", "=", "fileName", ".", "substring", "(", "0", ",", "fileName", ".", "indexOf", "(", "\"configuration\"", ")", "-", "1", ")", ";", "fileWriterMap", ".", "put", "(", "key", ",", "fileWriter", ")", ";", "//register file writer", "closer", ".", "register", "(", "fileWriter", ")", ";", "}", "// Sort defaultKeys", "List", "<", "PropertyKey", ">", "dfkeys", "=", "new", "ArrayList", "<>", "(", "defaultKeys", ")", ";", "Collections", ".", "sort", "(", "dfkeys", ")", ";", "for", "(", "PropertyKey", "iteratorPK", ":", "dfkeys", ")", "{", "String", "pKey", "=", "iteratorPK", ".", "toString", "(", ")", ";", "// Puts descriptions in single quotes to avoid having to escaping reserved characters.", "// Still needs to escape single quotes with double single quotes.", "String", "description", "=", "iteratorPK", ".", "getDescription", "(", ")", ".", "replace", "(", "\"'\"", ",", "\"''\"", ")", ";", "// Write property key and default value to yml files", "if", "(", "iteratorPK", ".", "isIgnoredSiteProperty", "(", ")", ")", "{", "description", "+=", "\" Note: This property must be specified as a JVM property; \"", "+", "\"it is not accepted in alluxio-site.properties.\"", ";", "}", "String", "keyValueStr", "=", "pKey", "+", "\":\\n '\"", "+", "description", "+", "\"'\\n\"", ";", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.user.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"user\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.master.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"master\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.worker.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"worker\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.security.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"security\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.keyvalue.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"key-value\"", ")", ";", "}", "else", "if", "(", "pKey", ".", "startsWith", "(", "\"alluxio.integration.\"", ")", ")", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"cluster-management\"", ")", ";", "}", "else", "{", "fileWriter", "=", "fileWriterMap", ".", "get", "(", "\"common\"", ")", ";", "}", "fileWriter", ".", "append", "(", "keyValueStr", ")", ";", "}", "LOG", ".", "info", "(", "\"YML files for description of Property Keys were created successfully.\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "closer", ".", "rethrow", "(", "e", ")", ";", "}", "finally", "{", "try", "{", "closer", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Error while flushing/closing YML files for description of Property Keys \"", "+", "\"FileWriter\"", ",", "e", ")", ";", "}", "}", "}" ]
Writes description of property key to yml files. @param defaultKeys Collection which is from PropertyKey DEFAULT_KEYS_MAP.values() @param filePath path for csv files
[ "Writes", "description", "of", "property", "key", "to", "yml", "files", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/ConfigurationDocGenerator.java#L133-L205
18,718
Alluxio/alluxio
shell/src/main/java/alluxio/cli/ConfigurationDocGenerator.java
ConfigurationDocGenerator.main
public static void main(String[] args) throws IOException { Collection<? extends PropertyKey> defaultKeys = PropertyKey.defaultKeys(); defaultKeys.removeIf(key -> key.isHidden()); String homeDir = new InstancedConfiguration(ConfigurationUtils.defaults()) .get(PropertyKey.HOME); // generate CSV files String filePath = PathUtils.concatPath(homeDir, CSV_FILE_DIR); writeCSVFile(defaultKeys, filePath); // generate YML files filePath = PathUtils.concatPath(homeDir, YML_FILE_DIR); writeYMLFile(defaultKeys, filePath); }
java
public static void main(String[] args) throws IOException { Collection<? extends PropertyKey> defaultKeys = PropertyKey.defaultKeys(); defaultKeys.removeIf(key -> key.isHidden()); String homeDir = new InstancedConfiguration(ConfigurationUtils.defaults()) .get(PropertyKey.HOME); // generate CSV files String filePath = PathUtils.concatPath(homeDir, CSV_FILE_DIR); writeCSVFile(defaultKeys, filePath); // generate YML files filePath = PathUtils.concatPath(homeDir, YML_FILE_DIR); writeYMLFile(defaultKeys, filePath); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "Collection", "<", "?", "extends", "PropertyKey", ">", "defaultKeys", "=", "PropertyKey", ".", "defaultKeys", "(", ")", ";", "defaultKeys", ".", "removeIf", "(", "key", "->", "key", ".", "isHidden", "(", ")", ")", ";", "String", "homeDir", "=", "new", "InstancedConfiguration", "(", "ConfigurationUtils", ".", "defaults", "(", ")", ")", ".", "get", "(", "PropertyKey", ".", "HOME", ")", ";", "// generate CSV files", "String", "filePath", "=", "PathUtils", ".", "concatPath", "(", "homeDir", ",", "CSV_FILE_DIR", ")", ";", "writeCSVFile", "(", "defaultKeys", ",", "filePath", ")", ";", "// generate YML files", "filePath", "=", "PathUtils", ".", "concatPath", "(", "homeDir", ",", "YML_FILE_DIR", ")", ";", "writeYMLFile", "(", "defaultKeys", ",", "filePath", ")", ";", "}" ]
Main entry for this util class. @param args arguments for command line
[ "Main", "entry", "for", "this", "util", "class", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/ConfigurationDocGenerator.java#L212-L223
18,719
Alluxio/alluxio
core/common/src/main/java/alluxio/util/network/NettyUtils.java
NettyUtils.enableAutoRead
public static void enableAutoRead(Channel channel) { if (!channel.config().isAutoRead()) { channel.config().setAutoRead(true); channel.read(); } }
java
public static void enableAutoRead(Channel channel) { if (!channel.config().isAutoRead()) { channel.config().setAutoRead(true); channel.read(); } }
[ "public", "static", "void", "enableAutoRead", "(", "Channel", "channel", ")", "{", "if", "(", "!", "channel", ".", "config", "(", ")", ".", "isAutoRead", "(", ")", ")", "{", "channel", ".", "config", "(", ")", ".", "setAutoRead", "(", "true", ")", ";", "channel", ".", "read", "(", ")", ";", "}", "}" ]
Enables auto read for a netty channel. @param channel the netty channel
[ "Enables", "auto", "read", "for", "a", "netty", "channel", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/network/NettyUtils.java#L134-L139
18,720
Alluxio/alluxio
shell/src/main/java/alluxio/cli/GetConfKey.java
GetConfKey.getConfKey
public static int getConfKey(String... args) { switch (args.length) { case 0: printHelp("Missing argument."); return 1; case 1: String varName = args[0].trim(); String propertyName = ENV_VIOLATORS.getOrDefault(varName, varName.toLowerCase().replace("_", ".")); if (!PropertyKey.isValid(propertyName)) { printHelp(String.format("%s is not a valid configuration key", propertyName)); return 1; } PropertyKey key = PropertyKey.fromString(propertyName); System.out.println(key.getName()); break; default: printHelp("More arguments than expected"); return 1; } return 0; }
java
public static int getConfKey(String... args) { switch (args.length) { case 0: printHelp("Missing argument."); return 1; case 1: String varName = args[0].trim(); String propertyName = ENV_VIOLATORS.getOrDefault(varName, varName.toLowerCase().replace("_", ".")); if (!PropertyKey.isValid(propertyName)) { printHelp(String.format("%s is not a valid configuration key", propertyName)); return 1; } PropertyKey key = PropertyKey.fromString(propertyName); System.out.println(key.getName()); break; default: printHelp("More arguments than expected"); return 1; } return 0; }
[ "public", "static", "int", "getConfKey", "(", "String", "...", "args", ")", "{", "switch", "(", "args", ".", "length", ")", "{", "case", "0", ":", "printHelp", "(", "\"Missing argument.\"", ")", ";", "return", "1", ";", "case", "1", ":", "String", "varName", "=", "args", "[", "0", "]", ".", "trim", "(", ")", ";", "String", "propertyName", "=", "ENV_VIOLATORS", ".", "getOrDefault", "(", "varName", ",", "varName", ".", "toLowerCase", "(", ")", ".", "replace", "(", "\"_\"", ",", "\".\"", ")", ")", ";", "if", "(", "!", "PropertyKey", ".", "isValid", "(", "propertyName", ")", ")", "{", "printHelp", "(", "String", ".", "format", "(", "\"%s is not a valid configuration key\"", ",", "propertyName", ")", ")", ";", "return", "1", ";", "}", "PropertyKey", "key", "=", "PropertyKey", ".", "fromString", "(", "propertyName", ")", ";", "System", ".", "out", ".", "println", "(", "key", ".", "getName", "(", ")", ")", ";", "break", ";", "default", ":", "printHelp", "(", "\"More arguments than expected\"", ")", ";", "return", "1", ";", "}", "return", "0", ";", "}" ]
Implements get configuration key. @param args the arguments to specify the environment variable name @return 0 on success, 1 on failures
[ "Implements", "get", "configuration", "key", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/GetConfKey.java#L55-L76
18,721
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fsadmin/FileSystemAdminShell.java
FileSystemAdminShell.main
public static void main(String[] args) { InstancedConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults()); if (!ConfigurationUtils.masterHostConfigured(conf) && args.length > 0) { System.out.println(ConfigurationUtils .getMasterHostNotConfiguredMessage("Alluxio fsadmin shell")); System.exit(1); } // Reduce the RPC retry max duration to fall earlier for CLIs conf.set(PropertyKey.USER_RPC_RETRY_MAX_DURATION, "5s", Source.DEFAULT); FileSystemAdminShell fsAdminShell = new FileSystemAdminShell(conf); System.exit(fsAdminShell.run(args)); }
java
public static void main(String[] args) { InstancedConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults()); if (!ConfigurationUtils.masterHostConfigured(conf) && args.length > 0) { System.out.println(ConfigurationUtils .getMasterHostNotConfiguredMessage("Alluxio fsadmin shell")); System.exit(1); } // Reduce the RPC retry max duration to fall earlier for CLIs conf.set(PropertyKey.USER_RPC_RETRY_MAX_DURATION, "5s", Source.DEFAULT); FileSystemAdminShell fsAdminShell = new FileSystemAdminShell(conf); System.exit(fsAdminShell.run(args)); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "InstancedConfiguration", "conf", "=", "new", "InstancedConfiguration", "(", "ConfigurationUtils", ".", "defaults", "(", ")", ")", ";", "if", "(", "!", "ConfigurationUtils", ".", "masterHostConfigured", "(", "conf", ")", "&&", "args", ".", "length", ">", "0", ")", "{", "System", ".", "out", ".", "println", "(", "ConfigurationUtils", ".", "getMasterHostNotConfiguredMessage", "(", "\"Alluxio fsadmin shell\"", ")", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "// Reduce the RPC retry max duration to fall earlier for CLIs", "conf", ".", "set", "(", "PropertyKey", ".", "USER_RPC_RETRY_MAX_DURATION", ",", "\"5s\"", ",", "Source", ".", "DEFAULT", ")", ";", "FileSystemAdminShell", "fsAdminShell", "=", "new", "FileSystemAdminShell", "(", "conf", ")", ";", "System", ".", "exit", "(", "fsAdminShell", ".", "run", "(", "args", ")", ")", ";", "}" ]
Manage Alluxio file system. @param args array of arguments given by the user's input from the terminal
[ "Manage", "Alluxio", "file", "system", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fsadmin/FileSystemAdminShell.java#L60-L71
18,722
Alluxio/alluxio
shell/src/main/java/alluxio/cli/GetConf.java
GetConf.main
public static void main(String[] args) { System.exit(getConf( ClientContext.create(new InstancedConfiguration(ConfigurationUtils.defaults())), args)); }
java
public static void main(String[] args) { System.exit(getConf( ClientContext.create(new InstancedConfiguration(ConfigurationUtils.defaults())), args)); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "System", ".", "exit", "(", "getConf", "(", "ClientContext", ".", "create", "(", "new", "InstancedConfiguration", "(", "ConfigurationUtils", ".", "defaults", "(", ")", ")", ")", ",", "args", ")", ")", ";", "}" ]
Prints Alluxio configuration. @param args the arguments to specify the unit (optional) and configuration key (optional)
[ "Prints", "Alluxio", "configuration", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/GetConf.java#L269-L272
18,723
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/file/UnderFileSystemUtils.java
UnderFileSystemUtils.prepareFilePath
public static void prepareFilePath(AlluxioURI alluxioPath, String ufsPath, FileSystem fs, UnderFileSystem ufs) throws AlluxioException, IOException { AlluxioURI dstPath = new AlluxioURI(ufsPath); String parentPath = dstPath.getParent().getPath(); // creates the parent folder if it does not exist if (!ufs.isDirectory(parentPath)) { // Create ancestor directories from top to the bottom. We cannot use recursive create parents // here because the permission for the ancestors can be different. Stack<Pair<String, MkdirsOptions>> ufsDirsToMakeWithOptions = new Stack<>(); AlluxioURI curAlluxioPath = alluxioPath.getParent(); AlluxioURI curUfsPath = dstPath.getParent(); // Stop at Alluxio mount point because the mapped directory in UFS may not exist. while (curUfsPath != null && !ufs.isDirectory(curUfsPath.toString()) && curAlluxioPath != null) { URIStatus curDirStatus = fs.getStatus(curAlluxioPath); if (curDirStatus.isMountPoint()) { throw new IOException(ExceptionMessage.UFS_PATH_DOES_NOT_EXIST.getMessage(curUfsPath)); } ufsDirsToMakeWithOptions.push(new Pair<>(curUfsPath.toString(), MkdirsOptions.defaults(ServerConfiguration.global()).setCreateParent(false) .setOwner(curDirStatus.getOwner()) .setGroup(curDirStatus.getGroup()) .setMode(new Mode((short) curDirStatus.getMode())))); curAlluxioPath = curAlluxioPath.getParent(); curUfsPath = curUfsPath.getParent(); } while (!ufsDirsToMakeWithOptions.empty()) { Pair<String, MkdirsOptions> ufsDirAndPerm = ufsDirsToMakeWithOptions.pop(); // UFS mkdirs might fail if the directory is already created. If so, skip the mkdirs // and assume the directory is already prepared, regardless of permission matching. if (!ufs.mkdirs(ufsDirAndPerm.getFirst(), ufsDirAndPerm.getSecond()) && !ufs.isDirectory(ufsDirAndPerm.getFirst())) { throw new IOException("Failed to create dir: " + ufsDirAndPerm.getFirst()); } } } }
java
public static void prepareFilePath(AlluxioURI alluxioPath, String ufsPath, FileSystem fs, UnderFileSystem ufs) throws AlluxioException, IOException { AlluxioURI dstPath = new AlluxioURI(ufsPath); String parentPath = dstPath.getParent().getPath(); // creates the parent folder if it does not exist if (!ufs.isDirectory(parentPath)) { // Create ancestor directories from top to the bottom. We cannot use recursive create parents // here because the permission for the ancestors can be different. Stack<Pair<String, MkdirsOptions>> ufsDirsToMakeWithOptions = new Stack<>(); AlluxioURI curAlluxioPath = alluxioPath.getParent(); AlluxioURI curUfsPath = dstPath.getParent(); // Stop at Alluxio mount point because the mapped directory in UFS may not exist. while (curUfsPath != null && !ufs.isDirectory(curUfsPath.toString()) && curAlluxioPath != null) { URIStatus curDirStatus = fs.getStatus(curAlluxioPath); if (curDirStatus.isMountPoint()) { throw new IOException(ExceptionMessage.UFS_PATH_DOES_NOT_EXIST.getMessage(curUfsPath)); } ufsDirsToMakeWithOptions.push(new Pair<>(curUfsPath.toString(), MkdirsOptions.defaults(ServerConfiguration.global()).setCreateParent(false) .setOwner(curDirStatus.getOwner()) .setGroup(curDirStatus.getGroup()) .setMode(new Mode((short) curDirStatus.getMode())))); curAlluxioPath = curAlluxioPath.getParent(); curUfsPath = curUfsPath.getParent(); } while (!ufsDirsToMakeWithOptions.empty()) { Pair<String, MkdirsOptions> ufsDirAndPerm = ufsDirsToMakeWithOptions.pop(); // UFS mkdirs might fail if the directory is already created. If so, skip the mkdirs // and assume the directory is already prepared, regardless of permission matching. if (!ufs.mkdirs(ufsDirAndPerm.getFirst(), ufsDirAndPerm.getSecond()) && !ufs.isDirectory(ufsDirAndPerm.getFirst())) { throw new IOException("Failed to create dir: " + ufsDirAndPerm.getFirst()); } } } }
[ "public", "static", "void", "prepareFilePath", "(", "AlluxioURI", "alluxioPath", ",", "String", "ufsPath", ",", "FileSystem", "fs", ",", "UnderFileSystem", "ufs", ")", "throws", "AlluxioException", ",", "IOException", "{", "AlluxioURI", "dstPath", "=", "new", "AlluxioURI", "(", "ufsPath", ")", ";", "String", "parentPath", "=", "dstPath", ".", "getParent", "(", ")", ".", "getPath", "(", ")", ";", "// creates the parent folder if it does not exist", "if", "(", "!", "ufs", ".", "isDirectory", "(", "parentPath", ")", ")", "{", "// Create ancestor directories from top to the bottom. We cannot use recursive create parents", "// here because the permission for the ancestors can be different.", "Stack", "<", "Pair", "<", "String", ",", "MkdirsOptions", ">", ">", "ufsDirsToMakeWithOptions", "=", "new", "Stack", "<>", "(", ")", ";", "AlluxioURI", "curAlluxioPath", "=", "alluxioPath", ".", "getParent", "(", ")", ";", "AlluxioURI", "curUfsPath", "=", "dstPath", ".", "getParent", "(", ")", ";", "// Stop at Alluxio mount point because the mapped directory in UFS may not exist.", "while", "(", "curUfsPath", "!=", "null", "&&", "!", "ufs", ".", "isDirectory", "(", "curUfsPath", ".", "toString", "(", ")", ")", "&&", "curAlluxioPath", "!=", "null", ")", "{", "URIStatus", "curDirStatus", "=", "fs", ".", "getStatus", "(", "curAlluxioPath", ")", ";", "if", "(", "curDirStatus", ".", "isMountPoint", "(", ")", ")", "{", "throw", "new", "IOException", "(", "ExceptionMessage", ".", "UFS_PATH_DOES_NOT_EXIST", ".", "getMessage", "(", "curUfsPath", ")", ")", ";", "}", "ufsDirsToMakeWithOptions", ".", "push", "(", "new", "Pair", "<>", "(", "curUfsPath", ".", "toString", "(", ")", ",", "MkdirsOptions", ".", "defaults", "(", "ServerConfiguration", ".", "global", "(", ")", ")", ".", "setCreateParent", "(", "false", ")", ".", "setOwner", "(", "curDirStatus", ".", "getOwner", "(", ")", ")", ".", "setGroup", "(", "curDirStatus", ".", "getGroup", "(", ")", ")", ".", "setMode", "(", "new", "Mode", "(", "(", "short", ")", "curDirStatus", ".", "getMode", "(", ")", ")", ")", ")", ")", ";", "curAlluxioPath", "=", "curAlluxioPath", ".", "getParent", "(", ")", ";", "curUfsPath", "=", "curUfsPath", ".", "getParent", "(", ")", ";", "}", "while", "(", "!", "ufsDirsToMakeWithOptions", ".", "empty", "(", ")", ")", "{", "Pair", "<", "String", ",", "MkdirsOptions", ">", "ufsDirAndPerm", "=", "ufsDirsToMakeWithOptions", ".", "pop", "(", ")", ";", "// UFS mkdirs might fail if the directory is already created. If so, skip the mkdirs", "// and assume the directory is already prepared, regardless of permission matching.", "if", "(", "!", "ufs", ".", "mkdirs", "(", "ufsDirAndPerm", ".", "getFirst", "(", ")", ",", "ufsDirAndPerm", ".", "getSecond", "(", ")", ")", "&&", "!", "ufs", ".", "isDirectory", "(", "ufsDirAndPerm", ".", "getFirst", "(", ")", ")", ")", "{", "throw", "new", "IOException", "(", "\"Failed to create dir: \"", "+", "ufsDirAndPerm", ".", "getFirst", "(", ")", ")", ";", "}", "}", "}", "}" ]
Creates parent directories for path with correct permissions if required. @param alluxioPath Alluxio path @param ufsPath path in the under file system @param fs file system master client @param ufs the under file system
[ "Creates", "parent", "directories", "for", "path", "with", "correct", "permissions", "if", "required", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/file/UnderFileSystemUtils.java#L44-L80
18,724
Alluxio/alluxio
core/common/src/main/java/alluxio/collections/LockCache.java
LockCache.evictIfOverLimit
private void evictIfOverLimit() { int numToEvict = mCache.size() - mSoftLimit; if (numToEvict <= 0) { return; } if (mEvictLock.tryLock()) { try { // update the total number to evict while we are holding the lock numToEvict = mCache.size() - mSoftLimit; // This thread won the race as the evictor while (numToEvict > 0) { if (!mIterator.hasNext()) { mIterator = mCache.entrySet().iterator(); } Map.Entry<K, ValNode> candidateMapEntry = mIterator.next(); ValNode candidate = candidateMapEntry.getValue(); if (candidate.mIsAccessed) { candidate.mIsAccessed = false; } else { if (candidate.mRefCount.compareAndSet(0, Integer.MIN_VALUE)) { // the value object can be evicted, at the same time we make refCount minValue mIterator.remove(); numToEvict--; } } } } finally { mEvictLock.unlock(); } } }
java
private void evictIfOverLimit() { int numToEvict = mCache.size() - mSoftLimit; if (numToEvict <= 0) { return; } if (mEvictLock.tryLock()) { try { // update the total number to evict while we are holding the lock numToEvict = mCache.size() - mSoftLimit; // This thread won the race as the evictor while (numToEvict > 0) { if (!mIterator.hasNext()) { mIterator = mCache.entrySet().iterator(); } Map.Entry<K, ValNode> candidateMapEntry = mIterator.next(); ValNode candidate = candidateMapEntry.getValue(); if (candidate.mIsAccessed) { candidate.mIsAccessed = false; } else { if (candidate.mRefCount.compareAndSet(0, Integer.MIN_VALUE)) { // the value object can be evicted, at the same time we make refCount minValue mIterator.remove(); numToEvict--; } } } } finally { mEvictLock.unlock(); } } }
[ "private", "void", "evictIfOverLimit", "(", ")", "{", "int", "numToEvict", "=", "mCache", ".", "size", "(", ")", "-", "mSoftLimit", ";", "if", "(", "numToEvict", "<=", "0", ")", "{", "return", ";", "}", "if", "(", "mEvictLock", ".", "tryLock", "(", ")", ")", "{", "try", "{", "// update the total number to evict while we are holding the lock", "numToEvict", "=", "mCache", ".", "size", "(", ")", "-", "mSoftLimit", ";", "// This thread won the race as the evictor", "while", "(", "numToEvict", ">", "0", ")", "{", "if", "(", "!", "mIterator", ".", "hasNext", "(", ")", ")", "{", "mIterator", "=", "mCache", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "}", "Map", ".", "Entry", "<", "K", ",", "ValNode", ">", "candidateMapEntry", "=", "mIterator", ".", "next", "(", ")", ";", "ValNode", "candidate", "=", "candidateMapEntry", ".", "getValue", "(", ")", ";", "if", "(", "candidate", ".", "mIsAccessed", ")", "{", "candidate", ".", "mIsAccessed", "=", "false", ";", "}", "else", "{", "if", "(", "candidate", ".", "mRefCount", ".", "compareAndSet", "(", "0", ",", "Integer", ".", "MIN_VALUE", ")", ")", "{", "// the value object can be evicted, at the same time we make refCount minValue", "mIterator", ".", "remove", "(", ")", ";", "numToEvict", "--", ";", "}", "}", "}", "}", "finally", "{", "mEvictLock", ".", "unlock", "(", ")", ";", "}", "}", "}" ]
If the size of the cache exceeds the soft limit and no other thread is evicting entries, start evicting entries.
[ "If", "the", "size", "of", "the", "cache", "exceeds", "the", "soft", "limit", "and", "no", "other", "thread", "is", "evicting", "entries", "start", "evicting", "entries", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/collections/LockCache.java#L81-L113
18,725
Alluxio/alluxio
core/common/src/main/java/alluxio/collections/LockCache.java
LockCache.get
public LockResource get(K key, LockMode mode) { ValNode valNode = getValNode(key); ReentrantReadWriteLock lock = valNode.mValue; switch (mode) { case READ: return new RefCountLockResource(lock.readLock(), true, valNode.mRefCount); case WRITE: return new RefCountLockResource(lock.writeLock(), true, valNode.mRefCount); default: throw new IllegalStateException("Unknown lock mode: " + mode); } }
java
public LockResource get(K key, LockMode mode) { ValNode valNode = getValNode(key); ReentrantReadWriteLock lock = valNode.mValue; switch (mode) { case READ: return new RefCountLockResource(lock.readLock(), true, valNode.mRefCount); case WRITE: return new RefCountLockResource(lock.writeLock(), true, valNode.mRefCount); default: throw new IllegalStateException("Unknown lock mode: " + mode); } }
[ "public", "LockResource", "get", "(", "K", "key", ",", "LockMode", "mode", ")", "{", "ValNode", "valNode", "=", "getValNode", "(", "key", ")", ";", "ReentrantReadWriteLock", "lock", "=", "valNode", ".", "mValue", ";", "switch", "(", "mode", ")", "{", "case", "READ", ":", "return", "new", "RefCountLockResource", "(", "lock", ".", "readLock", "(", ")", ",", "true", ",", "valNode", ".", "mRefCount", ")", ";", "case", "WRITE", ":", "return", "new", "RefCountLockResource", "(", "lock", ".", "writeLock", "(", ")", ",", "true", ",", "valNode", ".", "mRefCount", ")", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unknown lock mode: \"", "+", "mode", ")", ";", "}", "}" ]
Locks the specified key in the specified mode. @param key the key to lock @param mode the mode to lock in @return a lock resource which must be closed to unlock the key
[ "Locks", "the", "specified", "key", "in", "the", "specified", "mode", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/collections/LockCache.java#L123-L134
18,726
Alluxio/alluxio
core/common/src/main/java/alluxio/collections/LockCache.java
LockCache.tryGet
public Optional<LockResource> tryGet(K key, LockMode mode) { ValNode valNode = getValNode(key); ReentrantReadWriteLock lock = valNode.mValue; Lock innerLock; switch (mode) { case READ: innerLock = lock.readLock(); break; case WRITE: innerLock = lock.writeLock(); break; default: throw new IllegalStateException("Unknown lock mode: " + mode); } if (!innerLock.tryLock()) { return Optional.empty(); } return Optional.of(new RefCountLockResource(innerLock, false, valNode.mRefCount)); }
java
public Optional<LockResource> tryGet(K key, LockMode mode) { ValNode valNode = getValNode(key); ReentrantReadWriteLock lock = valNode.mValue; Lock innerLock; switch (mode) { case READ: innerLock = lock.readLock(); break; case WRITE: innerLock = lock.writeLock(); break; default: throw new IllegalStateException("Unknown lock mode: " + mode); } if (!innerLock.tryLock()) { return Optional.empty(); } return Optional.of(new RefCountLockResource(innerLock, false, valNode.mRefCount)); }
[ "public", "Optional", "<", "LockResource", ">", "tryGet", "(", "K", "key", ",", "LockMode", "mode", ")", "{", "ValNode", "valNode", "=", "getValNode", "(", "key", ")", ";", "ReentrantReadWriteLock", "lock", "=", "valNode", ".", "mValue", ";", "Lock", "innerLock", ";", "switch", "(", "mode", ")", "{", "case", "READ", ":", "innerLock", "=", "lock", ".", "readLock", "(", ")", ";", "break", ";", "case", "WRITE", ":", "innerLock", "=", "lock", ".", "writeLock", "(", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unknown lock mode: \"", "+", "mode", ")", ";", "}", "if", "(", "!", "innerLock", ".", "tryLock", "(", ")", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "return", "Optional", ".", "of", "(", "new", "RefCountLockResource", "(", "innerLock", ",", "false", ",", "valNode", ".", "mRefCount", ")", ")", ";", "}" ]
Attempts to take a lock on the given key. @param key the key to lock @param mode lockMode to acquire @return either empty or a lock resource which must be closed to unlock the key
[ "Attempts", "to", "take", "a", "lock", "on", "the", "given", "key", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/collections/LockCache.java#L143-L161
18,727
Alluxio/alluxio
core/common/src/main/java/alluxio/collections/LockCache.java
LockCache.getRawReadWriteLock
@VisibleForTesting public ReentrantReadWriteLock getRawReadWriteLock(K key) { return mCache.getOrDefault(key, new ValNode(new ReentrantReadWriteLock())).mValue; }
java
@VisibleForTesting public ReentrantReadWriteLock getRawReadWriteLock(K key) { return mCache.getOrDefault(key, new ValNode(new ReentrantReadWriteLock())).mValue; }
[ "@", "VisibleForTesting", "public", "ReentrantReadWriteLock", "getRawReadWriteLock", "(", "K", "key", ")", "{", "return", "mCache", ".", "getOrDefault", "(", "key", ",", "new", "ValNode", "(", "new", "ReentrantReadWriteLock", "(", ")", ")", ")", ".", "mValue", ";", "}" ]
Get the raw readwrite lock from the cache. @param key key to look up the value @return the lock associated with the key
[ "Get", "the", "raw", "readwrite", "lock", "from", "the", "cache", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/collections/LockCache.java#L169-L172
18,728
Alluxio/alluxio
core/common/src/main/java/alluxio/collections/LockCache.java
LockCache.containsKey
@VisibleForTesting public boolean containsKey(K key) { Preconditions.checkNotNull(key, "key can not be null"); return mCache.containsKey(key); }
java
@VisibleForTesting public boolean containsKey(K key) { Preconditions.checkNotNull(key, "key can not be null"); return mCache.containsKey(key); }
[ "@", "VisibleForTesting", "public", "boolean", "containsKey", "(", "K", "key", ")", "{", "Preconditions", ".", "checkNotNull", "(", "key", ",", "\"key can not be null\"", ")", ";", "return", "mCache", ".", "containsKey", "(", "key", ")", ";", "}" ]
Returns whether the cache contains a particular key. @param key the key to look up in the cache @return true if the key is contained in the cache
[ "Returns", "whether", "the", "cache", "contains", "a", "particular", "key", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/collections/LockCache.java#L229-L233
18,729
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/ChecksumCommand.java
ChecksumCommand.calculateChecksum
private String calculateChecksum(AlluxioURI filePath) throws AlluxioException, IOException { OpenFilePOptions options = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); try (FileInStream fis = mFileSystem.openFile(filePath, options)) { return DigestUtils.md5Hex(fis); } }
java
private String calculateChecksum(AlluxioURI filePath) throws AlluxioException, IOException { OpenFilePOptions options = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); try (FileInStream fis = mFileSystem.openFile(filePath, options)) { return DigestUtils.md5Hex(fis); } }
[ "private", "String", "calculateChecksum", "(", "AlluxioURI", "filePath", ")", "throws", "AlluxioException", ",", "IOException", "{", "OpenFilePOptions", "options", "=", "OpenFilePOptions", ".", "newBuilder", "(", ")", ".", "setReadType", "(", "ReadPType", ".", "NO_CACHE", ")", ".", "build", "(", ")", ";", "try", "(", "FileInStream", "fis", "=", "mFileSystem", ".", "openFile", "(", "filePath", ",", "options", ")", ")", "{", "return", "DigestUtils", ".", "md5Hex", "(", "fis", ")", ";", "}", "}" ]
Calculates the md5 checksum for a file. @param filePath The {@link AlluxioURI} path of the file calculate MD5 checksum on @return A string representation of the file's MD5 checksum
[ "Calculates", "the", "md5", "checksum", "for", "a", "file", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/ChecksumCommand.java#L81-L88
18,730
Alluxio/alluxio
core/common/src/main/java/alluxio/AbstractClient.java
AbstractClient.checkVersion
protected void checkVersion(long clientVersion) throws IOException { if (mServiceVersion == Constants.UNKNOWN_SERVICE_VERSION) { mServiceVersion = getRemoteServiceVersion(); if (mServiceVersion != clientVersion) { throw new IOException(ExceptionMessage.INCOMPATIBLE_VERSION.getMessage(getServiceName(), clientVersion, mServiceVersion)); } } }
java
protected void checkVersion(long clientVersion) throws IOException { if (mServiceVersion == Constants.UNKNOWN_SERVICE_VERSION) { mServiceVersion = getRemoteServiceVersion(); if (mServiceVersion != clientVersion) { throw new IOException(ExceptionMessage.INCOMPATIBLE_VERSION.getMessage(getServiceName(), clientVersion, mServiceVersion)); } } }
[ "protected", "void", "checkVersion", "(", "long", "clientVersion", ")", "throws", "IOException", "{", "if", "(", "mServiceVersion", "==", "Constants", ".", "UNKNOWN_SERVICE_VERSION", ")", "{", "mServiceVersion", "=", "getRemoteServiceVersion", "(", ")", ";", "if", "(", "mServiceVersion", "!=", "clientVersion", ")", "{", "throw", "new", "IOException", "(", "ExceptionMessage", ".", "INCOMPATIBLE_VERSION", ".", "getMessage", "(", "getServiceName", "(", ")", ",", "clientVersion", ",", "mServiceVersion", ")", ")", ";", "}", "}", "}" ]
Checks that the service version is compatible with the client. @param clientVersion the client version
[ "Checks", "that", "the", "service", "version", "is", "compatible", "with", "the", "client", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/AbstractClient.java#L140-L148
18,731
Alluxio/alluxio
core/common/src/main/java/alluxio/AbstractClient.java
AbstractClient.connect
@Override public synchronized void connect() throws AlluxioStatusException { if (mConnected) { return; } disconnect(); Preconditions.checkState(!mClosed, "Client is closed, will not try to connect."); IOException lastConnectFailure = null; RetryPolicy retryPolicy = mRetryPolicySupplier.get(); while (retryPolicy.attempt()) { if (mClosed) { throw new FailedPreconditionException("Failed to connect: client has been closed"); } // Re-query the address in each loop iteration in case it has changed (e.g. master // failover). try { mAddress = getAddress(); } catch (UnavailableException e) { LOG.warn("Failed to determine {} rpc address ({}): {}", getServiceName(), retryPolicy.getAttemptCount(), e.toString()); continue; } if (mAddress.isUnresolved()) { // Sometimes the acquired addressed wasn't resolved, retry resolving before // using it to connect. LOG.info("Retry resolving address {}", mAddress); // Creates a new InetSocketAddress to force resolving the hostname again. mAddress = new InetSocketAddress(mAddress.getHostName(), mAddress.getPort()); if (mAddress.isUnresolved()) { LOG.warn("Failed to resolve address on retry {}", mAddress); } } try { beforeConnect(); LOG.info("Alluxio client (version {}) is trying to connect with {} @ {}", RuntimeConstants.VERSION, getServiceName(), mAddress); mChannel = GrpcChannelBuilder .newBuilder(new GrpcServerAddress(mAddress), mContext.getConf()) .setSubject(mContext.getSubject()) .build(); // Create stub for version service on host mVersionService = ServiceVersionClientServiceGrpc.newBlockingStub(mChannel); mConnected = true; afterConnect(); checkVersion(getServiceVersion()); LOG.info("Alluxio client (version {}) is connected with {} @ {}", RuntimeConstants.VERSION, getServiceName(), mAddress); return; } catch (IOException e) { LOG.warn("Failed to connect ({}) with {} @ {}: {}", retryPolicy.getAttemptCount(), getServiceName(), mAddress, e.getMessage()); lastConnectFailure = e; } } // Reaching here indicates that we did not successfully connect. if (mChannel != null) { mChannel.shutdown(); } if (mAddress == null) { throw new UnavailableException( String.format("Failed to determine address for %s after %s attempts", getServiceName(), retryPolicy.getAttemptCount())); } /** * Throw as-is if {@link UnauthenticatedException} occurred. */ if (lastConnectFailure instanceof UnauthenticatedException) { throw (AlluxioStatusException) lastConnectFailure; } throw new UnavailableException(String.format("Failed to connect to %s @ %s after %s attempts", getServiceName(), mAddress, retryPolicy.getAttemptCount()), lastConnectFailure); }
java
@Override public synchronized void connect() throws AlluxioStatusException { if (mConnected) { return; } disconnect(); Preconditions.checkState(!mClosed, "Client is closed, will not try to connect."); IOException lastConnectFailure = null; RetryPolicy retryPolicy = mRetryPolicySupplier.get(); while (retryPolicy.attempt()) { if (mClosed) { throw new FailedPreconditionException("Failed to connect: client has been closed"); } // Re-query the address in each loop iteration in case it has changed (e.g. master // failover). try { mAddress = getAddress(); } catch (UnavailableException e) { LOG.warn("Failed to determine {} rpc address ({}): {}", getServiceName(), retryPolicy.getAttemptCount(), e.toString()); continue; } if (mAddress.isUnresolved()) { // Sometimes the acquired addressed wasn't resolved, retry resolving before // using it to connect. LOG.info("Retry resolving address {}", mAddress); // Creates a new InetSocketAddress to force resolving the hostname again. mAddress = new InetSocketAddress(mAddress.getHostName(), mAddress.getPort()); if (mAddress.isUnresolved()) { LOG.warn("Failed to resolve address on retry {}", mAddress); } } try { beforeConnect(); LOG.info("Alluxio client (version {}) is trying to connect with {} @ {}", RuntimeConstants.VERSION, getServiceName(), mAddress); mChannel = GrpcChannelBuilder .newBuilder(new GrpcServerAddress(mAddress), mContext.getConf()) .setSubject(mContext.getSubject()) .build(); // Create stub for version service on host mVersionService = ServiceVersionClientServiceGrpc.newBlockingStub(mChannel); mConnected = true; afterConnect(); checkVersion(getServiceVersion()); LOG.info("Alluxio client (version {}) is connected with {} @ {}", RuntimeConstants.VERSION, getServiceName(), mAddress); return; } catch (IOException e) { LOG.warn("Failed to connect ({}) with {} @ {}: {}", retryPolicy.getAttemptCount(), getServiceName(), mAddress, e.getMessage()); lastConnectFailure = e; } } // Reaching here indicates that we did not successfully connect. if (mChannel != null) { mChannel.shutdown(); } if (mAddress == null) { throw new UnavailableException( String.format("Failed to determine address for %s after %s attempts", getServiceName(), retryPolicy.getAttemptCount())); } /** * Throw as-is if {@link UnauthenticatedException} occurred. */ if (lastConnectFailure instanceof UnauthenticatedException) { throw (AlluxioStatusException) lastConnectFailure; } throw new UnavailableException(String.format("Failed to connect to %s @ %s after %s attempts", getServiceName(), mAddress, retryPolicy.getAttemptCount()), lastConnectFailure); }
[ "@", "Override", "public", "synchronized", "void", "connect", "(", ")", "throws", "AlluxioStatusException", "{", "if", "(", "mConnected", ")", "{", "return", ";", "}", "disconnect", "(", ")", ";", "Preconditions", ".", "checkState", "(", "!", "mClosed", ",", "\"Client is closed, will not try to connect.\"", ")", ";", "IOException", "lastConnectFailure", "=", "null", ";", "RetryPolicy", "retryPolicy", "=", "mRetryPolicySupplier", ".", "get", "(", ")", ";", "while", "(", "retryPolicy", ".", "attempt", "(", ")", ")", "{", "if", "(", "mClosed", ")", "{", "throw", "new", "FailedPreconditionException", "(", "\"Failed to connect: client has been closed\"", ")", ";", "}", "// Re-query the address in each loop iteration in case it has changed (e.g. master", "// failover).", "try", "{", "mAddress", "=", "getAddress", "(", ")", ";", "}", "catch", "(", "UnavailableException", "e", ")", "{", "LOG", ".", "warn", "(", "\"Failed to determine {} rpc address ({}): {}\"", ",", "getServiceName", "(", ")", ",", "retryPolicy", ".", "getAttemptCount", "(", ")", ",", "e", ".", "toString", "(", ")", ")", ";", "continue", ";", "}", "if", "(", "mAddress", ".", "isUnresolved", "(", ")", ")", "{", "// Sometimes the acquired addressed wasn't resolved, retry resolving before", "// using it to connect.", "LOG", ".", "info", "(", "\"Retry resolving address {}\"", ",", "mAddress", ")", ";", "// Creates a new InetSocketAddress to force resolving the hostname again.", "mAddress", "=", "new", "InetSocketAddress", "(", "mAddress", ".", "getHostName", "(", ")", ",", "mAddress", ".", "getPort", "(", ")", ")", ";", "if", "(", "mAddress", ".", "isUnresolved", "(", ")", ")", "{", "LOG", ".", "warn", "(", "\"Failed to resolve address on retry {}\"", ",", "mAddress", ")", ";", "}", "}", "try", "{", "beforeConnect", "(", ")", ";", "LOG", ".", "info", "(", "\"Alluxio client (version {}) is trying to connect with {} @ {}\"", ",", "RuntimeConstants", ".", "VERSION", ",", "getServiceName", "(", ")", ",", "mAddress", ")", ";", "mChannel", "=", "GrpcChannelBuilder", ".", "newBuilder", "(", "new", "GrpcServerAddress", "(", "mAddress", ")", ",", "mContext", ".", "getConf", "(", ")", ")", ".", "setSubject", "(", "mContext", ".", "getSubject", "(", ")", ")", ".", "build", "(", ")", ";", "// Create stub for version service on host", "mVersionService", "=", "ServiceVersionClientServiceGrpc", ".", "newBlockingStub", "(", "mChannel", ")", ";", "mConnected", "=", "true", ";", "afterConnect", "(", ")", ";", "checkVersion", "(", "getServiceVersion", "(", ")", ")", ";", "LOG", ".", "info", "(", "\"Alluxio client (version {}) is connected with {} @ {}\"", ",", "RuntimeConstants", ".", "VERSION", ",", "getServiceName", "(", ")", ",", "mAddress", ")", ";", "return", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "warn", "(", "\"Failed to connect ({}) with {} @ {}: {}\"", ",", "retryPolicy", ".", "getAttemptCount", "(", ")", ",", "getServiceName", "(", ")", ",", "mAddress", ",", "e", ".", "getMessage", "(", ")", ")", ";", "lastConnectFailure", "=", "e", ";", "}", "}", "// Reaching here indicates that we did not successfully connect.", "if", "(", "mChannel", "!=", "null", ")", "{", "mChannel", ".", "shutdown", "(", ")", ";", "}", "if", "(", "mAddress", "==", "null", ")", "{", "throw", "new", "UnavailableException", "(", "String", ".", "format", "(", "\"Failed to determine address for %s after %s attempts\"", ",", "getServiceName", "(", ")", ",", "retryPolicy", ".", "getAttemptCount", "(", ")", ")", ")", ";", "}", "/**\n * Throw as-is if {@link UnauthenticatedException} occurred.\n */", "if", "(", "lastConnectFailure", "instanceof", "UnauthenticatedException", ")", "{", "throw", "(", "AlluxioStatusException", ")", "lastConnectFailure", ";", "}", "throw", "new", "UnavailableException", "(", "String", ".", "format", "(", "\"Failed to connect to %s @ %s after %s attempts\"", ",", "getServiceName", "(", ")", ",", "mAddress", ",", "retryPolicy", ".", "getAttemptCount", "(", ")", ")", ",", "lastConnectFailure", ")", ";", "}" ]
Connects with the remote.
[ "Connects", "with", "the", "remote", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/AbstractClient.java#L192-L269
18,732
Alluxio/alluxio
core/common/src/main/java/alluxio/AbstractClient.java
AbstractClient.disconnect
public synchronized void disconnect() { if (mConnected) { Preconditions.checkNotNull(mChannel, PreconditionMessage.CHANNEL_NULL_WHEN_CONNECTED); LOG.debug("Disconnecting from the {} @ {}", getServiceName(), mAddress); beforeDisconnect(); mChannel.shutdown(); mConnected = false; afterDisconnect(); } }
java
public synchronized void disconnect() { if (mConnected) { Preconditions.checkNotNull(mChannel, PreconditionMessage.CHANNEL_NULL_WHEN_CONNECTED); LOG.debug("Disconnecting from the {} @ {}", getServiceName(), mAddress); beforeDisconnect(); mChannel.shutdown(); mConnected = false; afterDisconnect(); } }
[ "public", "synchronized", "void", "disconnect", "(", ")", "{", "if", "(", "mConnected", ")", "{", "Preconditions", ".", "checkNotNull", "(", "mChannel", ",", "PreconditionMessage", ".", "CHANNEL_NULL_WHEN_CONNECTED", ")", ";", "LOG", ".", "debug", "(", "\"Disconnecting from the {} @ {}\"", ",", "getServiceName", "(", ")", ",", "mAddress", ")", ";", "beforeDisconnect", "(", ")", ";", "mChannel", ".", "shutdown", "(", ")", ";", "mConnected", "=", "false", ";", "afterDisconnect", "(", ")", ";", "}", "}" ]
Closes the connection with the Alluxio remote and does the necessary cleanup. It should be used if the client has not connected with the remote for a while, for example.
[ "Closes", "the", "connection", "with", "the", "Alluxio", "remote", "and", "does", "the", "necessary", "cleanup", ".", "It", "should", "be", "used", "if", "the", "client", "has", "not", "connected", "with", "the", "remote", "for", "a", "while", "for", "example", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/AbstractClient.java#L275-L284
18,733
Alluxio/alluxio
shell/src/main/java/alluxio/master/AlluxioMasterMonitor.java
AlluxioMasterMonitor.main
public static void main(String[] args) { if (args.length != 0) { LOG.warn("java -cp {} {}", RuntimeConstants.ALLUXIO_JAR, AlluxioMasterMonitor.class.getCanonicalName()); LOG.warn("ignoring arguments"); } AlluxioConfiguration alluxioConf = new InstancedConfiguration(ConfigurationUtils.defaults()); MasterHealthCheckClient.Builder builder = new MasterHealthCheckClient.Builder(alluxioConf); if (ConfigurationUtils.isHaMode(alluxioConf)) { builder.withProcessCheck(true); } else { builder.withProcessCheck(false); } HealthCheckClient client = builder.build(); if (!client.isServing()) { System.exit(1); } System.exit(0); }
java
public static void main(String[] args) { if (args.length != 0) { LOG.warn("java -cp {} {}", RuntimeConstants.ALLUXIO_JAR, AlluxioMasterMonitor.class.getCanonicalName()); LOG.warn("ignoring arguments"); } AlluxioConfiguration alluxioConf = new InstancedConfiguration(ConfigurationUtils.defaults()); MasterHealthCheckClient.Builder builder = new MasterHealthCheckClient.Builder(alluxioConf); if (ConfigurationUtils.isHaMode(alluxioConf)) { builder.withProcessCheck(true); } else { builder.withProcessCheck(false); } HealthCheckClient client = builder.build(); if (!client.isServing()) { System.exit(1); } System.exit(0); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", "!=", "0", ")", "{", "LOG", ".", "warn", "(", "\"java -cp {} {}\"", ",", "RuntimeConstants", ".", "ALLUXIO_JAR", ",", "AlluxioMasterMonitor", ".", "class", ".", "getCanonicalName", "(", ")", ")", ";", "LOG", ".", "warn", "(", "\"ignoring arguments\"", ")", ";", "}", "AlluxioConfiguration", "alluxioConf", "=", "new", "InstancedConfiguration", "(", "ConfigurationUtils", ".", "defaults", "(", ")", ")", ";", "MasterHealthCheckClient", ".", "Builder", "builder", "=", "new", "MasterHealthCheckClient", ".", "Builder", "(", "alluxioConf", ")", ";", "if", "(", "ConfigurationUtils", ".", "isHaMode", "(", "alluxioConf", ")", ")", "{", "builder", ".", "withProcessCheck", "(", "true", ")", ";", "}", "else", "{", "builder", ".", "withProcessCheck", "(", "false", ")", ";", "}", "HealthCheckClient", "client", "=", "builder", ".", "build", "(", ")", ";", "if", "(", "!", "client", ".", "isServing", "(", ")", ")", "{", "System", ".", "exit", "(", "1", ")", ";", "}", "System", ".", "exit", "(", "0", ")", ";", "}" ]
Starts the Alluxio master monitor. @param args command line arguments, should be empty
[ "Starts", "the", "Alluxio", "master", "monitor", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/master/AlluxioMasterMonitor.java#L41-L61
18,734
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/LsCommand.java
LsCommand.formatLsString
public static String formatLsString(boolean hSize, boolean acl, boolean isFolder, String permission, String userName, String groupName, long size, long lastModifiedTime, int inAlluxioPercentage, String persistenceState, String path, String dateFormatPattern) { String inAlluxioState; String sizeStr; if (isFolder) { inAlluxioState = IN_ALLUXIO_STATE_DIR; sizeStr = String.valueOf(size); } else { inAlluxioState = String.format(IN_ALLUXIO_STATE_FILE_FORMAT, inAlluxioPercentage); sizeStr = hSize ? FormatUtils.getSizeFromBytes(size) : String.valueOf(size); } if (acl) { return String.format(LS_FORMAT, permission, userName, groupName, sizeStr, persistenceState, CommonUtils.convertMsToDate(lastModifiedTime, dateFormatPattern), inAlluxioState, path); } else { return String.format(LS_FORMAT_NO_ACL, sizeStr, persistenceState, CommonUtils.convertMsToDate(lastModifiedTime, dateFormatPattern), inAlluxioState, path); } }
java
public static String formatLsString(boolean hSize, boolean acl, boolean isFolder, String permission, String userName, String groupName, long size, long lastModifiedTime, int inAlluxioPercentage, String persistenceState, String path, String dateFormatPattern) { String inAlluxioState; String sizeStr; if (isFolder) { inAlluxioState = IN_ALLUXIO_STATE_DIR; sizeStr = String.valueOf(size); } else { inAlluxioState = String.format(IN_ALLUXIO_STATE_FILE_FORMAT, inAlluxioPercentage); sizeStr = hSize ? FormatUtils.getSizeFromBytes(size) : String.valueOf(size); } if (acl) { return String.format(LS_FORMAT, permission, userName, groupName, sizeStr, persistenceState, CommonUtils.convertMsToDate(lastModifiedTime, dateFormatPattern), inAlluxioState, path); } else { return String.format(LS_FORMAT_NO_ACL, sizeStr, persistenceState, CommonUtils.convertMsToDate(lastModifiedTime, dateFormatPattern), inAlluxioState, path); } }
[ "public", "static", "String", "formatLsString", "(", "boolean", "hSize", ",", "boolean", "acl", ",", "boolean", "isFolder", ",", "String", "permission", ",", "String", "userName", ",", "String", "groupName", ",", "long", "size", ",", "long", "lastModifiedTime", ",", "int", "inAlluxioPercentage", ",", "String", "persistenceState", ",", "String", "path", ",", "String", "dateFormatPattern", ")", "{", "String", "inAlluxioState", ";", "String", "sizeStr", ";", "if", "(", "isFolder", ")", "{", "inAlluxioState", "=", "IN_ALLUXIO_STATE_DIR", ";", "sizeStr", "=", "String", ".", "valueOf", "(", "size", ")", ";", "}", "else", "{", "inAlluxioState", "=", "String", ".", "format", "(", "IN_ALLUXIO_STATE_FILE_FORMAT", ",", "inAlluxioPercentage", ")", ";", "sizeStr", "=", "hSize", "?", "FormatUtils", ".", "getSizeFromBytes", "(", "size", ")", ":", "String", ".", "valueOf", "(", "size", ")", ";", "}", "if", "(", "acl", ")", "{", "return", "String", ".", "format", "(", "LS_FORMAT", ",", "permission", ",", "userName", ",", "groupName", ",", "sizeStr", ",", "persistenceState", ",", "CommonUtils", ".", "convertMsToDate", "(", "lastModifiedTime", ",", "dateFormatPattern", ")", ",", "inAlluxioState", ",", "path", ")", ";", "}", "else", "{", "return", "String", ".", "format", "(", "LS_FORMAT_NO_ACL", ",", "sizeStr", ",", "persistenceState", ",", "CommonUtils", ".", "convertMsToDate", "(", "lastModifiedTime", ",", "dateFormatPattern", ")", ",", "inAlluxioState", ",", "path", ")", ";", "}", "}" ]
Formats the ls result string. @param hSize print human-readable format sizes @param acl whether security is enabled @param isFolder whether this path is a file or a folder @param permission permission string @param userName user name @param groupName group name @param size size of the file in bytes @param lastModifiedTime the epoch time in ms when the path is last modified @param inAlluxioPercentage whether the file is in Alluxio @param persistenceState the persistence state of the file @param path path of the file or folder @param dateFormatPattern the format to follow when printing dates @return the formatted string according to acl and isFolder
[ "Formats", "the", "ls", "result", "string", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/LsCommand.java#L150-L173
18,735
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/LsCommand.java
LsCommand.ls
private void ls(AlluxioURI path, boolean recursive, boolean forceLoadMetadata, boolean dirAsFile, boolean hSize, boolean pinnedOnly, String sortField, boolean reverse) throws AlluxioException, IOException { URIStatus pathStatus = mFileSystem.getStatus(path); if (dirAsFile) { if (pinnedOnly && !pathStatus.isPinned()) { return; } printLsString(pathStatus, hSize); return; } ListStatusPOptions.Builder optionsBuilder = ListStatusPOptions.newBuilder(); if (forceLoadMetadata) { optionsBuilder.setLoadMetadataType(LoadMetadataPType.ALWAYS); } optionsBuilder.setRecursive(recursive); // If list status takes too long, print the message Timer timer = new Timer(); if (pathStatus.isFolder()) { timer.schedule(new TimerTask() { @Override public void run() { System.out.printf("Getting directory status of %s files or sub-directories " + "may take a while.", pathStatus.getLength()); } }, 10000); } List<URIStatus> statuses = mFileSystem.listStatus(path, optionsBuilder.build()); timer.cancel(); List<URIStatus> sorted = sortByFieldAndOrder(statuses, sortField, reverse); for (URIStatus status : sorted) { if (!pinnedOnly || status.isPinned()) { printLsString(status, hSize); } } }
java
private void ls(AlluxioURI path, boolean recursive, boolean forceLoadMetadata, boolean dirAsFile, boolean hSize, boolean pinnedOnly, String sortField, boolean reverse) throws AlluxioException, IOException { URIStatus pathStatus = mFileSystem.getStatus(path); if (dirAsFile) { if (pinnedOnly && !pathStatus.isPinned()) { return; } printLsString(pathStatus, hSize); return; } ListStatusPOptions.Builder optionsBuilder = ListStatusPOptions.newBuilder(); if (forceLoadMetadata) { optionsBuilder.setLoadMetadataType(LoadMetadataPType.ALWAYS); } optionsBuilder.setRecursive(recursive); // If list status takes too long, print the message Timer timer = new Timer(); if (pathStatus.isFolder()) { timer.schedule(new TimerTask() { @Override public void run() { System.out.printf("Getting directory status of %s files or sub-directories " + "may take a while.", pathStatus.getLength()); } }, 10000); } List<URIStatus> statuses = mFileSystem.listStatus(path, optionsBuilder.build()); timer.cancel(); List<URIStatus> sorted = sortByFieldAndOrder(statuses, sortField, reverse); for (URIStatus status : sorted) { if (!pinnedOnly || status.isPinned()) { printLsString(status, hSize); } } }
[ "private", "void", "ls", "(", "AlluxioURI", "path", ",", "boolean", "recursive", ",", "boolean", "forceLoadMetadata", ",", "boolean", "dirAsFile", ",", "boolean", "hSize", ",", "boolean", "pinnedOnly", ",", "String", "sortField", ",", "boolean", "reverse", ")", "throws", "AlluxioException", ",", "IOException", "{", "URIStatus", "pathStatus", "=", "mFileSystem", ".", "getStatus", "(", "path", ")", ";", "if", "(", "dirAsFile", ")", "{", "if", "(", "pinnedOnly", "&&", "!", "pathStatus", ".", "isPinned", "(", ")", ")", "{", "return", ";", "}", "printLsString", "(", "pathStatus", ",", "hSize", ")", ";", "return", ";", "}", "ListStatusPOptions", ".", "Builder", "optionsBuilder", "=", "ListStatusPOptions", ".", "newBuilder", "(", ")", ";", "if", "(", "forceLoadMetadata", ")", "{", "optionsBuilder", ".", "setLoadMetadataType", "(", "LoadMetadataPType", ".", "ALWAYS", ")", ";", "}", "optionsBuilder", ".", "setRecursive", "(", "recursive", ")", ";", "// If list status takes too long, print the message", "Timer", "timer", "=", "new", "Timer", "(", ")", ";", "if", "(", "pathStatus", ".", "isFolder", "(", ")", ")", "{", "timer", ".", "schedule", "(", "new", "TimerTask", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "System", ".", "out", ".", "printf", "(", "\"Getting directory status of %s files or sub-directories \"", "+", "\"may take a while.\"", ",", "pathStatus", ".", "getLength", "(", ")", ")", ";", "}", "}", ",", "10000", ")", ";", "}", "List", "<", "URIStatus", ">", "statuses", "=", "mFileSystem", ".", "listStatus", "(", "path", ",", "optionsBuilder", ".", "build", "(", ")", ")", ";", "timer", ".", "cancel", "(", ")", ";", "List", "<", "URIStatus", ">", "sorted", "=", "sortByFieldAndOrder", "(", "statuses", ",", "sortField", ",", "reverse", ")", ";", "for", "(", "URIStatus", "status", ":", "sorted", ")", "{", "if", "(", "!", "pinnedOnly", "||", "status", ".", "isPinned", "(", ")", ")", "{", "printLsString", "(", "status", ",", "hSize", ")", ";", "}", "}", "}" ]
Displays information for all directories and files directly under the path specified in args. @param path The {@link AlluxioURI} path as the input of the command @param recursive Whether list the path recursively @param dirAsFile list the directory status as a plain file @param hSize print human-readable format sizes @param sortField sort the result by this field
[ "Displays", "information", "for", "all", "directories", "and", "files", "directly", "under", "the", "path", "specified", "in", "args", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/LsCommand.java#L227-L265
18,736
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.isActivelySynced
public boolean isActivelySynced(AlluxioURI path) { for (AlluxioURI syncedPath : mSyncPathList) { try { if (PathUtils.hasPrefix(path.getPath(), syncedPath.getPath())) { return true; } } catch (InvalidPathException e) { return false; } } return false; }
java
public boolean isActivelySynced(AlluxioURI path) { for (AlluxioURI syncedPath : mSyncPathList) { try { if (PathUtils.hasPrefix(path.getPath(), syncedPath.getPath())) { return true; } } catch (InvalidPathException e) { return false; } } return false; }
[ "public", "boolean", "isActivelySynced", "(", "AlluxioURI", "path", ")", "{", "for", "(", "AlluxioURI", "syncedPath", ":", "mSyncPathList", ")", "{", "try", "{", "if", "(", "PathUtils", ".", "hasPrefix", "(", "path", ".", "getPath", "(", ")", ",", "syncedPath", ".", "getPath", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "catch", "(", "InvalidPathException", "e", ")", "{", "return", "false", ";", "}", "}", "return", "false", ";", "}" ]
Check if a URI is actively synced. @param path path to check @return true if a URI is being actively synced
[ "Check", "if", "a", "URI", "is", "actively", "synced", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L124-L135
18,737
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.start
public void start() throws IOException { // Initialize UFS states for (AlluxioURI syncPoint : mSyncPathList) { MountTable.Resolution resolution = null; long mountId = 0; try { resolution = mMountTable.resolve(syncPoint); mountId = resolution.getMountId(); } catch (InvalidPathException e) { LOG.info("Invalid Path encountered during start up of ActiveSyncManager, " + "path {}, exception {}", syncPoint, e); continue; } try (CloseableResource<UnderFileSystem> ufsResource = resolution.acquireUfsResource()) { if (!ufsResource.get().supportsActiveSync()) { throw new UnsupportedOperationException("Active Sync is not supported on this UFS type: " + ufsResource.get().getUnderFSType()); } ufsResource.get().startSync(resolution.getUri()); } } // attempt to restart from a past txid, if this fails, it will result in MissingEventException // therefore forces a sync for (long mountId: mFilterMap.keySet()) { long txId = mStartingTxIdMap.getOrDefault(mountId, SyncInfo.INVALID_TXID); launchPollingThread(mountId, txId); try { if ((txId == SyncInfo.INVALID_TXID) && ServerConfiguration.getBoolean(PropertyKey.MASTER_ACTIVE_UFS_SYNC_INITIAL_SYNC)) { mExecutorService.submit( () -> mFilterMap.get(mountId).parallelStream().forEach( syncPoint -> { try { RetryUtils.retry("active sync during start", () -> mFileSystemMaster.activeSyncMetadata(syncPoint, null, getExecutor()), RetryUtils.defaultActiveSyncClientRetry(ServerConfiguration .getMs(PropertyKey.MASTER_ACTIVE_UFS_POLL_TIMEOUT))); } catch (IOException e) { LOG.warn("IOException encountered during active sync while starting {}", e); } } )); } } catch (Exception e) { LOG.warn("exception encountered during initial sync {}", e); } } }
java
public void start() throws IOException { // Initialize UFS states for (AlluxioURI syncPoint : mSyncPathList) { MountTable.Resolution resolution = null; long mountId = 0; try { resolution = mMountTable.resolve(syncPoint); mountId = resolution.getMountId(); } catch (InvalidPathException e) { LOG.info("Invalid Path encountered during start up of ActiveSyncManager, " + "path {}, exception {}", syncPoint, e); continue; } try (CloseableResource<UnderFileSystem> ufsResource = resolution.acquireUfsResource()) { if (!ufsResource.get().supportsActiveSync()) { throw new UnsupportedOperationException("Active Sync is not supported on this UFS type: " + ufsResource.get().getUnderFSType()); } ufsResource.get().startSync(resolution.getUri()); } } // attempt to restart from a past txid, if this fails, it will result in MissingEventException // therefore forces a sync for (long mountId: mFilterMap.keySet()) { long txId = mStartingTxIdMap.getOrDefault(mountId, SyncInfo.INVALID_TXID); launchPollingThread(mountId, txId); try { if ((txId == SyncInfo.INVALID_TXID) && ServerConfiguration.getBoolean(PropertyKey.MASTER_ACTIVE_UFS_SYNC_INITIAL_SYNC)) { mExecutorService.submit( () -> mFilterMap.get(mountId).parallelStream().forEach( syncPoint -> { try { RetryUtils.retry("active sync during start", () -> mFileSystemMaster.activeSyncMetadata(syncPoint, null, getExecutor()), RetryUtils.defaultActiveSyncClientRetry(ServerConfiguration .getMs(PropertyKey.MASTER_ACTIVE_UFS_POLL_TIMEOUT))); } catch (IOException e) { LOG.warn("IOException encountered during active sync while starting {}", e); } } )); } } catch (Exception e) { LOG.warn("exception encountered during initial sync {}", e); } } }
[ "public", "void", "start", "(", ")", "throws", "IOException", "{", "// Initialize UFS states", "for", "(", "AlluxioURI", "syncPoint", ":", "mSyncPathList", ")", "{", "MountTable", ".", "Resolution", "resolution", "=", "null", ";", "long", "mountId", "=", "0", ";", "try", "{", "resolution", "=", "mMountTable", ".", "resolve", "(", "syncPoint", ")", ";", "mountId", "=", "resolution", ".", "getMountId", "(", ")", ";", "}", "catch", "(", "InvalidPathException", "e", ")", "{", "LOG", ".", "info", "(", "\"Invalid Path encountered during start up of ActiveSyncManager, \"", "+", "\"path {}, exception {}\"", ",", "syncPoint", ",", "e", ")", ";", "continue", ";", "}", "try", "(", "CloseableResource", "<", "UnderFileSystem", ">", "ufsResource", "=", "resolution", ".", "acquireUfsResource", "(", ")", ")", "{", "if", "(", "!", "ufsResource", ".", "get", "(", ")", ".", "supportsActiveSync", "(", ")", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Active Sync is not supported on this UFS type: \"", "+", "ufsResource", ".", "get", "(", ")", ".", "getUnderFSType", "(", ")", ")", ";", "}", "ufsResource", ".", "get", "(", ")", ".", "startSync", "(", "resolution", ".", "getUri", "(", ")", ")", ";", "}", "}", "// attempt to restart from a past txid, if this fails, it will result in MissingEventException", "// therefore forces a sync", "for", "(", "long", "mountId", ":", "mFilterMap", ".", "keySet", "(", ")", ")", "{", "long", "txId", "=", "mStartingTxIdMap", ".", "getOrDefault", "(", "mountId", ",", "SyncInfo", ".", "INVALID_TXID", ")", ";", "launchPollingThread", "(", "mountId", ",", "txId", ")", ";", "try", "{", "if", "(", "(", "txId", "==", "SyncInfo", ".", "INVALID_TXID", ")", "&&", "ServerConfiguration", ".", "getBoolean", "(", "PropertyKey", ".", "MASTER_ACTIVE_UFS_SYNC_INITIAL_SYNC", ")", ")", "{", "mExecutorService", ".", "submit", "(", "(", ")", "->", "mFilterMap", ".", "get", "(", "mountId", ")", ".", "parallelStream", "(", ")", ".", "forEach", "(", "syncPoint", "->", "{", "try", "{", "RetryUtils", ".", "retry", "(", "\"active sync during start\"", ",", "(", ")", "->", "mFileSystemMaster", ".", "activeSyncMetadata", "(", "syncPoint", ",", "null", ",", "getExecutor", "(", ")", ")", ",", "RetryUtils", ".", "defaultActiveSyncClientRetry", "(", "ServerConfiguration", ".", "getMs", "(", "PropertyKey", ".", "MASTER_ACTIVE_UFS_POLL_TIMEOUT", ")", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "warn", "(", "\"IOException encountered during active sync while starting {}\"", ",", "e", ")", ";", "}", "}", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "warn", "(", "\"exception encountered during initial sync {}\"", ",", "e", ")", ";", "}", "}", "}" ]
start the polling threads.
[ "start", "the", "polling", "threads", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L150-L201
18,738
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.launchPollingThread
public void launchPollingThread(long mountId, long txId) { LOG.debug("launch polling thread for mount id {}, txId {}", mountId, txId); if (!mPollerMap.containsKey(mountId)) { try (CloseableResource<UnderFileSystem> ufsClient = mMountTable.getUfsClient(mountId).acquireUfsResource()) { ufsClient.get().startActiveSyncPolling(txId); } catch (IOException e) { LOG.warn("IO Exception trying to launch Polling thread {}", e); } ActiveSyncer syncer = new ActiveSyncer(mFileSystemMaster, this, mMountTable, mountId); Future<?> future = getExecutor().submit( new HeartbeatThread(HeartbeatContext.MASTER_ACTIVE_UFS_SYNC, syncer, (int) ServerConfiguration.getMs(PropertyKey.MASTER_ACTIVE_UFS_SYNC_INTERVAL), ServerConfiguration.global())); mPollerMap.put(mountId, future); } }
java
public void launchPollingThread(long mountId, long txId) { LOG.debug("launch polling thread for mount id {}, txId {}", mountId, txId); if (!mPollerMap.containsKey(mountId)) { try (CloseableResource<UnderFileSystem> ufsClient = mMountTable.getUfsClient(mountId).acquireUfsResource()) { ufsClient.get().startActiveSyncPolling(txId); } catch (IOException e) { LOG.warn("IO Exception trying to launch Polling thread {}", e); } ActiveSyncer syncer = new ActiveSyncer(mFileSystemMaster, this, mMountTable, mountId); Future<?> future = getExecutor().submit( new HeartbeatThread(HeartbeatContext.MASTER_ACTIVE_UFS_SYNC, syncer, (int) ServerConfiguration.getMs(PropertyKey.MASTER_ACTIVE_UFS_SYNC_INTERVAL), ServerConfiguration.global())); mPollerMap.put(mountId, future); } }
[ "public", "void", "launchPollingThread", "(", "long", "mountId", ",", "long", "txId", ")", "{", "LOG", ".", "debug", "(", "\"launch polling thread for mount id {}, txId {}\"", ",", "mountId", ",", "txId", ")", ";", "if", "(", "!", "mPollerMap", ".", "containsKey", "(", "mountId", ")", ")", "{", "try", "(", "CloseableResource", "<", "UnderFileSystem", ">", "ufsClient", "=", "mMountTable", ".", "getUfsClient", "(", "mountId", ")", ".", "acquireUfsResource", "(", ")", ")", "{", "ufsClient", ".", "get", "(", ")", ".", "startActiveSyncPolling", "(", "txId", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "warn", "(", "\"IO Exception trying to launch Polling thread {}\"", ",", "e", ")", ";", "}", "ActiveSyncer", "syncer", "=", "new", "ActiveSyncer", "(", "mFileSystemMaster", ",", "this", ",", "mMountTable", ",", "mountId", ")", ";", "Future", "<", "?", ">", "future", "=", "getExecutor", "(", ")", ".", "submit", "(", "new", "HeartbeatThread", "(", "HeartbeatContext", ".", "MASTER_ACTIVE_UFS_SYNC", ",", "syncer", ",", "(", "int", ")", "ServerConfiguration", ".", "getMs", "(", "PropertyKey", ".", "MASTER_ACTIVE_UFS_SYNC_INTERVAL", ")", ",", "ServerConfiguration", ".", "global", "(", ")", ")", ")", ";", "mPollerMap", ".", "put", "(", "mountId", ",", "future", ")", ";", "}", "}" ]
Launches polling thread on a particular mount point with starting txId. @param mountId launch polling thread on a mount id @param txId specifies the transaction id to initialize the pollling thread
[ "Launches", "polling", "thread", "on", "a", "particular", "mount", "point", "with", "starting", "txId", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L209-L225
18,739
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.applyAndJournal
public void applyAndJournal(Supplier<JournalContext> context, AddSyncPointEntry entry) { try { apply(entry); context.get().append(Journal.JournalEntry.newBuilder().setAddSyncPoint(entry).build()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } }
java
public void applyAndJournal(Supplier<JournalContext> context, AddSyncPointEntry entry) { try { apply(entry); context.get().append(Journal.JournalEntry.newBuilder().setAddSyncPoint(entry).build()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } }
[ "public", "void", "applyAndJournal", "(", "Supplier", "<", "JournalContext", ">", "context", ",", "AddSyncPointEntry", "entry", ")", "{", "try", "{", "apply", "(", "entry", ")", ";", "context", ".", "get", "(", ")", ".", "append", "(", "Journal", ".", "JournalEntry", ".", "newBuilder", "(", ")", ".", "setAddSyncPoint", "(", "entry", ")", ".", "build", "(", ")", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "ProcessUtils", ".", "fatalError", "(", "LOG", ",", "t", ",", "\"Failed to apply %s\"", ",", "entry", ")", ";", "throw", "t", ";", "// fatalError will usually system.exit", "}", "}" ]
Apply AddSyncPoint entry and journal the entry. @param context journal context @param entry addSyncPoint entry
[ "Apply", "AddSyncPoint", "entry", "and", "journal", "the", "entry", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L232-L240
18,740
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.stopSyncForMount
public void stopSyncForMount(long mountId) throws InvalidPathException, IOException { LOG.debug("Stop sync for mount id {}", mountId); if (mFilterMap.containsKey(mountId)) { List<Pair<AlluxioURI, MountTable.Resolution>> toBeDeleted = new ArrayList<>(); for (AlluxioURI uri : mFilterMap.get(mountId)) { MountTable.Resolution resolution = resolveSyncPoint(uri); if (resolution != null) { toBeDeleted.add(new Pair<>(uri, resolution)); } } // Calling stopSyncInternal outside of the traversal of mFilterMap.get(mountId) to avoid // ConcurrentModificationException for (Pair<AlluxioURI, MountTable.Resolution> deleteInfo : toBeDeleted) { stopSyncInternal(deleteInfo.getFirst(), deleteInfo.getSecond()); } } }
java
public void stopSyncForMount(long mountId) throws InvalidPathException, IOException { LOG.debug("Stop sync for mount id {}", mountId); if (mFilterMap.containsKey(mountId)) { List<Pair<AlluxioURI, MountTable.Resolution>> toBeDeleted = new ArrayList<>(); for (AlluxioURI uri : mFilterMap.get(mountId)) { MountTable.Resolution resolution = resolveSyncPoint(uri); if (resolution != null) { toBeDeleted.add(new Pair<>(uri, resolution)); } } // Calling stopSyncInternal outside of the traversal of mFilterMap.get(mountId) to avoid // ConcurrentModificationException for (Pair<AlluxioURI, MountTable.Resolution> deleteInfo : toBeDeleted) { stopSyncInternal(deleteInfo.getFirst(), deleteInfo.getSecond()); } } }
[ "public", "void", "stopSyncForMount", "(", "long", "mountId", ")", "throws", "InvalidPathException", ",", "IOException", "{", "LOG", ".", "debug", "(", "\"Stop sync for mount id {}\"", ",", "mountId", ")", ";", "if", "(", "mFilterMap", ".", "containsKey", "(", "mountId", ")", ")", "{", "List", "<", "Pair", "<", "AlluxioURI", ",", "MountTable", ".", "Resolution", ">", ">", "toBeDeleted", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "AlluxioURI", "uri", ":", "mFilterMap", ".", "get", "(", "mountId", ")", ")", "{", "MountTable", ".", "Resolution", "resolution", "=", "resolveSyncPoint", "(", "uri", ")", ";", "if", "(", "resolution", "!=", "null", ")", "{", "toBeDeleted", ".", "add", "(", "new", "Pair", "<>", "(", "uri", ",", "resolution", ")", ")", ";", "}", "}", "// Calling stopSyncInternal outside of the traversal of mFilterMap.get(mountId) to avoid", "// ConcurrentModificationException", "for", "(", "Pair", "<", "AlluxioURI", ",", "MountTable", ".", "Resolution", ">", "deleteInfo", ":", "toBeDeleted", ")", "{", "stopSyncInternal", "(", "deleteInfo", ".", "getFirst", "(", ")", ",", "deleteInfo", ".", "getSecond", "(", ")", ")", ";", "}", "}", "}" ]
stop active sync on a mount id. @param mountId mountId to stop active sync
[ "stop", "active", "sync", "on", "a", "mount", "id", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L262-L278
18,741
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.resolveSyncPoint
@Nullable public MountTable.Resolution resolveSyncPoint(AlluxioURI syncPoint) throws InvalidPathException { if (!mSyncPathList.contains(syncPoint)) { LOG.debug("syncPoint not found {}", syncPoint.getPath()); return null; } MountTable.Resolution resolution = mMountTable.resolve(syncPoint); return resolution; }
java
@Nullable public MountTable.Resolution resolveSyncPoint(AlluxioURI syncPoint) throws InvalidPathException { if (!mSyncPathList.contains(syncPoint)) { LOG.debug("syncPoint not found {}", syncPoint.getPath()); return null; } MountTable.Resolution resolution = mMountTable.resolve(syncPoint); return resolution; }
[ "@", "Nullable", "public", "MountTable", ".", "Resolution", "resolveSyncPoint", "(", "AlluxioURI", "syncPoint", ")", "throws", "InvalidPathException", "{", "if", "(", "!", "mSyncPathList", ".", "contains", "(", "syncPoint", ")", ")", "{", "LOG", ".", "debug", "(", "\"syncPoint not found {}\"", ",", "syncPoint", ".", "getPath", "(", ")", ")", ";", "return", "null", ";", "}", "MountTable", ".", "Resolution", "resolution", "=", "mMountTable", ".", "resolve", "(", "syncPoint", ")", ";", "return", "resolution", ";", "}" ]
Perform various checks of stopping a sync point. @param syncPoint sync point to stop @return the path resolution result if successfully passed all checks
[ "Perform", "various", "checks", "of", "stopping", "a", "sync", "point", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L287-L295
18,742
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.stopSyncInternal
public void stopSyncInternal(AlluxioURI syncPoint, MountTable.Resolution resolution) { try (LockResource r = new LockResource(mSyncManagerLock)) { LOG.debug("stop syncPoint {}", syncPoint.getPath()); RemoveSyncPointEntry removeSyncPoint = File.RemoveSyncPointEntry.newBuilder() .setSyncpointPath(syncPoint.toString()) .setMountId(resolution.getMountId()) .build(); apply(removeSyncPoint); try { stopSyncPostJournal(syncPoint); } catch (Throwable e) { // revert state; AddSyncPointEntry addSyncPoint = File.AddSyncPointEntry.newBuilder() .setSyncpointPath(syncPoint.toString()).build(); apply(addSyncPoint); recoverFromStopSync(syncPoint, resolution.getMountId()); } } }
java
public void stopSyncInternal(AlluxioURI syncPoint, MountTable.Resolution resolution) { try (LockResource r = new LockResource(mSyncManagerLock)) { LOG.debug("stop syncPoint {}", syncPoint.getPath()); RemoveSyncPointEntry removeSyncPoint = File.RemoveSyncPointEntry.newBuilder() .setSyncpointPath(syncPoint.toString()) .setMountId(resolution.getMountId()) .build(); apply(removeSyncPoint); try { stopSyncPostJournal(syncPoint); } catch (Throwable e) { // revert state; AddSyncPointEntry addSyncPoint = File.AddSyncPointEntry.newBuilder() .setSyncpointPath(syncPoint.toString()).build(); apply(addSyncPoint); recoverFromStopSync(syncPoint, resolution.getMountId()); } } }
[ "public", "void", "stopSyncInternal", "(", "AlluxioURI", "syncPoint", ",", "MountTable", ".", "Resolution", "resolution", ")", "{", "try", "(", "LockResource", "r", "=", "new", "LockResource", "(", "mSyncManagerLock", ")", ")", "{", "LOG", ".", "debug", "(", "\"stop syncPoint {}\"", ",", "syncPoint", ".", "getPath", "(", ")", ")", ";", "RemoveSyncPointEntry", "removeSyncPoint", "=", "File", ".", "RemoveSyncPointEntry", ".", "newBuilder", "(", ")", ".", "setSyncpointPath", "(", "syncPoint", ".", "toString", "(", ")", ")", ".", "setMountId", "(", "resolution", ".", "getMountId", "(", ")", ")", ".", "build", "(", ")", ";", "apply", "(", "removeSyncPoint", ")", ";", "try", "{", "stopSyncPostJournal", "(", "syncPoint", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "// revert state;", "AddSyncPointEntry", "addSyncPoint", "=", "File", ".", "AddSyncPointEntry", ".", "newBuilder", "(", ")", ".", "setSyncpointPath", "(", "syncPoint", ".", "toString", "(", ")", ")", ".", "build", "(", ")", ";", "apply", "(", "addSyncPoint", ")", ";", "recoverFromStopSync", "(", "syncPoint", ",", "resolution", ".", "getMountId", "(", ")", ")", ";", "}", "}", "}" ]
stop active sync on a URI. @param syncPoint sync point to be stopped @param resolution path resolution for the sync point
[ "stop", "active", "sync", "on", "a", "URI", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L302-L321
18,743
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.getSyncPathList
public List<SyncPointInfo> getSyncPathList() { List<SyncPointInfo> returnList = new ArrayList<>(); for (AlluxioURI uri: mSyncPathList) { SyncPointInfo.SyncStatus status; Future<?> syncStatus = mSyncPathStatus.get(uri); if (syncStatus == null) { status = SyncPointInfo.SyncStatus.NOT_INITIALLY_SYNCED; } else if (syncStatus.isDone()) { status = SyncPointInfo.SyncStatus.INITIALLY_SYNCED; } else { status = SyncPointInfo.SyncStatus.SYNCING; } returnList.add(new SyncPointInfo(uri, status)); } return returnList; }
java
public List<SyncPointInfo> getSyncPathList() { List<SyncPointInfo> returnList = new ArrayList<>(); for (AlluxioURI uri: mSyncPathList) { SyncPointInfo.SyncStatus status; Future<?> syncStatus = mSyncPathStatus.get(uri); if (syncStatus == null) { status = SyncPointInfo.SyncStatus.NOT_INITIALLY_SYNCED; } else if (syncStatus.isDone()) { status = SyncPointInfo.SyncStatus.INITIALLY_SYNCED; } else { status = SyncPointInfo.SyncStatus.SYNCING; } returnList.add(new SyncPointInfo(uri, status)); } return returnList; }
[ "public", "List", "<", "SyncPointInfo", ">", "getSyncPathList", "(", ")", "{", "List", "<", "SyncPointInfo", ">", "returnList", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "AlluxioURI", "uri", ":", "mSyncPathList", ")", "{", "SyncPointInfo", ".", "SyncStatus", "status", ";", "Future", "<", "?", ">", "syncStatus", "=", "mSyncPathStatus", ".", "get", "(", "uri", ")", ";", "if", "(", "syncStatus", "==", "null", ")", "{", "status", "=", "SyncPointInfo", ".", "SyncStatus", ".", "NOT_INITIALLY_SYNCED", ";", "}", "else", "if", "(", "syncStatus", ".", "isDone", "(", ")", ")", "{", "status", "=", "SyncPointInfo", ".", "SyncStatus", ".", "INITIALLY_SYNCED", ";", "}", "else", "{", "status", "=", "SyncPointInfo", ".", "SyncStatus", ".", "SYNCING", ";", "}", "returnList", ".", "add", "(", "new", "SyncPointInfo", "(", "uri", ",", "status", ")", ")", ";", "}", "return", "returnList", ";", "}" ]
Get the sync point list. @return a list of URIs (sync points)
[ "Get", "the", "sync", "point", "list", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L338-L353
18,744
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.stopSyncPostJournal
public void stopSyncPostJournal(AlluxioURI syncPoint) throws InvalidPathException { MountTable.Resolution resolution = mMountTable.resolve(syncPoint); long mountId = resolution.getMountId(); // Remove initial sync thread Future<?> syncFuture = mSyncPathStatus.remove(syncPoint); if (syncFuture != null) { syncFuture.cancel(true); } if (mFilterMap.get(mountId).isEmpty()) { // syncPoint removed was the last syncPoint for the mountId mFilterMap.remove(mountId); Future<?> future = mPollerMap.remove(mountId); if (future != null) { future.cancel(true); } } // Tell UFS to stop monitoring the path try (CloseableResource<UnderFileSystem> ufs = resolution.acquireUfsResource()) { ufs.get().stopSync(resolution.getUri()); } catch (IOException e) { LOG.info("Ufs IOException for uri {}, exception is {}", syncPoint, e); } // Stop active sync polling on a particular UFS if it is the last sync point if (mFilterMap.containsKey(mountId) && mFilterMap.get(mountId).isEmpty()) { try (CloseableResource<UnderFileSystem> ufs = resolution.acquireUfsResource()) { ufs.get().stopActiveSyncPolling(); } catch (IOException e) { LOG.warn("Encountered IOException when trying to stop polling thread {}", e); } } }
java
public void stopSyncPostJournal(AlluxioURI syncPoint) throws InvalidPathException { MountTable.Resolution resolution = mMountTable.resolve(syncPoint); long mountId = resolution.getMountId(); // Remove initial sync thread Future<?> syncFuture = mSyncPathStatus.remove(syncPoint); if (syncFuture != null) { syncFuture.cancel(true); } if (mFilterMap.get(mountId).isEmpty()) { // syncPoint removed was the last syncPoint for the mountId mFilterMap.remove(mountId); Future<?> future = mPollerMap.remove(mountId); if (future != null) { future.cancel(true); } } // Tell UFS to stop monitoring the path try (CloseableResource<UnderFileSystem> ufs = resolution.acquireUfsResource()) { ufs.get().stopSync(resolution.getUri()); } catch (IOException e) { LOG.info("Ufs IOException for uri {}, exception is {}", syncPoint, e); } // Stop active sync polling on a particular UFS if it is the last sync point if (mFilterMap.containsKey(mountId) && mFilterMap.get(mountId).isEmpty()) { try (CloseableResource<UnderFileSystem> ufs = resolution.acquireUfsResource()) { ufs.get().stopActiveSyncPolling(); } catch (IOException e) { LOG.warn("Encountered IOException when trying to stop polling thread {}", e); } } }
[ "public", "void", "stopSyncPostJournal", "(", "AlluxioURI", "syncPoint", ")", "throws", "InvalidPathException", "{", "MountTable", ".", "Resolution", "resolution", "=", "mMountTable", ".", "resolve", "(", "syncPoint", ")", ";", "long", "mountId", "=", "resolution", ".", "getMountId", "(", ")", ";", "// Remove initial sync thread", "Future", "<", "?", ">", "syncFuture", "=", "mSyncPathStatus", ".", "remove", "(", "syncPoint", ")", ";", "if", "(", "syncFuture", "!=", "null", ")", "{", "syncFuture", ".", "cancel", "(", "true", ")", ";", "}", "if", "(", "mFilterMap", ".", "get", "(", "mountId", ")", ".", "isEmpty", "(", ")", ")", "{", "// syncPoint removed was the last syncPoint for the mountId", "mFilterMap", ".", "remove", "(", "mountId", ")", ";", "Future", "<", "?", ">", "future", "=", "mPollerMap", ".", "remove", "(", "mountId", ")", ";", "if", "(", "future", "!=", "null", ")", "{", "future", ".", "cancel", "(", "true", ")", ";", "}", "}", "// Tell UFS to stop monitoring the path", "try", "(", "CloseableResource", "<", "UnderFileSystem", ">", "ufs", "=", "resolution", ".", "acquireUfsResource", "(", ")", ")", "{", "ufs", ".", "get", "(", ")", ".", "stopSync", "(", "resolution", ".", "getUri", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "info", "(", "\"Ufs IOException for uri {}, exception is {}\"", ",", "syncPoint", ",", "e", ")", ";", "}", "// Stop active sync polling on a particular UFS if it is the last sync point", "if", "(", "mFilterMap", ".", "containsKey", "(", "mountId", ")", "&&", "mFilterMap", ".", "get", "(", "mountId", ")", ".", "isEmpty", "(", ")", ")", "{", "try", "(", "CloseableResource", "<", "UnderFileSystem", ">", "ufs", "=", "resolution", ".", "acquireUfsResource", "(", ")", ")", "{", "ufs", ".", "get", "(", ")", ".", "stopActiveSyncPolling", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "warn", "(", "\"Encountered IOException when trying to stop polling thread {}\"", ",", "e", ")", ";", "}", "}", "}" ]
Clean up tasks to stop sync point after we have journaled. @param syncPoint the sync point to stop @throws InvalidPathException
[ "Clean", "up", "tasks", "to", "stop", "sync", "point", "after", "we", "have", "journaled", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L457-L490
18,745
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.startSyncPostJournal
public void startSyncPostJournal(AlluxioURI uri) throws InvalidPathException { MountTable.Resolution resolution = mMountTable.resolve(uri); startInitSync(uri, resolution); launchPollingThread(resolution.getMountId(), SyncInfo.INVALID_TXID); }
java
public void startSyncPostJournal(AlluxioURI uri) throws InvalidPathException { MountTable.Resolution resolution = mMountTable.resolve(uri); startInitSync(uri, resolution); launchPollingThread(resolution.getMountId(), SyncInfo.INVALID_TXID); }
[ "public", "void", "startSyncPostJournal", "(", "AlluxioURI", "uri", ")", "throws", "InvalidPathException", "{", "MountTable", ".", "Resolution", "resolution", "=", "mMountTable", ".", "resolve", "(", "uri", ")", ";", "startInitSync", "(", "uri", ",", "resolution", ")", ";", "launchPollingThread", "(", "resolution", ".", "getMountId", "(", ")", ",", "SyncInfo", ".", "INVALID_TXID", ")", ";", "}" ]
Continue to start sync after we have journaled the operation. @param uri the sync point that we are trying to start
[ "Continue", "to", "start", "sync", "after", "we", "have", "journaled", "the", "operation", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L622-L626
18,746
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.recoverFromStopSync
public void recoverFromStopSync(AlluxioURI uri, long mountId) { if (mSyncPathStatus.containsKey(uri)) { // nothing to recover from, since the syncPathStatus still contains syncPoint return; } try { // the init sync thread has been removed, to reestablish sync, we need to sync again MountTable.Resolution resolution = mMountTable.resolve(uri); startInitSync(uri, resolution); launchPollingThread(resolution.getMountId(), SyncInfo.INVALID_TXID); } catch (Throwable t) { LOG.warn("Recovering from stop syncing failed {}", t); } }
java
public void recoverFromStopSync(AlluxioURI uri, long mountId) { if (mSyncPathStatus.containsKey(uri)) { // nothing to recover from, since the syncPathStatus still contains syncPoint return; } try { // the init sync thread has been removed, to reestablish sync, we need to sync again MountTable.Resolution resolution = mMountTable.resolve(uri); startInitSync(uri, resolution); launchPollingThread(resolution.getMountId(), SyncInfo.INVALID_TXID); } catch (Throwable t) { LOG.warn("Recovering from stop syncing failed {}", t); } }
[ "public", "void", "recoverFromStopSync", "(", "AlluxioURI", "uri", ",", "long", "mountId", ")", "{", "if", "(", "mSyncPathStatus", ".", "containsKey", "(", "uri", ")", ")", "{", "// nothing to recover from, since the syncPathStatus still contains syncPoint", "return", ";", "}", "try", "{", "// the init sync thread has been removed, to reestablish sync, we need to sync again", "MountTable", ".", "Resolution", "resolution", "=", "mMountTable", ".", "resolve", "(", "uri", ")", ";", "startInitSync", "(", "uri", ",", "resolution", ")", ";", "launchPollingThread", "(", "resolution", ".", "getMountId", "(", ")", ",", "SyncInfo", ".", "INVALID_TXID", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "LOG", ".", "warn", "(", "\"Recovering from stop syncing failed {}\"", ",", "t", ")", ";", "}", "}" ]
Recover from a stop sync operation. @param uri uri to stop sync @param mountId mount id of the uri
[ "Recover", "from", "a", "stop", "sync", "operation", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L634-L647
18,747
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.recoverFromStartSync
public void recoverFromStartSync(AlluxioURI uri, long mountId) { // if the init sync has been launched, we need to stop it if (mSyncPathStatus.containsKey(uri)) { Future<?> syncFuture = mSyncPathStatus.remove(uri); if (syncFuture != null) { syncFuture.cancel(true); } } // if the polling thread has been launched, we need to stop it mFilterMap.remove(mountId); Future<?> future = mPollerMap.remove(mountId); if (future != null) { future.cancel(true); } }
java
public void recoverFromStartSync(AlluxioURI uri, long mountId) { // if the init sync has been launched, we need to stop it if (mSyncPathStatus.containsKey(uri)) { Future<?> syncFuture = mSyncPathStatus.remove(uri); if (syncFuture != null) { syncFuture.cancel(true); } } // if the polling thread has been launched, we need to stop it mFilterMap.remove(mountId); Future<?> future = mPollerMap.remove(mountId); if (future != null) { future.cancel(true); } }
[ "public", "void", "recoverFromStartSync", "(", "AlluxioURI", "uri", ",", "long", "mountId", ")", "{", "// if the init sync has been launched, we need to stop it", "if", "(", "mSyncPathStatus", ".", "containsKey", "(", "uri", ")", ")", "{", "Future", "<", "?", ">", "syncFuture", "=", "mSyncPathStatus", ".", "remove", "(", "uri", ")", ";", "if", "(", "syncFuture", "!=", "null", ")", "{", "syncFuture", ".", "cancel", "(", "true", ")", ";", "}", "}", "// if the polling thread has been launched, we need to stop it", "mFilterMap", ".", "remove", "(", "mountId", ")", ";", "Future", "<", "?", ">", "future", "=", "mPollerMap", ".", "remove", "(", "mountId", ")", ";", "if", "(", "future", "!=", "null", ")", "{", "future", ".", "cancel", "(", "true", ")", ";", "}", "}" ]
Recover from start sync operation. @param uri uri to start sync @param mountId mount id of the uri
[ "Recover", "from", "start", "sync", "operation", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L655-L670
18,748
Alluxio/alluxio
core/common/src/main/java/alluxio/util/webui/WebUtils.java
WebUtils.convertByteArrayToStringWithoutEscape
public static String convertByteArrayToStringWithoutEscape(byte[] data, int offset, int length) { StringBuilder sb = new StringBuilder(length); for (int i = offset; i < length && i < data.length; i++) { sb.append((char) data[i]); } return sb.toString(); }
java
public static String convertByteArrayToStringWithoutEscape(byte[] data, int offset, int length) { StringBuilder sb = new StringBuilder(length); for (int i = offset; i < length && i < data.length; i++) { sb.append((char) data[i]); } return sb.toString(); }
[ "public", "static", "String", "convertByteArrayToStringWithoutEscape", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "length", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "length", ")", ";", "for", "(", "int", "i", "=", "offset", ";", "i", "<", "length", "&&", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "sb", ".", "append", "(", "(", "char", ")", "data", "[", "i", "]", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Converts a byte array to string. @param data byte array @param offset offset @param length number of bytes to encode @return string representation of the encoded byte sub-array
[ "Converts", "a", "byte", "array", "to", "string", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/webui/WebUtils.java#L37-L43
18,749
Alluxio/alluxio
core/common/src/main/java/alluxio/util/webui/WebUtils.java
WebUtils.convertMsToShortClockTime
public static String convertMsToShortClockTime(long millis) { Preconditions.checkArgument(millis >= 0, "Negative values are not supported"); long days = millis / Constants.DAY_MS; long hours = (millis % Constants.DAY_MS) / Constants.HOUR_MS; long mins = (millis % Constants.HOUR_MS) / Constants.MINUTE_MS; long secs = (millis % Constants.MINUTE_MS) / Constants.SECOND_MS; return String.format("%d d, %d h, %d m, and %d s", days, hours, mins, secs); }
java
public static String convertMsToShortClockTime(long millis) { Preconditions.checkArgument(millis >= 0, "Negative values are not supported"); long days = millis / Constants.DAY_MS; long hours = (millis % Constants.DAY_MS) / Constants.HOUR_MS; long mins = (millis % Constants.HOUR_MS) / Constants.MINUTE_MS; long secs = (millis % Constants.MINUTE_MS) / Constants.SECOND_MS; return String.format("%d d, %d h, %d m, and %d s", days, hours, mins, secs); }
[ "public", "static", "String", "convertMsToShortClockTime", "(", "long", "millis", ")", "{", "Preconditions", ".", "checkArgument", "(", "millis", ">=", "0", ",", "\"Negative values are not supported\"", ")", ";", "long", "days", "=", "millis", "/", "Constants", ".", "DAY_MS", ";", "long", "hours", "=", "(", "millis", "%", "Constants", ".", "DAY_MS", ")", "/", "Constants", ".", "HOUR_MS", ";", "long", "mins", "=", "(", "millis", "%", "Constants", ".", "HOUR_MS", ")", "/", "Constants", ".", "MINUTE_MS", ";", "long", "secs", "=", "(", "millis", "%", "Constants", ".", "MINUTE_MS", ")", "/", "Constants", ".", "SECOND_MS", ";", "return", "String", ".", "format", "(", "\"%d d, %d h, %d m, and %d s\"", ",", "days", ",", "hours", ",", "mins", ",", "secs", ")", ";", "}" ]
Converts milliseconds to short clock time. @param millis milliseconds @return input encoded as short clock time
[ "Converts", "milliseconds", "to", "short", "clock", "time", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/webui/WebUtils.java#L51-L60
18,750
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CheckConsistencyCommand.java
CheckConsistencyCommand.checkConsistency
List<AlluxioURI> checkConsistency(AlluxioURI path, CheckConsistencyPOptions options) throws IOException { FileSystemMasterClient client = mFsContext.acquireMasterClient(); try { return client.checkConsistency(path, options); } finally { mFsContext.releaseMasterClient(client); } }
java
List<AlluxioURI> checkConsistency(AlluxioURI path, CheckConsistencyPOptions options) throws IOException { FileSystemMasterClient client = mFsContext.acquireMasterClient(); try { return client.checkConsistency(path, options); } finally { mFsContext.releaseMasterClient(client); } }
[ "List", "<", "AlluxioURI", ">", "checkConsistency", "(", "AlluxioURI", "path", ",", "CheckConsistencyPOptions", "options", ")", "throws", "IOException", "{", "FileSystemMasterClient", "client", "=", "mFsContext", ".", "acquireMasterClient", "(", ")", ";", "try", "{", "return", "client", ".", "checkConsistency", "(", "path", ",", "options", ")", ";", "}", "finally", "{", "mFsContext", ".", "releaseMasterClient", "(", "client", ")", ";", "}", "}" ]
Checks the consistency of Alluxio metadata against the under storage for all files and directories in a given subtree. @param path the root of the subtree to check @return a list of inconsistent files and directories
[ "Checks", "the", "consistency", "of", "Alluxio", "metadata", "against", "the", "under", "storage", "for", "all", "files", "and", "directories", "in", "a", "given", "subtree", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CheckConsistencyCommand.java#L90-L98
18,751
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CheckConsistencyCommand.java
CheckConsistencyCommand.runConsistencyCheck
private void runConsistencyCheck(AlluxioURI path, boolean repairConsistency) throws AlluxioException, IOException { List<AlluxioURI> inconsistentUris = checkConsistency(path, FileSystemOptions.checkConsistencyDefaults( mFsContext.getPathConf(path))); if (inconsistentUris.isEmpty()) { System.out.println(path + " is consistent with the under storage system."); return; } if (!repairConsistency) { Collections.sort(inconsistentUris); System.out.println("The following files are inconsistent:"); for (AlluxioURI uri : inconsistentUris) { System.out.println(uri); } } else { Collections.sort(inconsistentUris); System.out.println(path + " has: " + inconsistentUris.size() + " inconsistent files."); List<AlluxioURI> inconsistentDirs = new ArrayList<AlluxioURI>(); for (AlluxioURI inconsistentUri : inconsistentUris) { URIStatus status = mFileSystem.getStatus(inconsistentUri); if (status.isFolder()) { inconsistentDirs.add(inconsistentUri); continue; } System.out.println("repairing path: " + inconsistentUri); DeletePOptions deleteOptions = DeletePOptions.newBuilder().setAlluxioOnly(true).build(); mFileSystem.delete(inconsistentUri, deleteOptions); mFileSystem.exists(inconsistentUri); System.out.println(inconsistentUri + " repaired"); System.out.println(); } for (AlluxioURI uri : inconsistentDirs) { DeletePOptions deleteOptions = DeletePOptions.newBuilder().setAlluxioOnly(true).setRecursive(true).build(); System.out.println("repairing path: " + uri); mFileSystem.delete(uri, deleteOptions); mFileSystem.exists(uri); System.out.println(uri + "repaired"); System.out.println(); } } }
java
private void runConsistencyCheck(AlluxioURI path, boolean repairConsistency) throws AlluxioException, IOException { List<AlluxioURI> inconsistentUris = checkConsistency(path, FileSystemOptions.checkConsistencyDefaults( mFsContext.getPathConf(path))); if (inconsistentUris.isEmpty()) { System.out.println(path + " is consistent with the under storage system."); return; } if (!repairConsistency) { Collections.sort(inconsistentUris); System.out.println("The following files are inconsistent:"); for (AlluxioURI uri : inconsistentUris) { System.out.println(uri); } } else { Collections.sort(inconsistentUris); System.out.println(path + " has: " + inconsistentUris.size() + " inconsistent files."); List<AlluxioURI> inconsistentDirs = new ArrayList<AlluxioURI>(); for (AlluxioURI inconsistentUri : inconsistentUris) { URIStatus status = mFileSystem.getStatus(inconsistentUri); if (status.isFolder()) { inconsistentDirs.add(inconsistentUri); continue; } System.out.println("repairing path: " + inconsistentUri); DeletePOptions deleteOptions = DeletePOptions.newBuilder().setAlluxioOnly(true).build(); mFileSystem.delete(inconsistentUri, deleteOptions); mFileSystem.exists(inconsistentUri); System.out.println(inconsistentUri + " repaired"); System.out.println(); } for (AlluxioURI uri : inconsistentDirs) { DeletePOptions deleteOptions = DeletePOptions.newBuilder().setAlluxioOnly(true).setRecursive(true).build(); System.out.println("repairing path: " + uri); mFileSystem.delete(uri, deleteOptions); mFileSystem.exists(uri); System.out.println(uri + "repaired"); System.out.println(); } } }
[ "private", "void", "runConsistencyCheck", "(", "AlluxioURI", "path", ",", "boolean", "repairConsistency", ")", "throws", "AlluxioException", ",", "IOException", "{", "List", "<", "AlluxioURI", ">", "inconsistentUris", "=", "checkConsistency", "(", "path", ",", "FileSystemOptions", ".", "checkConsistencyDefaults", "(", "mFsContext", ".", "getPathConf", "(", "path", ")", ")", ")", ";", "if", "(", "inconsistentUris", ".", "isEmpty", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "path", "+", "\" is consistent with the under storage system.\"", ")", ";", "return", ";", "}", "if", "(", "!", "repairConsistency", ")", "{", "Collections", ".", "sort", "(", "inconsistentUris", ")", ";", "System", ".", "out", ".", "println", "(", "\"The following files are inconsistent:\"", ")", ";", "for", "(", "AlluxioURI", "uri", ":", "inconsistentUris", ")", "{", "System", ".", "out", ".", "println", "(", "uri", ")", ";", "}", "}", "else", "{", "Collections", ".", "sort", "(", "inconsistentUris", ")", ";", "System", ".", "out", ".", "println", "(", "path", "+", "\" has: \"", "+", "inconsistentUris", ".", "size", "(", ")", "+", "\" inconsistent files.\"", ")", ";", "List", "<", "AlluxioURI", ">", "inconsistentDirs", "=", "new", "ArrayList", "<", "AlluxioURI", ">", "(", ")", ";", "for", "(", "AlluxioURI", "inconsistentUri", ":", "inconsistentUris", ")", "{", "URIStatus", "status", "=", "mFileSystem", ".", "getStatus", "(", "inconsistentUri", ")", ";", "if", "(", "status", ".", "isFolder", "(", ")", ")", "{", "inconsistentDirs", ".", "add", "(", "inconsistentUri", ")", ";", "continue", ";", "}", "System", ".", "out", ".", "println", "(", "\"repairing path: \"", "+", "inconsistentUri", ")", ";", "DeletePOptions", "deleteOptions", "=", "DeletePOptions", ".", "newBuilder", "(", ")", ".", "setAlluxioOnly", "(", "true", ")", ".", "build", "(", ")", ";", "mFileSystem", ".", "delete", "(", "inconsistentUri", ",", "deleteOptions", ")", ";", "mFileSystem", ".", "exists", "(", "inconsistentUri", ")", ";", "System", ".", "out", ".", "println", "(", "inconsistentUri", "+", "\" repaired\"", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "}", "for", "(", "AlluxioURI", "uri", ":", "inconsistentDirs", ")", "{", "DeletePOptions", "deleteOptions", "=", "DeletePOptions", ".", "newBuilder", "(", ")", ".", "setAlluxioOnly", "(", "true", ")", ".", "setRecursive", "(", "true", ")", ".", "build", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"repairing path: \"", "+", "uri", ")", ";", "mFileSystem", ".", "delete", "(", "uri", ",", "deleteOptions", ")", ";", "mFileSystem", ".", "exists", "(", "uri", ")", ";", "System", ".", "out", ".", "println", "(", "uri", "+", "\"repaired\"", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "}", "}", "}" ]
Checks the inconsistent files and directories which exist in Alluxio but don't exist in the under storage, repairs the inconsistent paths by deleting them if repairConsistency is true. @param path the specified path to be checked @param repairConsistency whether to repair the consistency or not @throws AlluxioException @throws IOException
[ "Checks", "the", "inconsistent", "files", "and", "directories", "which", "exist", "in", "Alluxio", "but", "don", "t", "exist", "in", "the", "under", "storage", "repairs", "the", "inconsistent", "paths", "by", "deleting", "them", "if", "repairConsistency", "is", "true", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CheckConsistencyCommand.java#L109-L151
18,752
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java
FileDataManager.needPersistence
public boolean needPersistence(long fileId) { if (isFilePersisting(fileId) || isFilePersisted(fileId)) { return false; } try { String ufsFingerprint = ufsFingerprint(fileId); if (ufsFingerprint != null) { // mark as persisted addPersistedFile(fileId, ufsFingerprint); return false; } } catch (Exception e) { LOG.warn("Failed to check if file {} exists in under storage system: {}", fileId, e.getMessage()); LOG.debug("Exception: ", e); } return true; }
java
public boolean needPersistence(long fileId) { if (isFilePersisting(fileId) || isFilePersisted(fileId)) { return false; } try { String ufsFingerprint = ufsFingerprint(fileId); if (ufsFingerprint != null) { // mark as persisted addPersistedFile(fileId, ufsFingerprint); return false; } } catch (Exception e) { LOG.warn("Failed to check if file {} exists in under storage system: {}", fileId, e.getMessage()); LOG.debug("Exception: ", e); } return true; }
[ "public", "boolean", "needPersistence", "(", "long", "fileId", ")", "{", "if", "(", "isFilePersisting", "(", "fileId", ")", "||", "isFilePersisted", "(", "fileId", ")", ")", "{", "return", "false", ";", "}", "try", "{", "String", "ufsFingerprint", "=", "ufsFingerprint", "(", "fileId", ")", ";", "if", "(", "ufsFingerprint", "!=", "null", ")", "{", "// mark as persisted", "addPersistedFile", "(", "fileId", ",", "ufsFingerprint", ")", ";", "return", "false", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "warn", "(", "\"Failed to check if file {} exists in under storage system: {}\"", ",", "fileId", ",", "e", ".", "getMessage", "(", ")", ")", ";", "LOG", ".", "debug", "(", "\"Exception: \"", ",", "e", ")", ";", "}", "return", "true", ";", "}" ]
Checks if the given file needs persistence. @param fileId the file id @return false if the file is being persisted, or is already persisted; otherwise true
[ "Checks", "if", "the", "given", "file", "needs", "persistence", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java#L144-L162
18,753
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java
FileDataManager.ufsFingerprint
private synchronized String ufsFingerprint(long fileId) throws IOException { FileInfo fileInfo = mBlockWorker.getFileInfo(fileId); String dstPath = fileInfo.getUfsPath(); try (CloseableResource<UnderFileSystem> ufsResource = mUfsManager.get(fileInfo.getMountId()).acquireUfsResource()) { UnderFileSystem ufs = ufsResource.get(); return ufs.isFile(dstPath) ? ufs.getFingerprint(dstPath) : null; } }
java
private synchronized String ufsFingerprint(long fileId) throws IOException { FileInfo fileInfo = mBlockWorker.getFileInfo(fileId); String dstPath = fileInfo.getUfsPath(); try (CloseableResource<UnderFileSystem> ufsResource = mUfsManager.get(fileInfo.getMountId()).acquireUfsResource()) { UnderFileSystem ufs = ufsResource.get(); return ufs.isFile(dstPath) ? ufs.getFingerprint(dstPath) : null; } }
[ "private", "synchronized", "String", "ufsFingerprint", "(", "long", "fileId", ")", "throws", "IOException", "{", "FileInfo", "fileInfo", "=", "mBlockWorker", ".", "getFileInfo", "(", "fileId", ")", ";", "String", "dstPath", "=", "fileInfo", ".", "getUfsPath", "(", ")", ";", "try", "(", "CloseableResource", "<", "UnderFileSystem", ">", "ufsResource", "=", "mUfsManager", ".", "get", "(", "fileInfo", ".", "getMountId", "(", ")", ")", ".", "acquireUfsResource", "(", ")", ")", "{", "UnderFileSystem", "ufs", "=", "ufsResource", ".", "get", "(", ")", ";", "return", "ufs", ".", "isFile", "(", "dstPath", ")", "?", "ufs", ".", "getFingerprint", "(", "dstPath", ")", ":", "null", ";", "}", "}" ]
Returns the ufs fingerprint of the given file, or null if the file doesn't exist. @param fileId the file id @return the ufs fingerprint of the file if it exists, null otherwise
[ "Returns", "the", "ufs", "fingerprint", "of", "the", "given", "file", "or", "null", "if", "the", "file", "doesn", "t", "exist", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java#L194-L202
18,754
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java
FileDataManager.lockBlocks
public void lockBlocks(long fileId, List<Long> blockIds) throws IOException { Map<Long, Long> blockIdToLockId = new HashMap<>(); List<Throwable> errors = new ArrayList<>(); synchronized (mLock) { if (mPersistingInProgressFiles.containsKey(fileId)) { throw new IOException("the file " + fileId + " is already being persisted"); } } try { // lock all the blocks to prevent any eviction for (long blockId : blockIds) { long lockId = mBlockWorker.lockBlock(Sessions.CHECKPOINT_SESSION_ID, blockId); blockIdToLockId.put(blockId, lockId); } } catch (BlockDoesNotExistException e) { errors.add(e); // make sure all the locks are released for (long lockId : blockIdToLockId.values()) { try { mBlockWorker.unlockBlock(lockId); } catch (BlockDoesNotExistException bdnee) { errors.add(bdnee); } } if (!errors.isEmpty()) { StringBuilder errorStr = new StringBuilder(); errorStr.append("failed to lock all blocks of file ").append(fileId).append("\n"); for (Throwable error : errors) { errorStr.append(error).append('\n'); } throw new IOException(errorStr.toString()); } } synchronized (mLock) { mPersistingInProgressFiles.put(fileId, blockIdToLockId); } }
java
public void lockBlocks(long fileId, List<Long> blockIds) throws IOException { Map<Long, Long> blockIdToLockId = new HashMap<>(); List<Throwable> errors = new ArrayList<>(); synchronized (mLock) { if (mPersistingInProgressFiles.containsKey(fileId)) { throw new IOException("the file " + fileId + " is already being persisted"); } } try { // lock all the blocks to prevent any eviction for (long blockId : blockIds) { long lockId = mBlockWorker.lockBlock(Sessions.CHECKPOINT_SESSION_ID, blockId); blockIdToLockId.put(blockId, lockId); } } catch (BlockDoesNotExistException e) { errors.add(e); // make sure all the locks are released for (long lockId : blockIdToLockId.values()) { try { mBlockWorker.unlockBlock(lockId); } catch (BlockDoesNotExistException bdnee) { errors.add(bdnee); } } if (!errors.isEmpty()) { StringBuilder errorStr = new StringBuilder(); errorStr.append("failed to lock all blocks of file ").append(fileId).append("\n"); for (Throwable error : errors) { errorStr.append(error).append('\n'); } throw new IOException(errorStr.toString()); } } synchronized (mLock) { mPersistingInProgressFiles.put(fileId, blockIdToLockId); } }
[ "public", "void", "lockBlocks", "(", "long", "fileId", ",", "List", "<", "Long", ">", "blockIds", ")", "throws", "IOException", "{", "Map", "<", "Long", ",", "Long", ">", "blockIdToLockId", "=", "new", "HashMap", "<>", "(", ")", ";", "List", "<", "Throwable", ">", "errors", "=", "new", "ArrayList", "<>", "(", ")", ";", "synchronized", "(", "mLock", ")", "{", "if", "(", "mPersistingInProgressFiles", ".", "containsKey", "(", "fileId", ")", ")", "{", "throw", "new", "IOException", "(", "\"the file \"", "+", "fileId", "+", "\" is already being persisted\"", ")", ";", "}", "}", "try", "{", "// lock all the blocks to prevent any eviction", "for", "(", "long", "blockId", ":", "blockIds", ")", "{", "long", "lockId", "=", "mBlockWorker", ".", "lockBlock", "(", "Sessions", ".", "CHECKPOINT_SESSION_ID", ",", "blockId", ")", ";", "blockIdToLockId", ".", "put", "(", "blockId", ",", "lockId", ")", ";", "}", "}", "catch", "(", "BlockDoesNotExistException", "e", ")", "{", "errors", ".", "add", "(", "e", ")", ";", "// make sure all the locks are released", "for", "(", "long", "lockId", ":", "blockIdToLockId", ".", "values", "(", ")", ")", "{", "try", "{", "mBlockWorker", ".", "unlockBlock", "(", "lockId", ")", ";", "}", "catch", "(", "BlockDoesNotExistException", "bdnee", ")", "{", "errors", ".", "add", "(", "bdnee", ")", ";", "}", "}", "if", "(", "!", "errors", ".", "isEmpty", "(", ")", ")", "{", "StringBuilder", "errorStr", "=", "new", "StringBuilder", "(", ")", ";", "errorStr", ".", "append", "(", "\"failed to lock all blocks of file \"", ")", ".", "append", "(", "fileId", ")", ".", "append", "(", "\"\\n\"", ")", ";", "for", "(", "Throwable", "error", ":", "errors", ")", "{", "errorStr", ".", "append", "(", "error", ")", ".", "append", "(", "'", "'", ")", ";", "}", "throw", "new", "IOException", "(", "errorStr", ".", "toString", "(", ")", ")", ";", "}", "}", "synchronized", "(", "mLock", ")", "{", "mPersistingInProgressFiles", ".", "put", "(", "fileId", ",", "blockIdToLockId", ")", ";", "}", "}" ]
Locks all the blocks of a given file Id. @param fileId the id of the file @param blockIds the ids of the file's blocks
[ "Locks", "all", "the", "blocks", "of", "a", "given", "file", "Id", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java#L210-L247
18,755
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java
FileDataManager.persistFile
public void persistFile(long fileId, List<Long> blockIds) throws AlluxioException, IOException { Map<Long, Long> blockIdToLockId; synchronized (mLock) { blockIdToLockId = mPersistingInProgressFiles.get(fileId); if (blockIdToLockId == null || !blockIdToLockId.keySet().equals(new HashSet<>(blockIds))) { throw new IOException("Not all the blocks of file " + fileId + " are locked"); } } FileInfo fileInfo = mBlockWorker.getFileInfo(fileId); try (CloseableResource<UnderFileSystem> ufsResource = mUfsManager.get(fileInfo.getMountId()).acquireUfsResource()) { UnderFileSystem ufs = ufsResource.get(); String dstPath = prepareUfsFilePath(fileInfo, ufs); OutputStream outputStream = ufs.createNonexistingFile(dstPath, CreateOptions.defaults(ServerConfiguration.global()) .setOwner(fileInfo.getOwner()).setGroup(fileInfo.getGroup()) .setMode(new Mode((short) fileInfo.getMode()))); final WritableByteChannel outputChannel = Channels.newChannel(outputStream); List<Throwable> errors = new ArrayList<>(); try { for (long blockId : blockIds) { long lockId = blockIdToLockId.get(blockId); if (ServerConfiguration.getBoolean(PropertyKey.WORKER_FILE_PERSIST_RATE_LIMIT_ENABLED)) { BlockMeta blockMeta = mBlockWorker.getBlockMeta(Sessions.CHECKPOINT_SESSION_ID, blockId, lockId); mPersistenceRateLimiter.acquire((int) blockMeta.getBlockSize()); } // obtain block reader BlockReader reader = mBlockWorker.readBlockRemote(Sessions.CHECKPOINT_SESSION_ID, blockId, lockId); // write content out ReadableByteChannel inputChannel = reader.getChannel(); mChannelCopier.copy(inputChannel, outputChannel); reader.close(); } } catch (BlockDoesNotExistException | InvalidWorkerStateException e) { errors.add(e); } finally { // make sure all the locks are released for (long lockId : blockIdToLockId.values()) { try { mBlockWorker.unlockBlock(lockId); } catch (BlockDoesNotExistException e) { errors.add(e); } } // Process any errors if (!errors.isEmpty()) { StringBuilder errorStr = new StringBuilder(); errorStr.append("the blocks of file").append(fileId).append(" are failed to persist\n"); for (Throwable e : errors) { errorStr.append(e).append('\n'); } throw new IOException(errorStr.toString()); } } outputStream.flush(); outputChannel.close(); outputStream.close(); String ufsFingerprint = ufs.getFingerprint(dstPath); synchronized (mLock) { mPersistingInProgressFiles.remove(fileId); mPersistedUfsFingerprints.put(fileId, ufsFingerprint); } } }
java
public void persistFile(long fileId, List<Long> blockIds) throws AlluxioException, IOException { Map<Long, Long> blockIdToLockId; synchronized (mLock) { blockIdToLockId = mPersistingInProgressFiles.get(fileId); if (blockIdToLockId == null || !blockIdToLockId.keySet().equals(new HashSet<>(blockIds))) { throw new IOException("Not all the blocks of file " + fileId + " are locked"); } } FileInfo fileInfo = mBlockWorker.getFileInfo(fileId); try (CloseableResource<UnderFileSystem> ufsResource = mUfsManager.get(fileInfo.getMountId()).acquireUfsResource()) { UnderFileSystem ufs = ufsResource.get(); String dstPath = prepareUfsFilePath(fileInfo, ufs); OutputStream outputStream = ufs.createNonexistingFile(dstPath, CreateOptions.defaults(ServerConfiguration.global()) .setOwner(fileInfo.getOwner()).setGroup(fileInfo.getGroup()) .setMode(new Mode((short) fileInfo.getMode()))); final WritableByteChannel outputChannel = Channels.newChannel(outputStream); List<Throwable> errors = new ArrayList<>(); try { for (long blockId : blockIds) { long lockId = blockIdToLockId.get(blockId); if (ServerConfiguration.getBoolean(PropertyKey.WORKER_FILE_PERSIST_RATE_LIMIT_ENABLED)) { BlockMeta blockMeta = mBlockWorker.getBlockMeta(Sessions.CHECKPOINT_SESSION_ID, blockId, lockId); mPersistenceRateLimiter.acquire((int) blockMeta.getBlockSize()); } // obtain block reader BlockReader reader = mBlockWorker.readBlockRemote(Sessions.CHECKPOINT_SESSION_ID, blockId, lockId); // write content out ReadableByteChannel inputChannel = reader.getChannel(); mChannelCopier.copy(inputChannel, outputChannel); reader.close(); } } catch (BlockDoesNotExistException | InvalidWorkerStateException e) { errors.add(e); } finally { // make sure all the locks are released for (long lockId : blockIdToLockId.values()) { try { mBlockWorker.unlockBlock(lockId); } catch (BlockDoesNotExistException e) { errors.add(e); } } // Process any errors if (!errors.isEmpty()) { StringBuilder errorStr = new StringBuilder(); errorStr.append("the blocks of file").append(fileId).append(" are failed to persist\n"); for (Throwable e : errors) { errorStr.append(e).append('\n'); } throw new IOException(errorStr.toString()); } } outputStream.flush(); outputChannel.close(); outputStream.close(); String ufsFingerprint = ufs.getFingerprint(dstPath); synchronized (mLock) { mPersistingInProgressFiles.remove(fileId); mPersistedUfsFingerprints.put(fileId, ufsFingerprint); } } }
[ "public", "void", "persistFile", "(", "long", "fileId", ",", "List", "<", "Long", ">", "blockIds", ")", "throws", "AlluxioException", ",", "IOException", "{", "Map", "<", "Long", ",", "Long", ">", "blockIdToLockId", ";", "synchronized", "(", "mLock", ")", "{", "blockIdToLockId", "=", "mPersistingInProgressFiles", ".", "get", "(", "fileId", ")", ";", "if", "(", "blockIdToLockId", "==", "null", "||", "!", "blockIdToLockId", ".", "keySet", "(", ")", ".", "equals", "(", "new", "HashSet", "<>", "(", "blockIds", ")", ")", ")", "{", "throw", "new", "IOException", "(", "\"Not all the blocks of file \"", "+", "fileId", "+", "\" are locked\"", ")", ";", "}", "}", "FileInfo", "fileInfo", "=", "mBlockWorker", ".", "getFileInfo", "(", "fileId", ")", ";", "try", "(", "CloseableResource", "<", "UnderFileSystem", ">", "ufsResource", "=", "mUfsManager", ".", "get", "(", "fileInfo", ".", "getMountId", "(", ")", ")", ".", "acquireUfsResource", "(", ")", ")", "{", "UnderFileSystem", "ufs", "=", "ufsResource", ".", "get", "(", ")", ";", "String", "dstPath", "=", "prepareUfsFilePath", "(", "fileInfo", ",", "ufs", ")", ";", "OutputStream", "outputStream", "=", "ufs", ".", "createNonexistingFile", "(", "dstPath", ",", "CreateOptions", ".", "defaults", "(", "ServerConfiguration", ".", "global", "(", ")", ")", ".", "setOwner", "(", "fileInfo", ".", "getOwner", "(", ")", ")", ".", "setGroup", "(", "fileInfo", ".", "getGroup", "(", ")", ")", ".", "setMode", "(", "new", "Mode", "(", "(", "short", ")", "fileInfo", ".", "getMode", "(", ")", ")", ")", ")", ";", "final", "WritableByteChannel", "outputChannel", "=", "Channels", ".", "newChannel", "(", "outputStream", ")", ";", "List", "<", "Throwable", ">", "errors", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "{", "for", "(", "long", "blockId", ":", "blockIds", ")", "{", "long", "lockId", "=", "blockIdToLockId", ".", "get", "(", "blockId", ")", ";", "if", "(", "ServerConfiguration", ".", "getBoolean", "(", "PropertyKey", ".", "WORKER_FILE_PERSIST_RATE_LIMIT_ENABLED", ")", ")", "{", "BlockMeta", "blockMeta", "=", "mBlockWorker", ".", "getBlockMeta", "(", "Sessions", ".", "CHECKPOINT_SESSION_ID", ",", "blockId", ",", "lockId", ")", ";", "mPersistenceRateLimiter", ".", "acquire", "(", "(", "int", ")", "blockMeta", ".", "getBlockSize", "(", ")", ")", ";", "}", "// obtain block reader", "BlockReader", "reader", "=", "mBlockWorker", ".", "readBlockRemote", "(", "Sessions", ".", "CHECKPOINT_SESSION_ID", ",", "blockId", ",", "lockId", ")", ";", "// write content out", "ReadableByteChannel", "inputChannel", "=", "reader", ".", "getChannel", "(", ")", ";", "mChannelCopier", ".", "copy", "(", "inputChannel", ",", "outputChannel", ")", ";", "reader", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "BlockDoesNotExistException", "|", "InvalidWorkerStateException", "e", ")", "{", "errors", ".", "add", "(", "e", ")", ";", "}", "finally", "{", "// make sure all the locks are released", "for", "(", "long", "lockId", ":", "blockIdToLockId", ".", "values", "(", ")", ")", "{", "try", "{", "mBlockWorker", ".", "unlockBlock", "(", "lockId", ")", ";", "}", "catch", "(", "BlockDoesNotExistException", "e", ")", "{", "errors", ".", "add", "(", "e", ")", ";", "}", "}", "// Process any errors", "if", "(", "!", "errors", ".", "isEmpty", "(", ")", ")", "{", "StringBuilder", "errorStr", "=", "new", "StringBuilder", "(", ")", ";", "errorStr", ".", "append", "(", "\"the blocks of file\"", ")", ".", "append", "(", "fileId", ")", ".", "append", "(", "\" are failed to persist\\n\"", ")", ";", "for", "(", "Throwable", "e", ":", "errors", ")", "{", "errorStr", ".", "append", "(", "e", ")", ".", "append", "(", "'", "'", ")", ";", "}", "throw", "new", "IOException", "(", "errorStr", ".", "toString", "(", ")", ")", ";", "}", "}", "outputStream", ".", "flush", "(", ")", ";", "outputChannel", ".", "close", "(", ")", ";", "outputStream", ".", "close", "(", ")", ";", "String", "ufsFingerprint", "=", "ufs", ".", "getFingerprint", "(", "dstPath", ")", ";", "synchronized", "(", "mLock", ")", "{", "mPersistingInProgressFiles", ".", "remove", "(", "fileId", ")", ";", "mPersistedUfsFingerprints", ".", "put", "(", "fileId", ",", "ufsFingerprint", ")", ";", "}", "}", "}" ]
Persists the blocks of a file into the under file system. @param fileId the id of the file @param blockIds the list of block ids
[ "Persists", "the", "blocks", "of", "a", "file", "into", "the", "under", "file", "system", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java#L255-L326
18,756
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java
FileDataManager.prepareUfsFilePath
private String prepareUfsFilePath(FileInfo fileInfo, UnderFileSystem ufs) throws AlluxioException, IOException { AlluxioURI alluxioPath = new AlluxioURI(fileInfo.getPath()); FileSystem fs = mFileSystemFactory.get(); URIStatus status = fs.getStatus(alluxioPath); String ufsPath = status.getUfsPath(); UnderFileSystemUtils.prepareFilePath(alluxioPath, ufsPath, fs, ufs); return ufsPath; }
java
private String prepareUfsFilePath(FileInfo fileInfo, UnderFileSystem ufs) throws AlluxioException, IOException { AlluxioURI alluxioPath = new AlluxioURI(fileInfo.getPath()); FileSystem fs = mFileSystemFactory.get(); URIStatus status = fs.getStatus(alluxioPath); String ufsPath = status.getUfsPath(); UnderFileSystemUtils.prepareFilePath(alluxioPath, ufsPath, fs, ufs); return ufsPath; }
[ "private", "String", "prepareUfsFilePath", "(", "FileInfo", "fileInfo", ",", "UnderFileSystem", "ufs", ")", "throws", "AlluxioException", ",", "IOException", "{", "AlluxioURI", "alluxioPath", "=", "new", "AlluxioURI", "(", "fileInfo", ".", "getPath", "(", ")", ")", ";", "FileSystem", "fs", "=", "mFileSystemFactory", ".", "get", "(", ")", ";", "URIStatus", "status", "=", "fs", ".", "getStatus", "(", "alluxioPath", ")", ";", "String", "ufsPath", "=", "status", ".", "getUfsPath", "(", ")", ";", "UnderFileSystemUtils", ".", "prepareFilePath", "(", "alluxioPath", ",", "ufsPath", ",", "fs", ",", "ufs", ")", ";", "return", "ufsPath", ";", "}" ]
Prepares the destination file path of the given file id. Also creates the parent folder if it does not exist. @param fileInfo the file info @param ufs the {@link UnderFileSystem} instance @return the path for persistence
[ "Prepares", "the", "destination", "file", "path", "of", "the", "given", "file", "id", ".", "Also", "creates", "the", "parent", "folder", "if", "it", "does", "not", "exist", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java#L336-L344
18,757
Alluxio/alluxio
job/server/src/main/java/alluxio/job/util/JobUtils.java
JobUtils.getWorkerWithMostBlocks
public static BlockWorkerInfo getWorkerWithMostBlocks(List<BlockWorkerInfo> workers, List<FileBlockInfo> fileBlockInfos) { // Index workers by their addresses. IndexedSet<BlockWorkerInfo> addressIndexedWorkers = new IndexedSet<>(WORKER_ADDRESS_INDEX); addressIndexedWorkers.addAll(workers); // Use ConcurrentMap for putIfAbsent. A regular Map works in Java 8. ConcurrentMap<BlockWorkerInfo, Integer> blocksPerWorker = Maps.newConcurrentMap(); int maxBlocks = 0; BlockWorkerInfo mostBlocksWorker = null; for (FileBlockInfo fileBlockInfo : fileBlockInfos) { for (BlockLocation location : fileBlockInfo.getBlockInfo().getLocations()) { BlockWorkerInfo worker = addressIndexedWorkers.getFirstByField(WORKER_ADDRESS_INDEX, location.getWorkerAddress()); if (worker == null) { // We can only choose workers in the workers list. continue; } blocksPerWorker.putIfAbsent(worker, 0); int newBlockCount = blocksPerWorker.get(worker) + 1; blocksPerWorker.put(worker, newBlockCount); if (newBlockCount > maxBlocks) { maxBlocks = newBlockCount; mostBlocksWorker = worker; } } } return mostBlocksWorker; }
java
public static BlockWorkerInfo getWorkerWithMostBlocks(List<BlockWorkerInfo> workers, List<FileBlockInfo> fileBlockInfos) { // Index workers by their addresses. IndexedSet<BlockWorkerInfo> addressIndexedWorkers = new IndexedSet<>(WORKER_ADDRESS_INDEX); addressIndexedWorkers.addAll(workers); // Use ConcurrentMap for putIfAbsent. A regular Map works in Java 8. ConcurrentMap<BlockWorkerInfo, Integer> blocksPerWorker = Maps.newConcurrentMap(); int maxBlocks = 0; BlockWorkerInfo mostBlocksWorker = null; for (FileBlockInfo fileBlockInfo : fileBlockInfos) { for (BlockLocation location : fileBlockInfo.getBlockInfo().getLocations()) { BlockWorkerInfo worker = addressIndexedWorkers.getFirstByField(WORKER_ADDRESS_INDEX, location.getWorkerAddress()); if (worker == null) { // We can only choose workers in the workers list. continue; } blocksPerWorker.putIfAbsent(worker, 0); int newBlockCount = blocksPerWorker.get(worker) + 1; blocksPerWorker.put(worker, newBlockCount); if (newBlockCount > maxBlocks) { maxBlocks = newBlockCount; mostBlocksWorker = worker; } } } return mostBlocksWorker; }
[ "public", "static", "BlockWorkerInfo", "getWorkerWithMostBlocks", "(", "List", "<", "BlockWorkerInfo", ">", "workers", ",", "List", "<", "FileBlockInfo", ">", "fileBlockInfos", ")", "{", "// Index workers by their addresses.", "IndexedSet", "<", "BlockWorkerInfo", ">", "addressIndexedWorkers", "=", "new", "IndexedSet", "<>", "(", "WORKER_ADDRESS_INDEX", ")", ";", "addressIndexedWorkers", ".", "addAll", "(", "workers", ")", ";", "// Use ConcurrentMap for putIfAbsent. A regular Map works in Java 8.", "ConcurrentMap", "<", "BlockWorkerInfo", ",", "Integer", ">", "blocksPerWorker", "=", "Maps", ".", "newConcurrentMap", "(", ")", ";", "int", "maxBlocks", "=", "0", ";", "BlockWorkerInfo", "mostBlocksWorker", "=", "null", ";", "for", "(", "FileBlockInfo", "fileBlockInfo", ":", "fileBlockInfos", ")", "{", "for", "(", "BlockLocation", "location", ":", "fileBlockInfo", ".", "getBlockInfo", "(", ")", ".", "getLocations", "(", ")", ")", "{", "BlockWorkerInfo", "worker", "=", "addressIndexedWorkers", ".", "getFirstByField", "(", "WORKER_ADDRESS_INDEX", ",", "location", ".", "getWorkerAddress", "(", ")", ")", ";", "if", "(", "worker", "==", "null", ")", "{", "// We can only choose workers in the workers list.", "continue", ";", "}", "blocksPerWorker", ".", "putIfAbsent", "(", "worker", ",", "0", ")", ";", "int", "newBlockCount", "=", "blocksPerWorker", ".", "get", "(", "worker", ")", "+", "1", ";", "blocksPerWorker", ".", "put", "(", "worker", ",", "newBlockCount", ")", ";", "if", "(", "newBlockCount", ">", "maxBlocks", ")", "{", "maxBlocks", "=", "newBlockCount", ";", "mostBlocksWorker", "=", "worker", ";", "}", "}", "}", "return", "mostBlocksWorker", ";", "}" ]
Returns whichever specified worker stores the most blocks from the block info list. @param workers a list of workers to consider @param fileBlockInfos a list of file block information @return a worker address storing the most blocks from the list
[ "Returns", "whichever", "specified", "worker", "stores", "the", "most", "blocks", "from", "the", "block", "info", "list", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/job/util/JobUtils.java#L68-L96
18,758
Alluxio/alluxio
job/server/src/main/java/alluxio/job/util/JobUtils.java
JobUtils.loadBlock
public static void loadBlock(FileSystem fs, FileSystemContext context, String path, long blockId) throws AlluxioException, IOException { AlluxioBlockStore blockStore = AlluxioBlockStore.create(context); String localHostName = NetworkAddressUtils.getConnectHost(ServiceType.WORKER_RPC, ServerConfiguration.global()); List<BlockWorkerInfo> workerInfoList = blockStore.getAllWorkers(); WorkerNetAddress localNetAddress = null; for (BlockWorkerInfo workerInfo : workerInfoList) { if (workerInfo.getNetAddress().getHost().equals(localHostName)) { localNetAddress = workerInfo.getNetAddress(); break; } } if (localNetAddress == null) { throw new NotFoundException(ExceptionMessage.NO_LOCAL_BLOCK_WORKER_REPLICATE_TASK .getMessage(blockId)); } // TODO(jiri): Replace with internal client that uses file ID once the internal client is // factored out of the core server module. The reason to prefer using file ID for this job is // to avoid the the race between "replicate" and "rename", so that even a file to replicate is // renamed, the job is still working on the correct file. URIStatus status = fs.getStatus(new AlluxioURI(path)); OpenFilePOptions openOptions = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); AlluxioConfiguration conf = ServerConfiguration.global(); InStreamOptions inOptions = new InStreamOptions(status, openOptions, conf); // Set read location policy always to loca first for loading blocks for job tasks inOptions.setUfsReadLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); OutStreamOptions outOptions = OutStreamOptions.defaults(conf); // Set write location policy always to local first for loading blocks for job tasks outOptions.setLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); // use -1 to reuse the existing block size for this block try (OutputStream outputStream = blockStore.getOutStream(blockId, -1, localNetAddress, outOptions)) { try (InputStream inputStream = blockStore.getInStream(blockId, inOptions)) { ByteStreams.copy(inputStream, outputStream); } catch (Throwable t) { try { ((Cancelable) outputStream).cancel(); } catch (Throwable t2) { t.addSuppressed(t2); } throw t; } } }
java
public static void loadBlock(FileSystem fs, FileSystemContext context, String path, long blockId) throws AlluxioException, IOException { AlluxioBlockStore blockStore = AlluxioBlockStore.create(context); String localHostName = NetworkAddressUtils.getConnectHost(ServiceType.WORKER_RPC, ServerConfiguration.global()); List<BlockWorkerInfo> workerInfoList = blockStore.getAllWorkers(); WorkerNetAddress localNetAddress = null; for (BlockWorkerInfo workerInfo : workerInfoList) { if (workerInfo.getNetAddress().getHost().equals(localHostName)) { localNetAddress = workerInfo.getNetAddress(); break; } } if (localNetAddress == null) { throw new NotFoundException(ExceptionMessage.NO_LOCAL_BLOCK_WORKER_REPLICATE_TASK .getMessage(blockId)); } // TODO(jiri): Replace with internal client that uses file ID once the internal client is // factored out of the core server module. The reason to prefer using file ID for this job is // to avoid the the race between "replicate" and "rename", so that even a file to replicate is // renamed, the job is still working on the correct file. URIStatus status = fs.getStatus(new AlluxioURI(path)); OpenFilePOptions openOptions = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); AlluxioConfiguration conf = ServerConfiguration.global(); InStreamOptions inOptions = new InStreamOptions(status, openOptions, conf); // Set read location policy always to loca first for loading blocks for job tasks inOptions.setUfsReadLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); OutStreamOptions outOptions = OutStreamOptions.defaults(conf); // Set write location policy always to local first for loading blocks for job tasks outOptions.setLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); // use -1 to reuse the existing block size for this block try (OutputStream outputStream = blockStore.getOutStream(blockId, -1, localNetAddress, outOptions)) { try (InputStream inputStream = blockStore.getInStream(blockId, inOptions)) { ByteStreams.copy(inputStream, outputStream); } catch (Throwable t) { try { ((Cancelable) outputStream).cancel(); } catch (Throwable t2) { t.addSuppressed(t2); } throw t; } } }
[ "public", "static", "void", "loadBlock", "(", "FileSystem", "fs", ",", "FileSystemContext", "context", ",", "String", "path", ",", "long", "blockId", ")", "throws", "AlluxioException", ",", "IOException", "{", "AlluxioBlockStore", "blockStore", "=", "AlluxioBlockStore", ".", "create", "(", "context", ")", ";", "String", "localHostName", "=", "NetworkAddressUtils", ".", "getConnectHost", "(", "ServiceType", ".", "WORKER_RPC", ",", "ServerConfiguration", ".", "global", "(", ")", ")", ";", "List", "<", "BlockWorkerInfo", ">", "workerInfoList", "=", "blockStore", ".", "getAllWorkers", "(", ")", ";", "WorkerNetAddress", "localNetAddress", "=", "null", ";", "for", "(", "BlockWorkerInfo", "workerInfo", ":", "workerInfoList", ")", "{", "if", "(", "workerInfo", ".", "getNetAddress", "(", ")", ".", "getHost", "(", ")", ".", "equals", "(", "localHostName", ")", ")", "{", "localNetAddress", "=", "workerInfo", ".", "getNetAddress", "(", ")", ";", "break", ";", "}", "}", "if", "(", "localNetAddress", "==", "null", ")", "{", "throw", "new", "NotFoundException", "(", "ExceptionMessage", ".", "NO_LOCAL_BLOCK_WORKER_REPLICATE_TASK", ".", "getMessage", "(", "blockId", ")", ")", ";", "}", "// TODO(jiri): Replace with internal client that uses file ID once the internal client is", "// factored out of the core server module. The reason to prefer using file ID for this job is", "// to avoid the the race between \"replicate\" and \"rename\", so that even a file to replicate is", "// renamed, the job is still working on the correct file.", "URIStatus", "status", "=", "fs", ".", "getStatus", "(", "new", "AlluxioURI", "(", "path", ")", ")", ";", "OpenFilePOptions", "openOptions", "=", "OpenFilePOptions", ".", "newBuilder", "(", ")", ".", "setReadType", "(", "ReadPType", ".", "NO_CACHE", ")", ".", "build", "(", ")", ";", "AlluxioConfiguration", "conf", "=", "ServerConfiguration", ".", "global", "(", ")", ";", "InStreamOptions", "inOptions", "=", "new", "InStreamOptions", "(", "status", ",", "openOptions", ",", "conf", ")", ";", "// Set read location policy always to loca first for loading blocks for job tasks", "inOptions", ".", "setUfsReadLocationPolicy", "(", "BlockLocationPolicy", ".", "Factory", ".", "create", "(", "LocalFirstPolicy", ".", "class", ".", "getCanonicalName", "(", ")", ",", "conf", ")", ")", ";", "OutStreamOptions", "outOptions", "=", "OutStreamOptions", ".", "defaults", "(", "conf", ")", ";", "// Set write location policy always to local first for loading blocks for job tasks", "outOptions", ".", "setLocationPolicy", "(", "BlockLocationPolicy", ".", "Factory", ".", "create", "(", "LocalFirstPolicy", ".", "class", ".", "getCanonicalName", "(", ")", ",", "conf", ")", ")", ";", "// use -1 to reuse the existing block size for this block", "try", "(", "OutputStream", "outputStream", "=", "blockStore", ".", "getOutStream", "(", "blockId", ",", "-", "1", ",", "localNetAddress", ",", "outOptions", ")", ")", "{", "try", "(", "InputStream", "inputStream", "=", "blockStore", ".", "getInStream", "(", "blockId", ",", "inOptions", ")", ")", "{", "ByteStreams", ".", "copy", "(", "inputStream", ",", "outputStream", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "try", "{", "(", "(", "Cancelable", ")", "outputStream", ")", ".", "cancel", "(", ")", ";", "}", "catch", "(", "Throwable", "t2", ")", "{", "t", ".", "addSuppressed", "(", "t2", ")", ";", "}", "throw", "t", ";", "}", "}", "}" ]
Loads a block into the local worker. If the block doesn't exist in Alluxio, it will be read from the UFS. @param fs the filesystem @param context filesystem context @param path the file path of the block to load @param blockId the id of the block to load
[ "Loads", "a", "block", "into", "the", "local", "worker", ".", "If", "the", "block", "doesn", "t", "exist", "in", "Alluxio", "it", "will", "be", "read", "from", "the", "UFS", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/job/util/JobUtils.java#L107-L161
18,759
Alluxio/alluxio
core/common/src/main/java/alluxio/network/RejectingServer.java
RejectingServer.stopAndJoin
public void stopAndJoin() { interrupt(); if (mServerSocket != null) { try { mServerSocket.close(); } catch (IOException e) { throw new RuntimeException(e); } } try { join(5 * Constants.SECOND_MS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (isAlive()) { LOG.warn("Failed to stop rejecting server thread"); } }
java
public void stopAndJoin() { interrupt(); if (mServerSocket != null) { try { mServerSocket.close(); } catch (IOException e) { throw new RuntimeException(e); } } try { join(5 * Constants.SECOND_MS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (isAlive()) { LOG.warn("Failed to stop rejecting server thread"); } }
[ "public", "void", "stopAndJoin", "(", ")", "{", "interrupt", "(", ")", ";", "if", "(", "mServerSocket", "!=", "null", ")", "{", "try", "{", "mServerSocket", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "try", "{", "join", "(", "5", "*", "Constants", ".", "SECOND_MS", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "if", "(", "isAlive", "(", ")", ")", "{", "LOG", ".", "warn", "(", "\"Failed to stop rejecting server thread\"", ")", ";", "}", "}" ]
Stops the server and joins the server thread.
[ "Stops", "the", "server", "and", "joins", "the", "server", "thread", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/network/RejectingServer.java#L65-L82
18,760
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.initializeRoot
public void initializeRoot(String owner, String group, Mode mode, JournalContext context) throws UnavailableException { if (mState.getRoot() == null) { MutableInodeDirectory root = MutableInodeDirectory.create( mDirectoryIdGenerator.getNewDirectoryId(context), NO_PARENT, ROOT_INODE_NAME, CreateDirectoryContext .mergeFrom(CreateDirectoryPOptions.newBuilder().setMode(mode.toProto())) .setOwner(owner).setGroup(group)); root.setPersistenceState(PersistenceState.PERSISTED); mState.applyAndJournal(context, root); } }
java
public void initializeRoot(String owner, String group, Mode mode, JournalContext context) throws UnavailableException { if (mState.getRoot() == null) { MutableInodeDirectory root = MutableInodeDirectory.create( mDirectoryIdGenerator.getNewDirectoryId(context), NO_PARENT, ROOT_INODE_NAME, CreateDirectoryContext .mergeFrom(CreateDirectoryPOptions.newBuilder().setMode(mode.toProto())) .setOwner(owner).setGroup(group)); root.setPersistenceState(PersistenceState.PERSISTED); mState.applyAndJournal(context, root); } }
[ "public", "void", "initializeRoot", "(", "String", "owner", ",", "String", "group", ",", "Mode", "mode", ",", "JournalContext", "context", ")", "throws", "UnavailableException", "{", "if", "(", "mState", ".", "getRoot", "(", ")", "==", "null", ")", "{", "MutableInodeDirectory", "root", "=", "MutableInodeDirectory", ".", "create", "(", "mDirectoryIdGenerator", ".", "getNewDirectoryId", "(", "context", ")", ",", "NO_PARENT", ",", "ROOT_INODE_NAME", ",", "CreateDirectoryContext", ".", "mergeFrom", "(", "CreateDirectoryPOptions", ".", "newBuilder", "(", ")", ".", "setMode", "(", "mode", ".", "toProto", "(", ")", ")", ")", ".", "setOwner", "(", "owner", ")", ".", "setGroup", "(", "group", ")", ")", ";", "root", ".", "setPersistenceState", "(", "PersistenceState", ".", "PERSISTED", ")", ";", "mState", ".", "applyAndJournal", "(", "context", ",", "root", ")", ";", "}", "}" ]
Initializes the root of the inode tree. @param owner the root owner @param group the root group @param mode the root mode @param context the journal context to journal the initialization to
[ "Initializes", "the", "root", "of", "the", "inode", "tree", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L224-L235
18,761
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.setDirectChildrenLoaded
public void setDirectChildrenLoaded(Supplier<JournalContext> context, InodeDirectory dir) { mState.applyAndJournal(context, UpdateInodeDirectoryEntry.newBuilder() .setId(dir.getId()) .setDirectChildrenLoaded(true) .build()); }
java
public void setDirectChildrenLoaded(Supplier<JournalContext> context, InodeDirectory dir) { mState.applyAndJournal(context, UpdateInodeDirectoryEntry.newBuilder() .setId(dir.getId()) .setDirectChildrenLoaded(true) .build()); }
[ "public", "void", "setDirectChildrenLoaded", "(", "Supplier", "<", "JournalContext", ">", "context", ",", "InodeDirectory", "dir", ")", "{", "mState", ".", "applyAndJournal", "(", "context", ",", "UpdateInodeDirectoryEntry", ".", "newBuilder", "(", ")", ".", "setId", "(", "dir", ".", "getId", "(", ")", ")", ".", "setDirectChildrenLoaded", "(", "true", ")", ".", "build", "(", ")", ")", ";", "}" ]
Marks an inode directory as having its direct children loaded. @param context journal context supplier @param dir the inode directory
[ "Marks", "an", "inode", "directory", "as", "having", "its", "direct", "children", "loaded", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L257-L262
18,762
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.lockInodePathPair
public InodePathPair lockInodePathPair(AlluxioURI path1, LockPattern lockPattern1, AlluxioURI path2, LockPattern lockPattern2) throws InvalidPathException { LockedInodePath lockedPath1 = null; LockedInodePath lockedPath2 = null; boolean valid = false; try { // Lock paths in a deterministic order. if (path1.getPath().compareTo(path2.getPath()) > 0) { lockedPath2 = lockInodePath(path2, lockPattern2); lockedPath1 = lockInodePath(path1, lockPattern1); } else { lockedPath1 = lockInodePath(path1, lockPattern1); lockedPath2 = lockInodePath(path2, lockPattern2); } valid = true; return new InodePathPair(lockedPath1, lockedPath2); } finally { if (!valid) { if (lockedPath1 != null) { lockedPath1.close(); } if (lockedPath2 != null) { lockedPath2.close(); } } } }
java
public InodePathPair lockInodePathPair(AlluxioURI path1, LockPattern lockPattern1, AlluxioURI path2, LockPattern lockPattern2) throws InvalidPathException { LockedInodePath lockedPath1 = null; LockedInodePath lockedPath2 = null; boolean valid = false; try { // Lock paths in a deterministic order. if (path1.getPath().compareTo(path2.getPath()) > 0) { lockedPath2 = lockInodePath(path2, lockPattern2); lockedPath1 = lockInodePath(path1, lockPattern1); } else { lockedPath1 = lockInodePath(path1, lockPattern1); lockedPath2 = lockInodePath(path2, lockPattern2); } valid = true; return new InodePathPair(lockedPath1, lockedPath2); } finally { if (!valid) { if (lockedPath1 != null) { lockedPath1.close(); } if (lockedPath2 != null) { lockedPath2.close(); } } } }
[ "public", "InodePathPair", "lockInodePathPair", "(", "AlluxioURI", "path1", ",", "LockPattern", "lockPattern1", ",", "AlluxioURI", "path2", ",", "LockPattern", "lockPattern2", ")", "throws", "InvalidPathException", "{", "LockedInodePath", "lockedPath1", "=", "null", ";", "LockedInodePath", "lockedPath2", "=", "null", ";", "boolean", "valid", "=", "false", ";", "try", "{", "// Lock paths in a deterministic order.", "if", "(", "path1", ".", "getPath", "(", ")", ".", "compareTo", "(", "path2", ".", "getPath", "(", ")", ")", ">", "0", ")", "{", "lockedPath2", "=", "lockInodePath", "(", "path2", ",", "lockPattern2", ")", ";", "lockedPath1", "=", "lockInodePath", "(", "path1", ",", "lockPattern1", ")", ";", "}", "else", "{", "lockedPath1", "=", "lockInodePath", "(", "path1", ",", "lockPattern1", ")", ";", "lockedPath2", "=", "lockInodePath", "(", "path2", ",", "lockPattern2", ")", ";", "}", "valid", "=", "true", ";", "return", "new", "InodePathPair", "(", "lockedPath1", ",", "lockedPath2", ")", ";", "}", "finally", "{", "if", "(", "!", "valid", ")", "{", "if", "(", "lockedPath1", "!=", "null", ")", "{", "lockedPath1", ".", "close", "(", ")", ";", "}", "if", "(", "lockedPath2", "!=", "null", ")", "{", "lockedPath2", ".", "close", "(", ")", ";", "}", "}", "}", "}" ]
Locks existing inodes on the two specified paths. The two paths will be locked in the correct order. The target inodes are not required to exist. @param path1 the first path to lock @param lockPattern1 the locking pattern for the first path @param path2 the second path to lock @param lockPattern2 the locking pattern for the second path @return a {@link InodePathPair} representing the two locked paths @throws InvalidPathException if a path is invalid
[ "Locks", "existing", "inodes", "on", "the", "two", "specified", "paths", ".", "The", "two", "paths", "will", "be", "locked", "in", "the", "correct", "order", ".", "The", "target", "inodes", "are", "not", "required", "to", "exist", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L459-L485
18,763
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.computePathForInode
private void computePathForInode(InodeView inode, StringBuilder builder) throws FileDoesNotExistException { long id; long parentId; String name; try (LockResource lr = mInodeLockManager.lockInode(inode, LockMode.READ)) { id = inode.getId(); parentId = inode.getParentId(); name = inode.getName(); } if (isRootId(id)) { builder.append(AlluxioURI.SEPARATOR); } else if (isRootId(parentId)) { builder.append(AlluxioURI.SEPARATOR); builder.append(name); } else { Optional<Inode> parentInode = mInodeStore.get(parentId); if (!parentInode.isPresent()) { throw new FileDoesNotExistException( ExceptionMessage.INODE_DOES_NOT_EXIST.getMessage(parentId)); } computePathForInode(parentInode.get(), builder); builder.append(AlluxioURI.SEPARATOR); builder.append(name); } }
java
private void computePathForInode(InodeView inode, StringBuilder builder) throws FileDoesNotExistException { long id; long parentId; String name; try (LockResource lr = mInodeLockManager.lockInode(inode, LockMode.READ)) { id = inode.getId(); parentId = inode.getParentId(); name = inode.getName(); } if (isRootId(id)) { builder.append(AlluxioURI.SEPARATOR); } else if (isRootId(parentId)) { builder.append(AlluxioURI.SEPARATOR); builder.append(name); } else { Optional<Inode> parentInode = mInodeStore.get(parentId); if (!parentInode.isPresent()) { throw new FileDoesNotExistException( ExceptionMessage.INODE_DOES_NOT_EXIST.getMessage(parentId)); } computePathForInode(parentInode.get(), builder); builder.append(AlluxioURI.SEPARATOR); builder.append(name); } }
[ "private", "void", "computePathForInode", "(", "InodeView", "inode", ",", "StringBuilder", "builder", ")", "throws", "FileDoesNotExistException", "{", "long", "id", ";", "long", "parentId", ";", "String", "name", ";", "try", "(", "LockResource", "lr", "=", "mInodeLockManager", ".", "lockInode", "(", "inode", ",", "LockMode", ".", "READ", ")", ")", "{", "id", "=", "inode", ".", "getId", "(", ")", ";", "parentId", "=", "inode", ".", "getParentId", "(", ")", ";", "name", "=", "inode", ".", "getName", "(", ")", ";", "}", "if", "(", "isRootId", "(", "id", ")", ")", "{", "builder", ".", "append", "(", "AlluxioURI", ".", "SEPARATOR", ")", ";", "}", "else", "if", "(", "isRootId", "(", "parentId", ")", ")", "{", "builder", ".", "append", "(", "AlluxioURI", ".", "SEPARATOR", ")", ";", "builder", ".", "append", "(", "name", ")", ";", "}", "else", "{", "Optional", "<", "Inode", ">", "parentInode", "=", "mInodeStore", ".", "get", "(", "parentId", ")", ";", "if", "(", "!", "parentInode", ".", "isPresent", "(", ")", ")", "{", "throw", "new", "FileDoesNotExistException", "(", "ExceptionMessage", ".", "INODE_DOES_NOT_EXIST", ".", "getMessage", "(", "parentId", ")", ")", ";", "}", "computePathForInode", "(", "parentInode", ".", "get", "(", ")", ",", "builder", ")", ";", "builder", ".", "append", "(", "AlluxioURI", ".", "SEPARATOR", ")", ";", "builder", ".", "append", "(", "name", ")", ";", "}", "}" ]
Appends components of the path from a given inode. @param inode the inode to compute the path for @param builder a {@link StringBuilder} that is updated with the path components @throws FileDoesNotExistException if an inode in the path does not exist
[ "Appends", "components", "of", "the", "path", "from", "a", "given", "inode", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L514-L541
18,764
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.getPath
public AlluxioURI getPath(InodeView inode) throws FileDoesNotExistException { StringBuilder builder = new StringBuilder(); computePathForInode(inode, builder); return new AlluxioURI(builder.toString()); }
java
public AlluxioURI getPath(InodeView inode) throws FileDoesNotExistException { StringBuilder builder = new StringBuilder(); computePathForInode(inode, builder); return new AlluxioURI(builder.toString()); }
[ "public", "AlluxioURI", "getPath", "(", "InodeView", "inode", ")", "throws", "FileDoesNotExistException", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "computePathForInode", "(", "inode", ",", "builder", ")", ";", "return", "new", "AlluxioURI", "(", "builder", ".", "toString", "(", ")", ")", ";", "}" ]
Returns the path for a particular inode. The inode and the path to the inode must already be locked. @param inode the inode to get the path for @return the {@link AlluxioURI} for the path of the inode @throws FileDoesNotExistException if the path does not exist
[ "Returns", "the", "path", "for", "a", "particular", "inode", ".", "The", "inode", "and", "the", "path", "to", "the", "inode", "must", "already", "be", "locked", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L551-L555
18,765
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.inheritOwnerAndGroupIfEmpty
private static void inheritOwnerAndGroupIfEmpty(MutableInode<?> newInode, InodeDirectoryView ancestorInode) { if (ServerConfiguration.getBoolean(PropertyKey.MASTER_METASTORE_INODE_INHERIT_OWNER_AND_GROUP) && newInode.getOwner().isEmpty() && newInode.getGroup().isEmpty()) { // Inherit owner / group if empty newInode.setOwner(ancestorInode.getOwner()); newInode.setGroup(ancestorInode.getGroup()); } }
java
private static void inheritOwnerAndGroupIfEmpty(MutableInode<?> newInode, InodeDirectoryView ancestorInode) { if (ServerConfiguration.getBoolean(PropertyKey.MASTER_METASTORE_INODE_INHERIT_OWNER_AND_GROUP) && newInode.getOwner().isEmpty() && newInode.getGroup().isEmpty()) { // Inherit owner / group if empty newInode.setOwner(ancestorInode.getOwner()); newInode.setGroup(ancestorInode.getGroup()); } }
[ "private", "static", "void", "inheritOwnerAndGroupIfEmpty", "(", "MutableInode", "<", "?", ">", "newInode", ",", "InodeDirectoryView", "ancestorInode", ")", "{", "if", "(", "ServerConfiguration", ".", "getBoolean", "(", "PropertyKey", ".", "MASTER_METASTORE_INODE_INHERIT_OWNER_AND_GROUP", ")", "&&", "newInode", ".", "getOwner", "(", ")", ".", "isEmpty", "(", ")", "&&", "newInode", ".", "getGroup", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "// Inherit owner / group if empty", "newInode", ".", "setOwner", "(", "ancestorInode", ".", "getOwner", "(", ")", ")", ";", "newInode", ".", "setGroup", "(", "ancestorInode", ".", "getGroup", "(", ")", ")", ";", "}", "}" ]
Inherit owner and group from ancestor if both are empty
[ "Inherit", "owner", "and", "group", "from", "ancestor", "if", "both", "are", "empty" ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L798-L806
18,766
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.deleteInode
public void deleteInode(RpcContext rpcContext, LockedInodePath inodePath, long opTimeMs) throws FileDoesNotExistException { Preconditions.checkState(inodePath.getLockPattern() == LockPattern.WRITE_EDGE); Inode inode = inodePath.getInode(); mState.applyAndJournal(rpcContext, DeleteFileEntry.newBuilder() .setId(inode.getId()) .setRecursive(false) .setOpTimeMs(opTimeMs) .build()); if (inode.isFile()) { rpcContext.getBlockDeletionContext().registerBlocksForDeletion(inode.asFile().getBlockIds()); } }
java
public void deleteInode(RpcContext rpcContext, LockedInodePath inodePath, long opTimeMs) throws FileDoesNotExistException { Preconditions.checkState(inodePath.getLockPattern() == LockPattern.WRITE_EDGE); Inode inode = inodePath.getInode(); mState.applyAndJournal(rpcContext, DeleteFileEntry.newBuilder() .setId(inode.getId()) .setRecursive(false) .setOpTimeMs(opTimeMs) .build()); if (inode.isFile()) { rpcContext.getBlockDeletionContext().registerBlocksForDeletion(inode.asFile().getBlockIds()); } }
[ "public", "void", "deleteInode", "(", "RpcContext", "rpcContext", ",", "LockedInodePath", "inodePath", ",", "long", "opTimeMs", ")", "throws", "FileDoesNotExistException", "{", "Preconditions", ".", "checkState", "(", "inodePath", ".", "getLockPattern", "(", ")", "==", "LockPattern", ".", "WRITE_EDGE", ")", ";", "Inode", "inode", "=", "inodePath", ".", "getInode", "(", ")", ";", "mState", ".", "applyAndJournal", "(", "rpcContext", ",", "DeleteFileEntry", ".", "newBuilder", "(", ")", ".", "setId", "(", "inode", ".", "getId", "(", ")", ")", ".", "setRecursive", "(", "false", ")", ".", "setOpTimeMs", "(", "opTimeMs", ")", ".", "build", "(", ")", ")", ";", "if", "(", "inode", ".", "isFile", "(", ")", ")", "{", "rpcContext", ".", "getBlockDeletionContext", "(", ")", ".", "registerBlocksForDeletion", "(", "inode", ".", "asFile", "(", ")", ".", "getBlockIds", "(", ")", ")", ";", "}", "}" ]
Deletes a single inode from the inode tree by removing it from the parent inode. @param rpcContext the rpc context @param inodePath the {@link LockedInodePath} to delete @param opTimeMs the operation time @throws FileDoesNotExistException if the Inode cannot be retrieved
[ "Deletes", "a", "single", "inode", "from", "the", "inode", "tree", "by", "removing", "it", "from", "the", "parent", "inode", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L852-L866
18,767
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.setPinned
public void setPinned(RpcContext rpcContext, LockedInodePath inodePath, boolean pinned, long opTimeMs) throws FileDoesNotExistException, InvalidPathException { Preconditions.checkState(inodePath.getLockPattern().isWrite()); Inode inode = inodePath.getInode(); mState.applyAndJournal(rpcContext, UpdateInodeEntry.newBuilder() .setId(inode.getId()) .setPinned(pinned) .setLastModificationTimeMs(opTimeMs) .build()); if (inode.isDirectory()) { assert inode instanceof InodeDirectory; // inode is a directory. Set the pinned state for all children. for (Inode child : mInodeStore.getChildren(inode.asDirectory())) { try (LockedInodePath childPath = inodePath.lockChild(child, LockPattern.WRITE_INODE)) { // No need for additional locking since the parent is write-locked. setPinned(rpcContext, childPath, pinned, opTimeMs); } } } }
java
public void setPinned(RpcContext rpcContext, LockedInodePath inodePath, boolean pinned, long opTimeMs) throws FileDoesNotExistException, InvalidPathException { Preconditions.checkState(inodePath.getLockPattern().isWrite()); Inode inode = inodePath.getInode(); mState.applyAndJournal(rpcContext, UpdateInodeEntry.newBuilder() .setId(inode.getId()) .setPinned(pinned) .setLastModificationTimeMs(opTimeMs) .build()); if (inode.isDirectory()) { assert inode instanceof InodeDirectory; // inode is a directory. Set the pinned state for all children. for (Inode child : mInodeStore.getChildren(inode.asDirectory())) { try (LockedInodePath childPath = inodePath.lockChild(child, LockPattern.WRITE_INODE)) { // No need for additional locking since the parent is write-locked. setPinned(rpcContext, childPath, pinned, opTimeMs); } } } }
[ "public", "void", "setPinned", "(", "RpcContext", "rpcContext", ",", "LockedInodePath", "inodePath", ",", "boolean", "pinned", ",", "long", "opTimeMs", ")", "throws", "FileDoesNotExistException", ",", "InvalidPathException", "{", "Preconditions", ".", "checkState", "(", "inodePath", ".", "getLockPattern", "(", ")", ".", "isWrite", "(", ")", ")", ";", "Inode", "inode", "=", "inodePath", ".", "getInode", "(", ")", ";", "mState", ".", "applyAndJournal", "(", "rpcContext", ",", "UpdateInodeEntry", ".", "newBuilder", "(", ")", ".", "setId", "(", "inode", ".", "getId", "(", ")", ")", ".", "setPinned", "(", "pinned", ")", ".", "setLastModificationTimeMs", "(", "opTimeMs", ")", ".", "build", "(", ")", ")", ";", "if", "(", "inode", ".", "isDirectory", "(", ")", ")", "{", "assert", "inode", "instanceof", "InodeDirectory", ";", "// inode is a directory. Set the pinned state for all children.", "for", "(", "Inode", "child", ":", "mInodeStore", ".", "getChildren", "(", "inode", ".", "asDirectory", "(", ")", ")", ")", "{", "try", "(", "LockedInodePath", "childPath", "=", "inodePath", ".", "lockChild", "(", "child", ",", "LockPattern", ".", "WRITE_INODE", ")", ")", "{", "// No need for additional locking since the parent is write-locked.", "setPinned", "(", "rpcContext", ",", "childPath", ",", "pinned", ",", "opTimeMs", ")", ";", "}", "}", "}", "}" ]
Sets the pinned state of an inode. If the inode is a directory, the pinned state will be set recursively. @param rpcContext the rpc context @param inodePath the {@link LockedInodePath} to set the pinned state for @param pinned the pinned state to set for the inode (and possible descendants) @param opTimeMs the operation time @throws FileDoesNotExistException if inode does not exist
[ "Sets", "the", "pinned", "state", "of", "an", "inode", ".", "If", "the", "inode", "is", "a", "directory", "the", "pinned", "state", "will", "be", "set", "recursively", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L878-L901
18,768
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.syncPersistExistingDirectory
public void syncPersistExistingDirectory(Supplier<JournalContext> context, InodeDirectoryView dir) throws IOException, InvalidPathException, FileDoesNotExistException { RetryPolicy retry = new ExponentialBackoffRetry(PERSIST_WAIT_BASE_SLEEP_MS, PERSIST_WAIT_MAX_SLEEP_MS, PERSIST_WAIT_MAX_RETRIES); while (retry.attempt()) { if (dir.getPersistenceState() == PersistenceState.PERSISTED) { // The directory is persisted return; } Optional<Scoped> persisting = mInodeLockManager.tryAcquirePersistingLock(dir.getId()); if (!persisting.isPresent()) { // Someone else is doing this persist. Continue and wait for them to finish. continue; } try (Scoped s = persisting.get()) { if (dir.getPersistenceState() == PersistenceState.PERSISTED) { // The directory is persisted return; } mState.applyAndJournal(context, UpdateInodeEntry.newBuilder() .setId(dir.getId()) .setPersistenceState(PersistenceState.TO_BE_PERSISTED.name()) .build()); UpdateInodeEntry.Builder entry = UpdateInodeEntry.newBuilder() .setId(dir.getId()); syncPersistDirectory(dir).ifPresent(status -> { if (isRootId(dir.getId())) { // Don't load the root dir metadata from UFS return; } entry.setOwner(status.getOwner()) .setGroup(status.getGroup()) .setMode(status.getMode()); Long lastModificationTime = status.getLastModifiedTime(); if (lastModificationTime != null) { entry.setLastModificationTimeMs(lastModificationTime) .setOverwriteModificationTime(true); } }); entry.setPersistenceState(PersistenceState.PERSISTED.name()); mState.applyAndJournal(context, entry.build()); return; } } throw new IOException(ExceptionMessage.FAILED_UFS_CREATE.getMessage(dir.getName())); }
java
public void syncPersistExistingDirectory(Supplier<JournalContext> context, InodeDirectoryView dir) throws IOException, InvalidPathException, FileDoesNotExistException { RetryPolicy retry = new ExponentialBackoffRetry(PERSIST_WAIT_BASE_SLEEP_MS, PERSIST_WAIT_MAX_SLEEP_MS, PERSIST_WAIT_MAX_RETRIES); while (retry.attempt()) { if (dir.getPersistenceState() == PersistenceState.PERSISTED) { // The directory is persisted return; } Optional<Scoped> persisting = mInodeLockManager.tryAcquirePersistingLock(dir.getId()); if (!persisting.isPresent()) { // Someone else is doing this persist. Continue and wait for them to finish. continue; } try (Scoped s = persisting.get()) { if (dir.getPersistenceState() == PersistenceState.PERSISTED) { // The directory is persisted return; } mState.applyAndJournal(context, UpdateInodeEntry.newBuilder() .setId(dir.getId()) .setPersistenceState(PersistenceState.TO_BE_PERSISTED.name()) .build()); UpdateInodeEntry.Builder entry = UpdateInodeEntry.newBuilder() .setId(dir.getId()); syncPersistDirectory(dir).ifPresent(status -> { if (isRootId(dir.getId())) { // Don't load the root dir metadata from UFS return; } entry.setOwner(status.getOwner()) .setGroup(status.getGroup()) .setMode(status.getMode()); Long lastModificationTime = status.getLastModifiedTime(); if (lastModificationTime != null) { entry.setLastModificationTimeMs(lastModificationTime) .setOverwriteModificationTime(true); } }); entry.setPersistenceState(PersistenceState.PERSISTED.name()); mState.applyAndJournal(context, entry.build()); return; } } throw new IOException(ExceptionMessage.FAILED_UFS_CREATE.getMessage(dir.getName())); }
[ "public", "void", "syncPersistExistingDirectory", "(", "Supplier", "<", "JournalContext", ">", "context", ",", "InodeDirectoryView", "dir", ")", "throws", "IOException", ",", "InvalidPathException", ",", "FileDoesNotExistException", "{", "RetryPolicy", "retry", "=", "new", "ExponentialBackoffRetry", "(", "PERSIST_WAIT_BASE_SLEEP_MS", ",", "PERSIST_WAIT_MAX_SLEEP_MS", ",", "PERSIST_WAIT_MAX_RETRIES", ")", ";", "while", "(", "retry", ".", "attempt", "(", ")", ")", "{", "if", "(", "dir", ".", "getPersistenceState", "(", ")", "==", "PersistenceState", ".", "PERSISTED", ")", "{", "// The directory is persisted", "return", ";", "}", "Optional", "<", "Scoped", ">", "persisting", "=", "mInodeLockManager", ".", "tryAcquirePersistingLock", "(", "dir", ".", "getId", "(", ")", ")", ";", "if", "(", "!", "persisting", ".", "isPresent", "(", ")", ")", "{", "// Someone else is doing this persist. Continue and wait for them to finish.", "continue", ";", "}", "try", "(", "Scoped", "s", "=", "persisting", ".", "get", "(", ")", ")", "{", "if", "(", "dir", ".", "getPersistenceState", "(", ")", "==", "PersistenceState", ".", "PERSISTED", ")", "{", "// The directory is persisted", "return", ";", "}", "mState", ".", "applyAndJournal", "(", "context", ",", "UpdateInodeEntry", ".", "newBuilder", "(", ")", ".", "setId", "(", "dir", ".", "getId", "(", ")", ")", ".", "setPersistenceState", "(", "PersistenceState", ".", "TO_BE_PERSISTED", ".", "name", "(", ")", ")", ".", "build", "(", ")", ")", ";", "UpdateInodeEntry", ".", "Builder", "entry", "=", "UpdateInodeEntry", ".", "newBuilder", "(", ")", ".", "setId", "(", "dir", ".", "getId", "(", ")", ")", ";", "syncPersistDirectory", "(", "dir", ")", ".", "ifPresent", "(", "status", "->", "{", "if", "(", "isRootId", "(", "dir", ".", "getId", "(", ")", ")", ")", "{", "// Don't load the root dir metadata from UFS", "return", ";", "}", "entry", ".", "setOwner", "(", "status", ".", "getOwner", "(", ")", ")", ".", "setGroup", "(", "status", ".", "getGroup", "(", ")", ")", ".", "setMode", "(", "status", ".", "getMode", "(", ")", ")", ";", "Long", "lastModificationTime", "=", "status", ".", "getLastModifiedTime", "(", ")", ";", "if", "(", "lastModificationTime", "!=", "null", ")", "{", "entry", ".", "setLastModificationTimeMs", "(", "lastModificationTime", ")", ".", "setOverwriteModificationTime", "(", "true", ")", ";", "}", "}", ")", ";", "entry", ".", "setPersistenceState", "(", "PersistenceState", ".", "PERSISTED", ".", "name", "(", ")", ")", ";", "mState", ".", "applyAndJournal", "(", "context", ",", "entry", ".", "build", "(", ")", ")", ";", "return", ";", "}", "}", "throw", "new", "IOException", "(", "ExceptionMessage", ".", "FAILED_UFS_CREATE", ".", "getMessage", "(", "dir", ".", "getName", "(", ")", ")", ")", ";", "}" ]
Synchronously persists an inode directory to the UFS. If concurrent calls are made, only one thread will persist to UFS, and the others will wait until it is persisted. @param context journal context supplier @param dir the inode directory to persist @throws InvalidPathException if the path for the inode is invalid @throws FileDoesNotExistException if the path for the inode is invalid
[ "Synchronously", "persists", "an", "inode", "directory", "to", "the", "UFS", ".", "If", "concurrent", "calls", "are", "made", "only", "one", "thread", "will", "persist", "to", "UFS", "and", "the", "others", "will", "wait", "until", "it", "is", "persisted", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L1010-L1058
18,769
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.syncPersistNewDirectory
public void syncPersistNewDirectory(MutableInodeDirectory dir) throws InvalidPathException, FileDoesNotExistException, IOException { dir.setPersistenceState(PersistenceState.TO_BE_PERSISTED); syncPersistDirectory(dir).ifPresent(status -> { // If the directory already exists in the UFS, update our metadata to match the UFS. dir.setOwner(status.getOwner()) .setGroup(status.getGroup()) .setMode(status.getMode()); Long lastModificationTime = status.getLastModifiedTime(); if (lastModificationTime != null) { dir.setLastModificationTimeMs(lastModificationTime, true); } }); dir.setPersistenceState(PersistenceState.PERSISTED); }
java
public void syncPersistNewDirectory(MutableInodeDirectory dir) throws InvalidPathException, FileDoesNotExistException, IOException { dir.setPersistenceState(PersistenceState.TO_BE_PERSISTED); syncPersistDirectory(dir).ifPresent(status -> { // If the directory already exists in the UFS, update our metadata to match the UFS. dir.setOwner(status.getOwner()) .setGroup(status.getGroup()) .setMode(status.getMode()); Long lastModificationTime = status.getLastModifiedTime(); if (lastModificationTime != null) { dir.setLastModificationTimeMs(lastModificationTime, true); } }); dir.setPersistenceState(PersistenceState.PERSISTED); }
[ "public", "void", "syncPersistNewDirectory", "(", "MutableInodeDirectory", "dir", ")", "throws", "InvalidPathException", ",", "FileDoesNotExistException", ",", "IOException", "{", "dir", ".", "setPersistenceState", "(", "PersistenceState", ".", "TO_BE_PERSISTED", ")", ";", "syncPersistDirectory", "(", "dir", ")", ".", "ifPresent", "(", "status", "->", "{", "// If the directory already exists in the UFS, update our metadata to match the UFS.", "dir", ".", "setOwner", "(", "status", ".", "getOwner", "(", ")", ")", ".", "setGroup", "(", "status", ".", "getGroup", "(", ")", ")", ".", "setMode", "(", "status", ".", "getMode", "(", ")", ")", ";", "Long", "lastModificationTime", "=", "status", ".", "getLastModifiedTime", "(", ")", ";", "if", "(", "lastModificationTime", "!=", "null", ")", "{", "dir", ".", "setLastModificationTimeMs", "(", "lastModificationTime", ",", "true", ")", ";", "}", "}", ")", ";", "dir", ".", "setPersistenceState", "(", "PersistenceState", ".", "PERSISTED", ")", ";", "}" ]
Synchronously persists an inode directory to the UFS. This method does not handle concurrent modification to the given inode, so the inode must not yet be added to the inode tree. @param dir the inode directory to persist
[ "Synchronously", "persists", "an", "inode", "directory", "to", "the", "UFS", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L1068-L1083
18,770
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.syncPersistDirectory
private Optional<UfsStatus> syncPersistDirectory(InodeDirectoryView dir) throws FileDoesNotExistException, IOException, InvalidPathException { AlluxioURI uri = getPath(dir); MountTable.Resolution resolution = mMountTable.resolve(uri); String ufsUri = resolution.getUri().toString(); try (CloseableResource<UnderFileSystem> ufsResource = resolution.acquireUfsResource()) { UnderFileSystem ufs = ufsResource.get(); MkdirsOptions mkdirsOptions = MkdirsOptions.defaults(ServerConfiguration.global()).setCreateParent(false) .setOwner(dir.getOwner()).setGroup(dir.getGroup()).setMode(new Mode(dir.getMode())); if (!ufs.mkdirs(ufsUri, mkdirsOptions)) { // Directory might already exist. Try loading the status from ufs. UfsStatus status; try { status = ufs.getStatus(ufsUri); } catch (Exception e) { throw new IOException(String.format("Cannot create or load UFS directory %s: %s.", ufsUri, e.toString()), e); } if (status.isFile()) { throw new InvalidPathException(String.format( "Error persisting directory. A file exists at the UFS location %s.", ufsUri)); } return Optional.of(status); } } return Optional.empty(); }
java
private Optional<UfsStatus> syncPersistDirectory(InodeDirectoryView dir) throws FileDoesNotExistException, IOException, InvalidPathException { AlluxioURI uri = getPath(dir); MountTable.Resolution resolution = mMountTable.resolve(uri); String ufsUri = resolution.getUri().toString(); try (CloseableResource<UnderFileSystem> ufsResource = resolution.acquireUfsResource()) { UnderFileSystem ufs = ufsResource.get(); MkdirsOptions mkdirsOptions = MkdirsOptions.defaults(ServerConfiguration.global()).setCreateParent(false) .setOwner(dir.getOwner()).setGroup(dir.getGroup()).setMode(new Mode(dir.getMode())); if (!ufs.mkdirs(ufsUri, mkdirsOptions)) { // Directory might already exist. Try loading the status from ufs. UfsStatus status; try { status = ufs.getStatus(ufsUri); } catch (Exception e) { throw new IOException(String.format("Cannot create or load UFS directory %s: %s.", ufsUri, e.toString()), e); } if (status.isFile()) { throw new InvalidPathException(String.format( "Error persisting directory. A file exists at the UFS location %s.", ufsUri)); } return Optional.of(status); } } return Optional.empty(); }
[ "private", "Optional", "<", "UfsStatus", ">", "syncPersistDirectory", "(", "InodeDirectoryView", "dir", ")", "throws", "FileDoesNotExistException", ",", "IOException", ",", "InvalidPathException", "{", "AlluxioURI", "uri", "=", "getPath", "(", "dir", ")", ";", "MountTable", ".", "Resolution", "resolution", "=", "mMountTable", ".", "resolve", "(", "uri", ")", ";", "String", "ufsUri", "=", "resolution", ".", "getUri", "(", ")", ".", "toString", "(", ")", ";", "try", "(", "CloseableResource", "<", "UnderFileSystem", ">", "ufsResource", "=", "resolution", ".", "acquireUfsResource", "(", ")", ")", "{", "UnderFileSystem", "ufs", "=", "ufsResource", ".", "get", "(", ")", ";", "MkdirsOptions", "mkdirsOptions", "=", "MkdirsOptions", ".", "defaults", "(", "ServerConfiguration", ".", "global", "(", ")", ")", ".", "setCreateParent", "(", "false", ")", ".", "setOwner", "(", "dir", ".", "getOwner", "(", ")", ")", ".", "setGroup", "(", "dir", ".", "getGroup", "(", ")", ")", ".", "setMode", "(", "new", "Mode", "(", "dir", ".", "getMode", "(", ")", ")", ")", ";", "if", "(", "!", "ufs", ".", "mkdirs", "(", "ufsUri", ",", "mkdirsOptions", ")", ")", "{", "// Directory might already exist. Try loading the status from ufs.", "UfsStatus", "status", ";", "try", "{", "status", "=", "ufs", ".", "getStatus", "(", "ufsUri", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IOException", "(", "String", ".", "format", "(", "\"Cannot create or load UFS directory %s: %s.\"", ",", "ufsUri", ",", "e", ".", "toString", "(", ")", ")", ",", "e", ")", ";", "}", "if", "(", "status", ".", "isFile", "(", ")", ")", "{", "throw", "new", "InvalidPathException", "(", "String", ".", "format", "(", "\"Error persisting directory. A file exists at the UFS location %s.\"", ",", "ufsUri", ")", ")", ";", "}", "return", "Optional", ".", "of", "(", "status", ")", ";", "}", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}" ]
Persists the directory to the UFS, returning the UFS status if the directory is found to already exist in the UFS. @param dir the directory to persist @return optional ufs status if the directory already existed
[ "Persists", "the", "directory", "to", "the", "UFS", "returning", "the", "UFS", "status", "if", "the", "directory", "is", "found", "to", "already", "exist", "in", "the", "UFS", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L1092-L1119
18,771
Alluxio/alluxio
job/server/src/main/java/alluxio/worker/AlluxioJobWorker.java
AlluxioJobWorker.main
public static void main(String[] args) { if (args.length != 0) { LOG.info("java -cp {} {}", RuntimeConstants.ALLUXIO_JAR, AlluxioJobWorker.class.getCanonicalName()); System.exit(-1); } if (!ConfigurationUtils.masterHostConfigured(ServerConfiguration.global())) { System.out.println(ConfigurationUtils .getMasterHostNotConfiguredMessage("Alluxio job worker")); System.exit(1); } if (!ConfigurationUtils.jobMasterHostConfigured(ServerConfiguration.global())) { System.out.println(ConfigurationUtils .getJobMasterHostNotConfiguredMessage("Alluxio job worker")); System.exit(1); } CommonUtils.PROCESS_TYPE.set(CommonUtils.ProcessType.JOB_WORKER); MasterInquireClient masterInquireClient = MasterInquireClient.Factory.create(ServerConfiguration.global()); try { RetryUtils.retry("load cluster default configuration with master", () -> { InetSocketAddress masterAddress = masterInquireClient.getPrimaryRpcAddress(); ServerConfiguration.loadClusterDefaults(masterAddress); }, RetryUtils.defaultWorkerMasterClientRetry( ServerConfiguration.getDuration(PropertyKey.WORKER_MASTER_CONNECT_RETRY_TIMEOUT))); } catch (IOException e) { ProcessUtils.fatalError(LOG, "Failed to load cluster default configuration for job worker: %s", e.getMessage()); } JobWorkerProcess process = JobWorkerProcess.Factory.create(); ProcessUtils.run(process); }
java
public static void main(String[] args) { if (args.length != 0) { LOG.info("java -cp {} {}", RuntimeConstants.ALLUXIO_JAR, AlluxioJobWorker.class.getCanonicalName()); System.exit(-1); } if (!ConfigurationUtils.masterHostConfigured(ServerConfiguration.global())) { System.out.println(ConfigurationUtils .getMasterHostNotConfiguredMessage("Alluxio job worker")); System.exit(1); } if (!ConfigurationUtils.jobMasterHostConfigured(ServerConfiguration.global())) { System.out.println(ConfigurationUtils .getJobMasterHostNotConfiguredMessage("Alluxio job worker")); System.exit(1); } CommonUtils.PROCESS_TYPE.set(CommonUtils.ProcessType.JOB_WORKER); MasterInquireClient masterInquireClient = MasterInquireClient.Factory.create(ServerConfiguration.global()); try { RetryUtils.retry("load cluster default configuration with master", () -> { InetSocketAddress masterAddress = masterInquireClient.getPrimaryRpcAddress(); ServerConfiguration.loadClusterDefaults(masterAddress); }, RetryUtils.defaultWorkerMasterClientRetry( ServerConfiguration.getDuration(PropertyKey.WORKER_MASTER_CONNECT_RETRY_TIMEOUT))); } catch (IOException e) { ProcessUtils.fatalError(LOG, "Failed to load cluster default configuration for job worker: %s", e.getMessage()); } JobWorkerProcess process = JobWorkerProcess.Factory.create(); ProcessUtils.run(process); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", "!=", "0", ")", "{", "LOG", ".", "info", "(", "\"java -cp {} {}\"", ",", "RuntimeConstants", ".", "ALLUXIO_JAR", ",", "AlluxioJobWorker", ".", "class", ".", "getCanonicalName", "(", ")", ")", ";", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "if", "(", "!", "ConfigurationUtils", ".", "masterHostConfigured", "(", "ServerConfiguration", ".", "global", "(", ")", ")", ")", "{", "System", ".", "out", ".", "println", "(", "ConfigurationUtils", ".", "getMasterHostNotConfiguredMessage", "(", "\"Alluxio job worker\"", ")", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "if", "(", "!", "ConfigurationUtils", ".", "jobMasterHostConfigured", "(", "ServerConfiguration", ".", "global", "(", ")", ")", ")", "{", "System", ".", "out", ".", "println", "(", "ConfigurationUtils", ".", "getJobMasterHostNotConfiguredMessage", "(", "\"Alluxio job worker\"", ")", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "CommonUtils", ".", "PROCESS_TYPE", ".", "set", "(", "CommonUtils", ".", "ProcessType", ".", "JOB_WORKER", ")", ";", "MasterInquireClient", "masterInquireClient", "=", "MasterInquireClient", ".", "Factory", ".", "create", "(", "ServerConfiguration", ".", "global", "(", ")", ")", ";", "try", "{", "RetryUtils", ".", "retry", "(", "\"load cluster default configuration with master\"", ",", "(", ")", "->", "{", "InetSocketAddress", "masterAddress", "=", "masterInquireClient", ".", "getPrimaryRpcAddress", "(", ")", ";", "ServerConfiguration", ".", "loadClusterDefaults", "(", "masterAddress", ")", ";", "}", ",", "RetryUtils", ".", "defaultWorkerMasterClientRetry", "(", "ServerConfiguration", ".", "getDuration", "(", "PropertyKey", ".", "WORKER_MASTER_CONNECT_RETRY_TIMEOUT", ")", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "ProcessUtils", ".", "fatalError", "(", "LOG", ",", "\"Failed to load cluster default configuration for job worker: %s\"", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "JobWorkerProcess", "process", "=", "JobWorkerProcess", ".", "Factory", ".", "create", "(", ")", ";", "ProcessUtils", ".", "run", "(", "process", ")", ";", "}" ]
Starts the Alluxio job worker. @param args command line arguments, should be empty
[ "Starts", "the", "Alluxio", "job", "worker", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/worker/AlluxioJobWorker.java#L43-L78
18,772
Alluxio/alluxio
integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java
ApplicationMaster.runApplicationMaster
private static void runApplicationMaster(final CommandLine cliParser, AlluxioConfiguration alluxioConf) throws Exception { int numWorkers = Integer.parseInt(cliParser.getOptionValue("num_workers", "1")); String masterAddress = cliParser.getOptionValue("master_address"); String resourcePath = cliParser.getOptionValue("resource_path"); ApplicationMaster applicationMaster = new ApplicationMaster(numWorkers, masterAddress, resourcePath, alluxioConf); applicationMaster.start(); applicationMaster.requestAndLaunchContainers(); applicationMaster.waitForShutdown(); applicationMaster.stop(); }
java
private static void runApplicationMaster(final CommandLine cliParser, AlluxioConfiguration alluxioConf) throws Exception { int numWorkers = Integer.parseInt(cliParser.getOptionValue("num_workers", "1")); String masterAddress = cliParser.getOptionValue("master_address"); String resourcePath = cliParser.getOptionValue("resource_path"); ApplicationMaster applicationMaster = new ApplicationMaster(numWorkers, masterAddress, resourcePath, alluxioConf); applicationMaster.start(); applicationMaster.requestAndLaunchContainers(); applicationMaster.waitForShutdown(); applicationMaster.stop(); }
[ "private", "static", "void", "runApplicationMaster", "(", "final", "CommandLine", "cliParser", ",", "AlluxioConfiguration", "alluxioConf", ")", "throws", "Exception", "{", "int", "numWorkers", "=", "Integer", ".", "parseInt", "(", "cliParser", ".", "getOptionValue", "(", "\"num_workers\"", ",", "\"1\"", ")", ")", ";", "String", "masterAddress", "=", "cliParser", ".", "getOptionValue", "(", "\"master_address\"", ")", ";", "String", "resourcePath", "=", "cliParser", ".", "getOptionValue", "(", "\"resource_path\"", ")", ";", "ApplicationMaster", "applicationMaster", "=", "new", "ApplicationMaster", "(", "numWorkers", ",", "masterAddress", ",", "resourcePath", ",", "alluxioConf", ")", ";", "applicationMaster", ".", "start", "(", ")", ";", "applicationMaster", ".", "requestAndLaunchContainers", "(", ")", ";", "applicationMaster", ".", "waitForShutdown", "(", ")", ";", "applicationMaster", ".", "stop", "(", ")", ";", "}" ]
Run the application master. @param cliParser client arguments parser
[ "Run", "the", "application", "master", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java#L233-L245
18,773
Alluxio/alluxio
integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java
ApplicationMaster.start
public void start() throws IOException, YarnException { if (UserGroupInformation.isSecurityEnabled()) { Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials(); DataOutputBuffer credentialsBuffer = new DataOutputBuffer(); credentials.writeTokenStorageToStream(credentialsBuffer); // Now remove the AM -> RM token so that containers cannot access it. Iterator<Token<?>> iter = credentials.getAllTokens().iterator(); while (iter.hasNext()) { Token<?> token = iter.next(); if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) { iter.remove(); } } mAllTokens = ByteBuffer.wrap(credentialsBuffer.getData(), 0, credentialsBuffer.getLength()); } mNMClient.init(mYarnConf); mNMClient.start(); mRMClient.init(mYarnConf); mRMClient.start(); mYarnClient.init(mYarnConf); mYarnClient.start(); // Register with ResourceManager String hostname = NetworkAddressUtils.getLocalHostName((int) mAlluxioConf .getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS)); mRMClient.registerApplicationMaster(hostname, 0 /* port */, "" /* tracking url */); LOG.info("ApplicationMaster registered"); }
java
public void start() throws IOException, YarnException { if (UserGroupInformation.isSecurityEnabled()) { Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials(); DataOutputBuffer credentialsBuffer = new DataOutputBuffer(); credentials.writeTokenStorageToStream(credentialsBuffer); // Now remove the AM -> RM token so that containers cannot access it. Iterator<Token<?>> iter = credentials.getAllTokens().iterator(); while (iter.hasNext()) { Token<?> token = iter.next(); if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) { iter.remove(); } } mAllTokens = ByteBuffer.wrap(credentialsBuffer.getData(), 0, credentialsBuffer.getLength()); } mNMClient.init(mYarnConf); mNMClient.start(); mRMClient.init(mYarnConf); mRMClient.start(); mYarnClient.init(mYarnConf); mYarnClient.start(); // Register with ResourceManager String hostname = NetworkAddressUtils.getLocalHostName((int) mAlluxioConf .getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS)); mRMClient.registerApplicationMaster(hostname, 0 /* port */, "" /* tracking url */); LOG.info("ApplicationMaster registered"); }
[ "public", "void", "start", "(", ")", "throws", "IOException", ",", "YarnException", "{", "if", "(", "UserGroupInformation", ".", "isSecurityEnabled", "(", ")", ")", "{", "Credentials", "credentials", "=", "UserGroupInformation", ".", "getCurrentUser", "(", ")", ".", "getCredentials", "(", ")", ";", "DataOutputBuffer", "credentialsBuffer", "=", "new", "DataOutputBuffer", "(", ")", ";", "credentials", ".", "writeTokenStorageToStream", "(", "credentialsBuffer", ")", ";", "// Now remove the AM -> RM token so that containers cannot access it.", "Iterator", "<", "Token", "<", "?", ">", ">", "iter", "=", "credentials", ".", "getAllTokens", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "Token", "<", "?", ">", "token", "=", "iter", ".", "next", "(", ")", ";", "if", "(", "token", ".", "getKind", "(", ")", ".", "equals", "(", "AMRMTokenIdentifier", ".", "KIND_NAME", ")", ")", "{", "iter", ".", "remove", "(", ")", ";", "}", "}", "mAllTokens", "=", "ByteBuffer", ".", "wrap", "(", "credentialsBuffer", ".", "getData", "(", ")", ",", "0", ",", "credentialsBuffer", ".", "getLength", "(", ")", ")", ";", "}", "mNMClient", ".", "init", "(", "mYarnConf", ")", ";", "mNMClient", ".", "start", "(", ")", ";", "mRMClient", ".", "init", "(", "mYarnConf", ")", ";", "mRMClient", ".", "start", "(", ")", ";", "mYarnClient", ".", "init", "(", "mYarnConf", ")", ";", "mYarnClient", ".", "start", "(", ")", ";", "// Register with ResourceManager", "String", "hostname", "=", "NetworkAddressUtils", ".", "getLocalHostName", "(", "(", "int", ")", "mAlluxioConf", ".", "getMs", "(", "PropertyKey", ".", "NETWORK_HOST_RESOLUTION_TIMEOUT_MS", ")", ")", ";", "mRMClient", ".", "registerApplicationMaster", "(", "hostname", ",", "0", "/* port */", ",", "\"\"", "/* tracking url */", ")", ";", "LOG", ".", "info", "(", "\"ApplicationMaster registered\"", ")", ";", "}" ]
Starts the application master.
[ "Starts", "the", "application", "master", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java#L289-L319
18,774
Alluxio/alluxio
integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java
ApplicationMaster.requestAndLaunchContainers
public void requestAndLaunchContainers() throws Exception { if (masterExists()) { InetAddress address = InetAddress.getByName(mMasterAddress); mMasterContainerNetAddress = address.getHostAddress(); LOG.info("Found master already running on " + mMasterAddress); } else { LOG.info("Configuring master container request."); Resource masterResource = Records.newRecord(Resource.class); masterResource.setMemory(mMasterMemInMB); masterResource.setVirtualCores(mMasterCpu); mContainerAllocator = new ContainerAllocator("master", 1, 1, masterResource, mYarnClient, mRMClient, mMasterAddress); List<Container> masterContainers = mContainerAllocator.allocateContainers(); launchMasterContainer(Iterables.getOnlyElement(masterContainers)); } Resource workerResource = Records.newRecord(Resource.class); workerResource.setMemory(mWorkerMemInMB + mRamdiskMemInMB); workerResource.setVirtualCores(mWorkerCpu); mContainerAllocator = new ContainerAllocator("worker", mNumWorkers, mMaxWorkersPerHost, workerResource, mYarnClient, mRMClient); List<Container> workerContainers = mContainerAllocator.allocateContainers(); for (Container container : workerContainers) { launchWorkerContainer(container); } LOG.info("Master and workers are launched"); }
java
public void requestAndLaunchContainers() throws Exception { if (masterExists()) { InetAddress address = InetAddress.getByName(mMasterAddress); mMasterContainerNetAddress = address.getHostAddress(); LOG.info("Found master already running on " + mMasterAddress); } else { LOG.info("Configuring master container request."); Resource masterResource = Records.newRecord(Resource.class); masterResource.setMemory(mMasterMemInMB); masterResource.setVirtualCores(mMasterCpu); mContainerAllocator = new ContainerAllocator("master", 1, 1, masterResource, mYarnClient, mRMClient, mMasterAddress); List<Container> masterContainers = mContainerAllocator.allocateContainers(); launchMasterContainer(Iterables.getOnlyElement(masterContainers)); } Resource workerResource = Records.newRecord(Resource.class); workerResource.setMemory(mWorkerMemInMB + mRamdiskMemInMB); workerResource.setVirtualCores(mWorkerCpu); mContainerAllocator = new ContainerAllocator("worker", mNumWorkers, mMaxWorkersPerHost, workerResource, mYarnClient, mRMClient); List<Container> workerContainers = mContainerAllocator.allocateContainers(); for (Container container : workerContainers) { launchWorkerContainer(container); } LOG.info("Master and workers are launched"); }
[ "public", "void", "requestAndLaunchContainers", "(", ")", "throws", "Exception", "{", "if", "(", "masterExists", "(", ")", ")", "{", "InetAddress", "address", "=", "InetAddress", ".", "getByName", "(", "mMasterAddress", ")", ";", "mMasterContainerNetAddress", "=", "address", ".", "getHostAddress", "(", ")", ";", "LOG", ".", "info", "(", "\"Found master already running on \"", "+", "mMasterAddress", ")", ";", "}", "else", "{", "LOG", ".", "info", "(", "\"Configuring master container request.\"", ")", ";", "Resource", "masterResource", "=", "Records", ".", "newRecord", "(", "Resource", ".", "class", ")", ";", "masterResource", ".", "setMemory", "(", "mMasterMemInMB", ")", ";", "masterResource", ".", "setVirtualCores", "(", "mMasterCpu", ")", ";", "mContainerAllocator", "=", "new", "ContainerAllocator", "(", "\"master\"", ",", "1", ",", "1", ",", "masterResource", ",", "mYarnClient", ",", "mRMClient", ",", "mMasterAddress", ")", ";", "List", "<", "Container", ">", "masterContainers", "=", "mContainerAllocator", ".", "allocateContainers", "(", ")", ";", "launchMasterContainer", "(", "Iterables", ".", "getOnlyElement", "(", "masterContainers", ")", ")", ";", "}", "Resource", "workerResource", "=", "Records", ".", "newRecord", "(", "Resource", ".", "class", ")", ";", "workerResource", ".", "setMemory", "(", "mWorkerMemInMB", "+", "mRamdiskMemInMB", ")", ";", "workerResource", ".", "setVirtualCores", "(", "mWorkerCpu", ")", ";", "mContainerAllocator", "=", "new", "ContainerAllocator", "(", "\"worker\"", ",", "mNumWorkers", ",", "mMaxWorkersPerHost", ",", "workerResource", ",", "mYarnClient", ",", "mRMClient", ")", ";", "List", "<", "Container", ">", "workerContainers", "=", "mContainerAllocator", ".", "allocateContainers", "(", ")", ";", "for", "(", "Container", "container", ":", "workerContainers", ")", "{", "launchWorkerContainer", "(", "container", ")", ";", "}", "LOG", ".", "info", "(", "\"Master and workers are launched\"", ")", ";", "}" ]
Submits requests for containers until the master and all workers are launched.
[ "Submits", "requests", "for", "containers", "until", "the", "master", "and", "all", "workers", "are", "launched", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java#L324-L351
18,775
Alluxio/alluxio
integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java
ApplicationMaster.stop
public void stop() { try { mRMClient.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "", ""); } catch (YarnException e) { LOG.error("Failed to unregister application", e); } catch (IOException e) { LOG.error("Failed to unregister application", e); } mRMClient.stop(); // TODO(andrew): Think about whether we should stop mNMClient here mYarnClient.stop(); }
java
public void stop() { try { mRMClient.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "", ""); } catch (YarnException e) { LOG.error("Failed to unregister application", e); } catch (IOException e) { LOG.error("Failed to unregister application", e); } mRMClient.stop(); // TODO(andrew): Think about whether we should stop mNMClient here mYarnClient.stop(); }
[ "public", "void", "stop", "(", ")", "{", "try", "{", "mRMClient", ".", "unregisterApplicationMaster", "(", "FinalApplicationStatus", ".", "SUCCEEDED", ",", "\"\"", ",", "\"\"", ")", ";", "}", "catch", "(", "YarnException", "e", ")", "{", "LOG", ".", "error", "(", "\"Failed to unregister application\"", ",", "e", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Failed to unregister application\"", ",", "e", ")", ";", "}", "mRMClient", ".", "stop", "(", ")", ";", "// TODO(andrew): Think about whether we should stop mNMClient here", "mYarnClient", ".", "stop", "(", ")", ";", "}" ]
Shuts down the application master, unregistering it from Yarn and stopping its clients.
[ "Shuts", "down", "the", "application", "master", "unregistering", "it", "from", "Yarn", "and", "stopping", "its", "clients", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java#L363-L374
18,776
Alluxio/alluxio
integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java
ApplicationMaster.masterExists
private boolean masterExists() { String webPort = mAlluxioConf.get(PropertyKey.MASTER_WEB_PORT); try { URL myURL = new URL("http://" + mMasterAddress + ":" + webPort + Constants.REST_API_PREFIX + "/master/version"); LOG.debug("Checking for master at: " + myURL.toString()); HttpURLConnection connection = (HttpURLConnection) myURL.openConnection(); connection.setRequestMethod(HttpMethod.GET); int resCode = connection.getResponseCode(); LOG.debug("Response code from master was: " + Integer.toString(resCode)); connection.disconnect(); return resCode == HttpURLConnection.HTTP_OK; } catch (MalformedURLException e) { LOG.error("Malformed URL in attempt to check if master is running already", e); } catch (IOException e) { LOG.debug("No existing master found", e); } return false; }
java
private boolean masterExists() { String webPort = mAlluxioConf.get(PropertyKey.MASTER_WEB_PORT); try { URL myURL = new URL("http://" + mMasterAddress + ":" + webPort + Constants.REST_API_PREFIX + "/master/version"); LOG.debug("Checking for master at: " + myURL.toString()); HttpURLConnection connection = (HttpURLConnection) myURL.openConnection(); connection.setRequestMethod(HttpMethod.GET); int resCode = connection.getResponseCode(); LOG.debug("Response code from master was: " + Integer.toString(resCode)); connection.disconnect(); return resCode == HttpURLConnection.HTTP_OK; } catch (MalformedURLException e) { LOG.error("Malformed URL in attempt to check if master is running already", e); } catch (IOException e) { LOG.debug("No existing master found", e); } return false; }
[ "private", "boolean", "masterExists", "(", ")", "{", "String", "webPort", "=", "mAlluxioConf", ".", "get", "(", "PropertyKey", ".", "MASTER_WEB_PORT", ")", ";", "try", "{", "URL", "myURL", "=", "new", "URL", "(", "\"http://\"", "+", "mMasterAddress", "+", "\":\"", "+", "webPort", "+", "Constants", ".", "REST_API_PREFIX", "+", "\"/master/version\"", ")", ";", "LOG", ".", "debug", "(", "\"Checking for master at: \"", "+", "myURL", ".", "toString", "(", ")", ")", ";", "HttpURLConnection", "connection", "=", "(", "HttpURLConnection", ")", "myURL", ".", "openConnection", "(", ")", ";", "connection", ".", "setRequestMethod", "(", "HttpMethod", ".", "GET", ")", ";", "int", "resCode", "=", "connection", ".", "getResponseCode", "(", ")", ";", "LOG", ".", "debug", "(", "\"Response code from master was: \"", "+", "Integer", ".", "toString", "(", "resCode", ")", ")", ";", "connection", ".", "disconnect", "(", ")", ";", "return", "resCode", "==", "HttpURLConnection", ".", "HTTP_OK", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "LOG", ".", "error", "(", "\"Malformed URL in attempt to check if master is running already\"", ",", "e", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "debug", "(", "\"No existing master found\"", ",", "e", ")", ";", "}", "return", "false", ";", "}" ]
Checks if an Alluxio master node is already running or not on the master address given. @return true if master exists, false otherwise
[ "Checks", "if", "an", "Alluxio", "master", "node", "is", "already", "running", "or", "not", "on", "the", "master", "address", "given", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/yarn/src/main/java/alluxio/yarn/ApplicationMaster.java#L424-L445
18,777
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/FaultTolerantAlluxioMasterProcess.java
FaultTolerantAlluxioMasterProcess.gainPrimacy
private boolean gainPrimacy() throws Exception { // Don't upgrade if this master's primacy is unstable. AtomicBoolean unstable = new AtomicBoolean(false); try (Scoped scoped = mLeaderSelector.onStateChange(state -> unstable.set(true))) { if (mLeaderSelector.getState() != State.PRIMARY) { unstable.set(true); } stopMasters(); LOG.info("Secondary stopped"); mJournalSystem.gainPrimacy(); // We only check unstable here because mJournalSystem.gainPrimacy() is the only slow method if (unstable.get()) { losePrimacy(); return false; } } startMasters(true); mServingThread = new Thread(() -> { try { startServing(" (gained leadership)", " (lost leadership)"); } catch (Throwable t) { Throwable root = ExceptionUtils.getRootCause(t); if ((root != null && (root instanceof InterruptedException)) || Thread.interrupted()) { return; } ProcessUtils.fatalError(LOG, t, "Exception thrown in main serving thread"); } }, "MasterServingThread"); mServingThread.start(); if (!waitForReady(10 * Constants.MINUTE_MS)) { ThreadUtils.logAllThreads(); throw new RuntimeException("Alluxio master failed to come up"); } LOG.info("Primary started"); return true; }
java
private boolean gainPrimacy() throws Exception { // Don't upgrade if this master's primacy is unstable. AtomicBoolean unstable = new AtomicBoolean(false); try (Scoped scoped = mLeaderSelector.onStateChange(state -> unstable.set(true))) { if (mLeaderSelector.getState() != State.PRIMARY) { unstable.set(true); } stopMasters(); LOG.info("Secondary stopped"); mJournalSystem.gainPrimacy(); // We only check unstable here because mJournalSystem.gainPrimacy() is the only slow method if (unstable.get()) { losePrimacy(); return false; } } startMasters(true); mServingThread = new Thread(() -> { try { startServing(" (gained leadership)", " (lost leadership)"); } catch (Throwable t) { Throwable root = ExceptionUtils.getRootCause(t); if ((root != null && (root instanceof InterruptedException)) || Thread.interrupted()) { return; } ProcessUtils.fatalError(LOG, t, "Exception thrown in main serving thread"); } }, "MasterServingThread"); mServingThread.start(); if (!waitForReady(10 * Constants.MINUTE_MS)) { ThreadUtils.logAllThreads(); throw new RuntimeException("Alluxio master failed to come up"); } LOG.info("Primary started"); return true; }
[ "private", "boolean", "gainPrimacy", "(", ")", "throws", "Exception", "{", "// Don't upgrade if this master's primacy is unstable.", "AtomicBoolean", "unstable", "=", "new", "AtomicBoolean", "(", "false", ")", ";", "try", "(", "Scoped", "scoped", "=", "mLeaderSelector", ".", "onStateChange", "(", "state", "->", "unstable", ".", "set", "(", "true", ")", ")", ")", "{", "if", "(", "mLeaderSelector", ".", "getState", "(", ")", "!=", "State", ".", "PRIMARY", ")", "{", "unstable", ".", "set", "(", "true", ")", ";", "}", "stopMasters", "(", ")", ";", "LOG", ".", "info", "(", "\"Secondary stopped\"", ")", ";", "mJournalSystem", ".", "gainPrimacy", "(", ")", ";", "// We only check unstable here because mJournalSystem.gainPrimacy() is the only slow method", "if", "(", "unstable", ".", "get", "(", ")", ")", "{", "losePrimacy", "(", ")", ";", "return", "false", ";", "}", "}", "startMasters", "(", "true", ")", ";", "mServingThread", "=", "new", "Thread", "(", "(", ")", "->", "{", "try", "{", "startServing", "(", "\" (gained leadership)\"", ",", "\" (lost leadership)\"", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "Throwable", "root", "=", "ExceptionUtils", ".", "getRootCause", "(", "t", ")", ";", "if", "(", "(", "root", "!=", "null", "&&", "(", "root", "instanceof", "InterruptedException", ")", ")", "||", "Thread", ".", "interrupted", "(", ")", ")", "{", "return", ";", "}", "ProcessUtils", ".", "fatalError", "(", "LOG", ",", "t", ",", "\"Exception thrown in main serving thread\"", ")", ";", "}", "}", ",", "\"MasterServingThread\"", ")", ";", "mServingThread", ".", "start", "(", ")", ";", "if", "(", "!", "waitForReady", "(", "10", "*", "Constants", ".", "MINUTE_MS", ")", ")", "{", "ThreadUtils", ".", "logAllThreads", "(", ")", ";", "throw", "new", "RuntimeException", "(", "\"Alluxio master failed to come up\"", ")", ";", "}", "LOG", ".", "info", "(", "\"Primary started\"", ")", ";", "return", "true", ";", "}" ]
Upgrades the master to primary mode. If the master loses primacy during the journal upgrade, this method will clean up the partial upgrade, leaving the master in secondary mode. @return whether the master successfully upgraded to primary
[ "Upgrades", "the", "master", "to", "primary", "mode", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/FaultTolerantAlluxioMasterProcess.java#L105-L140
18,778
Alluxio/alluxio
core/common/src/main/java/alluxio/util/HFSUtils.java
HFSUtils.getNumSector
public static long getNumSector(String requestSize, String sectorSize) { Double memSize = Double.parseDouble(requestSize); Double sectorBytes = Double.parseDouble(sectorSize); Double nSectors = memSize / sectorBytes; Double memSizeKB = memSize / 1024; Double memSizeGB = memSize / (1024 * 1024 * 1024); Double memSize100GB = memSizeGB / 100; // allocation bitmap file: one bit per sector Double allocBitmapSize = nSectors / 8; // extend overflow file: 4MB, plus 4MB per 100GB Double extOverflowFileSize = memSize100GB * 1024 * 1024 * 4; // journal file: 8MB, plus 8MB per 100GB Double journalFileSize = memSize100GB * 1024 * 1024 * 8; // catalog file: 10bytes per KB Double catalogFileSize = memSizeKB * 10; // hot files: 5bytes per KB Double hotFileSize = memSizeKB * 5; // quota users file and quota groups file Double quotaUsersFileSize = (memSizeGB * 256 + 1) * 64; Double quotaGroupsFileSize = (memSizeGB * 32 + 1) * 64; Double metadataSize = allocBitmapSize + extOverflowFileSize + journalFileSize + catalogFileSize + hotFileSize + quotaUsersFileSize + quotaGroupsFileSize; Double allocSize = memSize + metadataSize; Double numSectors = allocSize / sectorBytes; System.out.println(numSectors.longValue() + 1); // round up return numSectors.longValue() + 1; }
java
public static long getNumSector(String requestSize, String sectorSize) { Double memSize = Double.parseDouble(requestSize); Double sectorBytes = Double.parseDouble(sectorSize); Double nSectors = memSize / sectorBytes; Double memSizeKB = memSize / 1024; Double memSizeGB = memSize / (1024 * 1024 * 1024); Double memSize100GB = memSizeGB / 100; // allocation bitmap file: one bit per sector Double allocBitmapSize = nSectors / 8; // extend overflow file: 4MB, plus 4MB per 100GB Double extOverflowFileSize = memSize100GB * 1024 * 1024 * 4; // journal file: 8MB, plus 8MB per 100GB Double journalFileSize = memSize100GB * 1024 * 1024 * 8; // catalog file: 10bytes per KB Double catalogFileSize = memSizeKB * 10; // hot files: 5bytes per KB Double hotFileSize = memSizeKB * 5; // quota users file and quota groups file Double quotaUsersFileSize = (memSizeGB * 256 + 1) * 64; Double quotaGroupsFileSize = (memSizeGB * 32 + 1) * 64; Double metadataSize = allocBitmapSize + extOverflowFileSize + journalFileSize + catalogFileSize + hotFileSize + quotaUsersFileSize + quotaGroupsFileSize; Double allocSize = memSize + metadataSize; Double numSectors = allocSize / sectorBytes; System.out.println(numSectors.longValue() + 1); // round up return numSectors.longValue() + 1; }
[ "public", "static", "long", "getNumSector", "(", "String", "requestSize", ",", "String", "sectorSize", ")", "{", "Double", "memSize", "=", "Double", ".", "parseDouble", "(", "requestSize", ")", ";", "Double", "sectorBytes", "=", "Double", ".", "parseDouble", "(", "sectorSize", ")", ";", "Double", "nSectors", "=", "memSize", "/", "sectorBytes", ";", "Double", "memSizeKB", "=", "memSize", "/", "1024", ";", "Double", "memSizeGB", "=", "memSize", "/", "(", "1024", "*", "1024", "*", "1024", ")", ";", "Double", "memSize100GB", "=", "memSizeGB", "/", "100", ";", "// allocation bitmap file: one bit per sector", "Double", "allocBitmapSize", "=", "nSectors", "/", "8", ";", "// extend overflow file: 4MB, plus 4MB per 100GB", "Double", "extOverflowFileSize", "=", "memSize100GB", "*", "1024", "*", "1024", "*", "4", ";", "// journal file: 8MB, plus 8MB per 100GB", "Double", "journalFileSize", "=", "memSize100GB", "*", "1024", "*", "1024", "*", "8", ";", "// catalog file: 10bytes per KB", "Double", "catalogFileSize", "=", "memSizeKB", "*", "10", ";", "// hot files: 5bytes per KB", "Double", "hotFileSize", "=", "memSizeKB", "*", "5", ";", "// quota users file and quota groups file", "Double", "quotaUsersFileSize", "=", "(", "memSizeGB", "*", "256", "+", "1", ")", "*", "64", ";", "Double", "quotaGroupsFileSize", "=", "(", "memSizeGB", "*", "32", "+", "1", ")", "*", "64", ";", "Double", "metadataSize", "=", "allocBitmapSize", "+", "extOverflowFileSize", "+", "journalFileSize", "+", "catalogFileSize", "+", "hotFileSize", "+", "quotaUsersFileSize", "+", "quotaGroupsFileSize", ";", "Double", "allocSize", "=", "memSize", "+", "metadataSize", ";", "Double", "numSectors", "=", "allocSize", "/", "sectorBytes", ";", "System", ".", "out", ".", "println", "(", "numSectors", ".", "longValue", "(", ")", "+", "1", ")", ";", "// round up", "return", "numSectors", ".", "longValue", "(", ")", "+", "1", ";", "}" ]
Converts the memory size to number of sectors. @param requestSize requested filesystem size in bytes @param sectorSize the size of each sector in bytes @return total sectors of HFS+ including estimated metadata zone size
[ "Converts", "the", "memory", "size", "to", "number", "of", "sectors", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/HFSUtils.java#L29-L63
18,779
Alluxio/alluxio
core/common/src/main/java/alluxio/util/HFSUtils.java
HFSUtils.main
public static void main(String[] args) { if (args.length != 2) { System.exit(-1); } String mem = args[0]; String sector = args[1]; try { getNumSector(mem, sector); } catch (Exception e) { throw new RuntimeException(e); } }
java
public static void main(String[] args) { if (args.length != 2) { System.exit(-1); } String mem = args[0]; String sector = args[1]; try { getNumSector(mem, sector); } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", "!=", "2", ")", "{", "System", ".", "exit", "(", "-", "1", ")", ";", "}", "String", "mem", "=", "args", "[", "0", "]", ";", "String", "sector", "=", "args", "[", "1", "]", ";", "try", "{", "getNumSector", "(", "mem", ",", "sector", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
The main class to invoke the getNumSector. @param args the arguments parsed by commandline
[ "The", "main", "class", "to", "invoke", "the", "getNumSector", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/HFSUtils.java#L70-L81
18,780
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/AsyncUfsAbsentPathCache.java
AsyncUfsAbsentPathCache.processSinglePath
private boolean processSinglePath(AlluxioURI alluxioUri, MountInfo mountInfo) { PathLock pathLock = new PathLock(); Lock writeLock = pathLock.writeLock(); Lock readLock = null; try { // Write lock this path, to only enable a single task per path writeLock.lock(); PathLock existingLock = mCurrentPaths.putIfAbsent(alluxioUri.getPath(), pathLock); if (existingLock != null) { // Another thread already locked this path and is processing it. Wait for the other // thread to finish, by locking the existing read lock. writeLock.unlock(); writeLock = null; readLock = existingLock.readLock(); readLock.lock(); if (mCache.getIfPresent(alluxioUri.getPath()) != null) { // This path is already in the cache (is absent). Further traversal is unnecessary. return false; } } else { // This thread has the exclusive lock for this path. // Resolve this Alluxio uri. It should match the original mount id. MountTable.Resolution resolution = mMountTable.resolve(alluxioUri); if (resolution.getMountId() != mountInfo.getMountId()) { // This mount point has changed. Further traversal is unnecessary. return false; } boolean existsInUfs; try (CloseableResource<UnderFileSystem> ufsResource = resolution.acquireUfsResource()) { UnderFileSystem ufs = ufsResource.get(); existsInUfs = ufs.exists(resolution.getUri().toString()); } if (existsInUfs) { // This ufs path exists. Remove the cache entry. mCache.invalidate(alluxioUri.getPath()); } else { // This is the first ufs path which does not exist. Add it to the cache. mCache.put(alluxioUri.getPath(), mountInfo.getMountId()); if (pathLock.isInvalidate()) { // This path was marked to be invalidated, meaning this UFS path was just created, // and now exists. Invalidate the entry. // This check is necessary to avoid the race with the invalidating thread. mCache.invalidate(alluxioUri.getPath()); } else { // Further traversal is unnecessary. return false; } } } } catch (InvalidPathException | IOException e) { LOG.warn("Processing path failed: " + alluxioUri, e); return false; } finally { // Unlock the path if (readLock != null) { readLock.unlock(); } if (writeLock != null) { mCurrentPaths.remove(alluxioUri.getPath(), pathLock); writeLock.unlock(); } } return true; }
java
private boolean processSinglePath(AlluxioURI alluxioUri, MountInfo mountInfo) { PathLock pathLock = new PathLock(); Lock writeLock = pathLock.writeLock(); Lock readLock = null; try { // Write lock this path, to only enable a single task per path writeLock.lock(); PathLock existingLock = mCurrentPaths.putIfAbsent(alluxioUri.getPath(), pathLock); if (existingLock != null) { // Another thread already locked this path and is processing it. Wait for the other // thread to finish, by locking the existing read lock. writeLock.unlock(); writeLock = null; readLock = existingLock.readLock(); readLock.lock(); if (mCache.getIfPresent(alluxioUri.getPath()) != null) { // This path is already in the cache (is absent). Further traversal is unnecessary. return false; } } else { // This thread has the exclusive lock for this path. // Resolve this Alluxio uri. It should match the original mount id. MountTable.Resolution resolution = mMountTable.resolve(alluxioUri); if (resolution.getMountId() != mountInfo.getMountId()) { // This mount point has changed. Further traversal is unnecessary. return false; } boolean existsInUfs; try (CloseableResource<UnderFileSystem> ufsResource = resolution.acquireUfsResource()) { UnderFileSystem ufs = ufsResource.get(); existsInUfs = ufs.exists(resolution.getUri().toString()); } if (existsInUfs) { // This ufs path exists. Remove the cache entry. mCache.invalidate(alluxioUri.getPath()); } else { // This is the first ufs path which does not exist. Add it to the cache. mCache.put(alluxioUri.getPath(), mountInfo.getMountId()); if (pathLock.isInvalidate()) { // This path was marked to be invalidated, meaning this UFS path was just created, // and now exists. Invalidate the entry. // This check is necessary to avoid the race with the invalidating thread. mCache.invalidate(alluxioUri.getPath()); } else { // Further traversal is unnecessary. return false; } } } } catch (InvalidPathException | IOException e) { LOG.warn("Processing path failed: " + alluxioUri, e); return false; } finally { // Unlock the path if (readLock != null) { readLock.unlock(); } if (writeLock != null) { mCurrentPaths.remove(alluxioUri.getPath(), pathLock); writeLock.unlock(); } } return true; }
[ "private", "boolean", "processSinglePath", "(", "AlluxioURI", "alluxioUri", ",", "MountInfo", "mountInfo", ")", "{", "PathLock", "pathLock", "=", "new", "PathLock", "(", ")", ";", "Lock", "writeLock", "=", "pathLock", ".", "writeLock", "(", ")", ";", "Lock", "readLock", "=", "null", ";", "try", "{", "// Write lock this path, to only enable a single task per path", "writeLock", ".", "lock", "(", ")", ";", "PathLock", "existingLock", "=", "mCurrentPaths", ".", "putIfAbsent", "(", "alluxioUri", ".", "getPath", "(", ")", ",", "pathLock", ")", ";", "if", "(", "existingLock", "!=", "null", ")", "{", "// Another thread already locked this path and is processing it. Wait for the other", "// thread to finish, by locking the existing read lock.", "writeLock", ".", "unlock", "(", ")", ";", "writeLock", "=", "null", ";", "readLock", "=", "existingLock", ".", "readLock", "(", ")", ";", "readLock", ".", "lock", "(", ")", ";", "if", "(", "mCache", ".", "getIfPresent", "(", "alluxioUri", ".", "getPath", "(", ")", ")", "!=", "null", ")", "{", "// This path is already in the cache (is absent). Further traversal is unnecessary.", "return", "false", ";", "}", "}", "else", "{", "// This thread has the exclusive lock for this path.", "// Resolve this Alluxio uri. It should match the original mount id.", "MountTable", ".", "Resolution", "resolution", "=", "mMountTable", ".", "resolve", "(", "alluxioUri", ")", ";", "if", "(", "resolution", ".", "getMountId", "(", ")", "!=", "mountInfo", ".", "getMountId", "(", ")", ")", "{", "// This mount point has changed. Further traversal is unnecessary.", "return", "false", ";", "}", "boolean", "existsInUfs", ";", "try", "(", "CloseableResource", "<", "UnderFileSystem", ">", "ufsResource", "=", "resolution", ".", "acquireUfsResource", "(", ")", ")", "{", "UnderFileSystem", "ufs", "=", "ufsResource", ".", "get", "(", ")", ";", "existsInUfs", "=", "ufs", ".", "exists", "(", "resolution", ".", "getUri", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "if", "(", "existsInUfs", ")", "{", "// This ufs path exists. Remove the cache entry.", "mCache", ".", "invalidate", "(", "alluxioUri", ".", "getPath", "(", ")", ")", ";", "}", "else", "{", "// This is the first ufs path which does not exist. Add it to the cache.", "mCache", ".", "put", "(", "alluxioUri", ".", "getPath", "(", ")", ",", "mountInfo", ".", "getMountId", "(", ")", ")", ";", "if", "(", "pathLock", ".", "isInvalidate", "(", ")", ")", "{", "// This path was marked to be invalidated, meaning this UFS path was just created,", "// and now exists. Invalidate the entry.", "// This check is necessary to avoid the race with the invalidating thread.", "mCache", ".", "invalidate", "(", "alluxioUri", ".", "getPath", "(", ")", ")", ";", "}", "else", "{", "// Further traversal is unnecessary.", "return", "false", ";", "}", "}", "}", "}", "catch", "(", "InvalidPathException", "|", "IOException", "e", ")", "{", "LOG", ".", "warn", "(", "\"Processing path failed: \"", "+", "alluxioUri", ",", "e", ")", ";", "return", "false", ";", "}", "finally", "{", "// Unlock the path", "if", "(", "readLock", "!=", "null", ")", "{", "readLock", ".", "unlock", "(", ")", ";", "}", "if", "(", "writeLock", "!=", "null", ")", "{", "mCurrentPaths", ".", "remove", "(", "alluxioUri", ".", "getPath", "(", ")", ",", "pathLock", ")", ";", "writeLock", ".", "unlock", "(", ")", ";", "}", "}", "return", "true", ";", "}" ]
Processes and checks the existence of the corresponding ufs path for the given Alluxio path. @param alluxioUri the Alluxio path to process @param mountInfo the associated {@link MountInfo} for the Alluxio path @return if true, further traversal of the descendant paths should continue
[ "Processes", "and", "checks", "the", "existence", "of", "the", "corresponding", "ufs", "path", "for", "the", "given", "Alluxio", "path", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/AsyncUfsAbsentPathCache.java#L138-L205
18,781
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/AsyncUfsAbsentPathCache.java
AsyncUfsAbsentPathCache.getNestedPaths
private List<AlluxioURI> getNestedPaths(AlluxioURI alluxioUri, int startComponentIndex) { try { String[] fullComponents = PathUtils.getPathComponents(alluxioUri.getPath()); String[] baseComponents = Arrays.copyOfRange(fullComponents, 0, startComponentIndex); AlluxioURI uri = new AlluxioURI( PathUtils.concatPath(AlluxioURI.SEPARATOR, baseComponents)); List<AlluxioURI> components = new ArrayList<>(fullComponents.length - startComponentIndex); for (int i = startComponentIndex; i < fullComponents.length; i++) { uri = uri.joinUnsafe(fullComponents[i]); components.add(uri); } return components; } catch (InvalidPathException e) { return Collections.emptyList(); } }
java
private List<AlluxioURI> getNestedPaths(AlluxioURI alluxioUri, int startComponentIndex) { try { String[] fullComponents = PathUtils.getPathComponents(alluxioUri.getPath()); String[] baseComponents = Arrays.copyOfRange(fullComponents, 0, startComponentIndex); AlluxioURI uri = new AlluxioURI( PathUtils.concatPath(AlluxioURI.SEPARATOR, baseComponents)); List<AlluxioURI> components = new ArrayList<>(fullComponents.length - startComponentIndex); for (int i = startComponentIndex; i < fullComponents.length; i++) { uri = uri.joinUnsafe(fullComponents[i]); components.add(uri); } return components; } catch (InvalidPathException e) { return Collections.emptyList(); } }
[ "private", "List", "<", "AlluxioURI", ">", "getNestedPaths", "(", "AlluxioURI", "alluxioUri", ",", "int", "startComponentIndex", ")", "{", "try", "{", "String", "[", "]", "fullComponents", "=", "PathUtils", ".", "getPathComponents", "(", "alluxioUri", ".", "getPath", "(", ")", ")", ";", "String", "[", "]", "baseComponents", "=", "Arrays", ".", "copyOfRange", "(", "fullComponents", ",", "0", ",", "startComponentIndex", ")", ";", "AlluxioURI", "uri", "=", "new", "AlluxioURI", "(", "PathUtils", ".", "concatPath", "(", "AlluxioURI", ".", "SEPARATOR", ",", "baseComponents", ")", ")", ";", "List", "<", "AlluxioURI", ">", "components", "=", "new", "ArrayList", "<>", "(", "fullComponents", ".", "length", "-", "startComponentIndex", ")", ";", "for", "(", "int", "i", "=", "startComponentIndex", ";", "i", "<", "fullComponents", ".", "length", ";", "i", "++", ")", "{", "uri", "=", "uri", ".", "joinUnsafe", "(", "fullComponents", "[", "i", "]", ")", ";", "components", ".", "add", "(", "uri", ")", ";", "}", "return", "components", ";", "}", "catch", "(", "InvalidPathException", "e", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "}" ]
Returns a sequence of Alluxio paths for a specified path, starting from the path component at a specific index, to the specified path. @param alluxioUri the Alluxio path to get the nested paths for @param startComponentIndex the index to the starting path component, root directory has index 0 @return a list of nested paths from the starting component to the given path
[ "Returns", "a", "sequence", "of", "Alluxio", "paths", "for", "a", "specified", "path", "starting", "from", "the", "path", "component", "at", "a", "specific", "index", "to", "the", "specified", "path", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/AsyncUfsAbsentPathCache.java#L231-L246
18,782
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CpCommand.java
CpCommand.copyWildcard
private void copyWildcard(List<AlluxioURI> srcPaths, AlluxioURI dstPath, boolean recursive) throws AlluxioException, IOException { URIStatus dstStatus = null; try { dstStatus = mFileSystem.getStatus(dstPath); } catch (FileDoesNotExistException e) { // if the destination does not exist, it will be created } if (dstStatus != null && !dstStatus.isFolder()) { throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage()); } if (dstStatus == null) { mFileSystem.createDirectory(dstPath); System.out.println("Created directory: " + dstPath); } List<String> errorMessages = new ArrayList<>(); for (AlluxioURI srcPath : srcPaths) { try { copy(srcPath, new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), PathUtils.concatPath(dstPath.getPath(), srcPath.getName())), recursive); } catch (AlluxioException | IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { throw new IOException(Joiner.on('\n').join(errorMessages)); } }
java
private void copyWildcard(List<AlluxioURI> srcPaths, AlluxioURI dstPath, boolean recursive) throws AlluxioException, IOException { URIStatus dstStatus = null; try { dstStatus = mFileSystem.getStatus(dstPath); } catch (FileDoesNotExistException e) { // if the destination does not exist, it will be created } if (dstStatus != null && !dstStatus.isFolder()) { throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage()); } if (dstStatus == null) { mFileSystem.createDirectory(dstPath); System.out.println("Created directory: " + dstPath); } List<String> errorMessages = new ArrayList<>(); for (AlluxioURI srcPath : srcPaths) { try { copy(srcPath, new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), PathUtils.concatPath(dstPath.getPath(), srcPath.getName())), recursive); } catch (AlluxioException | IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { throw new IOException(Joiner.on('\n').join(errorMessages)); } }
[ "private", "void", "copyWildcard", "(", "List", "<", "AlluxioURI", ">", "srcPaths", ",", "AlluxioURI", "dstPath", ",", "boolean", "recursive", ")", "throws", "AlluxioException", ",", "IOException", "{", "URIStatus", "dstStatus", "=", "null", ";", "try", "{", "dstStatus", "=", "mFileSystem", ".", "getStatus", "(", "dstPath", ")", ";", "}", "catch", "(", "FileDoesNotExistException", "e", ")", "{", "// if the destination does not exist, it will be created", "}", "if", "(", "dstStatus", "!=", "null", "&&", "!", "dstStatus", ".", "isFolder", "(", ")", ")", "{", "throw", "new", "InvalidPathException", "(", "ExceptionMessage", ".", "DESTINATION_CANNOT_BE_FILE", ".", "getMessage", "(", ")", ")", ";", "}", "if", "(", "dstStatus", "==", "null", ")", "{", "mFileSystem", ".", "createDirectory", "(", "dstPath", ")", ";", "System", ".", "out", ".", "println", "(", "\"Created directory: \"", "+", "dstPath", ")", ";", "}", "List", "<", "String", ">", "errorMessages", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "AlluxioURI", "srcPath", ":", "srcPaths", ")", "{", "try", "{", "copy", "(", "srcPath", ",", "new", "AlluxioURI", "(", "dstPath", ".", "getScheme", "(", ")", ",", "dstPath", ".", "getAuthority", "(", ")", ",", "PathUtils", ".", "concatPath", "(", "dstPath", ".", "getPath", "(", ")", ",", "srcPath", ".", "getName", "(", ")", ")", ")", ",", "recursive", ")", ";", "}", "catch", "(", "AlluxioException", "|", "IOException", "e", ")", "{", "errorMessages", ".", "add", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "if", "(", "errorMessages", ".", "size", "(", ")", "!=", "0", ")", "{", "throw", "new", "IOException", "(", "Joiner", ".", "on", "(", "'", "'", ")", ".", "join", "(", "errorMessages", ")", ")", ";", "}", "}" ]
Copies a list of files or directories specified by srcPaths to the destination specified by dstPath. This method is used when the original source path contains wildcards. @param srcPaths a list of files or directories in the Alluxio filesystem @param dstPath the destination in the Alluxio filesystem @param recursive indicates whether directories should be copied recursively
[ "Copies", "a", "list", "of", "files", "or", "directories", "specified", "by", "srcPaths", "to", "the", "destination", "specified", "by", "dstPath", ".", "This", "method", "is", "used", "when", "the", "original", "source", "path", "contains", "wildcards", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L431-L459
18,783
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CpCommand.java
CpCommand.copy
private void copy(AlluxioURI srcPath, AlluxioURI dstPath, boolean recursive) throws AlluxioException, IOException { URIStatus srcStatus = mFileSystem.getStatus(srcPath); URIStatus dstStatus = null; try { dstStatus = mFileSystem.getStatus(dstPath); } catch (FileDoesNotExistException e) { // if the destination does not exist, it will be created } if (!srcStatus.isFolder()) { if (dstStatus != null && dstStatus.isFolder()) { dstPath = new AlluxioURI(PathUtils.concatPath(dstPath.getPath(), srcPath.getName())); } copyFile(srcPath, dstPath); } else { if (!recursive) { throw new IOException( srcPath.getPath() + " is a directory, to copy it please use \"cp -R <src> <dst>\""); } List<URIStatus> statuses; statuses = mFileSystem.listStatus(srcPath); if (dstStatus != null) { if (!dstStatus.isFolder()) { throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage()); } // if copying a directory to an existing directory, the copied directory will become a // subdirectory of the destination if (srcStatus.isFolder()) { dstPath = new AlluxioURI(PathUtils.concatPath(dstPath.getPath(), srcPath.getName())); mFileSystem.createDirectory(dstPath); System.out.println("Created directory: " + dstPath); } } if (dstStatus == null) { mFileSystem.createDirectory(dstPath); System.out.println("Created directory: " + dstPath); } preserveAttributes(srcPath, dstPath); List<String> errorMessages = new ArrayList<>(); for (URIStatus status : statuses) { try { copy(new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), status.getPath()), new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), PathUtils.concatPath(dstPath.getPath(), status.getName())), recursive); } catch (IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { throw new IOException(Joiner.on('\n').join(errorMessages)); } } }
java
private void copy(AlluxioURI srcPath, AlluxioURI dstPath, boolean recursive) throws AlluxioException, IOException { URIStatus srcStatus = mFileSystem.getStatus(srcPath); URIStatus dstStatus = null; try { dstStatus = mFileSystem.getStatus(dstPath); } catch (FileDoesNotExistException e) { // if the destination does not exist, it will be created } if (!srcStatus.isFolder()) { if (dstStatus != null && dstStatus.isFolder()) { dstPath = new AlluxioURI(PathUtils.concatPath(dstPath.getPath(), srcPath.getName())); } copyFile(srcPath, dstPath); } else { if (!recursive) { throw new IOException( srcPath.getPath() + " is a directory, to copy it please use \"cp -R <src> <dst>\""); } List<URIStatus> statuses; statuses = mFileSystem.listStatus(srcPath); if (dstStatus != null) { if (!dstStatus.isFolder()) { throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage()); } // if copying a directory to an existing directory, the copied directory will become a // subdirectory of the destination if (srcStatus.isFolder()) { dstPath = new AlluxioURI(PathUtils.concatPath(dstPath.getPath(), srcPath.getName())); mFileSystem.createDirectory(dstPath); System.out.println("Created directory: " + dstPath); } } if (dstStatus == null) { mFileSystem.createDirectory(dstPath); System.out.println("Created directory: " + dstPath); } preserveAttributes(srcPath, dstPath); List<String> errorMessages = new ArrayList<>(); for (URIStatus status : statuses) { try { copy(new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), status.getPath()), new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), PathUtils.concatPath(dstPath.getPath(), status.getName())), recursive); } catch (IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { throw new IOException(Joiner.on('\n').join(errorMessages)); } } }
[ "private", "void", "copy", "(", "AlluxioURI", "srcPath", ",", "AlluxioURI", "dstPath", ",", "boolean", "recursive", ")", "throws", "AlluxioException", ",", "IOException", "{", "URIStatus", "srcStatus", "=", "mFileSystem", ".", "getStatus", "(", "srcPath", ")", ";", "URIStatus", "dstStatus", "=", "null", ";", "try", "{", "dstStatus", "=", "mFileSystem", ".", "getStatus", "(", "dstPath", ")", ";", "}", "catch", "(", "FileDoesNotExistException", "e", ")", "{", "// if the destination does not exist, it will be created", "}", "if", "(", "!", "srcStatus", ".", "isFolder", "(", ")", ")", "{", "if", "(", "dstStatus", "!=", "null", "&&", "dstStatus", ".", "isFolder", "(", ")", ")", "{", "dstPath", "=", "new", "AlluxioURI", "(", "PathUtils", ".", "concatPath", "(", "dstPath", ".", "getPath", "(", ")", ",", "srcPath", ".", "getName", "(", ")", ")", ")", ";", "}", "copyFile", "(", "srcPath", ",", "dstPath", ")", ";", "}", "else", "{", "if", "(", "!", "recursive", ")", "{", "throw", "new", "IOException", "(", "srcPath", ".", "getPath", "(", ")", "+", "\" is a directory, to copy it please use \\\"cp -R <src> <dst>\\\"\"", ")", ";", "}", "List", "<", "URIStatus", ">", "statuses", ";", "statuses", "=", "mFileSystem", ".", "listStatus", "(", "srcPath", ")", ";", "if", "(", "dstStatus", "!=", "null", ")", "{", "if", "(", "!", "dstStatus", ".", "isFolder", "(", ")", ")", "{", "throw", "new", "InvalidPathException", "(", "ExceptionMessage", ".", "DESTINATION_CANNOT_BE_FILE", ".", "getMessage", "(", ")", ")", ";", "}", "// if copying a directory to an existing directory, the copied directory will become a", "// subdirectory of the destination", "if", "(", "srcStatus", ".", "isFolder", "(", ")", ")", "{", "dstPath", "=", "new", "AlluxioURI", "(", "PathUtils", ".", "concatPath", "(", "dstPath", ".", "getPath", "(", ")", ",", "srcPath", ".", "getName", "(", ")", ")", ")", ";", "mFileSystem", ".", "createDirectory", "(", "dstPath", ")", ";", "System", ".", "out", ".", "println", "(", "\"Created directory: \"", "+", "dstPath", ")", ";", "}", "}", "if", "(", "dstStatus", "==", "null", ")", "{", "mFileSystem", ".", "createDirectory", "(", "dstPath", ")", ";", "System", ".", "out", ".", "println", "(", "\"Created directory: \"", "+", "dstPath", ")", ";", "}", "preserveAttributes", "(", "srcPath", ",", "dstPath", ")", ";", "List", "<", "String", ">", "errorMessages", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "URIStatus", "status", ":", "statuses", ")", "{", "try", "{", "copy", "(", "new", "AlluxioURI", "(", "srcPath", ".", "getScheme", "(", ")", ",", "srcPath", ".", "getAuthority", "(", ")", ",", "status", ".", "getPath", "(", ")", ")", ",", "new", "AlluxioURI", "(", "dstPath", ".", "getScheme", "(", ")", ",", "dstPath", ".", "getAuthority", "(", ")", ",", "PathUtils", ".", "concatPath", "(", "dstPath", ".", "getPath", "(", ")", ",", "status", ".", "getName", "(", ")", ")", ")", ",", "recursive", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "errorMessages", ".", "add", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "if", "(", "errorMessages", ".", "size", "(", ")", "!=", "0", ")", "{", "throw", "new", "IOException", "(", "Joiner", ".", "on", "(", "'", "'", ")", ".", "join", "(", "errorMessages", ")", ")", ";", "}", "}", "}" ]
Copies a file or a directory in the Alluxio filesystem. @param srcPath the source {@link AlluxioURI} (could be a file or a directory) @param dstPath the {@link AlluxioURI} of the destination path in the Alluxio filesystem @param recursive indicates whether directories should be copied recursively
[ "Copies", "a", "file", "or", "a", "directory", "in", "the", "Alluxio", "filesystem", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L468-L527
18,784
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CpCommand.java
CpCommand.copyFile
private void copyFile(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException { try (Closer closer = Closer.create()) { FileInStream is = closer.register(mFileSystem.openFile(srcPath)); FileOutStream os = closer.register(mFileSystem.createFile(dstPath)); try { IOUtils.copy(is, os); } catch (Exception e) { os.cancel(); throw e; } System.out.println(String.format(COPY_SUCCEED_MESSAGE, srcPath, dstPath)); } preserveAttributes(srcPath, dstPath); }
java
private void copyFile(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException { try (Closer closer = Closer.create()) { FileInStream is = closer.register(mFileSystem.openFile(srcPath)); FileOutStream os = closer.register(mFileSystem.createFile(dstPath)); try { IOUtils.copy(is, os); } catch (Exception e) { os.cancel(); throw e; } System.out.println(String.format(COPY_SUCCEED_MESSAGE, srcPath, dstPath)); } preserveAttributes(srcPath, dstPath); }
[ "private", "void", "copyFile", "(", "AlluxioURI", "srcPath", ",", "AlluxioURI", "dstPath", ")", "throws", "AlluxioException", ",", "IOException", "{", "try", "(", "Closer", "closer", "=", "Closer", ".", "create", "(", ")", ")", "{", "FileInStream", "is", "=", "closer", ".", "register", "(", "mFileSystem", ".", "openFile", "(", "srcPath", ")", ")", ";", "FileOutStream", "os", "=", "closer", ".", "register", "(", "mFileSystem", ".", "createFile", "(", "dstPath", ")", ")", ";", "try", "{", "IOUtils", ".", "copy", "(", "is", ",", "os", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "os", ".", "cancel", "(", ")", ";", "throw", "e", ";", "}", "System", ".", "out", ".", "println", "(", "String", ".", "format", "(", "COPY_SUCCEED_MESSAGE", ",", "srcPath", ",", "dstPath", ")", ")", ";", "}", "preserveAttributes", "(", "srcPath", ",", "dstPath", ")", ";", "}" ]
Copies a file in the Alluxio filesystem. @param srcPath the source {@link AlluxioURI} (has to be a file) @param dstPath the destination path in the Alluxio filesystem
[ "Copies", "a", "file", "in", "the", "Alluxio", "filesystem", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L535-L549
18,785
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CpCommand.java
CpCommand.preserveAttributes
private void preserveAttributes(AlluxioURI srcPath, AlluxioURI dstPath) throws IOException, AlluxioException { if (mPreservePermissions) { URIStatus srcStatus = mFileSystem.getStatus(srcPath); mFileSystem.setAttribute(dstPath, SetAttributePOptions.newBuilder() .setOwner(srcStatus.getOwner()) .setGroup(srcStatus.getGroup()) .setMode(new Mode((short) srcStatus.getMode()).toProto()) .build()); mFileSystem.setAcl(dstPath, SetAclAction.REPLACE, srcStatus.getAcl().getEntries()); } }
java
private void preserveAttributes(AlluxioURI srcPath, AlluxioURI dstPath) throws IOException, AlluxioException { if (mPreservePermissions) { URIStatus srcStatus = mFileSystem.getStatus(srcPath); mFileSystem.setAttribute(dstPath, SetAttributePOptions.newBuilder() .setOwner(srcStatus.getOwner()) .setGroup(srcStatus.getGroup()) .setMode(new Mode((short) srcStatus.getMode()).toProto()) .build()); mFileSystem.setAcl(dstPath, SetAclAction.REPLACE, srcStatus.getAcl().getEntries()); } }
[ "private", "void", "preserveAttributes", "(", "AlluxioURI", "srcPath", ",", "AlluxioURI", "dstPath", ")", "throws", "IOException", ",", "AlluxioException", "{", "if", "(", "mPreservePermissions", ")", "{", "URIStatus", "srcStatus", "=", "mFileSystem", ".", "getStatus", "(", "srcPath", ")", ";", "mFileSystem", ".", "setAttribute", "(", "dstPath", ",", "SetAttributePOptions", ".", "newBuilder", "(", ")", ".", "setOwner", "(", "srcStatus", ".", "getOwner", "(", ")", ")", ".", "setGroup", "(", "srcStatus", ".", "getGroup", "(", ")", ")", ".", "setMode", "(", "new", "Mode", "(", "(", "short", ")", "srcStatus", ".", "getMode", "(", ")", ")", ".", "toProto", "(", ")", ")", ".", "build", "(", ")", ")", ";", "mFileSystem", ".", "setAcl", "(", "dstPath", ",", "SetAclAction", ".", "REPLACE", ",", "srcStatus", ".", "getAcl", "(", ")", ".", "getEntries", "(", ")", ")", ";", "}", "}" ]
Preserves attributes from the source file to the target file. @param srcPath the source path @param dstPath the destination path in the Alluxio filesystem
[ "Preserves", "attributes", "from", "the", "source", "file", "to", "the", "target", "file", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L557-L568
18,786
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CpCommand.java
CpCommand.createDstDir
private void createDstDir(AlluxioURI dstPath) throws AlluxioException, IOException { try { mFileSystem.createDirectory(dstPath); } catch (FileAlreadyExistsException e) { // it's fine if the directory already exists } URIStatus dstStatus = mFileSystem.getStatus(dstPath); if (!dstStatus.isFolder()) { throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage()); } }
java
private void createDstDir(AlluxioURI dstPath) throws AlluxioException, IOException { try { mFileSystem.createDirectory(dstPath); } catch (FileAlreadyExistsException e) { // it's fine if the directory already exists } URIStatus dstStatus = mFileSystem.getStatus(dstPath); if (!dstStatus.isFolder()) { throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage()); } }
[ "private", "void", "createDstDir", "(", "AlluxioURI", "dstPath", ")", "throws", "AlluxioException", ",", "IOException", "{", "try", "{", "mFileSystem", ".", "createDirectory", "(", "dstPath", ")", ";", "}", "catch", "(", "FileAlreadyExistsException", "e", ")", "{", "// it's fine if the directory already exists", "}", "URIStatus", "dstStatus", "=", "mFileSystem", ".", "getStatus", "(", "dstPath", ")", ";", "if", "(", "!", "dstStatus", ".", "isFolder", "(", ")", ")", "{", "throw", "new", "InvalidPathException", "(", "ExceptionMessage", ".", "DESTINATION_CANNOT_BE_FILE", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Creates a directory in the Alluxio filesystem space. It will not throw any exception if the destination directory already exists. @param dstPath the {@link AlluxioURI} of the destination directory which will be created
[ "Creates", "a", "directory", "in", "the", "Alluxio", "filesystem", "space", ".", "It", "will", "not", "throw", "any", "exception", "if", "the", "destination", "directory", "already", "exists", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L576-L587
18,787
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CpCommand.java
CpCommand.asyncCopyLocalPath
private void asyncCopyLocalPath(CopyThreadPoolExecutor pool, AlluxioURI srcPath, AlluxioURI dstPath) throws InterruptedException { File src = new File(srcPath.getPath()); if (!src.isDirectory()) { pool.submit(() -> { try { copyFromLocalFile(srcPath, dstPath); pool.succeed(srcPath, dstPath); } catch (Exception e) { pool.fail(srcPath, dstPath, e); } return null; }); } else { try { mFileSystem.createDirectory(dstPath); } catch (Exception e) { pool.fail(srcPath, dstPath, e); return; } File[] fileList = src.listFiles(); if (fileList == null) { pool.fail(srcPath, dstPath, new IOException(String.format("Failed to list directory %s.", src))); return; } for (File srcFile : fileList) { AlluxioURI newURI = new AlluxioURI(dstPath, new AlluxioURI(srcFile.getName())); asyncCopyLocalPath(pool, new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), srcFile.getPath()), newURI); } } }
java
private void asyncCopyLocalPath(CopyThreadPoolExecutor pool, AlluxioURI srcPath, AlluxioURI dstPath) throws InterruptedException { File src = new File(srcPath.getPath()); if (!src.isDirectory()) { pool.submit(() -> { try { copyFromLocalFile(srcPath, dstPath); pool.succeed(srcPath, dstPath); } catch (Exception e) { pool.fail(srcPath, dstPath, e); } return null; }); } else { try { mFileSystem.createDirectory(dstPath); } catch (Exception e) { pool.fail(srcPath, dstPath, e); return; } File[] fileList = src.listFiles(); if (fileList == null) { pool.fail(srcPath, dstPath, new IOException(String.format("Failed to list directory %s.", src))); return; } for (File srcFile : fileList) { AlluxioURI newURI = new AlluxioURI(dstPath, new AlluxioURI(srcFile.getName())); asyncCopyLocalPath(pool, new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), srcFile.getPath()), newURI); } } }
[ "private", "void", "asyncCopyLocalPath", "(", "CopyThreadPoolExecutor", "pool", ",", "AlluxioURI", "srcPath", ",", "AlluxioURI", "dstPath", ")", "throws", "InterruptedException", "{", "File", "src", "=", "new", "File", "(", "srcPath", ".", "getPath", "(", ")", ")", ";", "if", "(", "!", "src", ".", "isDirectory", "(", ")", ")", "{", "pool", ".", "submit", "(", "(", ")", "->", "{", "try", "{", "copyFromLocalFile", "(", "srcPath", ",", "dstPath", ")", ";", "pool", ".", "succeed", "(", "srcPath", ",", "dstPath", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "pool", ".", "fail", "(", "srcPath", ",", "dstPath", ",", "e", ")", ";", "}", "return", "null", ";", "}", ")", ";", "}", "else", "{", "try", "{", "mFileSystem", ".", "createDirectory", "(", "dstPath", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "pool", ".", "fail", "(", "srcPath", ",", "dstPath", ",", "e", ")", ";", "return", ";", "}", "File", "[", "]", "fileList", "=", "src", ".", "listFiles", "(", ")", ";", "if", "(", "fileList", "==", "null", ")", "{", "pool", ".", "fail", "(", "srcPath", ",", "dstPath", ",", "new", "IOException", "(", "String", ".", "format", "(", "\"Failed to list directory %s.\"", ",", "src", ")", ")", ")", ";", "return", ";", "}", "for", "(", "File", "srcFile", ":", "fileList", ")", "{", "AlluxioURI", "newURI", "=", "new", "AlluxioURI", "(", "dstPath", ",", "new", "AlluxioURI", "(", "srcFile", ".", "getName", "(", ")", ")", ")", ";", "asyncCopyLocalPath", "(", "pool", ",", "new", "AlluxioURI", "(", "srcPath", ".", "getScheme", "(", ")", ",", "srcPath", ".", "getAuthority", "(", ")", ",", "srcFile", ".", "getPath", "(", ")", ")", ",", "newURI", ")", ";", "}", "}", "}" ]
Asynchronously copies a file or directory specified by srcPath from the local filesystem to dstPath in the Alluxio filesystem space, assuming dstPath does not exist. @param srcPath the {@link AlluxioURI} of the source file in the local filesystem @param dstPath the {@link AlluxioURI} of the destination @throws InterruptedException when failed to send messages to the pool
[ "Asynchronously", "copies", "a", "file", "or", "directory", "specified", "by", "srcPath", "from", "the", "local", "filesystem", "to", "dstPath", "in", "the", "Alluxio", "filesystem", "space", "assuming", "dstPath", "does", "not", "exist", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L632-L665
18,788
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CpCommand.java
CpCommand.copyWildcardToLocal
private void copyWildcardToLocal(List<AlluxioURI> srcPaths, AlluxioURI dstPath) throws AlluxioException, IOException { File dstFile = new File(dstPath.getPath()); if (dstFile.exists() && !dstFile.isDirectory()) { throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage()); } if (!dstFile.exists()) { if (!dstFile.mkdirs()) { throw new IOException("Fail to create directory: " + dstPath); } else { System.out.println("Create directory: " + dstPath); } } List<String> errorMessages = new ArrayList<>(); for (AlluxioURI srcPath : srcPaths) { try { File dstSubFile = new File(dstFile.getAbsoluteFile(), srcPath.getName()); copyToLocal(srcPath, new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), dstSubFile.getPath())); } catch (IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { throw new IOException(Joiner.on('\n').join(errorMessages)); } }
java
private void copyWildcardToLocal(List<AlluxioURI> srcPaths, AlluxioURI dstPath) throws AlluxioException, IOException { File dstFile = new File(dstPath.getPath()); if (dstFile.exists() && !dstFile.isDirectory()) { throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage()); } if (!dstFile.exists()) { if (!dstFile.mkdirs()) { throw new IOException("Fail to create directory: " + dstPath); } else { System.out.println("Create directory: " + dstPath); } } List<String> errorMessages = new ArrayList<>(); for (AlluxioURI srcPath : srcPaths) { try { File dstSubFile = new File(dstFile.getAbsoluteFile(), srcPath.getName()); copyToLocal(srcPath, new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), dstSubFile.getPath())); } catch (IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { throw new IOException(Joiner.on('\n').join(errorMessages)); } }
[ "private", "void", "copyWildcardToLocal", "(", "List", "<", "AlluxioURI", ">", "srcPaths", ",", "AlluxioURI", "dstPath", ")", "throws", "AlluxioException", ",", "IOException", "{", "File", "dstFile", "=", "new", "File", "(", "dstPath", ".", "getPath", "(", ")", ")", ";", "if", "(", "dstFile", ".", "exists", "(", ")", "&&", "!", "dstFile", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "InvalidPathException", "(", "ExceptionMessage", ".", "DESTINATION_CANNOT_BE_FILE", ".", "getMessage", "(", ")", ")", ";", "}", "if", "(", "!", "dstFile", ".", "exists", "(", ")", ")", "{", "if", "(", "!", "dstFile", ".", "mkdirs", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"Fail to create directory: \"", "+", "dstPath", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"Create directory: \"", "+", "dstPath", ")", ";", "}", "}", "List", "<", "String", ">", "errorMessages", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "AlluxioURI", "srcPath", ":", "srcPaths", ")", "{", "try", "{", "File", "dstSubFile", "=", "new", "File", "(", "dstFile", ".", "getAbsoluteFile", "(", ")", ",", "srcPath", ".", "getName", "(", ")", ")", ";", "copyToLocal", "(", "srcPath", ",", "new", "AlluxioURI", "(", "dstPath", ".", "getScheme", "(", ")", ",", "dstPath", ".", "getAuthority", "(", ")", ",", "dstSubFile", ".", "getPath", "(", ")", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "errorMessages", ".", "add", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "if", "(", "errorMessages", ".", "size", "(", ")", "!=", "0", ")", "{", "throw", "new", "IOException", "(", "Joiner", ".", "on", "(", "'", "'", ")", ".", "join", "(", "errorMessages", ")", ")", ";", "}", "}" ]
Copies a list of files or directories specified by srcPaths from the Alluxio filesystem to dstPath in the local filesystem. This method is used when the input path contains wildcards. @param srcPaths the list of files in the Alluxio filesystem @param dstPath the {@link AlluxioURI} of the destination directory in the local filesystem
[ "Copies", "a", "list", "of", "files", "or", "directories", "specified", "by", "srcPaths", "from", "the", "Alluxio", "filesystem", "to", "dstPath", "in", "the", "local", "filesystem", ".", "This", "method", "is", "used", "when", "the", "input", "path", "contains", "wildcards", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L674-L700
18,789
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CpCommand.java
CpCommand.copyToLocal
private void copyToLocal(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException { URIStatus srcStatus = mFileSystem.getStatus(srcPath); File dstFile = new File(dstPath.getPath()); if (srcStatus.isFolder()) { // make a local directory if (!dstFile.exists()) { if (!dstFile.mkdirs()) { throw new IOException("mkdir failure for directory: " + dstPath); } else { System.out.println("Create directory: " + dstPath); } } List<URIStatus> statuses; try { statuses = mFileSystem.listStatus(srcPath); } catch (AlluxioException e) { throw new IOException(e.getMessage()); } List<String> errorMessages = new ArrayList<>(); for (URIStatus status : statuses) { try { File subDstFile = new File(dstFile.getAbsolutePath(), status.getName()); copyToLocal( new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), status.getPath()), new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), subDstFile.getPath())); } catch (IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { throw new IOException(Joiner.on('\n').join(errorMessages)); } } else { copyFileToLocal(srcPath, dstPath); } }
java
private void copyToLocal(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException { URIStatus srcStatus = mFileSystem.getStatus(srcPath); File dstFile = new File(dstPath.getPath()); if (srcStatus.isFolder()) { // make a local directory if (!dstFile.exists()) { if (!dstFile.mkdirs()) { throw new IOException("mkdir failure for directory: " + dstPath); } else { System.out.println("Create directory: " + dstPath); } } List<URIStatus> statuses; try { statuses = mFileSystem.listStatus(srcPath); } catch (AlluxioException e) { throw new IOException(e.getMessage()); } List<String> errorMessages = new ArrayList<>(); for (URIStatus status : statuses) { try { File subDstFile = new File(dstFile.getAbsolutePath(), status.getName()); copyToLocal( new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), status.getPath()), new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), subDstFile.getPath())); } catch (IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { throw new IOException(Joiner.on('\n').join(errorMessages)); } } else { copyFileToLocal(srcPath, dstPath); } }
[ "private", "void", "copyToLocal", "(", "AlluxioURI", "srcPath", ",", "AlluxioURI", "dstPath", ")", "throws", "AlluxioException", ",", "IOException", "{", "URIStatus", "srcStatus", "=", "mFileSystem", ".", "getStatus", "(", "srcPath", ")", ";", "File", "dstFile", "=", "new", "File", "(", "dstPath", ".", "getPath", "(", ")", ")", ";", "if", "(", "srcStatus", ".", "isFolder", "(", ")", ")", "{", "// make a local directory", "if", "(", "!", "dstFile", ".", "exists", "(", ")", ")", "{", "if", "(", "!", "dstFile", ".", "mkdirs", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"mkdir failure for directory: \"", "+", "dstPath", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"Create directory: \"", "+", "dstPath", ")", ";", "}", "}", "List", "<", "URIStatus", ">", "statuses", ";", "try", "{", "statuses", "=", "mFileSystem", ".", "listStatus", "(", "srcPath", ")", ";", "}", "catch", "(", "AlluxioException", "e", ")", "{", "throw", "new", "IOException", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "List", "<", "String", ">", "errorMessages", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "URIStatus", "status", ":", "statuses", ")", "{", "try", "{", "File", "subDstFile", "=", "new", "File", "(", "dstFile", ".", "getAbsolutePath", "(", ")", ",", "status", ".", "getName", "(", ")", ")", ";", "copyToLocal", "(", "new", "AlluxioURI", "(", "srcPath", ".", "getScheme", "(", ")", ",", "srcPath", ".", "getAuthority", "(", ")", ",", "status", ".", "getPath", "(", ")", ")", ",", "new", "AlluxioURI", "(", "dstPath", ".", "getScheme", "(", ")", ",", "dstPath", ".", "getAuthority", "(", ")", ",", "subDstFile", ".", "getPath", "(", ")", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "errorMessages", ".", "add", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "if", "(", "errorMessages", ".", "size", "(", ")", "!=", "0", ")", "{", "throw", "new", "IOException", "(", "Joiner", ".", "on", "(", "'", "'", ")", ".", "join", "(", "errorMessages", ")", ")", ";", "}", "}", "else", "{", "copyFileToLocal", "(", "srcPath", ",", "dstPath", ")", ";", "}", "}" ]
Copies a file or a directory from the Alluxio filesystem to the local filesystem. @param srcPath the source {@link AlluxioURI} (could be a file or a directory) @param dstPath the {@link AlluxioURI} of the destination in the local filesystem
[ "Copies", "a", "file", "or", "a", "directory", "from", "the", "Alluxio", "filesystem", "to", "the", "local", "filesystem", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L708-L747
18,790
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/CpCommand.java
CpCommand.copyFileToLocal
private void copyFileToLocal(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException { File dstFile = new File(dstPath.getPath()); String randomSuffix = String.format(".%s_copyToLocal_", RandomStringUtils.randomAlphanumeric(8)); File outputFile; if (dstFile.isDirectory()) { outputFile = new File(PathUtils.concatPath(dstFile.getAbsolutePath(), srcPath.getName())); } else { outputFile = dstFile; } File tmpDst = new File(outputFile.getPath() + randomSuffix); try (Closer closer = Closer.create()) { FileInStream is = closer.register(mFileSystem.openFile(srcPath)); FileOutputStream out = closer.register(new FileOutputStream(tmpDst)); byte[] buf = new byte[mCopyToLocalBufferSize]; int t = is.read(buf); while (t != -1) { out.write(buf, 0, t); t = is.read(buf); } if (!tmpDst.renameTo(outputFile)) { throw new IOException( "Failed to rename " + tmpDst.getPath() + " to destination " + outputFile.getPath()); } System.out.println("Copied " + srcPath + " to " + "file://" + outputFile.getPath()); } finally { tmpDst.delete(); } }
java
private void copyFileToLocal(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException { File dstFile = new File(dstPath.getPath()); String randomSuffix = String.format(".%s_copyToLocal_", RandomStringUtils.randomAlphanumeric(8)); File outputFile; if (dstFile.isDirectory()) { outputFile = new File(PathUtils.concatPath(dstFile.getAbsolutePath(), srcPath.getName())); } else { outputFile = dstFile; } File tmpDst = new File(outputFile.getPath() + randomSuffix); try (Closer closer = Closer.create()) { FileInStream is = closer.register(mFileSystem.openFile(srcPath)); FileOutputStream out = closer.register(new FileOutputStream(tmpDst)); byte[] buf = new byte[mCopyToLocalBufferSize]; int t = is.read(buf); while (t != -1) { out.write(buf, 0, t); t = is.read(buf); } if (!tmpDst.renameTo(outputFile)) { throw new IOException( "Failed to rename " + tmpDst.getPath() + " to destination " + outputFile.getPath()); } System.out.println("Copied " + srcPath + " to " + "file://" + outputFile.getPath()); } finally { tmpDst.delete(); } }
[ "private", "void", "copyFileToLocal", "(", "AlluxioURI", "srcPath", ",", "AlluxioURI", "dstPath", ")", "throws", "AlluxioException", ",", "IOException", "{", "File", "dstFile", "=", "new", "File", "(", "dstPath", ".", "getPath", "(", ")", ")", ";", "String", "randomSuffix", "=", "String", ".", "format", "(", "\".%s_copyToLocal_\"", ",", "RandomStringUtils", ".", "randomAlphanumeric", "(", "8", ")", ")", ";", "File", "outputFile", ";", "if", "(", "dstFile", ".", "isDirectory", "(", ")", ")", "{", "outputFile", "=", "new", "File", "(", "PathUtils", ".", "concatPath", "(", "dstFile", ".", "getAbsolutePath", "(", ")", ",", "srcPath", ".", "getName", "(", ")", ")", ")", ";", "}", "else", "{", "outputFile", "=", "dstFile", ";", "}", "File", "tmpDst", "=", "new", "File", "(", "outputFile", ".", "getPath", "(", ")", "+", "randomSuffix", ")", ";", "try", "(", "Closer", "closer", "=", "Closer", ".", "create", "(", ")", ")", "{", "FileInStream", "is", "=", "closer", ".", "register", "(", "mFileSystem", ".", "openFile", "(", "srcPath", ")", ")", ";", "FileOutputStream", "out", "=", "closer", ".", "register", "(", "new", "FileOutputStream", "(", "tmpDst", ")", ")", ";", "byte", "[", "]", "buf", "=", "new", "byte", "[", "mCopyToLocalBufferSize", "]", ";", "int", "t", "=", "is", ".", "read", "(", "buf", ")", ";", "while", "(", "t", "!=", "-", "1", ")", "{", "out", ".", "write", "(", "buf", ",", "0", ",", "t", ")", ";", "t", "=", "is", ".", "read", "(", "buf", ")", ";", "}", "if", "(", "!", "tmpDst", ".", "renameTo", "(", "outputFile", ")", ")", "{", "throw", "new", "IOException", "(", "\"Failed to rename \"", "+", "tmpDst", ".", "getPath", "(", ")", "+", "\" to destination \"", "+", "outputFile", ".", "getPath", "(", ")", ")", ";", "}", "System", ".", "out", ".", "println", "(", "\"Copied \"", "+", "srcPath", "+", "\" to \"", "+", "\"file://\"", "+", "outputFile", ".", "getPath", "(", ")", ")", ";", "}", "finally", "{", "tmpDst", ".", "delete", "(", ")", ";", "}", "}" ]
Copies a file specified by argv from the filesystem to the local filesystem. This is the utility function. @param srcPath The source {@link AlluxioURI} (has to be a file) @param dstPath The {@link AlluxioURI} of the destination in the local filesystem
[ "Copies", "a", "file", "specified", "by", "argv", "from", "the", "filesystem", "to", "the", "local", "filesystem", ".", "This", "is", "the", "utility", "function", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L756-L786
18,791
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java
BlockLockManager.lockBlock
public long lockBlock(long sessionId, long blockId, BlockLockType blockLockType) { ClientRWLock blockLock = getBlockLock(blockId); Lock lock; if (blockLockType == BlockLockType.READ) { lock = blockLock.readLock(); } else { // Make sure the session isn't already holding the block lock. if (sessionHoldsLock(sessionId, blockId)) { throw new IllegalStateException(String .format("Session %s attempted to take a write lock on block %s, but the session already" + " holds a lock on the block", sessionId, blockId)); } lock = blockLock.writeLock(); } lock.lock(); try { long lockId = LOCK_ID_GEN.getAndIncrement(); synchronized (mSharedMapsLock) { mLockIdToRecordMap.put(lockId, new LockRecord(sessionId, blockId, lock)); Set<Long> sessionLockIds = mSessionIdToLockIdsMap.get(sessionId); if (sessionLockIds == null) { mSessionIdToLockIdsMap.put(sessionId, Sets.newHashSet(lockId)); } else { sessionLockIds.add(lockId); } } return lockId; } catch (RuntimeException e) { // If an unexpected exception occurs, we should release the lock to be conservative. unlock(lock, blockId); throw e; } }
java
public long lockBlock(long sessionId, long blockId, BlockLockType blockLockType) { ClientRWLock blockLock = getBlockLock(blockId); Lock lock; if (blockLockType == BlockLockType.READ) { lock = blockLock.readLock(); } else { // Make sure the session isn't already holding the block lock. if (sessionHoldsLock(sessionId, blockId)) { throw new IllegalStateException(String .format("Session %s attempted to take a write lock on block %s, but the session already" + " holds a lock on the block", sessionId, blockId)); } lock = blockLock.writeLock(); } lock.lock(); try { long lockId = LOCK_ID_GEN.getAndIncrement(); synchronized (mSharedMapsLock) { mLockIdToRecordMap.put(lockId, new LockRecord(sessionId, blockId, lock)); Set<Long> sessionLockIds = mSessionIdToLockIdsMap.get(sessionId); if (sessionLockIds == null) { mSessionIdToLockIdsMap.put(sessionId, Sets.newHashSet(lockId)); } else { sessionLockIds.add(lockId); } } return lockId; } catch (RuntimeException e) { // If an unexpected exception occurs, we should release the lock to be conservative. unlock(lock, blockId); throw e; } }
[ "public", "long", "lockBlock", "(", "long", "sessionId", ",", "long", "blockId", ",", "BlockLockType", "blockLockType", ")", "{", "ClientRWLock", "blockLock", "=", "getBlockLock", "(", "blockId", ")", ";", "Lock", "lock", ";", "if", "(", "blockLockType", "==", "BlockLockType", ".", "READ", ")", "{", "lock", "=", "blockLock", ".", "readLock", "(", ")", ";", "}", "else", "{", "// Make sure the session isn't already holding the block lock.", "if", "(", "sessionHoldsLock", "(", "sessionId", ",", "blockId", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "String", ".", "format", "(", "\"Session %s attempted to take a write lock on block %s, but the session already\"", "+", "\" holds a lock on the block\"", ",", "sessionId", ",", "blockId", ")", ")", ";", "}", "lock", "=", "blockLock", ".", "writeLock", "(", ")", ";", "}", "lock", ".", "lock", "(", ")", ";", "try", "{", "long", "lockId", "=", "LOCK_ID_GEN", ".", "getAndIncrement", "(", ")", ";", "synchronized", "(", "mSharedMapsLock", ")", "{", "mLockIdToRecordMap", ".", "put", "(", "lockId", ",", "new", "LockRecord", "(", "sessionId", ",", "blockId", ",", "lock", ")", ")", ";", "Set", "<", "Long", ">", "sessionLockIds", "=", "mSessionIdToLockIdsMap", ".", "get", "(", "sessionId", ")", ";", "if", "(", "sessionLockIds", "==", "null", ")", "{", "mSessionIdToLockIdsMap", ".", "put", "(", "sessionId", ",", "Sets", ".", "newHashSet", "(", "lockId", ")", ")", ";", "}", "else", "{", "sessionLockIds", ".", "add", "(", "lockId", ")", ";", "}", "}", "return", "lockId", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "// If an unexpected exception occurs, we should release the lock to be conservative.", "unlock", "(", "lock", ",", "blockId", ")", ";", "throw", "e", ";", "}", "}" ]
Locks a block. Note that even if this block does not exist, a lock id is still returned. If all {@link PropertyKey#WORKER_TIERED_STORE_BLOCK_LOCKS} are already in use and no lock has been allocated for the specified block, this method will need to wait until a lock can be acquired from the lock pool. @param sessionId the session id @param blockId the block id @param blockLockType {@link BlockLockType#READ} or {@link BlockLockType#WRITE} @return lock id
[ "Locks", "a", "block", ".", "Note", "that", "even", "if", "this", "block", "does", "not", "exist", "a", "lock", "id", "is", "still", "returned", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java#L100-L132
18,792
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java
BlockLockManager.getBlockLock
private ClientRWLock getBlockLock(long blockId) { // Loop until we either find the block lock in the mLocks map, or successfully acquire a new // block lock from the lock pool. while (true) { ClientRWLock blockLock; // Check whether a lock has already been allocated for the block id. synchronized (mSharedMapsLock) { blockLock = mLocks.get(blockId); if (blockLock != null) { blockLock.addReference(); return blockLock; } } // Since a block lock hasn't already been allocated, try to acquire a new one from the pool. // Acquire the lock outside the synchronized section because #acquire might need to block. // We shouldn't wait indefinitely in acquire because the another lock for this block could be // allocated to another thread, in which case we could just use that lock. blockLock = mLockPool.acquire(1, TimeUnit.SECONDS); if (blockLock != null) { synchronized (mSharedMapsLock) { // Check if someone else acquired a block lock for blockId while we were acquiring one. if (mLocks.containsKey(blockId)) { mLockPool.release(blockLock); blockLock = mLocks.get(blockId); } else { mLocks.put(blockId, blockLock); } blockLock.addReference(); return blockLock; } } } }
java
private ClientRWLock getBlockLock(long blockId) { // Loop until we either find the block lock in the mLocks map, or successfully acquire a new // block lock from the lock pool. while (true) { ClientRWLock blockLock; // Check whether a lock has already been allocated for the block id. synchronized (mSharedMapsLock) { blockLock = mLocks.get(blockId); if (blockLock != null) { blockLock.addReference(); return blockLock; } } // Since a block lock hasn't already been allocated, try to acquire a new one from the pool. // Acquire the lock outside the synchronized section because #acquire might need to block. // We shouldn't wait indefinitely in acquire because the another lock for this block could be // allocated to another thread, in which case we could just use that lock. blockLock = mLockPool.acquire(1, TimeUnit.SECONDS); if (blockLock != null) { synchronized (mSharedMapsLock) { // Check if someone else acquired a block lock for blockId while we were acquiring one. if (mLocks.containsKey(blockId)) { mLockPool.release(blockLock); blockLock = mLocks.get(blockId); } else { mLocks.put(blockId, blockLock); } blockLock.addReference(); return blockLock; } } } }
[ "private", "ClientRWLock", "getBlockLock", "(", "long", "blockId", ")", "{", "// Loop until we either find the block lock in the mLocks map, or successfully acquire a new", "// block lock from the lock pool.", "while", "(", "true", ")", "{", "ClientRWLock", "blockLock", ";", "// Check whether a lock has already been allocated for the block id.", "synchronized", "(", "mSharedMapsLock", ")", "{", "blockLock", "=", "mLocks", ".", "get", "(", "blockId", ")", ";", "if", "(", "blockLock", "!=", "null", ")", "{", "blockLock", ".", "addReference", "(", ")", ";", "return", "blockLock", ";", "}", "}", "// Since a block lock hasn't already been allocated, try to acquire a new one from the pool.", "// Acquire the lock outside the synchronized section because #acquire might need to block.", "// We shouldn't wait indefinitely in acquire because the another lock for this block could be", "// allocated to another thread, in which case we could just use that lock.", "blockLock", "=", "mLockPool", ".", "acquire", "(", "1", ",", "TimeUnit", ".", "SECONDS", ")", ";", "if", "(", "blockLock", "!=", "null", ")", "{", "synchronized", "(", "mSharedMapsLock", ")", "{", "// Check if someone else acquired a block lock for blockId while we were acquiring one.", "if", "(", "mLocks", ".", "containsKey", "(", "blockId", ")", ")", "{", "mLockPool", ".", "release", "(", "blockLock", ")", ";", "blockLock", "=", "mLocks", ".", "get", "(", "blockId", ")", ";", "}", "else", "{", "mLocks", ".", "put", "(", "blockId", ",", "blockLock", ")", ";", "}", "blockLock", ".", "addReference", "(", ")", ";", "return", "blockLock", ";", "}", "}", "}", "}" ]
Returns the block lock for the given block id, acquiring such a lock if it doesn't exist yet. If all locks have been allocated, this method will block until one can be acquired. @param blockId the block id to get the lock for @return the block lock
[ "Returns", "the", "block", "lock", "for", "the", "given", "block", "id", "acquiring", "such", "a", "lock", "if", "it", "doesn", "t", "exist", "yet", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java#L163-L195
18,793
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java
BlockLockManager.validateLock
public void validateLock(long sessionId, long blockId, long lockId) throws BlockDoesNotExistException, InvalidWorkerStateException { synchronized (mSharedMapsLock) { LockRecord record = mLockIdToRecordMap.get(lockId); if (record == null) { throw new BlockDoesNotExistException(ExceptionMessage.LOCK_RECORD_NOT_FOUND_FOR_LOCK_ID, lockId); } if (sessionId != record.getSessionId()) { throw new InvalidWorkerStateException(ExceptionMessage.LOCK_ID_FOR_DIFFERENT_SESSION, lockId, record.getSessionId(), sessionId); } if (blockId != record.getBlockId()) { throw new InvalidWorkerStateException(ExceptionMessage.LOCK_ID_FOR_DIFFERENT_BLOCK, lockId, record.getBlockId(), blockId); } } }
java
public void validateLock(long sessionId, long blockId, long lockId) throws BlockDoesNotExistException, InvalidWorkerStateException { synchronized (mSharedMapsLock) { LockRecord record = mLockIdToRecordMap.get(lockId); if (record == null) { throw new BlockDoesNotExistException(ExceptionMessage.LOCK_RECORD_NOT_FOUND_FOR_LOCK_ID, lockId); } if (sessionId != record.getSessionId()) { throw new InvalidWorkerStateException(ExceptionMessage.LOCK_ID_FOR_DIFFERENT_SESSION, lockId, record.getSessionId(), sessionId); } if (blockId != record.getBlockId()) { throw new InvalidWorkerStateException(ExceptionMessage.LOCK_ID_FOR_DIFFERENT_BLOCK, lockId, record.getBlockId(), blockId); } } }
[ "public", "void", "validateLock", "(", "long", "sessionId", ",", "long", "blockId", ",", "long", "lockId", ")", "throws", "BlockDoesNotExistException", ",", "InvalidWorkerStateException", "{", "synchronized", "(", "mSharedMapsLock", ")", "{", "LockRecord", "record", "=", "mLockIdToRecordMap", ".", "get", "(", "lockId", ")", ";", "if", "(", "record", "==", "null", ")", "{", "throw", "new", "BlockDoesNotExistException", "(", "ExceptionMessage", ".", "LOCK_RECORD_NOT_FOUND_FOR_LOCK_ID", ",", "lockId", ")", ";", "}", "if", "(", "sessionId", "!=", "record", ".", "getSessionId", "(", ")", ")", "{", "throw", "new", "InvalidWorkerStateException", "(", "ExceptionMessage", ".", "LOCK_ID_FOR_DIFFERENT_SESSION", ",", "lockId", ",", "record", ".", "getSessionId", "(", ")", ",", "sessionId", ")", ";", "}", "if", "(", "blockId", "!=", "record", ".", "getBlockId", "(", ")", ")", "{", "throw", "new", "InvalidWorkerStateException", "(", "ExceptionMessage", ".", "LOCK_ID_FOR_DIFFERENT_BLOCK", ",", "lockId", ",", "record", ".", "getBlockId", "(", ")", ",", "blockId", ")", ";", "}", "}", "}" ]
Validates the lock is hold by the given session for the given block. @param sessionId the session id @param blockId the block id @param lockId the lock id @throws BlockDoesNotExistException when no lock record can be found for lock id @throws InvalidWorkerStateException when session id or block id is not consistent with that in the lock record for lock id
[ "Validates", "the", "lock", "is", "hold", "by", "the", "given", "session", "for", "the", "given", "block", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java#L282-L299
18,794
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java
BlockLockManager.cleanupSession
public void cleanupSession(long sessionId) { synchronized (mSharedMapsLock) { Set<Long> sessionLockIds = mSessionIdToLockIdsMap.get(sessionId); if (sessionLockIds == null) { return; } for (long lockId : sessionLockIds) { LockRecord record = mLockIdToRecordMap.get(lockId); if (record == null) { LOG.error(ExceptionMessage.LOCK_RECORD_NOT_FOUND_FOR_LOCK_ID.getMessage(lockId)); continue; } Lock lock = record.getLock(); unlock(lock, record.getBlockId()); mLockIdToRecordMap.remove(lockId); } mSessionIdToLockIdsMap.remove(sessionId); } }
java
public void cleanupSession(long sessionId) { synchronized (mSharedMapsLock) { Set<Long> sessionLockIds = mSessionIdToLockIdsMap.get(sessionId); if (sessionLockIds == null) { return; } for (long lockId : sessionLockIds) { LockRecord record = mLockIdToRecordMap.get(lockId); if (record == null) { LOG.error(ExceptionMessage.LOCK_RECORD_NOT_FOUND_FOR_LOCK_ID.getMessage(lockId)); continue; } Lock lock = record.getLock(); unlock(lock, record.getBlockId()); mLockIdToRecordMap.remove(lockId); } mSessionIdToLockIdsMap.remove(sessionId); } }
[ "public", "void", "cleanupSession", "(", "long", "sessionId", ")", "{", "synchronized", "(", "mSharedMapsLock", ")", "{", "Set", "<", "Long", ">", "sessionLockIds", "=", "mSessionIdToLockIdsMap", ".", "get", "(", "sessionId", ")", ";", "if", "(", "sessionLockIds", "==", "null", ")", "{", "return", ";", "}", "for", "(", "long", "lockId", ":", "sessionLockIds", ")", "{", "LockRecord", "record", "=", "mLockIdToRecordMap", ".", "get", "(", "lockId", ")", ";", "if", "(", "record", "==", "null", ")", "{", "LOG", ".", "error", "(", "ExceptionMessage", ".", "LOCK_RECORD_NOT_FOUND_FOR_LOCK_ID", ".", "getMessage", "(", "lockId", ")", ")", ";", "continue", ";", "}", "Lock", "lock", "=", "record", ".", "getLock", "(", ")", ";", "unlock", "(", "lock", ",", "record", ".", "getBlockId", "(", ")", ")", ";", "mLockIdToRecordMap", ".", "remove", "(", "lockId", ")", ";", "}", "mSessionIdToLockIdsMap", ".", "remove", "(", "sessionId", ")", ";", "}", "}" ]
Cleans up the locks currently hold by a specific session. @param sessionId the id of the session to cleanup
[ "Cleans", "up", "the", "locks", "currently", "hold", "by", "a", "specific", "session", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java#L306-L324
18,795
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java
BlockLockManager.getLockedBlocks
public Set<Long> getLockedBlocks() { synchronized (mSharedMapsLock) { Set<Long> set = new HashSet<>(); for (LockRecord lockRecord : mLockIdToRecordMap.values()) { set.add(lockRecord.getBlockId()); } return set; } }
java
public Set<Long> getLockedBlocks() { synchronized (mSharedMapsLock) { Set<Long> set = new HashSet<>(); for (LockRecord lockRecord : mLockIdToRecordMap.values()) { set.add(lockRecord.getBlockId()); } return set; } }
[ "public", "Set", "<", "Long", ">", "getLockedBlocks", "(", ")", "{", "synchronized", "(", "mSharedMapsLock", ")", "{", "Set", "<", "Long", ">", "set", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "LockRecord", "lockRecord", ":", "mLockIdToRecordMap", ".", "values", "(", ")", ")", "{", "set", ".", "add", "(", "lockRecord", ".", "getBlockId", "(", ")", ")", ";", "}", "return", "set", ";", "}", "}" ]
Gets a set of currently locked blocks. @return a set of locked blocks
[ "Gets", "a", "set", "of", "currently", "locked", "blocks", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java#L331-L339
18,796
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java
BlockLockManager.releaseBlockLockIfUnused
private void releaseBlockLockIfUnused(long blockId) { synchronized (mSharedMapsLock) { ClientRWLock lock = mLocks.get(blockId); if (lock == null) { // Someone else probably released the block lock already. return; } // If we were the last worker with a reference to the lock, clean it up. if (lock.dropReference() == 0) { mLocks.remove(blockId); mLockPool.release(lock); } } }
java
private void releaseBlockLockIfUnused(long blockId) { synchronized (mSharedMapsLock) { ClientRWLock lock = mLocks.get(blockId); if (lock == null) { // Someone else probably released the block lock already. return; } // If we were the last worker with a reference to the lock, clean it up. if (lock.dropReference() == 0) { mLocks.remove(blockId); mLockPool.release(lock); } } }
[ "private", "void", "releaseBlockLockIfUnused", "(", "long", "blockId", ")", "{", "synchronized", "(", "mSharedMapsLock", ")", "{", "ClientRWLock", "lock", "=", "mLocks", ".", "get", "(", "blockId", ")", ";", "if", "(", "lock", "==", "null", ")", "{", "// Someone else probably released the block lock already.", "return", ";", "}", "// If we were the last worker with a reference to the lock, clean it up.", "if", "(", "lock", ".", "dropReference", "(", ")", "==", "0", ")", "{", "mLocks", ".", "remove", "(", "blockId", ")", ";", "mLockPool", ".", "release", "(", "lock", ")", ";", "}", "}", "}" ]
Checks whether anyone is using the block lock for the given block id, returning the lock to the lock pool if it is unused. @param blockId the block id for which to potentially release the block lock
[ "Checks", "whether", "anyone", "is", "using", "the", "block", "lock", "for", "the", "given", "block", "id", "returning", "the", "lock", "to", "the", "lock", "pool", "if", "it", "is", "unused", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java#L359-L372
18,797
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java
BlockLockManager.validate
public void validate() { synchronized (mSharedMapsLock) { // Compute block lock reference counts based off of lock records ConcurrentMap<Long, AtomicInteger> blockLockReferenceCounts = new ConcurrentHashMap<>(); for (LockRecord record : mLockIdToRecordMap.values()) { blockLockReferenceCounts.putIfAbsent(record.getBlockId(), new AtomicInteger(0)); blockLockReferenceCounts.get(record.getBlockId()).incrementAndGet(); } // Check that the reference count for each block lock matches the lock record counts. for (Entry<Long, ClientRWLock> entry : mLocks.entrySet()) { long blockId = entry.getKey(); ClientRWLock lock = entry.getValue(); Integer recordCount = blockLockReferenceCounts.get(blockId).get(); Integer referenceCount = lock.getReferenceCount(); if (!Objects.equal(recordCount, referenceCount)) { throw new IllegalStateException("There are " + recordCount + " lock records for block" + " id " + blockId + ", but the reference count is " + referenceCount); } } // Check that if a lock id is mapped to by a session id, the lock record for that lock id // contains that session id. for (Entry<Long, Set<Long>> entry : mSessionIdToLockIdsMap.entrySet()) { for (Long lockId : entry.getValue()) { LockRecord record = mLockIdToRecordMap.get(lockId); if (record.getSessionId() != entry.getKey()) { throw new IllegalStateException("The session id map contains lock id " + lockId + "under session id " + entry.getKey() + ", but the record for that lock id (" + record + ")" + " doesn't contain that session id"); } } } } }
java
public void validate() { synchronized (mSharedMapsLock) { // Compute block lock reference counts based off of lock records ConcurrentMap<Long, AtomicInteger> blockLockReferenceCounts = new ConcurrentHashMap<>(); for (LockRecord record : mLockIdToRecordMap.values()) { blockLockReferenceCounts.putIfAbsent(record.getBlockId(), new AtomicInteger(0)); blockLockReferenceCounts.get(record.getBlockId()).incrementAndGet(); } // Check that the reference count for each block lock matches the lock record counts. for (Entry<Long, ClientRWLock> entry : mLocks.entrySet()) { long blockId = entry.getKey(); ClientRWLock lock = entry.getValue(); Integer recordCount = blockLockReferenceCounts.get(blockId).get(); Integer referenceCount = lock.getReferenceCount(); if (!Objects.equal(recordCount, referenceCount)) { throw new IllegalStateException("There are " + recordCount + " lock records for block" + " id " + blockId + ", but the reference count is " + referenceCount); } } // Check that if a lock id is mapped to by a session id, the lock record for that lock id // contains that session id. for (Entry<Long, Set<Long>> entry : mSessionIdToLockIdsMap.entrySet()) { for (Long lockId : entry.getValue()) { LockRecord record = mLockIdToRecordMap.get(lockId); if (record.getSessionId() != entry.getKey()) { throw new IllegalStateException("The session id map contains lock id " + lockId + "under session id " + entry.getKey() + ", but the record for that lock id (" + record + ")" + " doesn't contain that session id"); } } } } }
[ "public", "void", "validate", "(", ")", "{", "synchronized", "(", "mSharedMapsLock", ")", "{", "// Compute block lock reference counts based off of lock records", "ConcurrentMap", "<", "Long", ",", "AtomicInteger", ">", "blockLockReferenceCounts", "=", "new", "ConcurrentHashMap", "<>", "(", ")", ";", "for", "(", "LockRecord", "record", ":", "mLockIdToRecordMap", ".", "values", "(", ")", ")", "{", "blockLockReferenceCounts", ".", "putIfAbsent", "(", "record", ".", "getBlockId", "(", ")", ",", "new", "AtomicInteger", "(", "0", ")", ")", ";", "blockLockReferenceCounts", ".", "get", "(", "record", ".", "getBlockId", "(", ")", ")", ".", "incrementAndGet", "(", ")", ";", "}", "// Check that the reference count for each block lock matches the lock record counts.", "for", "(", "Entry", "<", "Long", ",", "ClientRWLock", ">", "entry", ":", "mLocks", ".", "entrySet", "(", ")", ")", "{", "long", "blockId", "=", "entry", ".", "getKey", "(", ")", ";", "ClientRWLock", "lock", "=", "entry", ".", "getValue", "(", ")", ";", "Integer", "recordCount", "=", "blockLockReferenceCounts", ".", "get", "(", "blockId", ")", ".", "get", "(", ")", ";", "Integer", "referenceCount", "=", "lock", ".", "getReferenceCount", "(", ")", ";", "if", "(", "!", "Objects", ".", "equal", "(", "recordCount", ",", "referenceCount", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"There are \"", "+", "recordCount", "+", "\" lock records for block\"", "+", "\" id \"", "+", "blockId", "+", "\", but the reference count is \"", "+", "referenceCount", ")", ";", "}", "}", "// Check that if a lock id is mapped to by a session id, the lock record for that lock id", "// contains that session id.", "for", "(", "Entry", "<", "Long", ",", "Set", "<", "Long", ">", ">", "entry", ":", "mSessionIdToLockIdsMap", ".", "entrySet", "(", ")", ")", "{", "for", "(", "Long", "lockId", ":", "entry", ".", "getValue", "(", ")", ")", "{", "LockRecord", "record", "=", "mLockIdToRecordMap", ".", "get", "(", "lockId", ")", ";", "if", "(", "record", ".", "getSessionId", "(", ")", "!=", "entry", ".", "getKey", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"The session id map contains lock id \"", "+", "lockId", "+", "\"under session id \"", "+", "entry", ".", "getKey", "(", ")", "+", "\", but the record for that lock id (\"", "+", "record", "+", "\")\"", "+", "\" doesn't contain that session id\"", ")", ";", "}", "}", "}", "}", "}" ]
Checks the internal state of the manager to make sure invariants hold. This method is intended for testing purposes. A runtime exception will be thrown if invalid state is encountered.
[ "Checks", "the", "internal", "state", "of", "the", "manager", "to", "make", "sure", "invariants", "hold", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java#L380-L414
18,798
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/TtlBucket.java
TtlBucket.compareTo
@Override public int compareTo(TtlBucket ttlBucket) { long startTime1 = getTtlIntervalStartTimeMs(); long startTime2 = ttlBucket.getTtlIntervalStartTimeMs(); return Long.compare(startTime1, startTime2); }
java
@Override public int compareTo(TtlBucket ttlBucket) { long startTime1 = getTtlIntervalStartTimeMs(); long startTime2 = ttlBucket.getTtlIntervalStartTimeMs(); return Long.compare(startTime1, startTime2); }
[ "@", "Override", "public", "int", "compareTo", "(", "TtlBucket", "ttlBucket", ")", "{", "long", "startTime1", "=", "getTtlIntervalStartTimeMs", "(", ")", ";", "long", "startTime2", "=", "ttlBucket", ".", "getTtlIntervalStartTimeMs", "(", ")", ";", "return", "Long", ".", "compare", "(", "startTime1", ",", "startTime2", ")", ";", "}" ]
Compares this bucket's TTL interval start time to that of another bucket. @param ttlBucket the bucket to be compared to @return 0 when return values of {@link #getTtlIntervalStartTimeMs()} from the two buckets are the same, -1 when that value of current instance is smaller, otherwise, 1
[ "Compares", "this", "bucket", "s", "TTL", "interval", "start", "time", "to", "that", "of", "another", "bucket", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/TtlBucket.java#L114-L119
18,799
Alluxio/alluxio
integration/checker/src/main/java/alluxio/checker/MapReduceIntegrationChecker.java
MapReduceIntegrationChecker.createHdfsFilesystem
private void createHdfsFilesystem(Configuration conf) throws Exception { // Inits HDFS file system object mFileSystem = FileSystem.get(URI.create(conf.get("fs.defaultFS")), conf); mOutputFilePath = new Path("./MapReduceOutputFile"); if (mFileSystem.exists(mOutputFilePath)) { mFileSystem.delete(mOutputFilePath, true); } }
java
private void createHdfsFilesystem(Configuration conf) throws Exception { // Inits HDFS file system object mFileSystem = FileSystem.get(URI.create(conf.get("fs.defaultFS")), conf); mOutputFilePath = new Path("./MapReduceOutputFile"); if (mFileSystem.exists(mOutputFilePath)) { mFileSystem.delete(mOutputFilePath, true); } }
[ "private", "void", "createHdfsFilesystem", "(", "Configuration", "conf", ")", "throws", "Exception", "{", "// Inits HDFS file system object", "mFileSystem", "=", "FileSystem", ".", "get", "(", "URI", ".", "create", "(", "conf", ".", "get", "(", "\"fs.defaultFS\"", ")", ")", ",", "conf", ")", ";", "mOutputFilePath", "=", "new", "Path", "(", "\"./MapReduceOutputFile\"", ")", ";", "if", "(", "mFileSystem", ".", "exists", "(", "mOutputFilePath", ")", ")", "{", "mFileSystem", ".", "delete", "(", "mOutputFilePath", ",", "true", ")", ";", "}", "}" ]
Creates the HDFS filesystem to store output files. @param conf Hadoop configuration
[ "Creates", "the", "HDFS", "filesystem", "to", "store", "output", "files", "." ]
af38cf3ab44613355b18217a3a4d961f8fec3a10
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/checker/src/main/java/alluxio/checker/MapReduceIntegrationChecker.java#L209-L216