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
161,100
voldemort/voldemort
src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java
ClientConfigUtil.compareSingleClientConfigAvro
public static Boolean compareSingleClientConfigAvro(String configAvro1, String configAvro2) { Properties props1 = readSingleClientConfigAvro(configAvro1); Properties props2 = readSingleClientConfigAvro(configAvro2); if(props1.equals(props2)) { return true; } else { return false; } }
java
public static Boolean compareSingleClientConfigAvro(String configAvro1, String configAvro2) { Properties props1 = readSingleClientConfigAvro(configAvro1); Properties props2 = readSingleClientConfigAvro(configAvro2); if(props1.equals(props2)) { return true; } else { return false; } }
[ "public", "static", "Boolean", "compareSingleClientConfigAvro", "(", "String", "configAvro1", ",", "String", "configAvro2", ")", "{", "Properties", "props1", "=", "readSingleClientConfigAvro", "(", "configAvro1", ")", ";", "Properties", "props2", "=", "readSingleClientConfigAvro", "(", "configAvro2", ")", ";", "if", "(", "props1", ".", "equals", "(", "props2", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Compares two avro strings which contains single store configs @param configAvro1 @param configAvro2 @return true if two config avro strings have same content
[ "Compares", "two", "avro", "strings", "which", "contains", "single", "store", "configs" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java#L145-L153
161,101
voldemort/voldemort
src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java
ClientConfigUtil.compareMultipleClientConfigAvro
public static Boolean compareMultipleClientConfigAvro(String configAvro1, String configAvro2) { Map<String, Properties> mapStoreToProps1 = readMultipleClientConfigAvro(configAvro1); Map<String, Properties> mapStoreToProps2 = readMultipleClientConfigAvro(configAvro2); Set<String> keySet1 = mapStoreToProps1.keySet(); Set<String> keySet2 = mapStoreToProps2.keySet(); if(!keySet1.equals(keySet2)) { return false; } for(String storeName: keySet1) { Properties props1 = mapStoreToProps1.get(storeName); Properties props2 = mapStoreToProps2.get(storeName); if(!props1.equals(props2)) { return false; } } return true; }
java
public static Boolean compareMultipleClientConfigAvro(String configAvro1, String configAvro2) { Map<String, Properties> mapStoreToProps1 = readMultipleClientConfigAvro(configAvro1); Map<String, Properties> mapStoreToProps2 = readMultipleClientConfigAvro(configAvro2); Set<String> keySet1 = mapStoreToProps1.keySet(); Set<String> keySet2 = mapStoreToProps2.keySet(); if(!keySet1.equals(keySet2)) { return false; } for(String storeName: keySet1) { Properties props1 = mapStoreToProps1.get(storeName); Properties props2 = mapStoreToProps2.get(storeName); if(!props1.equals(props2)) { return false; } } return true; }
[ "public", "static", "Boolean", "compareMultipleClientConfigAvro", "(", "String", "configAvro1", ",", "String", "configAvro2", ")", "{", "Map", "<", "String", ",", "Properties", ">", "mapStoreToProps1", "=", "readMultipleClientConfigAvro", "(", "configAvro1", ")", ";", "Map", "<", "String", ",", "Properties", ">", "mapStoreToProps2", "=", "readMultipleClientConfigAvro", "(", "configAvro2", ")", ";", "Set", "<", "String", ">", "keySet1", "=", "mapStoreToProps1", ".", "keySet", "(", ")", ";", "Set", "<", "String", ">", "keySet2", "=", "mapStoreToProps2", ".", "keySet", "(", ")", ";", "if", "(", "!", "keySet1", ".", "equals", "(", "keySet2", ")", ")", "{", "return", "false", ";", "}", "for", "(", "String", "storeName", ":", "keySet1", ")", "{", "Properties", "props1", "=", "mapStoreToProps1", ".", "get", "(", "storeName", ")", ";", "Properties", "props2", "=", "mapStoreToProps2", ".", "get", "(", "storeName", ")", ";", "if", "(", "!", "props1", ".", "equals", "(", "props2", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Compares two avro strings which contains multiple store configs @param configAvro1 @param configAvro2 @return true if two config avro strings have same content
[ "Compares", "two", "avro", "strings", "which", "contains", "multiple", "store", "configs" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java#L162-L178
161,102
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandAsyncJob.java
AdminCommandAsyncJob.printHelp
public static void printHelp(PrintStream stream) { stream.println(); stream.println("Voldemort Admin Tool Async-Job Commands"); stream.println("---------------------------------------"); stream.println("list Get async job list from nodes."); stream.println("stop Stop async jobs on one node."); stream.println(); stream.println("To get more information on each command,"); stream.println("please try \'help async-job <command-name>\'."); stream.println(); }
java
public static void printHelp(PrintStream stream) { stream.println(); stream.println("Voldemort Admin Tool Async-Job Commands"); stream.println("---------------------------------------"); stream.println("list Get async job list from nodes."); stream.println("stop Stop async jobs on one node."); stream.println(); stream.println("To get more information on each command,"); stream.println("please try \'help async-job <command-name>\'."); stream.println(); }
[ "public", "static", "void", "printHelp", "(", "PrintStream", "stream", ")", "{", "stream", ".", "println", "(", ")", ";", "stream", ".", "println", "(", "\"Voldemort Admin Tool Async-Job Commands\"", ")", ";", "stream", ".", "println", "(", "\"---------------------------------------\"", ")", ";", "stream", ".", "println", "(", "\"list Get async job list from nodes.\"", ")", ";", "stream", ".", "println", "(", "\"stop Stop async jobs on one node.\"", ")", ";", "stream", ".", "println", "(", ")", ";", "stream", ".", "println", "(", "\"To get more information on each command,\"", ")", ";", "stream", ".", "println", "(", "\"please try \\'help async-job <command-name>\\'.\"", ")", ";", "stream", ".", "println", "(", ")", ";", "}" ]
Prints command-line help menu.
[ "Prints", "command", "-", "line", "help", "menu", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandAsyncJob.java#L59-L69
161,103
voldemort/voldemort
src/java/voldemort/store/bdb/BdbStorageConfiguration.java
BdbStorageConfiguration.removeStorageEngine
@Override public void removeStorageEngine(StorageEngine<ByteArray, byte[], byte[]> engine) { String storeName = engine.getName(); BdbStorageEngine bdbEngine = (BdbStorageEngine) engine; synchronized(lock) { // Only cleanup the environment if it is per store. We cannot // cleanup a shared 'Environment' object if(useOneEnvPerStore) { Environment environment = this.environments.get(storeName); if(environment == null) { // Nothing to clean up. return; } // Remove from the set of unreserved stores if needed. if(this.unreservedStores.remove(environment)) { logger.info("Removed environment for store name: " + storeName + " from unreserved stores"); } else { logger.info("No environment found in unreserved stores for store name: " + storeName); } // Try to delete the BDB directory associated File bdbDir = environment.getHome(); if(bdbDir.exists() && bdbDir.isDirectory()) { String bdbDirPath = bdbDir.getPath(); try { FileUtils.deleteDirectory(bdbDir); logger.info("Successfully deleted BDB directory : " + bdbDirPath + " for store name: " + storeName); } catch(IOException e) { logger.error("Unable to delete BDB directory: " + bdbDirPath + " for store name: " + storeName); } } // Remove the reference to BdbEnvironmentStats, which holds a // reference to the Environment BdbEnvironmentStats bdbEnvStats = bdbEngine.getBdbEnvironmentStats(); this.aggBdbStats.unTrackEnvironment(bdbEnvStats); // Unregister the JMX bean for Environment if(voldemortConfig.isJmxEnabled()) { ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(bdbEnvStats.getClass()), storeName); // Un-register the environment stats mbean JmxUtils.unregisterMbean(name); } // Cleanup the environment environment.close(); this.environments.remove(storeName); logger.info("Successfully closed the environment for store name : " + storeName); } } }
java
@Override public void removeStorageEngine(StorageEngine<ByteArray, byte[], byte[]> engine) { String storeName = engine.getName(); BdbStorageEngine bdbEngine = (BdbStorageEngine) engine; synchronized(lock) { // Only cleanup the environment if it is per store. We cannot // cleanup a shared 'Environment' object if(useOneEnvPerStore) { Environment environment = this.environments.get(storeName); if(environment == null) { // Nothing to clean up. return; } // Remove from the set of unreserved stores if needed. if(this.unreservedStores.remove(environment)) { logger.info("Removed environment for store name: " + storeName + " from unreserved stores"); } else { logger.info("No environment found in unreserved stores for store name: " + storeName); } // Try to delete the BDB directory associated File bdbDir = environment.getHome(); if(bdbDir.exists() && bdbDir.isDirectory()) { String bdbDirPath = bdbDir.getPath(); try { FileUtils.deleteDirectory(bdbDir); logger.info("Successfully deleted BDB directory : " + bdbDirPath + " for store name: " + storeName); } catch(IOException e) { logger.error("Unable to delete BDB directory: " + bdbDirPath + " for store name: " + storeName); } } // Remove the reference to BdbEnvironmentStats, which holds a // reference to the Environment BdbEnvironmentStats bdbEnvStats = bdbEngine.getBdbEnvironmentStats(); this.aggBdbStats.unTrackEnvironment(bdbEnvStats); // Unregister the JMX bean for Environment if(voldemortConfig.isJmxEnabled()) { ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(bdbEnvStats.getClass()), storeName); // Un-register the environment stats mbean JmxUtils.unregisterMbean(name); } // Cleanup the environment environment.close(); this.environments.remove(storeName); logger.info("Successfully closed the environment for store name : " + storeName); } } }
[ "@", "Override", "public", "void", "removeStorageEngine", "(", "StorageEngine", "<", "ByteArray", ",", "byte", "[", "]", ",", "byte", "[", "]", ">", "engine", ")", "{", "String", "storeName", "=", "engine", ".", "getName", "(", ")", ";", "BdbStorageEngine", "bdbEngine", "=", "(", "BdbStorageEngine", ")", "engine", ";", "synchronized", "(", "lock", ")", "{", "// Only cleanup the environment if it is per store. We cannot", "// cleanup a shared 'Environment' object", "if", "(", "useOneEnvPerStore", ")", "{", "Environment", "environment", "=", "this", ".", "environments", ".", "get", "(", "storeName", ")", ";", "if", "(", "environment", "==", "null", ")", "{", "// Nothing to clean up.", "return", ";", "}", "// Remove from the set of unreserved stores if needed.", "if", "(", "this", ".", "unreservedStores", ".", "remove", "(", "environment", ")", ")", "{", "logger", ".", "info", "(", "\"Removed environment for store name: \"", "+", "storeName", "+", "\" from unreserved stores\"", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "\"No environment found in unreserved stores for store name: \"", "+", "storeName", ")", ";", "}", "// Try to delete the BDB directory associated", "File", "bdbDir", "=", "environment", ".", "getHome", "(", ")", ";", "if", "(", "bdbDir", ".", "exists", "(", ")", "&&", "bdbDir", ".", "isDirectory", "(", ")", ")", "{", "String", "bdbDirPath", "=", "bdbDir", ".", "getPath", "(", ")", ";", "try", "{", "FileUtils", ".", "deleteDirectory", "(", "bdbDir", ")", ";", "logger", ".", "info", "(", "\"Successfully deleted BDB directory : \"", "+", "bdbDirPath", "+", "\" for store name: \"", "+", "storeName", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"Unable to delete BDB directory: \"", "+", "bdbDirPath", "+", "\" for store name: \"", "+", "storeName", ")", ";", "}", "}", "// Remove the reference to BdbEnvironmentStats, which holds a", "// reference to the Environment", "BdbEnvironmentStats", "bdbEnvStats", "=", "bdbEngine", ".", "getBdbEnvironmentStats", "(", ")", ";", "this", ".", "aggBdbStats", ".", "unTrackEnvironment", "(", "bdbEnvStats", ")", ";", "// Unregister the JMX bean for Environment", "if", "(", "voldemortConfig", ".", "isJmxEnabled", "(", ")", ")", "{", "ObjectName", "name", "=", "JmxUtils", ".", "createObjectName", "(", "JmxUtils", ".", "getPackageName", "(", "bdbEnvStats", ".", "getClass", "(", ")", ")", ",", "storeName", ")", ";", "// Un-register the environment stats mbean", "JmxUtils", ".", "unregisterMbean", "(", "name", ")", ";", "}", "// Cleanup the environment", "environment", ".", "close", "(", ")", ";", "this", ".", "environments", ".", "remove", "(", "storeName", ")", ";", "logger", ".", "info", "(", "\"Successfully closed the environment for store name : \"", "+", "storeName", ")", ";", "}", "}", "}" ]
Clean up the environment object for the given storage engine
[ "Clean", "up", "the", "environment", "object", "for", "the", "given", "storage", "engine" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/bdb/BdbStorageConfiguration.java#L215-L275
161,104
voldemort/voldemort
src/java/voldemort/store/bdb/BdbStorageConfiguration.java
BdbStorageConfiguration.cleanLogs
@JmxOperation(description = "Forcefully invoke the log cleaning") public void cleanLogs() { synchronized(lock) { try { for(Environment environment: environments.values()) { environment.cleanLog(); } } catch(DatabaseException e) { throw new VoldemortException(e); } } }
java
@JmxOperation(description = "Forcefully invoke the log cleaning") public void cleanLogs() { synchronized(lock) { try { for(Environment environment: environments.values()) { environment.cleanLog(); } } catch(DatabaseException e) { throw new VoldemortException(e); } } }
[ "@", "JmxOperation", "(", "description", "=", "\"Forcefully invoke the log cleaning\"", ")", "public", "void", "cleanLogs", "(", ")", "{", "synchronized", "(", "lock", ")", "{", "try", "{", "for", "(", "Environment", "environment", ":", "environments", ".", "values", "(", ")", ")", "{", "environment", ".", "cleanLog", "(", ")", ";", "}", "}", "catch", "(", "DatabaseException", "e", ")", "{", "throw", "new", "VoldemortException", "(", "e", ")", ";", "}", "}", "}" ]
Forceful cleanup the logs
[ "Forceful", "cleanup", "the", "logs" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/bdb/BdbStorageConfiguration.java#L417-L428
161,105
voldemort/voldemort
src/java/voldemort/store/bdb/BdbStorageConfiguration.java
BdbStorageConfiguration.update
public void update(StoreDefinition storeDef) { if(!useOneEnvPerStore) throw new VoldemortException("Memory foot print can be set only when using different environments per store"); String storeName = storeDef.getName(); Environment environment = environments.get(storeName); // change reservation amount of reserved store if(!unreservedStores.contains(environment) && storeDef.hasMemoryFootprint()) { EnvironmentMutableConfig mConfig = environment.getMutableConfig(); long currentCacheSize = mConfig.getCacheSize(); long newCacheSize = storeDef.getMemoryFootprintMB() * ByteUtils.BYTES_PER_MB; if(currentCacheSize != newCacheSize) { long newReservedCacheSize = this.reservedCacheSize - currentCacheSize + newCacheSize; // check that we leave a 'minimum' shared cache if((voldemortConfig.getBdbCacheSize() - newReservedCacheSize) < voldemortConfig.getBdbMinimumSharedCache()) { throw new StorageInitializationException("Reservation of " + storeDef.getMemoryFootprintMB() + " MB for store " + storeName + " violates minimum shared cache size of " + voldemortConfig.getBdbMinimumSharedCache()); } this.reservedCacheSize = newReservedCacheSize; adjustCacheSizes(); mConfig.setCacheSize(newCacheSize); environment.setMutableConfig(mConfig); logger.info("Setting private cache for store " + storeDef.getName() + " to " + newCacheSize); } } else { // we cannot support changing a reserved store to unreserved or vice // versa since the sharedCache param is not mutable throw new VoldemortException("Cannot switch between shared and private cache dynamically"); } }
java
public void update(StoreDefinition storeDef) { if(!useOneEnvPerStore) throw new VoldemortException("Memory foot print can be set only when using different environments per store"); String storeName = storeDef.getName(); Environment environment = environments.get(storeName); // change reservation amount of reserved store if(!unreservedStores.contains(environment) && storeDef.hasMemoryFootprint()) { EnvironmentMutableConfig mConfig = environment.getMutableConfig(); long currentCacheSize = mConfig.getCacheSize(); long newCacheSize = storeDef.getMemoryFootprintMB() * ByteUtils.BYTES_PER_MB; if(currentCacheSize != newCacheSize) { long newReservedCacheSize = this.reservedCacheSize - currentCacheSize + newCacheSize; // check that we leave a 'minimum' shared cache if((voldemortConfig.getBdbCacheSize() - newReservedCacheSize) < voldemortConfig.getBdbMinimumSharedCache()) { throw new StorageInitializationException("Reservation of " + storeDef.getMemoryFootprintMB() + " MB for store " + storeName + " violates minimum shared cache size of " + voldemortConfig.getBdbMinimumSharedCache()); } this.reservedCacheSize = newReservedCacheSize; adjustCacheSizes(); mConfig.setCacheSize(newCacheSize); environment.setMutableConfig(mConfig); logger.info("Setting private cache for store " + storeDef.getName() + " to " + newCacheSize); } } else { // we cannot support changing a reserved store to unreserved or vice // versa since the sharedCache param is not mutable throw new VoldemortException("Cannot switch between shared and private cache dynamically"); } }
[ "public", "void", "update", "(", "StoreDefinition", "storeDef", ")", "{", "if", "(", "!", "useOneEnvPerStore", ")", "throw", "new", "VoldemortException", "(", "\"Memory foot print can be set only when using different environments per store\"", ")", ";", "String", "storeName", "=", "storeDef", ".", "getName", "(", ")", ";", "Environment", "environment", "=", "environments", ".", "get", "(", "storeName", ")", ";", "// change reservation amount of reserved store", "if", "(", "!", "unreservedStores", ".", "contains", "(", "environment", ")", "&&", "storeDef", ".", "hasMemoryFootprint", "(", ")", ")", "{", "EnvironmentMutableConfig", "mConfig", "=", "environment", ".", "getMutableConfig", "(", ")", ";", "long", "currentCacheSize", "=", "mConfig", ".", "getCacheSize", "(", ")", ";", "long", "newCacheSize", "=", "storeDef", ".", "getMemoryFootprintMB", "(", ")", "*", "ByteUtils", ".", "BYTES_PER_MB", ";", "if", "(", "currentCacheSize", "!=", "newCacheSize", ")", "{", "long", "newReservedCacheSize", "=", "this", ".", "reservedCacheSize", "-", "currentCacheSize", "+", "newCacheSize", ";", "// check that we leave a 'minimum' shared cache", "if", "(", "(", "voldemortConfig", ".", "getBdbCacheSize", "(", ")", "-", "newReservedCacheSize", ")", "<", "voldemortConfig", ".", "getBdbMinimumSharedCache", "(", ")", ")", "{", "throw", "new", "StorageInitializationException", "(", "\"Reservation of \"", "+", "storeDef", ".", "getMemoryFootprintMB", "(", ")", "+", "\" MB for store \"", "+", "storeName", "+", "\" violates minimum shared cache size of \"", "+", "voldemortConfig", ".", "getBdbMinimumSharedCache", "(", ")", ")", ";", "}", "this", ".", "reservedCacheSize", "=", "newReservedCacheSize", ";", "adjustCacheSizes", "(", ")", ";", "mConfig", ".", "setCacheSize", "(", "newCacheSize", ")", ";", "environment", ".", "setMutableConfig", "(", "mConfig", ")", ";", "logger", ".", "info", "(", "\"Setting private cache for store \"", "+", "storeDef", ".", "getName", "(", ")", "+", "\" to \"", "+", "newCacheSize", ")", ";", "}", "}", "else", "{", "// we cannot support changing a reserved store to unreserved or vice", "// versa since the sharedCache param is not mutable", "throw", "new", "VoldemortException", "(", "\"Cannot switch between shared and private cache dynamically\"", ")", ";", "}", "}" ]
Detect what has changed in the store definition and rewire BDB environments accordingly. @param storeDef updated store definition
[ "Detect", "what", "has", "changed", "in", "the", "store", "definition", "and", "rewire", "BDB", "environments", "accordingly", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/bdb/BdbStorageConfiguration.java#L467-L504
161,106
voldemort/voldemort
src/java/voldemort/tools/Repartitioner.java
Repartitioner.getBalancedNumberOfPrimaryPartitionsPerNode
public static HashMap<Integer, List<Integer>> getBalancedNumberOfPrimaryPartitionsPerNode(final Cluster nextCandidateCluster, Map<Integer, Integer> targetPartitionsPerZone) { HashMap<Integer, List<Integer>> numPartitionsPerNode = Maps.newHashMap(); for(Integer zoneId: nextCandidateCluster.getZoneIds()) { List<Integer> partitionsOnNode = Utils.distributeEvenlyIntoList(nextCandidateCluster.getNumberOfNodesInZone(zoneId), targetPartitionsPerZone.get(zoneId)); numPartitionsPerNode.put(zoneId, partitionsOnNode); } return numPartitionsPerNode; }
java
public static HashMap<Integer, List<Integer>> getBalancedNumberOfPrimaryPartitionsPerNode(final Cluster nextCandidateCluster, Map<Integer, Integer> targetPartitionsPerZone) { HashMap<Integer, List<Integer>> numPartitionsPerNode = Maps.newHashMap(); for(Integer zoneId: nextCandidateCluster.getZoneIds()) { List<Integer> partitionsOnNode = Utils.distributeEvenlyIntoList(nextCandidateCluster.getNumberOfNodesInZone(zoneId), targetPartitionsPerZone.get(zoneId)); numPartitionsPerNode.put(zoneId, partitionsOnNode); } return numPartitionsPerNode; }
[ "public", "static", "HashMap", "<", "Integer", ",", "List", "<", "Integer", ">", ">", "getBalancedNumberOfPrimaryPartitionsPerNode", "(", "final", "Cluster", "nextCandidateCluster", ",", "Map", "<", "Integer", ",", "Integer", ">", "targetPartitionsPerZone", ")", "{", "HashMap", "<", "Integer", ",", "List", "<", "Integer", ">", ">", "numPartitionsPerNode", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "Integer", "zoneId", ":", "nextCandidateCluster", ".", "getZoneIds", "(", ")", ")", "{", "List", "<", "Integer", ">", "partitionsOnNode", "=", "Utils", ".", "distributeEvenlyIntoList", "(", "nextCandidateCluster", ".", "getNumberOfNodesInZone", "(", "zoneId", ")", ",", "targetPartitionsPerZone", ".", "get", "(", "zoneId", ")", ")", ";", "numPartitionsPerNode", ".", "put", "(", "zoneId", ",", "partitionsOnNode", ")", ";", "}", "return", "numPartitionsPerNode", ";", "}" ]
Determines how many primary partitions each node within each zone should have. The list of integers returned per zone is the same length as the number of nodes in that zone. @param nextCandidateCluster @param targetPartitionsPerZone @return A map of zoneId to list of target number of partitions per node within zone.
[ "Determines", "how", "many", "primary", "partitions", "each", "node", "within", "each", "zone", "should", "have", ".", "The", "list", "of", "integers", "returned", "per", "zone", "is", "the", "same", "length", "as", "the", "number", "of", "nodes", "in", "that", "zone", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L255-L265
161,107
voldemort/voldemort
src/java/voldemort/tools/Repartitioner.java
Repartitioner.getDonorsAndStealersForBalance
public static Pair<HashMap<Node, Integer>, HashMap<Node, Integer>> getDonorsAndStealersForBalance(final Cluster nextCandidateCluster, Map<Integer, List<Integer>> numPartitionsPerNodePerZone) { HashMap<Node, Integer> donorNodes = Maps.newHashMap(); HashMap<Node, Integer> stealerNodes = Maps.newHashMap(); HashMap<Integer, Integer> numNodesAssignedInZone = Maps.newHashMap(); for(Integer zoneId: nextCandidateCluster.getZoneIds()) { numNodesAssignedInZone.put(zoneId, 0); } for(Node node: nextCandidateCluster.getNodes()) { int zoneId = node.getZoneId(); int offset = numNodesAssignedInZone.get(zoneId); numNodesAssignedInZone.put(zoneId, offset + 1); int numPartitions = numPartitionsPerNodePerZone.get(zoneId).get(offset); if(numPartitions < node.getNumberOfPartitions()) { donorNodes.put(node, numPartitions); } else if(numPartitions > node.getNumberOfPartitions()) { stealerNodes.put(node, numPartitions); } } // Print out donor/stealer information for(Node node: donorNodes.keySet()) { System.out.println("Donor Node: " + node.getId() + ", zoneId " + node.getZoneId() + ", numPartitions " + node.getNumberOfPartitions() + ", target number of partitions " + donorNodes.get(node)); } for(Node node: stealerNodes.keySet()) { System.out.println("Stealer Node: " + node.getId() + ", zoneId " + node.getZoneId() + ", numPartitions " + node.getNumberOfPartitions() + ", target number of partitions " + stealerNodes.get(node)); } return new Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>(donorNodes, stealerNodes); }
java
public static Pair<HashMap<Node, Integer>, HashMap<Node, Integer>> getDonorsAndStealersForBalance(final Cluster nextCandidateCluster, Map<Integer, List<Integer>> numPartitionsPerNodePerZone) { HashMap<Node, Integer> donorNodes = Maps.newHashMap(); HashMap<Node, Integer> stealerNodes = Maps.newHashMap(); HashMap<Integer, Integer> numNodesAssignedInZone = Maps.newHashMap(); for(Integer zoneId: nextCandidateCluster.getZoneIds()) { numNodesAssignedInZone.put(zoneId, 0); } for(Node node: nextCandidateCluster.getNodes()) { int zoneId = node.getZoneId(); int offset = numNodesAssignedInZone.get(zoneId); numNodesAssignedInZone.put(zoneId, offset + 1); int numPartitions = numPartitionsPerNodePerZone.get(zoneId).get(offset); if(numPartitions < node.getNumberOfPartitions()) { donorNodes.put(node, numPartitions); } else if(numPartitions > node.getNumberOfPartitions()) { stealerNodes.put(node, numPartitions); } } // Print out donor/stealer information for(Node node: donorNodes.keySet()) { System.out.println("Donor Node: " + node.getId() + ", zoneId " + node.getZoneId() + ", numPartitions " + node.getNumberOfPartitions() + ", target number of partitions " + donorNodes.get(node)); } for(Node node: stealerNodes.keySet()) { System.out.println("Stealer Node: " + node.getId() + ", zoneId " + node.getZoneId() + ", numPartitions " + node.getNumberOfPartitions() + ", target number of partitions " + stealerNodes.get(node)); } return new Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>(donorNodes, stealerNodes); }
[ "public", "static", "Pair", "<", "HashMap", "<", "Node", ",", "Integer", ">", ",", "HashMap", "<", "Node", ",", "Integer", ">", ">", "getDonorsAndStealersForBalance", "(", "final", "Cluster", "nextCandidateCluster", ",", "Map", "<", "Integer", ",", "List", "<", "Integer", ">", ">", "numPartitionsPerNodePerZone", ")", "{", "HashMap", "<", "Node", ",", "Integer", ">", "donorNodes", "=", "Maps", ".", "newHashMap", "(", ")", ";", "HashMap", "<", "Node", ",", "Integer", ">", "stealerNodes", "=", "Maps", ".", "newHashMap", "(", ")", ";", "HashMap", "<", "Integer", ",", "Integer", ">", "numNodesAssignedInZone", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "Integer", "zoneId", ":", "nextCandidateCluster", ".", "getZoneIds", "(", ")", ")", "{", "numNodesAssignedInZone", ".", "put", "(", "zoneId", ",", "0", ")", ";", "}", "for", "(", "Node", "node", ":", "nextCandidateCluster", ".", "getNodes", "(", ")", ")", "{", "int", "zoneId", "=", "node", ".", "getZoneId", "(", ")", ";", "int", "offset", "=", "numNodesAssignedInZone", ".", "get", "(", "zoneId", ")", ";", "numNodesAssignedInZone", ".", "put", "(", "zoneId", ",", "offset", "+", "1", ")", ";", "int", "numPartitions", "=", "numPartitionsPerNodePerZone", ".", "get", "(", "zoneId", ")", ".", "get", "(", "offset", ")", ";", "if", "(", "numPartitions", "<", "node", ".", "getNumberOfPartitions", "(", ")", ")", "{", "donorNodes", ".", "put", "(", "node", ",", "numPartitions", ")", ";", "}", "else", "if", "(", "numPartitions", ">", "node", ".", "getNumberOfPartitions", "(", ")", ")", "{", "stealerNodes", ".", "put", "(", "node", ",", "numPartitions", ")", ";", "}", "}", "// Print out donor/stealer information", "for", "(", "Node", "node", ":", "donorNodes", ".", "keySet", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"Donor Node: \"", "+", "node", ".", "getId", "(", ")", "+", "\", zoneId \"", "+", "node", ".", "getZoneId", "(", ")", "+", "\", numPartitions \"", "+", "node", ".", "getNumberOfPartitions", "(", ")", "+", "\", target number of partitions \"", "+", "donorNodes", ".", "get", "(", "node", ")", ")", ";", "}", "for", "(", "Node", "node", ":", "stealerNodes", ".", "keySet", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"Stealer Node: \"", "+", "node", ".", "getId", "(", ")", "+", "\", zoneId \"", "+", "node", ".", "getZoneId", "(", ")", "+", "\", numPartitions \"", "+", "node", ".", "getNumberOfPartitions", "(", ")", "+", "\", target number of partitions \"", "+", "stealerNodes", ".", "get", "(", "node", ")", ")", ";", "}", "return", "new", "Pair", "<", "HashMap", "<", "Node", ",", "Integer", ">", ",", "HashMap", "<", "Node", ",", "Integer", ">", ">", "(", "donorNodes", ",", "stealerNodes", ")", ";", "}" ]
Assign target number of partitions per node to specific node IDs. Then, separates Nodes into donorNodes and stealerNodes based on whether the node needs to donate or steal primary partitions. @param nextCandidateCluster @param numPartitionsPerNodePerZone @return a Pair. First element is donorNodes, second element is stealerNodes. Each element in the pair is a HashMap of Node to Integer where the integer value is the number of partitions to store.
[ "Assign", "target", "number", "of", "partitions", "per", "node", "to", "specific", "node", "IDs", ".", "Then", "separates", "Nodes", "into", "donorNodes", "and", "stealerNodes", "based", "on", "whether", "the", "node", "needs", "to", "donate", "or", "steal", "primary", "partitions", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L279-L317
161,108
voldemort/voldemort
src/java/voldemort/tools/Repartitioner.java
Repartitioner.repeatedlyBalanceContiguousPartitionsPerZone
public static Cluster repeatedlyBalanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster, final int maxContiguousPartitionsPerZone) { System.out.println("Looping to evenly balance partitions across zones while limiting contiguous partitions"); // This loop is hard to make definitive. I.e., there are corner cases // for small clusters and/or clusters with few partitions for which it // may be impossible to achieve tight limits on contiguous run lenghts. // Therefore, a constant number of loops are run. Note that once the // goal is reached, the loop becomes a no-op. int repeatContigBalance = 10; Cluster returnCluster = nextCandidateCluster; for(int i = 0; i < repeatContigBalance; i++) { returnCluster = balanceContiguousPartitionsPerZone(returnCluster, maxContiguousPartitionsPerZone); returnCluster = balancePrimaryPartitions(returnCluster, false); System.out.println("Completed round of balancing contiguous partitions: round " + (i + 1) + " of " + repeatContigBalance); } return returnCluster; }
java
public static Cluster repeatedlyBalanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster, final int maxContiguousPartitionsPerZone) { System.out.println("Looping to evenly balance partitions across zones while limiting contiguous partitions"); // This loop is hard to make definitive. I.e., there are corner cases // for small clusters and/or clusters with few partitions for which it // may be impossible to achieve tight limits on contiguous run lenghts. // Therefore, a constant number of loops are run. Note that once the // goal is reached, the loop becomes a no-op. int repeatContigBalance = 10; Cluster returnCluster = nextCandidateCluster; for(int i = 0; i < repeatContigBalance; i++) { returnCluster = balanceContiguousPartitionsPerZone(returnCluster, maxContiguousPartitionsPerZone); returnCluster = balancePrimaryPartitions(returnCluster, false); System.out.println("Completed round of balancing contiguous partitions: round " + (i + 1) + " of " + repeatContigBalance); } return returnCluster; }
[ "public", "static", "Cluster", "repeatedlyBalanceContiguousPartitionsPerZone", "(", "final", "Cluster", "nextCandidateCluster", ",", "final", "int", "maxContiguousPartitionsPerZone", ")", "{", "System", ".", "out", ".", "println", "(", "\"Looping to evenly balance partitions across zones while limiting contiguous partitions\"", ")", ";", "// This loop is hard to make definitive. I.e., there are corner cases", "// for small clusters and/or clusters with few partitions for which it", "// may be impossible to achieve tight limits on contiguous run lenghts.", "// Therefore, a constant number of loops are run. Note that once the", "// goal is reached, the loop becomes a no-op.", "int", "repeatContigBalance", "=", "10", ";", "Cluster", "returnCluster", "=", "nextCandidateCluster", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "repeatContigBalance", ";", "i", "++", ")", "{", "returnCluster", "=", "balanceContiguousPartitionsPerZone", "(", "returnCluster", ",", "maxContiguousPartitionsPerZone", ")", ";", "returnCluster", "=", "balancePrimaryPartitions", "(", "returnCluster", ",", "false", ")", ";", "System", ".", "out", ".", "println", "(", "\"Completed round of balancing contiguous partitions: round \"", "+", "(", "i", "+", "1", ")", "+", "\" of \"", "+", "repeatContigBalance", ")", ";", "}", "return", "returnCluster", ";", "}" ]
Loops over cluster and repeatedly tries to break up contiguous runs of partitions. After each phase of breaking up contiguous partitions, random partitions are selected to move between zones to balance the number of partitions in each zone. The second phase may re-introduce contiguous partition runs in another zone. Therefore, this overall process is repeated multiple times. @param nextCandidateCluster @param maxContiguousPartitionsPerZone See RebalanceCLI. @return updated cluster
[ "Loops", "over", "cluster", "and", "repeatedly", "tries", "to", "break", "up", "contiguous", "runs", "of", "partitions", ".", "After", "each", "phase", "of", "breaking", "up", "contiguous", "partitions", "random", "partitions", "are", "selected", "to", "move", "between", "zones", "to", "balance", "the", "number", "of", "partitions", "in", "each", "zone", ".", "The", "second", "phase", "may", "re", "-", "introduce", "contiguous", "partition", "runs", "in", "another", "zone", ".", "Therefore", "this", "overall", "process", "is", "repeated", "multiple", "times", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L454-L475
161,109
voldemort/voldemort
src/java/voldemort/tools/Repartitioner.java
Repartitioner.balanceContiguousPartitionsPerZone
public static Cluster balanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster, final int maxContiguousPartitionsPerZone) { System.out.println("Balance number of contiguous partitions within a zone."); System.out.println("numPartitionsPerZone"); for(int zoneId: nextCandidateCluster.getZoneIds()) { System.out.println(zoneId + " : " + nextCandidateCluster.getNumberOfPartitionsInZone(zoneId)); } System.out.println("numNodesPerZone"); for(int zoneId: nextCandidateCluster.getZoneIds()) { System.out.println(zoneId + " : " + nextCandidateCluster.getNumberOfNodesInZone(zoneId)); } // Break up contiguous partitions within each zone HashMap<Integer, List<Integer>> partitionsToRemoveFromZone = Maps.newHashMap(); System.out.println("Contiguous partitions"); for(Integer zoneId: nextCandidateCluster.getZoneIds()) { System.out.println("\tZone: " + zoneId); Map<Integer, Integer> partitionToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(nextCandidateCluster, zoneId); List<Integer> partitionsToRemoveFromThisZone = new ArrayList<Integer>(); for(Map.Entry<Integer, Integer> entry: partitionToRunLength.entrySet()) { if(entry.getValue() > maxContiguousPartitionsPerZone) { List<Integer> contiguousPartitions = new ArrayList<Integer>(entry.getValue()); for(int partitionId = entry.getKey(); partitionId < entry.getKey() + entry.getValue(); partitionId++) { contiguousPartitions.add(partitionId % nextCandidateCluster.getNumberOfPartitions()); } System.out.println("Contiguous partitions: " + contiguousPartitions); partitionsToRemoveFromThisZone.addAll(Utils.removeItemsToSplitListEvenly(contiguousPartitions, maxContiguousPartitionsPerZone)); } } partitionsToRemoveFromZone.put(zoneId, partitionsToRemoveFromThisZone); System.out.println("\t\tPartitions to remove: " + partitionsToRemoveFromThisZone); } Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); Random r = new Random(); for(int zoneId: returnCluster.getZoneIds()) { for(int partitionId: partitionsToRemoveFromZone.get(zoneId)) { // Pick a random other zone Id List<Integer> otherZoneIds = new ArrayList<Integer>(); for(int otherZoneId: returnCluster.getZoneIds()) { if(otherZoneId != zoneId) { otherZoneIds.add(otherZoneId); } } int whichOtherZoneId = otherZoneIds.get(r.nextInt(otherZoneIds.size())); // Pick a random node from other zone ID int whichNodeOffset = r.nextInt(returnCluster.getNumberOfNodesInZone(whichOtherZoneId)); int whichNodeId = new ArrayList<Integer>(returnCluster.getNodeIdsInZone(whichOtherZoneId)).get(whichNodeOffset); // Steal partition from one zone to another! returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster, whichNodeId, Lists.newArrayList(partitionId)); } } return returnCluster; }
java
public static Cluster balanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster, final int maxContiguousPartitionsPerZone) { System.out.println("Balance number of contiguous partitions within a zone."); System.out.println("numPartitionsPerZone"); for(int zoneId: nextCandidateCluster.getZoneIds()) { System.out.println(zoneId + " : " + nextCandidateCluster.getNumberOfPartitionsInZone(zoneId)); } System.out.println("numNodesPerZone"); for(int zoneId: nextCandidateCluster.getZoneIds()) { System.out.println(zoneId + " : " + nextCandidateCluster.getNumberOfNodesInZone(zoneId)); } // Break up contiguous partitions within each zone HashMap<Integer, List<Integer>> partitionsToRemoveFromZone = Maps.newHashMap(); System.out.println("Contiguous partitions"); for(Integer zoneId: nextCandidateCluster.getZoneIds()) { System.out.println("\tZone: " + zoneId); Map<Integer, Integer> partitionToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(nextCandidateCluster, zoneId); List<Integer> partitionsToRemoveFromThisZone = new ArrayList<Integer>(); for(Map.Entry<Integer, Integer> entry: partitionToRunLength.entrySet()) { if(entry.getValue() > maxContiguousPartitionsPerZone) { List<Integer> contiguousPartitions = new ArrayList<Integer>(entry.getValue()); for(int partitionId = entry.getKey(); partitionId < entry.getKey() + entry.getValue(); partitionId++) { contiguousPartitions.add(partitionId % nextCandidateCluster.getNumberOfPartitions()); } System.out.println("Contiguous partitions: " + contiguousPartitions); partitionsToRemoveFromThisZone.addAll(Utils.removeItemsToSplitListEvenly(contiguousPartitions, maxContiguousPartitionsPerZone)); } } partitionsToRemoveFromZone.put(zoneId, partitionsToRemoveFromThisZone); System.out.println("\t\tPartitions to remove: " + partitionsToRemoveFromThisZone); } Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); Random r = new Random(); for(int zoneId: returnCluster.getZoneIds()) { for(int partitionId: partitionsToRemoveFromZone.get(zoneId)) { // Pick a random other zone Id List<Integer> otherZoneIds = new ArrayList<Integer>(); for(int otherZoneId: returnCluster.getZoneIds()) { if(otherZoneId != zoneId) { otherZoneIds.add(otherZoneId); } } int whichOtherZoneId = otherZoneIds.get(r.nextInt(otherZoneIds.size())); // Pick a random node from other zone ID int whichNodeOffset = r.nextInt(returnCluster.getNumberOfNodesInZone(whichOtherZoneId)); int whichNodeId = new ArrayList<Integer>(returnCluster.getNodeIdsInZone(whichOtherZoneId)).get(whichNodeOffset); // Steal partition from one zone to another! returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster, whichNodeId, Lists.newArrayList(partitionId)); } } return returnCluster; }
[ "public", "static", "Cluster", "balanceContiguousPartitionsPerZone", "(", "final", "Cluster", "nextCandidateCluster", ",", "final", "int", "maxContiguousPartitionsPerZone", ")", "{", "System", ".", "out", ".", "println", "(", "\"Balance number of contiguous partitions within a zone.\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"numPartitionsPerZone\"", ")", ";", "for", "(", "int", "zoneId", ":", "nextCandidateCluster", ".", "getZoneIds", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "zoneId", "+", "\" : \"", "+", "nextCandidateCluster", ".", "getNumberOfPartitionsInZone", "(", "zoneId", ")", ")", ";", "}", "System", ".", "out", ".", "println", "(", "\"numNodesPerZone\"", ")", ";", "for", "(", "int", "zoneId", ":", "nextCandidateCluster", ".", "getZoneIds", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "zoneId", "+", "\" : \"", "+", "nextCandidateCluster", ".", "getNumberOfNodesInZone", "(", "zoneId", ")", ")", ";", "}", "// Break up contiguous partitions within each zone", "HashMap", "<", "Integer", ",", "List", "<", "Integer", ">", ">", "partitionsToRemoveFromZone", "=", "Maps", ".", "newHashMap", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"Contiguous partitions\"", ")", ";", "for", "(", "Integer", "zoneId", ":", "nextCandidateCluster", ".", "getZoneIds", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"\\tZone: \"", "+", "zoneId", ")", ";", "Map", "<", "Integer", ",", "Integer", ">", "partitionToRunLength", "=", "PartitionBalanceUtils", ".", "getMapOfContiguousPartitions", "(", "nextCandidateCluster", ",", "zoneId", ")", ";", "List", "<", "Integer", ">", "partitionsToRemoveFromThisZone", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "Integer", ",", "Integer", ">", "entry", ":", "partitionToRunLength", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getValue", "(", ")", ">", "maxContiguousPartitionsPerZone", ")", "{", "List", "<", "Integer", ">", "contiguousPartitions", "=", "new", "ArrayList", "<", "Integer", ">", "(", "entry", ".", "getValue", "(", ")", ")", ";", "for", "(", "int", "partitionId", "=", "entry", ".", "getKey", "(", ")", ";", "partitionId", "<", "entry", ".", "getKey", "(", ")", "+", "entry", ".", "getValue", "(", ")", ";", "partitionId", "++", ")", "{", "contiguousPartitions", ".", "add", "(", "partitionId", "%", "nextCandidateCluster", ".", "getNumberOfPartitions", "(", ")", ")", ";", "}", "System", ".", "out", ".", "println", "(", "\"Contiguous partitions: \"", "+", "contiguousPartitions", ")", ";", "partitionsToRemoveFromThisZone", ".", "addAll", "(", "Utils", ".", "removeItemsToSplitListEvenly", "(", "contiguousPartitions", ",", "maxContiguousPartitionsPerZone", ")", ")", ";", "}", "}", "partitionsToRemoveFromZone", ".", "put", "(", "zoneId", ",", "partitionsToRemoveFromThisZone", ")", ";", "System", ".", "out", ".", "println", "(", "\"\\t\\tPartitions to remove: \"", "+", "partitionsToRemoveFromThisZone", ")", ";", "}", "Cluster", "returnCluster", "=", "Cluster", ".", "cloneCluster", "(", "nextCandidateCluster", ")", ";", "Random", "r", "=", "new", "Random", "(", ")", ";", "for", "(", "int", "zoneId", ":", "returnCluster", ".", "getZoneIds", "(", ")", ")", "{", "for", "(", "int", "partitionId", ":", "partitionsToRemoveFromZone", ".", "get", "(", "zoneId", ")", ")", "{", "// Pick a random other zone Id", "List", "<", "Integer", ">", "otherZoneIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "int", "otherZoneId", ":", "returnCluster", ".", "getZoneIds", "(", ")", ")", "{", "if", "(", "otherZoneId", "!=", "zoneId", ")", "{", "otherZoneIds", ".", "add", "(", "otherZoneId", ")", ";", "}", "}", "int", "whichOtherZoneId", "=", "otherZoneIds", ".", "get", "(", "r", ".", "nextInt", "(", "otherZoneIds", ".", "size", "(", ")", ")", ")", ";", "// Pick a random node from other zone ID", "int", "whichNodeOffset", "=", "r", ".", "nextInt", "(", "returnCluster", ".", "getNumberOfNodesInZone", "(", "whichOtherZoneId", ")", ")", ";", "int", "whichNodeId", "=", "new", "ArrayList", "<", "Integer", ">", "(", "returnCluster", ".", "getNodeIdsInZone", "(", "whichOtherZoneId", ")", ")", ".", "get", "(", "whichNodeOffset", ")", ";", "// Steal partition from one zone to another!", "returnCluster", "=", "UpdateClusterUtils", ".", "createUpdatedCluster", "(", "returnCluster", ",", "whichNodeId", ",", "Lists", ".", "newArrayList", "(", "partitionId", ")", ")", ";", "}", "}", "return", "returnCluster", ";", "}" ]
Ensures that no more than maxContiguousPartitionsPerZone partitions are contiguous within a single zone. Moves the necessary partitions to break up contiguous runs from each zone to some other random zone/node. There is some chance that such random moves could result in contiguous partitions in other zones. @param nextCandidateCluster cluster metadata @param maxContiguousPartitionsPerZone See RebalanceCLI. @return Return updated cluster metadata.
[ "Ensures", "that", "no", "more", "than", "maxContiguousPartitionsPerZone", "partitions", "are", "contiguous", "within", "a", "single", "zone", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L489-L557
161,110
voldemort/voldemort
src/java/voldemort/tools/Repartitioner.java
Repartitioner.swapPartitions
public static Cluster swapPartitions(final Cluster nextCandidateCluster, final int nodeIdA, final int partitionIdA, final int nodeIdB, final int partitionIdB) { Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); // Swap partitions between nodes! returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster, nodeIdA, Lists.newArrayList(partitionIdB)); returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster, nodeIdB, Lists.newArrayList(partitionIdA)); return returnCluster; }
java
public static Cluster swapPartitions(final Cluster nextCandidateCluster, final int nodeIdA, final int partitionIdA, final int nodeIdB, final int partitionIdB) { Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); // Swap partitions between nodes! returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster, nodeIdA, Lists.newArrayList(partitionIdB)); returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster, nodeIdB, Lists.newArrayList(partitionIdA)); return returnCluster; }
[ "public", "static", "Cluster", "swapPartitions", "(", "final", "Cluster", "nextCandidateCluster", ",", "final", "int", "nodeIdA", ",", "final", "int", "partitionIdA", ",", "final", "int", "nodeIdB", ",", "final", "int", "partitionIdB", ")", "{", "Cluster", "returnCluster", "=", "Cluster", ".", "cloneCluster", "(", "nextCandidateCluster", ")", ";", "// Swap partitions between nodes!", "returnCluster", "=", "UpdateClusterUtils", ".", "createUpdatedCluster", "(", "returnCluster", ",", "nodeIdA", ",", "Lists", ".", "newArrayList", "(", "partitionIdB", ")", ")", ";", "returnCluster", "=", "UpdateClusterUtils", ".", "createUpdatedCluster", "(", "returnCluster", ",", "nodeIdB", ",", "Lists", ".", "newArrayList", "(", "partitionIdA", ")", ")", ";", "return", "returnCluster", ";", "}" ]
Swaps two specified partitions. Pair-wase partition swapping may be more prone to local minima than larger perturbations. Could consider "swapping" a list of <nodeId/partitionId>. This would allow a few nodes to be identified (random # btw 2-5?) and then "swapped" (shuffled? rotated?). @return modified cluster metadata.
[ "Swaps", "two", "specified", "partitions", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L569-L585
161,111
voldemort/voldemort
src/java/voldemort/tools/Repartitioner.java
Repartitioner.swapRandomPartitionsWithinZone
public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster, final int zoneId) { Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); Random r = new Random(); List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId)); if(nodeIdsInZone.size() == 0) { return returnCluster; } // Select random stealer node int stealerNodeOffset = r.nextInt(nodeIdsInZone.size()); Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset); // Select random stealer partition List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId) .getPartitionIds(); if(stealerPartitions.size() == 0) { return nextCandidateCluster; } int stealerPartitionOffset = r.nextInt(stealerPartitions.size()); int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset); // Select random donor node List<Integer> donorNodeIds = new ArrayList<Integer>(); donorNodeIds.addAll(nodeIdsInZone); donorNodeIds.remove(stealerNodeId); if(donorNodeIds.isEmpty()) { // No donor nodes! return returnCluster; } int donorIdOffset = r.nextInt(donorNodeIds.size()); Integer donorNodeId = donorNodeIds.get(donorIdOffset); // Select random donor partition List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds(); int donorPartitionOffset = r.nextInt(donorPartitions.size()); int donorPartitionId = donorPartitions.get(donorPartitionOffset); return swapPartitions(returnCluster, stealerNodeId, stealerPartitionId, donorNodeId, donorPartitionId); }
java
public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster, final int zoneId) { Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); Random r = new Random(); List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId)); if(nodeIdsInZone.size() == 0) { return returnCluster; } // Select random stealer node int stealerNodeOffset = r.nextInt(nodeIdsInZone.size()); Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset); // Select random stealer partition List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId) .getPartitionIds(); if(stealerPartitions.size() == 0) { return nextCandidateCluster; } int stealerPartitionOffset = r.nextInt(stealerPartitions.size()); int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset); // Select random donor node List<Integer> donorNodeIds = new ArrayList<Integer>(); donorNodeIds.addAll(nodeIdsInZone); donorNodeIds.remove(stealerNodeId); if(donorNodeIds.isEmpty()) { // No donor nodes! return returnCluster; } int donorIdOffset = r.nextInt(donorNodeIds.size()); Integer donorNodeId = donorNodeIds.get(donorIdOffset); // Select random donor partition List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds(); int donorPartitionOffset = r.nextInt(donorPartitions.size()); int donorPartitionId = donorPartitions.get(donorPartitionOffset); return swapPartitions(returnCluster, stealerNodeId, stealerPartitionId, donorNodeId, donorPartitionId); }
[ "public", "static", "Cluster", "swapRandomPartitionsWithinZone", "(", "final", "Cluster", "nextCandidateCluster", ",", "final", "int", "zoneId", ")", "{", "Cluster", "returnCluster", "=", "Cluster", ".", "cloneCluster", "(", "nextCandidateCluster", ")", ";", "Random", "r", "=", "new", "Random", "(", ")", ";", "List", "<", "Integer", ">", "nodeIdsInZone", "=", "new", "ArrayList", "<", "Integer", ">", "(", "nextCandidateCluster", ".", "getNodeIdsInZone", "(", "zoneId", ")", ")", ";", "if", "(", "nodeIdsInZone", ".", "size", "(", ")", "==", "0", ")", "{", "return", "returnCluster", ";", "}", "// Select random stealer node", "int", "stealerNodeOffset", "=", "r", ".", "nextInt", "(", "nodeIdsInZone", ".", "size", "(", ")", ")", ";", "Integer", "stealerNodeId", "=", "nodeIdsInZone", ".", "get", "(", "stealerNodeOffset", ")", ";", "// Select random stealer partition", "List", "<", "Integer", ">", "stealerPartitions", "=", "returnCluster", ".", "getNodeById", "(", "stealerNodeId", ")", ".", "getPartitionIds", "(", ")", ";", "if", "(", "stealerPartitions", ".", "size", "(", ")", "==", "0", ")", "{", "return", "nextCandidateCluster", ";", "}", "int", "stealerPartitionOffset", "=", "r", ".", "nextInt", "(", "stealerPartitions", ".", "size", "(", ")", ")", ";", "int", "stealerPartitionId", "=", "stealerPartitions", ".", "get", "(", "stealerPartitionOffset", ")", ";", "// Select random donor node", "List", "<", "Integer", ">", "donorNodeIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "donorNodeIds", ".", "addAll", "(", "nodeIdsInZone", ")", ";", "donorNodeIds", ".", "remove", "(", "stealerNodeId", ")", ";", "if", "(", "donorNodeIds", ".", "isEmpty", "(", ")", ")", "{", "// No donor nodes!", "return", "returnCluster", ";", "}", "int", "donorIdOffset", "=", "r", ".", "nextInt", "(", "donorNodeIds", ".", "size", "(", ")", ")", ";", "Integer", "donorNodeId", "=", "donorNodeIds", ".", "get", "(", "donorIdOffset", ")", ";", "// Select random donor partition", "List", "<", "Integer", ">", "donorPartitions", "=", "returnCluster", ".", "getNodeById", "(", "donorNodeId", ")", ".", "getPartitionIds", "(", ")", ";", "int", "donorPartitionOffset", "=", "r", ".", "nextInt", "(", "donorPartitions", ".", "size", "(", ")", ")", ";", "int", "donorPartitionId", "=", "donorPartitions", ".", "get", "(", "donorPartitionOffset", ")", ";", "return", "swapPartitions", "(", "returnCluster", ",", "stealerNodeId", ",", "stealerPartitionId", ",", "donorNodeId", ",", "donorPartitionId", ")", ";", "}" ]
Within a single zone, swaps one random partition on one random node with another random partition on different random node. @param nextCandidateCluster @param zoneId Zone ID within which to shuffle partitions @return updated cluster
[ "Within", "a", "single", "zone", "swaps", "one", "random", "partition", "on", "one", "random", "node", "with", "another", "random", "partition", "on", "different", "random", "node", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L595-L640
161,112
voldemort/voldemort
src/java/voldemort/tools/Repartitioner.java
Repartitioner.randomShufflePartitions
public static Cluster randomShufflePartitions(final Cluster nextCandidateCluster, final int randomSwapAttempts, final int randomSwapSuccesses, final List<Integer> randomSwapZoneIds, List<StoreDefinition> storeDefs) { List<Integer> zoneIds = null; if(randomSwapZoneIds.isEmpty()) { zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds()); } else { zoneIds = new ArrayList<Integer>(randomSwapZoneIds); } List<Integer> nodeIds = new ArrayList<Integer>(); Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility(); int successes = 0; for(int i = 0; i < randomSwapAttempts; i++) { // Iterate over zone ids to decide which node ids to include for // intra-zone swapping. // In future, if there is a need to support inter-zone swapping, // then just remove the // zone specific logic that populates nodeIdSet and add all nodes // from across all zones. int zoneIdOffset = i % zoneIds.size(); Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset)); nodeIds = new ArrayList<Integer>(nodeIdSet); Collections.shuffle(zoneIds, new Random(System.currentTimeMillis())); Cluster shuffleResults = swapRandomPartitionsAmongNodes(returnCluster, nodeIds); double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility(); if(nextUtility < currentUtility) { System.out.println("Swap improved max-min ratio: " + currentUtility + " -> " + nextUtility + " (improvement " + successes + " on swap attempt " + i + ")"); successes++; returnCluster = shuffleResults; currentUtility = nextUtility; } if(successes >= randomSwapSuccesses) { // Enough successes, move on. break; } } return returnCluster; }
java
public static Cluster randomShufflePartitions(final Cluster nextCandidateCluster, final int randomSwapAttempts, final int randomSwapSuccesses, final List<Integer> randomSwapZoneIds, List<StoreDefinition> storeDefs) { List<Integer> zoneIds = null; if(randomSwapZoneIds.isEmpty()) { zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds()); } else { zoneIds = new ArrayList<Integer>(randomSwapZoneIds); } List<Integer> nodeIds = new ArrayList<Integer>(); Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility(); int successes = 0; for(int i = 0; i < randomSwapAttempts; i++) { // Iterate over zone ids to decide which node ids to include for // intra-zone swapping. // In future, if there is a need to support inter-zone swapping, // then just remove the // zone specific logic that populates nodeIdSet and add all nodes // from across all zones. int zoneIdOffset = i % zoneIds.size(); Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset)); nodeIds = new ArrayList<Integer>(nodeIdSet); Collections.shuffle(zoneIds, new Random(System.currentTimeMillis())); Cluster shuffleResults = swapRandomPartitionsAmongNodes(returnCluster, nodeIds); double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility(); if(nextUtility < currentUtility) { System.out.println("Swap improved max-min ratio: " + currentUtility + " -> " + nextUtility + " (improvement " + successes + " on swap attempt " + i + ")"); successes++; returnCluster = shuffleResults; currentUtility = nextUtility; } if(successes >= randomSwapSuccesses) { // Enough successes, move on. break; } } return returnCluster; }
[ "public", "static", "Cluster", "randomShufflePartitions", "(", "final", "Cluster", "nextCandidateCluster", ",", "final", "int", "randomSwapAttempts", ",", "final", "int", "randomSwapSuccesses", ",", "final", "List", "<", "Integer", ">", "randomSwapZoneIds", ",", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "List", "<", "Integer", ">", "zoneIds", "=", "null", ";", "if", "(", "randomSwapZoneIds", ".", "isEmpty", "(", ")", ")", "{", "zoneIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", "nextCandidateCluster", ".", "getZoneIds", "(", ")", ")", ";", "}", "else", "{", "zoneIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", "randomSwapZoneIds", ")", ";", "}", "List", "<", "Integer", ">", "nodeIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "Cluster", "returnCluster", "=", "Cluster", ".", "cloneCluster", "(", "nextCandidateCluster", ")", ";", "double", "currentUtility", "=", "new", "PartitionBalance", "(", "returnCluster", ",", "storeDefs", ")", ".", "getUtility", "(", ")", ";", "int", "successes", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "randomSwapAttempts", ";", "i", "++", ")", "{", "// Iterate over zone ids to decide which node ids to include for", "// intra-zone swapping.", "// In future, if there is a need to support inter-zone swapping,", "// then just remove the", "// zone specific logic that populates nodeIdSet and add all nodes", "// from across all zones.", "int", "zoneIdOffset", "=", "i", "%", "zoneIds", ".", "size", "(", ")", ";", "Set", "<", "Integer", ">", "nodeIdSet", "=", "nextCandidateCluster", ".", "getNodeIdsInZone", "(", "zoneIds", ".", "get", "(", "zoneIdOffset", ")", ")", ";", "nodeIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", "nodeIdSet", ")", ";", "Collections", ".", "shuffle", "(", "zoneIds", ",", "new", "Random", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ")", ";", "Cluster", "shuffleResults", "=", "swapRandomPartitionsAmongNodes", "(", "returnCluster", ",", "nodeIds", ")", ";", "double", "nextUtility", "=", "new", "PartitionBalance", "(", "shuffleResults", ",", "storeDefs", ")", ".", "getUtility", "(", ")", ";", "if", "(", "nextUtility", "<", "currentUtility", ")", "{", "System", ".", "out", ".", "println", "(", "\"Swap improved max-min ratio: \"", "+", "currentUtility", "+", "\" -> \"", "+", "nextUtility", "+", "\" (improvement \"", "+", "successes", "+", "\" on swap attempt \"", "+", "i", "+", "\")\"", ")", ";", "successes", "++", ";", "returnCluster", "=", "shuffleResults", ";", "currentUtility", "=", "nextUtility", ";", "}", "if", "(", "successes", ">=", "randomSwapSuccesses", ")", "{", "// Enough successes, move on.", "break", ";", "}", "}", "return", "returnCluster", ";", "}" ]
Randomly shuffle partitions between nodes within every zone. @param nextCandidateCluster cluster object. @param randomSwapAttempts See RebalanceCLI. @param randomSwapSuccesses See RebalanceCLI. @param randomSwapZoneIds The set of zoneIds to consider. Each zone is done independently. @param storeDefs List of store definitions @return updated cluster
[ "Randomly", "shuffle", "partitions", "between", "nodes", "within", "every", "zone", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L705-L754
161,113
voldemort/voldemort
src/java/voldemort/tools/Repartitioner.java
Repartitioner.swapGreedyRandomPartitions
public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster, final List<Integer> nodeIds, final int greedySwapMaxPartitionsPerNode, final int greedySwapMaxPartitionsPerZone, List<StoreDefinition> storeDefs) { System.out.println("GreedyRandom : nodeIds:" + nodeIds); Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility(); int nodeIdA = -1; int nodeIdB = -1; int partitionIdA = -1; int partitionIdB = -1; for(int nodeIdAPrime: nodeIds) { System.out.println("GreedyRandom : processing nodeId:" + nodeIdAPrime); List<Integer> partitionIdsAPrime = new ArrayList<Integer>(); partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds()); Collections.shuffle(partitionIdsAPrime); int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode, partitionIdsAPrime.size()); for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) { Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime); List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>(); for(int nodeIdBPrime: nodeIds) { if(nodeIdBPrime == nodeIdAPrime) continue; for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime) .getPartitionIds()) { partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime, partitionIdBPrime)); } } Collections.shuffle(partitionIdsZone); int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone, partitionIdsZone.size()); for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) { Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst(); Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond(); Cluster swapResult = swapPartitions(returnCluster, nodeIdAPrime, partitionIdAPrime, nodeIdBPrime, partitionIdBPrime); double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility(); if(swapUtility < currentUtility) { currentUtility = swapUtility; System.out.println(" -> " + currentUtility); nodeIdA = nodeIdAPrime; partitionIdA = partitionIdAPrime; nodeIdB = nodeIdBPrime; partitionIdB = partitionIdBPrime; } } } } if(nodeIdA == -1) { return returnCluster; } return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB); }
java
public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster, final List<Integer> nodeIds, final int greedySwapMaxPartitionsPerNode, final int greedySwapMaxPartitionsPerZone, List<StoreDefinition> storeDefs) { System.out.println("GreedyRandom : nodeIds:" + nodeIds); Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility(); int nodeIdA = -1; int nodeIdB = -1; int partitionIdA = -1; int partitionIdB = -1; for(int nodeIdAPrime: nodeIds) { System.out.println("GreedyRandom : processing nodeId:" + nodeIdAPrime); List<Integer> partitionIdsAPrime = new ArrayList<Integer>(); partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds()); Collections.shuffle(partitionIdsAPrime); int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode, partitionIdsAPrime.size()); for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) { Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime); List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>(); for(int nodeIdBPrime: nodeIds) { if(nodeIdBPrime == nodeIdAPrime) continue; for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime) .getPartitionIds()) { partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime, partitionIdBPrime)); } } Collections.shuffle(partitionIdsZone); int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone, partitionIdsZone.size()); for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) { Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst(); Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond(); Cluster swapResult = swapPartitions(returnCluster, nodeIdAPrime, partitionIdAPrime, nodeIdBPrime, partitionIdBPrime); double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility(); if(swapUtility < currentUtility) { currentUtility = swapUtility; System.out.println(" -> " + currentUtility); nodeIdA = nodeIdAPrime; partitionIdA = partitionIdAPrime; nodeIdB = nodeIdBPrime; partitionIdB = partitionIdBPrime; } } } } if(nodeIdA == -1) { return returnCluster; } return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB); }
[ "public", "static", "Cluster", "swapGreedyRandomPartitions", "(", "final", "Cluster", "nextCandidateCluster", ",", "final", "List", "<", "Integer", ">", "nodeIds", ",", "final", "int", "greedySwapMaxPartitionsPerNode", ",", "final", "int", "greedySwapMaxPartitionsPerZone", ",", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "System", ".", "out", ".", "println", "(", "\"GreedyRandom : nodeIds:\"", "+", "nodeIds", ")", ";", "Cluster", "returnCluster", "=", "Cluster", ".", "cloneCluster", "(", "nextCandidateCluster", ")", ";", "double", "currentUtility", "=", "new", "PartitionBalance", "(", "returnCluster", ",", "storeDefs", ")", ".", "getUtility", "(", ")", ";", "int", "nodeIdA", "=", "-", "1", ";", "int", "nodeIdB", "=", "-", "1", ";", "int", "partitionIdA", "=", "-", "1", ";", "int", "partitionIdB", "=", "-", "1", ";", "for", "(", "int", "nodeIdAPrime", ":", "nodeIds", ")", "{", "System", ".", "out", ".", "println", "(", "\"GreedyRandom : processing nodeId:\"", "+", "nodeIdAPrime", ")", ";", "List", "<", "Integer", ">", "partitionIdsAPrime", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "partitionIdsAPrime", ".", "addAll", "(", "returnCluster", ".", "getNodeById", "(", "nodeIdAPrime", ")", ".", "getPartitionIds", "(", ")", ")", ";", "Collections", ".", "shuffle", "(", "partitionIdsAPrime", ")", ";", "int", "maxPartitionsInAPrime", "=", "Math", ".", "min", "(", "greedySwapMaxPartitionsPerNode", ",", "partitionIdsAPrime", ".", "size", "(", ")", ")", ";", "for", "(", "int", "offsetAPrime", "=", "0", ";", "offsetAPrime", "<", "maxPartitionsInAPrime", ";", "offsetAPrime", "++", ")", "{", "Integer", "partitionIdAPrime", "=", "partitionIdsAPrime", ".", "get", "(", "offsetAPrime", ")", ";", "List", "<", "Pair", "<", "Integer", ",", "Integer", ">", ">", "partitionIdsZone", "=", "new", "ArrayList", "<", "Pair", "<", "Integer", ",", "Integer", ">", ">", "(", ")", ";", "for", "(", "int", "nodeIdBPrime", ":", "nodeIds", ")", "{", "if", "(", "nodeIdBPrime", "==", "nodeIdAPrime", ")", "continue", ";", "for", "(", "Integer", "partitionIdBPrime", ":", "returnCluster", ".", "getNodeById", "(", "nodeIdBPrime", ")", ".", "getPartitionIds", "(", ")", ")", "{", "partitionIdsZone", ".", "add", "(", "new", "Pair", "<", "Integer", ",", "Integer", ">", "(", "nodeIdBPrime", ",", "partitionIdBPrime", ")", ")", ";", "}", "}", "Collections", ".", "shuffle", "(", "partitionIdsZone", ")", ";", "int", "maxPartitionsInZone", "=", "Math", ".", "min", "(", "greedySwapMaxPartitionsPerZone", ",", "partitionIdsZone", ".", "size", "(", ")", ")", ";", "for", "(", "int", "offsetZone", "=", "0", ";", "offsetZone", "<", "maxPartitionsInZone", ";", "offsetZone", "++", ")", "{", "Integer", "nodeIdBPrime", "=", "partitionIdsZone", ".", "get", "(", "offsetZone", ")", ".", "getFirst", "(", ")", ";", "Integer", "partitionIdBPrime", "=", "partitionIdsZone", ".", "get", "(", "offsetZone", ")", ".", "getSecond", "(", ")", ";", "Cluster", "swapResult", "=", "swapPartitions", "(", "returnCluster", ",", "nodeIdAPrime", ",", "partitionIdAPrime", ",", "nodeIdBPrime", ",", "partitionIdBPrime", ")", ";", "double", "swapUtility", "=", "new", "PartitionBalance", "(", "swapResult", ",", "storeDefs", ")", ".", "getUtility", "(", ")", ";", "if", "(", "swapUtility", "<", "currentUtility", ")", "{", "currentUtility", "=", "swapUtility", ";", "System", ".", "out", ".", "println", "(", "\" -> \"", "+", "currentUtility", ")", ";", "nodeIdA", "=", "nodeIdAPrime", ";", "partitionIdA", "=", "partitionIdAPrime", ";", "nodeIdB", "=", "nodeIdBPrime", ";", "partitionIdB", "=", "partitionIdBPrime", ";", "}", "}", "}", "}", "if", "(", "nodeIdA", "==", "-", "1", ")", "{", "return", "returnCluster", ";", "}", "return", "swapPartitions", "(", "returnCluster", ",", "nodeIdA", ",", "partitionIdA", ",", "nodeIdB", ",", "partitionIdB", ")", ";", "}" ]
For each node in specified zones, tries swapping some minimum number of random partitions per node with some minimum number of random partitions from other specified nodes. Chooses the best swap in each iteration. Large values of the greedSwapMaxPartitions... arguments make this method equivalent to comparing every possible swap. This may get very expensive. So if a node had partitions P1, P2, P3 and P4 and the other partitions set was Q1, Q2, Q3, Q4, Q5 The combinations that will be tried for swapping will be the cartesian product of the two sets. That is, {P1, Q1}, {P2, Q2}...{P2,Q1}, {P2,Q2}, in total 20 such swap pairs will be generated. The best among these swap pairs will be chosen. @param nextCandidateCluster @param nodeIds Node IDs within which to shuffle partitions @param greedySwapMaxPartitionsPerNode See RebalanceCLI. @param greedySwapMaxPartitionsPerZone See RebalanceCLI. @param storeDefs @return updated cluster
[ "For", "each", "node", "in", "specified", "zones", "tries", "swapping", "some", "minimum", "number", "of", "random", "partitions", "per", "node", "with", "some", "minimum", "number", "of", "random", "partitions", "from", "other", "specified", "nodes", ".", "Chooses", "the", "best", "swap", "in", "each", "iteration", ".", "Large", "values", "of", "the", "greedSwapMaxPartitions", "...", "arguments", "make", "this", "method", "equivalent", "to", "comparing", "every", "possible", "swap", ".", "This", "may", "get", "very", "expensive", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L776-L840
161,114
voldemort/voldemort
src/java/voldemort/tools/Repartitioner.java
Repartitioner.greedyShufflePartitions
public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster, final int greedyAttempts, final int greedySwapMaxPartitionsPerNode, final int greedySwapMaxPartitionsPerZone, List<Integer> greedySwapZoneIds, List<StoreDefinition> storeDefs) { List<Integer> zoneIds = null; if(greedySwapZoneIds.isEmpty()) { zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds()); } else { zoneIds = new ArrayList<Integer>(greedySwapZoneIds); } List<Integer> nodeIds = new ArrayList<Integer>(); Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility(); for(int i = 0; i < greedyAttempts; i++) { // Iterate over zone ids to decide which node ids to include for // intra-zone swapping. // In future, if there is a need to support inter-zone swapping, // then just remove the // zone specific logic that populates nodeIdSet and add all nodes // from across all zones. int zoneIdOffset = i % zoneIds.size(); Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset)); nodeIds = new ArrayList<Integer>(nodeIdSet); Collections.shuffle(zoneIds, new Random(System.currentTimeMillis())); Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster, nodeIds, greedySwapMaxPartitionsPerNode, greedySwapMaxPartitionsPerZone, storeDefs); double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility(); System.out.println("Swap improved max-min ratio: " + currentUtility + " -> " + nextUtility + " (swap attempt " + i + " in zone " + zoneIds.get(zoneIdOffset) + ")"); returnCluster = shuffleResults; currentUtility = nextUtility; } return returnCluster; }
java
public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster, final int greedyAttempts, final int greedySwapMaxPartitionsPerNode, final int greedySwapMaxPartitionsPerZone, List<Integer> greedySwapZoneIds, List<StoreDefinition> storeDefs) { List<Integer> zoneIds = null; if(greedySwapZoneIds.isEmpty()) { zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds()); } else { zoneIds = new ArrayList<Integer>(greedySwapZoneIds); } List<Integer> nodeIds = new ArrayList<Integer>(); Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility(); for(int i = 0; i < greedyAttempts; i++) { // Iterate over zone ids to decide which node ids to include for // intra-zone swapping. // In future, if there is a need to support inter-zone swapping, // then just remove the // zone specific logic that populates nodeIdSet and add all nodes // from across all zones. int zoneIdOffset = i % zoneIds.size(); Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset)); nodeIds = new ArrayList<Integer>(nodeIdSet); Collections.shuffle(zoneIds, new Random(System.currentTimeMillis())); Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster, nodeIds, greedySwapMaxPartitionsPerNode, greedySwapMaxPartitionsPerZone, storeDefs); double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility(); System.out.println("Swap improved max-min ratio: " + currentUtility + " -> " + nextUtility + " (swap attempt " + i + " in zone " + zoneIds.get(zoneIdOffset) + ")"); returnCluster = shuffleResults; currentUtility = nextUtility; } return returnCluster; }
[ "public", "static", "Cluster", "greedyShufflePartitions", "(", "final", "Cluster", "nextCandidateCluster", ",", "final", "int", "greedyAttempts", ",", "final", "int", "greedySwapMaxPartitionsPerNode", ",", "final", "int", "greedySwapMaxPartitionsPerZone", ",", "List", "<", "Integer", ">", "greedySwapZoneIds", ",", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "List", "<", "Integer", ">", "zoneIds", "=", "null", ";", "if", "(", "greedySwapZoneIds", ".", "isEmpty", "(", ")", ")", "{", "zoneIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", "nextCandidateCluster", ".", "getZoneIds", "(", ")", ")", ";", "}", "else", "{", "zoneIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", "greedySwapZoneIds", ")", ";", "}", "List", "<", "Integer", ">", "nodeIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "Cluster", "returnCluster", "=", "Cluster", ".", "cloneCluster", "(", "nextCandidateCluster", ")", ";", "double", "currentUtility", "=", "new", "PartitionBalance", "(", "returnCluster", ",", "storeDefs", ")", ".", "getUtility", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "greedyAttempts", ";", "i", "++", ")", "{", "// Iterate over zone ids to decide which node ids to include for", "// intra-zone swapping.", "// In future, if there is a need to support inter-zone swapping,", "// then just remove the", "// zone specific logic that populates nodeIdSet and add all nodes", "// from across all zones.", "int", "zoneIdOffset", "=", "i", "%", "zoneIds", ".", "size", "(", ")", ";", "Set", "<", "Integer", ">", "nodeIdSet", "=", "nextCandidateCluster", ".", "getNodeIdsInZone", "(", "zoneIds", ".", "get", "(", "zoneIdOffset", ")", ")", ";", "nodeIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", "nodeIdSet", ")", ";", "Collections", ".", "shuffle", "(", "zoneIds", ",", "new", "Random", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ")", ";", "Cluster", "shuffleResults", "=", "swapGreedyRandomPartitions", "(", "returnCluster", ",", "nodeIds", ",", "greedySwapMaxPartitionsPerNode", ",", "greedySwapMaxPartitionsPerZone", ",", "storeDefs", ")", ";", "double", "nextUtility", "=", "new", "PartitionBalance", "(", "shuffleResults", ",", "storeDefs", ")", ".", "getUtility", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"Swap improved max-min ratio: \"", "+", "currentUtility", "+", "\" -> \"", "+", "nextUtility", "+", "\" (swap attempt \"", "+", "i", "+", "\" in zone \"", "+", "zoneIds", ".", "get", "(", "zoneIdOffset", ")", "+", "\")\"", ")", ";", "returnCluster", "=", "shuffleResults", ";", "currentUtility", "=", "nextUtility", ";", "}", "return", "returnCluster", ";", "}" ]
Within a single zone, tries swapping some minimum number of random partitions per node with some minimum number of random partitions from other nodes within the zone. Chooses the best swap in each iteration. Large values of the greedSwapMaxPartitions... arguments make this method equivalent to comparing every possible swap. This is very expensive. Normal case should be : #zones X #nodes/zone X max partitions/node X max partitions/zone @param nextCandidateCluster cluster object. @param greedyAttempts See RebalanceCLI. @param greedySwapMaxPartitionsPerNode See RebalanceCLI. @param greedySwapMaxPartitionsPerZone See RebalanceCLI. @param greedySwapZoneIds The set of zoneIds to consider. Each zone is done independently. @param storeDefs @return updated cluster
[ "Within", "a", "single", "zone", "tries", "swapping", "some", "minimum", "number", "of", "random", "partitions", "per", "node", "with", "some", "minimum", "number", "of", "random", "partitions", "from", "other", "nodes", "within", "the", "zone", ".", "Chooses", "the", "best", "swap", "in", "each", "iteration", ".", "Large", "values", "of", "the", "greedSwapMaxPartitions", "...", "arguments", "make", "this", "method", "equivalent", "to", "comparing", "every", "possible", "swap", ".", "This", "is", "very", "expensive", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L862-L907
161,115
voldemort/voldemort
src/java/voldemort/rest/server/RestService.java
RestService.stopInner
@Override protected void stopInner() { /* * TODO REST-Server Need to handle inflight operations. What happens to * the existing async operations when a channel.close() is issued in * Netty? */ if(this.nettyServerChannel != null) { this.nettyServerChannel.close(); } if(allChannels != null) { allChannels.close().awaitUninterruptibly(); } this.bootstrap.releaseExternalResources(); }
java
@Override protected void stopInner() { /* * TODO REST-Server Need to handle inflight operations. What happens to * the existing async operations when a channel.close() is issued in * Netty? */ if(this.nettyServerChannel != null) { this.nettyServerChannel.close(); } if(allChannels != null) { allChannels.close().awaitUninterruptibly(); } this.bootstrap.releaseExternalResources(); }
[ "@", "Override", "protected", "void", "stopInner", "(", ")", "{", "/*\n * TODO REST-Server Need to handle inflight operations. What happens to\n * the existing async operations when a channel.close() is issued in\n * Netty?\n */", "if", "(", "this", ".", "nettyServerChannel", "!=", "null", ")", "{", "this", ".", "nettyServerChannel", ".", "close", "(", ")", ";", "}", "if", "(", "allChannels", "!=", "null", ")", "{", "allChannels", ".", "close", "(", ")", ".", "awaitUninterruptibly", "(", ")", ";", "}", "this", ".", "bootstrap", ".", "releaseExternalResources", "(", ")", ";", "}" ]
Closes the Netty Channel and releases all resources
[ "Closes", "the", "Netty", "Channel", "and", "releases", "all", "resources" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/server/RestService.java#L84-L99
161,116
voldemort/voldemort
src/java/voldemort/rest/server/RestServerRequestHandler.java
RestServerRequestHandler.parseZoneId
protected int parseZoneId() { int result = -1; String zoneIdStr = this.request.getHeader(RestMessageHeaders.X_VOLD_ZONE_ID); if(zoneIdStr != null) { try { int zoneId = Integer.parseInt(zoneIdStr); if(zoneId < 0) { logger.error("ZoneId cannot be negative. Assuming the default zone id."); } else { result = zoneId; } } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect zone id parameter. Cannot parse this to int: " + zoneIdStr, nfe); } } return result; }
java
protected int parseZoneId() { int result = -1; String zoneIdStr = this.request.getHeader(RestMessageHeaders.X_VOLD_ZONE_ID); if(zoneIdStr != null) { try { int zoneId = Integer.parseInt(zoneIdStr); if(zoneId < 0) { logger.error("ZoneId cannot be negative. Assuming the default zone id."); } else { result = zoneId; } } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect zone id parameter. Cannot parse this to int: " + zoneIdStr, nfe); } } return result; }
[ "protected", "int", "parseZoneId", "(", ")", "{", "int", "result", "=", "-", "1", ";", "String", "zoneIdStr", "=", "this", ".", "request", ".", "getHeader", "(", "RestMessageHeaders", ".", "X_VOLD_ZONE_ID", ")", ";", "if", "(", "zoneIdStr", "!=", "null", ")", "{", "try", "{", "int", "zoneId", "=", "Integer", ".", "parseInt", "(", "zoneIdStr", ")", ";", "if", "(", "zoneId", "<", "0", ")", "{", "logger", ".", "error", "(", "\"ZoneId cannot be negative. Assuming the default zone id.\"", ")", ";", "}", "else", "{", "result", "=", "zoneId", ";", "}", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "logger", ".", "error", "(", "\"Exception when validating request. Incorrect zone id parameter. Cannot parse this to int: \"", "+", "zoneIdStr", ",", "nfe", ")", ";", "}", "}", "return", "result", ";", "}" ]
Retrieve and validate the zone id value from the REST request. "X-VOLD-Zone-Id" is the zone id header. @return valid zone id or -1 if there is no/invalid zone id
[ "Retrieve", "and", "validate", "the", "zone", "id", "value", "from", "the", "REST", "request", ".", "X", "-", "VOLD", "-", "Zone", "-", "Id", "is", "the", "zone", "id", "header", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/server/RestServerRequestHandler.java#L82-L100
161,117
voldemort/voldemort
src/java/voldemort/rest/server/RestServerRequestHandler.java
RestServerRequestHandler.registerRequest
@Override protected void registerRequest(RestRequestValidator requestValidator, ChannelHandlerContext ctx, MessageEvent messageEvent) { // At this point we know the request is valid and we have a // error handler. So we construct the composite Voldemort // request object. CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject(); if(requestObject != null) { // Dropping dead requests from going to next handler long now = System.currentTimeMillis(); if(requestObject.getRequestOriginTimeInMs() + requestObject.getRoutingTimeoutInMs() <= now) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, "current time: " + now + "\torigin time: " + requestObject.getRequestOriginTimeInMs() + "\ttimeout in ms: " + requestObject.getRoutingTimeoutInMs()); return; } else { Store store = getStore(requestValidator.getStoreName(), requestValidator.getParsedRoutingType()); if(store != null) { VoldemortStoreRequest voldemortStoreRequest = new VoldemortStoreRequest(requestObject, store, parseZoneId()); Channels.fireMessageReceived(ctx, voldemortStoreRequest); } else { logger.error("Error when getting store. Non Existing store name."); RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Non Existing store name. Critical error."); return; } } } }
java
@Override protected void registerRequest(RestRequestValidator requestValidator, ChannelHandlerContext ctx, MessageEvent messageEvent) { // At this point we know the request is valid and we have a // error handler. So we construct the composite Voldemort // request object. CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject(); if(requestObject != null) { // Dropping dead requests from going to next handler long now = System.currentTimeMillis(); if(requestObject.getRequestOriginTimeInMs() + requestObject.getRoutingTimeoutInMs() <= now) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, "current time: " + now + "\torigin time: " + requestObject.getRequestOriginTimeInMs() + "\ttimeout in ms: " + requestObject.getRoutingTimeoutInMs()); return; } else { Store store = getStore(requestValidator.getStoreName(), requestValidator.getParsedRoutingType()); if(store != null) { VoldemortStoreRequest voldemortStoreRequest = new VoldemortStoreRequest(requestObject, store, parseZoneId()); Channels.fireMessageReceived(ctx, voldemortStoreRequest); } else { logger.error("Error when getting store. Non Existing store name."); RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Non Existing store name. Critical error."); return; } } } }
[ "@", "Override", "protected", "void", "registerRequest", "(", "RestRequestValidator", "requestValidator", ",", "ChannelHandlerContext", "ctx", ",", "MessageEvent", "messageEvent", ")", "{", "// At this point we know the request is valid and we have a", "// error handler. So we construct the composite Voldemort", "// request object.", "CompositeVoldemortRequest", "<", "ByteArray", ",", "byte", "[", "]", ">", "requestObject", "=", "requestValidator", ".", "constructCompositeVoldemortRequestObject", "(", ")", ";", "if", "(", "requestObject", "!=", "null", ")", "{", "// Dropping dead requests from going to next handler", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "requestObject", ".", "getRequestOriginTimeInMs", "(", ")", "+", "requestObject", ".", "getRoutingTimeoutInMs", "(", ")", "<=", "now", ")", "{", "RestErrorHandler", ".", "writeErrorResponse", "(", "messageEvent", ",", "HttpResponseStatus", ".", "REQUEST_TIMEOUT", ",", "\"current time: \"", "+", "now", "+", "\"\\torigin time: \"", "+", "requestObject", ".", "getRequestOriginTimeInMs", "(", ")", "+", "\"\\ttimeout in ms: \"", "+", "requestObject", ".", "getRoutingTimeoutInMs", "(", ")", ")", ";", "return", ";", "}", "else", "{", "Store", "store", "=", "getStore", "(", "requestValidator", ".", "getStoreName", "(", ")", ",", "requestValidator", ".", "getParsedRoutingType", "(", ")", ")", ";", "if", "(", "store", "!=", "null", ")", "{", "VoldemortStoreRequest", "voldemortStoreRequest", "=", "new", "VoldemortStoreRequest", "(", "requestObject", ",", "store", ",", "parseZoneId", "(", ")", ")", ";", "Channels", ".", "fireMessageReceived", "(", "ctx", ",", "voldemortStoreRequest", ")", ";", "}", "else", "{", "logger", ".", "error", "(", "\"Error when getting store. Non Existing store name.\"", ")", ";", "RestErrorHandler", ".", "writeErrorResponse", "(", "messageEvent", ",", "HttpResponseStatus", ".", "BAD_REQUEST", ",", "\"Non Existing store name. Critical error.\"", ")", ";", "return", ";", "}", "}", "}", "}" ]
Constructs a valid request and passes it on to the next handler. It also creates the 'Store' object corresponding to the store name specified in the REST request. @param requestValidator The Validator object used to construct the request object @param ctx Context of the Netty channel @param messageEvent Message Event used to write the response / exception
[ "Constructs", "a", "valid", "request", "and", "passes", "it", "on", "to", "the", "next", "handler", ".", "It", "also", "creates", "the", "Store", "object", "corresponding", "to", "the", "store", "name", "specified", "in", "the", "REST", "request", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/server/RestServerRequestHandler.java#L112-L152
161,118
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceController.java
RebalanceController.getCurrentClusterState
private Pair<Cluster, List<StoreDefinition>> getCurrentClusterState() { // Retrieve the latest cluster metadata from the existing nodes Versioned<Cluster> currentVersionedCluster = adminClient.rebalanceOps.getLatestCluster(Utils.nodeListToNodeIdList(Lists.newArrayList(adminClient.getAdminClientCluster() .getNodes()))); Cluster cluster = currentVersionedCluster.getValue(); List<StoreDefinition> storeDefs = adminClient.rebalanceOps.getCurrentStoreDefinitions(cluster); return new Pair<Cluster, List<StoreDefinition>>(cluster, storeDefs); }
java
private Pair<Cluster, List<StoreDefinition>> getCurrentClusterState() { // Retrieve the latest cluster metadata from the existing nodes Versioned<Cluster> currentVersionedCluster = adminClient.rebalanceOps.getLatestCluster(Utils.nodeListToNodeIdList(Lists.newArrayList(adminClient.getAdminClientCluster() .getNodes()))); Cluster cluster = currentVersionedCluster.getValue(); List<StoreDefinition> storeDefs = adminClient.rebalanceOps.getCurrentStoreDefinitions(cluster); return new Pair<Cluster, List<StoreDefinition>>(cluster, storeDefs); }
[ "private", "Pair", "<", "Cluster", ",", "List", "<", "StoreDefinition", ">", ">", "getCurrentClusterState", "(", ")", "{", "// Retrieve the latest cluster metadata from the existing nodes", "Versioned", "<", "Cluster", ">", "currentVersionedCluster", "=", "adminClient", ".", "rebalanceOps", ".", "getLatestCluster", "(", "Utils", ".", "nodeListToNodeIdList", "(", "Lists", ".", "newArrayList", "(", "adminClient", ".", "getAdminClientCluster", "(", ")", ".", "getNodes", "(", ")", ")", ")", ")", ";", "Cluster", "cluster", "=", "currentVersionedCluster", ".", "getValue", "(", ")", ";", "List", "<", "StoreDefinition", ">", "storeDefs", "=", "adminClient", ".", "rebalanceOps", ".", "getCurrentStoreDefinitions", "(", "cluster", ")", ";", "return", "new", "Pair", "<", "Cluster", ",", "List", "<", "StoreDefinition", ">", ">", "(", "cluster", ",", "storeDefs", ")", ";", "}" ]
Probe the existing cluster to retrieve the current cluster xml and stores xml. @return Pair of Cluster and List<StoreDefinition> from current cluster.
[ "Probe", "the", "existing", "cluster", "to", "retrieve", "the", "current", "cluster", "xml", "and", "stores", "xml", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceController.java#L82-L90
161,119
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceController.java
RebalanceController.executePlan
private void executePlan(RebalancePlan rebalancePlan) { logger.info("Starting to execute rebalance Plan!"); int batchCount = 0; int partitionStoreCount = 0; long totalTimeMs = 0; List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan(); int numBatches = entirePlan.size(); int numPartitionStores = rebalancePlan.getPartitionStoresMoved(); for(RebalanceBatchPlan batchPlan: entirePlan) { logger.info("======== REBALANCING BATCH " + (batchCount + 1) + " ========"); RebalanceUtils.printBatchLog(batchCount, logger, batchPlan.toString()); long startTimeMs = System.currentTimeMillis(); // ACTUALLY DO A BATCH OF REBALANCING! executeBatch(batchCount, batchPlan); totalTimeMs += (System.currentTimeMillis() - startTimeMs); // Bump up the statistics batchCount++; partitionStoreCount += batchPlan.getPartitionStoreMoves(); batchStatusLog(batchCount, numBatches, partitionStoreCount, numPartitionStores, totalTimeMs); } }
java
private void executePlan(RebalancePlan rebalancePlan) { logger.info("Starting to execute rebalance Plan!"); int batchCount = 0; int partitionStoreCount = 0; long totalTimeMs = 0; List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan(); int numBatches = entirePlan.size(); int numPartitionStores = rebalancePlan.getPartitionStoresMoved(); for(RebalanceBatchPlan batchPlan: entirePlan) { logger.info("======== REBALANCING BATCH " + (batchCount + 1) + " ========"); RebalanceUtils.printBatchLog(batchCount, logger, batchPlan.toString()); long startTimeMs = System.currentTimeMillis(); // ACTUALLY DO A BATCH OF REBALANCING! executeBatch(batchCount, batchPlan); totalTimeMs += (System.currentTimeMillis() - startTimeMs); // Bump up the statistics batchCount++; partitionStoreCount += batchPlan.getPartitionStoreMoves(); batchStatusLog(batchCount, numBatches, partitionStoreCount, numPartitionStores, totalTimeMs); } }
[ "private", "void", "executePlan", "(", "RebalancePlan", "rebalancePlan", ")", "{", "logger", ".", "info", "(", "\"Starting to execute rebalance Plan!\"", ")", ";", "int", "batchCount", "=", "0", ";", "int", "partitionStoreCount", "=", "0", ";", "long", "totalTimeMs", "=", "0", ";", "List", "<", "RebalanceBatchPlan", ">", "entirePlan", "=", "rebalancePlan", ".", "getPlan", "(", ")", ";", "int", "numBatches", "=", "entirePlan", ".", "size", "(", ")", ";", "int", "numPartitionStores", "=", "rebalancePlan", ".", "getPartitionStoresMoved", "(", ")", ";", "for", "(", "RebalanceBatchPlan", "batchPlan", ":", "entirePlan", ")", "{", "logger", ".", "info", "(", "\"======== REBALANCING BATCH \"", "+", "(", "batchCount", "+", "1", ")", "+", "\" ========\"", ")", ";", "RebalanceUtils", ".", "printBatchLog", "(", "batchCount", ",", "logger", ",", "batchPlan", ".", "toString", "(", ")", ")", ";", "long", "startTimeMs", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "// ACTUALLY DO A BATCH OF REBALANCING!", "executeBatch", "(", "batchCount", ",", "batchPlan", ")", ";", "totalTimeMs", "+=", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "startTimeMs", ")", ";", "// Bump up the statistics", "batchCount", "++", ";", "partitionStoreCount", "+=", "batchPlan", ".", "getPartitionStoreMoves", "(", ")", ";", "batchStatusLog", "(", "batchCount", ",", "numBatches", ",", "partitionStoreCount", ",", "numPartitionStores", ",", "totalTimeMs", ")", ";", "}", "}" ]
Executes the rebalance plan. Does so batch-by-batch. Between each batch, status is dumped to logger.info. @param rebalancePlan
[ "Executes", "the", "rebalance", "plan", ".", "Does", "so", "batch", "-", "by", "-", "batch", ".", "Between", "each", "batch", "status", "is", "dumped", "to", "logger", ".", "info", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceController.java#L192-L224
161,120
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceController.java
RebalanceController.batchStatusLog
private void batchStatusLog(int batchCount, int numBatches, int partitionStoreCount, int numPartitionStores, long totalTimeMs) { // Calculate the estimated end time and pretty print stats double rate = 1; long estimatedTimeMs = 0; if(numPartitionStores > 0) { rate = partitionStoreCount / numPartitionStores; estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs; } StringBuilder sb = new StringBuilder(); sb.append("Batch Complete!") .append(Utils.NEWLINE) .append("\tbatches moved: ") .append(batchCount) .append(" out of ") .append(numBatches) .append(Utils.NEWLINE) .append("\tPartition stores moved: ") .append(partitionStoreCount) .append(" out of ") .append(numPartitionStores) .append(Utils.NEWLINE) .append("\tPercent done: ") .append(decimalFormatter.format(rate * 100.0)) .append(Utils.NEWLINE) .append("\tEstimated time left: ") .append(estimatedTimeMs) .append(" ms (") .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs)) .append(" hours)"); RebalanceUtils.printBatchLog(batchCount, logger, sb.toString()); }
java
private void batchStatusLog(int batchCount, int numBatches, int partitionStoreCount, int numPartitionStores, long totalTimeMs) { // Calculate the estimated end time and pretty print stats double rate = 1; long estimatedTimeMs = 0; if(numPartitionStores > 0) { rate = partitionStoreCount / numPartitionStores; estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs; } StringBuilder sb = new StringBuilder(); sb.append("Batch Complete!") .append(Utils.NEWLINE) .append("\tbatches moved: ") .append(batchCount) .append(" out of ") .append(numBatches) .append(Utils.NEWLINE) .append("\tPartition stores moved: ") .append(partitionStoreCount) .append(" out of ") .append(numPartitionStores) .append(Utils.NEWLINE) .append("\tPercent done: ") .append(decimalFormatter.format(rate * 100.0)) .append(Utils.NEWLINE) .append("\tEstimated time left: ") .append(estimatedTimeMs) .append(" ms (") .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs)) .append(" hours)"); RebalanceUtils.printBatchLog(batchCount, logger, sb.toString()); }
[ "private", "void", "batchStatusLog", "(", "int", "batchCount", ",", "int", "numBatches", ",", "int", "partitionStoreCount", ",", "int", "numPartitionStores", ",", "long", "totalTimeMs", ")", "{", "// Calculate the estimated end time and pretty print stats", "double", "rate", "=", "1", ";", "long", "estimatedTimeMs", "=", "0", ";", "if", "(", "numPartitionStores", ">", "0", ")", "{", "rate", "=", "partitionStoreCount", "/", "numPartitionStores", ";", "estimatedTimeMs", "=", "(", "long", ")", "(", "totalTimeMs", "/", "rate", ")", "-", "totalTimeMs", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"Batch Complete!\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ".", "append", "(", "\"\\tbatches moved: \"", ")", ".", "append", "(", "batchCount", ")", ".", "append", "(", "\" out of \"", ")", ".", "append", "(", "numBatches", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ".", "append", "(", "\"\\tPartition stores moved: \"", ")", ".", "append", "(", "partitionStoreCount", ")", ".", "append", "(", "\" out of \"", ")", ".", "append", "(", "numPartitionStores", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ".", "append", "(", "\"\\tPercent done: \"", ")", ".", "append", "(", "decimalFormatter", ".", "format", "(", "rate", "*", "100.0", ")", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ".", "append", "(", "\"\\tEstimated time left: \"", ")", ".", "append", "(", "estimatedTimeMs", ")", ".", "append", "(", "\" ms (\"", ")", ".", "append", "(", "TimeUnit", ".", "MILLISECONDS", ".", "toHours", "(", "estimatedTimeMs", ")", ")", ".", "append", "(", "\" hours)\"", ")", ";", "RebalanceUtils", ".", "printBatchLog", "(", "batchCount", ",", "logger", ",", "sb", ".", "toString", "(", ")", ")", ";", "}" ]
Pretty print a progress update after each batch complete. @param batchCount current batch @param numBatches total number of batches @param partitionStoreCount partition stores migrated @param numPartitionStores total number of partition stores to migrate @param totalTimeMs total time, in milliseconds, of execution thus far.
[ "Pretty", "print", "a", "progress", "update", "after", "each", "batch", "complete", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceController.java#L235-L270
161,121
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceController.java
RebalanceController.executeBatch
private void executeBatch(int batchId, final RebalanceBatchPlan batchPlan) { final Cluster batchCurrentCluster = batchPlan.getCurrentCluster(); final List<StoreDefinition> batchCurrentStoreDefs = batchPlan.getCurrentStoreDefs(); final Cluster batchFinalCluster = batchPlan.getFinalCluster(); final List<StoreDefinition> batchFinalStoreDefs = batchPlan.getFinalStoreDefs(); try { final List<RebalanceTaskInfo> rebalanceTaskInfoList = batchPlan.getBatchPlan(); if(rebalanceTaskInfoList.isEmpty()) { RebalanceUtils.printBatchLog(batchId, logger, "Skipping batch " + batchId + " since it is empty."); // Even though there is no rebalancing work to do, cluster // metadata must be updated so that the server is aware of the // new cluster xml. adminClient.rebalanceOps.rebalanceStateChange(batchCurrentCluster, batchFinalCluster, batchCurrentStoreDefs, batchFinalStoreDefs, rebalanceTaskInfoList, false, true, false, false, true); return; } RebalanceUtils.printBatchLog(batchId, logger, "Starting batch " + batchId + "."); // Split the store definitions List<StoreDefinition> readOnlyStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs, true); List<StoreDefinition> readWriteStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs, false); boolean hasReadOnlyStores = readOnlyStoreDefs != null && readOnlyStoreDefs.size() > 0; boolean hasReadWriteStores = readWriteStoreDefs != null && readWriteStoreDefs.size() > 0; // STEP 1 - Cluster state change boolean finishedReadOnlyPhase = false; List<RebalanceTaskInfo> filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList, readOnlyStoreDefs); rebalanceStateChange(batchId, batchCurrentCluster, batchCurrentStoreDefs, batchFinalCluster, batchFinalStoreDefs, filteredRebalancePartitionPlanList, hasReadOnlyStores, hasReadWriteStores, finishedReadOnlyPhase); // STEP 2 - Move RO data if(hasReadOnlyStores) { RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId); executeSubBatch(batchId, progressBar, batchCurrentCluster, batchCurrentStoreDefs, filteredRebalancePartitionPlanList, hasReadOnlyStores, hasReadWriteStores, finishedReadOnlyPhase); } // STEP 3 - Cluster change state finishedReadOnlyPhase = true; filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList, readWriteStoreDefs); rebalanceStateChange(batchId, batchCurrentCluster, batchCurrentStoreDefs, batchFinalCluster, batchFinalStoreDefs, filteredRebalancePartitionPlanList, hasReadOnlyStores, hasReadWriteStores, finishedReadOnlyPhase); // STEP 4 - Move RW data if(hasReadWriteStores) { proxyPause(); RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId); executeSubBatch(batchId, progressBar, batchCurrentCluster, batchCurrentStoreDefs, filteredRebalancePartitionPlanList, hasReadOnlyStores, hasReadWriteStores, finishedReadOnlyPhase); } RebalanceUtils.printBatchLog(batchId, logger, "Successfully terminated batch " + batchId + "."); } catch(Exception e) { RebalanceUtils.printErrorLog(batchId, logger, "Error in batch " + batchId + " - " + e.getMessage(), e); throw new VoldemortException("Rebalance failed on batch " + batchId, e); } }
java
private void executeBatch(int batchId, final RebalanceBatchPlan batchPlan) { final Cluster batchCurrentCluster = batchPlan.getCurrentCluster(); final List<StoreDefinition> batchCurrentStoreDefs = batchPlan.getCurrentStoreDefs(); final Cluster batchFinalCluster = batchPlan.getFinalCluster(); final List<StoreDefinition> batchFinalStoreDefs = batchPlan.getFinalStoreDefs(); try { final List<RebalanceTaskInfo> rebalanceTaskInfoList = batchPlan.getBatchPlan(); if(rebalanceTaskInfoList.isEmpty()) { RebalanceUtils.printBatchLog(batchId, logger, "Skipping batch " + batchId + " since it is empty."); // Even though there is no rebalancing work to do, cluster // metadata must be updated so that the server is aware of the // new cluster xml. adminClient.rebalanceOps.rebalanceStateChange(batchCurrentCluster, batchFinalCluster, batchCurrentStoreDefs, batchFinalStoreDefs, rebalanceTaskInfoList, false, true, false, false, true); return; } RebalanceUtils.printBatchLog(batchId, logger, "Starting batch " + batchId + "."); // Split the store definitions List<StoreDefinition> readOnlyStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs, true); List<StoreDefinition> readWriteStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs, false); boolean hasReadOnlyStores = readOnlyStoreDefs != null && readOnlyStoreDefs.size() > 0; boolean hasReadWriteStores = readWriteStoreDefs != null && readWriteStoreDefs.size() > 0; // STEP 1 - Cluster state change boolean finishedReadOnlyPhase = false; List<RebalanceTaskInfo> filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList, readOnlyStoreDefs); rebalanceStateChange(batchId, batchCurrentCluster, batchCurrentStoreDefs, batchFinalCluster, batchFinalStoreDefs, filteredRebalancePartitionPlanList, hasReadOnlyStores, hasReadWriteStores, finishedReadOnlyPhase); // STEP 2 - Move RO data if(hasReadOnlyStores) { RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId); executeSubBatch(batchId, progressBar, batchCurrentCluster, batchCurrentStoreDefs, filteredRebalancePartitionPlanList, hasReadOnlyStores, hasReadWriteStores, finishedReadOnlyPhase); } // STEP 3 - Cluster change state finishedReadOnlyPhase = true; filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList, readWriteStoreDefs); rebalanceStateChange(batchId, batchCurrentCluster, batchCurrentStoreDefs, batchFinalCluster, batchFinalStoreDefs, filteredRebalancePartitionPlanList, hasReadOnlyStores, hasReadWriteStores, finishedReadOnlyPhase); // STEP 4 - Move RW data if(hasReadWriteStores) { proxyPause(); RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId); executeSubBatch(batchId, progressBar, batchCurrentCluster, batchCurrentStoreDefs, filteredRebalancePartitionPlanList, hasReadOnlyStores, hasReadWriteStores, finishedReadOnlyPhase); } RebalanceUtils.printBatchLog(batchId, logger, "Successfully terminated batch " + batchId + "."); } catch(Exception e) { RebalanceUtils.printErrorLog(batchId, logger, "Error in batch " + batchId + " - " + e.getMessage(), e); throw new VoldemortException("Rebalance failed on batch " + batchId, e); } }
[ "private", "void", "executeBatch", "(", "int", "batchId", ",", "final", "RebalanceBatchPlan", "batchPlan", ")", "{", "final", "Cluster", "batchCurrentCluster", "=", "batchPlan", ".", "getCurrentCluster", "(", ")", ";", "final", "List", "<", "StoreDefinition", ">", "batchCurrentStoreDefs", "=", "batchPlan", ".", "getCurrentStoreDefs", "(", ")", ";", "final", "Cluster", "batchFinalCluster", "=", "batchPlan", ".", "getFinalCluster", "(", ")", ";", "final", "List", "<", "StoreDefinition", ">", "batchFinalStoreDefs", "=", "batchPlan", ".", "getFinalStoreDefs", "(", ")", ";", "try", "{", "final", "List", "<", "RebalanceTaskInfo", ">", "rebalanceTaskInfoList", "=", "batchPlan", ".", "getBatchPlan", "(", ")", ";", "if", "(", "rebalanceTaskInfoList", ".", "isEmpty", "(", ")", ")", "{", "RebalanceUtils", ".", "printBatchLog", "(", "batchId", ",", "logger", ",", "\"Skipping batch \"", "+", "batchId", "+", "\" since it is empty.\"", ")", ";", "// Even though there is no rebalancing work to do, cluster", "// metadata must be updated so that the server is aware of the", "// new cluster xml.", "adminClient", ".", "rebalanceOps", ".", "rebalanceStateChange", "(", "batchCurrentCluster", ",", "batchFinalCluster", ",", "batchCurrentStoreDefs", ",", "batchFinalStoreDefs", ",", "rebalanceTaskInfoList", ",", "false", ",", "true", ",", "false", ",", "false", ",", "true", ")", ";", "return", ";", "}", "RebalanceUtils", ".", "printBatchLog", "(", "batchId", ",", "logger", ",", "\"Starting batch \"", "+", "batchId", "+", "\".\"", ")", ";", "// Split the store definitions", "List", "<", "StoreDefinition", ">", "readOnlyStoreDefs", "=", "StoreDefinitionUtils", ".", "filterStores", "(", "batchFinalStoreDefs", ",", "true", ")", ";", "List", "<", "StoreDefinition", ">", "readWriteStoreDefs", "=", "StoreDefinitionUtils", ".", "filterStores", "(", "batchFinalStoreDefs", ",", "false", ")", ";", "boolean", "hasReadOnlyStores", "=", "readOnlyStoreDefs", "!=", "null", "&&", "readOnlyStoreDefs", ".", "size", "(", ")", ">", "0", ";", "boolean", "hasReadWriteStores", "=", "readWriteStoreDefs", "!=", "null", "&&", "readWriteStoreDefs", ".", "size", "(", ")", ">", "0", ";", "// STEP 1 - Cluster state change", "boolean", "finishedReadOnlyPhase", "=", "false", ";", "List", "<", "RebalanceTaskInfo", ">", "filteredRebalancePartitionPlanList", "=", "RebalanceUtils", ".", "filterTaskPlanWithStores", "(", "rebalanceTaskInfoList", ",", "readOnlyStoreDefs", ")", ";", "rebalanceStateChange", "(", "batchId", ",", "batchCurrentCluster", ",", "batchCurrentStoreDefs", ",", "batchFinalCluster", ",", "batchFinalStoreDefs", ",", "filteredRebalancePartitionPlanList", ",", "hasReadOnlyStores", ",", "hasReadWriteStores", ",", "finishedReadOnlyPhase", ")", ";", "// STEP 2 - Move RO data", "if", "(", "hasReadOnlyStores", ")", "{", "RebalanceBatchPlanProgressBar", "progressBar", "=", "batchPlan", ".", "getProgressBar", "(", "batchId", ")", ";", "executeSubBatch", "(", "batchId", ",", "progressBar", ",", "batchCurrentCluster", ",", "batchCurrentStoreDefs", ",", "filteredRebalancePartitionPlanList", ",", "hasReadOnlyStores", ",", "hasReadWriteStores", ",", "finishedReadOnlyPhase", ")", ";", "}", "// STEP 3 - Cluster change state", "finishedReadOnlyPhase", "=", "true", ";", "filteredRebalancePartitionPlanList", "=", "RebalanceUtils", ".", "filterTaskPlanWithStores", "(", "rebalanceTaskInfoList", ",", "readWriteStoreDefs", ")", ";", "rebalanceStateChange", "(", "batchId", ",", "batchCurrentCluster", ",", "batchCurrentStoreDefs", ",", "batchFinalCluster", ",", "batchFinalStoreDefs", ",", "filteredRebalancePartitionPlanList", ",", "hasReadOnlyStores", ",", "hasReadWriteStores", ",", "finishedReadOnlyPhase", ")", ";", "// STEP 4 - Move RW data", "if", "(", "hasReadWriteStores", ")", "{", "proxyPause", "(", ")", ";", "RebalanceBatchPlanProgressBar", "progressBar", "=", "batchPlan", ".", "getProgressBar", "(", "batchId", ")", ";", "executeSubBatch", "(", "batchId", ",", "progressBar", ",", "batchCurrentCluster", ",", "batchCurrentStoreDefs", ",", "filteredRebalancePartitionPlanList", ",", "hasReadOnlyStores", ",", "hasReadWriteStores", ",", "finishedReadOnlyPhase", ")", ";", "}", "RebalanceUtils", ".", "printBatchLog", "(", "batchId", ",", "logger", ",", "\"Successfully terminated batch \"", "+", "batchId", "+", "\".\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "RebalanceUtils", ".", "printErrorLog", "(", "batchId", ",", "logger", ",", "\"Error in batch \"", "+", "batchId", "+", "\" - \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "throw", "new", "VoldemortException", "(", "\"Rebalance failed on batch \"", "+", "batchId", ",", "e", ")", ";", "}", "}" ]
Executes a batch plan. @param batchId Used as the ID of the batch plan. This allows related tasks on client- & server-side to pretty print messages in a manner that debugging can track specific batch plans across the cluster. @param batchPlan The batch plan...
[ "Executes", "a", "batch", "plan", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceController.java#L281-L390
161,122
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceController.java
RebalanceController.proxyPause
private void proxyPause() { logger.info("Pausing after cluster state has changed to allow proxy bridges to be established. " + "Will start rebalancing work on servers in " + proxyPauseSec + " seconds."); try { Thread.sleep(TimeUnit.SECONDS.toMillis(proxyPauseSec)); } catch(InterruptedException e) { logger.warn("Sleep interrupted in proxy pause."); } }
java
private void proxyPause() { logger.info("Pausing after cluster state has changed to allow proxy bridges to be established. " + "Will start rebalancing work on servers in " + proxyPauseSec + " seconds."); try { Thread.sleep(TimeUnit.SECONDS.toMillis(proxyPauseSec)); } catch(InterruptedException e) { logger.warn("Sleep interrupted in proxy pause."); } }
[ "private", "void", "proxyPause", "(", ")", "{", "logger", ".", "info", "(", "\"Pausing after cluster state has changed to allow proxy bridges to be established. \"", "+", "\"Will start rebalancing work on servers in \"", "+", "proxyPauseSec", "+", "\" seconds.\"", ")", ";", "try", "{", "Thread", ".", "sleep", "(", "TimeUnit", ".", "SECONDS", ".", "toMillis", "(", "proxyPauseSec", ")", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "logger", ".", "warn", "(", "\"Sleep interrupted in proxy pause.\"", ")", ";", "}", "}" ]
Pause between cluster change in metadata and starting server rebalancing work.
[ "Pause", "between", "cluster", "change", "in", "metadata", "and", "starting", "server", "rebalancing", "work", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceController.java#L396-L406
161,123
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceController.java
RebalanceController.executeSubBatch
private void executeSubBatch(final int batchId, RebalanceBatchPlanProgressBar progressBar, final Cluster batchRollbackCluster, final List<StoreDefinition> batchRollbackStoreDefs, final List<RebalanceTaskInfo> rebalanceTaskPlanList, boolean hasReadOnlyStores, boolean hasReadWriteStores, boolean finishedReadOnlyStores) { RebalanceUtils.printBatchLog(batchId, logger, "Submitting rebalance tasks "); // Get an ExecutorService in place used for submitting our tasks ExecutorService service = RebalanceUtils.createExecutors(maxParallelRebalancing); // Sub-list of the above list final List<RebalanceTask> failedTasks = Lists.newArrayList(); final List<RebalanceTask> incompleteTasks = Lists.newArrayList(); // Semaphores for donor nodes - To avoid multiple disk sweeps Map<Integer, Semaphore> donorPermits = new HashMap<Integer, Semaphore>(); for(Node node: batchRollbackCluster.getNodes()) { donorPermits.put(node.getId(), new Semaphore(1)); } try { // List of tasks which will run asynchronously List<RebalanceTask> allTasks = executeTasks(batchId, progressBar, service, rebalanceTaskPlanList, donorPermits); RebalanceUtils.printBatchLog(batchId, logger, "All rebalance tasks submitted"); // Wait and shutdown after (infinite) timeout RebalanceUtils.executorShutDown(service, Long.MAX_VALUE); RebalanceUtils.printBatchLog(batchId, logger, "Finished waiting for executors"); // Collects all failures + incomplete tasks from the rebalance // tasks. List<Exception> failures = Lists.newArrayList(); for(RebalanceTask task: allTasks) { if(task.hasException()) { failedTasks.add(task); failures.add(task.getError()); } else if(!task.isComplete()) { incompleteTasks.add(task); } } if(failedTasks.size() > 0) { throw new VoldemortRebalancingException("Rebalance task terminated unsuccessfully on tasks " + failedTasks, failures); } // If there were no failures, then we could have had a genuine // timeout ( Rebalancing took longer than the operator expected ). // We should throw a VoldemortException and not a // VoldemortRebalancingException ( which will start reverting // metadata ). The operator may want to manually then resume the // process. if(incompleteTasks.size() > 0) { throw new VoldemortException("Rebalance tasks are still incomplete / running " + incompleteTasks); } } catch(VoldemortRebalancingException e) { logger.error("Failure while migrating partitions for rebalance task " + batchId); if(hasReadOnlyStores && hasReadWriteStores && finishedReadOnlyStores) { // Case 0 adminClient.rebalanceOps.rebalanceStateChange(null, batchRollbackCluster, null, batchRollbackStoreDefs, null, true, true, false, false, false); } else if(hasReadWriteStores && finishedReadOnlyStores) { // Case 4 adminClient.rebalanceOps.rebalanceStateChange(null, batchRollbackCluster, null, batchRollbackStoreDefs, null, false, true, false, false, false); } throw e; } finally { if(!service.isShutdown()) { RebalanceUtils.printErrorLog(batchId, logger, "Could not shutdown service cleanly for rebalance task " + batchId, null); service.shutdownNow(); } } }
java
private void executeSubBatch(final int batchId, RebalanceBatchPlanProgressBar progressBar, final Cluster batchRollbackCluster, final List<StoreDefinition> batchRollbackStoreDefs, final List<RebalanceTaskInfo> rebalanceTaskPlanList, boolean hasReadOnlyStores, boolean hasReadWriteStores, boolean finishedReadOnlyStores) { RebalanceUtils.printBatchLog(batchId, logger, "Submitting rebalance tasks "); // Get an ExecutorService in place used for submitting our tasks ExecutorService service = RebalanceUtils.createExecutors(maxParallelRebalancing); // Sub-list of the above list final List<RebalanceTask> failedTasks = Lists.newArrayList(); final List<RebalanceTask> incompleteTasks = Lists.newArrayList(); // Semaphores for donor nodes - To avoid multiple disk sweeps Map<Integer, Semaphore> donorPermits = new HashMap<Integer, Semaphore>(); for(Node node: batchRollbackCluster.getNodes()) { donorPermits.put(node.getId(), new Semaphore(1)); } try { // List of tasks which will run asynchronously List<RebalanceTask> allTasks = executeTasks(batchId, progressBar, service, rebalanceTaskPlanList, donorPermits); RebalanceUtils.printBatchLog(batchId, logger, "All rebalance tasks submitted"); // Wait and shutdown after (infinite) timeout RebalanceUtils.executorShutDown(service, Long.MAX_VALUE); RebalanceUtils.printBatchLog(batchId, logger, "Finished waiting for executors"); // Collects all failures + incomplete tasks from the rebalance // tasks. List<Exception> failures = Lists.newArrayList(); for(RebalanceTask task: allTasks) { if(task.hasException()) { failedTasks.add(task); failures.add(task.getError()); } else if(!task.isComplete()) { incompleteTasks.add(task); } } if(failedTasks.size() > 0) { throw new VoldemortRebalancingException("Rebalance task terminated unsuccessfully on tasks " + failedTasks, failures); } // If there were no failures, then we could have had a genuine // timeout ( Rebalancing took longer than the operator expected ). // We should throw a VoldemortException and not a // VoldemortRebalancingException ( which will start reverting // metadata ). The operator may want to manually then resume the // process. if(incompleteTasks.size() > 0) { throw new VoldemortException("Rebalance tasks are still incomplete / running " + incompleteTasks); } } catch(VoldemortRebalancingException e) { logger.error("Failure while migrating partitions for rebalance task " + batchId); if(hasReadOnlyStores && hasReadWriteStores && finishedReadOnlyStores) { // Case 0 adminClient.rebalanceOps.rebalanceStateChange(null, batchRollbackCluster, null, batchRollbackStoreDefs, null, true, true, false, false, false); } else if(hasReadWriteStores && finishedReadOnlyStores) { // Case 4 adminClient.rebalanceOps.rebalanceStateChange(null, batchRollbackCluster, null, batchRollbackStoreDefs, null, false, true, false, false, false); } throw e; } finally { if(!service.isShutdown()) { RebalanceUtils.printErrorLog(batchId, logger, "Could not shutdown service cleanly for rebalance task " + batchId, null); service.shutdownNow(); } } }
[ "private", "void", "executeSubBatch", "(", "final", "int", "batchId", ",", "RebalanceBatchPlanProgressBar", "progressBar", ",", "final", "Cluster", "batchRollbackCluster", ",", "final", "List", "<", "StoreDefinition", ">", "batchRollbackStoreDefs", ",", "final", "List", "<", "RebalanceTaskInfo", ">", "rebalanceTaskPlanList", ",", "boolean", "hasReadOnlyStores", ",", "boolean", "hasReadWriteStores", ",", "boolean", "finishedReadOnlyStores", ")", "{", "RebalanceUtils", ".", "printBatchLog", "(", "batchId", ",", "logger", ",", "\"Submitting rebalance tasks \"", ")", ";", "// Get an ExecutorService in place used for submitting our tasks", "ExecutorService", "service", "=", "RebalanceUtils", ".", "createExecutors", "(", "maxParallelRebalancing", ")", ";", "// Sub-list of the above list", "final", "List", "<", "RebalanceTask", ">", "failedTasks", "=", "Lists", ".", "newArrayList", "(", ")", ";", "final", "List", "<", "RebalanceTask", ">", "incompleteTasks", "=", "Lists", ".", "newArrayList", "(", ")", ";", "// Semaphores for donor nodes - To avoid multiple disk sweeps", "Map", "<", "Integer", ",", "Semaphore", ">", "donorPermits", "=", "new", "HashMap", "<", "Integer", ",", "Semaphore", ">", "(", ")", ";", "for", "(", "Node", "node", ":", "batchRollbackCluster", ".", "getNodes", "(", ")", ")", "{", "donorPermits", ".", "put", "(", "node", ".", "getId", "(", ")", ",", "new", "Semaphore", "(", "1", ")", ")", ";", "}", "try", "{", "// List of tasks which will run asynchronously", "List", "<", "RebalanceTask", ">", "allTasks", "=", "executeTasks", "(", "batchId", ",", "progressBar", ",", "service", ",", "rebalanceTaskPlanList", ",", "donorPermits", ")", ";", "RebalanceUtils", ".", "printBatchLog", "(", "batchId", ",", "logger", ",", "\"All rebalance tasks submitted\"", ")", ";", "// Wait and shutdown after (infinite) timeout", "RebalanceUtils", ".", "executorShutDown", "(", "service", ",", "Long", ".", "MAX_VALUE", ")", ";", "RebalanceUtils", ".", "printBatchLog", "(", "batchId", ",", "logger", ",", "\"Finished waiting for executors\"", ")", ";", "// Collects all failures + incomplete tasks from the rebalance", "// tasks.", "List", "<", "Exception", ">", "failures", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "RebalanceTask", "task", ":", "allTasks", ")", "{", "if", "(", "task", ".", "hasException", "(", ")", ")", "{", "failedTasks", ".", "add", "(", "task", ")", ";", "failures", ".", "add", "(", "task", ".", "getError", "(", ")", ")", ";", "}", "else", "if", "(", "!", "task", ".", "isComplete", "(", ")", ")", "{", "incompleteTasks", ".", "add", "(", "task", ")", ";", "}", "}", "if", "(", "failedTasks", ".", "size", "(", ")", ">", "0", ")", "{", "throw", "new", "VoldemortRebalancingException", "(", "\"Rebalance task terminated unsuccessfully on tasks \"", "+", "failedTasks", ",", "failures", ")", ";", "}", "// If there were no failures, then we could have had a genuine", "// timeout ( Rebalancing took longer than the operator expected ).", "// We should throw a VoldemortException and not a", "// VoldemortRebalancingException ( which will start reverting", "// metadata ). The operator may want to manually then resume the", "// process.", "if", "(", "incompleteTasks", ".", "size", "(", ")", ">", "0", ")", "{", "throw", "new", "VoldemortException", "(", "\"Rebalance tasks are still incomplete / running \"", "+", "incompleteTasks", ")", ";", "}", "}", "catch", "(", "VoldemortRebalancingException", "e", ")", "{", "logger", ".", "error", "(", "\"Failure while migrating partitions for rebalance task \"", "+", "batchId", ")", ";", "if", "(", "hasReadOnlyStores", "&&", "hasReadWriteStores", "&&", "finishedReadOnlyStores", ")", "{", "// Case 0", "adminClient", ".", "rebalanceOps", ".", "rebalanceStateChange", "(", "null", ",", "batchRollbackCluster", ",", "null", ",", "batchRollbackStoreDefs", ",", "null", ",", "true", ",", "true", ",", "false", ",", "false", ",", "false", ")", ";", "}", "else", "if", "(", "hasReadWriteStores", "&&", "finishedReadOnlyStores", ")", "{", "// Case 4", "adminClient", ".", "rebalanceOps", ".", "rebalanceStateChange", "(", "null", ",", "batchRollbackCluster", ",", "null", ",", "batchRollbackStoreDefs", ",", "null", ",", "false", ",", "true", ",", "false", ",", "false", ",", "false", ")", ";", "}", "throw", "e", ";", "}", "finally", "{", "if", "(", "!", "service", ".", "isShutdown", "(", ")", ")", "{", "RebalanceUtils", ".", "printErrorLog", "(", "batchId", ",", "logger", ",", "\"Could not shutdown service cleanly for rebalance task \"", "+", "batchId", ",", "null", ")", ";", "service", ".", "shutdownNow", "(", ")", ";", "}", "}", "}" ]
The smallest granularity of rebalancing where-in we move partitions for a sub-set of stores. Finally at the end of the movement, the node is removed out of rebalance state <br> Also any errors + rollback procedures are performed at this level itself. <pre> | Case | hasRO | hasRW | finishedRO | Action | | 0 | t | t | t | rollback cluster change + swap | | 1 | t | t | f | nothing to do since "rebalance state change" should have removed everything | | 2 | t | f | t | won't be triggered since hasRW is false | | 3 | t | f | f | nothing to do since "rebalance state change" should have removed everything | | 4 | f | t | t | rollback cluster change | | 5 | f | t | f | won't be triggered | | 6 | f | f | t | won't be triggered | | 7 | f | f | f | won't be triggered | </pre> @param batchId Rebalance batch id @param batchRollbackCluster Cluster to rollback to if we have a problem @param rebalanceTaskPlanList The list of rebalance partition plans @param hasReadOnlyStores Are we rebalancing any read-only stores? @param hasReadWriteStores Are we rebalancing any read-write stores? @param finishedReadOnlyStores Have we finished rebalancing of read-only stores?
[ "The", "smallest", "granularity", "of", "rebalancing", "where", "-", "in", "we", "move", "partitions", "for", "a", "sub", "-", "set", "of", "stores", ".", "Finally", "at", "the", "end", "of", "the", "movement", "the", "node", "is", "removed", "out", "of", "rebalance", "state" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceController.java#L563-L679
161,124
voldemort/voldemort
src/java/voldemort/utils/ConsistencyCheck.java
ConsistencyCheck.determineConsistency
public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap, int replicationFactor) { boolean fullyConsistent = true; Value latestVersion = null; for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) { Value value = versionNodeSetEntry.getKey(); if (latestVersion == null) { latestVersion = value; } else if (value.isTimeStampLaterThan(latestVersion)) { latestVersion = value; } Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue(); fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor); } if (fullyConsistent) { return ConsistencyLevel.FULL; } else { // latest write consistent, effectively consistent if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) { return ConsistencyLevel.LATEST_CONSISTENT; } // all other states inconsistent return ConsistencyLevel.INCONSISTENT; } }
java
public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap, int replicationFactor) { boolean fullyConsistent = true; Value latestVersion = null; for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) { Value value = versionNodeSetEntry.getKey(); if (latestVersion == null) { latestVersion = value; } else if (value.isTimeStampLaterThan(latestVersion)) { latestVersion = value; } Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue(); fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor); } if (fullyConsistent) { return ConsistencyLevel.FULL; } else { // latest write consistent, effectively consistent if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) { return ConsistencyLevel.LATEST_CONSISTENT; } // all other states inconsistent return ConsistencyLevel.INCONSISTENT; } }
[ "public", "static", "ConsistencyLevel", "determineConsistency", "(", "Map", "<", "Value", ",", "Set", "<", "ClusterNode", ">", ">", "versionNodeSetMap", ",", "int", "replicationFactor", ")", "{", "boolean", "fullyConsistent", "=", "true", ";", "Value", "latestVersion", "=", "null", ";", "for", "(", "Map", ".", "Entry", "<", "Value", ",", "Set", "<", "ClusterNode", ">", ">", "versionNodeSetEntry", ":", "versionNodeSetMap", ".", "entrySet", "(", ")", ")", "{", "Value", "value", "=", "versionNodeSetEntry", ".", "getKey", "(", ")", ";", "if", "(", "latestVersion", "==", "null", ")", "{", "latestVersion", "=", "value", ";", "}", "else", "if", "(", "value", ".", "isTimeStampLaterThan", "(", "latestVersion", ")", ")", "{", "latestVersion", "=", "value", ";", "}", "Set", "<", "ClusterNode", ">", "nodeSet", "=", "versionNodeSetEntry", ".", "getValue", "(", ")", ";", "fullyConsistent", "=", "fullyConsistent", "&&", "(", "nodeSet", ".", "size", "(", ")", "==", "replicationFactor", ")", ";", "}", "if", "(", "fullyConsistent", ")", "{", "return", "ConsistencyLevel", ".", "FULL", ";", "}", "else", "{", "// latest write consistent, effectively consistent", "if", "(", "latestVersion", "!=", "null", "&&", "versionNodeSetMap", ".", "get", "(", "latestVersion", ")", ".", "size", "(", ")", "==", "replicationFactor", ")", "{", "return", "ConsistencyLevel", ".", "LATEST_CONSISTENT", ";", "}", "// all other states inconsistent", "return", "ConsistencyLevel", ".", "INCONSISTENT", ";", "}", "}" ]
Determine the consistency level of a key @param versionNodeSetMap A map that maps version to set of PrefixNodes @param replicationFactor Total replication factor for the set of clusters @return ConsistencyLevel Enum
[ "Determine", "the", "consistency", "level", "of", "a", "key" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ConsistencyCheck.java#L654-L678
161,125
voldemort/voldemort
src/java/voldemort/utils/ConsistencyCheck.java
ConsistencyCheck.cleanIneligibleKeys
public static void cleanIneligibleKeys(Map<ByteArray, Map<Value, Set<ClusterNode>>> keyVersionNodeSetMap, int requiredWrite) { Set<ByteArray> keysToDelete = new HashSet<ByteArray>(); for (Map.Entry<ByteArray, Map<Value, Set<ClusterNode>>> entry : keyVersionNodeSetMap.entrySet()) { Set<Value> valuesToDelete = new HashSet<Value>(); ByteArray key = entry.getKey(); Map<Value, Set<ClusterNode>> valueNodeSetMap = entry.getValue(); // mark version for deletion if not enough writes for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : valueNodeSetMap.entrySet()) { Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue(); if (nodeSet.size() < requiredWrite) { valuesToDelete.add(versionNodeSetEntry.getKey()); } } // delete versions for (Value v : valuesToDelete) { valueNodeSetMap.remove(v); } // mark key for deletion if no versions left if (valueNodeSetMap.size() == 0) { keysToDelete.add(key); } } // delete keys for (ByteArray k : keysToDelete) { keyVersionNodeSetMap.remove(k); } }
java
public static void cleanIneligibleKeys(Map<ByteArray, Map<Value, Set<ClusterNode>>> keyVersionNodeSetMap, int requiredWrite) { Set<ByteArray> keysToDelete = new HashSet<ByteArray>(); for (Map.Entry<ByteArray, Map<Value, Set<ClusterNode>>> entry : keyVersionNodeSetMap.entrySet()) { Set<Value> valuesToDelete = new HashSet<Value>(); ByteArray key = entry.getKey(); Map<Value, Set<ClusterNode>> valueNodeSetMap = entry.getValue(); // mark version for deletion if not enough writes for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : valueNodeSetMap.entrySet()) { Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue(); if (nodeSet.size() < requiredWrite) { valuesToDelete.add(versionNodeSetEntry.getKey()); } } // delete versions for (Value v : valuesToDelete) { valueNodeSetMap.remove(v); } // mark key for deletion if no versions left if (valueNodeSetMap.size() == 0) { keysToDelete.add(key); } } // delete keys for (ByteArray k : keysToDelete) { keyVersionNodeSetMap.remove(k); } }
[ "public", "static", "void", "cleanIneligibleKeys", "(", "Map", "<", "ByteArray", ",", "Map", "<", "Value", ",", "Set", "<", "ClusterNode", ">", ">", ">", "keyVersionNodeSetMap", ",", "int", "requiredWrite", ")", "{", "Set", "<", "ByteArray", ">", "keysToDelete", "=", "new", "HashSet", "<", "ByteArray", ">", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "ByteArray", ",", "Map", "<", "Value", ",", "Set", "<", "ClusterNode", ">", ">", ">", "entry", ":", "keyVersionNodeSetMap", ".", "entrySet", "(", ")", ")", "{", "Set", "<", "Value", ">", "valuesToDelete", "=", "new", "HashSet", "<", "Value", ">", "(", ")", ";", "ByteArray", "key", "=", "entry", ".", "getKey", "(", ")", ";", "Map", "<", "Value", ",", "Set", "<", "ClusterNode", ">", ">", "valueNodeSetMap", "=", "entry", ".", "getValue", "(", ")", ";", "// mark version for deletion if not enough writes", "for", "(", "Map", ".", "Entry", "<", "Value", ",", "Set", "<", "ClusterNode", ">", ">", "versionNodeSetEntry", ":", "valueNodeSetMap", ".", "entrySet", "(", ")", ")", "{", "Set", "<", "ClusterNode", ">", "nodeSet", "=", "versionNodeSetEntry", ".", "getValue", "(", ")", ";", "if", "(", "nodeSet", ".", "size", "(", ")", "<", "requiredWrite", ")", "{", "valuesToDelete", ".", "add", "(", "versionNodeSetEntry", ".", "getKey", "(", ")", ")", ";", "}", "}", "// delete versions", "for", "(", "Value", "v", ":", "valuesToDelete", ")", "{", "valueNodeSetMap", ".", "remove", "(", "v", ")", ";", "}", "// mark key for deletion if no versions left", "if", "(", "valueNodeSetMap", ".", "size", "(", ")", "==", "0", ")", "{", "keysToDelete", ".", "add", "(", "key", ")", ";", "}", "}", "// delete keys", "for", "(", "ByteArray", "k", ":", "keysToDelete", ")", "{", "keyVersionNodeSetMap", ".", "remove", "(", "k", ")", ";", "}", "}" ]
Determine if a key version is invalid by comparing the version's existence and required writes configuration @param keyVersionNodeSetMap A map that contains keys mapping to a map that maps versions to set of PrefixNodes @param requiredWrite Required Write configuration
[ "Determine", "if", "a", "key", "version", "is", "invalid", "by", "comparing", "the", "version", "s", "existence", "and", "required", "writes", "configuration" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ConsistencyCheck.java#L689-L717
161,126
voldemort/voldemort
src/java/voldemort/utils/ConsistencyCheck.java
ConsistencyCheck.keyVersionToString
public static String keyVersionToString(ByteArray key, Map<Value, Set<ClusterNode>> versionMap, String storeName, Integer partitionId) { StringBuilder record = new StringBuilder(); for (Map.Entry<Value, Set<ClusterNode>> versionSet : versionMap.entrySet()) { Value value = versionSet.getKey(); Set<ClusterNode> nodeSet = versionSet.getValue(); record.append("BAD_KEY,"); record.append(storeName + ","); record.append(partitionId + ","); record.append(ByteUtils.toHexString(key.get()) + ","); record.append(nodeSet.toString().replace(", ", ";") + ","); record.append(value.toString()); } return record.toString(); }
java
public static String keyVersionToString(ByteArray key, Map<Value, Set<ClusterNode>> versionMap, String storeName, Integer partitionId) { StringBuilder record = new StringBuilder(); for (Map.Entry<Value, Set<ClusterNode>> versionSet : versionMap.entrySet()) { Value value = versionSet.getKey(); Set<ClusterNode> nodeSet = versionSet.getValue(); record.append("BAD_KEY,"); record.append(storeName + ","); record.append(partitionId + ","); record.append(ByteUtils.toHexString(key.get()) + ","); record.append(nodeSet.toString().replace(", ", ";") + ","); record.append(value.toString()); } return record.toString(); }
[ "public", "static", "String", "keyVersionToString", "(", "ByteArray", "key", ",", "Map", "<", "Value", ",", "Set", "<", "ClusterNode", ">", ">", "versionMap", ",", "String", "storeName", ",", "Integer", "partitionId", ")", "{", "StringBuilder", "record", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "Value", ",", "Set", "<", "ClusterNode", ">", ">", "versionSet", ":", "versionMap", ".", "entrySet", "(", ")", ")", "{", "Value", "value", "=", "versionSet", ".", "getKey", "(", ")", ";", "Set", "<", "ClusterNode", ">", "nodeSet", "=", "versionSet", ".", "getValue", "(", ")", ";", "record", ".", "append", "(", "\"BAD_KEY,\"", ")", ";", "record", ".", "append", "(", "storeName", "+", "\",\"", ")", ";", "record", ".", "append", "(", "partitionId", "+", "\",\"", ")", ";", "record", ".", "append", "(", "ByteUtils", ".", "toHexString", "(", "key", ".", "get", "(", ")", ")", "+", "\",\"", ")", ";", "record", ".", "append", "(", "nodeSet", ".", "toString", "(", ")", ".", "replace", "(", "\", \"", ",", "\";\"", ")", "+", "\",\"", ")", ";", "record", ".", "append", "(", "value", ".", "toString", "(", ")", ")", ";", "}", "return", "record", ".", "toString", "(", ")", ";", "}" ]
Convert a key-version-nodeSet information to string @param key The key @param versionMap mapping versions to set of PrefixNodes @param storeName store's name @param partitionId partition scanned @return a string that describe the information passed in
[ "Convert", "a", "key", "-", "version", "-", "nodeSet", "information", "to", "string" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ConsistencyCheck.java#L815-L832
161,127
voldemort/voldemort
src/java/voldemort/rest/GetMetadataResponseSender.java
GetMetadataResponseSender.sendResponse
@Override public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception { ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(this.responseValue.length); responseContent.writeBytes(responseValue); // 1. Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // 2. Set the right headers response.setHeader(CONTENT_TYPE, "binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); // 3. Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); if(logger.isDebugEnabled()) { logger.debug("Response = " + response); } // Write the response to the Netty Channel this.messageEvent.getChannel().write(response); if(performanceStats != null && isFromLocalZone) { recordStats(performanceStats, startTimeInMs, Tracked.GET); } }
java
@Override public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception { ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(this.responseValue.length); responseContent.writeBytes(responseValue); // 1. Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // 2. Set the right headers response.setHeader(CONTENT_TYPE, "binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); // 3. Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); if(logger.isDebugEnabled()) { logger.debug("Response = " + response); } // Write the response to the Netty Channel this.messageEvent.getChannel().write(response); if(performanceStats != null && isFromLocalZone) { recordStats(performanceStats, startTimeInMs, Tracked.GET); } }
[ "@", "Override", "public", "void", "sendResponse", "(", "StoreStats", "performanceStats", ",", "boolean", "isFromLocalZone", ",", "long", "startTimeInMs", ")", "throws", "Exception", "{", "ChannelBuffer", "responseContent", "=", "ChannelBuffers", ".", "dynamicBuffer", "(", "this", ".", "responseValue", ".", "length", ")", ";", "responseContent", ".", "writeBytes", "(", "responseValue", ")", ";", "// 1. Create the Response object", "HttpResponse", "response", "=", "new", "DefaultHttpResponse", "(", "HTTP_1_1", ",", "OK", ")", ";", "// 2. Set the right headers", "response", ".", "setHeader", "(", "CONTENT_TYPE", ",", "\"binary\"", ")", ";", "response", ".", "setHeader", "(", "CONTENT_TRANSFER_ENCODING", ",", "\"binary\"", ")", ";", "// 3. Copy the data into the payload", "response", ".", "setContent", "(", "responseContent", ")", ";", "response", ".", "setHeader", "(", "CONTENT_LENGTH", ",", "response", ".", "getContent", "(", ")", ".", "readableBytes", "(", ")", ")", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Response = \"", "+", "response", ")", ";", "}", "// Write the response to the Netty Channel", "this", ".", "messageEvent", ".", "getChannel", "(", ")", ".", "write", "(", "response", ")", ";", "if", "(", "performanceStats", "!=", "null", "&&", "isFromLocalZone", ")", "{", "recordStats", "(", "performanceStats", ",", "startTimeInMs", ",", "Tracked", ".", "GET", ")", ";", "}", "}" ]
Sends a normal HTTP response containing the serialization information in a XML format
[ "Sends", "a", "normal", "HTTP", "response", "containing", "the", "serialization", "information", "in", "a", "XML", "format" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/GetMetadataResponseSender.java#L33-L62
161,128
voldemort/voldemort
src/java/voldemort/cluster/failuredetector/FailureDetectorConfig.java
FailureDetectorConfig.setCluster
public FailureDetectorConfig setCluster(Cluster cluster) { Utils.notNull(cluster); this.cluster = cluster; /* * FIXME: this is the hacky way to refresh the admin connection * verifier, but it'll just work. The clean way to do so is to have a * centralized metadata management, and all references of cluster object * point to that. */ if(this.connectionVerifier instanceof AdminConnectionVerifier) { ((AdminConnectionVerifier) connectionVerifier).setCluster(cluster); } return this; }
java
public FailureDetectorConfig setCluster(Cluster cluster) { Utils.notNull(cluster); this.cluster = cluster; /* * FIXME: this is the hacky way to refresh the admin connection * verifier, but it'll just work. The clean way to do so is to have a * centralized metadata management, and all references of cluster object * point to that. */ if(this.connectionVerifier instanceof AdminConnectionVerifier) { ((AdminConnectionVerifier) connectionVerifier).setCluster(cluster); } return this; }
[ "public", "FailureDetectorConfig", "setCluster", "(", "Cluster", "cluster", ")", "{", "Utils", ".", "notNull", "(", "cluster", ")", ";", "this", ".", "cluster", "=", "cluster", ";", "/*\n * FIXME: this is the hacky way to refresh the admin connection\n * verifier, but it'll just work. The clean way to do so is to have a\n * centralized metadata management, and all references of cluster object\n * point to that.\n */", "if", "(", "this", ".", "connectionVerifier", "instanceof", "AdminConnectionVerifier", ")", "{", "(", "(", "AdminConnectionVerifier", ")", "connectionVerifier", ")", ".", "setCluster", "(", "cluster", ")", ";", "}", "return", "this", ";", "}" ]
Look at the comments on cluster variable to see why this is problematic
[ "Look", "at", "the", "comments", "on", "cluster", "variable", "to", "see", "why", "this", "is", "problematic" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/cluster/failuredetector/FailureDetectorConfig.java#L576-L589
161,129
voldemort/voldemort
src/java/voldemort/cluster/failuredetector/FailureDetectorConfig.java
FailureDetectorConfig.setNodes
@Deprecated public synchronized FailureDetectorConfig setNodes(Collection<Node> nodes) { Utils.notNull(nodes); this.nodes = new HashSet<Node>(nodes); return this; }
java
@Deprecated public synchronized FailureDetectorConfig setNodes(Collection<Node> nodes) { Utils.notNull(nodes); this.nodes = new HashSet<Node>(nodes); return this; }
[ "@", "Deprecated", "public", "synchronized", "FailureDetectorConfig", "setNodes", "(", "Collection", "<", "Node", ">", "nodes", ")", "{", "Utils", ".", "notNull", "(", "nodes", ")", ";", "this", ".", "nodes", "=", "new", "HashSet", "<", "Node", ">", "(", "nodes", ")", ";", "return", "this", ";", "}" ]
Assigns a list of nodes in the cluster represented by this failure detector configuration. @param nodes Collection of Node instances, usually determined from the Cluster; must be non-null
[ "Assigns", "a", "list", "of", "nodes", "in", "the", "cluster", "represented", "by", "this", "failure", "detector", "configuration", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/cluster/failuredetector/FailureDetectorConfig.java#L611-L616
161,130
voldemort/voldemort
src/java/voldemort/cluster/Cluster.java
Cluster.hasNodeWithId
public boolean hasNodeWithId(int nodeId) { Node node = nodesById.get(nodeId); if(node == null) { return false; } return true; }
java
public boolean hasNodeWithId(int nodeId) { Node node = nodesById.get(nodeId); if(node == null) { return false; } return true; }
[ "public", "boolean", "hasNodeWithId", "(", "int", "nodeId", ")", "{", "Node", "node", "=", "nodesById", ".", "get", "(", "nodeId", ")", ";", "if", "(", "node", "==", "null", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Given a cluster and a node id checks if the node exists @param nodeId The node id to search for @return True if cluster contains the node id, else false
[ "Given", "a", "cluster", "and", "a", "node", "id", "checks", "if", "the", "node", "exists" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/cluster/Cluster.java#L264-L270
161,131
voldemort/voldemort
src/java/voldemort/cluster/Cluster.java
Cluster.cloneCluster
public static Cluster cloneCluster(Cluster cluster) { // Could add a better .clone() implementation that clones the derived // data structures. The constructor invoked by this clone implementation // can be slow for large numbers of partitions. Probably faster to copy // all the maps and stuff. return new Cluster(cluster.getName(), new ArrayList<Node>(cluster.getNodes()), new ArrayList<Zone>(cluster.getZones())); /*- * Historic "clone" code being kept in case this, for some reason, was the "right" way to be doing this. ClusterMapper mapper = new ClusterMapper(); return mapper.readCluster(new StringReader(mapper.writeCluster(cluster))); */ }
java
public static Cluster cloneCluster(Cluster cluster) { // Could add a better .clone() implementation that clones the derived // data structures. The constructor invoked by this clone implementation // can be slow for large numbers of partitions. Probably faster to copy // all the maps and stuff. return new Cluster(cluster.getName(), new ArrayList<Node>(cluster.getNodes()), new ArrayList<Zone>(cluster.getZones())); /*- * Historic "clone" code being kept in case this, for some reason, was the "right" way to be doing this. ClusterMapper mapper = new ClusterMapper(); return mapper.readCluster(new StringReader(mapper.writeCluster(cluster))); */ }
[ "public", "static", "Cluster", "cloneCluster", "(", "Cluster", "cluster", ")", "{", "// Could add a better .clone() implementation that clones the derived", "// data structures. The constructor invoked by this clone implementation", "// can be slow for large numbers of partitions. Probably faster to copy", "// all the maps and stuff.", "return", "new", "Cluster", "(", "cluster", ".", "getName", "(", ")", ",", "new", "ArrayList", "<", "Node", ">", "(", "cluster", ".", "getNodes", "(", ")", ")", ",", "new", "ArrayList", "<", "Zone", ">", "(", "cluster", ".", "getZones", "(", ")", ")", ")", ";", "/*-\n * Historic \"clone\" code being kept in case this, for some reason, was the \"right\" way to be doing this.\n ClusterMapper mapper = new ClusterMapper();\n return mapper.readCluster(new StringReader(mapper.writeCluster(cluster)));\n */", "}" ]
Clones the cluster by constructing a new one with same name, partition layout, and nodes. @param cluster @return clone of Cluster cluster.
[ "Clones", "the", "cluster", "by", "constructing", "a", "new", "one", "with", "same", "name", "partition", "layout", "and", "nodes", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/cluster/Cluster.java#L322-L335
161,132
voldemort/voldemort
src/java/voldemort/client/protocol/admin/AdminClientPool.java
AdminClientPool.checkout
public AdminClient checkout() { if (isClosed.get()) { throw new IllegalStateException("Pool is closing"); } AdminClient client; // Try to get one from the Cache. while ((client = clientCache.poll()) != null) { if (!client.isClusterModified()) { return client; } else { // Cluster is Modified, after the AdminClient is created. Close it client.close(); } } // None is available, create new one. return createAdminClient(); }
java
public AdminClient checkout() { if (isClosed.get()) { throw new IllegalStateException("Pool is closing"); } AdminClient client; // Try to get one from the Cache. while ((client = clientCache.poll()) != null) { if (!client.isClusterModified()) { return client; } else { // Cluster is Modified, after the AdminClient is created. Close it client.close(); } } // None is available, create new one. return createAdminClient(); }
[ "public", "AdminClient", "checkout", "(", ")", "{", "if", "(", "isClosed", ".", "get", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Pool is closing\"", ")", ";", "}", "AdminClient", "client", ";", "// Try to get one from the Cache.", "while", "(", "(", "client", "=", "clientCache", ".", "poll", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "!", "client", ".", "isClusterModified", "(", ")", ")", "{", "return", "client", ";", "}", "else", "{", "// Cluster is Modified, after the AdminClient is created. Close it", "client", ".", "close", "(", ")", ";", "}", "}", "// None is available, create new one.", "return", "createAdminClient", "(", ")", ";", "}" ]
get an AdminClient from the cache if exists, if not create new one and return it. This method is non-blocking. All AdminClient returned from checkout, once after the completion of usage must be returned to the pool by calling checkin. If not, there will be leak of AdminClients (connections, threads and file handles). @return AdminClient
[ "get", "an", "AdminClient", "from", "the", "cache", "if", "exists", "if", "not", "create", "new", "one", "and", "return", "it", ".", "This", "method", "is", "non", "-", "blocking", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/AdminClientPool.java#L82-L101
161,133
voldemort/voldemort
src/java/voldemort/client/protocol/admin/AdminClientPool.java
AdminClientPool.checkin
public void checkin(AdminClient client) { if (isClosed.get()) { throw new IllegalStateException("Pool is closing"); } if (client == null) { throw new IllegalArgumentException("client is null"); } boolean isCheckedIn = clientCache.offer(client); if (!isCheckedIn) { // Cache is already full, close this AdminClient client.close(); } }
java
public void checkin(AdminClient client) { if (isClosed.get()) { throw new IllegalStateException("Pool is closing"); } if (client == null) { throw new IllegalArgumentException("client is null"); } boolean isCheckedIn = clientCache.offer(client); if (!isCheckedIn) { // Cache is already full, close this AdminClient client.close(); } }
[ "public", "void", "checkin", "(", "AdminClient", "client", ")", "{", "if", "(", "isClosed", ".", "get", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Pool is closing\"", ")", ";", "}", "if", "(", "client", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"client is null\"", ")", ";", "}", "boolean", "isCheckedIn", "=", "clientCache", ".", "offer", "(", "client", ")", ";", "if", "(", "!", "isCheckedIn", ")", "{", "// Cache is already full, close this AdminClient", "client", ".", "close", "(", ")", ";", "}", "}" ]
submit the adminClient after usage is completed. Behavior is undefined, if checkin is called with objects not retrieved from checkout. @param client AdminClient retrieved from checkout
[ "submit", "the", "adminClient", "after", "usage", "is", "completed", ".", "Behavior", "is", "undefined", "if", "checkin", "is", "called", "with", "objects", "not", "retrieved", "from", "checkout", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/AdminClientPool.java#L110-L125
161,134
voldemort/voldemort
src/java/voldemort/client/protocol/admin/AdminClientPool.java
AdminClientPool.close
public void close() { boolean isPreviouslyClosed = isClosed.getAndSet(true); if (isPreviouslyClosed) { return; } AdminClient client; while ((client = clientCache.poll()) != null) { client.close(); } }
java
public void close() { boolean isPreviouslyClosed = isClosed.getAndSet(true); if (isPreviouslyClosed) { return; } AdminClient client; while ((client = clientCache.poll()) != null) { client.close(); } }
[ "public", "void", "close", "(", ")", "{", "boolean", "isPreviouslyClosed", "=", "isClosed", ".", "getAndSet", "(", "true", ")", ";", "if", "(", "isPreviouslyClosed", ")", "{", "return", ";", "}", "AdminClient", "client", ";", "while", "(", "(", "client", "=", "clientCache", ".", "poll", "(", ")", ")", "!=", "null", ")", "{", "client", ".", "close", "(", ")", ";", "}", "}" ]
close the AdminPool, if no long required. After closed, all public methods will throw IllegalStateException
[ "close", "the", "AdminPool", "if", "no", "long", "required", ".", "After", "closed", "all", "public", "methods", "will", "throw", "IllegalStateException" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/AdminClientPool.java#L131-L141
161,135
voldemort/voldemort
src/java/voldemort/utils/PartitionBalanceUtils.java
PartitionBalanceUtils.compressedListOfPartitionsInZone
public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) { Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster, zoneId); StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet()); for(int initPartitionId: sortedInitPartitionIds) { if(!first) { sb.append(", "); } else { first = false; } int runLength = idToRunLength.get(initPartitionId); if(runLength == 1) { sb.append(initPartitionId); } else { int endPartitionId = (initPartitionId + runLength - 1) % cluster.getNumberOfPartitions(); sb.append(initPartitionId).append("-").append(endPartitionId); } } sb.append("]"); return sb.toString(); }
java
public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) { Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster, zoneId); StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet()); for(int initPartitionId: sortedInitPartitionIds) { if(!first) { sb.append(", "); } else { first = false; } int runLength = idToRunLength.get(initPartitionId); if(runLength == 1) { sb.append(initPartitionId); } else { int endPartitionId = (initPartitionId + runLength - 1) % cluster.getNumberOfPartitions(); sb.append(initPartitionId).append("-").append(endPartitionId); } } sb.append("]"); return sb.toString(); }
[ "public", "static", "String", "compressedListOfPartitionsInZone", "(", "final", "Cluster", "cluster", ",", "int", "zoneId", ")", "{", "Map", "<", "Integer", ",", "Integer", ">", "idToRunLength", "=", "PartitionBalanceUtils", ".", "getMapOfContiguousPartitions", "(", "cluster", ",", "zoneId", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"[\"", ")", ";", "boolean", "first", "=", "true", ";", "Set", "<", "Integer", ">", "sortedInitPartitionIds", "=", "new", "TreeSet", "<", "Integer", ">", "(", "idToRunLength", ".", "keySet", "(", ")", ")", ";", "for", "(", "int", "initPartitionId", ":", "sortedInitPartitionIds", ")", "{", "if", "(", "!", "first", ")", "{", "sb", ".", "append", "(", "\", \"", ")", ";", "}", "else", "{", "first", "=", "false", ";", "}", "int", "runLength", "=", "idToRunLength", ".", "get", "(", "initPartitionId", ")", ";", "if", "(", "runLength", "==", "1", ")", "{", "sb", ".", "append", "(", "initPartitionId", ")", ";", "}", "else", "{", "int", "endPartitionId", "=", "(", "initPartitionId", "+", "runLength", "-", "1", ")", "%", "cluster", ".", "getNumberOfPartitions", "(", ")", ";", "sb", ".", "append", "(", "initPartitionId", ")", ".", "append", "(", "\"-\"", ")", ".", "append", "(", "endPartitionId", ")", ";", "}", "}", "sb", ".", "append", "(", "\"]\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Compress contiguous partitions into format "e-i" instead of "e, f, g, h, i". This helps illustrate contiguous partitions within a zone. @param cluster @param zoneId @return pretty string of partitions per zone
[ "Compress", "contiguous", "partitions", "into", "format", "e", "-", "i", "instead", "of", "e", "f", "g", "h", "i", ".", "This", "helps", "illustrate", "contiguous", "partitions", "within", "a", "zone", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/PartitionBalanceUtils.java#L54-L81
161,136
voldemort/voldemort
src/java/voldemort/utils/PartitionBalanceUtils.java
PartitionBalanceUtils.getMapOfContiguousPartitions
public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster, int zoneId) { List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId)); Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap(); if(partitionIds.isEmpty()) { return partitionIdToRunLength; } int lastPartitionId = partitionIds.get(0); int initPartitionId = lastPartitionId; for(int offset = 1; offset < partitionIds.size(); offset++) { int partitionId = partitionIds.get(offset); if(partitionId == lastPartitionId + 1) { lastPartitionId = partitionId; continue; } int runLength = lastPartitionId - initPartitionId + 1; partitionIdToRunLength.put(initPartitionId, runLength); initPartitionId = partitionId; lastPartitionId = initPartitionId; } int runLength = lastPartitionId - initPartitionId + 1; if(lastPartitionId == cluster.getNumberOfPartitions() - 1 && partitionIdToRunLength.containsKey(0)) { // special case of contiguity that wraps around the ring. partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0)); partitionIdToRunLength.remove(0); } else { partitionIdToRunLength.put(initPartitionId, runLength); } return partitionIdToRunLength; }
java
public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster, int zoneId) { List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId)); Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap(); if(partitionIds.isEmpty()) { return partitionIdToRunLength; } int lastPartitionId = partitionIds.get(0); int initPartitionId = lastPartitionId; for(int offset = 1; offset < partitionIds.size(); offset++) { int partitionId = partitionIds.get(offset); if(partitionId == lastPartitionId + 1) { lastPartitionId = partitionId; continue; } int runLength = lastPartitionId - initPartitionId + 1; partitionIdToRunLength.put(initPartitionId, runLength); initPartitionId = partitionId; lastPartitionId = initPartitionId; } int runLength = lastPartitionId - initPartitionId + 1; if(lastPartitionId == cluster.getNumberOfPartitions() - 1 && partitionIdToRunLength.containsKey(0)) { // special case of contiguity that wraps around the ring. partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0)); partitionIdToRunLength.remove(0); } else { partitionIdToRunLength.put(initPartitionId, runLength); } return partitionIdToRunLength; }
[ "public", "static", "Map", "<", "Integer", ",", "Integer", ">", "getMapOfContiguousPartitions", "(", "final", "Cluster", "cluster", ",", "int", "zoneId", ")", "{", "List", "<", "Integer", ">", "partitionIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", "cluster", ".", "getPartitionIdsInZone", "(", "zoneId", ")", ")", ";", "Map", "<", "Integer", ",", "Integer", ">", "partitionIdToRunLength", "=", "Maps", ".", "newHashMap", "(", ")", ";", "if", "(", "partitionIds", ".", "isEmpty", "(", ")", ")", "{", "return", "partitionIdToRunLength", ";", "}", "int", "lastPartitionId", "=", "partitionIds", ".", "get", "(", "0", ")", ";", "int", "initPartitionId", "=", "lastPartitionId", ";", "for", "(", "int", "offset", "=", "1", ";", "offset", "<", "partitionIds", ".", "size", "(", ")", ";", "offset", "++", ")", "{", "int", "partitionId", "=", "partitionIds", ".", "get", "(", "offset", ")", ";", "if", "(", "partitionId", "==", "lastPartitionId", "+", "1", ")", "{", "lastPartitionId", "=", "partitionId", ";", "continue", ";", "}", "int", "runLength", "=", "lastPartitionId", "-", "initPartitionId", "+", "1", ";", "partitionIdToRunLength", ".", "put", "(", "initPartitionId", ",", "runLength", ")", ";", "initPartitionId", "=", "partitionId", ";", "lastPartitionId", "=", "initPartitionId", ";", "}", "int", "runLength", "=", "lastPartitionId", "-", "initPartitionId", "+", "1", ";", "if", "(", "lastPartitionId", "==", "cluster", ".", "getNumberOfPartitions", "(", ")", "-", "1", "&&", "partitionIdToRunLength", ".", "containsKey", "(", "0", ")", ")", "{", "// special case of contiguity that wraps around the ring.", "partitionIdToRunLength", ".", "put", "(", "initPartitionId", ",", "runLength", "+", "partitionIdToRunLength", ".", "get", "(", "0", ")", ")", ";", "partitionIdToRunLength", ".", "remove", "(", "0", ")", ";", "}", "else", "{", "partitionIdToRunLength", ".", "put", "(", "initPartitionId", ",", "runLength", ")", ";", "}", "return", "partitionIdToRunLength", ";", "}" ]
Determines run length for each 'initial' partition ID. Note that a contiguous run may "wrap around" the end of the ring. @param cluster @param zoneId @return map of initial partition Id to length of contiguous run of partition IDs within the same zone..
[ "Determines", "run", "length", "for", "each", "initial", "partition", "ID", ".", "Note", "that", "a", "contiguous", "run", "may", "wrap", "around", "the", "end", "of", "the", "ring", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/PartitionBalanceUtils.java#L92-L129
161,137
voldemort/voldemort
src/java/voldemort/utils/PartitionBalanceUtils.java
PartitionBalanceUtils.getMapOfContiguousPartitionRunLengths
public static Map<Integer, Integer> getMapOfContiguousPartitionRunLengths(final Cluster cluster, int zoneId) { Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId); Map<Integer, Integer> runLengthToCount = Maps.newHashMap(); if(idToRunLength.isEmpty()) { return runLengthToCount; } for(int runLength: idToRunLength.values()) { if(!runLengthToCount.containsKey(runLength)) { runLengthToCount.put(runLength, 0); } runLengthToCount.put(runLength, runLengthToCount.get(runLength) + 1); } return runLengthToCount; }
java
public static Map<Integer, Integer> getMapOfContiguousPartitionRunLengths(final Cluster cluster, int zoneId) { Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId); Map<Integer, Integer> runLengthToCount = Maps.newHashMap(); if(idToRunLength.isEmpty()) { return runLengthToCount; } for(int runLength: idToRunLength.values()) { if(!runLengthToCount.containsKey(runLength)) { runLengthToCount.put(runLength, 0); } runLengthToCount.put(runLength, runLengthToCount.get(runLength) + 1); } return runLengthToCount; }
[ "public", "static", "Map", "<", "Integer", ",", "Integer", ">", "getMapOfContiguousPartitionRunLengths", "(", "final", "Cluster", "cluster", ",", "int", "zoneId", ")", "{", "Map", "<", "Integer", ",", "Integer", ">", "idToRunLength", "=", "getMapOfContiguousPartitions", "(", "cluster", ",", "zoneId", ")", ";", "Map", "<", "Integer", ",", "Integer", ">", "runLengthToCount", "=", "Maps", ".", "newHashMap", "(", ")", ";", "if", "(", "idToRunLength", ".", "isEmpty", "(", ")", ")", "{", "return", "runLengthToCount", ";", "}", "for", "(", "int", "runLength", ":", "idToRunLength", ".", "values", "(", ")", ")", "{", "if", "(", "!", "runLengthToCount", ".", "containsKey", "(", "runLength", ")", ")", "{", "runLengthToCount", ".", "put", "(", "runLength", ",", "0", ")", ";", "}", "runLengthToCount", ".", "put", "(", "runLength", ",", "runLengthToCount", ".", "get", "(", "runLength", ")", "+", "1", ")", ";", "}", "return", "runLengthToCount", ";", "}" ]
Determines a histogram of contiguous runs of partitions within a zone. I.e., for each run length of contiguous partitions, how many such runs are there. Does not correctly address "wrap around" of partition IDs (i.e., the fact that partition ID 0 is "next" to partition ID 'max') @param cluster @param zoneId @return map of length of contiguous run of partitions to count of number of such runs.
[ "Determines", "a", "histogram", "of", "contiguous", "runs", "of", "partitions", "within", "a", "zone", ".", "I", ".", "e", ".", "for", "each", "run", "length", "of", "contiguous", "partitions", "how", "many", "such", "runs", "are", "there", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/PartitionBalanceUtils.java#L144-L161
161,138
voldemort/voldemort
src/java/voldemort/utils/PartitionBalanceUtils.java
PartitionBalanceUtils.getPrettyMapOfContiguousPartitionRunLengths
public static String getPrettyMapOfContiguousPartitionRunLengths(final Cluster cluster, int zoneId) { Map<Integer, Integer> runLengthToCount = getMapOfContiguousPartitionRunLengths(cluster, zoneId); String prettyHistogram = "["; boolean first = true; Set<Integer> runLengths = new TreeSet<Integer>(runLengthToCount.keySet()); for(int runLength: runLengths) { if(first) { first = false; } else { prettyHistogram += ", "; } prettyHistogram += "{" + runLength + " : " + runLengthToCount.get(runLength) + "}"; } prettyHistogram += "]"; return prettyHistogram; }
java
public static String getPrettyMapOfContiguousPartitionRunLengths(final Cluster cluster, int zoneId) { Map<Integer, Integer> runLengthToCount = getMapOfContiguousPartitionRunLengths(cluster, zoneId); String prettyHistogram = "["; boolean first = true; Set<Integer> runLengths = new TreeSet<Integer>(runLengthToCount.keySet()); for(int runLength: runLengths) { if(first) { first = false; } else { prettyHistogram += ", "; } prettyHistogram += "{" + runLength + " : " + runLengthToCount.get(runLength) + "}"; } prettyHistogram += "]"; return prettyHistogram; }
[ "public", "static", "String", "getPrettyMapOfContiguousPartitionRunLengths", "(", "final", "Cluster", "cluster", ",", "int", "zoneId", ")", "{", "Map", "<", "Integer", ",", "Integer", ">", "runLengthToCount", "=", "getMapOfContiguousPartitionRunLengths", "(", "cluster", ",", "zoneId", ")", ";", "String", "prettyHistogram", "=", "\"[\"", ";", "boolean", "first", "=", "true", ";", "Set", "<", "Integer", ">", "runLengths", "=", "new", "TreeSet", "<", "Integer", ">", "(", "runLengthToCount", ".", "keySet", "(", ")", ")", ";", "for", "(", "int", "runLength", ":", "runLengths", ")", "{", "if", "(", "first", ")", "{", "first", "=", "false", ";", "}", "else", "{", "prettyHistogram", "+=", "\", \"", ";", "}", "prettyHistogram", "+=", "\"{\"", "+", "runLength", "+", "\" : \"", "+", "runLengthToCount", ".", "get", "(", "runLength", ")", "+", "\"}\"", ";", "}", "prettyHistogram", "+=", "\"]\"", ";", "return", "prettyHistogram", ";", "}" ]
Pretty prints the output of getMapOfContiguousPartitionRunLengths @param cluster @param zoneId @return pretty string of contiguous run lengths
[ "Pretty", "prints", "the", "output", "of", "getMapOfContiguousPartitionRunLengths" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/PartitionBalanceUtils.java#L170-L187
161,139
voldemort/voldemort
src/java/voldemort/utils/PartitionBalanceUtils.java
PartitionBalanceUtils.getHotPartitionsDueToContiguity
public static String getHotPartitionsDueToContiguity(final Cluster cluster, int hotContiguityCutoff) { StringBuilder sb = new StringBuilder(); for(int zoneId: cluster.getZoneIds()) { Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId); for(Integer initialPartitionId: idToRunLength.keySet()) { int runLength = idToRunLength.get(initialPartitionId); if(runLength < hotContiguityCutoff) continue; int hotPartitionId = (initialPartitionId + runLength) % cluster.getNumberOfPartitions(); Node hotNode = cluster.getNodeForPartitionId(hotPartitionId); sb.append("\tNode " + hotNode.getId() + " (" + hotNode.getHost() + ") has hot primary partition " + hotPartitionId + " that follows contiguous run of length " + runLength + Utils.NEWLINE); } } return sb.toString(); }
java
public static String getHotPartitionsDueToContiguity(final Cluster cluster, int hotContiguityCutoff) { StringBuilder sb = new StringBuilder(); for(int zoneId: cluster.getZoneIds()) { Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId); for(Integer initialPartitionId: idToRunLength.keySet()) { int runLength = idToRunLength.get(initialPartitionId); if(runLength < hotContiguityCutoff) continue; int hotPartitionId = (initialPartitionId + runLength) % cluster.getNumberOfPartitions(); Node hotNode = cluster.getNodeForPartitionId(hotPartitionId); sb.append("\tNode " + hotNode.getId() + " (" + hotNode.getHost() + ") has hot primary partition " + hotPartitionId + " that follows contiguous run of length " + runLength + Utils.NEWLINE); } } return sb.toString(); }
[ "public", "static", "String", "getHotPartitionsDueToContiguity", "(", "final", "Cluster", "cluster", ",", "int", "hotContiguityCutoff", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "zoneId", ":", "cluster", ".", "getZoneIds", "(", ")", ")", "{", "Map", "<", "Integer", ",", "Integer", ">", "idToRunLength", "=", "getMapOfContiguousPartitions", "(", "cluster", ",", "zoneId", ")", ";", "for", "(", "Integer", "initialPartitionId", ":", "idToRunLength", ".", "keySet", "(", ")", ")", "{", "int", "runLength", "=", "idToRunLength", ".", "get", "(", "initialPartitionId", ")", ";", "if", "(", "runLength", "<", "hotContiguityCutoff", ")", "continue", ";", "int", "hotPartitionId", "=", "(", "initialPartitionId", "+", "runLength", ")", "%", "cluster", ".", "getNumberOfPartitions", "(", ")", ";", "Node", "hotNode", "=", "cluster", ".", "getNodeForPartitionId", "(", "hotPartitionId", ")", ";", "sb", ".", "append", "(", "\"\\tNode \"", "+", "hotNode", ".", "getId", "(", ")", "+", "\" (\"", "+", "hotNode", ".", "getHost", "(", ")", "+", "\") has hot primary partition \"", "+", "hotPartitionId", "+", "\" that follows contiguous run of length \"", "+", "runLength", "+", "Utils", ".", "NEWLINE", ")", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Returns a pretty printed string of nodes that host specific "hot" partitions, where hot is defined as following a contiguous run of partitions of some length in another zone. @param cluster The cluster to analyze @param hotContiguityCutoff cutoff below which a contiguous run is not hot. @return pretty string of hot partitions
[ "Returns", "a", "pretty", "printed", "string", "of", "nodes", "that", "host", "specific", "hot", "partitions", "where", "hot", "is", "defined", "as", "following", "a", "contiguous", "run", "of", "partitions", "of", "some", "length", "in", "another", "zone", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/PartitionBalanceUtils.java#L199-L220
161,140
voldemort/voldemort
src/java/voldemort/utils/PartitionBalanceUtils.java
PartitionBalanceUtils.analyzeInvalidMetadataRate
public static String analyzeInvalidMetadataRate(final Cluster currentCluster, List<StoreDefinition> currentStoreDefs, final Cluster finalCluster, List<StoreDefinition> finalStoreDefs) { StringBuilder sb = new StringBuilder(); sb.append("Dump of invalid metadata rates per zone").append(Utils.NEWLINE); HashMap<StoreDefinition, Integer> uniqueStores = StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts(currentStoreDefs); for(StoreDefinition currentStoreDef: uniqueStores.keySet()) { sb.append("Store exemplar: " + currentStoreDef.getName()) .append(Utils.NEWLINE) .append("\tThere are " + uniqueStores.get(currentStoreDef) + " other similar stores.") .append(Utils.NEWLINE); StoreRoutingPlan currentSRP = new StoreRoutingPlan(currentCluster, currentStoreDef); StoreDefinition finalStoreDef = StoreUtils.getStoreDef(finalStoreDefs, currentStoreDef.getName()); StoreRoutingPlan finalSRP = new StoreRoutingPlan(finalCluster, finalStoreDef); // Only care about existing zones for(int zoneId: currentCluster.getZoneIds()) { int zonePrimariesCount = 0; int invalidMetadata = 0; // Examine nodes in current cluster in existing zone. for(int nodeId: currentCluster.getNodeIdsInZone(zoneId)) { // For every zone-primary in current cluster for(int zonePrimaryPartitionId: currentSRP.getZonePrimaryPartitionIds(nodeId)) { zonePrimariesCount++; // Determine if original zone-primary node is still some // form of n-ary in final cluster. If not, // InvalidMetadataException will fire. if(!finalSRP.getZoneNAryPartitionIds(nodeId) .contains(zonePrimaryPartitionId)) { invalidMetadata++; } } } float rate = invalidMetadata / (float) zonePrimariesCount; sb.append("\tZone " + zoneId) .append(" : total zone primaries " + zonePrimariesCount) .append(", # that trigger invalid metadata " + invalidMetadata) .append(" => " + rate) .append(Utils.NEWLINE); } } return sb.toString(); }
java
public static String analyzeInvalidMetadataRate(final Cluster currentCluster, List<StoreDefinition> currentStoreDefs, final Cluster finalCluster, List<StoreDefinition> finalStoreDefs) { StringBuilder sb = new StringBuilder(); sb.append("Dump of invalid metadata rates per zone").append(Utils.NEWLINE); HashMap<StoreDefinition, Integer> uniqueStores = StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts(currentStoreDefs); for(StoreDefinition currentStoreDef: uniqueStores.keySet()) { sb.append("Store exemplar: " + currentStoreDef.getName()) .append(Utils.NEWLINE) .append("\tThere are " + uniqueStores.get(currentStoreDef) + " other similar stores.") .append(Utils.NEWLINE); StoreRoutingPlan currentSRP = new StoreRoutingPlan(currentCluster, currentStoreDef); StoreDefinition finalStoreDef = StoreUtils.getStoreDef(finalStoreDefs, currentStoreDef.getName()); StoreRoutingPlan finalSRP = new StoreRoutingPlan(finalCluster, finalStoreDef); // Only care about existing zones for(int zoneId: currentCluster.getZoneIds()) { int zonePrimariesCount = 0; int invalidMetadata = 0; // Examine nodes in current cluster in existing zone. for(int nodeId: currentCluster.getNodeIdsInZone(zoneId)) { // For every zone-primary in current cluster for(int zonePrimaryPartitionId: currentSRP.getZonePrimaryPartitionIds(nodeId)) { zonePrimariesCount++; // Determine if original zone-primary node is still some // form of n-ary in final cluster. If not, // InvalidMetadataException will fire. if(!finalSRP.getZoneNAryPartitionIds(nodeId) .contains(zonePrimaryPartitionId)) { invalidMetadata++; } } } float rate = invalidMetadata / (float) zonePrimariesCount; sb.append("\tZone " + zoneId) .append(" : total zone primaries " + zonePrimariesCount) .append(", # that trigger invalid metadata " + invalidMetadata) .append(" => " + rate) .append(Utils.NEWLINE); } } return sb.toString(); }
[ "public", "static", "String", "analyzeInvalidMetadataRate", "(", "final", "Cluster", "currentCluster", ",", "List", "<", "StoreDefinition", ">", "currentStoreDefs", ",", "final", "Cluster", "finalCluster", ",", "List", "<", "StoreDefinition", ">", "finalStoreDefs", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"Dump of invalid metadata rates per zone\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "HashMap", "<", "StoreDefinition", ",", "Integer", ">", "uniqueStores", "=", "StoreDefinitionUtils", ".", "getUniqueStoreDefinitionsWithCounts", "(", "currentStoreDefs", ")", ";", "for", "(", "StoreDefinition", "currentStoreDef", ":", "uniqueStores", ".", "keySet", "(", ")", ")", "{", "sb", ".", "append", "(", "\"Store exemplar: \"", "+", "currentStoreDef", ".", "getName", "(", ")", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ".", "append", "(", "\"\\tThere are \"", "+", "uniqueStores", ".", "get", "(", "currentStoreDef", ")", "+", "\" other similar stores.\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "StoreRoutingPlan", "currentSRP", "=", "new", "StoreRoutingPlan", "(", "currentCluster", ",", "currentStoreDef", ")", ";", "StoreDefinition", "finalStoreDef", "=", "StoreUtils", ".", "getStoreDef", "(", "finalStoreDefs", ",", "currentStoreDef", ".", "getName", "(", ")", ")", ";", "StoreRoutingPlan", "finalSRP", "=", "new", "StoreRoutingPlan", "(", "finalCluster", ",", "finalStoreDef", ")", ";", "// Only care about existing zones", "for", "(", "int", "zoneId", ":", "currentCluster", ".", "getZoneIds", "(", ")", ")", "{", "int", "zonePrimariesCount", "=", "0", ";", "int", "invalidMetadata", "=", "0", ";", "// Examine nodes in current cluster in existing zone.", "for", "(", "int", "nodeId", ":", "currentCluster", ".", "getNodeIdsInZone", "(", "zoneId", ")", ")", "{", "// For every zone-primary in current cluster", "for", "(", "int", "zonePrimaryPartitionId", ":", "currentSRP", ".", "getZonePrimaryPartitionIds", "(", "nodeId", ")", ")", "{", "zonePrimariesCount", "++", ";", "// Determine if original zone-primary node is still some", "// form of n-ary in final cluster. If not,", "// InvalidMetadataException will fire.", "if", "(", "!", "finalSRP", ".", "getZoneNAryPartitionIds", "(", "nodeId", ")", ".", "contains", "(", "zonePrimaryPartitionId", ")", ")", "{", "invalidMetadata", "++", ";", "}", "}", "}", "float", "rate", "=", "invalidMetadata", "/", "(", "float", ")", "zonePrimariesCount", ";", "sb", ".", "append", "(", "\"\\tZone \"", "+", "zoneId", ")", ".", "append", "(", "\" : total zone primaries \"", "+", "zonePrimariesCount", ")", ".", "append", "(", "\", # that trigger invalid metadata \"", "+", "invalidMetadata", ")", ".", "append", "(", "\" => \"", "+", "rate", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Compares current cluster with final cluster. Uses pertinent store defs for each cluster to determine if a node that hosts a zone-primary in the current cluster will no longer host any zone-nary in the final cluster. This check is the precondition for a server returning an invalid metadata exception to a client on a normal-case put or get. Normal-case being that the zone-primary receives the pseudo-master put or the get operation. @param currentCluster @param currentStoreDefs @param finalCluster @param finalStoreDefs @return pretty-printed string documenting invalid metadata rates for each zone.
[ "Compares", "current", "cluster", "with", "final", "cluster", ".", "Uses", "pertinent", "store", "defs", "for", "each", "cluster", "to", "determine", "if", "a", "node", "that", "hosts", "a", "zone", "-", "primary", "in", "the", "current", "cluster", "will", "no", "longer", "host", "any", "zone", "-", "nary", "in", "the", "final", "cluster", ".", "This", "check", "is", "the", "precondition", "for", "a", "server", "returning", "an", "invalid", "metadata", "exception", "to", "a", "client", "on", "a", "normal", "-", "case", "put", "or", "get", ".", "Normal", "-", "case", "being", "that", "the", "zone", "-", "primary", "receives", "the", "pseudo", "-", "master", "put", "or", "the", "get", "operation", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/PartitionBalanceUtils.java#L320-L369
161,141
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.create
public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory, ResourcePoolConfig config) { return new QueuedKeyedResourcePool<K, V>(factory, config); }
java
public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory, ResourcePoolConfig config) { return new QueuedKeyedResourcePool<K, V>(factory, config); }
[ "public", "static", "<", "K", ",", "V", ">", "QueuedKeyedResourcePool", "<", "K", ",", "V", ">", "create", "(", "ResourceFactory", "<", "K", ",", "V", ">", "factory", ",", "ResourcePoolConfig", "config", ")", "{", "return", "new", "QueuedKeyedResourcePool", "<", "K", ",", "V", ">", "(", "factory", ",", "config", ")", ";", "}" ]
Create a new queued pool with key type K, request type R, and value type V. @param factory The factory that creates objects @param config The pool config @return The created pool
[ "Create", "a", "new", "queued", "pool", "with", "key", "type", "K", "request", "type", "R", "and", "value", "type", "V", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L67-L70
161,142
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.create
public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory) { return create(factory, new ResourcePoolConfig()); }
java
public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory) { return create(factory, new ResourcePoolConfig()); }
[ "public", "static", "<", "K", ",", "V", ">", "QueuedKeyedResourcePool", "<", "K", ",", "V", ">", "create", "(", "ResourceFactory", "<", "K", ",", "V", ">", "factory", ")", "{", "return", "create", "(", "factory", ",", "new", "ResourcePoolConfig", "(", ")", ")", ";", "}" ]
Create a new queued pool using the defaults for key of type K, request of type R, and value of Type V. @param factory The factory that creates objects @return The created pool
[ "Create", "a", "new", "queued", "pool", "using", "the", "defaults", "for", "key", "of", "type", "K", "request", "of", "type", "R", "and", "value", "of", "Type", "V", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L79-L81
161,143
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.internalNonBlockingGet
public V internalNonBlockingGet(K key) throws Exception { Pool<V> resourcePool = getResourcePoolForKey(key); return attemptNonBlockingCheckout(key, resourcePool); }
java
public V internalNonBlockingGet(K key) throws Exception { Pool<V> resourcePool = getResourcePoolForKey(key); return attemptNonBlockingCheckout(key, resourcePool); }
[ "public", "V", "internalNonBlockingGet", "(", "K", "key", ")", "throws", "Exception", "{", "Pool", "<", "V", ">", "resourcePool", "=", "getResourcePoolForKey", "(", "key", ")", ";", "return", "attemptNonBlockingCheckout", "(", "key", ",", "resourcePool", ")", ";", "}" ]
Used only for unit testing. Please do not use this method in other ways. @param key @return @throws Exception
[ "Used", "only", "for", "unit", "testing", ".", "Please", "do", "not", "use", "this", "method", "in", "other", "ways", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L131-L134
161,144
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.getNextUnexpiredResourceRequest
private AsyncResourceRequest<V> getNextUnexpiredResourceRequest(Queue<AsyncResourceRequest<V>> requestQueue) { AsyncResourceRequest<V> resourceRequest = requestQueue.poll(); while(resourceRequest != null) { if(resourceRequest.getDeadlineNs() < System.nanoTime()) { resourceRequest.handleTimeout(); resourceRequest = requestQueue.poll(); } else { break; } } return resourceRequest; }
java
private AsyncResourceRequest<V> getNextUnexpiredResourceRequest(Queue<AsyncResourceRequest<V>> requestQueue) { AsyncResourceRequest<V> resourceRequest = requestQueue.poll(); while(resourceRequest != null) { if(resourceRequest.getDeadlineNs() < System.nanoTime()) { resourceRequest.handleTimeout(); resourceRequest = requestQueue.poll(); } else { break; } } return resourceRequest; }
[ "private", "AsyncResourceRequest", "<", "V", ">", "getNextUnexpiredResourceRequest", "(", "Queue", "<", "AsyncResourceRequest", "<", "V", ">", ">", "requestQueue", ")", "{", "AsyncResourceRequest", "<", "V", ">", "resourceRequest", "=", "requestQueue", ".", "poll", "(", ")", ";", "while", "(", "resourceRequest", "!=", "null", ")", "{", "if", "(", "resourceRequest", ".", "getDeadlineNs", "(", ")", "<", "System", ".", "nanoTime", "(", ")", ")", "{", "resourceRequest", ".", "handleTimeout", "(", ")", ";", "resourceRequest", "=", "requestQueue", ".", "poll", "(", ")", ";", "}", "else", "{", "break", ";", "}", "}", "return", "resourceRequest", ";", "}" ]
Pops resource requests off the queue until queue is empty or an unexpired resource request is found. Invokes .handleTimeout on all expired resource requests popped off the queue. @return null or a valid ResourceRequest
[ "Pops", "resource", "requests", "off", "the", "queue", "until", "queue", "is", "empty", "or", "an", "unexpired", "resource", "request", "is", "found", ".", "Invokes", ".", "handleTimeout", "on", "all", "expired", "resource", "requests", "popped", "off", "the", "queue", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L143-L154
161,145
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.processQueue
private boolean processQueue(K key) { Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key); if(requestQueue.isEmpty()) { return false; } // Attempt to get a resource. Pool<V> resourcePool = getResourcePoolForKey(key); V resource = null; Exception ex = null; try { // Must attempt non-blocking checkout to ensure resources are // created for the pool. resource = attemptNonBlockingCheckout(key, resourcePool); } catch(Exception e) { destroyResource(key, resourcePool, resource); ex = e; resource = null; } // Neither we got a resource, nor an exception. So no requests can be // processed return if(resource == null && ex == null) { return false; } // With resource in hand, process the resource requests AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue); if(resourceRequest == null) { if(resource != null) { // Did not use the resource! Directly check in via super to // avoid // circular call to processQueue(). try { super.checkin(key, resource); } catch(Exception e) { logger.error("Exception checking in resource: ", e); } } else { // Poor exception, no request to tag this exception onto // drop it on the floor and continue as usual. } return false; } else { // We have a request here. if(resource != null) { resourceRequest.useResource(resource); } else { resourceRequest.handleException(ex); } return true; } }
java
private boolean processQueue(K key) { Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key); if(requestQueue.isEmpty()) { return false; } // Attempt to get a resource. Pool<V> resourcePool = getResourcePoolForKey(key); V resource = null; Exception ex = null; try { // Must attempt non-blocking checkout to ensure resources are // created for the pool. resource = attemptNonBlockingCheckout(key, resourcePool); } catch(Exception e) { destroyResource(key, resourcePool, resource); ex = e; resource = null; } // Neither we got a resource, nor an exception. So no requests can be // processed return if(resource == null && ex == null) { return false; } // With resource in hand, process the resource requests AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue); if(resourceRequest == null) { if(resource != null) { // Did not use the resource! Directly check in via super to // avoid // circular call to processQueue(). try { super.checkin(key, resource); } catch(Exception e) { logger.error("Exception checking in resource: ", e); } } else { // Poor exception, no request to tag this exception onto // drop it on the floor and continue as usual. } return false; } else { // We have a request here. if(resource != null) { resourceRequest.useResource(resource); } else { resourceRequest.handleException(ex); } return true; } }
[ "private", "boolean", "processQueue", "(", "K", "key", ")", "{", "Queue", "<", "AsyncResourceRequest", "<", "V", ">>", "requestQueue", "=", "getRequestQueueForKey", "(", "key", ")", ";", "if", "(", "requestQueue", ".", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "// Attempt to get a resource.", "Pool", "<", "V", ">", "resourcePool", "=", "getResourcePoolForKey", "(", "key", ")", ";", "V", "resource", "=", "null", ";", "Exception", "ex", "=", "null", ";", "try", "{", "// Must attempt non-blocking checkout to ensure resources are", "// created for the pool.", "resource", "=", "attemptNonBlockingCheckout", "(", "key", ",", "resourcePool", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "destroyResource", "(", "key", ",", "resourcePool", ",", "resource", ")", ";", "ex", "=", "e", ";", "resource", "=", "null", ";", "}", "// Neither we got a resource, nor an exception. So no requests can be", "// processed return", "if", "(", "resource", "==", "null", "&&", "ex", "==", "null", ")", "{", "return", "false", ";", "}", "// With resource in hand, process the resource requests", "AsyncResourceRequest", "<", "V", ">", "resourceRequest", "=", "getNextUnexpiredResourceRequest", "(", "requestQueue", ")", ";", "if", "(", "resourceRequest", "==", "null", ")", "{", "if", "(", "resource", "!=", "null", ")", "{", "// Did not use the resource! Directly check in via super to", "// avoid", "// circular call to processQueue().", "try", "{", "super", ".", "checkin", "(", "key", ",", "resource", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Exception checking in resource: \"", ",", "e", ")", ";", "}", "}", "else", "{", "// Poor exception, no request to tag this exception onto", "// drop it on the floor and continue as usual.", "}", "return", "false", ";", "}", "else", "{", "// We have a request here.", "if", "(", "resource", "!=", "null", ")", "{", "resourceRequest", ".", "useResource", "(", "resource", ")", ";", "}", "else", "{", "resourceRequest", ".", "handleException", "(", "ex", ")", ";", "}", "return", "true", ";", "}", "}" ]
Attempts to checkout a resource so that one queued request can be serviced. @param key The key for which to process the requestQueue @return true iff an item was processed from the Queue.
[ "Attempts", "to", "checkout", "a", "resource", "so", "that", "one", "queued", "request", "can", "be", "serviced", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L163-L214
161,146
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.checkin
@Override public void checkin(K key, V resource) { super.checkin(key, resource); // NB: Blocking checkout calls for synchronous requests get the resource // checked in above before processQueueLoop() attempts checkout below. // There is therefore a risk that asynchronous requests will be starved. processQueueLoop(key); }
java
@Override public void checkin(K key, V resource) { super.checkin(key, resource); // NB: Blocking checkout calls for synchronous requests get the resource // checked in above before processQueueLoop() attempts checkout below. // There is therefore a risk that asynchronous requests will be starved. processQueueLoop(key); }
[ "@", "Override", "public", "void", "checkin", "(", "K", "key", ",", "V", "resource", ")", "{", "super", ".", "checkin", "(", "key", ",", "resource", ")", ";", "// NB: Blocking checkout calls for synchronous requests get the resource", "// checked in above before processQueueLoop() attempts checkout below.", "// There is therefore a risk that asynchronous requests will be starved.", "processQueueLoop", "(", "key", ")", ";", "}" ]
Check the given resource back into the pool @param key The key for the resource @param resource The resource
[ "Check", "the", "given", "resource", "back", "into", "the", "pool" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L248-L255
161,147
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.destroyRequest
protected void destroyRequest(AsyncResourceRequest<V> resourceRequest) { if(resourceRequest != null) { try { // To hand control back to the owner of the // AsyncResourceRequest, treat "destroy" as an exception since // there is no resource to pass into useResource, and the // timeout has not expired. Exception e = new UnreachableStoreException("Client request was terminated while waiting in the queue."); resourceRequest.handleException(e); } catch(Exception ex) { logger.error("Exception while destroying resource request:", ex); } } }
java
protected void destroyRequest(AsyncResourceRequest<V> resourceRequest) { if(resourceRequest != null) { try { // To hand control back to the owner of the // AsyncResourceRequest, treat "destroy" as an exception since // there is no resource to pass into useResource, and the // timeout has not expired. Exception e = new UnreachableStoreException("Client request was terminated while waiting in the queue."); resourceRequest.handleException(e); } catch(Exception ex) { logger.error("Exception while destroying resource request:", ex); } } }
[ "protected", "void", "destroyRequest", "(", "AsyncResourceRequest", "<", "V", ">", "resourceRequest", ")", "{", "if", "(", "resourceRequest", "!=", "null", ")", "{", "try", "{", "// To hand control back to the owner of the", "// AsyncResourceRequest, treat \"destroy\" as an exception since", "// there is no resource to pass into useResource, and the", "// timeout has not expired.", "Exception", "e", "=", "new", "UnreachableStoreException", "(", "\"Client request was terminated while waiting in the queue.\"", ")", ";", "resourceRequest", ".", "handleException", "(", "e", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "logger", ".", "error", "(", "\"Exception while destroying resource request:\"", ",", "ex", ")", ";", "}", "}", "}" ]
A safe wrapper to destroy the given resource request.
[ "A", "safe", "wrapper", "to", "destroy", "the", "given", "resource", "request", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L260-L273
161,148
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.destroyRequestQueue
private void destroyRequestQueue(Queue<AsyncResourceRequest<V>> requestQueue) { if(requestQueue != null) { AsyncResourceRequest<V> resourceRequest = requestQueue.poll(); while(resourceRequest != null) { destroyRequest(resourceRequest); resourceRequest = requestQueue.poll(); } } }
java
private void destroyRequestQueue(Queue<AsyncResourceRequest<V>> requestQueue) { if(requestQueue != null) { AsyncResourceRequest<V> resourceRequest = requestQueue.poll(); while(resourceRequest != null) { destroyRequest(resourceRequest); resourceRequest = requestQueue.poll(); } } }
[ "private", "void", "destroyRequestQueue", "(", "Queue", "<", "AsyncResourceRequest", "<", "V", ">", ">", "requestQueue", ")", "{", "if", "(", "requestQueue", "!=", "null", ")", "{", "AsyncResourceRequest", "<", "V", ">", "resourceRequest", "=", "requestQueue", ".", "poll", "(", ")", ";", "while", "(", "resourceRequest", "!=", "null", ")", "{", "destroyRequest", "(", "resourceRequest", ")", ";", "resourceRequest", "=", "requestQueue", ".", "poll", "(", ")", ";", "}", "}", "}" ]
Destroys all resource requests in requestQueue. @param requestQueue The queue for which all resource requests are to be destroyed.
[ "Destroys", "all", "resource", "requests", "in", "requestQueue", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L281-L289
161,149
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.getRegisteredResourceRequestCount
public int getRegisteredResourceRequestCount(K key) { if(requestQueueMap.containsKey(key)) { Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForExistingKey(key); // FYI: .size() is not constant time in the next call. ;) if(requestQueue != null) { return requestQueue.size(); } } return 0; }
java
public int getRegisteredResourceRequestCount(K key) { if(requestQueueMap.containsKey(key)) { Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForExistingKey(key); // FYI: .size() is not constant time in the next call. ;) if(requestQueue != null) { return requestQueue.size(); } } return 0; }
[ "public", "int", "getRegisteredResourceRequestCount", "(", "K", "key", ")", "{", "if", "(", "requestQueueMap", ".", "containsKey", "(", "key", ")", ")", "{", "Queue", "<", "AsyncResourceRequest", "<", "V", ">>", "requestQueue", "=", "getRequestQueueForExistingKey", "(", "key", ")", ";", "// FYI: .size() is not constant time in the next call. ;)", "if", "(", "requestQueue", "!=", "null", ")", "{", "return", "requestQueue", ".", "size", "(", ")", ";", "}", "}", "return", "0", ";", "}" ]
Count the number of queued resource requests for a specific pool. @param key The key @return The count of queued resource requests. Returns 0 if no queue exists for given key.
[ "Count", "the", "number", "of", "queued", "resource", "requests", "for", "a", "specific", "pool", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L355-L364
161,150
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.getRegisteredResourceRequestCount
public int getRegisteredResourceRequestCount() { int count = 0; for(Entry<K, Queue<AsyncResourceRequest<V>>> entry: this.requestQueueMap.entrySet()) { // FYI: .size() is not constant time in the next call. ;) count += entry.getValue().size(); } return count; }
java
public int getRegisteredResourceRequestCount() { int count = 0; for(Entry<K, Queue<AsyncResourceRequest<V>>> entry: this.requestQueueMap.entrySet()) { // FYI: .size() is not constant time in the next call. ;) count += entry.getValue().size(); } return count; }
[ "public", "int", "getRegisteredResourceRequestCount", "(", ")", "{", "int", "count", "=", "0", ";", "for", "(", "Entry", "<", "K", ",", "Queue", "<", "AsyncResourceRequest", "<", "V", ">", ">", ">", "entry", ":", "this", ".", "requestQueueMap", ".", "entrySet", "(", ")", ")", "{", "// FYI: .size() is not constant time in the next call. ;)", "count", "+=", "entry", ".", "getValue", "(", ")", ".", "size", "(", ")", ";", "}", "return", "count", ";", "}" ]
Count the total number of queued resource requests for all queues. The result is "approximate" in the face of concurrency since individual queues can change size during the aggregate count. @return The (approximate) aggregate count of queued resource requests.
[ "Count", "the", "total", "number", "of", "queued", "resource", "requests", "for", "all", "queues", ".", "The", "result", "is", "approximate", "in", "the", "face", "of", "concurrency", "since", "individual", "queues", "can", "change", "size", "during", "the", "aggregate", "count", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L373-L380
161,151
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceScheduler.java
RebalanceScheduler.populateTasksByStealer
protected void populateTasksByStealer(List<StealerBasedRebalanceTask> sbTaskList) { // Setup mapping of stealers to work for this run. for(StealerBasedRebalanceTask task: sbTaskList) { if(task.getStealInfos().size() != 1) { throw new VoldemortException("StealerBasedRebalanceTasks should have a list of RebalancePartitionsInfo of length 1."); } RebalanceTaskInfo stealInfo = task.getStealInfos().get(0); int stealerId = stealInfo.getStealerId(); if(!this.tasksByStealer.containsKey(stealerId)) { this.tasksByStealer.put(stealerId, new ArrayList<StealerBasedRebalanceTask>()); } this.tasksByStealer.get(stealerId).add(task); } if(tasksByStealer.isEmpty()) { return; } // Shuffle order of each stealer's work list. This randomization // helps to get rid of any "patterns" in how rebalancing tasks were // added to the task list passed in. for(List<StealerBasedRebalanceTask> taskList: tasksByStealer.values()) { Collections.shuffle(taskList); } }
java
protected void populateTasksByStealer(List<StealerBasedRebalanceTask> sbTaskList) { // Setup mapping of stealers to work for this run. for(StealerBasedRebalanceTask task: sbTaskList) { if(task.getStealInfos().size() != 1) { throw new VoldemortException("StealerBasedRebalanceTasks should have a list of RebalancePartitionsInfo of length 1."); } RebalanceTaskInfo stealInfo = task.getStealInfos().get(0); int stealerId = stealInfo.getStealerId(); if(!this.tasksByStealer.containsKey(stealerId)) { this.tasksByStealer.put(stealerId, new ArrayList<StealerBasedRebalanceTask>()); } this.tasksByStealer.get(stealerId).add(task); } if(tasksByStealer.isEmpty()) { return; } // Shuffle order of each stealer's work list. This randomization // helps to get rid of any "patterns" in how rebalancing tasks were // added to the task list passed in. for(List<StealerBasedRebalanceTask> taskList: tasksByStealer.values()) { Collections.shuffle(taskList); } }
[ "protected", "void", "populateTasksByStealer", "(", "List", "<", "StealerBasedRebalanceTask", ">", "sbTaskList", ")", "{", "// Setup mapping of stealers to work for this run.", "for", "(", "StealerBasedRebalanceTask", "task", ":", "sbTaskList", ")", "{", "if", "(", "task", ".", "getStealInfos", "(", ")", ".", "size", "(", ")", "!=", "1", ")", "{", "throw", "new", "VoldemortException", "(", "\"StealerBasedRebalanceTasks should have a list of RebalancePartitionsInfo of length 1.\"", ")", ";", "}", "RebalanceTaskInfo", "stealInfo", "=", "task", ".", "getStealInfos", "(", ")", ".", "get", "(", "0", ")", ";", "int", "stealerId", "=", "stealInfo", ".", "getStealerId", "(", ")", ";", "if", "(", "!", "this", ".", "tasksByStealer", ".", "containsKey", "(", "stealerId", ")", ")", "{", "this", ".", "tasksByStealer", ".", "put", "(", "stealerId", ",", "new", "ArrayList", "<", "StealerBasedRebalanceTask", ">", "(", ")", ")", ";", "}", "this", ".", "tasksByStealer", ".", "get", "(", "stealerId", ")", ".", "add", "(", "task", ")", ";", "}", "if", "(", "tasksByStealer", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "// Shuffle order of each stealer's work list. This randomization", "// helps to get rid of any \"patterns\" in how rebalancing tasks were", "// added to the task list passed in.", "for", "(", "List", "<", "StealerBasedRebalanceTask", ">", "taskList", ":", "tasksByStealer", ".", "values", "(", ")", ")", "{", "Collections", ".", "shuffle", "(", "taskList", ")", ";", "}", "}" ]
Go over the task list and create a map of stealerId -> Tasks @param sbTaskList List of all stealer-based rebalancing tasks to be scheduled.
[ "Go", "over", "the", "task", "list", "and", "create", "a", "map", "of", "stealerId", "-", ">", "Tasks" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceScheduler.java#L92-L116
161,152
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceScheduler.java
RebalanceScheduler.scheduleNextTask
protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) { // Make sure there is work left to do. if(doneSignal.getCount() == 0) { logger.info("All tasks completion signaled... returning"); return null; } // Limit number of tasks outstanding. if(this.numTasksExecuting >= maxParallelRebalancing) { logger.info("Executing more tasks than [" + this.numTasksExecuting + "] the parallel allowed " + maxParallelRebalancing); return null; } // Shuffle list of stealer IDs each time a new task to schedule needs to // be found. Randomizing the order should avoid prioritizing one // specific stealer's work ahead of all others. List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet()); Collections.shuffle(stealerIds); for(int stealerId: stealerIds) { if(nodeIdsWithWork.contains(stealerId)) { logger.info("Stealer " + stealerId + " is already working... continuing"); continue; } for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) { int donorId = sbTask.getStealInfos().get(0).getDonorId(); if(nodeIdsWithWork.contains(donorId)) { logger.info("Stealer " + stealerId + " Donor " + donorId + " is already working... continuing"); continue; } // Book keeping addNodesToWorkerList(Arrays.asList(stealerId, donorId)); numTasksExecuting++; // Remove this task from list thus destroying list being // iterated over. This is safe because returning directly out of // this branch. tasksByStealer.get(stealerId).remove(sbTask); try { if(executeService) { logger.info("Stealer " + stealerId + " Donor " + donorId + " going to schedule work"); service.execute(sbTask); } } catch(RejectedExecutionException ree) { logger.error("Stealer " + stealerId + "Rebalancing task rejected by executor service.", ree); throw new VoldemortRebalancingException("Stealer " + stealerId + "Rebalancing task rejected by executor service."); } return sbTask; } } printRemainingTasks(stealerIds); return null; }
java
protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) { // Make sure there is work left to do. if(doneSignal.getCount() == 0) { logger.info("All tasks completion signaled... returning"); return null; } // Limit number of tasks outstanding. if(this.numTasksExecuting >= maxParallelRebalancing) { logger.info("Executing more tasks than [" + this.numTasksExecuting + "] the parallel allowed " + maxParallelRebalancing); return null; } // Shuffle list of stealer IDs each time a new task to schedule needs to // be found. Randomizing the order should avoid prioritizing one // specific stealer's work ahead of all others. List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet()); Collections.shuffle(stealerIds); for(int stealerId: stealerIds) { if(nodeIdsWithWork.contains(stealerId)) { logger.info("Stealer " + stealerId + " is already working... continuing"); continue; } for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) { int donorId = sbTask.getStealInfos().get(0).getDonorId(); if(nodeIdsWithWork.contains(donorId)) { logger.info("Stealer " + stealerId + " Donor " + donorId + " is already working... continuing"); continue; } // Book keeping addNodesToWorkerList(Arrays.asList(stealerId, donorId)); numTasksExecuting++; // Remove this task from list thus destroying list being // iterated over. This is safe because returning directly out of // this branch. tasksByStealer.get(stealerId).remove(sbTask); try { if(executeService) { logger.info("Stealer " + stealerId + " Donor " + donorId + " going to schedule work"); service.execute(sbTask); } } catch(RejectedExecutionException ree) { logger.error("Stealer " + stealerId + "Rebalancing task rejected by executor service.", ree); throw new VoldemortRebalancingException("Stealer " + stealerId + "Rebalancing task rejected by executor service."); } return sbTask; } } printRemainingTasks(stealerIds); return null; }
[ "protected", "synchronized", "StealerBasedRebalanceTask", "scheduleNextTask", "(", "boolean", "executeService", ")", "{", "// Make sure there is work left to do.", "if", "(", "doneSignal", ".", "getCount", "(", ")", "==", "0", ")", "{", "logger", ".", "info", "(", "\"All tasks completion signaled... returning\"", ")", ";", "return", "null", ";", "}", "// Limit number of tasks outstanding.", "if", "(", "this", ".", "numTasksExecuting", ">=", "maxParallelRebalancing", ")", "{", "logger", ".", "info", "(", "\"Executing more tasks than [\"", "+", "this", ".", "numTasksExecuting", "+", "\"] the parallel allowed \"", "+", "maxParallelRebalancing", ")", ";", "return", "null", ";", "}", "// Shuffle list of stealer IDs each time a new task to schedule needs to", "// be found. Randomizing the order should avoid prioritizing one", "// specific stealer's work ahead of all others.", "List", "<", "Integer", ">", "stealerIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", "tasksByStealer", ".", "keySet", "(", ")", ")", ";", "Collections", ".", "shuffle", "(", "stealerIds", ")", ";", "for", "(", "int", "stealerId", ":", "stealerIds", ")", "{", "if", "(", "nodeIdsWithWork", ".", "contains", "(", "stealerId", ")", ")", "{", "logger", ".", "info", "(", "\"Stealer \"", "+", "stealerId", "+", "\" is already working... continuing\"", ")", ";", "continue", ";", "}", "for", "(", "StealerBasedRebalanceTask", "sbTask", ":", "tasksByStealer", ".", "get", "(", "stealerId", ")", ")", "{", "int", "donorId", "=", "sbTask", ".", "getStealInfos", "(", ")", ".", "get", "(", "0", ")", ".", "getDonorId", "(", ")", ";", "if", "(", "nodeIdsWithWork", ".", "contains", "(", "donorId", ")", ")", "{", "logger", ".", "info", "(", "\"Stealer \"", "+", "stealerId", "+", "\" Donor \"", "+", "donorId", "+", "\" is already working... continuing\"", ")", ";", "continue", ";", "}", "// Book keeping", "addNodesToWorkerList", "(", "Arrays", ".", "asList", "(", "stealerId", ",", "donorId", ")", ")", ";", "numTasksExecuting", "++", ";", "// Remove this task from list thus destroying list being", "// iterated over. This is safe because returning directly out of", "// this branch.", "tasksByStealer", ".", "get", "(", "stealerId", ")", ".", "remove", "(", "sbTask", ")", ";", "try", "{", "if", "(", "executeService", ")", "{", "logger", ".", "info", "(", "\"Stealer \"", "+", "stealerId", "+", "\" Donor \"", "+", "donorId", "+", "\" going to schedule work\"", ")", ";", "service", ".", "execute", "(", "sbTask", ")", ";", "}", "}", "catch", "(", "RejectedExecutionException", "ree", ")", "{", "logger", ".", "error", "(", "\"Stealer \"", "+", "stealerId", "+", "\"Rebalancing task rejected by executor service.\"", ",", "ree", ")", ";", "throw", "new", "VoldemortRebalancingException", "(", "\"Stealer \"", "+", "stealerId", "+", "\"Rebalancing task rejected by executor service.\"", ")", ";", "}", "return", "sbTask", ";", "}", "}", "printRemainingTasks", "(", "stealerIds", ")", ";", "return", "null", ";", "}" ]
Schedule at most one task. The scheduled task *must* invoke 'doneTask()' upon completion/termination. @param executeService flag to control execution of the service, some tests pass in value 'false' @return The task scheduled or null if not possible to schedule a task at this time.
[ "Schedule", "at", "most", "one", "task", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceScheduler.java#L177-L233
161,153
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceScheduler.java
RebalanceScheduler.addNodesToWorkerList
public synchronized void addNodesToWorkerList(List<Integer> nodeIds) { // Bookkeeping for nodes that will be involved in the next task nodeIdsWithWork.addAll(nodeIds); logger.info("Node IDs with work: " + nodeIdsWithWork + " Newly added nodes " + nodeIds); }
java
public synchronized void addNodesToWorkerList(List<Integer> nodeIds) { // Bookkeeping for nodes that will be involved in the next task nodeIdsWithWork.addAll(nodeIds); logger.info("Node IDs with work: " + nodeIdsWithWork + " Newly added nodes " + nodeIds); }
[ "public", "synchronized", "void", "addNodesToWorkerList", "(", "List", "<", "Integer", ">", "nodeIds", ")", "{", "// Bookkeeping for nodes that will be involved in the next task", "nodeIdsWithWork", ".", "addAll", "(", "nodeIds", ")", ";", "logger", ".", "info", "(", "\"Node IDs with work: \"", "+", "nodeIdsWithWork", "+", "\" Newly added nodes \"", "+", "nodeIds", ")", ";", "}" ]
Add nodes to the workers list @param nodeIds list of node ids.
[ "Add", "nodes", "to", "the", "workers", "list" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceScheduler.java#L251-L255
161,154
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceScheduler.java
RebalanceScheduler.doneTask
public synchronized void doneTask(int stealerId, int donorId) { removeNodesFromWorkerList(Arrays.asList(stealerId, donorId)); numTasksExecuting--; doneSignal.countDown(); // Try and schedule more tasks now that resources may be available to do // so. scheduleMoreTasks(); }
java
public synchronized void doneTask(int stealerId, int donorId) { removeNodesFromWorkerList(Arrays.asList(stealerId, donorId)); numTasksExecuting--; doneSignal.countDown(); // Try and schedule more tasks now that resources may be available to do // so. scheduleMoreTasks(); }
[ "public", "synchronized", "void", "doneTask", "(", "int", "stealerId", ",", "int", "donorId", ")", "{", "removeNodesFromWorkerList", "(", "Arrays", ".", "asList", "(", "stealerId", ",", "donorId", ")", ")", ";", "numTasksExecuting", "--", ";", "doneSignal", ".", "countDown", "(", ")", ";", "// Try and schedule more tasks now that resources may be available to do", "// so.", "scheduleMoreTasks", "(", ")", ";", "}" ]
Method must be invoked upon completion of a rebalancing task. It is the task's responsibility to do so. @param stealerId @param donorId
[ "Method", "must", "be", "invoked", "upon", "completion", "of", "a", "rebalancing", "task", ".", "It", "is", "the", "task", "s", "responsibility", "to", "do", "so", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceScheduler.java#L274-L281
161,155
voldemort/voldemort
src/java/voldemort/store/bdb/stats/AggregatedBdbEnvironmentStats.java
AggregatedBdbEnvironmentStats.collectLongMetric
private List<Long> collectLongMetric(String metricGetterName) { List<Long> vals = new ArrayList<Long>(); for(BdbEnvironmentStats envStats: environmentStatsTracked) { vals.add((Long) ReflectUtils.callMethod(envStats, BdbEnvironmentStats.class, metricGetterName, new Class<?>[0], new Object[0])); } return vals; }
java
private List<Long> collectLongMetric(String metricGetterName) { List<Long> vals = new ArrayList<Long>(); for(BdbEnvironmentStats envStats: environmentStatsTracked) { vals.add((Long) ReflectUtils.callMethod(envStats, BdbEnvironmentStats.class, metricGetterName, new Class<?>[0], new Object[0])); } return vals; }
[ "private", "List", "<", "Long", ">", "collectLongMetric", "(", "String", "metricGetterName", ")", "{", "List", "<", "Long", ">", "vals", "=", "new", "ArrayList", "<", "Long", ">", "(", ")", ";", "for", "(", "BdbEnvironmentStats", "envStats", ":", "environmentStatsTracked", ")", "{", "vals", ".", "add", "(", "(", "Long", ")", "ReflectUtils", ".", "callMethod", "(", "envStats", ",", "BdbEnvironmentStats", ".", "class", ",", "metricGetterName", ",", "new", "Class", "<", "?", ">", "[", "0", "]", ",", "new", "Object", "[", "0", "]", ")", ")", ";", "}", "return", "vals", ";", "}" ]
Calls the provided metric getter on all the tracked environments and obtains their values @param metricGetterName @return
[ "Calls", "the", "provided", "metric", "getter", "on", "all", "the", "tracked", "environments", "and", "obtains", "their", "values" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/bdb/stats/AggregatedBdbEnvironmentStats.java#L38-L48
161,156
voldemort/voldemort
src/java/voldemort/utils/ByteArray.java
ByteArray.toHexStrings
public static Iterable<String> toHexStrings(Iterable<ByteArray> arrays) { ArrayList<String> ret = new ArrayList<String>(); for(ByteArray array: arrays) ret.add(ByteUtils.toHexString(array.get())); return ret; }
java
public static Iterable<String> toHexStrings(Iterable<ByteArray> arrays) { ArrayList<String> ret = new ArrayList<String>(); for(ByteArray array: arrays) ret.add(ByteUtils.toHexString(array.get())); return ret; }
[ "public", "static", "Iterable", "<", "String", ">", "toHexStrings", "(", "Iterable", "<", "ByteArray", ">", "arrays", ")", "{", "ArrayList", "<", "String", ">", "ret", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "ByteArray", "array", ":", "arrays", ")", "ret", ".", "(", "ByteUtils", ".", "toHexString", "(", "array", ".", "get", "(", ")", ")", ")", ";", "return", "ret", ";", "}" ]
Translate the each ByteArray in an iterable into a hexadecimal string @param arrays The array of bytes to translate @return An iterable of converted strings
[ "Translate", "the", "each", "ByteArray", "in", "an", "iterable", "into", "a", "hexadecimal", "string" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteArray.java#L53-L58
161,157
voldemort/voldemort
src/java/voldemort/rest/GetResponseSender.java
GetResponseSender.sendResponse
@Override public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception { /* * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage. * However when writing to the outputStream we only send the multiPart object and not the entire * mimeMessage. This is intentional. * * In the earlier version of this code we used to create a multiPart object and just send that multiPart * across the wire. * * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders() * on the body part. It's this updateHeaders call that transfers the content type from the * DataHandler to the part's MIME Content-Type header. * * To make sure that the Content-Type headers are being updated (without changing too much code), we decided * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart. * This is to make sure multiPart's headers are updated accurately. */ MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMultipart multiPart = new MimeMultipart(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String base64Key = RestUtils.encodeVoldemortKey(key.get()); String contentLocationKey = "/" + this.storeName + "/" + base64Key; for(Versioned<byte[]> versionedValue: versionedValues) { byte[] responseValue = versionedValue.getValue(); VectorClock vectorClock = (VectorClock) versionedValue.getVersion(); String eTag = RestUtils.getSerializedVectorClock(vectorClock); numVectorClockEntries += vectorClock.getVersionMap().size(); // Create the individual body part for each versioned value of the // requested key MimeBodyPart body = new MimeBodyPart(); try { // Add the right headers body.addHeader(CONTENT_TYPE, "application/octet-stream"); body.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag); body.setContent(responseValue, "application/octet-stream"); body.addHeader(RestMessageHeaders.CONTENT_LENGTH, Integer.toString(responseValue.length)); multiPart.addBodyPart(body); } catch(MessagingException me) { logger.error("Exception while constructing body part", me); outputStream.close(); throw me; } } message.setContent(multiPart); message.saveChanges(); try { multiPart.writeTo(outputStream); } catch(Exception e) { logger.error("Exception while writing multipart to output stream", e); outputStream.close(); throw e; } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.toByteArray()); // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); response.setHeader(CONTENT_LOCATION, contentLocationKey); // Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Write the response to the Netty Channel if(logger.isDebugEnabled()) { String keyStr = RestUtils.getKeyHexString(this.key); debugLog("GET", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), numVectorClockEntries); } this.messageEvent.getChannel().write(response); if(performanceStats != null && isFromLocalZone) { recordStats(performanceStats, startTimeInMs, Tracked.GET); } outputStream.close(); }
java
@Override public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception { /* * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage. * However when writing to the outputStream we only send the multiPart object and not the entire * mimeMessage. This is intentional. * * In the earlier version of this code we used to create a multiPart object and just send that multiPart * across the wire. * * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders() * on the body part. It's this updateHeaders call that transfers the content type from the * DataHandler to the part's MIME Content-Type header. * * To make sure that the Content-Type headers are being updated (without changing too much code), we decided * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart. * This is to make sure multiPart's headers are updated accurately. */ MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMultipart multiPart = new MimeMultipart(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String base64Key = RestUtils.encodeVoldemortKey(key.get()); String contentLocationKey = "/" + this.storeName + "/" + base64Key; for(Versioned<byte[]> versionedValue: versionedValues) { byte[] responseValue = versionedValue.getValue(); VectorClock vectorClock = (VectorClock) versionedValue.getVersion(); String eTag = RestUtils.getSerializedVectorClock(vectorClock); numVectorClockEntries += vectorClock.getVersionMap().size(); // Create the individual body part for each versioned value of the // requested key MimeBodyPart body = new MimeBodyPart(); try { // Add the right headers body.addHeader(CONTENT_TYPE, "application/octet-stream"); body.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag); body.setContent(responseValue, "application/octet-stream"); body.addHeader(RestMessageHeaders.CONTENT_LENGTH, Integer.toString(responseValue.length)); multiPart.addBodyPart(body); } catch(MessagingException me) { logger.error("Exception while constructing body part", me); outputStream.close(); throw me; } } message.setContent(multiPart); message.saveChanges(); try { multiPart.writeTo(outputStream); } catch(Exception e) { logger.error("Exception while writing multipart to output stream", e); outputStream.close(); throw e; } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.toByteArray()); // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); response.setHeader(CONTENT_LOCATION, contentLocationKey); // Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Write the response to the Netty Channel if(logger.isDebugEnabled()) { String keyStr = RestUtils.getKeyHexString(this.key); debugLog("GET", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), numVectorClockEntries); } this.messageEvent.getChannel().write(response); if(performanceStats != null && isFromLocalZone) { recordStats(performanceStats, startTimeInMs, Tracked.GET); } outputStream.close(); }
[ "@", "Override", "public", "void", "sendResponse", "(", "StoreStats", "performanceStats", ",", "boolean", "isFromLocalZone", ",", "long", "startTimeInMs", ")", "throws", "Exception", "{", "/*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */", "MimeMessage", "message", "=", "new", "MimeMessage", "(", "Session", ".", "getDefaultInstance", "(", "new", "Properties", "(", ")", ")", ")", ";", "MimeMultipart", "multiPart", "=", "new", "MimeMultipart", "(", ")", ";", "ByteArrayOutputStream", "outputStream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "String", "base64Key", "=", "RestUtils", ".", "encodeVoldemortKey", "(", "key", ".", "get", "(", ")", ")", ";", "String", "contentLocationKey", "=", "\"/\"", "+", "this", ".", "storeName", "+", "\"/\"", "+", "base64Key", ";", "for", "(", "Versioned", "<", "byte", "[", "]", ">", "versionedValue", ":", "versionedValues", ")", "{", "byte", "[", "]", "responseValue", "=", "versionedValue", ".", "getValue", "(", ")", ";", "VectorClock", "vectorClock", "=", "(", "VectorClock", ")", "versionedValue", ".", "getVersion", "(", ")", ";", "String", "eTag", "=", "RestUtils", ".", "getSerializedVectorClock", "(", "vectorClock", ")", ";", "numVectorClockEntries", "+=", "vectorClock", ".", "getVersionMap", "(", ")", ".", "size", "(", ")", ";", "// Create the individual body part for each versioned value of the", "// requested key", "MimeBodyPart", "body", "=", "new", "MimeBodyPart", "(", ")", ";", "try", "{", "// Add the right headers", "body", ".", "addHeader", "(", "CONTENT_TYPE", ",", "\"application/octet-stream\"", ")", ";", "body", ".", "addHeader", "(", "CONTENT_TRANSFER_ENCODING", ",", "\"binary\"", ")", ";", "body", ".", "addHeader", "(", "RestMessageHeaders", ".", "X_VOLD_VECTOR_CLOCK", ",", "eTag", ")", ";", "body", ".", "setContent", "(", "responseValue", ",", "\"application/octet-stream\"", ")", ";", "body", ".", "addHeader", "(", "RestMessageHeaders", ".", "CONTENT_LENGTH", ",", "Integer", ".", "toString", "(", "responseValue", ".", "length", ")", ")", ";", "multiPart", ".", "addBodyPart", "(", "body", ")", ";", "}", "catch", "(", "MessagingException", "me", ")", "{", "logger", ".", "error", "(", "\"Exception while constructing body part\"", ",", "me", ")", ";", "outputStream", ".", "close", "(", ")", ";", "throw", "me", ";", "}", "}", "message", ".", "setContent", "(", "multiPart", ")", ";", "message", ".", "saveChanges", "(", ")", ";", "try", "{", "multiPart", ".", "writeTo", "(", "outputStream", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Exception while writing multipart to output stream\"", ",", "e", ")", ";", "outputStream", ".", "close", "(", ")", ";", "throw", "e", ";", "}", "ChannelBuffer", "responseContent", "=", "ChannelBuffers", ".", "dynamicBuffer", "(", ")", ";", "responseContent", ".", "writeBytes", "(", "outputStream", ".", "toByteArray", "(", ")", ")", ";", "// Create the Response object", "HttpResponse", "response", "=", "new", "DefaultHttpResponse", "(", "HTTP_1_1", ",", "OK", ")", ";", "// Set the right headers", "response", ".", "setHeader", "(", "CONTENT_TYPE", ",", "\"multipart/binary\"", ")", ";", "response", ".", "setHeader", "(", "CONTENT_TRANSFER_ENCODING", ",", "\"binary\"", ")", ";", "response", ".", "setHeader", "(", "CONTENT_LOCATION", ",", "contentLocationKey", ")", ";", "// Copy the data into the payload", "response", ".", "setContent", "(", "responseContent", ")", ";", "response", ".", "setHeader", "(", "CONTENT_LENGTH", ",", "response", ".", "getContent", "(", ")", ".", "readableBytes", "(", ")", ")", ";", "// Write the response to the Netty Channel", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "String", "keyStr", "=", "RestUtils", ".", "getKeyHexString", "(", "this", ".", "key", ")", ";", "debugLog", "(", "\"GET\"", ",", "this", ".", "storeName", ",", "keyStr", ",", "startTimeInMs", ",", "System", ".", "currentTimeMillis", "(", ")", ",", "numVectorClockEntries", ")", ";", "}", "this", ".", "messageEvent", ".", "getChannel", "(", ")", ".", "write", "(", "response", ")", ";", "if", "(", "performanceStats", "!=", "null", "&&", "isFromLocalZone", ")", "{", "recordStats", "(", "performanceStats", ",", "startTimeInMs", ",", "Tracked", ".", "GET", ")", ";", "}", "outputStream", ".", "close", "(", ")", ";", "}" ]
Sends a multipart response. Each body part represents a versioned value of the given key. @throws IOException @throws MessagingException
[ "Sends", "a", "multipart", "response", ".", "Each", "body", "part", "represents", "a", "versioned", "value", "of", "the", "given", "key", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/GetResponseSender.java#L58-L159
161,158
voldemort/voldemort
src/java/voldemort/server/VoldemortConfig.java
VoldemortConfig.getPublicConfigValue
public String getPublicConfigValue(String key) throws ConfigurationException { if (!allProps.containsKey(key)) { throw new UndefinedPropertyException("The requested config key does not exist."); } if (restrictedConfigs.contains(key)) { throw new ConfigurationException("The requested config key is not publicly available!"); } return allProps.get(key); }
java
public String getPublicConfigValue(String key) throws ConfigurationException { if (!allProps.containsKey(key)) { throw new UndefinedPropertyException("The requested config key does not exist."); } if (restrictedConfigs.contains(key)) { throw new ConfigurationException("The requested config key is not publicly available!"); } return allProps.get(key); }
[ "public", "String", "getPublicConfigValue", "(", "String", "key", ")", "throws", "ConfigurationException", "{", "if", "(", "!", "allProps", ".", "containsKey", "(", "key", ")", ")", "{", "throw", "new", "UndefinedPropertyException", "(", "\"The requested config key does not exist.\"", ")", ";", "}", "if", "(", "restrictedConfigs", ".", "contains", "(", "key", ")", ")", "{", "throw", "new", "ConfigurationException", "(", "\"The requested config key is not publicly available!\"", ")", ";", "}", "return", "allProps", ".", "get", "(", "key", ")", ";", "}" ]
This is a generic function for retrieving any config value. The returned value is the one the server is operating with, no matter whether it comes from defaults or from the user-supplied configuration. This function only provides access to configs which are deemed safe to share publicly (i.e.: not security-related configs). The list of configs which are considered off-limit can itself be configured via '{@value #RESTRICTED_CONFIGS}'. @param key config key for which to retrieve the value. @return the value for the requested config key, in String format. May return null if the key exists and its value is explicitly set to null. @throws UndefinedPropertyException if the requested key does not exist in the config. @throws ConfigurationException if the requested key is not publicly available.
[ "This", "is", "a", "generic", "function", "for", "retrieving", "any", "config", "value", ".", "The", "returned", "value", "is", "the", "one", "the", "server", "is", "operating", "with", "no", "matter", "whether", "it", "comes", "from", "defaults", "or", "from", "the", "user", "-", "supplied", "configuration", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/VoldemortConfig.java#L1171-L1179
161,159
voldemort/voldemort
src/java/voldemort/store/quota/QuotaLimitingStore.java
QuotaLimitingStore.checkRateLimit
private void checkRateLimit(String quotaKey, Tracked trackedOp) { String quotaValue = null; try { if(!metadataStore.getQuotaEnforcingEnabledUnlocked()) { return; } quotaValue = quotaStore.cacheGet(quotaKey); // Store may not have any quotas if(quotaValue == null) { return; } // But, if it does float currentRate = getThroughput(trackedOp); float allowedRate = Float.parseFloat(quotaValue); // TODO the histogram should be reasonably accurate to do all // these things.. (ghost qps and all) // Report the current quota usage level quotaStats.reportQuotaUsed(trackedOp, Utils.safeGetPercentage(currentRate, allowedRate)); // check if we have exceeded rate. if(currentRate > allowedRate) { quotaStats.reportRateLimitedOp(trackedOp); throw new QuotaExceededException("Exceeded rate limit for " + quotaKey + ". Maximum allowed : " + allowedRate + " Current: " + currentRate); } } catch(NumberFormatException nfe) { // move on, if we cannot parse quota value properly logger.debug("Invalid formatting of quota value for key " + quotaKey + " : " + quotaValue); } }
java
private void checkRateLimit(String quotaKey, Tracked trackedOp) { String quotaValue = null; try { if(!metadataStore.getQuotaEnforcingEnabledUnlocked()) { return; } quotaValue = quotaStore.cacheGet(quotaKey); // Store may not have any quotas if(quotaValue == null) { return; } // But, if it does float currentRate = getThroughput(trackedOp); float allowedRate = Float.parseFloat(quotaValue); // TODO the histogram should be reasonably accurate to do all // these things.. (ghost qps and all) // Report the current quota usage level quotaStats.reportQuotaUsed(trackedOp, Utils.safeGetPercentage(currentRate, allowedRate)); // check if we have exceeded rate. if(currentRate > allowedRate) { quotaStats.reportRateLimitedOp(trackedOp); throw new QuotaExceededException("Exceeded rate limit for " + quotaKey + ". Maximum allowed : " + allowedRate + " Current: " + currentRate); } } catch(NumberFormatException nfe) { // move on, if we cannot parse quota value properly logger.debug("Invalid formatting of quota value for key " + quotaKey + " : " + quotaValue); } }
[ "private", "void", "checkRateLimit", "(", "String", "quotaKey", ",", "Tracked", "trackedOp", ")", "{", "String", "quotaValue", "=", "null", ";", "try", "{", "if", "(", "!", "metadataStore", ".", "getQuotaEnforcingEnabledUnlocked", "(", ")", ")", "{", "return", ";", "}", "quotaValue", "=", "quotaStore", ".", "cacheGet", "(", "quotaKey", ")", ";", "// Store may not have any quotas", "if", "(", "quotaValue", "==", "null", ")", "{", "return", ";", "}", "// But, if it does", "float", "currentRate", "=", "getThroughput", "(", "trackedOp", ")", ";", "float", "allowedRate", "=", "Float", ".", "parseFloat", "(", "quotaValue", ")", ";", "// TODO the histogram should be reasonably accurate to do all", "// these things.. (ghost qps and all)", "// Report the current quota usage level", "quotaStats", ".", "reportQuotaUsed", "(", "trackedOp", ",", "Utils", ".", "safeGetPercentage", "(", "currentRate", ",", "allowedRate", ")", ")", ";", "// check if we have exceeded rate.", "if", "(", "currentRate", ">", "allowedRate", ")", "{", "quotaStats", ".", "reportRateLimitedOp", "(", "trackedOp", ")", ";", "throw", "new", "QuotaExceededException", "(", "\"Exceeded rate limit for \"", "+", "quotaKey", "+", "\". Maximum allowed : \"", "+", "allowedRate", "+", "\" Current: \"", "+", "currentRate", ")", ";", "}", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "// move on, if we cannot parse quota value properly", "logger", ".", "debug", "(", "\"Invalid formatting of quota value for key \"", "+", "quotaKey", "+", "\" : \"", "+", "quotaValue", ")", ";", "}", "}" ]
Ensure the current throughput levels for the tracked operation does not exceed set quota limits. Throws an exception if exceeded quota. @param quotaKey @param trackedOp
[ "Ensure", "the", "current", "throughput", "levels", "for", "the", "tracked", "operation", "does", "not", "exceed", "set", "quota", "limits", ".", "Throws", "an", "exception", "if", "exceeded", "quota", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/quota/QuotaLimitingStore.java#L88-L120
161,160
voldemort/voldemort
src/java/voldemort/server/protocol/admin/AsyncOperationService.java
AsyncOperationService.submitOperation
public synchronized void submitOperation(int requestId, AsyncOperation operation) { if(this.operations.containsKey(requestId)) throw new VoldemortException("Request " + requestId + " already submitted to the system"); this.operations.put(requestId, operation); scheduler.scheduleNow(operation); logger.debug("Handling async operation " + requestId); }
java
public synchronized void submitOperation(int requestId, AsyncOperation operation) { if(this.operations.containsKey(requestId)) throw new VoldemortException("Request " + requestId + " already submitted to the system"); this.operations.put(requestId, operation); scheduler.scheduleNow(operation); logger.debug("Handling async operation " + requestId); }
[ "public", "synchronized", "void", "submitOperation", "(", "int", "requestId", ",", "AsyncOperation", "operation", ")", "{", "if", "(", "this", ".", "operations", ".", "containsKey", "(", "requestId", ")", ")", "throw", "new", "VoldemortException", "(", "\"Request \"", "+", "requestId", "+", "\" already submitted to the system\"", ")", ";", "this", ".", "operations", ".", "put", "(", "requestId", ",", "operation", ")", ";", "scheduler", ".", "scheduleNow", "(", "operation", ")", ";", "logger", ".", "debug", "(", "\"Handling async operation \"", "+", "requestId", ")", ";", "}" ]
Submit a operations. Throw a run time exception if the operations is already submitted @param operation The asynchronous operations to submit @param requestId Id of the request
[ "Submit", "a", "operations", ".", "Throw", "a", "run", "time", "exception", "if", "the", "operations", "is", "already", "submitted" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/AsyncOperationService.java#L68-L76
161,161
voldemort/voldemort
src/java/voldemort/server/protocol/admin/AsyncOperationService.java
AsyncOperationService.isComplete
public synchronized boolean isComplete(int requestId, boolean remove) { if (!operations.containsKey(requestId)) throw new VoldemortException("No operation with id " + requestId + " found"); if (operations.get(requestId).getStatus().isComplete()) { if (logger.isDebugEnabled()) logger.debug("Operation complete " + requestId); if (remove) operations.remove(requestId); return true; } return false; }
java
public synchronized boolean isComplete(int requestId, boolean remove) { if (!operations.containsKey(requestId)) throw new VoldemortException("No operation with id " + requestId + " found"); if (operations.get(requestId).getStatus().isComplete()) { if (logger.isDebugEnabled()) logger.debug("Operation complete " + requestId); if (remove) operations.remove(requestId); return true; } return false; }
[ "public", "synchronized", "boolean", "isComplete", "(", "int", "requestId", ",", "boolean", "remove", ")", "{", "if", "(", "!", "operations", ".", "containsKey", "(", "requestId", ")", ")", "throw", "new", "VoldemortException", "(", "\"No operation with id \"", "+", "requestId", "+", "\" found\"", ")", ";", "if", "(", "operations", ".", "get", "(", "requestId", ")", ".", "getStatus", "(", ")", ".", "isComplete", "(", ")", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "logger", ".", "debug", "(", "\"Operation complete \"", "+", "requestId", ")", ";", "if", "(", "remove", ")", "operations", ".", "remove", "(", "requestId", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check if the an operation is done or not. @param requestId Id of the request @param remove Whether remove the request out of the list if it is done. @return True if request is complete, false otherwise
[ "Check", "if", "the", "an", "operation", "is", "done", "or", "not", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/AsyncOperationService.java#L85-L100
161,162
voldemort/voldemort
src/java/voldemort/server/protocol/admin/AsyncOperationService.java
AsyncOperationService.getStatus
@JmxOperation(description = "Retrieve operation status") public String getStatus(int id) { try { return getOperationStatus(id).toString(); } catch(VoldemortException e) { return "No operation with id " + id + " found"; } }
java
@JmxOperation(description = "Retrieve operation status") public String getStatus(int id) { try { return getOperationStatus(id).toString(); } catch(VoldemortException e) { return "No operation with id " + id + " found"; } }
[ "@", "JmxOperation", "(", "description", "=", "\"Retrieve operation status\"", ")", "public", "String", "getStatus", "(", "int", "id", ")", "{", "try", "{", "return", "getOperationStatus", "(", "id", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "VoldemortException", "e", ")", "{", "return", "\"No operation with id \"", "+", "id", "+", "\" found\"", ";", "}", "}" ]
Wrap getOperationStatus to avoid throwing exception over JMX
[ "Wrap", "getOperationStatus", "to", "avoid", "throwing", "exception", "over", "JMX" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/AsyncOperationService.java#L110-L117
161,163
voldemort/voldemort
src/java/voldemort/server/protocol/admin/AsyncOperationService.java
AsyncOperationService.getAsyncOperationList
public List<Integer> getAsyncOperationList(boolean showCompleted) { /** * Create a copy using an immutable set to avoid a * {@link java.util.ConcurrentModificationException} */ Set<Integer> keySet = ImmutableSet.copyOf(operations.keySet()); if(showCompleted) return new ArrayList<Integer>(keySet); List<Integer> keyList = new ArrayList<Integer>(); for(int key: keySet) { AsyncOperation operation = operations.get(key); if(operation != null && !operation.getStatus().isComplete()) keyList.add(key); } return keyList; }
java
public List<Integer> getAsyncOperationList(boolean showCompleted) { /** * Create a copy using an immutable set to avoid a * {@link java.util.ConcurrentModificationException} */ Set<Integer> keySet = ImmutableSet.copyOf(operations.keySet()); if(showCompleted) return new ArrayList<Integer>(keySet); List<Integer> keyList = new ArrayList<Integer>(); for(int key: keySet) { AsyncOperation operation = operations.get(key); if(operation != null && !operation.getStatus().isComplete()) keyList.add(key); } return keyList; }
[ "public", "List", "<", "Integer", ">", "getAsyncOperationList", "(", "boolean", "showCompleted", ")", "{", "/**\n * Create a copy using an immutable set to avoid a\n * {@link java.util.ConcurrentModificationException}\n */", "Set", "<", "Integer", ">", "keySet", "=", "ImmutableSet", ".", "copyOf", "(", "operations", ".", "keySet", "(", ")", ")", ";", "if", "(", "showCompleted", ")", "return", "new", "ArrayList", "<", "Integer", ">", "(", "keySet", ")", ";", "List", "<", "Integer", ">", "keyList", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "int", "key", ":", "keySet", ")", "{", "AsyncOperation", "operation", "=", "operations", ".", "get", "(", "key", ")", ";", "if", "(", "operation", "!=", "null", "&&", "!", "operation", ".", "getStatus", "(", ")", ".", "isComplete", "(", ")", ")", "keyList", ".", "add", "(", "key", ")", ";", "}", "return", "keyList", ";", "}" ]
Get list of asynchronous operations on this node. By default, only the pending operations are returned. @param showCompleted Show completed operations @return A list of operation ids.
[ "Get", "list", "of", "asynchronous", "operations", "on", "this", "node", ".", "By", "default", "only", "the", "pending", "operations", "are", "returned", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/AsyncOperationService.java#L150-L167
161,164
voldemort/voldemort
src/java/voldemort/server/protocol/admin/AsyncOperationService.java
AsyncOperationService.stopAsyncOperation
@JmxOperation public String stopAsyncOperation(int requestId) { try { stopOperation(requestId); } catch(VoldemortException e) { return e.getMessage(); } return "Stopping operation " + requestId; }
java
@JmxOperation public String stopAsyncOperation(int requestId) { try { stopOperation(requestId); } catch(VoldemortException e) { return e.getMessage(); } return "Stopping operation " + requestId; }
[ "@", "JmxOperation", "public", "String", "stopAsyncOperation", "(", "int", "requestId", ")", "{", "try", "{", "stopOperation", "(", "requestId", ")", ";", "}", "catch", "(", "VoldemortException", "e", ")", "{", "return", "e", ".", "getMessage", "(", ")", ";", "}", "return", "\"Stopping operation \"", "+", "requestId", ";", "}" ]
Wrapper to avoid throwing an exception over JMX
[ "Wrapper", "to", "avoid", "throwing", "an", "exception", "over", "JMX" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/AsyncOperationService.java#L177-L186
161,165
voldemort/voldemort
src/java/voldemort/store/retention/RetentionEnforcingStore.java
RetentionEnforcingStore.updateStoreDefinition
@Override public void updateStoreDefinition(StoreDefinition storeDef) { this.storeDef = storeDef; if(storeDef.hasRetentionPeriod()) this.retentionTimeMs = storeDef.getRetentionDays() * Time.MS_PER_DAY; }
java
@Override public void updateStoreDefinition(StoreDefinition storeDef) { this.storeDef = storeDef; if(storeDef.hasRetentionPeriod()) this.retentionTimeMs = storeDef.getRetentionDays() * Time.MS_PER_DAY; }
[ "@", "Override", "public", "void", "updateStoreDefinition", "(", "StoreDefinition", "storeDef", ")", "{", "this", ".", "storeDef", "=", "storeDef", ";", "if", "(", "storeDef", ".", "hasRetentionPeriod", "(", ")", ")", "this", ".", "retentionTimeMs", "=", "storeDef", ".", "getRetentionDays", "(", ")", "*", "Time", ".", "MS_PER_DAY", ";", "}" ]
Updates the store definition object and the retention time based on the updated store definition
[ "Updates", "the", "store", "definition", "object", "and", "the", "retention", "time", "based", "on", "the", "updated", "store", "definition" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/retention/RetentionEnforcingStore.java#L51-L56
161,166
voldemort/voldemort
src/java/voldemort/store/retention/RetentionEnforcingStore.java
RetentionEnforcingStore.filterExpiredEntries
private List<Versioned<byte[]>> filterExpiredEntries(ByteArray key, List<Versioned<byte[]>> vals) { Iterator<Versioned<byte[]>> valsIterator = vals.iterator(); while(valsIterator.hasNext()) { Versioned<byte[]> val = valsIterator.next(); VectorClock clock = (VectorClock) val.getVersion(); // omit if expired if(clock.getTimestamp() < (time.getMilliseconds() - this.retentionTimeMs)) { valsIterator.remove(); // delete stale value if configured if(deleteExpiredEntries) { getInnerStore().delete(key, clock); } } } return vals; }
java
private List<Versioned<byte[]>> filterExpiredEntries(ByteArray key, List<Versioned<byte[]>> vals) { Iterator<Versioned<byte[]>> valsIterator = vals.iterator(); while(valsIterator.hasNext()) { Versioned<byte[]> val = valsIterator.next(); VectorClock clock = (VectorClock) val.getVersion(); // omit if expired if(clock.getTimestamp() < (time.getMilliseconds() - this.retentionTimeMs)) { valsIterator.remove(); // delete stale value if configured if(deleteExpiredEntries) { getInnerStore().delete(key, clock); } } } return vals; }
[ "private", "List", "<", "Versioned", "<", "byte", "[", "]", ">", ">", "filterExpiredEntries", "(", "ByteArray", "key", ",", "List", "<", "Versioned", "<", "byte", "[", "]", ">", ">", "vals", ")", "{", "Iterator", "<", "Versioned", "<", "byte", "[", "]", ">", ">", "valsIterator", "=", "vals", ".", "iterator", "(", ")", ";", "while", "(", "valsIterator", ".", "hasNext", "(", ")", ")", "{", "Versioned", "<", "byte", "[", "]", ">", "val", "=", "valsIterator", ".", "next", "(", ")", ";", "VectorClock", "clock", "=", "(", "VectorClock", ")", "val", ".", "getVersion", "(", ")", ";", "// omit if expired", "if", "(", "clock", ".", "getTimestamp", "(", ")", "<", "(", "time", ".", "getMilliseconds", "(", ")", "-", "this", ".", "retentionTimeMs", ")", ")", "{", "valsIterator", ".", "remove", "(", ")", ";", "// delete stale value if configured", "if", "(", "deleteExpiredEntries", ")", "{", "getInnerStore", "(", ")", ".", "delete", "(", "key", ",", "clock", ")", ";", "}", "}", "}", "return", "vals", ";", "}" ]
Performs the filtering of the expired entries based on retention time. Optionally, deletes them also @param key the key whose value is to be deleted if needed @param vals set of values to be filtered out @return filtered list of values which are currently valid
[ "Performs", "the", "filtering", "of", "the", "expired", "entries", "based", "on", "retention", "time", ".", "Optionally", "deletes", "them", "also" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/retention/RetentionEnforcingStore.java#L66-L81
161,167
voldemort/voldemort
src/java/voldemort/store/configuration/FileBackedCachingStorageEngine.java
FileBackedCachingStorageEngine.flushData
private synchronized void flushData() { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(new File(this.inputPath))); for(String key: this.metadataMap.keySet()) { writer.write(NEW_PROPERTY_SEPARATOR + key.toString() + "]" + NEW_LINE); writer.write(this.metadataMap.get(key).toString()); writer.write("" + NEW_LINE + "" + NEW_LINE); } writer.flush(); } catch(IOException e) { logger.error("IO exception while flushing data to file backed storage: " + e.getMessage()); } try { if(writer != null) writer.close(); } catch(Exception e) { logger.error("Error while flushing data to file backed storage: " + e.getMessage()); } }
java
private synchronized void flushData() { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(new File(this.inputPath))); for(String key: this.metadataMap.keySet()) { writer.write(NEW_PROPERTY_SEPARATOR + key.toString() + "]" + NEW_LINE); writer.write(this.metadataMap.get(key).toString()); writer.write("" + NEW_LINE + "" + NEW_LINE); } writer.flush(); } catch(IOException e) { logger.error("IO exception while flushing data to file backed storage: " + e.getMessage()); } try { if(writer != null) writer.close(); } catch(Exception e) { logger.error("Error while flushing data to file backed storage: " + e.getMessage()); } }
[ "private", "synchronized", "void", "flushData", "(", ")", "{", "BufferedWriter", "writer", "=", "null", ";", "try", "{", "writer", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "new", "File", "(", "this", ".", "inputPath", ")", ")", ")", ";", "for", "(", "String", "key", ":", "this", ".", "metadataMap", ".", "keySet", "(", ")", ")", "{", "writer", ".", "write", "(", "NEW_PROPERTY_SEPARATOR", "+", "key", ".", "toString", "(", ")", "+", "\"]\"", "+", "NEW_LINE", ")", ";", "writer", ".", "write", "(", "this", ".", "metadataMap", ".", "get", "(", "key", ")", ".", "toString", "(", ")", ")", ";", "writer", ".", "write", "(", "\"\"", "+", "NEW_LINE", "+", "\"\"", "+", "NEW_LINE", ")", ";", "}", "writer", ".", "flush", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"IO exception while flushing data to file backed storage: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "try", "{", "if", "(", "writer", "!=", "null", ")", "writer", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Error while flushing data to file backed storage: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Flush the in-memory data to the file
[ "Flush", "the", "in", "-", "memory", "data", "to", "the", "file" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/configuration/FileBackedCachingStorageEngine.java#L181-L202
161,168
voldemort/voldemort
src/java/voldemort/rest/RestUtils.java
RestUtils.getSerializedVectorClock
public static String getSerializedVectorClock(VectorClock vc) { VectorClockWrapper vcWrapper = new VectorClockWrapper(vc); String serializedVC = ""; try { serializedVC = mapper.writeValueAsString(vcWrapper); } catch(Exception e) { e.printStackTrace(); } return serializedVC; }
java
public static String getSerializedVectorClock(VectorClock vc) { VectorClockWrapper vcWrapper = new VectorClockWrapper(vc); String serializedVC = ""; try { serializedVC = mapper.writeValueAsString(vcWrapper); } catch(Exception e) { e.printStackTrace(); } return serializedVC; }
[ "public", "static", "String", "getSerializedVectorClock", "(", "VectorClock", "vc", ")", "{", "VectorClockWrapper", "vcWrapper", "=", "new", "VectorClockWrapper", "(", "vc", ")", ";", "String", "serializedVC", "=", "\"\"", ";", "try", "{", "serializedVC", "=", "mapper", ".", "writeValueAsString", "(", "vcWrapper", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "serializedVC", ";", "}" ]
Function to serialize the given Vector clock into a string. If something goes wrong, it returns an empty string. @param vc The Vector clock to serialize @return The string (JSON) version of the specified Vector clock
[ "Function", "to", "serialize", "the", "given", "Vector", "clock", "into", "a", "string", ".", "If", "something", "goes", "wrong", "it", "returns", "an", "empty", "string", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestUtils.java#L40-L49
161,169
voldemort/voldemort
src/java/voldemort/rest/RestUtils.java
RestUtils.getSerializedVectorClocks
public static String getSerializedVectorClocks(List<VectorClock> vectorClocks) { List<VectorClockWrapper> vectorClockWrappers = new ArrayList<VectorClockWrapper>(); for(VectorClock vc: vectorClocks) { vectorClockWrappers.add(new VectorClockWrapper(vc)); } String serializedVC = ""; try { serializedVC = mapper.writeValueAsString(vectorClockWrappers); } catch(Exception e) { e.printStackTrace(); } return serializedVC; }
java
public static String getSerializedVectorClocks(List<VectorClock> vectorClocks) { List<VectorClockWrapper> vectorClockWrappers = new ArrayList<VectorClockWrapper>(); for(VectorClock vc: vectorClocks) { vectorClockWrappers.add(new VectorClockWrapper(vc)); } String serializedVC = ""; try { serializedVC = mapper.writeValueAsString(vectorClockWrappers); } catch(Exception e) { e.printStackTrace(); } return serializedVC; }
[ "public", "static", "String", "getSerializedVectorClocks", "(", "List", "<", "VectorClock", ">", "vectorClocks", ")", "{", "List", "<", "VectorClockWrapper", ">", "vectorClockWrappers", "=", "new", "ArrayList", "<", "VectorClockWrapper", ">", "(", ")", ";", "for", "(", "VectorClock", "vc", ":", "vectorClocks", ")", "{", "vectorClockWrappers", ".", "add", "(", "new", "VectorClockWrapper", "(", "vc", ")", ")", ";", "}", "String", "serializedVC", "=", "\"\"", ";", "try", "{", "serializedVC", "=", "mapper", ".", "writeValueAsString", "(", "vectorClockWrappers", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "serializedVC", ";", "}" ]
Function to serialize the given list of Vector clocks into a string. If something goes wrong, it returns an empty string. @param vectorClocks The Vector clock list to serialize @return The string (JSON) version of the specified Vector clock
[ "Function", "to", "serialize", "the", "given", "list", "of", "Vector", "clocks", "into", "a", "string", ".", "If", "something", "goes", "wrong", "it", "returns", "an", "empty", "string", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestUtils.java#L74-L86
161,170
voldemort/voldemort
src/java/voldemort/rest/RestUtils.java
RestUtils.constructSerializerInfoXml
public static String constructSerializerInfoXml(StoreDefinition storeDefinition) { Element store = new Element(StoreDefinitionsMapper.STORE_ELMT); store.addContent(new Element(StoreDefinitionsMapper.STORE_NAME_ELMT).setText(storeDefinition.getName())); Element keySerializer = new Element(StoreDefinitionsMapper.STORE_KEY_SERIALIZER_ELMT); StoreDefinitionsMapper.addSerializer(keySerializer, storeDefinition.getKeySerializer()); store.addContent(keySerializer); Element valueSerializer = new Element(StoreDefinitionsMapper.STORE_VALUE_SERIALIZER_ELMT); StoreDefinitionsMapper.addSerializer(valueSerializer, storeDefinition.getValueSerializer()); store.addContent(valueSerializer); XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat()); return serializer.outputString(store); }
java
public static String constructSerializerInfoXml(StoreDefinition storeDefinition) { Element store = new Element(StoreDefinitionsMapper.STORE_ELMT); store.addContent(new Element(StoreDefinitionsMapper.STORE_NAME_ELMT).setText(storeDefinition.getName())); Element keySerializer = new Element(StoreDefinitionsMapper.STORE_KEY_SERIALIZER_ELMT); StoreDefinitionsMapper.addSerializer(keySerializer, storeDefinition.getKeySerializer()); store.addContent(keySerializer); Element valueSerializer = new Element(StoreDefinitionsMapper.STORE_VALUE_SERIALIZER_ELMT); StoreDefinitionsMapper.addSerializer(valueSerializer, storeDefinition.getValueSerializer()); store.addContent(valueSerializer); XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat()); return serializer.outputString(store); }
[ "public", "static", "String", "constructSerializerInfoXml", "(", "StoreDefinition", "storeDefinition", ")", "{", "Element", "store", "=", "new", "Element", "(", "StoreDefinitionsMapper", ".", "STORE_ELMT", ")", ";", "store", ".", "addContent", "(", "new", "Element", "(", "StoreDefinitionsMapper", ".", "STORE_NAME_ELMT", ")", ".", "setText", "(", "storeDefinition", ".", "getName", "(", ")", ")", ")", ";", "Element", "keySerializer", "=", "new", "Element", "(", "StoreDefinitionsMapper", ".", "STORE_KEY_SERIALIZER_ELMT", ")", ";", "StoreDefinitionsMapper", ".", "addSerializer", "(", "keySerializer", ",", "storeDefinition", ".", "getKeySerializer", "(", ")", ")", ";", "store", ".", "addContent", "(", "keySerializer", ")", ";", "Element", "valueSerializer", "=", "new", "Element", "(", "StoreDefinitionsMapper", ".", "STORE_VALUE_SERIALIZER_ELMT", ")", ";", "StoreDefinitionsMapper", ".", "addSerializer", "(", "valueSerializer", ",", "storeDefinition", ".", "getValueSerializer", "(", ")", ")", ";", "store", ".", "addContent", "(", "valueSerializer", ")", ";", "XMLOutputter", "serializer", "=", "new", "XMLOutputter", "(", "Format", ".", "getPrettyFormat", "(", ")", ")", ";", "return", "serializer", ".", "outputString", "(", "store", ")", ";", "}" ]
Given a storedefinition, constructs the xml string to be sent out in response to a "schemata" fetch request @param storeDefinition @return serialized store definition
[ "Given", "a", "storedefinition", "constructs", "the", "xml", "string", "to", "be", "sent", "out", "in", "response", "to", "a", "schemata", "fetch", "request" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestUtils.java#L119-L132
161,171
voldemort/voldemort
src/java/voldemort/client/scheduler/AsyncMetadataVersionManager.java
AsyncMetadataVersionManager.updateMetadataVersions
public void updateMetadataVersions() { Properties versionProps = MetadataVersionStoreUtils.getProperties(this.systemStoreRepository.getMetadataVersionStore()); Long newVersion = fetchNewVersion(SystemStoreConstants.CLUSTER_VERSION_KEY, null, versionProps); if(newVersion != null) { this.currentClusterVersion = newVersion; } }
java
public void updateMetadataVersions() { Properties versionProps = MetadataVersionStoreUtils.getProperties(this.systemStoreRepository.getMetadataVersionStore()); Long newVersion = fetchNewVersion(SystemStoreConstants.CLUSTER_VERSION_KEY, null, versionProps); if(newVersion != null) { this.currentClusterVersion = newVersion; } }
[ "public", "void", "updateMetadataVersions", "(", ")", "{", "Properties", "versionProps", "=", "MetadataVersionStoreUtils", ".", "getProperties", "(", "this", ".", "systemStoreRepository", ".", "getMetadataVersionStore", "(", ")", ")", ";", "Long", "newVersion", "=", "fetchNewVersion", "(", "SystemStoreConstants", ".", "CLUSTER_VERSION_KEY", ",", "null", ",", "versionProps", ")", ";", "if", "(", "newVersion", "!=", "null", ")", "{", "this", ".", "currentClusterVersion", "=", "newVersion", ";", "}", "}" ]
Fetch the latest versions for cluster metadata
[ "Fetch", "the", "latest", "versions", "for", "cluster", "metadata" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/scheduler/AsyncMetadataVersionManager.java#L203-L211
161,172
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.validateClusterStores
public static void validateClusterStores(final Cluster cluster, final List<StoreDefinition> storeDefs) { // Constructing a StoreRoutingPlan has the (desirable in this // case) side-effect of verifying that the store definition is congruent // with the cluster definition. If there are issues, exceptions are // thrown. for(StoreDefinition storeDefinition: storeDefs) { new StoreRoutingPlan(cluster, storeDefinition); } return; }
java
public static void validateClusterStores(final Cluster cluster, final List<StoreDefinition> storeDefs) { // Constructing a StoreRoutingPlan has the (desirable in this // case) side-effect of verifying that the store definition is congruent // with the cluster definition. If there are issues, exceptions are // thrown. for(StoreDefinition storeDefinition: storeDefs) { new StoreRoutingPlan(cluster, storeDefinition); } return; }
[ "public", "static", "void", "validateClusterStores", "(", "final", "Cluster", "cluster", ",", "final", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "// Constructing a StoreRoutingPlan has the (desirable in this", "// case) side-effect of verifying that the store definition is congruent", "// with the cluster definition. If there are issues, exceptions are", "// thrown.", "for", "(", "StoreDefinition", "storeDefinition", ":", "storeDefs", ")", "{", "new", "StoreRoutingPlan", "(", "cluster", ",", "storeDefinition", ")", ";", "}", "return", ";", "}" ]
Verify store definitions are congruent with cluster definition. @param cluster @param storeDefs
[ "Verify", "store", "definitions", "are", "congruent", "with", "cluster", "definition", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L76-L86
161,173
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.validateCurrentFinalCluster
public static void validateCurrentFinalCluster(final Cluster currentCluster, final Cluster finalCluster) { validateClusterPartitionCounts(currentCluster, finalCluster); validateClusterNodeState(currentCluster, finalCluster); return; }
java
public static void validateCurrentFinalCluster(final Cluster currentCluster, final Cluster finalCluster) { validateClusterPartitionCounts(currentCluster, finalCluster); validateClusterNodeState(currentCluster, finalCluster); return; }
[ "public", "static", "void", "validateCurrentFinalCluster", "(", "final", "Cluster", "currentCluster", ",", "final", "Cluster", "finalCluster", ")", "{", "validateClusterPartitionCounts", "(", "currentCluster", ",", "finalCluster", ")", ";", "validateClusterNodeState", "(", "currentCluster", ",", "finalCluster", ")", ";", "return", ";", "}" ]
A final cluster ought to be a super set of current cluster. I.e., existing node IDs ought to map to same server, but partition layout can have changed and there may exist new nodes. @param currentCluster @param finalCluster
[ "A", "final", "cluster", "ought", "to", "be", "a", "super", "set", "of", "current", "cluster", ".", "I", ".", "e", ".", "existing", "node", "IDs", "ought", "to", "map", "to", "same", "server", "but", "partition", "layout", "can", "have", "changed", "and", "there", "may", "exist", "new", "nodes", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L102-L108
161,174
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.validateInterimFinalCluster
public static void validateInterimFinalCluster(final Cluster interimCluster, final Cluster finalCluster) { validateClusterPartitionCounts(interimCluster, finalCluster); validateClusterZonesSame(interimCluster, finalCluster); validateClusterNodeCounts(interimCluster, finalCluster); validateClusterNodeState(interimCluster, finalCluster); return; }
java
public static void validateInterimFinalCluster(final Cluster interimCluster, final Cluster finalCluster) { validateClusterPartitionCounts(interimCluster, finalCluster); validateClusterZonesSame(interimCluster, finalCluster); validateClusterNodeCounts(interimCluster, finalCluster); validateClusterNodeState(interimCluster, finalCluster); return; }
[ "public", "static", "void", "validateInterimFinalCluster", "(", "final", "Cluster", "interimCluster", ",", "final", "Cluster", "finalCluster", ")", "{", "validateClusterPartitionCounts", "(", "interimCluster", ",", "finalCluster", ")", ";", "validateClusterZonesSame", "(", "interimCluster", ",", "finalCluster", ")", ";", "validateClusterNodeCounts", "(", "interimCluster", ",", "finalCluster", ")", ";", "validateClusterNodeState", "(", "interimCluster", ",", "finalCluster", ")", ";", "return", ";", "}" ]
Interim and final clusters ought to have same partition counts, same zones, and same node state. Partitions per node may of course differ. @param interimCluster @param finalCluster
[ "Interim", "and", "final", "clusters", "ought", "to", "have", "same", "partition", "counts", "same", "zones", "and", "same", "node", "state", ".", "Partitions", "per", "node", "may", "of", "course", "differ", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L135-L142
161,175
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.validateClusterPartitionCounts
public static void validateClusterPartitionCounts(final Cluster lhs, final Cluster rhs) { if(lhs.getNumberOfPartitions() != rhs.getNumberOfPartitions()) throw new VoldemortException("Total number of partitions should be equal [ lhs cluster (" + lhs.getNumberOfPartitions() + ") not equal to rhs cluster (" + rhs.getNumberOfPartitions() + ") ]"); }
java
public static void validateClusterPartitionCounts(final Cluster lhs, final Cluster rhs) { if(lhs.getNumberOfPartitions() != rhs.getNumberOfPartitions()) throw new VoldemortException("Total number of partitions should be equal [ lhs cluster (" + lhs.getNumberOfPartitions() + ") not equal to rhs cluster (" + rhs.getNumberOfPartitions() + ") ]"); }
[ "public", "static", "void", "validateClusterPartitionCounts", "(", "final", "Cluster", "lhs", ",", "final", "Cluster", "rhs", ")", "{", "if", "(", "lhs", ".", "getNumberOfPartitions", "(", ")", "!=", "rhs", ".", "getNumberOfPartitions", "(", ")", ")", "throw", "new", "VoldemortException", "(", "\"Total number of partitions should be equal [ lhs cluster (\"", "+", "lhs", ".", "getNumberOfPartitions", "(", ")", "+", "\") not equal to rhs cluster (\"", "+", "rhs", ".", "getNumberOfPartitions", "(", ")", "+", "\") ]\"", ")", ";", "}" ]
Confirms that both clusters have the same number of total partitions. @param lhs @param rhs
[ "Confirms", "that", "both", "clusters", "have", "the", "same", "number", "of", "total", "partitions", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L150-L156
161,176
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.validateClusterPartitionState
public static void validateClusterPartitionState(final Cluster subsetCluster, final Cluster supersetCluster) { if(!supersetCluster.getNodeIds().containsAll(subsetCluster.getNodeIds())) { throw new VoldemortException("Superset cluster does not contain all nodes from subset cluster[ subset cluster node ids (" + subsetCluster.getNodeIds() + ") are not a subset of superset cluster node ids (" + supersetCluster.getNodeIds() + ") ]"); } for(int nodeId: subsetCluster.getNodeIds()) { Node supersetNode = supersetCluster.getNodeById(nodeId); Node subsetNode = subsetCluster.getNodeById(nodeId); if(!supersetNode.getPartitionIds().equals(subsetNode.getPartitionIds())) { throw new VoldemortRebalancingException("Partition IDs do not match between clusters for nodes with id " + nodeId + " : subset cluster has " + subsetNode.getPartitionIds() + " and superset cluster has " + supersetNode.getPartitionIds()); } } Set<Integer> nodeIds = supersetCluster.getNodeIds(); nodeIds.removeAll(subsetCluster.getNodeIds()); for(int nodeId: nodeIds) { Node supersetNode = supersetCluster.getNodeById(nodeId); if(!supersetNode.getPartitionIds().isEmpty()) { throw new VoldemortRebalancingException("New node " + nodeId + " in superset cluster already has partitions: " + supersetNode.getPartitionIds()); } } }
java
public static void validateClusterPartitionState(final Cluster subsetCluster, final Cluster supersetCluster) { if(!supersetCluster.getNodeIds().containsAll(subsetCluster.getNodeIds())) { throw new VoldemortException("Superset cluster does not contain all nodes from subset cluster[ subset cluster node ids (" + subsetCluster.getNodeIds() + ") are not a subset of superset cluster node ids (" + supersetCluster.getNodeIds() + ") ]"); } for(int nodeId: subsetCluster.getNodeIds()) { Node supersetNode = supersetCluster.getNodeById(nodeId); Node subsetNode = subsetCluster.getNodeById(nodeId); if(!supersetNode.getPartitionIds().equals(subsetNode.getPartitionIds())) { throw new VoldemortRebalancingException("Partition IDs do not match between clusters for nodes with id " + nodeId + " : subset cluster has " + subsetNode.getPartitionIds() + " and superset cluster has " + supersetNode.getPartitionIds()); } } Set<Integer> nodeIds = supersetCluster.getNodeIds(); nodeIds.removeAll(subsetCluster.getNodeIds()); for(int nodeId: nodeIds) { Node supersetNode = supersetCluster.getNodeById(nodeId); if(!supersetNode.getPartitionIds().isEmpty()) { throw new VoldemortRebalancingException("New node " + nodeId + " in superset cluster already has partitions: " + supersetNode.getPartitionIds()); } } }
[ "public", "static", "void", "validateClusterPartitionState", "(", "final", "Cluster", "subsetCluster", ",", "final", "Cluster", "supersetCluster", ")", "{", "if", "(", "!", "supersetCluster", ".", "getNodeIds", "(", ")", ".", "containsAll", "(", "subsetCluster", ".", "getNodeIds", "(", ")", ")", ")", "{", "throw", "new", "VoldemortException", "(", "\"Superset cluster does not contain all nodes from subset cluster[ subset cluster node ids (\"", "+", "subsetCluster", ".", "getNodeIds", "(", ")", "+", "\") are not a subset of superset cluster node ids (\"", "+", "supersetCluster", ".", "getNodeIds", "(", ")", "+", "\") ]\"", ")", ";", "}", "for", "(", "int", "nodeId", ":", "subsetCluster", ".", "getNodeIds", "(", ")", ")", "{", "Node", "supersetNode", "=", "supersetCluster", ".", "getNodeById", "(", "nodeId", ")", ";", "Node", "subsetNode", "=", "subsetCluster", ".", "getNodeById", "(", "nodeId", ")", ";", "if", "(", "!", "supersetNode", ".", "getPartitionIds", "(", ")", ".", "equals", "(", "subsetNode", ".", "getPartitionIds", "(", ")", ")", ")", "{", "throw", "new", "VoldemortRebalancingException", "(", "\"Partition IDs do not match between clusters for nodes with id \"", "+", "nodeId", "+", "\" : subset cluster has \"", "+", "subsetNode", ".", "getPartitionIds", "(", ")", "+", "\" and superset cluster has \"", "+", "supersetNode", ".", "getPartitionIds", "(", ")", ")", ";", "}", "}", "Set", "<", "Integer", ">", "nodeIds", "=", "supersetCluster", ".", "getNodeIds", "(", ")", ";", "nodeIds", ".", "removeAll", "(", "subsetCluster", ".", "getNodeIds", "(", ")", ")", ";", "for", "(", "int", "nodeId", ":", "nodeIds", ")", "{", "Node", "supersetNode", "=", "supersetCluster", ".", "getNodeById", "(", "nodeId", ")", ";", "if", "(", "!", "supersetNode", ".", "getPartitionIds", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "VoldemortRebalancingException", "(", "\"New node \"", "+", "nodeId", "+", "\" in superset cluster already has partitions: \"", "+", "supersetNode", ".", "getPartitionIds", "(", ")", ")", ";", "}", "}", "}" ]
Confirm that all nodes shared between clusters host exact same partition IDs and that nodes only in the super set cluster have no partition IDs. @param subsetCluster @param supersetCluster
[ "Confirm", "that", "all", "nodes", "shared", "between", "clusters", "host", "exact", "same", "partition", "IDs", "and", "that", "nodes", "only", "in", "the", "super", "set", "cluster", "have", "no", "partition", "IDs", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L165-L197
161,177
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.validateClusterZonesSame
public static void validateClusterZonesSame(final Cluster lhs, final Cluster rhs) { Set<Zone> lhsSet = new HashSet<Zone>(lhs.getZones()); Set<Zone> rhsSet = new HashSet<Zone>(rhs.getZones()); if(!lhsSet.equals(rhsSet)) throw new VoldemortException("Zones are not the same [ lhs cluster zones (" + lhs.getZones() + ") not equal to rhs cluster zones (" + rhs.getZones() + ") ]"); }
java
public static void validateClusterZonesSame(final Cluster lhs, final Cluster rhs) { Set<Zone> lhsSet = new HashSet<Zone>(lhs.getZones()); Set<Zone> rhsSet = new HashSet<Zone>(rhs.getZones()); if(!lhsSet.equals(rhsSet)) throw new VoldemortException("Zones are not the same [ lhs cluster zones (" + lhs.getZones() + ") not equal to rhs cluster zones (" + rhs.getZones() + ") ]"); }
[ "public", "static", "void", "validateClusterZonesSame", "(", "final", "Cluster", "lhs", ",", "final", "Cluster", "rhs", ")", "{", "Set", "<", "Zone", ">", "lhsSet", "=", "new", "HashSet", "<", "Zone", ">", "(", "lhs", ".", "getZones", "(", ")", ")", ";", "Set", "<", "Zone", ">", "rhsSet", "=", "new", "HashSet", "<", "Zone", ">", "(", "rhs", ".", "getZones", "(", ")", ")", ";", "if", "(", "!", "lhsSet", ".", "equals", "(", "rhsSet", ")", ")", "throw", "new", "VoldemortException", "(", "\"Zones are not the same [ lhs cluster zones (\"", "+", "lhs", ".", "getZones", "(", ")", "+", "\") not equal to rhs cluster zones (\"", "+", "rhs", ".", "getZones", "(", ")", "+", "\") ]\"", ")", ";", "}" ]
Confirms that both clusters have the same set of zones defined. @param lhs @param rhs
[ "Confirms", "that", "both", "clusters", "have", "the", "same", "set", "of", "zones", "defined", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L205-L212
161,178
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.validateClusterNodeCounts
public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) { if(!lhs.getNodeIds().equals(rhs.getNodeIds())) { throw new VoldemortException("Node ids are not the same [ lhs cluster node ids (" + lhs.getNodeIds() + ") not equal to rhs cluster node ids (" + rhs.getNodeIds() + ") ]"); } }
java
public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) { if(!lhs.getNodeIds().equals(rhs.getNodeIds())) { throw new VoldemortException("Node ids are not the same [ lhs cluster node ids (" + lhs.getNodeIds() + ") not equal to rhs cluster node ids (" + rhs.getNodeIds() + ") ]"); } }
[ "public", "static", "void", "validateClusterNodeCounts", "(", "final", "Cluster", "lhs", ",", "final", "Cluster", "rhs", ")", "{", "if", "(", "!", "lhs", ".", "getNodeIds", "(", ")", ".", "equals", "(", "rhs", ".", "getNodeIds", "(", ")", ")", ")", "{", "throw", "new", "VoldemortException", "(", "\"Node ids are not the same [ lhs cluster node ids (\"", "+", "lhs", ".", "getNodeIds", "(", ")", "+", "\") not equal to rhs cluster node ids (\"", "+", "rhs", ".", "getNodeIds", "(", ")", "+", "\") ]\"", ")", ";", "}", "}" ]
Confirms that both clusters have the same number of nodes by comparing set of node Ids between clusters. @param lhs @param rhs
[ "Confirms", "that", "both", "clusters", "have", "the", "same", "number", "of", "nodes", "by", "comparing", "set", "of", "node", "Ids", "between", "clusters", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L221-L228
161,179
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.vacateZone
public static Cluster vacateZone(Cluster currentCluster, int dropZoneId) { Cluster returnCluster = Cluster.cloneCluster(currentCluster); // Go over each node in the zone being dropped for(Integer nodeId: currentCluster.getNodeIdsInZone(dropZoneId)) { // For each node grab all the partitions it hosts for(Integer partitionId: currentCluster.getNodeById(nodeId).getPartitionIds()) { // Now for each partition find a new home..which would be a node // in one of the existing zones int finalZoneId = -1; int finalNodeId = -1; int adjacentPartitionId = partitionId; do { adjacentPartitionId = (adjacentPartitionId + 1) % currentCluster.getNumberOfPartitions(); finalNodeId = currentCluster.getNodeForPartitionId(adjacentPartitionId).getId(); finalZoneId = currentCluster.getZoneForPartitionId(adjacentPartitionId).getId(); if(adjacentPartitionId == partitionId) { logger.error("PartitionId " + partitionId + "stays unchanged \n"); } else { logger.info("PartitionId " + partitionId + " goes together with partition " + adjacentPartitionId + " on node " + finalNodeId + " in zone " + finalZoneId); returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster, finalNodeId, Lists.newArrayList(partitionId)); } } while(finalZoneId == dropZoneId); } } return returnCluster; }
java
public static Cluster vacateZone(Cluster currentCluster, int dropZoneId) { Cluster returnCluster = Cluster.cloneCluster(currentCluster); // Go over each node in the zone being dropped for(Integer nodeId: currentCluster.getNodeIdsInZone(dropZoneId)) { // For each node grab all the partitions it hosts for(Integer partitionId: currentCluster.getNodeById(nodeId).getPartitionIds()) { // Now for each partition find a new home..which would be a node // in one of the existing zones int finalZoneId = -1; int finalNodeId = -1; int adjacentPartitionId = partitionId; do { adjacentPartitionId = (adjacentPartitionId + 1) % currentCluster.getNumberOfPartitions(); finalNodeId = currentCluster.getNodeForPartitionId(adjacentPartitionId).getId(); finalZoneId = currentCluster.getZoneForPartitionId(adjacentPartitionId).getId(); if(adjacentPartitionId == partitionId) { logger.error("PartitionId " + partitionId + "stays unchanged \n"); } else { logger.info("PartitionId " + partitionId + " goes together with partition " + adjacentPartitionId + " on node " + finalNodeId + " in zone " + finalZoneId); returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster, finalNodeId, Lists.newArrayList(partitionId)); } } while(finalZoneId == dropZoneId); } } return returnCluster; }
[ "public", "static", "Cluster", "vacateZone", "(", "Cluster", "currentCluster", ",", "int", "dropZoneId", ")", "{", "Cluster", "returnCluster", "=", "Cluster", ".", "cloneCluster", "(", "currentCluster", ")", ";", "// Go over each node in the zone being dropped", "for", "(", "Integer", "nodeId", ":", "currentCluster", ".", "getNodeIdsInZone", "(", "dropZoneId", ")", ")", "{", "// For each node grab all the partitions it hosts", "for", "(", "Integer", "partitionId", ":", "currentCluster", ".", "getNodeById", "(", "nodeId", ")", ".", "getPartitionIds", "(", ")", ")", "{", "// Now for each partition find a new home..which would be a node", "// in one of the existing zones", "int", "finalZoneId", "=", "-", "1", ";", "int", "finalNodeId", "=", "-", "1", ";", "int", "adjacentPartitionId", "=", "partitionId", ";", "do", "{", "adjacentPartitionId", "=", "(", "adjacentPartitionId", "+", "1", ")", "%", "currentCluster", ".", "getNumberOfPartitions", "(", ")", ";", "finalNodeId", "=", "currentCluster", ".", "getNodeForPartitionId", "(", "adjacentPartitionId", ")", ".", "getId", "(", ")", ";", "finalZoneId", "=", "currentCluster", ".", "getZoneForPartitionId", "(", "adjacentPartitionId", ")", ".", "getId", "(", ")", ";", "if", "(", "adjacentPartitionId", "==", "partitionId", ")", "{", "logger", ".", "error", "(", "\"PartitionId \"", "+", "partitionId", "+", "\"stays unchanged \\n\"", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "\"PartitionId \"", "+", "partitionId", "+", "\" goes together with partition \"", "+", "adjacentPartitionId", "+", "\" on node \"", "+", "finalNodeId", "+", "\" in zone \"", "+", "finalZoneId", ")", ";", "returnCluster", "=", "UpdateClusterUtils", ".", "createUpdatedCluster", "(", "returnCluster", ",", "finalNodeId", ",", "Lists", ".", "newArrayList", "(", "partitionId", ")", ")", ";", "}", "}", "while", "(", "finalZoneId", "==", "dropZoneId", ")", ";", "}", "}", "return", "returnCluster", ";", "}" ]
Given the current cluster and a zone id that needs to be dropped, this method will remove all partitions from the zone that is being dropped and move it to the existing zones. The partitions are moved intelligently so as not to avoid any data movement in the existing zones. This is achieved by moving the partitions to nodes in the surviving zones that is zone-nry to that partition in the surviving zone. @param currentCluster Current cluster metadata @return Returns an interim cluster with empty partition lists on the nodes from the zone being dropped
[ "Given", "the", "current", "cluster", "and", "a", "zone", "id", "that", "needs", "to", "be", "dropped", "this", "method", "will", "remove", "all", "partitions", "from", "the", "zone", "that", "is", "being", "dropped", "and", "move", "it", "to", "the", "existing", "zones", ".", "The", "partitions", "are", "moved", "intelligently", "so", "as", "not", "to", "avoid", "any", "data", "movement", "in", "the", "existing", "zones", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L295-L325
161,180
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.dropZone
public static Cluster dropZone(Cluster intermediateCluster, int dropZoneId) { // Filter out nodes that don't belong to the zone being dropped Set<Node> survivingNodes = new HashSet<Node>(); for(int nodeId: intermediateCluster.getNodeIds()) { if(intermediateCluster.getNodeById(nodeId).getZoneId() != dropZoneId) { survivingNodes.add(intermediateCluster.getNodeById(nodeId)); } } // Filter out dropZoneId from all zones Set<Zone> zones = new HashSet<Zone>(); for(int zoneId: intermediateCluster.getZoneIds()) { if(zoneId == dropZoneId) { continue; } List<Integer> proximityList = intermediateCluster.getZoneById(zoneId) .getProximityList(); proximityList.remove(new Integer(dropZoneId)); zones.add(new Zone(zoneId, proximityList)); } return new Cluster(intermediateCluster.getName(), Utils.asSortedList(survivingNodes), Utils.asSortedList(zones)); }
java
public static Cluster dropZone(Cluster intermediateCluster, int dropZoneId) { // Filter out nodes that don't belong to the zone being dropped Set<Node> survivingNodes = new HashSet<Node>(); for(int nodeId: intermediateCluster.getNodeIds()) { if(intermediateCluster.getNodeById(nodeId).getZoneId() != dropZoneId) { survivingNodes.add(intermediateCluster.getNodeById(nodeId)); } } // Filter out dropZoneId from all zones Set<Zone> zones = new HashSet<Zone>(); for(int zoneId: intermediateCluster.getZoneIds()) { if(zoneId == dropZoneId) { continue; } List<Integer> proximityList = intermediateCluster.getZoneById(zoneId) .getProximityList(); proximityList.remove(new Integer(dropZoneId)); zones.add(new Zone(zoneId, proximityList)); } return new Cluster(intermediateCluster.getName(), Utils.asSortedList(survivingNodes), Utils.asSortedList(zones)); }
[ "public", "static", "Cluster", "dropZone", "(", "Cluster", "intermediateCluster", ",", "int", "dropZoneId", ")", "{", "// Filter out nodes that don't belong to the zone being dropped", "Set", "<", "Node", ">", "survivingNodes", "=", "new", "HashSet", "<", "Node", ">", "(", ")", ";", "for", "(", "int", "nodeId", ":", "intermediateCluster", ".", "getNodeIds", "(", ")", ")", "{", "if", "(", "intermediateCluster", ".", "getNodeById", "(", "nodeId", ")", ".", "getZoneId", "(", ")", "!=", "dropZoneId", ")", "{", "survivingNodes", ".", "add", "(", "intermediateCluster", ".", "getNodeById", "(", "nodeId", ")", ")", ";", "}", "}", "// Filter out dropZoneId from all zones", "Set", "<", "Zone", ">", "zones", "=", "new", "HashSet", "<", "Zone", ">", "(", ")", ";", "for", "(", "int", "zoneId", ":", "intermediateCluster", ".", "getZoneIds", "(", ")", ")", "{", "if", "(", "zoneId", "==", "dropZoneId", ")", "{", "continue", ";", "}", "List", "<", "Integer", ">", "proximityList", "=", "intermediateCluster", ".", "getZoneById", "(", "zoneId", ")", ".", "getProximityList", "(", ")", ";", "proximityList", ".", "remove", "(", "new", "Integer", "(", "dropZoneId", ")", ")", ";", "zones", ".", "add", "(", "new", "Zone", "(", "zoneId", ",", "proximityList", ")", ")", ";", "}", "return", "new", "Cluster", "(", "intermediateCluster", ".", "getName", "(", ")", ",", "Utils", ".", "asSortedList", "(", "survivingNodes", ")", ",", "Utils", ".", "asSortedList", "(", "zones", ")", ")", ";", "}" ]
Given a interim cluster with a previously vacated zone, constructs a new cluster object with the drop zone completely removed @param intermediateCluster @param dropZoneId @return adjusted cluster with the zone dropped
[ "Given", "a", "interim", "cluster", "with", "a", "previously", "vacated", "zone", "constructs", "a", "new", "cluster", "object", "with", "the", "drop", "zone", "completely", "removed" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L335-L359
161,181
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.getStolenPrimaryPartitions
public static List<Integer> getStolenPrimaryPartitions(final Cluster currentCluster, final Cluster finalCluster, final int stealNodeId) { List<Integer> finalList = new ArrayList<Integer>(finalCluster.getNodeById(stealNodeId) .getPartitionIds()); List<Integer> currentList = new ArrayList<Integer>(); if(currentCluster.hasNodeWithId(stealNodeId)) { currentList = currentCluster.getNodeById(stealNodeId).getPartitionIds(); } else { if(logger.isDebugEnabled()) { logger.debug("Current cluster does not contain stealer node (cluster : [[[" + currentCluster + "]]], node id " + stealNodeId + ")"); } } finalList.removeAll(currentList); return finalList; }
java
public static List<Integer> getStolenPrimaryPartitions(final Cluster currentCluster, final Cluster finalCluster, final int stealNodeId) { List<Integer> finalList = new ArrayList<Integer>(finalCluster.getNodeById(stealNodeId) .getPartitionIds()); List<Integer> currentList = new ArrayList<Integer>(); if(currentCluster.hasNodeWithId(stealNodeId)) { currentList = currentCluster.getNodeById(stealNodeId).getPartitionIds(); } else { if(logger.isDebugEnabled()) { logger.debug("Current cluster does not contain stealer node (cluster : [[[" + currentCluster + "]]], node id " + stealNodeId + ")"); } } finalList.removeAll(currentList); return finalList; }
[ "public", "static", "List", "<", "Integer", ">", "getStolenPrimaryPartitions", "(", "final", "Cluster", "currentCluster", ",", "final", "Cluster", "finalCluster", ",", "final", "int", "stealNodeId", ")", "{", "List", "<", "Integer", ">", "finalList", "=", "new", "ArrayList", "<", "Integer", ">", "(", "finalCluster", ".", "getNodeById", "(", "stealNodeId", ")", ".", "getPartitionIds", "(", ")", ")", ";", "List", "<", "Integer", ">", "currentList", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "if", "(", "currentCluster", ".", "hasNodeWithId", "(", "stealNodeId", ")", ")", "{", "currentList", "=", "currentCluster", ".", "getNodeById", "(", "stealNodeId", ")", ".", "getPartitionIds", "(", ")", ";", "}", "else", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Current cluster does not contain stealer node (cluster : [[[\"", "+", "currentCluster", "+", "\"]]], node id \"", "+", "stealNodeId", "+", "\")\"", ")", ";", "}", "}", "finalList", ".", "removeAll", "(", "currentList", ")", ";", "return", "finalList", ";", "}" ]
For a particular stealer node find all the primary partitions tuples it will steal. @param currentCluster The cluster definition of the existing cluster @param finalCluster The final cluster definition @param stealNodeId Node id of the stealer node @return Returns a list of primary partitions which this stealer node will get
[ "For", "a", "particular", "stealer", "node", "find", "all", "the", "primary", "partitions", "tuples", "it", "will", "steal", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L425-L443
161,182
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.validateRebalanceStore
public static List<StoreDefinition> validateRebalanceStore(List<StoreDefinition> storeDefList) { List<StoreDefinition> returnList = new ArrayList<StoreDefinition>(storeDefList.size()); for(StoreDefinition def: storeDefList) { if(!def.isView() && !canRebalanceList.contains(def.getType())) { throw new VoldemortException("Rebalance does not support rebalancing of stores of type " + def.getType() + " - " + def.getName()); } else if(!def.isView()) { returnList.add(def); } else { logger.debug("Ignoring view " + def.getName() + " for rebalancing"); } } return returnList; }
java
public static List<StoreDefinition> validateRebalanceStore(List<StoreDefinition> storeDefList) { List<StoreDefinition> returnList = new ArrayList<StoreDefinition>(storeDefList.size()); for(StoreDefinition def: storeDefList) { if(!def.isView() && !canRebalanceList.contains(def.getType())) { throw new VoldemortException("Rebalance does not support rebalancing of stores of type " + def.getType() + " - " + def.getName()); } else if(!def.isView()) { returnList.add(def); } else { logger.debug("Ignoring view " + def.getName() + " for rebalancing"); } } return returnList; }
[ "public", "static", "List", "<", "StoreDefinition", ">", "validateRebalanceStore", "(", "List", "<", "StoreDefinition", ">", "storeDefList", ")", "{", "List", "<", "StoreDefinition", ">", "returnList", "=", "new", "ArrayList", "<", "StoreDefinition", ">", "(", "storeDefList", ".", "size", "(", ")", ")", ";", "for", "(", "StoreDefinition", "def", ":", "storeDefList", ")", "{", "if", "(", "!", "def", ".", "isView", "(", ")", "&&", "!", "canRebalanceList", ".", "contains", "(", "def", ".", "getType", "(", ")", ")", ")", "{", "throw", "new", "VoldemortException", "(", "\"Rebalance does not support rebalancing of stores of type \"", "+", "def", ".", "getType", "(", ")", "+", "\" - \"", "+", "def", ".", "getName", "(", ")", ")", ";", "}", "else", "if", "(", "!", "def", ".", "isView", "(", ")", ")", "{", "returnList", ".", "add", "(", "def", ")", ";", "}", "else", "{", "logger", ".", "debug", "(", "\"Ignoring view \"", "+", "def", ".", "getName", "(", ")", "+", "\" for rebalancing\"", ")", ";", "}", "}", "return", "returnList", ";", "}" ]
Given a list of store definitions, makes sure that rebalance supports all of them. If not it throws an error. @param storeDefList List of store definitions @return Filtered list of store definitions which rebalancing supports
[ "Given", "a", "list", "of", "store", "definitions", "makes", "sure", "that", "rebalance", "supports", "all", "of", "them", ".", "If", "not", "it", "throws", "an", "error", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L490-L504
161,183
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.dumpClusters
public static void dumpClusters(Cluster currentCluster, Cluster finalCluster, String outputDirName, String filePrefix) { dumpClusterToFile(outputDirName, filePrefix + currentClusterFileName, currentCluster); dumpClusterToFile(outputDirName, filePrefix + finalClusterFileName, finalCluster); }
java
public static void dumpClusters(Cluster currentCluster, Cluster finalCluster, String outputDirName, String filePrefix) { dumpClusterToFile(outputDirName, filePrefix + currentClusterFileName, currentCluster); dumpClusterToFile(outputDirName, filePrefix + finalClusterFileName, finalCluster); }
[ "public", "static", "void", "dumpClusters", "(", "Cluster", "currentCluster", ",", "Cluster", "finalCluster", ",", "String", "outputDirName", ",", "String", "filePrefix", ")", "{", "dumpClusterToFile", "(", "outputDirName", ",", "filePrefix", "+", "currentClusterFileName", ",", "currentCluster", ")", ";", "dumpClusterToFile", "(", "outputDirName", ",", "filePrefix", "+", "finalClusterFileName", ",", "finalCluster", ")", ";", "}" ]
Given the initial and final cluster dumps it into the output directory @param currentCluster Initial cluster metadata @param finalCluster Final cluster metadata @param outputDirName Output directory where to dump this file @param filePrefix String to prepend to the initial & final cluster metadata files @throws IOException
[ "Given", "the", "initial", "and", "final", "cluster", "dumps", "it", "into", "the", "output", "directory" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L516-L522
161,184
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.dumpClusters
public static void dumpClusters(Cluster currentCluster, Cluster finalCluster, String outputDirName) { dumpClusters(currentCluster, finalCluster, outputDirName, ""); }
java
public static void dumpClusters(Cluster currentCluster, Cluster finalCluster, String outputDirName) { dumpClusters(currentCluster, finalCluster, outputDirName, ""); }
[ "public", "static", "void", "dumpClusters", "(", "Cluster", "currentCluster", ",", "Cluster", "finalCluster", ",", "String", "outputDirName", ")", "{", "dumpClusters", "(", "currentCluster", ",", "finalCluster", ",", "outputDirName", ",", "\"\"", ")", ";", "}" ]
Given the current and final cluster dumps it into the output directory @param currentCluster Initial cluster metadata @param finalCluster Final cluster metadata @param outputDirName Output directory where to dump this file @throws IOException
[ "Given", "the", "current", "and", "final", "cluster", "dumps", "it", "into", "the", "output", "directory" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L532-L536
161,185
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.dumpClusterToFile
public static void dumpClusterToFile(String outputDirName, String fileName, Cluster cluster) { if(outputDirName != null) { File outputDir = new File(outputDirName); if(!outputDir.exists()) { Utils.mkdirs(outputDir); } try { FileUtils.writeStringToFile(new File(outputDirName, fileName), new ClusterMapper().writeCluster(cluster)); } catch(IOException e) { logger.error("IOException during dumpClusterToFile: " + e); } } }
java
public static void dumpClusterToFile(String outputDirName, String fileName, Cluster cluster) { if(outputDirName != null) { File outputDir = new File(outputDirName); if(!outputDir.exists()) { Utils.mkdirs(outputDir); } try { FileUtils.writeStringToFile(new File(outputDirName, fileName), new ClusterMapper().writeCluster(cluster)); } catch(IOException e) { logger.error("IOException during dumpClusterToFile: " + e); } } }
[ "public", "static", "void", "dumpClusterToFile", "(", "String", "outputDirName", ",", "String", "fileName", ",", "Cluster", "cluster", ")", "{", "if", "(", "outputDirName", "!=", "null", ")", "{", "File", "outputDir", "=", "new", "File", "(", "outputDirName", ")", ";", "if", "(", "!", "outputDir", ".", "exists", "(", ")", ")", "{", "Utils", ".", "mkdirs", "(", "outputDir", ")", ";", "}", "try", "{", "FileUtils", ".", "writeStringToFile", "(", "new", "File", "(", "outputDirName", ",", "fileName", ")", ",", "new", "ClusterMapper", "(", ")", ".", "writeCluster", "(", "cluster", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"IOException during dumpClusterToFile: \"", "+", "e", ")", ";", "}", "}", "}" ]
Prints a cluster xml to a file. @param outputDirName @param fileName @param cluster
[ "Prints", "a", "cluster", "xml", "to", "a", "file", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L545-L560
161,186
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.dumpStoreDefsToFile
public static void dumpStoreDefsToFile(String outputDirName, String fileName, List<StoreDefinition> storeDefs) { if(outputDirName != null) { File outputDir = new File(outputDirName); if(!outputDir.exists()) { Utils.mkdirs(outputDir); } try { FileUtils.writeStringToFile(new File(outputDirName, fileName), new StoreDefinitionsMapper().writeStoreList(storeDefs)); } catch(IOException e) { logger.error("IOException during dumpStoreDefsToFile: " + e); } } }
java
public static void dumpStoreDefsToFile(String outputDirName, String fileName, List<StoreDefinition> storeDefs) { if(outputDirName != null) { File outputDir = new File(outputDirName); if(!outputDir.exists()) { Utils.mkdirs(outputDir); } try { FileUtils.writeStringToFile(new File(outputDirName, fileName), new StoreDefinitionsMapper().writeStoreList(storeDefs)); } catch(IOException e) { logger.error("IOException during dumpStoreDefsToFile: " + e); } } }
[ "public", "static", "void", "dumpStoreDefsToFile", "(", "String", "outputDirName", ",", "String", "fileName", ",", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "if", "(", "outputDirName", "!=", "null", ")", "{", "File", "outputDir", "=", "new", "File", "(", "outputDirName", ")", ";", "if", "(", "!", "outputDir", ".", "exists", "(", ")", ")", "{", "Utils", ".", "mkdirs", "(", "outputDir", ")", ";", "}", "try", "{", "FileUtils", ".", "writeStringToFile", "(", "new", "File", "(", "outputDirName", ",", "fileName", ")", ",", "new", "StoreDefinitionsMapper", "(", ")", ".", "writeStoreList", "(", "storeDefs", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"IOException during dumpStoreDefsToFile: \"", "+", "e", ")", ";", "}", "}", "}" ]
Prints a stores xml to a file. @param outputDirName @param fileName @param list of storeDefs
[ "Prints", "a", "stores", "xml", "to", "a", "file", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L569-L586
161,187
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.dumpAnalysisToFile
public static void dumpAnalysisToFile(String outputDirName, String baseFileName, PartitionBalance partitionBalance) { if(outputDirName != null) { File outputDir = new File(outputDirName); if(!outputDir.exists()) { Utils.mkdirs(outputDir); } try { FileUtils.writeStringToFile(new File(outputDirName, baseFileName + ".analysis"), partitionBalance.toString()); } catch(IOException e) { logger.error("IOException during dumpAnalysisToFile: " + e); } } }
java
public static void dumpAnalysisToFile(String outputDirName, String baseFileName, PartitionBalance partitionBalance) { if(outputDirName != null) { File outputDir = new File(outputDirName); if(!outputDir.exists()) { Utils.mkdirs(outputDir); } try { FileUtils.writeStringToFile(new File(outputDirName, baseFileName + ".analysis"), partitionBalance.toString()); } catch(IOException e) { logger.error("IOException during dumpAnalysisToFile: " + e); } } }
[ "public", "static", "void", "dumpAnalysisToFile", "(", "String", "outputDirName", ",", "String", "baseFileName", ",", "PartitionBalance", "partitionBalance", ")", "{", "if", "(", "outputDirName", "!=", "null", ")", "{", "File", "outputDir", "=", "new", "File", "(", "outputDirName", ")", ";", "if", "(", "!", "outputDir", ".", "exists", "(", ")", ")", "{", "Utils", ".", "mkdirs", "(", "outputDir", ")", ";", "}", "try", "{", "FileUtils", ".", "writeStringToFile", "(", "new", "File", "(", "outputDirName", ",", "baseFileName", "+", "\".analysis\"", ")", ",", "partitionBalance", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"IOException during dumpAnalysisToFile: \"", "+", "e", ")", ";", "}", "}", "}" ]
Prints a balance analysis to a file. @param outputDirName @param baseFileName suffix '.analysis' is appended to baseFileName. @param partitionBalance
[ "Prints", "a", "balance", "analysis", "to", "a", "file", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L595-L611
161,188
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.dumpPlanToFile
public static void dumpPlanToFile(String outputDirName, RebalancePlan plan) { if(outputDirName != null) { File outputDir = new File(outputDirName); if(!outputDir.exists()) { Utils.mkdirs(outputDir); } try { FileUtils.writeStringToFile(new File(outputDirName, "plan.out"), plan.toString()); } catch(IOException e) { logger.error("IOException during dumpPlanToFile: " + e); } } }
java
public static void dumpPlanToFile(String outputDirName, RebalancePlan plan) { if(outputDirName != null) { File outputDir = new File(outputDirName); if(!outputDir.exists()) { Utils.mkdirs(outputDir); } try { FileUtils.writeStringToFile(new File(outputDirName, "plan.out"), plan.toString()); } catch(IOException e) { logger.error("IOException during dumpPlanToFile: " + e); } } }
[ "public", "static", "void", "dumpPlanToFile", "(", "String", "outputDirName", ",", "RebalancePlan", "plan", ")", "{", "if", "(", "outputDirName", "!=", "null", ")", "{", "File", "outputDir", "=", "new", "File", "(", "outputDirName", ")", ";", "if", "(", "!", "outputDir", ".", "exists", "(", ")", ")", "{", "Utils", ".", "mkdirs", "(", "outputDir", ")", ";", "}", "try", "{", "FileUtils", ".", "writeStringToFile", "(", "new", "File", "(", "outputDirName", ",", "\"plan.out\"", ")", ",", "plan", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"IOException during dumpPlanToFile: \"", "+", "e", ")", ";", "}", "}", "}" ]
Prints the plan to a file. @param outputDirName @param plan
[ "Prints", "the", "plan", "to", "a", "file", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L619-L631
161,189
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.filterTaskPlanWithStores
public static List<RebalanceTaskInfo> filterTaskPlanWithStores(List<RebalanceTaskInfo> existingPlanList, List<StoreDefinition> storeDefs) { List<RebalanceTaskInfo> plans = Lists.newArrayList(); List<String> storeNames = StoreDefinitionUtils.getStoreNames(storeDefs); for(RebalanceTaskInfo existingPlan: existingPlanList) { RebalanceTaskInfo info = RebalanceTaskInfo.create(existingPlan.toJsonString()); // Filter the plans only for stores given HashMap<String, List<Integer>> storeToPartitions = info.getStoreToPartitionIds(); HashMap<String, List<Integer>> newStoreToPartitions = Maps.newHashMap(); for(String storeName: storeNames) { if(storeToPartitions.containsKey(storeName)) newStoreToPartitions.put(storeName, storeToPartitions.get(storeName)); } info.setStoreToPartitionList(newStoreToPartitions); plans.add(info); } return plans; }
java
public static List<RebalanceTaskInfo> filterTaskPlanWithStores(List<RebalanceTaskInfo> existingPlanList, List<StoreDefinition> storeDefs) { List<RebalanceTaskInfo> plans = Lists.newArrayList(); List<String> storeNames = StoreDefinitionUtils.getStoreNames(storeDefs); for(RebalanceTaskInfo existingPlan: existingPlanList) { RebalanceTaskInfo info = RebalanceTaskInfo.create(existingPlan.toJsonString()); // Filter the plans only for stores given HashMap<String, List<Integer>> storeToPartitions = info.getStoreToPartitionIds(); HashMap<String, List<Integer>> newStoreToPartitions = Maps.newHashMap(); for(String storeName: storeNames) { if(storeToPartitions.containsKey(storeName)) newStoreToPartitions.put(storeName, storeToPartitions.get(storeName)); } info.setStoreToPartitionList(newStoreToPartitions); plans.add(info); } return plans; }
[ "public", "static", "List", "<", "RebalanceTaskInfo", ">", "filterTaskPlanWithStores", "(", "List", "<", "RebalanceTaskInfo", ">", "existingPlanList", ",", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "List", "<", "RebalanceTaskInfo", ">", "plans", "=", "Lists", ".", "newArrayList", "(", ")", ";", "List", "<", "String", ">", "storeNames", "=", "StoreDefinitionUtils", ".", "getStoreNames", "(", "storeDefs", ")", ";", "for", "(", "RebalanceTaskInfo", "existingPlan", ":", "existingPlanList", ")", "{", "RebalanceTaskInfo", "info", "=", "RebalanceTaskInfo", ".", "create", "(", "existingPlan", ".", "toJsonString", "(", ")", ")", ";", "// Filter the plans only for stores given", "HashMap", "<", "String", ",", "List", "<", "Integer", ">", ">", "storeToPartitions", "=", "info", ".", "getStoreToPartitionIds", "(", ")", ";", "HashMap", "<", "String", ",", "List", "<", "Integer", ">", ">", "newStoreToPartitions", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "String", "storeName", ":", "storeNames", ")", "{", "if", "(", "storeToPartitions", ".", "containsKey", "(", "storeName", ")", ")", "newStoreToPartitions", ".", "put", "(", "storeName", ",", "storeToPartitions", ".", "get", "(", "storeName", ")", ")", ";", "}", "info", ".", "setStoreToPartitionList", "(", "newStoreToPartitions", ")", ";", "plans", ".", "add", "(", "info", ")", ";", "}", "return", "plans", ";", "}" ]
Given a list of partition plans and a set of stores, copies the store names to every individual plan and creates a new list @param existingPlanList Existing partition plan list @param storeDefs List of store names we are rebalancing @return List of updated partition plan
[ "Given", "a", "list", "of", "partition", "plans", "and", "a", "set", "of", "stores", "copies", "the", "store", "names", "to", "every", "individual", "plan", "and", "creates", "a", "new", "list" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L649-L669
161,190
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.executorShutDown
public static void executorShutDown(ExecutorService executorService, long timeOutSec) { try { executorService.shutdown(); executorService.awaitTermination(timeOutSec, TimeUnit.SECONDS); } catch(Exception e) { logger.warn("Error while stoping executor service.", e); } }
java
public static void executorShutDown(ExecutorService executorService, long timeOutSec) { try { executorService.shutdown(); executorService.awaitTermination(timeOutSec, TimeUnit.SECONDS); } catch(Exception e) { logger.warn("Error while stoping executor service.", e); } }
[ "public", "static", "void", "executorShutDown", "(", "ExecutorService", "executorService", ",", "long", "timeOutSec", ")", "{", "try", "{", "executorService", ".", "shutdown", "(", ")", ";", "executorService", ".", "awaitTermination", "(", "timeOutSec", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "warn", "(", "\"Error while stoping executor service.\"", ",", "e", ")", ";", "}", "}" ]
Wait to shutdown service @param executorService Executor service to shutdown @param timeOutSec Time we wait for
[ "Wait", "to", "shutdown", "service" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L704-L711
161,191
voldemort/voldemort
src/java/voldemort/versioning/ArbitraryInconsistencyResolver.java
ArbitraryInconsistencyResolver.resolveConflicts
public List<T> resolveConflicts(List<T> values) { if(values.size() > 1) return values; else return Collections.singletonList(values.get(0)); }
java
public List<T> resolveConflicts(List<T> values) { if(values.size() > 1) return values; else return Collections.singletonList(values.get(0)); }
[ "public", "List", "<", "T", ">", "resolveConflicts", "(", "List", "<", "T", ">", "values", ")", "{", "if", "(", "values", ".", "size", "(", ")", ">", "1", ")", "return", "values", ";", "else", "return", "Collections", ".", "singletonList", "(", "values", ".", "get", "(", "0", ")", ")", ";", "}" ]
Arbitrarily resolve the inconsistency by choosing the first object if there is one. @param values The list of objects @return A single value, if one exists, taken from the input list.
[ "Arbitrarily", "resolve", "the", "inconsistency", "by", "choosing", "the", "first", "object", "if", "there", "is", "one", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/versioning/ArbitraryInconsistencyResolver.java#L37-L42
161,192
voldemort/voldemort
src/java/voldemort/store/StoreUtils.java
StoreUtils.get
public static <K, V, T> List<Versioned<V>> get(Store<K, V, T> storageEngine, K key, T transform) { Map<K, List<Versioned<V>>> result = storageEngine.getAll(Collections.singleton(key), Collections.singletonMap(key, transform)); if(result.size() > 0) return result.get(key); else return Collections.emptyList(); }
java
public static <K, V, T> List<Versioned<V>> get(Store<K, V, T> storageEngine, K key, T transform) { Map<K, List<Versioned<V>>> result = storageEngine.getAll(Collections.singleton(key), Collections.singletonMap(key, transform)); if(result.size() > 0) return result.get(key); else return Collections.emptyList(); }
[ "public", "static", "<", "K", ",", "V", ",", "T", ">", "List", "<", "Versioned", "<", "V", ">", ">", "get", "(", "Store", "<", "K", ",", "V", ",", "T", ">", "storageEngine", ",", "K", "key", ",", "T", "transform", ")", "{", "Map", "<", "K", ",", "List", "<", "Versioned", "<", "V", ">", ">", ">", "result", "=", "storageEngine", ".", "getAll", "(", "Collections", ".", "singleton", "(", "key", ")", ",", "Collections", ".", "singletonMap", "(", "key", ",", "transform", ")", ")", ";", "if", "(", "result", ".", "size", "(", ")", ">", "0", ")", "return", "result", ".", "get", "(", "key", ")", ";", "else", "return", "Collections", ".", "emptyList", "(", ")", ";", "}" ]
Implements get by delegating to getAll.
[ "Implements", "get", "by", "delegating", "to", "getAll", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/StoreUtils.java#L68-L76
161,193
voldemort/voldemort
src/java/voldemort/store/StoreUtils.java
StoreUtils.getAll
public static <K, V, T> Map<K, List<Versioned<V>>> getAll(Store<K, V, T> storageEngine, Iterable<K> keys, Map<K, T> transforms) { Map<K, List<Versioned<V>>> result = newEmptyHashMap(keys); for(K key: keys) { List<Versioned<V>> value = storageEngine.get(key, transforms != null ? transforms.get(key) : null); if(!value.isEmpty()) result.put(key, value); } return result; }
java
public static <K, V, T> Map<K, List<Versioned<V>>> getAll(Store<K, V, T> storageEngine, Iterable<K> keys, Map<K, T> transforms) { Map<K, List<Versioned<V>>> result = newEmptyHashMap(keys); for(K key: keys) { List<Versioned<V>> value = storageEngine.get(key, transforms != null ? transforms.get(key) : null); if(!value.isEmpty()) result.put(key, value); } return result; }
[ "public", "static", "<", "K", ",", "V", ",", "T", ">", "Map", "<", "K", ",", "List", "<", "Versioned", "<", "V", ">", ">", ">", "getAll", "(", "Store", "<", "K", ",", "V", ",", "T", ">", "storageEngine", ",", "Iterable", "<", "K", ">", "keys", ",", "Map", "<", "K", ",", "T", ">", "transforms", ")", "{", "Map", "<", "K", ",", "List", "<", "Versioned", "<", "V", ">", ">", ">", "result", "=", "newEmptyHashMap", "(", "keys", ")", ";", "for", "(", "K", "key", ":", "keys", ")", "{", "List", "<", "Versioned", "<", "V", ">>", "value", "=", "storageEngine", ".", "get", "(", "key", ",", "transforms", "!=", "null", "?", "transforms", ".", "get", "(", "key", ")", ":", "null", ")", ";", "if", "(", "!", "value", ".", "isEmpty", "(", ")", ")", "result", ".", "put", "(", "key", ",", "value", ")", ";", "}", "return", "result", ";", "}" ]
Implements getAll by delegating to get.
[ "Implements", "getAll", "by", "delegating", "to", "get", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/StoreUtils.java#L81-L93
161,194
voldemort/voldemort
src/java/voldemort/store/StoreUtils.java
StoreUtils.newEmptyHashMap
public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) { if(iterable instanceof Collection<?>) return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size()); return Maps.newHashMap(); }
java
public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) { if(iterable instanceof Collection<?>) return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size()); return Maps.newHashMap(); }
[ "public", "static", "<", "K", ",", "V", ">", "HashMap", "<", "K", ",", "V", ">", "newEmptyHashMap", "(", "Iterable", "<", "?", ">", "iterable", ")", "{", "if", "(", "iterable", "instanceof", "Collection", "<", "?", ">", ")", "return", "Maps", ".", "newHashMapWithExpectedSize", "(", "(", "(", "Collection", "<", "?", ">", ")", "iterable", ")", ".", "size", "(", ")", ")", ";", "return", "Maps", ".", "newHashMap", "(", ")", ";", "}" ]
Returns an empty map with expected size matching the iterable size if it's of type Collection. Otherwise, an empty map with the default size is returned.
[ "Returns", "an", "empty", "map", "with", "expected", "size", "matching", "the", "iterable", "size", "if", "it", "s", "of", "type", "Collection", ".", "Otherwise", "an", "empty", "map", "with", "the", "default", "size", "is", "returned", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/StoreUtils.java#L100-L104
161,195
voldemort/voldemort
src/java/voldemort/store/StoreUtils.java
StoreUtils.assertValidMetadata
public static void assertValidMetadata(ByteArray key, RoutingStrategy routingStrategy, Node currentNode) { List<Node> nodes = routingStrategy.routeRequest(key.get()); for(Node node: nodes) { if(node.getId() == currentNode.getId()) { return; } } throw new InvalidMetadataException("Client accessing key belonging to partitions " + routingStrategy.getPartitionList(key.get()) + " not present at " + currentNode); }
java
public static void assertValidMetadata(ByteArray key, RoutingStrategy routingStrategy, Node currentNode) { List<Node> nodes = routingStrategy.routeRequest(key.get()); for(Node node: nodes) { if(node.getId() == currentNode.getId()) { return; } } throw new InvalidMetadataException("Client accessing key belonging to partitions " + routingStrategy.getPartitionList(key.get()) + " not present at " + currentNode); }
[ "public", "static", "void", "assertValidMetadata", "(", "ByteArray", "key", ",", "RoutingStrategy", "routingStrategy", ",", "Node", "currentNode", ")", "{", "List", "<", "Node", ">", "nodes", "=", "routingStrategy", ".", "routeRequest", "(", "key", ".", "get", "(", ")", ")", ";", "for", "(", "Node", "node", ":", "nodes", ")", "{", "if", "(", "node", ".", "getId", "(", ")", "==", "currentNode", ".", "getId", "(", ")", ")", "{", "return", ";", "}", "}", "throw", "new", "InvalidMetadataException", "(", "\"Client accessing key belonging to partitions \"", "+", "routingStrategy", ".", "getPartitionList", "(", "key", ".", "get", "(", ")", ")", "+", "\" not present at \"", "+", "currentNode", ")", ";", "}" ]
Check if the current node is part of routing request based on cluster.xml or throw an exception. @param key The key we are checking @param routingStrategy The routing strategy @param currentNode Current node
[ "Check", "if", "the", "current", "node", "is", "part", "of", "routing", "request", "based", "on", "cluster", ".", "xml", "or", "throw", "an", "exception", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/StoreUtils.java#L133-L146
161,196
voldemort/voldemort
src/java/voldemort/store/StoreUtils.java
StoreUtils.assertValidNode
public static void assertValidNode(MetadataStore metadataStore, Integer nodeId) { if(!metadataStore.getCluster().hasNodeWithId(nodeId)) { throw new InvalidMetadataException("NodeId " + nodeId + " is not or no longer in this cluster"); } }
java
public static void assertValidNode(MetadataStore metadataStore, Integer nodeId) { if(!metadataStore.getCluster().hasNodeWithId(nodeId)) { throw new InvalidMetadataException("NodeId " + nodeId + " is not or no longer in this cluster"); } }
[ "public", "static", "void", "assertValidNode", "(", "MetadataStore", "metadataStore", ",", "Integer", "nodeId", ")", "{", "if", "(", "!", "metadataStore", ".", "getCluster", "(", ")", ".", "hasNodeWithId", "(", "nodeId", ")", ")", "{", "throw", "new", "InvalidMetadataException", "(", "\"NodeId \"", "+", "nodeId", "+", "\" is not or no longer in this cluster\"", ")", ";", "}", "}" ]
Check if the the nodeId is present in the cluster managed by the metadata store or throw an exception. @param nodeId The nodeId to check existence of
[ "Check", "if", "the", "the", "nodeId", "is", "present", "in", "the", "cluster", "managed", "by", "the", "metadata", "store", "or", "throw", "an", "exception", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/StoreUtils.java#L154-L158
161,197
voldemort/voldemort
src/java/voldemort/store/StoreUtils.java
StoreUtils.unsafeGetSerializer
@SuppressWarnings("unchecked") public static <T> Serializer<T> unsafeGetSerializer(SerializerFactory serializerFactory, SerializerDefinition serializerDefinition) { return (Serializer<T>) serializerFactory.getSerializer(serializerDefinition); }
java
@SuppressWarnings("unchecked") public static <T> Serializer<T> unsafeGetSerializer(SerializerFactory serializerFactory, SerializerDefinition serializerDefinition) { return (Serializer<T>) serializerFactory.getSerializer(serializerDefinition); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "Serializer", "<", "T", ">", "unsafeGetSerializer", "(", "SerializerFactory", "serializerFactory", ",", "SerializerDefinition", "serializerDefinition", ")", "{", "return", "(", "Serializer", "<", "T", ">", ")", "serializerFactory", ".", "getSerializer", "(", "serializerDefinition", ")", ";", "}" ]
This is a temporary measure until we have a type-safe solution for retrieving serializers from a SerializerFactory. It avoids warnings all over the codebase while making it easy to verify who calls it.
[ "This", "is", "a", "temporary", "measure", "until", "we", "have", "a", "type", "-", "safe", "solution", "for", "retrieving", "serializers", "from", "a", "SerializerFactory", ".", "It", "avoids", "warnings", "all", "over", "the", "codebase", "while", "making", "it", "easy", "to", "verify", "who", "calls", "it", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/StoreUtils.java#L197-L201
161,198
voldemort/voldemort
src/java/voldemort/store/StoreUtils.java
StoreUtils.getStoreDef
public static StoreDefinition getStoreDef(List<StoreDefinition> list, String name) { for(StoreDefinition def: list) if(def.getName().equals(name)) return def; return null; }
java
public static StoreDefinition getStoreDef(List<StoreDefinition> list, String name) { for(StoreDefinition def: list) if(def.getName().equals(name)) return def; return null; }
[ "public", "static", "StoreDefinition", "getStoreDef", "(", "List", "<", "StoreDefinition", ">", "list", ",", "String", "name", ")", "{", "for", "(", "StoreDefinition", "def", ":", "list", ")", "if", "(", "def", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", "return", "def", ";", "return", "null", ";", "}" ]
Get a store definition from the given list of store definitions @param list A list of store definitions @param name The name of the store @return The store definition
[ "Get", "a", "store", "definition", "from", "the", "given", "list", "of", "store", "definitions" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/StoreUtils.java#L210-L215
161,199
voldemort/voldemort
src/java/voldemort/store/StoreUtils.java
StoreUtils.getStoreNames
public static List<String> getStoreNames(List<StoreDefinition> list, boolean ignoreViews) { List<String> storeNameSet = new ArrayList<String>(); for(StoreDefinition def: list) if(!def.isView() || !ignoreViews) storeNameSet.add(def.getName()); return storeNameSet; }
java
public static List<String> getStoreNames(List<StoreDefinition> list, boolean ignoreViews) { List<String> storeNameSet = new ArrayList<String>(); for(StoreDefinition def: list) if(!def.isView() || !ignoreViews) storeNameSet.add(def.getName()); return storeNameSet; }
[ "public", "static", "List", "<", "String", ">", "getStoreNames", "(", "List", "<", "StoreDefinition", ">", "list", ",", "boolean", "ignoreViews", ")", "{", "List", "<", "String", ">", "storeNameSet", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "StoreDefinition", "def", ":", "list", ")", "if", "(", "!", "def", ".", "isView", "(", ")", "||", "!", "ignoreViews", ")", "storeNameSet", ".", "add", "(", "def", ".", "getName", "(", ")", ")", ";", "return", "storeNameSet", ";", "}" ]
Get the list of store names from a list of store definitions @param list @param ignoreViews @return list of store names
[ "Get", "the", "list", "of", "store", "names", "from", "a", "list", "of", "store", "definitions" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/StoreUtils.java#L224-L230