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
partition
stringclasses
1 value
voldemort/voldemort
src/java/voldemort/server/niosocket/AsyncRequestHandler.java
AsyncRequestHandler.initRequestHandler
private boolean initRequestHandler(SelectionKey selectionKey) { ByteBuffer inputBuffer = inputStream.getBuffer(); int remaining = inputBuffer.remaining(); // Don't have enough bytes to determine the protocol yet... if(remaining < 3) return true; byte[] protoBytes = { inputBuffer.get(0), inputBuffer.get(1), inputBuffer.get(2) }; try { String proto = ByteUtils.getString(protoBytes, "UTF-8"); inputBuffer.clear(); RequestFormatType requestFormatType = RequestFormatType.fromCode(proto); requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType); if(logger.isInfoEnabled()) logger.info("Protocol negotiated for " + socketChannel.socket() + ": " + requestFormatType.getDisplayName()); // The protocol negotiation is the first request, so respond by // sticking the bytes in the output buffer, signaling the Selector, // and returning false to denote no further processing is needed. outputStream.getBuffer().put(ByteUtils.getBytes("ok", "UTF-8")); prepForWrite(selectionKey); return false; } catch(IllegalArgumentException e) { // okay we got some nonsense. For backwards compatibility, // assume this is an old client who does not know how to negotiate RequestFormatType requestFormatType = RequestFormatType.VOLDEMORT_V0; requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType); if(logger.isInfoEnabled()) logger.info("No protocol proposal given for " + socketChannel.socket() + ", assuming " + requestFormatType.getDisplayName()); return true; } }
java
private boolean initRequestHandler(SelectionKey selectionKey) { ByteBuffer inputBuffer = inputStream.getBuffer(); int remaining = inputBuffer.remaining(); // Don't have enough bytes to determine the protocol yet... if(remaining < 3) return true; byte[] protoBytes = { inputBuffer.get(0), inputBuffer.get(1), inputBuffer.get(2) }; try { String proto = ByteUtils.getString(protoBytes, "UTF-8"); inputBuffer.clear(); RequestFormatType requestFormatType = RequestFormatType.fromCode(proto); requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType); if(logger.isInfoEnabled()) logger.info("Protocol negotiated for " + socketChannel.socket() + ": " + requestFormatType.getDisplayName()); // The protocol negotiation is the first request, so respond by // sticking the bytes in the output buffer, signaling the Selector, // and returning false to denote no further processing is needed. outputStream.getBuffer().put(ByteUtils.getBytes("ok", "UTF-8")); prepForWrite(selectionKey); return false; } catch(IllegalArgumentException e) { // okay we got some nonsense. For backwards compatibility, // assume this is an old client who does not know how to negotiate RequestFormatType requestFormatType = RequestFormatType.VOLDEMORT_V0; requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType); if(logger.isInfoEnabled()) logger.info("No protocol proposal given for " + socketChannel.socket() + ", assuming " + requestFormatType.getDisplayName()); return true; } }
[ "private", "boolean", "initRequestHandler", "(", "SelectionKey", "selectionKey", ")", "{", "ByteBuffer", "inputBuffer", "=", "inputStream", ".", "getBuffer", "(", ")", ";", "int", "remaining", "=", "inputBuffer", ".", "remaining", "(", ")", ";", "// Don't have eno...
Returns true if the request should continue. @return
[ "Returns", "true", "if", "the", "request", "should", "continue", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/niosocket/AsyncRequestHandler.java#L401-L440
train
voldemort/voldemort
src/java/voldemort/client/rebalance/QuotaResetter.java
QuotaResetter.rememberAndDisableQuota
public void rememberAndDisableQuota() { for(Integer nodeId: nodeIds) { boolean quotaEnforcement = Boolean.parseBoolean(adminClient.metadataMgmtOps.getRemoteMetadata(nodeId, MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY) .getValue()); mapNodeToQuotaEnforcingEnabled.put(nodeId, quotaEnforcement); } adminClient.metadataMgmtOps.updateRemoteMetadata(nodeIds, MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY, Boolean.toString(false)); }
java
public void rememberAndDisableQuota() { for(Integer nodeId: nodeIds) { boolean quotaEnforcement = Boolean.parseBoolean(adminClient.metadataMgmtOps.getRemoteMetadata(nodeId, MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY) .getValue()); mapNodeToQuotaEnforcingEnabled.put(nodeId, quotaEnforcement); } adminClient.metadataMgmtOps.updateRemoteMetadata(nodeIds, MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY, Boolean.toString(false)); }
[ "public", "void", "rememberAndDisableQuota", "(", ")", "{", "for", "(", "Integer", "nodeId", ":", "nodeIds", ")", "{", "boolean", "quotaEnforcement", "=", "Boolean", ".", "parseBoolean", "(", "adminClient", ".", "metadataMgmtOps", ".", "getRemoteMetadata", "(", ...
Before cluster management operations, i.e. remember and disable quota enforcement settings
[ "Before", "cluster", "management", "operations", "i", ".", "e", ".", "remember", "and", "disable", "quota", "enforcement", "settings" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/QuotaResetter.java#L37-L47
train
voldemort/voldemort
src/java/voldemort/client/rebalance/QuotaResetter.java
QuotaResetter.resetQuotaAndRecoverEnforcement
public void resetQuotaAndRecoverEnforcement() { for(Integer nodeId: nodeIds) { boolean quotaEnforcement = mapNodeToQuotaEnforcingEnabled.get(nodeId); adminClient.metadataMgmtOps.updateRemoteMetadata(Arrays.asList(nodeId), MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY, Boolean.toString(quotaEnforcement)); } for(String storeName: storeNames) { adminClient.quotaMgmtOps.rebalanceQuota(storeName); } }
java
public void resetQuotaAndRecoverEnforcement() { for(Integer nodeId: nodeIds) { boolean quotaEnforcement = mapNodeToQuotaEnforcingEnabled.get(nodeId); adminClient.metadataMgmtOps.updateRemoteMetadata(Arrays.asList(nodeId), MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY, Boolean.toString(quotaEnforcement)); } for(String storeName: storeNames) { adminClient.quotaMgmtOps.rebalanceQuota(storeName); } }
[ "public", "void", "resetQuotaAndRecoverEnforcement", "(", ")", "{", "for", "(", "Integer", "nodeId", ":", "nodeIds", ")", "{", "boolean", "quotaEnforcement", "=", "mapNodeToQuotaEnforcingEnabled", ".", "get", "(", "nodeId", ")", ";", "adminClient", ".", "metadataM...
After cluster management operations, i.e. reset quota and recover quota enforcement settings
[ "After", "cluster", "management", "operations", "i", ".", "e", ".", "reset", "quota", "and", "recover", "quota", "enforcement", "settings" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/QuotaResetter.java#L53-L63
train
voldemort/voldemort
src/java/voldemort/versioning/VectorClock.java
VectorClock.incrementVersion
public void incrementVersion(int node, long time) { if(node < 0 || node > Short.MAX_VALUE) throw new IllegalArgumentException(node + " is outside the acceptable range of node ids."); this.timestamp = time; Long version = versionMap.get((short) node); if(version == null) { version = 1L; } else { version = version + 1L; } versionMap.put((short) node, version); if(versionMap.size() >= MAX_NUMBER_OF_VERSIONS) { throw new IllegalStateException("Vector clock is full!"); } }
java
public void incrementVersion(int node, long time) { if(node < 0 || node > Short.MAX_VALUE) throw new IllegalArgumentException(node + " is outside the acceptable range of node ids."); this.timestamp = time; Long version = versionMap.get((short) node); if(version == null) { version = 1L; } else { version = version + 1L; } versionMap.put((short) node, version); if(versionMap.size() >= MAX_NUMBER_OF_VERSIONS) { throw new IllegalStateException("Vector clock is full!"); } }
[ "public", "void", "incrementVersion", "(", "int", "node", ",", "long", "time", ")", "{", "if", "(", "node", "<", "0", "||", "node", ">", "Short", ".", "MAX_VALUE", ")", "throw", "new", "IllegalArgumentException", "(", "node", "+", "\" is outside the acceptab...
Increment the version info associated with the given node @param node The node
[ "Increment", "the", "version", "info", "associated", "with", "the", "given", "node" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/versioning/VectorClock.java#L205-L224
train
voldemort/voldemort
src/java/voldemort/versioning/VectorClock.java
VectorClock.incremented
public VectorClock incremented(int nodeId, long time) { VectorClock copyClock = this.clone(); copyClock.incrementVersion(nodeId, time); return copyClock; }
java
public VectorClock incremented(int nodeId, long time) { VectorClock copyClock = this.clone(); copyClock.incrementVersion(nodeId, time); return copyClock; }
[ "public", "VectorClock", "incremented", "(", "int", "nodeId", ",", "long", "time", ")", "{", "VectorClock", "copyClock", "=", "this", ".", "clone", "(", ")", ";", "copyClock", ".", "incrementVersion", "(", "nodeId", ",", "time", ")", ";", "return", "copyCl...
Get new vector clock based on this clock but incremented on index nodeId @param nodeId The id of the node to increment @return A vector clock equal on each element execept that indexed by nodeId
[ "Get", "new", "vector", "clock", "based", "on", "this", "clock", "but", "incremented", "on", "index", "nodeId" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/versioning/VectorClock.java#L233-L237
train
voldemort/voldemort
src/java/voldemort/tools/PartitionBalance.java
PartitionBalance.getNodeIdToPrimaryCount
private Map<Integer, Integer> getNodeIdToPrimaryCount(Cluster cluster) { Map<Integer, Integer> nodeIdToPrimaryCount = Maps.newHashMap(); for(Node node: cluster.getNodes()) { nodeIdToPrimaryCount.put(node.getId(), node.getPartitionIds().size()); } return nodeIdToPrimaryCount; }
java
private Map<Integer, Integer> getNodeIdToPrimaryCount(Cluster cluster) { Map<Integer, Integer> nodeIdToPrimaryCount = Maps.newHashMap(); for(Node node: cluster.getNodes()) { nodeIdToPrimaryCount.put(node.getId(), node.getPartitionIds().size()); } return nodeIdToPrimaryCount; }
[ "private", "Map", "<", "Integer", ",", "Integer", ">", "getNodeIdToPrimaryCount", "(", "Cluster", "cluster", ")", "{", "Map", "<", "Integer", ",", "Integer", ">", "nodeIdToPrimaryCount", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "Node", "n...
Go through all nodes and determine how many partition Ids each node hosts. @param cluster @return map of nodeId to number of primary partitions hosted on node.
[ "Go", "through", "all", "nodes", "and", "determine", "how", "many", "partition", "Ids", "each", "node", "hosts", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/PartitionBalance.java#L180-L187
train
voldemort/voldemort
src/java/voldemort/tools/PartitionBalance.java
PartitionBalance.getNodeIdToZonePrimaryCount
private Map<Integer, Integer> getNodeIdToZonePrimaryCount(Cluster cluster, StoreRoutingPlan storeRoutingPlan) { Map<Integer, Integer> nodeIdToZonePrimaryCount = Maps.newHashMap(); for(Integer nodeId: cluster.getNodeIds()) { nodeIdToZonePrimaryCount.put(nodeId, storeRoutingPlan.getZonePrimaryPartitionIds(nodeId).size()); } return nodeIdToZonePrimaryCount; }
java
private Map<Integer, Integer> getNodeIdToZonePrimaryCount(Cluster cluster, StoreRoutingPlan storeRoutingPlan) { Map<Integer, Integer> nodeIdToZonePrimaryCount = Maps.newHashMap(); for(Integer nodeId: cluster.getNodeIds()) { nodeIdToZonePrimaryCount.put(nodeId, storeRoutingPlan.getZonePrimaryPartitionIds(nodeId).size()); } return nodeIdToZonePrimaryCount; }
[ "private", "Map", "<", "Integer", ",", "Integer", ">", "getNodeIdToZonePrimaryCount", "(", "Cluster", "cluster", ",", "StoreRoutingPlan", "storeRoutingPlan", ")", "{", "Map", "<", "Integer", ",", "Integer", ">", "nodeIdToZonePrimaryCount", "=", "Maps", ".", "newHa...
Go through all partition IDs and determine which node is "first" in the replicating node list for every zone. This determines the number of "zone primaries" each node hosts. @return map of nodeId to number of zone-primaries hosted on node.
[ "Go", "through", "all", "partition", "IDs", "and", "determine", "which", "node", "is", "first", "in", "the", "replicating", "node", "list", "for", "every", "zone", ".", "This", "determines", "the", "number", "of", "zone", "primaries", "each", "node", "hosts"...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/PartitionBalance.java#L196-L205
train
voldemort/voldemort
src/java/voldemort/tools/PartitionBalance.java
PartitionBalance.getNodeIdToNaryCount
private Map<Integer, Integer> getNodeIdToNaryCount(Cluster cluster, StoreRoutingPlan storeRoutingPlan) { Map<Integer, Integer> nodeIdToNaryCount = Maps.newHashMap(); for(int nodeId: cluster.getNodeIds()) { nodeIdToNaryCount.put(nodeId, storeRoutingPlan.getZoneNAryPartitionIds(nodeId).size()); } return nodeIdToNaryCount; }
java
private Map<Integer, Integer> getNodeIdToNaryCount(Cluster cluster, StoreRoutingPlan storeRoutingPlan) { Map<Integer, Integer> nodeIdToNaryCount = Maps.newHashMap(); for(int nodeId: cluster.getNodeIds()) { nodeIdToNaryCount.put(nodeId, storeRoutingPlan.getZoneNAryPartitionIds(nodeId).size()); } return nodeIdToNaryCount; }
[ "private", "Map", "<", "Integer", ",", "Integer", ">", "getNodeIdToNaryCount", "(", "Cluster", "cluster", ",", "StoreRoutingPlan", "storeRoutingPlan", ")", "{", "Map", "<", "Integer", ",", "Integer", ">", "nodeIdToNaryCount", "=", "Maps", ".", "newHashMap", "(",...
Go through all node IDs and determine which node @param cluster @param storeRoutingPlan @return
[ "Go", "through", "all", "node", "IDs", "and", "determine", "which", "node" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/PartitionBalance.java#L214-L223
train
voldemort/voldemort
src/java/voldemort/tools/PartitionBalance.java
PartitionBalance.dumpZoneNAryDetails
private String dumpZoneNAryDetails(StoreRoutingPlan storeRoutingPlan) { StringBuilder sb = new StringBuilder(); sb.append("\tDetailed Dump (Zone N-Aries):").append(Utils.NEWLINE); for(Node node: storeRoutingPlan.getCluster().getNodes()) { int zoneId = node.getZoneId(); int nodeId = node.getId(); sb.append("\tNode ID: " + nodeId + " in zone " + zoneId).append(Utils.NEWLINE); List<Integer> naries = storeRoutingPlan.getZoneNAryPartitionIds(nodeId); Map<Integer, List<Integer>> zoneNaryTypeToPartitionIds = new HashMap<Integer, List<Integer>>(); for(int nary: naries) { int zoneReplicaType = storeRoutingPlan.getZoneNaryForNodesPartition(zoneId, nodeId, nary); if(!zoneNaryTypeToPartitionIds.containsKey(zoneReplicaType)) { zoneNaryTypeToPartitionIds.put(zoneReplicaType, new ArrayList<Integer>()); } zoneNaryTypeToPartitionIds.get(zoneReplicaType).add(nary); } for(int replicaType: new TreeSet<Integer>(zoneNaryTypeToPartitionIds.keySet())) { sb.append("\t\t" + replicaType + " : "); sb.append(zoneNaryTypeToPartitionIds.get(replicaType).toString()); sb.append(Utils.NEWLINE); } } return sb.toString(); }
java
private String dumpZoneNAryDetails(StoreRoutingPlan storeRoutingPlan) { StringBuilder sb = new StringBuilder(); sb.append("\tDetailed Dump (Zone N-Aries):").append(Utils.NEWLINE); for(Node node: storeRoutingPlan.getCluster().getNodes()) { int zoneId = node.getZoneId(); int nodeId = node.getId(); sb.append("\tNode ID: " + nodeId + " in zone " + zoneId).append(Utils.NEWLINE); List<Integer> naries = storeRoutingPlan.getZoneNAryPartitionIds(nodeId); Map<Integer, List<Integer>> zoneNaryTypeToPartitionIds = new HashMap<Integer, List<Integer>>(); for(int nary: naries) { int zoneReplicaType = storeRoutingPlan.getZoneNaryForNodesPartition(zoneId, nodeId, nary); if(!zoneNaryTypeToPartitionIds.containsKey(zoneReplicaType)) { zoneNaryTypeToPartitionIds.put(zoneReplicaType, new ArrayList<Integer>()); } zoneNaryTypeToPartitionIds.get(zoneReplicaType).add(nary); } for(int replicaType: new TreeSet<Integer>(zoneNaryTypeToPartitionIds.keySet())) { sb.append("\t\t" + replicaType + " : "); sb.append(zoneNaryTypeToPartitionIds.get(replicaType).toString()); sb.append(Utils.NEWLINE); } } return sb.toString(); }
[ "private", "String", "dumpZoneNAryDetails", "(", "StoreRoutingPlan", "storeRoutingPlan", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"\\tDetailed Dump (Zone N-Aries):\"", ")", ".", "append", "(", "Utils", ...
Dumps the partition IDs per node in terms of zone n-ary type. @param cluster @param storeRoutingPlan @return pretty printed string of detailed zone n-ary type.
[ "Dumps", "the", "partition", "IDs", "per", "node", "in", "terms", "of", "zone", "n", "-", "ary", "type", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/PartitionBalance.java#L232-L260
train
voldemort/voldemort
src/java/voldemort/tools/PartitionBalance.java
PartitionBalance.summarizeBalance
private Pair<Double, String> summarizeBalance(final Map<Integer, Integer> nodeIdToPartitionCount, String title) { StringBuilder builder = new StringBuilder(); builder.append("\n" + title + "\n"); Map<Integer, ZoneBalanceStats> zoneToBalanceStats = new HashMap<Integer, ZoneBalanceStats>(); for(Integer zoneId: cluster.getZoneIds()) { zoneToBalanceStats.put(zoneId, new ZoneBalanceStats()); } for(Node node: cluster.getNodes()) { int curCount = nodeIdToPartitionCount.get(node.getId()); builder.append("\tNode ID: " + node.getId() + " : " + curCount + " (" + node.getHost() + ")\n"); zoneToBalanceStats.get(node.getZoneId()).addPartitions(curCount); } // double utilityToBeMinimized = Double.MIN_VALUE; double utilityToBeMinimized = 0; for(Integer zoneId: cluster.getZoneIds()) { builder.append("Zone " + zoneId + "\n"); builder.append(zoneToBalanceStats.get(zoneId).dumpStats()); utilityToBeMinimized += zoneToBalanceStats.get(zoneId).getUtility(); /*- * Another utility function to consider if(zoneToBalanceStats.get(zoneId).getMaxMinRatio() > utilityToBeMinimized) { utilityToBeMinimized = zoneToBalanceStats.get(zoneId).getUtility(); } */ } return Pair.create(utilityToBeMinimized, builder.toString()); }
java
private Pair<Double, String> summarizeBalance(final Map<Integer, Integer> nodeIdToPartitionCount, String title) { StringBuilder builder = new StringBuilder(); builder.append("\n" + title + "\n"); Map<Integer, ZoneBalanceStats> zoneToBalanceStats = new HashMap<Integer, ZoneBalanceStats>(); for(Integer zoneId: cluster.getZoneIds()) { zoneToBalanceStats.put(zoneId, new ZoneBalanceStats()); } for(Node node: cluster.getNodes()) { int curCount = nodeIdToPartitionCount.get(node.getId()); builder.append("\tNode ID: " + node.getId() + " : " + curCount + " (" + node.getHost() + ")\n"); zoneToBalanceStats.get(node.getZoneId()).addPartitions(curCount); } // double utilityToBeMinimized = Double.MIN_VALUE; double utilityToBeMinimized = 0; for(Integer zoneId: cluster.getZoneIds()) { builder.append("Zone " + zoneId + "\n"); builder.append(zoneToBalanceStats.get(zoneId).dumpStats()); utilityToBeMinimized += zoneToBalanceStats.get(zoneId).getUtility(); /*- * Another utility function to consider if(zoneToBalanceStats.get(zoneId).getMaxMinRatio() > utilityToBeMinimized) { utilityToBeMinimized = zoneToBalanceStats.get(zoneId).getUtility(); } */ } return Pair.create(utilityToBeMinimized, builder.toString()); }
[ "private", "Pair", "<", "Double", ",", "String", ">", "summarizeBalance", "(", "final", "Map", "<", "Integer", ",", "Integer", ">", "nodeIdToPartitionCount", ",", "String", "title", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ...
Summarizes balance for the given nodeId to PartitionCount. @param nodeIdToPartitionCount @param title for use in pretty string @return Pair: getFirst() is utility value to be minimized, getSecond() is pretty summary string of balance
[ "Summarizes", "balance", "for", "the", "given", "nodeId", "to", "PartitionCount", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/PartitionBalance.java#L398-L430
train
voldemort/voldemort
src/java/voldemort/server/rebalance/async/StealerBasedRebalanceAsyncOperation.java
StealerBasedRebalanceAsyncOperation.rebalanceStore
private void rebalanceStore(String storeName, final AdminClient adminClient, RebalanceTaskInfo stealInfo, boolean isReadOnlyStore) { // Move partitions if (stealInfo.getPartitionIds(storeName) != null && stealInfo.getPartitionIds(storeName).size() > 0) { logger.info(getHeader(stealInfo) + "Starting partitions migration for store " + storeName + " from donor node " + stealInfo.getDonorId()); int asyncId = adminClient.storeMntOps.migratePartitions(stealInfo.getDonorId(), metadataStore.getNodeId(), storeName, stealInfo.getPartitionIds(storeName), null, stealInfo.getInitialCluster()); rebalanceStatusList.add(asyncId); if(logger.isDebugEnabled()) { logger.debug(getHeader(stealInfo) + "Waiting for completion for " + storeName + " with async id " + asyncId); } adminClient.rpcOps.waitForCompletion(metadataStore.getNodeId(), asyncId, voldemortConfig.getRebalancingTimeoutSec(), TimeUnit.SECONDS, getStatus()); rebalanceStatusList.remove((Object) asyncId); logger.info(getHeader(stealInfo) + "Completed partition migration for store " + storeName + " from donor node " + stealInfo.getDonorId()); } logger.info(getHeader(stealInfo) + "Finished all migration for store " + storeName); }
java
private void rebalanceStore(String storeName, final AdminClient adminClient, RebalanceTaskInfo stealInfo, boolean isReadOnlyStore) { // Move partitions if (stealInfo.getPartitionIds(storeName) != null && stealInfo.getPartitionIds(storeName).size() > 0) { logger.info(getHeader(stealInfo) + "Starting partitions migration for store " + storeName + " from donor node " + stealInfo.getDonorId()); int asyncId = adminClient.storeMntOps.migratePartitions(stealInfo.getDonorId(), metadataStore.getNodeId(), storeName, stealInfo.getPartitionIds(storeName), null, stealInfo.getInitialCluster()); rebalanceStatusList.add(asyncId); if(logger.isDebugEnabled()) { logger.debug(getHeader(stealInfo) + "Waiting for completion for " + storeName + " with async id " + asyncId); } adminClient.rpcOps.waitForCompletion(metadataStore.getNodeId(), asyncId, voldemortConfig.getRebalancingTimeoutSec(), TimeUnit.SECONDS, getStatus()); rebalanceStatusList.remove((Object) asyncId); logger.info(getHeader(stealInfo) + "Completed partition migration for store " + storeName + " from donor node " + stealInfo.getDonorId()); } logger.info(getHeader(stealInfo) + "Finished all migration for store " + storeName); }
[ "private", "void", "rebalanceStore", "(", "String", "storeName", ",", "final", "AdminClient", "adminClient", ",", "RebalanceTaskInfo", "stealInfo", ",", "boolean", "isReadOnlyStore", ")", "{", "// Move partitions", "if", "(", "stealInfo", ".", "getPartitionIds", "(", ...
Blocking function which completes the migration of one store @param storeName The name of the store @param adminClient Admin client used to initiate the copying of data @param stealInfo The steal information @param isReadOnlyStore Boolean indicating that this is a read-only store
[ "Blocking", "function", "which", "completes", "the", "migration", "of", "one", "store" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/rebalance/async/StealerBasedRebalanceAsyncOperation.java#L174-L209
train
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordSyncOpTimeNs
public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) { if(dest != null) { getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs); recordSyncOpTimeNs(null, opTimeNs); } else { this.syncOpTimeRequestCounter.addRequest(opTimeNs); } }
java
public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) { if(dest != null) { getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs); recordSyncOpTimeNs(null, opTimeNs); } else { this.syncOpTimeRequestCounter.addRequest(opTimeNs); } }
[ "public", "void", "recordSyncOpTimeNs", "(", "SocketDestination", "dest", ",", "long", "opTimeNs", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordSyncOpTimeNs", "(", "null", ",", "opTimeNs", ")", ";...
Record operation for sync ops time @param dest Destination of the socket to connect to. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param opTimeUs The number of us for the op to finish
[ "Record", "operation", "for", "sync", "ops", "time" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L213-L220
train
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordAsyncOpTimeNs
public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) { if(dest != null) { getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs); recordAsyncOpTimeNs(null, opTimeNs); } else { this.asynOpTimeRequestCounter.addRequest(opTimeNs); } }
java
public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) { if(dest != null) { getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs); recordAsyncOpTimeNs(null, opTimeNs); } else { this.asynOpTimeRequestCounter.addRequest(opTimeNs); } }
[ "public", "void", "recordAsyncOpTimeNs", "(", "SocketDestination", "dest", ",", "long", "opTimeNs", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordAsyncOpTimeNs", "(", "null", ",", "opTimeNs", ")", ...
Record operation for async ops time @param dest Destination of the socket to connect to. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param opTimeUs The number of us for the op to finish
[ "Record", "operation", "for", "async", "ops", "time" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L230-L237
train
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordConnectionEstablishmentTimeUs
public void recordConnectionEstablishmentTimeUs(SocketDestination dest, long connEstTimeUs) { if(dest != null) { getOrCreateNodeStats(dest).recordConnectionEstablishmentTimeUs(null, connEstTimeUs); recordConnectionEstablishmentTimeUs(null, connEstTimeUs); } else { this.connectionEstablishmentRequestCounter.addRequest(connEstTimeUs * Time.NS_PER_US); } }
java
public void recordConnectionEstablishmentTimeUs(SocketDestination dest, long connEstTimeUs) { if(dest != null) { getOrCreateNodeStats(dest).recordConnectionEstablishmentTimeUs(null, connEstTimeUs); recordConnectionEstablishmentTimeUs(null, connEstTimeUs); } else { this.connectionEstablishmentRequestCounter.addRequest(connEstTimeUs * Time.NS_PER_US); } }
[ "public", "void", "recordConnectionEstablishmentTimeUs", "(", "SocketDestination", "dest", ",", "long", "connEstTimeUs", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordConnectionEstablishmentTimeUs", "(", "...
Record the connection establishment time @param dest Destination of the socket to connect to. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param connEstTimeUs The number of us to wait before establishing a connection
[ "Record", "the", "connection", "establishment", "time" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L248-L255
train
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordCheckoutTimeUs
public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) { if(dest != null) { getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs); recordCheckoutTimeUs(null, checkoutTimeUs); } else { this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US); } }
java
public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) { if(dest != null) { getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs); recordCheckoutTimeUs(null, checkoutTimeUs); } else { this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US); } }
[ "public", "void", "recordCheckoutTimeUs", "(", "SocketDestination", "dest", ",", "long", "checkoutTimeUs", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordCheckoutTimeUs", "(", "null", ",", "checkoutTime...
Record the checkout wait time in us @param dest Destination of the socket to checkout. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param checkoutTimeUs The number of us to wait before getting a socket
[ "Record", "the", "checkout", "wait", "time", "in", "us" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L265-L272
train
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordCheckoutQueueLength
public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) { if(dest != null) { getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength); recordCheckoutQueueLength(null, queueLength); } else { this.checkoutQueueLengthHistogram.insert(queueLength); checkMonitoringInterval(); } }
java
public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) { if(dest != null) { getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength); recordCheckoutQueueLength(null, queueLength); } else { this.checkoutQueueLengthHistogram.insert(queueLength); checkMonitoringInterval(); } }
[ "public", "void", "recordCheckoutQueueLength", "(", "SocketDestination", "dest", ",", "int", "queueLength", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordCheckoutQueueLength", "(", "null", ",", "queueL...
Record the checkout queue length @param dest Destination of the socket to checkout. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param queueLength The number of entries in the "synchronous" checkout queue.
[ "Record", "the", "checkout", "queue", "length" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L283-L291
train
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordResourceRequestTimeUs
public void recordResourceRequestTimeUs(SocketDestination dest, long resourceRequestTimeUs) { if(dest != null) { getOrCreateNodeStats(dest).recordResourceRequestTimeUs(null, resourceRequestTimeUs); recordResourceRequestTimeUs(null, resourceRequestTimeUs); } else { this.resourceRequestTimeRequestCounter.addRequest(resourceRequestTimeUs * Time.NS_PER_US); } }
java
public void recordResourceRequestTimeUs(SocketDestination dest, long resourceRequestTimeUs) { if(dest != null) { getOrCreateNodeStats(dest).recordResourceRequestTimeUs(null, resourceRequestTimeUs); recordResourceRequestTimeUs(null, resourceRequestTimeUs); } else { this.resourceRequestTimeRequestCounter.addRequest(resourceRequestTimeUs * Time.NS_PER_US); } }
[ "public", "void", "recordResourceRequestTimeUs", "(", "SocketDestination", "dest", ",", "long", "resourceRequestTimeUs", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordResourceRequestTimeUs", "(", "null", ...
Record the resource request wait time in us @param dest Destination of the socket for which the resource was requested. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param resourceRequestTimeUs The number of us to wait before getting a socket
[ "Record", "the", "resource", "request", "wait", "time", "in", "us" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L302-L310
train
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordResourceRequestQueueLength
public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) { if(dest != null) { getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength); recordResourceRequestQueueLength(null, queueLength); } else { this.resourceRequestQueueLengthHistogram.insert(queueLength); checkMonitoringInterval(); } }
java
public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) { if(dest != null) { getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength); recordResourceRequestQueueLength(null, queueLength); } else { this.resourceRequestQueueLengthHistogram.insert(queueLength); checkMonitoringInterval(); } }
[ "public", "void", "recordResourceRequestQueueLength", "(", "SocketDestination", "dest", ",", "int", "queueLength", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordResourceRequestQueueLength", "(", "null", ...
Record the resource request queue length @param dest Destination of the socket for which resource request is enqueued. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param queueLength The number of entries in the "asynchronous" resource request queue.
[ "Record", "the", "resource", "request", "queue", "length" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L321-L329
train
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.close
public void close() { Iterator<SocketDestination> it = getStatsMap().keySet().iterator(); while(it.hasNext()) { try { SocketDestination destination = it.next(); JmxUtils.unregisterMbean(JmxUtils.createObjectName(JmxUtils.getPackageName(ClientRequestExecutor.class), "stats_" + destination.toString() .replace(':', '_') + identifierString)); } catch(Exception e) {} } }
java
public void close() { Iterator<SocketDestination> it = getStatsMap().keySet().iterator(); while(it.hasNext()) { try { SocketDestination destination = it.next(); JmxUtils.unregisterMbean(JmxUtils.createObjectName(JmxUtils.getPackageName(ClientRequestExecutor.class), "stats_" + destination.toString() .replace(':', '_') + identifierString)); } catch(Exception e) {} } }
[ "public", "void", "close", "(", ")", "{", "Iterator", "<", "SocketDestination", ">", "it", "=", "getStatsMap", "(", ")", ".", "keySet", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "try", "{", ...
Unregister all MBeans
[ "Unregister", "all", "MBeans" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L504-L517
train
voldemort/voldemort
src/java/voldemort/store/socket/SocketStore.java
SocketStore.request
private <T> T request(ClientRequest<T> delegate, String operationName) { long startTimeMs = -1; long startTimeNs = -1; if(logger.isDebugEnabled()) { startTimeMs = System.currentTimeMillis(); } ClientRequestExecutor clientRequestExecutor = pool.checkout(destination); String debugMsgStr = ""; startTimeNs = System.nanoTime(); BlockingClientRequest<T> blockingClientRequest = null; try { blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs); clientRequestExecutor.addClientRequest(blockingClientRequest, timeoutMs, System.nanoTime() - startTimeNs); boolean awaitResult = blockingClientRequest.await(); if(awaitResult == false) { blockingClientRequest.timeOut(); } if(logger.isDebugEnabled()) debugMsgStr += "success"; return blockingClientRequest.getResult(); } catch(InterruptedException e) { if(logger.isDebugEnabled()) debugMsgStr += "unreachable: " + e.getMessage(); throw new UnreachableStoreException("Failure in " + operationName + " on " + destination + ": " + e.getMessage(), e); } catch(UnreachableStoreException e) { clientRequestExecutor.close(); if(logger.isDebugEnabled()) debugMsgStr += "failure: " + e.getMessage(); throw new UnreachableStoreException("Failure in " + operationName + " on " + destination + ": " + e.getMessage(), e.getCause()); } finally { if(blockingClientRequest != null && !blockingClientRequest.isComplete()) { // close the executor if we timed out clientRequestExecutor.close(); } // Record operation time long opTimeNs = Utils.elapsedTimeNs(startTimeNs, System.nanoTime()); if(stats != null) { stats.recordSyncOpTimeNs(destination, opTimeNs); } if(logger.isDebugEnabled()) { logger.debug("Sync request end, type: " + operationName + " requestRef: " + System.identityHashCode(delegate) + " totalTimeNs: " + opTimeNs + " start time: " + startTimeMs + " end time: " + System.currentTimeMillis() + " client:" + clientRequestExecutor.getSocketChannel().socket().getLocalAddress() + ":" + clientRequestExecutor.getSocketChannel().socket().getLocalPort() + " server: " + clientRequestExecutor.getSocketChannel() .socket() .getRemoteSocketAddress() + " outcome: " + debugMsgStr); } pool.checkin(destination, clientRequestExecutor); } }
java
private <T> T request(ClientRequest<T> delegate, String operationName) { long startTimeMs = -1; long startTimeNs = -1; if(logger.isDebugEnabled()) { startTimeMs = System.currentTimeMillis(); } ClientRequestExecutor clientRequestExecutor = pool.checkout(destination); String debugMsgStr = ""; startTimeNs = System.nanoTime(); BlockingClientRequest<T> blockingClientRequest = null; try { blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs); clientRequestExecutor.addClientRequest(blockingClientRequest, timeoutMs, System.nanoTime() - startTimeNs); boolean awaitResult = blockingClientRequest.await(); if(awaitResult == false) { blockingClientRequest.timeOut(); } if(logger.isDebugEnabled()) debugMsgStr += "success"; return blockingClientRequest.getResult(); } catch(InterruptedException e) { if(logger.isDebugEnabled()) debugMsgStr += "unreachable: " + e.getMessage(); throw new UnreachableStoreException("Failure in " + operationName + " on " + destination + ": " + e.getMessage(), e); } catch(UnreachableStoreException e) { clientRequestExecutor.close(); if(logger.isDebugEnabled()) debugMsgStr += "failure: " + e.getMessage(); throw new UnreachableStoreException("Failure in " + operationName + " on " + destination + ": " + e.getMessage(), e.getCause()); } finally { if(blockingClientRequest != null && !blockingClientRequest.isComplete()) { // close the executor if we timed out clientRequestExecutor.close(); } // Record operation time long opTimeNs = Utils.elapsedTimeNs(startTimeNs, System.nanoTime()); if(stats != null) { stats.recordSyncOpTimeNs(destination, opTimeNs); } if(logger.isDebugEnabled()) { logger.debug("Sync request end, type: " + operationName + " requestRef: " + System.identityHashCode(delegate) + " totalTimeNs: " + opTimeNs + " start time: " + startTimeMs + " end time: " + System.currentTimeMillis() + " client:" + clientRequestExecutor.getSocketChannel().socket().getLocalAddress() + ":" + clientRequestExecutor.getSocketChannel().socket().getLocalPort() + " server: " + clientRequestExecutor.getSocketChannel() .socket() .getRemoteSocketAddress() + " outcome: " + debugMsgStr); } pool.checkin(destination, clientRequestExecutor); } }
[ "private", "<", "T", ">", "T", "request", "(", "ClientRequest", "<", "T", ">", "delegate", ",", "String", "operationName", ")", "{", "long", "startTimeMs", "=", "-", "1", ";", "long", "startTimeNs", "=", "-", "1", ";", "if", "(", "logger", ".", "isDe...
This method handles submitting and then waiting for the request from the server. It uses the ClientRequest API to actually write the request and then read back the response. This implementation will block for a response from the server. @param <T> Return type @param clientRequest ClientRequest implementation used to write the request and read the response @param operationName Simple string representing the type of request @return Data returned by the individual requests
[ "This", "method", "handles", "submitting", "and", "then", "waiting", "for", "the", "request", "from", "the", "server", ".", "It", "uses", "the", "ClientRequest", "API", "to", "actually", "write", "the", "request", "and", "then", "read", "back", "the", "respo...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/socket/SocketStore.java#L271-L349
train
voldemort/voldemort
src/java/voldemort/store/socket/SocketStore.java
SocketStore.requestAsync
private <T> void requestAsync(ClientRequest<T> delegate, NonblockingStoreCallback callback, long timeoutMs, String operationName) { pool.submitAsync(this.destination, delegate, callback, timeoutMs, operationName); }
java
private <T> void requestAsync(ClientRequest<T> delegate, NonblockingStoreCallback callback, long timeoutMs, String operationName) { pool.submitAsync(this.destination, delegate, callback, timeoutMs, operationName); }
[ "private", "<", "T", ">", "void", "requestAsync", "(", "ClientRequest", "<", "T", ">", "delegate", ",", "NonblockingStoreCallback", "callback", ",", "long", "timeoutMs", ",", "String", "operationName", ")", "{", "pool", ".", "submitAsync", "(", "this", ".", ...
This method handles submitting and then waiting for the request from the server. It uses the ClientRequest API to actually write the request and then read back the response. This implementation will not block for a response from the server. @param <T> Return type @param clientRequest ClientRequest implementation used to write the request and read the response @param operationName Simple string representing the type of request @return Data returned by the individual requests
[ "This", "method", "handles", "submitting", "and", "then", "waiting", "for", "the", "request", "from", "the", "server", ".", "It", "uses", "the", "ClientRequest", "API", "to", "actually", "write", "the", "request", "and", "then", "read", "back", "the", "respo...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/socket/SocketStore.java#L366-L371
train
voldemort/voldemort
src/java/voldemort/store/stats/StreamingStats.java
StreamingStats.getAvgFetchKeysNetworkTimeMs
@JmxGetter(name = "avgFetchKeysNetworkTimeMs", description = "average time spent on network, for fetch keys") public double getAvgFetchKeysNetworkTimeMs() { return networkTimeCounterMap.get(Operation.FETCH_KEYS).getAvgEventValue() / Time.NS_PER_MS; }
java
@JmxGetter(name = "avgFetchKeysNetworkTimeMs", description = "average time spent on network, for fetch keys") public double getAvgFetchKeysNetworkTimeMs() { return networkTimeCounterMap.get(Operation.FETCH_KEYS).getAvgEventValue() / Time.NS_PER_MS; }
[ "@", "JmxGetter", "(", "name", "=", "\"avgFetchKeysNetworkTimeMs\"", ",", "description", "=", "\"average time spent on network, for fetch keys\"", ")", "public", "double", "getAvgFetchKeysNetworkTimeMs", "(", ")", "{", "return", "networkTimeCounterMap", ".", "get", "(", "...
Mbeans for FETCH_KEYS
[ "Mbeans", "for", "FETCH_KEYS" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/StreamingStats.java#L118-L121
train
voldemort/voldemort
src/java/voldemort/store/stats/StreamingStats.java
StreamingStats.getAvgFetchEntriesNetworkTimeMs
@JmxGetter(name = "avgFetchEntriesNetworkTimeMs", description = "average time spent on network, for streaming operations") public double getAvgFetchEntriesNetworkTimeMs() { return networkTimeCounterMap.get(Operation.FETCH_ENTRIES).getAvgEventValue() / Time.NS_PER_MS; }
java
@JmxGetter(name = "avgFetchEntriesNetworkTimeMs", description = "average time spent on network, for streaming operations") public double getAvgFetchEntriesNetworkTimeMs() { return networkTimeCounterMap.get(Operation.FETCH_ENTRIES).getAvgEventValue() / Time.NS_PER_MS; }
[ "@", "JmxGetter", "(", "name", "=", "\"avgFetchEntriesNetworkTimeMs\"", ",", "description", "=", "\"average time spent on network, for streaming operations\"", ")", "public", "double", "getAvgFetchEntriesNetworkTimeMs", "(", ")", "{", "return", "networkTimeCounterMap", ".", "...
Mbeans for FETCH_ENTRIES
[ "Mbeans", "for", "FETCH_ENTRIES" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/StreamingStats.java#L139-L143
train
voldemort/voldemort
src/java/voldemort/store/stats/StreamingStats.java
StreamingStats.getAvgUpdateEntriesNetworkTimeMs
@JmxGetter(name = "avgUpdateEntriesNetworkTimeMs", description = "average time spent on network, for streaming operations") public double getAvgUpdateEntriesNetworkTimeMs() { return networkTimeCounterMap.get(Operation.UPDATE_ENTRIES).getAvgEventValue() / Time.NS_PER_MS; }
java
@JmxGetter(name = "avgUpdateEntriesNetworkTimeMs", description = "average time spent on network, for streaming operations") public double getAvgUpdateEntriesNetworkTimeMs() { return networkTimeCounterMap.get(Operation.UPDATE_ENTRIES).getAvgEventValue() / Time.NS_PER_MS; }
[ "@", "JmxGetter", "(", "name", "=", "\"avgUpdateEntriesNetworkTimeMs\"", ",", "description", "=", "\"average time spent on network, for streaming operations\"", ")", "public", "double", "getAvgUpdateEntriesNetworkTimeMs", "(", ")", "{", "return", "networkTimeCounterMap", ".", ...
Mbeans for UPDATE_ENTRIES
[ "Mbeans", "for", "UPDATE_ENTRIES" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/StreamingStats.java#L168-L172
train
voldemort/voldemort
src/java/voldemort/store/stats/StreamingStats.java
StreamingStats.getAvgSlopUpdateNetworkTimeMs
@JmxGetter(name = "avgSlopUpdateNetworkTimeMs", description = "average time spent on network, for streaming operations") public double getAvgSlopUpdateNetworkTimeMs() { return networkTimeCounterMap.get(Operation.SLOP_UPDATE).getAvgEventValue() / Time.NS_PER_MS; }
java
@JmxGetter(name = "avgSlopUpdateNetworkTimeMs", description = "average time spent on network, for streaming operations") public double getAvgSlopUpdateNetworkTimeMs() { return networkTimeCounterMap.get(Operation.SLOP_UPDATE).getAvgEventValue() / Time.NS_PER_MS; }
[ "@", "JmxGetter", "(", "name", "=", "\"avgSlopUpdateNetworkTimeMs\"", ",", "description", "=", "\"average time spent on network, for streaming operations\"", ")", "public", "double", "getAvgSlopUpdateNetworkTimeMs", "(", ")", "{", "return", "networkTimeCounterMap", ".", "get"...
Mbeans for SLOP_UPDATE
[ "Mbeans", "for", "SLOP_UPDATE" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/StreamingStats.java#L186-L189
train
voldemort/voldemort
src/java/voldemort/serialization/SerializationUtils.java
SerializationUtils.getJavaClassFromSchemaInfo
public static String getJavaClassFromSchemaInfo(String schemaInfo) { final String ONLY_JAVA_CLIENTS_SUPPORTED = "Only Java clients are supported currently, so the format of the schema-info should be: <schema-info>java=foo.Bar</schema-info> where foo.Bar is the fully qualified name of the message."; if(StringUtils.isEmpty(schemaInfo)) throw new IllegalArgumentException("This serializer requires a non-empty schema-info."); String[] languagePairs = StringUtils.split(schemaInfo, ','); if(languagePairs.length > 1) throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED); String[] javaPair = StringUtils.split(languagePairs[0], '='); if(javaPair.length != 2 || !javaPair[0].trim().equals("java")) throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED); return javaPair[1].trim(); }
java
public static String getJavaClassFromSchemaInfo(String schemaInfo) { final String ONLY_JAVA_CLIENTS_SUPPORTED = "Only Java clients are supported currently, so the format of the schema-info should be: <schema-info>java=foo.Bar</schema-info> where foo.Bar is the fully qualified name of the message."; if(StringUtils.isEmpty(schemaInfo)) throw new IllegalArgumentException("This serializer requires a non-empty schema-info."); String[] languagePairs = StringUtils.split(schemaInfo, ','); if(languagePairs.length > 1) throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED); String[] javaPair = StringUtils.split(languagePairs[0], '='); if(javaPair.length != 2 || !javaPair[0].trim().equals("java")) throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED); return javaPair[1].trim(); }
[ "public", "static", "String", "getJavaClassFromSchemaInfo", "(", "String", "schemaInfo", ")", "{", "final", "String", "ONLY_JAVA_CLIENTS_SUPPORTED", "=", "\"Only Java clients are supported currently, so the format of the schema-info should be: <schema-info>java=foo.Bar</schema-info> where ...
Extracts the java class name from the schema info @param schemaInfo the schema info, a string like: java=java.lang.String @return the name of the class extracted from the schema info
[ "Extracts", "the", "java", "class", "name", "from", "the", "schema", "info" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/serialization/SerializationUtils.java#L35-L50
train
voldemort/voldemort
src/java/voldemort/utils/StoreDefinitionUtils.java
StoreDefinitionUtils.filterStores
public static List<StoreDefinition> filterStores(List<StoreDefinition> storeDefs, final boolean isReadOnly) { List<StoreDefinition> filteredStores = Lists.newArrayList(); for(StoreDefinition storeDef: storeDefs) { if(storeDef.getType().equals(ReadOnlyStorageConfiguration.TYPE_NAME) == isReadOnly) { filteredStores.add(storeDef); } } return filteredStores; }
java
public static List<StoreDefinition> filterStores(List<StoreDefinition> storeDefs, final boolean isReadOnly) { List<StoreDefinition> filteredStores = Lists.newArrayList(); for(StoreDefinition storeDef: storeDefs) { if(storeDef.getType().equals(ReadOnlyStorageConfiguration.TYPE_NAME) == isReadOnly) { filteredStores.add(storeDef); } } return filteredStores; }
[ "public", "static", "List", "<", "StoreDefinition", ">", "filterStores", "(", "List", "<", "StoreDefinition", ">", "storeDefs", ",", "final", "boolean", "isReadOnly", ")", "{", "List", "<", "StoreDefinition", ">", "filteredStores", "=", "Lists", ".", "newArrayLi...
Given a list of store definitions, filters the list depending on the boolean @param storeDefs Complete list of store definitions @param isReadOnly Boolean indicating whether filter on read-only or not? @return List of filtered store definition
[ "Given", "a", "list", "of", "store", "definitions", "filters", "the", "list", "depending", "on", "the", "boolean" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/StoreDefinitionUtils.java#L57-L66
train
voldemort/voldemort
src/java/voldemort/utils/StoreDefinitionUtils.java
StoreDefinitionUtils.getStoreNames
public static List<String> getStoreNames(List<StoreDefinition> storeDefList) { List<String> storeList = new ArrayList<String>(); for(StoreDefinition def: storeDefList) { storeList.add(def.getName()); } return storeList; }
java
public static List<String> getStoreNames(List<StoreDefinition> storeDefList) { List<String> storeList = new ArrayList<String>(); for(StoreDefinition def: storeDefList) { storeList.add(def.getName()); } return storeList; }
[ "public", "static", "List", "<", "String", ">", "getStoreNames", "(", "List", "<", "StoreDefinition", ">", "storeDefList", ")", "{", "List", "<", "String", ">", "storeList", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "StoreDe...
Given a list of store definitions return a list of store names @param storeDefList The list of store definitions @return Returns a list of store names
[ "Given", "a", "list", "of", "store", "definitions", "return", "a", "list", "of", "store", "names" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/StoreDefinitionUtils.java#L74-L80
train
voldemort/voldemort
src/java/voldemort/utils/StoreDefinitionUtils.java
StoreDefinitionUtils.getStoreNamesSet
public static Set<String> getStoreNamesSet(List<StoreDefinition> storeDefList) { HashSet<String> storeSet = new HashSet<String>(); for(StoreDefinition def: storeDefList) { storeSet.add(def.getName()); } return storeSet; }
java
public static Set<String> getStoreNamesSet(List<StoreDefinition> storeDefList) { HashSet<String> storeSet = new HashSet<String>(); for(StoreDefinition def: storeDefList) { storeSet.add(def.getName()); } return storeSet; }
[ "public", "static", "Set", "<", "String", ">", "getStoreNamesSet", "(", "List", "<", "StoreDefinition", ">", "storeDefList", ")", "{", "HashSet", "<", "String", ">", "storeSet", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "Store...
Given a list of store definitions return a set of store names @param storeDefList The list of store definitions @return Returns a set of store names
[ "Given", "a", "list", "of", "store", "definitions", "return", "a", "set", "of", "store", "names" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/StoreDefinitionUtils.java#L88-L94
train
voldemort/voldemort
src/java/voldemort/utils/StoreDefinitionUtils.java
StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts
public static HashMap<StoreDefinition, Integer> getUniqueStoreDefinitionsWithCounts(List<StoreDefinition> storeDefs) { HashMap<StoreDefinition, Integer> uniqueStoreDefs = Maps.newHashMap(); for(StoreDefinition storeDef: storeDefs) { if(uniqueStoreDefs.isEmpty()) { uniqueStoreDefs.put(storeDef, 1); } else { StoreDefinition sameStore = null; // Go over all the other stores to find if this is unique for(StoreDefinition uniqueStoreDef: uniqueStoreDefs.keySet()) { if(uniqueStoreDef.getReplicationFactor() == storeDef.getReplicationFactor() && uniqueStoreDef.getRoutingStrategyType() .compareTo(storeDef.getRoutingStrategyType()) == 0) { // Further check for the zone routing case if(uniqueStoreDef.getRoutingStrategyType() .compareTo(RoutingStrategyType.ZONE_STRATEGY) == 0) { boolean zonesSame = true; for(int zoneId: uniqueStoreDef.getZoneReplicationFactor().keySet()) { if(storeDef.getZoneReplicationFactor().get(zoneId) == null || storeDef.getZoneReplicationFactor().get(zoneId) != uniqueStoreDef.getZoneReplicationFactor() .get(zoneId)) { zonesSame = false; break; } } if(zonesSame) { sameStore = uniqueStoreDef; } } else { sameStore = uniqueStoreDef; } if(sameStore != null) { // Bump up the count int currentCount = uniqueStoreDefs.get(sameStore); uniqueStoreDefs.put(sameStore, currentCount + 1); break; } } } if(sameStore == null) { // New store uniqueStoreDefs.put(storeDef, 1); } } } return uniqueStoreDefs; }
java
public static HashMap<StoreDefinition, Integer> getUniqueStoreDefinitionsWithCounts(List<StoreDefinition> storeDefs) { HashMap<StoreDefinition, Integer> uniqueStoreDefs = Maps.newHashMap(); for(StoreDefinition storeDef: storeDefs) { if(uniqueStoreDefs.isEmpty()) { uniqueStoreDefs.put(storeDef, 1); } else { StoreDefinition sameStore = null; // Go over all the other stores to find if this is unique for(StoreDefinition uniqueStoreDef: uniqueStoreDefs.keySet()) { if(uniqueStoreDef.getReplicationFactor() == storeDef.getReplicationFactor() && uniqueStoreDef.getRoutingStrategyType() .compareTo(storeDef.getRoutingStrategyType()) == 0) { // Further check for the zone routing case if(uniqueStoreDef.getRoutingStrategyType() .compareTo(RoutingStrategyType.ZONE_STRATEGY) == 0) { boolean zonesSame = true; for(int zoneId: uniqueStoreDef.getZoneReplicationFactor().keySet()) { if(storeDef.getZoneReplicationFactor().get(zoneId) == null || storeDef.getZoneReplicationFactor().get(zoneId) != uniqueStoreDef.getZoneReplicationFactor() .get(zoneId)) { zonesSame = false; break; } } if(zonesSame) { sameStore = uniqueStoreDef; } } else { sameStore = uniqueStoreDef; } if(sameStore != null) { // Bump up the count int currentCount = uniqueStoreDefs.get(sameStore); uniqueStoreDefs.put(sameStore, currentCount + 1); break; } } } if(sameStore == null) { // New store uniqueStoreDefs.put(storeDef, 1); } } } return uniqueStoreDefs; }
[ "public", "static", "HashMap", "<", "StoreDefinition", ",", "Integer", ">", "getUniqueStoreDefinitionsWithCounts", "(", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "HashMap", "<", "StoreDefinition", ",", "Integer", ">", "uniqueStoreDefs", "=", "Maps"...
Given a list of store definitions, find out and return a map of similar store definitions + count of them @param storeDefs All store definitions @return Map of a unique store definition + counts
[ "Given", "a", "list", "of", "store", "definitions", "find", "out", "and", "return", "a", "map", "of", "similar", "store", "definitions", "+", "count", "of", "them" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/StoreDefinitionUtils.java#L127-L178
train
voldemort/voldemort
src/java/voldemort/utils/StoreDefinitionUtils.java
StoreDefinitionUtils.isAvroSchema
public static boolean isAvroSchema(String serializerName) { if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME) || serializerName.equals(AVRO_GENERIC_TYPE_NAME) || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME) || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) { return true; } else { return false; } }
java
public static boolean isAvroSchema(String serializerName) { if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME) || serializerName.equals(AVRO_GENERIC_TYPE_NAME) || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME) || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) { return true; } else { return false; } }
[ "public", "static", "boolean", "isAvroSchema", "(", "String", "serializerName", ")", "{", "if", "(", "serializerName", ".", "equals", "(", "AVRO_GENERIC_VERSIONED_TYPE_NAME", ")", "||", "serializerName", ".", "equals", "(", "AVRO_GENERIC_TYPE_NAME", ")", "||", "seri...
Determine whether or not a given serializedr is "AVRO" based @param serializerName @return
[ "Determine", "whether", "or", "not", "a", "given", "serializedr", "is", "AVRO", "based" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/StoreDefinitionUtils.java#L186-L195
train
voldemort/voldemort
src/java/voldemort/utils/StoreDefinitionUtils.java
StoreDefinitionUtils.validateIfAvroSchema
private static void validateIfAvroSchema(SerializerDefinition serializerDef) { if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME) || serializerDef.getName().equals(AVRO_GENERIC_TYPE_NAME)) { SchemaEvolutionValidator.validateAllAvroSchemas(serializerDef); // check backwards compatibility if needed if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)) { SchemaEvolutionValidator.checkSchemaCompatibility(serializerDef); } } }
java
private static void validateIfAvroSchema(SerializerDefinition serializerDef) { if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME) || serializerDef.getName().equals(AVRO_GENERIC_TYPE_NAME)) { SchemaEvolutionValidator.validateAllAvroSchemas(serializerDef); // check backwards compatibility if needed if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)) { SchemaEvolutionValidator.checkSchemaCompatibility(serializerDef); } } }
[ "private", "static", "void", "validateIfAvroSchema", "(", "SerializerDefinition", "serializerDef", ")", "{", "if", "(", "serializerDef", ".", "getName", "(", ")", ".", "equals", "(", "AVRO_GENERIC_VERSIONED_TYPE_NAME", ")", "||", "serializerDef", ".", "getName", "("...
If provided with an AVRO schema, validates it and checks if there are backwards compatible. TODO should probably place some similar checks for other serializer types as well? @param serializerDef
[ "If", "provided", "with", "an", "AVRO", "schema", "validates", "it", "and", "checks", "if", "there", "are", "backwards", "compatible", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/StoreDefinitionUtils.java#L206-L215
train
voldemort/voldemort
src/java/voldemort/store/stats/Histogram.java
Histogram.insert
public synchronized void insert(long data) { resetIfNeeded(); long index = 0; if(data >= this.upperBound) { index = nBuckets - 1; } else if(data < 0) { logger.error(data + " can't be bucketed because it is negative!"); return; } else { index = data / step; } if(index < 0 || index >= nBuckets) { // This should be dead code. Defending against code changes in // future. logger.error(data + " can't be bucketed because index is not in range [0,nBuckets)."); return; } buckets[(int) index]++; sum += data; size++; }
java
public synchronized void insert(long data) { resetIfNeeded(); long index = 0; if(data >= this.upperBound) { index = nBuckets - 1; } else if(data < 0) { logger.error(data + " can't be bucketed because it is negative!"); return; } else { index = data / step; } if(index < 0 || index >= nBuckets) { // This should be dead code. Defending against code changes in // future. logger.error(data + " can't be bucketed because index is not in range [0,nBuckets)."); return; } buckets[(int) index]++; sum += data; size++; }
[ "public", "synchronized", "void", "insert", "(", "long", "data", ")", "{", "resetIfNeeded", "(", ")", ";", "long", "index", "=", "0", ";", "if", "(", "data", ">=", "this", ".", "upperBound", ")", "{", "index", "=", "nBuckets", "-", "1", ";", "}", "...
Insert a value into the right bucket of the histogram. If the value is larger than any bound, insert into the last bucket. If the value is less than zero, then ignore it. @param data The value to insert into the histogram
[ "Insert", "a", "value", "into", "the", "right", "bucket", "of", "the", "histogram", ".", "If", "the", "value", "is", "larger", "than", "any", "bound", "insert", "into", "the", "last", "bucket", ".", "If", "the", "value", "is", "less", "than", "zero", "...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/Histogram.java#L101-L121
train
voldemort/voldemort
src/java/voldemort/store/rebalancing/RebootstrappingStore.java
RebootstrappingStore.checkAndAddNodeStore
private void checkAndAddNodeStore() { for(Node node: metadata.getCluster().getNodes()) { if(!routedStore.getInnerStores().containsKey(node.getId())) { if(!storeRepository.hasNodeStore(getName(), node.getId())) { storeRepository.addNodeStore(node.getId(), createNodeStore(node)); } routedStore.getInnerStores().put(node.getId(), storeRepository.getNodeStore(getName(), node.getId())); } } }
java
private void checkAndAddNodeStore() { for(Node node: metadata.getCluster().getNodes()) { if(!routedStore.getInnerStores().containsKey(node.getId())) { if(!storeRepository.hasNodeStore(getName(), node.getId())) { storeRepository.addNodeStore(node.getId(), createNodeStore(node)); } routedStore.getInnerStores().put(node.getId(), storeRepository.getNodeStore(getName(), node.getId())); } } }
[ "private", "void", "checkAndAddNodeStore", "(", ")", "{", "for", "(", "Node", "node", ":", "metadata", ".", "getCluster", "(", ")", ".", "getNodes", "(", ")", ")", "{", "if", "(", "!", "routedStore", ".", "getInnerStores", "(", ")", ".", "containsKey", ...
Check that all nodes in the new cluster have a corresponding entry in storeRepository and innerStores. add a NodeStore if not present, is needed as with rebalancing we can add new nodes on the fly.
[ "Check", "that", "all", "nodes", "in", "the", "new", "cluster", "have", "a", "corresponding", "entry", "in", "storeRepository", "and", "innerStores", ".", "add", "a", "NodeStore", "if", "not", "present", "is", "needed", "as", "with", "rebalancing", "we", "ca...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/rebalancing/RebootstrappingStore.java#L93-L104
train
voldemort/voldemort
src/java/voldemort/utils/pool/ResourcePoolConfig.java
ResourcePoolConfig.setTimeout
public ResourcePoolConfig setTimeout(long timeout, TimeUnit unit) { if(timeout < 0) throw new IllegalArgumentException("The timeout must be a non-negative number."); this.timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, unit); return this; }
java
public ResourcePoolConfig setTimeout(long timeout, TimeUnit unit) { if(timeout < 0) throw new IllegalArgumentException("The timeout must be a non-negative number."); this.timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, unit); return this; }
[ "public", "ResourcePoolConfig", "setTimeout", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "{", "if", "(", "timeout", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"The timeout must be a non-negative number.\"", ")", ";", "this", ".", ...
The timeout which we block for when a resource is not available @param timeout The timeout @param unit The units of the timeout
[ "The", "timeout", "which", "we", "block", "for", "when", "a", "resource", "is", "not", "available" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/ResourcePoolConfig.java#L59-L64
train
voldemort/voldemort
contrib/krati/src/java/voldemort/store/krati/KratiStorageEngine.java
KratiStorageEngine.assembleValues
private byte[] assembleValues(List<Versioned<byte[]>> values) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream dataStream = new DataOutputStream(stream); for(Versioned<byte[]> value: values) { byte[] object = value.getValue(); dataStream.writeInt(object.length); dataStream.write(object); VectorClock clock = (VectorClock) value.getVersion(); dataStream.writeInt(clock.sizeInBytes()); dataStream.write(clock.toBytes()); } return stream.toByteArray(); }
java
private byte[] assembleValues(List<Versioned<byte[]>> values) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream dataStream = new DataOutputStream(stream); for(Versioned<byte[]> value: values) { byte[] object = value.getValue(); dataStream.writeInt(object.length); dataStream.write(object); VectorClock clock = (VectorClock) value.getVersion(); dataStream.writeInt(clock.sizeInBytes()); dataStream.write(clock.toBytes()); } return stream.toByteArray(); }
[ "private", "byte", "[", "]", "assembleValues", "(", "List", "<", "Versioned", "<", "byte", "[", "]", ">", ">", "values", ")", "throws", "IOException", "{", "ByteArrayOutputStream", "stream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "DataOutputStream...
Store the versioned values @param values list of versioned bytes @return the list of versioned values rolled into an array of bytes
[ "Store", "the", "versioned", "values" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/krati/src/java/voldemort/store/krati/KratiStorageEngine.java#L266-L282
train
voldemort/voldemort
contrib/krati/src/java/voldemort/store/krati/KratiStorageEngine.java
KratiStorageEngine.disassembleValues
private List<Versioned<byte[]>> disassembleValues(byte[] values) throws IOException { if(values == null) return new ArrayList<Versioned<byte[]>>(0); List<Versioned<byte[]>> returnList = new ArrayList<Versioned<byte[]>>(); ByteArrayInputStream stream = new ByteArrayInputStream(values); DataInputStream dataStream = new DataInputStream(stream); while(dataStream.available() > 0) { byte[] object = new byte[dataStream.readInt()]; dataStream.read(object); byte[] clockBytes = new byte[dataStream.readInt()]; dataStream.read(clockBytes); VectorClock clock = new VectorClock(clockBytes); returnList.add(new Versioned<byte[]>(object, clock)); } return returnList; }
java
private List<Versioned<byte[]>> disassembleValues(byte[] values) throws IOException { if(values == null) return new ArrayList<Versioned<byte[]>>(0); List<Versioned<byte[]>> returnList = new ArrayList<Versioned<byte[]>>(); ByteArrayInputStream stream = new ByteArrayInputStream(values); DataInputStream dataStream = new DataInputStream(stream); while(dataStream.available() > 0) { byte[] object = new byte[dataStream.readInt()]; dataStream.read(object); byte[] clockBytes = new byte[dataStream.readInt()]; dataStream.read(clockBytes); VectorClock clock = new VectorClock(clockBytes); returnList.add(new Versioned<byte[]>(object, clock)); } return returnList; }
[ "private", "List", "<", "Versioned", "<", "byte", "[", "]", ">", ">", "disassembleValues", "(", "byte", "[", "]", "values", ")", "throws", "IOException", "{", "if", "(", "values", "==", "null", ")", "return", "new", "ArrayList", "<", "Versioned", "<", ...
Splits up value into multiple versioned values @param value @return @throws IOException
[ "Splits", "up", "value", "into", "multiple", "versioned", "values" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/krati/src/java/voldemort/store/krati/KratiStorageEngine.java#L291-L312
train
voldemort/voldemort
src/java/voldemort/server/protocol/admin/PartitionScanFetchStreamRequestHandler.java
PartitionScanFetchStreamRequestHandler.statusInfoMessage
protected void statusInfoMessage(final String tag) { if(logger.isInfoEnabled()) { logger.info(tag + " : [partition: " + currentPartition + ", partitionFetched: " + currentPartitionFetched + "] for store " + storageEngine.getName()); } }
java
protected void statusInfoMessage(final String tag) { if(logger.isInfoEnabled()) { logger.info(tag + " : [partition: " + currentPartition + ", partitionFetched: " + currentPartitionFetched + "] for store " + storageEngine.getName()); } }
[ "protected", "void", "statusInfoMessage", "(", "final", "String", "tag", ")", "{", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "logger", ".", "info", "(", "tag", "+", "\" : [partition: \"", "+", "currentPartition", "+", "\", partitionFetched...
Simple info message for status @param tag Message to print out at start of info message
[ "Simple", "info", "message", "for", "status" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/PartitionScanFetchStreamRequestHandler.java#L75-L81
train
voldemort/voldemort
src/java/voldemort/server/scheduler/slop/StreamingSlopPusherJob.java
StreamingSlopPusherJob.slopSize
private int slopSize(Versioned<Slop> slopVersioned) { int nBytes = 0; Slop slop = slopVersioned.getValue(); nBytes += slop.getKey().length(); nBytes += ((VectorClock) slopVersioned.getVersion()).sizeInBytes(); switch(slop.getOperation()) { case PUT: { nBytes += slop.getValue().length; break; } case DELETE: { break; } default: logger.error("Unknown slop operation: " + slop.getOperation()); } return nBytes; }
java
private int slopSize(Versioned<Slop> slopVersioned) { int nBytes = 0; Slop slop = slopVersioned.getValue(); nBytes += slop.getKey().length(); nBytes += ((VectorClock) slopVersioned.getVersion()).sizeInBytes(); switch(slop.getOperation()) { case PUT: { nBytes += slop.getValue().length; break; } case DELETE: { break; } default: logger.error("Unknown slop operation: " + slop.getOperation()); } return nBytes; }
[ "private", "int", "slopSize", "(", "Versioned", "<", "Slop", ">", "slopVersioned", ")", "{", "int", "nBytes", "=", "0", ";", "Slop", "slop", "=", "slopVersioned", ".", "getValue", "(", ")", ";", "nBytes", "+=", "slop", ".", "getKey", "(", ")", ".", "...
Returns the approximate size of slop to help in throttling @param slopVersioned The versioned slop whose size we want @return Size in bytes
[ "Returns", "the", "approximate", "size", "of", "slop", "to", "help", "in", "throttling" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/scheduler/slop/StreamingSlopPusherJob.java#L328-L345
train
voldemort/voldemort
contrib/restclient/src/java/voldemort/restclient/RESTClientFactory.java
RESTClientFactory.getStoreClient
@Override public <K, V> StoreClient<K, V> getStoreClient(final String storeName, final InconsistencyResolver<Versioned<V>> resolver) { // wrap it in LazyStoreClient here so any direct calls to this method // returns a lazy client return new LazyStoreClient<K, V>(new Callable<StoreClient<K, V>>() { @Override public StoreClient<K, V> call() throws Exception { Store<K, V, Object> clientStore = getRawStore(storeName, resolver); return new RESTClient<K, V>(storeName, clientStore); } }, true); }
java
@Override public <K, V> StoreClient<K, V> getStoreClient(final String storeName, final InconsistencyResolver<Versioned<V>> resolver) { // wrap it in LazyStoreClient here so any direct calls to this method // returns a lazy client return new LazyStoreClient<K, V>(new Callable<StoreClient<K, V>>() { @Override public StoreClient<K, V> call() throws Exception { Store<K, V, Object> clientStore = getRawStore(storeName, resolver); return new RESTClient<K, V>(storeName, clientStore); } }, true); }
[ "@", "Override", "public", "<", "K", ",", "V", ">", "StoreClient", "<", "K", ",", "V", ">", "getStoreClient", "(", "final", "String", "storeName", ",", "final", "InconsistencyResolver", "<", "Versioned", "<", "V", ">", ">", "resolver", ")", "{", "// wrap...
Creates a REST client used to perform Voldemort operations against the Coordinator @param storeName Name of the store to perform the operations on @param resolver Custom resolver as specified by the application @return
[ "Creates", "a", "REST", "client", "used", "to", "perform", "Voldemort", "operations", "against", "the", "Coordinator" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/restclient/src/java/voldemort/restclient/RESTClientFactory.java#L105-L118
train
voldemort/voldemort
src/java/voldemort/routing/ConsistentRoutingStrategy.java
ConsistentRoutingStrategy.abs
private static int abs(int a) { if(a >= 0) return a; else if(a != Integer.MIN_VALUE) return -a; return Integer.MAX_VALUE; }
java
private static int abs(int a) { if(a >= 0) return a; else if(a != Integer.MIN_VALUE) return -a; return Integer.MAX_VALUE; }
[ "private", "static", "int", "abs", "(", "int", "a", ")", "{", "if", "(", "a", ">=", "0", ")", "return", "a", ";", "else", "if", "(", "a", "!=", "Integer", ".", "MIN_VALUE", ")", "return", "-", "a", ";", "return", "Integer", ".", "MAX_VALUE", ";",...
A modified version of abs that always returns a non-negative value. Math.abs returns Integer.MIN_VALUE if a == Integer.MIN_VALUE and this method returns Integer.MAX_VALUE in that case.
[ "A", "modified", "version", "of", "abs", "that", "always", "returns", "a", "non", "-", "negative", "value", ".", "Math", ".", "abs", "returns", "Integer", ".", "MIN_VALUE", "if", "a", "==", "Integer", ".", "MIN_VALUE", "and", "this", "method", "returns", ...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/ConsistentRoutingStrategy.java#L106-L112
train
voldemort/voldemort
src/java/voldemort/routing/ConsistentRoutingStrategy.java
ConsistentRoutingStrategy.getMasterPartition
@Override public Integer getMasterPartition(byte[] key) { return abs(hash.hash(key)) % (Math.max(1, this.partitionToNode.length)); }
java
@Override public Integer getMasterPartition(byte[] key) { return abs(hash.hash(key)) % (Math.max(1, this.partitionToNode.length)); }
[ "@", "Override", "public", "Integer", "getMasterPartition", "(", "byte", "[", "]", "key", ")", "{", "return", "abs", "(", "hash", ".", "hash", "(", "key", ")", ")", "%", "(", "Math", ".", "max", "(", "1", ",", "this", ".", "partitionToNode", ".", "...
Obtain the master partition for a given key @param key @return master partition id
[ "Obtain", "the", "master", "partition", "for", "a", "given", "key" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/ConsistentRoutingStrategy.java#L170-L173
train
voldemort/voldemort
src/java/voldemort/server/scheduler/slop/SlopPusherJob.java
SlopPusherJob.isSlopDead
protected boolean isSlopDead(Cluster cluster, Set<String> storeNames, Slop slop) { // destination node , no longer exists if(!cluster.getNodeIds().contains(slop.getNodeId())) { return true; } // destination store, no longer exists if(!storeNames.contains(slop.getStoreName())) { return true; } // else. slop is alive return false; }
java
protected boolean isSlopDead(Cluster cluster, Set<String> storeNames, Slop slop) { // destination node , no longer exists if(!cluster.getNodeIds().contains(slop.getNodeId())) { return true; } // destination store, no longer exists if(!storeNames.contains(slop.getStoreName())) { return true; } // else. slop is alive return false; }
[ "protected", "boolean", "isSlopDead", "(", "Cluster", "cluster", ",", "Set", "<", "String", ">", "storeNames", ",", "Slop", "slop", ")", "{", "// destination node , no longer exists", "if", "(", "!", "cluster", ".", "getNodeIds", "(", ")", ".", "contains", "("...
A slop is dead if the destination node or the store does not exist anymore on the cluster. @param slop @return
[ "A", "slop", "is", "dead", "if", "the", "destination", "node", "or", "the", "store", "does", "not", "exist", "anymore", "on", "the", "cluster", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/scheduler/slop/SlopPusherJob.java#L52-L65
train
voldemort/voldemort
src/java/voldemort/server/scheduler/slop/SlopPusherJob.java
SlopPusherJob.handleDeadSlop
protected void handleDeadSlop(SlopStorageEngine slopStorageEngine, Pair<ByteArray, Versioned<Slop>> keyAndVal) { Versioned<Slop> versioned = keyAndVal.getSecond(); // If configured to delete the dead slop if(voldemortConfig.getAutoPurgeDeadSlops()) { slopStorageEngine.delete(keyAndVal.getFirst(), versioned.getVersion()); if(getLogger().isDebugEnabled()) { getLogger().debug("Auto purging dead slop :" + versioned.getValue()); } } else { // Keep ignoring the dead slops if(getLogger().isDebugEnabled()) { getLogger().debug("Ignoring dead slop :" + versioned.getValue()); } } }
java
protected void handleDeadSlop(SlopStorageEngine slopStorageEngine, Pair<ByteArray, Versioned<Slop>> keyAndVal) { Versioned<Slop> versioned = keyAndVal.getSecond(); // If configured to delete the dead slop if(voldemortConfig.getAutoPurgeDeadSlops()) { slopStorageEngine.delete(keyAndVal.getFirst(), versioned.getVersion()); if(getLogger().isDebugEnabled()) { getLogger().debug("Auto purging dead slop :" + versioned.getValue()); } } else { // Keep ignoring the dead slops if(getLogger().isDebugEnabled()) { getLogger().debug("Ignoring dead slop :" + versioned.getValue()); } } }
[ "protected", "void", "handleDeadSlop", "(", "SlopStorageEngine", "slopStorageEngine", ",", "Pair", "<", "ByteArray", ",", "Versioned", "<", "Slop", ">", ">", "keyAndVal", ")", "{", "Versioned", "<", "Slop", ">", "versioned", "=", "keyAndVal", ".", "getSecond", ...
Handle slop for nodes that are no longer part of the cluster. It may not always be the case. For example, shrinking a zone or deleting a store.
[ "Handle", "slop", "for", "nodes", "that", "are", "no", "longer", "part", "of", "the", "cluster", ".", "It", "may", "not", "always", "be", "the", "case", ".", "For", "example", "shrinking", "a", "zone", "or", "deleting", "a", "store", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/scheduler/slop/SlopPusherJob.java#L71-L87
train
voldemort/voldemort
src/java/voldemort/store/socket/clientrequest/ClientRequestExecutorFactory.java
ClientRequestExecutorFactory.destroy
@Override public void destroy(SocketDestination dest, ClientRequestExecutor clientRequestExecutor) throws Exception { clientRequestExecutor.close(); int numDestroyed = destroyed.incrementAndGet(); if(stats != null) { stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_DESTROYED_EVENT); } if(logger.isDebugEnabled()) logger.debug("Destroyed socket " + numDestroyed + " connection to " + dest.getHost() + ":" + dest.getPort()); }
java
@Override public void destroy(SocketDestination dest, ClientRequestExecutor clientRequestExecutor) throws Exception { clientRequestExecutor.close(); int numDestroyed = destroyed.incrementAndGet(); if(stats != null) { stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_DESTROYED_EVENT); } if(logger.isDebugEnabled()) logger.debug("Destroyed socket " + numDestroyed + " connection to " + dest.getHost() + ":" + dest.getPort()); }
[ "@", "Override", "public", "void", "destroy", "(", "SocketDestination", "dest", ",", "ClientRequestExecutor", "clientRequestExecutor", ")", "throws", "Exception", "{", "clientRequestExecutor", ".", "close", "(", ")", ";", "int", "numDestroyed", "=", "destroyed", "."...
Close the ClientRequestExecutor.
[ "Close", "the", "ClientRequestExecutor", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/socket/clientrequest/ClientRequestExecutorFactory.java#L120-L132
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java
ClientConfigUtil.readSingleClientConfigAvro
@SuppressWarnings("unchecked") public static Properties readSingleClientConfigAvro(String configAvro) { Properties props = new Properties(); try { JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIG_AVRO_SCHEMA, configAvro); GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIG_AVRO_SCHEMA); Map<Utf8, Utf8> flowMap = (Map<Utf8, Utf8>) datumReader.read(null, decoder); for(Utf8 key: flowMap.keySet()) { props.put(key.toString(), flowMap.get(key).toString()); } } catch(Exception e) { e.printStackTrace(); } return props; }
java
@SuppressWarnings("unchecked") public static Properties readSingleClientConfigAvro(String configAvro) { Properties props = new Properties(); try { JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIG_AVRO_SCHEMA, configAvro); GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIG_AVRO_SCHEMA); Map<Utf8, Utf8> flowMap = (Map<Utf8, Utf8>) datumReader.read(null, decoder); for(Utf8 key: flowMap.keySet()) { props.put(key.toString(), flowMap.get(key).toString()); } } catch(Exception e) { e.printStackTrace(); } return props; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Properties", "readSingleClientConfigAvro", "(", "String", "configAvro", ")", "{", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "try", "{", "JsonDecoder", "decoder", "=", ...
Parses a string that contains single fat client config string in avro format @param configAvro Input string of avro format, that contains config for multiple stores @return Properties of single fat client config
[ "Parses", "a", "string", "that", "contains", "single", "fat", "client", "config", "string", "in", "avro", "format" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java#L34-L48
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java
ClientConfigUtil.readMultipleClientConfigAvro
@SuppressWarnings("unchecked") public static Map<String, Properties> readMultipleClientConfigAvro(String configAvro) { Map<String, Properties> mapStoreToProps = Maps.newHashMap(); try { JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIGS_AVRO_SCHEMA, configAvro); GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIGS_AVRO_SCHEMA); Map<Utf8, Map<Utf8, Utf8>> storeConfigs = (Map<Utf8, Map<Utf8, Utf8>>) datumReader.read(null, decoder); // Store config props to return back for(Utf8 storeName: storeConfigs.keySet()) { Properties props = new Properties(); Map<Utf8, Utf8> singleConfig = storeConfigs.get(storeName); for(Utf8 key: singleConfig.keySet()) { props.put(key.toString(), singleConfig.get(key).toString()); } if(storeName == null || storeName.length() == 0) { throw new Exception("Invalid store name found!"); } mapStoreToProps.put(storeName.toString(), props); } } catch(Exception e) { e.printStackTrace(); } return mapStoreToProps; }
java
@SuppressWarnings("unchecked") public static Map<String, Properties> readMultipleClientConfigAvro(String configAvro) { Map<String, Properties> mapStoreToProps = Maps.newHashMap(); try { JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIGS_AVRO_SCHEMA, configAvro); GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIGS_AVRO_SCHEMA); Map<Utf8, Map<Utf8, Utf8>> storeConfigs = (Map<Utf8, Map<Utf8, Utf8>>) datumReader.read(null, decoder); // Store config props to return back for(Utf8 storeName: storeConfigs.keySet()) { Properties props = new Properties(); Map<Utf8, Utf8> singleConfig = storeConfigs.get(storeName); for(Utf8 key: singleConfig.keySet()) { props.put(key.toString(), singleConfig.get(key).toString()); } if(storeName == null || storeName.length() == 0) { throw new Exception("Invalid store name found!"); } mapStoreToProps.put(storeName.toString(), props); } } catch(Exception e) { e.printStackTrace(); } return mapStoreToProps; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Map", "<", "String", ",", "Properties", ">", "readMultipleClientConfigAvro", "(", "String", "configAvro", ")", "{", "Map", "<", "String", ",", "Properties", ">", "mapStoreToProps", "=", "Ma...
Parses a string that contains multiple fat client configs in avro format @param configAvro Input string of avro format, that contains config for multiple stores @return Map of store names to store config properties
[ "Parses", "a", "string", "that", "contains", "multiple", "fat", "client", "configs", "in", "avro", "format" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java#L57-L85
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java
ClientConfigUtil.writeSingleClientConfigAvro
public static String writeSingleClientConfigAvro(Properties props) { // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json... String avroConfig = ""; Boolean firstProp = true; for(String key: props.stringPropertyNames()) { if(firstProp) { firstProp = false; } else { avroConfig = avroConfig + ",\n"; } avroConfig = avroConfig + "\t\t\"" + key + "\": \"" + props.getProperty(key) + "\""; } if(avroConfig.isEmpty()) { return "{}"; } else { return "{\n" + avroConfig + "\n\t}"; } }
java
public static String writeSingleClientConfigAvro(Properties props) { // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json... String avroConfig = ""; Boolean firstProp = true; for(String key: props.stringPropertyNames()) { if(firstProp) { firstProp = false; } else { avroConfig = avroConfig + ",\n"; } avroConfig = avroConfig + "\t\t\"" + key + "\": \"" + props.getProperty(key) + "\""; } if(avroConfig.isEmpty()) { return "{}"; } else { return "{\n" + avroConfig + "\n\t}"; } }
[ "public", "static", "String", "writeSingleClientConfigAvro", "(", "Properties", "props", ")", "{", "// TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...", "String", "avroConfig", "=", "\"\"", ";", "Boolean", "firstProp", "=", "true", ";", "for", ...
Assembles an avro format string of single store config from store properties @param props Store properties @return String in avro format that contains single store configs
[ "Assembles", "an", "avro", "format", "string", "of", "single", "store", "config", "from", "store", "properties" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java#L94-L111
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java
ClientConfigUtil.writeMultipleClientConfigAvro
public static String writeMultipleClientConfigAvro(Map<String, Properties> mapStoreToProps) { // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json... String avroConfig = ""; Boolean firstStore = true; for(String storeName: mapStoreToProps.keySet()) { if(firstStore) { firstStore = false; } else { avroConfig = avroConfig + ",\n"; } Properties props = mapStoreToProps.get(storeName); avroConfig = avroConfig + "\t\"" + storeName + "\": " + writeSingleClientConfigAvro(props); } return "{\n" + avroConfig + "\n}"; }
java
public static String writeMultipleClientConfigAvro(Map<String, Properties> mapStoreToProps) { // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json... String avroConfig = ""; Boolean firstStore = true; for(String storeName: mapStoreToProps.keySet()) { if(firstStore) { firstStore = false; } else { avroConfig = avroConfig + ",\n"; } Properties props = mapStoreToProps.get(storeName); avroConfig = avroConfig + "\t\"" + storeName + "\": " + writeSingleClientConfigAvro(props); } return "{\n" + avroConfig + "\n}"; }
[ "public", "static", "String", "writeMultipleClientConfigAvro", "(", "Map", "<", "String", ",", "Properties", ">", "mapStoreToProps", ")", "{", "// TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...", "String", "avroConfig", "=", "\"\"", ";", "Boolea...
Assembles an avro format string that contains multiple fat client configs from map of store to properties @param mapStoreToProps A map of store names to their properties @return Avro string that contains multiple store configs
[ "Assembles", "an", "avro", "format", "string", "that", "contains", "multiple", "fat", "client", "configs", "from", "map", "of", "store", "to", "properties" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/config/ClientConfigUtil.java#L120-L136
train
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", "=", "readSingleClientC...
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
train
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", ")", ";",...
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
train
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", "(", "\"--------------------...
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
train
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"...
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
train
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", ".", "val...
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
train
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...
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
train
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", ")", "{"...
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", "t...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L255-L265
train
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", "...
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", ...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L279-L317
train
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 ...
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", ...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L454-L475
train
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 ...
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
train
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", "retu...
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
train
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",...
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
train
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...
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
train
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"...
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", ".", "Ch...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L776-L840
train
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", "<"...
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"...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/Repartitioner.java#L862-L907
train
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", ".", "ne...
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
train
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", ...
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
train
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 cons...
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
train
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", "...
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
train
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", "totalTimeM...
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
train
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", "rat...
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
train
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", ">",...
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
train
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.\"", ")", ";", "tr...
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
train
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",...
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"...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceController.java#L563-L679
train
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", "latestVers...
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
train
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", ">", "keysToDele...
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
train
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", "=", ...
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
train
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", ...
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
train
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 * ver...
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
train
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", ">", "(", ...
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
train
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
train
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 fas...
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
train
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.", "whi...
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
train
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", ")", "{", ...
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
train
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", ...
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
train
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", "(", ...
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
train
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", ">", "("...
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
train
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", "=", "getMapOfContiguousPartit...
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
train
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",...
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
train
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", ".",...
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
train
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", ")...
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", ...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/PartitionBalanceUtils.java#L320-L369
train
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", ...
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
train
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
train
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
train
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", ...
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",...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L143-L154
train
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", "(", ")", ")", "{", "retur...
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
train
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 process...
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
train
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...
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
train
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", ...
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
train
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"...
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
train
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", ".", "ent...
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", ...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L373-L380
train