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/store/metadata/MetadataStore.java
MetadataStore.init
private void init() { logger.info("metadata init()."); writeLock.lock(); try { // Required keys initCache(CLUSTER_KEY); // If stores definition storage engine is not null, initialize metadata // Add the mapping from key to the storage engine used if(this.storeDefinitionsStorageEngine != null) { initStoreDefinitions(null); } else { initCache(STORES_KEY); } // Initialize system store in the metadata cache initSystemCache(); initSystemRoutingStrategies(getCluster()); // Initialize with default if not present initCache(SLOP_STREAMING_ENABLED_KEY, true); initCache(PARTITION_STREAMING_ENABLED_KEY, true); initCache(READONLY_FETCH_ENABLED_KEY, true); initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true); initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>())); initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString()); initCache(REBALANCING_SOURCE_CLUSTER_XML, null); initCache(REBALANCING_SOURCE_STORES_XML, null); } finally { writeLock.unlock(); } }
java
private void init() { logger.info("metadata init()."); writeLock.lock(); try { // Required keys initCache(CLUSTER_KEY); // If stores definition storage engine is not null, initialize metadata // Add the mapping from key to the storage engine used if(this.storeDefinitionsStorageEngine != null) { initStoreDefinitions(null); } else { initCache(STORES_KEY); } // Initialize system store in the metadata cache initSystemCache(); initSystemRoutingStrategies(getCluster()); // Initialize with default if not present initCache(SLOP_STREAMING_ENABLED_KEY, true); initCache(PARTITION_STREAMING_ENABLED_KEY, true); initCache(READONLY_FETCH_ENABLED_KEY, true); initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true); initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>())); initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString()); initCache(REBALANCING_SOURCE_CLUSTER_XML, null); initCache(REBALANCING_SOURCE_STORES_XML, null); } finally { writeLock.unlock(); } }
[ "private", "void", "init", "(", ")", "{", "logger", ".", "info", "(", "\"metadata init().\"", ")", ";", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "// Required keys", "initCache", "(", "CLUSTER_KEY", ")", ";", "// If stores definition storage engine is...
Initializes the metadataCache for MetadataStore
[ "Initializes", "the", "metadataCache", "for", "MetadataStore" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L1188-L1222
train
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.initStoreDefinitions
private void initStoreDefinitions(Version storesXmlVersion) { if(this.storeDefinitionsStorageEngine == null) { throw new VoldemortException("The store definitions directory is empty"); } String allStoreDefinitions = "<stores>"; Version finalStoresXmlVersion = null; if(storesXmlVersion != null) { finalStoresXmlVersion = storesXmlVersion; } this.storeNames.clear(); ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries(); // Some test setups may result in duplicate entries for 'store' element. // Do the de-dup here Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>(); Version maxVersion = null; while(storesIterator.hasNext()) { Pair<String, Versioned<String>> storeDetail = storesIterator.next(); String storeName = storeDetail.getFirst(); Versioned<String> versionedStoreDef = storeDetail.getSecond(); storeNameToDefMap.put(storeName, versionedStoreDef); Version curVersion = versionedStoreDef.getVersion(); // Get the highest version from all the store entries if(maxVersion == null) { maxVersion = curVersion; } else if(maxVersion.compare(curVersion) == Occurred.BEFORE) { maxVersion = curVersion; } } // If the specified version is null, assign highest Version to // 'stores.xml' key if(finalStoresXmlVersion == null) { finalStoresXmlVersion = maxVersion; } // Go through all the individual stores and update metadata for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) { String storeName = storeEntry.getKey(); Versioned<String> versionedStoreDef = storeEntry.getValue(); // Add all the store names to the list of storeNames this.storeNames.add(storeName); this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(), versionedStoreDef.getVersion())); } Collections.sort(this.storeNames); for(String storeName: this.storeNames) { Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName); // Stitch together to form the complete store definition list. allStoreDefinitions += versionedStoreDef.getValue(); } allStoreDefinitions += "</stores>"; // Update cache with the composite store definition list. metadataCache.put(STORES_KEY, convertStringToObject(STORES_KEY, new Versioned<String>(allStoreDefinitions, finalStoresXmlVersion))); }
java
private void initStoreDefinitions(Version storesXmlVersion) { if(this.storeDefinitionsStorageEngine == null) { throw new VoldemortException("The store definitions directory is empty"); } String allStoreDefinitions = "<stores>"; Version finalStoresXmlVersion = null; if(storesXmlVersion != null) { finalStoresXmlVersion = storesXmlVersion; } this.storeNames.clear(); ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries(); // Some test setups may result in duplicate entries for 'store' element. // Do the de-dup here Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>(); Version maxVersion = null; while(storesIterator.hasNext()) { Pair<String, Versioned<String>> storeDetail = storesIterator.next(); String storeName = storeDetail.getFirst(); Versioned<String> versionedStoreDef = storeDetail.getSecond(); storeNameToDefMap.put(storeName, versionedStoreDef); Version curVersion = versionedStoreDef.getVersion(); // Get the highest version from all the store entries if(maxVersion == null) { maxVersion = curVersion; } else if(maxVersion.compare(curVersion) == Occurred.BEFORE) { maxVersion = curVersion; } } // If the specified version is null, assign highest Version to // 'stores.xml' key if(finalStoresXmlVersion == null) { finalStoresXmlVersion = maxVersion; } // Go through all the individual stores and update metadata for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) { String storeName = storeEntry.getKey(); Versioned<String> versionedStoreDef = storeEntry.getValue(); // Add all the store names to the list of storeNames this.storeNames.add(storeName); this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(), versionedStoreDef.getVersion())); } Collections.sort(this.storeNames); for(String storeName: this.storeNames) { Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName); // Stitch together to form the complete store definition list. allStoreDefinitions += versionedStoreDef.getValue(); } allStoreDefinitions += "</stores>"; // Update cache with the composite store definition list. metadataCache.put(STORES_KEY, convertStringToObject(STORES_KEY, new Versioned<String>(allStoreDefinitions, finalStoresXmlVersion))); }
[ "private", "void", "initStoreDefinitions", "(", "Version", "storesXmlVersion", ")", "{", "if", "(", "this", ".", "storeDefinitionsStorageEngine", "==", "null", ")", "{", "throw", "new", "VoldemortException", "(", "\"The store definitions directory is empty\"", ")", ";",...
Function to go through all the store definitions contained in the STORES directory and 1. Update metadata cache. 2. Update STORES_KEY by stitching together all these keys. 3. Update 'storeNames' list. This method is not thread safe. It is expected that the caller of this method will correctly handle concurrency issues. Currently this is not an issue since its invoked by init, put, add and delete store all of which use locks to deal with any concurrency related issues.
[ "Function", "to", "go", "through", "all", "the", "store", "definitions", "contained", "in", "the", "STORES", "directory", "and" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L1239-L1305
train
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.resetStoreDefinitions
private void resetStoreDefinitions(Set<String> storeNamesToDelete) { // Clear entries in the metadata cache for(String storeName: storeNamesToDelete) { this.metadataCache.remove(storeName); this.storeDefinitionsStorageEngine.delete(storeName, null); this.storeNames.remove(storeName); } }
java
private void resetStoreDefinitions(Set<String> storeNamesToDelete) { // Clear entries in the metadata cache for(String storeName: storeNamesToDelete) { this.metadataCache.remove(storeName); this.storeDefinitionsStorageEngine.delete(storeName, null); this.storeNames.remove(storeName); } }
[ "private", "void", "resetStoreDefinitions", "(", "Set", "<", "String", ">", "storeNamesToDelete", ")", "{", "// Clear entries in the metadata cache", "for", "(", "String", "storeName", ":", "storeNamesToDelete", ")", "{", "this", ".", "metadataCache", ".", "remove", ...
Function to clear all the metadata related to the given store definitions. This is needed when a put on 'stores.xml' is called, thus replacing the existing state. This method is not thread safe. It is expected that the caller of this method will handle concurrency related issues. @param storeNamesToDelete
[ "Function", "to", "clear", "all", "the", "metadata", "related", "to", "the", "given", "store", "definitions", ".", "This", "is", "needed", "when", "a", "put", "on", "stores", ".", "xml", "is", "called", "thus", "replacing", "the", "existing", "state", "." ...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L1317-L1324
train
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.initSystemCache
private synchronized void initSystemCache() { List<StoreDefinition> value = storeMapper.readStoreList(new StringReader(SystemStoreConstants.SYSTEM_STORE_SCHEMA)); metadataCache.put(SYSTEM_STORES_KEY, new Versioned<Object>(value)); }
java
private synchronized void initSystemCache() { List<StoreDefinition> value = storeMapper.readStoreList(new StringReader(SystemStoreConstants.SYSTEM_STORE_SCHEMA)); metadataCache.put(SYSTEM_STORES_KEY, new Versioned<Object>(value)); }
[ "private", "synchronized", "void", "initSystemCache", "(", ")", "{", "List", "<", "StoreDefinition", ">", "value", "=", "storeMapper", ".", "readStoreList", "(", "new", "StringReader", "(", "SystemStoreConstants", ".", "SYSTEM_STORE_SCHEMA", ")", ")", ";", "metada...
Initialize the metadata cache with system store list
[ "Initialize", "the", "metadata", "cache", "with", "system", "store", "list" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L1331-L1334
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java
DynamicTimeoutStoreClient.getWithCustomTimeout
public List<Versioned<V>> getWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) { validateTimeout(requestWrapper.getRoutingTimeoutInMs()); for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) { try { long startTimeInMs = System.currentTimeMillis(); String keyHexString = ""; if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) requestWrapper.getKey(); keyHexString = RestUtils.getKeyHexString(key); debugLogStart("GET", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, keyHexString); } List<Versioned<V>> items = store.get(requestWrapper); if(logger.isDebugEnabled()) { int vcEntrySize = 0; for(Versioned<V> vc: items) { vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size(); } debugLogEnd("GET", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, System.currentTimeMillis(), keyHexString, vcEntrySize); } return items; } catch(InvalidMetadataException e) { logger.info("Received invalid metadata exception during get [ " + e.getMessage() + " ] on store '" + storeName + "'. Rebootstrapping"); bootStrap(); } } throw new VoldemortException(this.metadataRefreshAttempts + " metadata refresh attempts failed."); }
java
public List<Versioned<V>> getWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) { validateTimeout(requestWrapper.getRoutingTimeoutInMs()); for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) { try { long startTimeInMs = System.currentTimeMillis(); String keyHexString = ""; if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) requestWrapper.getKey(); keyHexString = RestUtils.getKeyHexString(key); debugLogStart("GET", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, keyHexString); } List<Versioned<V>> items = store.get(requestWrapper); if(logger.isDebugEnabled()) { int vcEntrySize = 0; for(Versioned<V> vc: items) { vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size(); } debugLogEnd("GET", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, System.currentTimeMillis(), keyHexString, vcEntrySize); } return items; } catch(InvalidMetadataException e) { logger.info("Received invalid metadata exception during get [ " + e.getMessage() + " ] on store '" + storeName + "'. Rebootstrapping"); bootStrap(); } } throw new VoldemortException(this.metadataRefreshAttempts + " metadata refresh attempts failed."); }
[ "public", "List", "<", "Versioned", "<", "V", ">", ">", "getWithCustomTimeout", "(", "CompositeVoldemortRequest", "<", "K", ",", "V", ">", "requestWrapper", ")", "{", "validateTimeout", "(", "requestWrapper", ".", "getRoutingTimeoutInMs", "(", ")", ")", ";", "...
Performs a get operation with the specified composite request object @param requestWrapper A composite request object containing the key (and / or default value) and timeout. @return The Versioned value corresponding to the key
[ "Performs", "a", "get", "operation", "with", "the", "specified", "composite", "request", "object" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java#L99-L135
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java
DynamicTimeoutStoreClient.putWithCustomTimeout
public Version putWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) { validateTimeout(requestWrapper.getRoutingTimeoutInMs()); List<Versioned<V>> versionedValues; long startTime = System.currentTimeMillis(); String keyHexString = ""; if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) requestWrapper.getKey(); keyHexString = RestUtils.getKeyHexString(key); logger.debug("PUT requested for key: " + keyHexString + " , for store: " + this.storeName + " at time(in ms): " + startTime + " . Nested GET and PUT VERSION requests to follow ---"); } // We use the full timeout for doing the Get. In this, we're being // optimistic that the subsequent put might be faster such that all the // steps might finish within the allotted time requestWrapper.setResolveConflicts(true); versionedValues = getWithCustomTimeout(requestWrapper); Versioned<V> versioned = getItemOrThrow(requestWrapper.getKey(), null, versionedValues); long endTime = System.currentTimeMillis(); if(versioned == null) versioned = Versioned.value(requestWrapper.getRawValue(), new VectorClock()); else versioned.setObject(requestWrapper.getRawValue()); // This should not happen unless there's a bug in the // getWithCustomTimeout long timeLeft = requestWrapper.getRoutingTimeoutInMs() - (endTime - startTime); if(timeLeft <= 0) { throw new StoreTimeoutException("PUT request timed out"); } CompositeVersionedPutVoldemortRequest<K, V> putVersionedRequestObject = new CompositeVersionedPutVoldemortRequest<K, V>(requestWrapper.getKey(), versioned, timeLeft); putVersionedRequestObject.setRequestOriginTimeInMs(requestWrapper.getRequestOriginTimeInMs()); Version result = putVersionedWithCustomTimeout(putVersionedRequestObject); long endTimeInMs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { logger.debug("PUT response received for key: " + keyHexString + " , for store: " + this.storeName + " at time(in ms): " + endTimeInMs); } return result; }
java
public Version putWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) { validateTimeout(requestWrapper.getRoutingTimeoutInMs()); List<Versioned<V>> versionedValues; long startTime = System.currentTimeMillis(); String keyHexString = ""; if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) requestWrapper.getKey(); keyHexString = RestUtils.getKeyHexString(key); logger.debug("PUT requested for key: " + keyHexString + " , for store: " + this.storeName + " at time(in ms): " + startTime + " . Nested GET and PUT VERSION requests to follow ---"); } // We use the full timeout for doing the Get. In this, we're being // optimistic that the subsequent put might be faster such that all the // steps might finish within the allotted time requestWrapper.setResolveConflicts(true); versionedValues = getWithCustomTimeout(requestWrapper); Versioned<V> versioned = getItemOrThrow(requestWrapper.getKey(), null, versionedValues); long endTime = System.currentTimeMillis(); if(versioned == null) versioned = Versioned.value(requestWrapper.getRawValue(), new VectorClock()); else versioned.setObject(requestWrapper.getRawValue()); // This should not happen unless there's a bug in the // getWithCustomTimeout long timeLeft = requestWrapper.getRoutingTimeoutInMs() - (endTime - startTime); if(timeLeft <= 0) { throw new StoreTimeoutException("PUT request timed out"); } CompositeVersionedPutVoldemortRequest<K, V> putVersionedRequestObject = new CompositeVersionedPutVoldemortRequest<K, V>(requestWrapper.getKey(), versioned, timeLeft); putVersionedRequestObject.setRequestOriginTimeInMs(requestWrapper.getRequestOriginTimeInMs()); Version result = putVersionedWithCustomTimeout(putVersionedRequestObject); long endTimeInMs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { logger.debug("PUT response received for key: " + keyHexString + " , for store: " + this.storeName + " at time(in ms): " + endTimeInMs); } return result; }
[ "public", "Version", "putWithCustomTimeout", "(", "CompositeVoldemortRequest", "<", "K", ",", "V", ">", "requestWrapper", ")", "{", "validateTimeout", "(", "requestWrapper", ".", "getRoutingTimeoutInMs", "(", ")", ")", ";", "List", "<", "Versioned", "<", "V", ">...
Performs a put operation with the specified composite request object @param requestWrapper A composite request object containing the key and value @return Version of the value for the successful put
[ "Performs", "a", "put", "operation", "with", "the", "specified", "composite", "request", "object" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java#L144-L187
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java
DynamicTimeoutStoreClient.putVersionedWithCustomTimeout
public Version putVersionedWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) throws ObsoleteVersionException { validateTimeout(requestWrapper.getRoutingTimeoutInMs()); for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) { try { String keyHexString = ""; long startTimeInMs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) requestWrapper.getKey(); keyHexString = RestUtils.getKeyHexString(key); debugLogStart("PUT_VERSION", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, keyHexString); } store.put(requestWrapper); if(logger.isDebugEnabled()) { debugLogEnd("PUT_VERSION", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, System.currentTimeMillis(), keyHexString, 0); } return requestWrapper.getValue().getVersion(); } catch(InvalidMetadataException e) { logger.info("Received invalid metadata exception during put [ " + e.getMessage() + " ] on store '" + storeName + "'. Rebootstrapping"); bootStrap(); } } throw new VoldemortException(this.metadataRefreshAttempts + " metadata refresh attempts failed."); }
java
public Version putVersionedWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) throws ObsoleteVersionException { validateTimeout(requestWrapper.getRoutingTimeoutInMs()); for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) { try { String keyHexString = ""; long startTimeInMs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) requestWrapper.getKey(); keyHexString = RestUtils.getKeyHexString(key); debugLogStart("PUT_VERSION", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, keyHexString); } store.put(requestWrapper); if(logger.isDebugEnabled()) { debugLogEnd("PUT_VERSION", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, System.currentTimeMillis(), keyHexString, 0); } return requestWrapper.getValue().getVersion(); } catch(InvalidMetadataException e) { logger.info("Received invalid metadata exception during put [ " + e.getMessage() + " ] on store '" + storeName + "'. Rebootstrapping"); bootStrap(); } } throw new VoldemortException(this.metadataRefreshAttempts + " metadata refresh attempts failed."); }
[ "public", "Version", "putVersionedWithCustomTimeout", "(", "CompositeVoldemortRequest", "<", "K", ",", "V", ">", "requestWrapper", ")", "throws", "ObsoleteVersionException", "{", "validateTimeout", "(", "requestWrapper", ".", "getRoutingTimeoutInMs", "(", ")", ")", ";",...
Performs a Versioned put operation with the specified composite request object @param requestWrapper Composite request object containing the key and the versioned object @return Version of the value for the successful put @throws ObsoleteVersionException
[ "Performs", "a", "Versioned", "put", "operation", "with", "the", "specified", "composite", "request", "object" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java#L198-L231
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java
DynamicTimeoutStoreClient.getAllWithCustomTimeout
public Map<K, List<Versioned<V>>> getAllWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) { validateTimeout(requestWrapper.getRoutingTimeoutInMs()); Map<K, List<Versioned<V>>> items = null; for(int attempts = 0;; attempts++) { if(attempts >= this.metadataRefreshAttempts) throw new VoldemortException(this.metadataRefreshAttempts + " metadata refresh attempts failed."); try { String KeysHexString = ""; long startTimeInMs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { Iterable<ByteArray> keys = (Iterable<ByteArray>) requestWrapper.getIterableKeys(); KeysHexString = getKeysHexString(keys); debugLogStart("GET_ALL", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, KeysHexString); } items = store.getAll(requestWrapper); if(logger.isDebugEnabled()) { int vcEntrySize = 0; for(List<Versioned<V>> item: items.values()) { for(Versioned<V> vc: item) { vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size(); } } debugLogEnd("GET_ALL", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, System.currentTimeMillis(), KeysHexString, vcEntrySize); } return items; } catch(InvalidMetadataException e) { logger.info("Received invalid metadata exception during getAll [ " + e.getMessage() + " ] on store '" + storeName + "'. Rebootstrapping"); bootStrap(); } } }
java
public Map<K, List<Versioned<V>>> getAllWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) { validateTimeout(requestWrapper.getRoutingTimeoutInMs()); Map<K, List<Versioned<V>>> items = null; for(int attempts = 0;; attempts++) { if(attempts >= this.metadataRefreshAttempts) throw new VoldemortException(this.metadataRefreshAttempts + " metadata refresh attempts failed."); try { String KeysHexString = ""; long startTimeInMs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { Iterable<ByteArray> keys = (Iterable<ByteArray>) requestWrapper.getIterableKeys(); KeysHexString = getKeysHexString(keys); debugLogStart("GET_ALL", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, KeysHexString); } items = store.getAll(requestWrapper); if(logger.isDebugEnabled()) { int vcEntrySize = 0; for(List<Versioned<V>> item: items.values()) { for(Versioned<V> vc: item) { vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size(); } } debugLogEnd("GET_ALL", requestWrapper.getRequestOriginTimeInMs(), startTimeInMs, System.currentTimeMillis(), KeysHexString, vcEntrySize); } return items; } catch(InvalidMetadataException e) { logger.info("Received invalid metadata exception during getAll [ " + e.getMessage() + " ] on store '" + storeName + "'. Rebootstrapping"); bootStrap(); } } }
[ "public", "Map", "<", "K", ",", "List", "<", "Versioned", "<", "V", ">", ">", ">", "getAllWithCustomTimeout", "(", "CompositeVoldemortRequest", "<", "K", ",", "V", ">", "requestWrapper", ")", "{", "validateTimeout", "(", "requestWrapper", ".", "getRoutingTimeo...
Performs a get all operation with the specified composite request object @param requestWrapper Composite request object containing a reference to the Iterable keys @return Map of the keys to the corresponding versioned values
[ "Performs", "a", "get", "all", "operation", "with", "the", "specified", "composite", "request", "object" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java#L241-L283
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java
DynamicTimeoutStoreClient.deleteWithCustomTimeout
public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) { List<Versioned<V>> versionedValues; validateTimeout(deleteRequestObject.getRoutingTimeoutInMs()); boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true; String keyHexString = ""; if(!hasVersion) { long startTimeInMs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) deleteRequestObject.getKey(); keyHexString = RestUtils.getKeyHexString(key); logger.debug("DELETE without version requested for key: " + keyHexString + " , for store: " + this.storeName + " at time(in ms): " + startTimeInMs + " . Nested GET and DELETE requests to follow ---"); } // We use the full timeout for doing the Get. In this, we're being // optimistic that the subsequent delete might be faster all the // steps might finish within the allotted time deleteRequestObject.setResolveConflicts(true); versionedValues = getWithCustomTimeout(deleteRequestObject); Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(), null, versionedValues); if(versioned == null) { return false; } long timeLeft = deleteRequestObject.getRoutingTimeoutInMs() - (System.currentTimeMillis() - startTimeInMs); // This should not happen unless there's a bug in the // getWithCustomTimeout if(timeLeft < 0) { throw new StoreTimeoutException("DELETE request timed out"); } // Update the version and the new timeout deleteRequestObject.setVersion(versioned.getVersion()); deleteRequestObject.setRoutingTimeoutInMs(timeLeft); } long deleteVersionStartTimeInNs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) deleteRequestObject.getKey(); keyHexString = RestUtils.getKeyHexString(key); debugLogStart("DELETE", deleteRequestObject.getRequestOriginTimeInMs(), deleteVersionStartTimeInNs, keyHexString); } boolean result = store.delete(deleteRequestObject); if(logger.isDebugEnabled()) { debugLogEnd("DELETE", deleteRequestObject.getRequestOriginTimeInMs(), deleteVersionStartTimeInNs, System.currentTimeMillis(), keyHexString, 0); } if(!hasVersion && logger.isDebugEnabled()) { logger.debug("DELETE without version response received for key: " + keyHexString + ", for store: " + this.storeName + " at time(in ms): " + System.currentTimeMillis()); } return result; }
java
public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) { List<Versioned<V>> versionedValues; validateTimeout(deleteRequestObject.getRoutingTimeoutInMs()); boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true; String keyHexString = ""; if(!hasVersion) { long startTimeInMs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) deleteRequestObject.getKey(); keyHexString = RestUtils.getKeyHexString(key); logger.debug("DELETE without version requested for key: " + keyHexString + " , for store: " + this.storeName + " at time(in ms): " + startTimeInMs + " . Nested GET and DELETE requests to follow ---"); } // We use the full timeout for doing the Get. In this, we're being // optimistic that the subsequent delete might be faster all the // steps might finish within the allotted time deleteRequestObject.setResolveConflicts(true); versionedValues = getWithCustomTimeout(deleteRequestObject); Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(), null, versionedValues); if(versioned == null) { return false; } long timeLeft = deleteRequestObject.getRoutingTimeoutInMs() - (System.currentTimeMillis() - startTimeInMs); // This should not happen unless there's a bug in the // getWithCustomTimeout if(timeLeft < 0) { throw new StoreTimeoutException("DELETE request timed out"); } // Update the version and the new timeout deleteRequestObject.setVersion(versioned.getVersion()); deleteRequestObject.setRoutingTimeoutInMs(timeLeft); } long deleteVersionStartTimeInNs = System.currentTimeMillis(); if(logger.isDebugEnabled()) { ByteArray key = (ByteArray) deleteRequestObject.getKey(); keyHexString = RestUtils.getKeyHexString(key); debugLogStart("DELETE", deleteRequestObject.getRequestOriginTimeInMs(), deleteVersionStartTimeInNs, keyHexString); } boolean result = store.delete(deleteRequestObject); if(logger.isDebugEnabled()) { debugLogEnd("DELETE", deleteRequestObject.getRequestOriginTimeInMs(), deleteVersionStartTimeInNs, System.currentTimeMillis(), keyHexString, 0); } if(!hasVersion && logger.isDebugEnabled()) { logger.debug("DELETE without version response received for key: " + keyHexString + ", for store: " + this.storeName + " at time(in ms): " + System.currentTimeMillis()); } return result; }
[ "public", "boolean", "deleteWithCustomTimeout", "(", "CompositeVoldemortRequest", "<", "K", ",", "V", ">", "deleteRequestObject", ")", "{", "List", "<", "Versioned", "<", "V", ">>", "versionedValues", ";", "validateTimeout", "(", "deleteRequestObject", ".", "getRout...
Performs a delete operation with the specified composite request object @param deleteRequestObject Composite request object containing the key to delete @return true if delete was successful. False otherwise
[ "Performs", "a", "delete", "operation", "with", "the", "specified", "composite", "request", "object" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java#L292-L358
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java
DynamicTimeoutStoreClient.debugLogStart
private void debugLogStart(String operationType, Long originTimeInMS, Long requestReceivedTimeInMs, String keyString) { long durationInMs = requestReceivedTimeInMs - originTimeInMS; logger.debug("Received a new request. Operation Type: " + operationType + " , key(s): " + keyString + " , Store: " + this.storeName + " , Origin time (in ms): " + originTimeInMS + " . Request received at time(in ms): " + requestReceivedTimeInMs + " , Duration from RESTClient to CoordinatorFatClient(in ms): " + durationInMs); }
java
private void debugLogStart(String operationType, Long originTimeInMS, Long requestReceivedTimeInMs, String keyString) { long durationInMs = requestReceivedTimeInMs - originTimeInMS; logger.debug("Received a new request. Operation Type: " + operationType + " , key(s): " + keyString + " , Store: " + this.storeName + " , Origin time (in ms): " + originTimeInMS + " . Request received at time(in ms): " + requestReceivedTimeInMs + " , Duration from RESTClient to CoordinatorFatClient(in ms): " + durationInMs); }
[ "private", "void", "debugLogStart", "(", "String", "operationType", ",", "Long", "originTimeInMS", ",", "Long", "requestReceivedTimeInMs", ",", "String", "keyString", ")", "{", "long", "durationInMs", "=", "requestReceivedTimeInMs", "-", "originTimeInMS", ";", "logger...
Traces the duration between origin time in the http Request and time just before being processed by the fat client @param operationType @param originTimeInMS - origin time in the Http Request @param requestReceivedTimeInMs - System Time in ms @param keyString
[ "Traces", "the", "duration", "between", "origin", "time", "in", "the", "http", "Request", "and", "time", "just", "before", "being", "processed", "by", "the", "fat", "client" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java#L385-L397
train
voldemort/voldemort
src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java
DynamicTimeoutStoreClient.debugLogEnd
private void debugLogEnd(String operationType, Long OriginTimeInMs, Long RequestStartTimeInMs, Long ResponseReceivedTimeInMs, String keyString, int numVectorClockEntries) { long durationInMs = ResponseReceivedTimeInMs - RequestStartTimeInMs; logger.debug("Received a response from voldemort server for Operation Type: " + operationType + " , For key(s): " + keyString + " , Store: " + this.storeName + " , Origin time of request (in ms): " + OriginTimeInMs + " , Response received at time (in ms): " + ResponseReceivedTimeInMs + " . Request sent at(in ms): " + RequestStartTimeInMs + " , Num vector clock entries: " + numVectorClockEntries + " , Duration from CoordinatorFatClient back to CoordinatorFatClient(in ms): " + durationInMs); }
java
private void debugLogEnd(String operationType, Long OriginTimeInMs, Long RequestStartTimeInMs, Long ResponseReceivedTimeInMs, String keyString, int numVectorClockEntries) { long durationInMs = ResponseReceivedTimeInMs - RequestStartTimeInMs; logger.debug("Received a response from voldemort server for Operation Type: " + operationType + " , For key(s): " + keyString + " , Store: " + this.storeName + " , Origin time of request (in ms): " + OriginTimeInMs + " , Response received at time (in ms): " + ResponseReceivedTimeInMs + " . Request sent at(in ms): " + RequestStartTimeInMs + " , Num vector clock entries: " + numVectorClockEntries + " , Duration from CoordinatorFatClient back to CoordinatorFatClient(in ms): " + durationInMs); }
[ "private", "void", "debugLogEnd", "(", "String", "operationType", ",", "Long", "OriginTimeInMs", ",", "Long", "RequestStartTimeInMs", ",", "Long", "ResponseReceivedTimeInMs", ",", "String", "keyString", ",", "int", "numVectorClockEntries", ")", "{", "long", "durationI...
Traces the time taken just by the fat client inside Coordinator to process this request @param operationType @param OriginTimeInMs - Original request time in Http Request @param RequestStartTimeInMs - Time recorded just before fat client started processing @param ResponseReceivedTimeInMs - Time when Response was received from fat client @param keyString - Hex denotation of the key(s) @param numVectorClockEntries - represents the sum of entries size of all vector clocks received in response. Size of a single vector clock represents the number of entries(nodes) in the vector
[ "Traces", "the", "time", "taken", "just", "by", "the", "fat", "client", "inside", "Coordinator", "to", "process", "this", "request" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/DynamicTimeoutStoreClient.java#L415-L438
train
voldemort/voldemort
src/java/voldemort/utils/UpdateClusterUtils.java
UpdateClusterUtils.updateNode
public static Node updateNode(Node node, List<Integer> partitionsList) { return new Node(node.getId(), node.getHost(), node.getHttpPort(), node.getSocketPort(), node.getAdminPort(), node.getZoneId(), partitionsList); }
java
public static Node updateNode(Node node, List<Integer> partitionsList) { return new Node(node.getId(), node.getHost(), node.getHttpPort(), node.getSocketPort(), node.getAdminPort(), node.getZoneId(), partitionsList); }
[ "public", "static", "Node", "updateNode", "(", "Node", "node", ",", "List", "<", "Integer", ">", "partitionsList", ")", "{", "return", "new", "Node", "(", "node", ".", "getId", "(", ")", ",", "node", ".", "getHost", "(", ")", ",", "node", ".", "getHt...
Creates a replica of the node with the new partitions list @param node The node whose replica we are creating @param partitionsList The new partitions list @return Replica of node with new partitions list
[ "Creates", "a", "replica", "of", "the", "node", "with", "the", "new", "partitions", "list" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/UpdateClusterUtils.java#L50-L58
train
voldemort/voldemort
src/java/voldemort/utils/UpdateClusterUtils.java
UpdateClusterUtils.addPartitionToNode
public static Node addPartitionToNode(final Node node, Integer donatedPartition) { return UpdateClusterUtils.addPartitionsToNode(node, Sets.newHashSet(donatedPartition)); }
java
public static Node addPartitionToNode(final Node node, Integer donatedPartition) { return UpdateClusterUtils.addPartitionsToNode(node, Sets.newHashSet(donatedPartition)); }
[ "public", "static", "Node", "addPartitionToNode", "(", "final", "Node", "node", ",", "Integer", "donatedPartition", ")", "{", "return", "UpdateClusterUtils", ".", "addPartitionsToNode", "(", "node", ",", "Sets", ".", "newHashSet", "(", "donatedPartition", ")", ")"...
Add a partition to the node provided @param node The node to which we'll add the partition @param donatedPartition The partition to add @return The new node with the new partition
[ "Add", "a", "partition", "to", "the", "node", "provided" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/UpdateClusterUtils.java#L67-L69
train
voldemort/voldemort
src/java/voldemort/utils/UpdateClusterUtils.java
UpdateClusterUtils.removePartitionFromNode
public static Node removePartitionFromNode(final Node node, Integer donatedPartition) { return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition)); }
java
public static Node removePartitionFromNode(final Node node, Integer donatedPartition) { return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition)); }
[ "public", "static", "Node", "removePartitionFromNode", "(", "final", "Node", "node", ",", "Integer", "donatedPartition", ")", "{", "return", "UpdateClusterUtils", ".", "removePartitionsFromNode", "(", "node", ",", "Sets", ".", "newHashSet", "(", "donatedPartition", ...
Remove a partition from the node provided @param node The node from which we're removing the partition @param donatedPartition The partitions to remove @return The new node without the partition
[ "Remove", "a", "partition", "from", "the", "node", "provided" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/UpdateClusterUtils.java#L78-L80
train
voldemort/voldemort
src/java/voldemort/utils/UpdateClusterUtils.java
UpdateClusterUtils.addPartitionsToNode
public static Node addPartitionsToNode(final Node node, final Set<Integer> donatedPartitions) { List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds()); deepCopy.addAll(donatedPartitions); Collections.sort(deepCopy); return updateNode(node, deepCopy); }
java
public static Node addPartitionsToNode(final Node node, final Set<Integer> donatedPartitions) { List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds()); deepCopy.addAll(donatedPartitions); Collections.sort(deepCopy); return updateNode(node, deepCopy); }
[ "public", "static", "Node", "addPartitionsToNode", "(", "final", "Node", "node", ",", "final", "Set", "<", "Integer", ">", "donatedPartitions", ")", "{", "List", "<", "Integer", ">", "deepCopy", "=", "new", "ArrayList", "<", "Integer", ">", "(", "node", "....
Add the set of partitions to the node provided @param node The node to which we'll add the partitions @param donatedPartitions The list of partitions to add @return The new node with the new partitions
[ "Add", "the", "set", "of", "partitions", "to", "the", "node", "provided" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/UpdateClusterUtils.java#L89-L94
train
voldemort/voldemort
src/java/voldemort/utils/UpdateClusterUtils.java
UpdateClusterUtils.removePartitionsFromNode
public static Node removePartitionsFromNode(final Node node, final Set<Integer> donatedPartitions) { List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds()); deepCopy.removeAll(donatedPartitions); return updateNode(node, deepCopy); }
java
public static Node removePartitionsFromNode(final Node node, final Set<Integer> donatedPartitions) { List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds()); deepCopy.removeAll(donatedPartitions); return updateNode(node, deepCopy); }
[ "public", "static", "Node", "removePartitionsFromNode", "(", "final", "Node", "node", ",", "final", "Set", "<", "Integer", ">", "donatedPartitions", ")", "{", "List", "<", "Integer", ">", "deepCopy", "=", "new", "ArrayList", "<", "Integer", ">", "(", "node",...
Remove the set of partitions from the node provided @param node The node from which we're removing the partitions @param donatedPartitions The list of partitions to remove @return The new node without the partitions
[ "Remove", "the", "set", "of", "partitions", "from", "the", "node", "provided" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/UpdateClusterUtils.java#L103-L108
train
voldemort/voldemort
src/java/voldemort/utils/UpdateClusterUtils.java
UpdateClusterUtils.createUpdatedCluster
public static Cluster createUpdatedCluster(Cluster currentCluster, int stealerNodeId, List<Integer> donatedPartitions) { Cluster updatedCluster = Cluster.cloneCluster(currentCluster); // Go over every donated partition one by one for(int donatedPartition: donatedPartitions) { // Gets the donor Node that owns this donated partition Node donorNode = updatedCluster.getNodeForPartitionId(donatedPartition); Node stealerNode = updatedCluster.getNodeById(stealerNodeId); if(donorNode == stealerNode) { // Moving to the same location = No-op continue; } // Update the list of partitions for this node donorNode = removePartitionFromNode(donorNode, donatedPartition); stealerNode = addPartitionToNode(stealerNode, donatedPartition); // Sort the nodes updatedCluster = updateCluster(updatedCluster, Lists.newArrayList(donorNode, stealerNode)); } return updatedCluster; }
java
public static Cluster createUpdatedCluster(Cluster currentCluster, int stealerNodeId, List<Integer> donatedPartitions) { Cluster updatedCluster = Cluster.cloneCluster(currentCluster); // Go over every donated partition one by one for(int donatedPartition: donatedPartitions) { // Gets the donor Node that owns this donated partition Node donorNode = updatedCluster.getNodeForPartitionId(donatedPartition); Node stealerNode = updatedCluster.getNodeById(stealerNodeId); if(donorNode == stealerNode) { // Moving to the same location = No-op continue; } // Update the list of partitions for this node donorNode = removePartitionFromNode(donorNode, donatedPartition); stealerNode = addPartitionToNode(stealerNode, donatedPartition); // Sort the nodes updatedCluster = updateCluster(updatedCluster, Lists.newArrayList(donorNode, stealerNode)); } return updatedCluster; }
[ "public", "static", "Cluster", "createUpdatedCluster", "(", "Cluster", "currentCluster", ",", "int", "stealerNodeId", ",", "List", "<", "Integer", ">", "donatedPartitions", ")", "{", "Cluster", "updatedCluster", "=", "Cluster", ".", "cloneCluster", "(", "currentClus...
Updates the existing cluster such that we remove partitions mentioned from the stealer node and add them to the donor node @param currentCluster Existing cluster metadata. Both stealer and donor node should already exist in this metadata @param stealerNodeId Id of node for which we are stealing the partitions @param donatedPartitions List of partitions we are moving @return Updated cluster metadata
[ "Updates", "the", "existing", "cluster", "such", "that", "we", "remove", "partitions", "mentioned", "from", "the", "stealer", "node", "and", "add", "them", "to", "the", "donor", "node" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/UpdateClusterUtils.java#L143-L170
train
voldemort/voldemort
src/java/voldemort/utils/DirectoryIterator.java
DirectoryIterator.main
public static void main(String[] args) { DirectoryIterator iter = new DirectoryIterator(args); while(iter.hasNext()) System.out.println(iter.next().getAbsolutePath()); }
java
public static void main(String[] args) { DirectoryIterator iter = new DirectoryIterator(args); while(iter.hasNext()) System.out.println(iter.next().getAbsolutePath()); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "DirectoryIterator", "iter", "=", "new", "DirectoryIterator", "(", "args", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "System", ".", "out", ".", "println...
Command line method to walk the directories provided on the command line and print out their contents @param args Directory names
[ "Command", "line", "method", "to", "walk", "the", "directories", "provided", "on", "the", "command", "line", "and", "print", "out", "their", "contents" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/DirectoryIterator.java#L55-L59
train
voldemort/voldemort
src/java/voldemort/routing/StoreRoutingPlan.java
StoreRoutingPlan.verifyClusterStoreDefinition
private void verifyClusterStoreDefinition() { if(SystemStoreConstants.isSystemStore(storeDefinition.getName())) { // TODO: Once "todo" in StorageService.initSystemStores is complete, // this early return can be removed and verification can be enabled // for system stores. return; } Set<Integer> clusterZoneIds = cluster.getZoneIds(); if(clusterZoneIds.size() > 1) { // Zoned Map<Integer, Integer> zoneRepFactor = storeDefinition.getZoneReplicationFactor(); Set<Integer> storeDefZoneIds = zoneRepFactor.keySet(); if(!clusterZoneIds.equals(storeDefZoneIds)) { throw new VoldemortException("Zone IDs in cluster (" + clusterZoneIds + ") are incongruent with zone IDs in store defs (" + storeDefZoneIds + ")"); } for(int zoneId: clusterZoneIds) { if(zoneRepFactor.get(zoneId) > cluster.getNumberOfNodesInZone(zoneId)) { throw new VoldemortException("Not enough nodes (" + cluster.getNumberOfNodesInZone(zoneId) + ") in zone with id " + zoneId + " for replication factor of " + zoneRepFactor.get(zoneId) + "."); } } } else { // Non-zoned if(storeDefinition.getReplicationFactor() > cluster.getNumberOfNodes()) { System.err.println(storeDefinition); System.err.println(cluster); throw new VoldemortException("Not enough nodes (" + cluster.getNumberOfNodes() + ") for replication factor of " + storeDefinition.getReplicationFactor() + "."); } } }
java
private void verifyClusterStoreDefinition() { if(SystemStoreConstants.isSystemStore(storeDefinition.getName())) { // TODO: Once "todo" in StorageService.initSystemStores is complete, // this early return can be removed and verification can be enabled // for system stores. return; } Set<Integer> clusterZoneIds = cluster.getZoneIds(); if(clusterZoneIds.size() > 1) { // Zoned Map<Integer, Integer> zoneRepFactor = storeDefinition.getZoneReplicationFactor(); Set<Integer> storeDefZoneIds = zoneRepFactor.keySet(); if(!clusterZoneIds.equals(storeDefZoneIds)) { throw new VoldemortException("Zone IDs in cluster (" + clusterZoneIds + ") are incongruent with zone IDs in store defs (" + storeDefZoneIds + ")"); } for(int zoneId: clusterZoneIds) { if(zoneRepFactor.get(zoneId) > cluster.getNumberOfNodesInZone(zoneId)) { throw new VoldemortException("Not enough nodes (" + cluster.getNumberOfNodesInZone(zoneId) + ") in zone with id " + zoneId + " for replication factor of " + zoneRepFactor.get(zoneId) + "."); } } } else { // Non-zoned if(storeDefinition.getReplicationFactor() > cluster.getNumberOfNodes()) { System.err.println(storeDefinition); System.err.println(cluster); throw new VoldemortException("Not enough nodes (" + cluster.getNumberOfNodes() + ") for replication factor of " + storeDefinition.getReplicationFactor() + "."); } } }
[ "private", "void", "verifyClusterStoreDefinition", "(", ")", "{", "if", "(", "SystemStoreConstants", ".", "isSystemStore", "(", "storeDefinition", ".", "getName", "(", ")", ")", ")", "{", "// TODO: Once \"todo\" in StorageService.initSystemStores is complete,", "// this ear...
Verify that cluster is congruent to store def wrt zones.
[ "Verify", "that", "cluster", "is", "congruent", "to", "store", "def", "wrt", "zones", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/StoreRoutingPlan.java#L126-L165
train
voldemort/voldemort
src/java/voldemort/routing/StoreRoutingPlan.java
StoreRoutingPlan.getNodesPartitionIdForKey
public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) { // this is all the partitions the key replicates to. List<Integer> partitionIds = getReplicatingPartitionList(key); for(Integer partitionId: partitionIds) { // check which of the replicating partitions belongs to the node in // question if(getNodeIdForPartitionId(partitionId) == nodeId) { return partitionId; } } return null; }
java
public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) { // this is all the partitions the key replicates to. List<Integer> partitionIds = getReplicatingPartitionList(key); for(Integer partitionId: partitionIds) { // check which of the replicating partitions belongs to the node in // question if(getNodeIdForPartitionId(partitionId) == nodeId) { return partitionId; } } return null; }
[ "public", "Integer", "getNodesPartitionIdForKey", "(", "int", "nodeId", ",", "final", "byte", "[", "]", "key", ")", "{", "// this is all the partitions the key replicates to.", "List", "<", "Integer", ">", "partitionIds", "=", "getReplicatingPartitionList", "(", "key", ...
Determines the partition ID that replicates the key on the given node. @param nodeId of the node @param key to look up. @return partitionId if found, otherwise null.
[ "Determines", "the", "partition", "ID", "that", "replicates", "the", "key", "on", "the", "given", "node", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/StoreRoutingPlan.java#L214-L225
train
voldemort/voldemort
src/java/voldemort/routing/StoreRoutingPlan.java
StoreRoutingPlan.getNodeIdListForPartitionIdList
private List<Integer> getNodeIdListForPartitionIdList(List<Integer> partitionIds) throws VoldemortException { List<Integer> nodeIds = new ArrayList<Integer>(partitionIds.size()); for(Integer partitionId: partitionIds) { int nodeId = getNodeIdForPartitionId(partitionId); if(nodeIds.contains(nodeId)) { throw new VoldemortException("Node ID " + nodeId + " already in list of Node IDs."); } else { nodeIds.add(nodeId); } } return nodeIds; }
java
private List<Integer> getNodeIdListForPartitionIdList(List<Integer> partitionIds) throws VoldemortException { List<Integer> nodeIds = new ArrayList<Integer>(partitionIds.size()); for(Integer partitionId: partitionIds) { int nodeId = getNodeIdForPartitionId(partitionId); if(nodeIds.contains(nodeId)) { throw new VoldemortException("Node ID " + nodeId + " already in list of Node IDs."); } else { nodeIds.add(nodeId); } } return nodeIds; }
[ "private", "List", "<", "Integer", ">", "getNodeIdListForPartitionIdList", "(", "List", "<", "Integer", ">", "partitionIds", ")", "throws", "VoldemortException", "{", "List", "<", "Integer", ">", "nodeIds", "=", "new", "ArrayList", "<", "Integer", ">", "(", "p...
Converts from partitionId to nodeId. The list of partition IDs, partitionIds, is expected to be a "replicating partition list", i.e., the mapping from partition ID to node ID should be one to one. @param partitionIds List of partition IDs for which to find the Node ID for the Node that owns the partition. @return List of node ids, one for each partition ID in partitionIds @throws VoldemortException If multiple partition IDs in partitionIds map to the same Node ID.
[ "Converts", "from", "partitionId", "to", "nodeId", ".", "The", "list", "of", "partition", "IDs", "partitionIds", "is", "expected", "to", "be", "a", "replicating", "partition", "list", "i", ".", "e", ".", "the", "mapping", "from", "partition", "ID", "to", "...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/StoreRoutingPlan.java#L238-L250
train
voldemort/voldemort
src/java/voldemort/routing/StoreRoutingPlan.java
StoreRoutingPlan.checkKeyBelongsToNode
public boolean checkKeyBelongsToNode(byte[] key, int nodeId) { List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds(); List<Integer> replicatingPartitions = getReplicatingPartitionList(key); // remove all partitions from the list, except those that belong to the // node replicatingPartitions.retainAll(nodePartitions); return replicatingPartitions.size() > 0; }
java
public boolean checkKeyBelongsToNode(byte[] key, int nodeId) { List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds(); List<Integer> replicatingPartitions = getReplicatingPartitionList(key); // remove all partitions from the list, except those that belong to the // node replicatingPartitions.retainAll(nodePartitions); return replicatingPartitions.size() > 0; }
[ "public", "boolean", "checkKeyBelongsToNode", "(", "byte", "[", "]", "key", ",", "int", "nodeId", ")", "{", "List", "<", "Integer", ">", "nodePartitions", "=", "cluster", ".", "getNodeById", "(", "nodeId", ")", ".", "getPartitionIds", "(", ")", ";", "List"...
Determines if the key replicates to the given node @param key @param nodeId @return true if the key belongs to the node as some replica
[ "Determines", "if", "the", "key", "replicates", "to", "the", "given", "node" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/StoreRoutingPlan.java#L360-L367
train
voldemort/voldemort
src/java/voldemort/routing/StoreRoutingPlan.java
StoreRoutingPlan.checkKeyBelongsToPartition
public static List<Integer> checkKeyBelongsToPartition(byte[] key, Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples, Cluster cluster, StoreDefinition storeDef) { List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef, cluster) .getPartitionList(key); List<Integer> nodesToPush = Lists.newArrayList(); for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) { List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst()) .getPartitionIds(); if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions, nodePartitions, stealNodeToMap.getSecond())) { nodesToPush.add(stealNodeToMap.getFirst()); } } return nodesToPush; }
java
public static List<Integer> checkKeyBelongsToPartition(byte[] key, Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples, Cluster cluster, StoreDefinition storeDef) { List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef, cluster) .getPartitionList(key); List<Integer> nodesToPush = Lists.newArrayList(); for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) { List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst()) .getPartitionIds(); if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions, nodePartitions, stealNodeToMap.getSecond())) { nodesToPush.add(stealNodeToMap.getFirst()); } } return nodesToPush; }
[ "public", "static", "List", "<", "Integer", ">", "checkKeyBelongsToPartition", "(", "byte", "[", "]", "key", ",", "Set", "<", "Pair", "<", "Integer", ",", "HashMap", "<", "Integer", ",", "List", "<", "Integer", ">", ">", ">", ">", "stealerNodeToMappingTupl...
Given a key and a list of steal infos give back a list of stealer node ids which will steal this. @param key Byte array of key @param stealerNodeToMappingTuples Pairs of stealer node id to their corresponding [ partition - replica ] tuples @param cluster Cluster metadata @param storeDef Store definitions @return List of node ids
[ "Given", "a", "key", "and", "a", "list", "of", "steal", "infos", "give", "back", "a", "list", "of", "stealer", "node", "ids", "which", "will", "steal", "this", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/StoreRoutingPlan.java#L448-L466
train
voldemort/voldemort
src/java/voldemort/utils/EventThrottler.java
EventThrottler.maybeThrottle
public synchronized void maybeThrottle(int eventsSeen) { if (maxRatePerSecond > 0) { long now = time.milliseconds(); try { rateSensor.record(eventsSeen, now); } catch (QuotaViolationException e) { // If we're over quota, we calculate how long to sleep to compensate. double currentRate = e.getValue(); if (currentRate > this.maxRatePerSecond) { double excessRate = currentRate - this.maxRatePerSecond; long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND); if(logger.isDebugEnabled()) { logger.debug("Throttler quota exceeded:\n" + "eventsSeen \t= " + eventsSeen + " in this call of maybeThrotte(),\n" + "currentRate \t= " + currentRate + " events/sec,\n" + "maxRatePerSecond \t= " + this.maxRatePerSecond + " events/sec,\n" + "excessRate \t= " + excessRate + " events/sec,\n" + "sleeping for \t" + sleepTimeMs + " ms to compensate.\n" + "rateConfig.timeWindowMs() = " + rateConfig.timeWindowMs()); } if (sleepTimeMs > rateConfig.timeWindowMs()) { logger.warn("Throttler sleep time (" + sleepTimeMs + " ms) exceeds " + "window size (" + rateConfig.timeWindowMs() + " ms). This will likely " + "result in not being able to honor the rate limit accurately."); // When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size // too high could cause this problem. } time.sleep(sleepTimeMs); } else if (logger.isDebugEnabled()) { logger.debug("Weird. Got QuotaValidationException but measured rate not over rateLimit: " + "currentRate = " + currentRate + " , rateLimit = " + this.maxRatePerSecond); } } } }
java
public synchronized void maybeThrottle(int eventsSeen) { if (maxRatePerSecond > 0) { long now = time.milliseconds(); try { rateSensor.record(eventsSeen, now); } catch (QuotaViolationException e) { // If we're over quota, we calculate how long to sleep to compensate. double currentRate = e.getValue(); if (currentRate > this.maxRatePerSecond) { double excessRate = currentRate - this.maxRatePerSecond; long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND); if(logger.isDebugEnabled()) { logger.debug("Throttler quota exceeded:\n" + "eventsSeen \t= " + eventsSeen + " in this call of maybeThrotte(),\n" + "currentRate \t= " + currentRate + " events/sec,\n" + "maxRatePerSecond \t= " + this.maxRatePerSecond + " events/sec,\n" + "excessRate \t= " + excessRate + " events/sec,\n" + "sleeping for \t" + sleepTimeMs + " ms to compensate.\n" + "rateConfig.timeWindowMs() = " + rateConfig.timeWindowMs()); } if (sleepTimeMs > rateConfig.timeWindowMs()) { logger.warn("Throttler sleep time (" + sleepTimeMs + " ms) exceeds " + "window size (" + rateConfig.timeWindowMs() + " ms). This will likely " + "result in not being able to honor the rate limit accurately."); // When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size // too high could cause this problem. } time.sleep(sleepTimeMs); } else if (logger.isDebugEnabled()) { logger.debug("Weird. Got QuotaValidationException but measured rate not over rateLimit: " + "currentRate = " + currentRate + " , rateLimit = " + this.maxRatePerSecond); } } } }
[ "public", "synchronized", "void", "maybeThrottle", "(", "int", "eventsSeen", ")", "{", "if", "(", "maxRatePerSecond", ">", "0", ")", "{", "long", "now", "=", "time", ".", "milliseconds", "(", ")", ";", "try", "{", "rateSensor", ".", "record", "(", "event...
Sleeps if necessary to slow down the caller. @param eventsSeen Number of events seen since last invocation. Basis for determining whether its necessary to sleep.
[ "Sleeps", "if", "necessary", "to", "slow", "down", "the", "caller", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/EventThrottler.java#L136-L170
train
voldemort/voldemort
src/java/voldemort/store/routed/ReadRepairer.java
ReadRepairer.getRepairs
public List<NodeValue<K, V>> getRepairs(List<NodeValue<K, V>> nodeValues) { int size = nodeValues.size(); if(size <= 1) return Collections.emptyList(); Map<K, List<NodeValue<K, V>>> keyToNodeValues = Maps.newHashMap(); for(NodeValue<K, V> nodeValue: nodeValues) { List<NodeValue<K, V>> keyNodeValues = keyToNodeValues.get(nodeValue.getKey()); if(keyNodeValues == null) { keyNodeValues = Lists.newArrayListWithCapacity(5); keyToNodeValues.put(nodeValue.getKey(), keyNodeValues); } keyNodeValues.add(nodeValue); } List<NodeValue<K, V>> result = Lists.newArrayList(); for(List<NodeValue<K, V>> keyNodeValues: keyToNodeValues.values()) result.addAll(singleKeyGetRepairs(keyNodeValues)); return result; }
java
public List<NodeValue<K, V>> getRepairs(List<NodeValue<K, V>> nodeValues) { int size = nodeValues.size(); if(size <= 1) return Collections.emptyList(); Map<K, List<NodeValue<K, V>>> keyToNodeValues = Maps.newHashMap(); for(NodeValue<K, V> nodeValue: nodeValues) { List<NodeValue<K, V>> keyNodeValues = keyToNodeValues.get(nodeValue.getKey()); if(keyNodeValues == null) { keyNodeValues = Lists.newArrayListWithCapacity(5); keyToNodeValues.put(nodeValue.getKey(), keyNodeValues); } keyNodeValues.add(nodeValue); } List<NodeValue<K, V>> result = Lists.newArrayList(); for(List<NodeValue<K, V>> keyNodeValues: keyToNodeValues.values()) result.addAll(singleKeyGetRepairs(keyNodeValues)); return result; }
[ "public", "List", "<", "NodeValue", "<", "K", ",", "V", ">", ">", "getRepairs", "(", "List", "<", "NodeValue", "<", "K", ",", "V", ">", ">", "nodeValues", ")", "{", "int", "size", "=", "nodeValues", ".", "size", "(", ")", ";", "if", "(", "size", ...
Compute the repair set from the given values and nodes @param nodeValues The value found on each node @return A set of repairs to perform
[ "Compute", "the", "repair", "set", "from", "the", "given", "values", "and", "nodes" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/ReadRepairer.java#L59-L78
train
voldemort/voldemort
src/java/voldemort/versioning/VectorClockUtils.java
VectorClockUtils.resolveVersions
public static List<Versioned<byte[]>> resolveVersions(List<Versioned<byte[]>> values) { List<Versioned<byte[]>> resolvedVersions = new ArrayList<Versioned<byte[]>>(values.size()); // Go over all the values and determine whether the version is // acceptable for(Versioned<byte[]> value: values) { Iterator<Versioned<byte[]>> iter = resolvedVersions.iterator(); boolean obsolete = false; // Compare the current version with a set of accepted versions while(iter.hasNext()) { Versioned<byte[]> curr = iter.next(); Occurred occurred = value.getVersion().compare(curr.getVersion()); if(occurred == Occurred.BEFORE) { obsolete = true; break; } else if(occurred == Occurred.AFTER) { iter.remove(); } } if(!obsolete) { // else update the set of accepted versions resolvedVersions.add(value); } } return resolvedVersions; }
java
public static List<Versioned<byte[]>> resolveVersions(List<Versioned<byte[]>> values) { List<Versioned<byte[]>> resolvedVersions = new ArrayList<Versioned<byte[]>>(values.size()); // Go over all the values and determine whether the version is // acceptable for(Versioned<byte[]> value: values) { Iterator<Versioned<byte[]>> iter = resolvedVersions.iterator(); boolean obsolete = false; // Compare the current version with a set of accepted versions while(iter.hasNext()) { Versioned<byte[]> curr = iter.next(); Occurred occurred = value.getVersion().compare(curr.getVersion()); if(occurred == Occurred.BEFORE) { obsolete = true; break; } else if(occurred == Occurred.AFTER) { iter.remove(); } } if(!obsolete) { // else update the set of accepted versions resolvedVersions.add(value); } } return resolvedVersions; }
[ "public", "static", "List", "<", "Versioned", "<", "byte", "[", "]", ">", ">", "resolveVersions", "(", "List", "<", "Versioned", "<", "byte", "[", "]", ">", ">", "values", ")", "{", "List", "<", "Versioned", "<", "byte", "[", "]", ">", ">", "resolv...
Given a set of versions, constructs a resolved list of versions based on the compare function above @param values @return list of values after resolution
[ "Given", "a", "set", "of", "versions", "constructs", "a", "resolved", "list", "of", "versions", "based", "on", "the", "compare", "function", "above" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/versioning/VectorClockUtils.java#L102-L127
train
voldemort/voldemort
src/java/voldemort/versioning/VectorClockUtils.java
VectorClockUtils.makeClock
public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) { List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size()); for(Integer serverId: serverIds) { clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue)); } return new VectorClock(clockEntries, timestamp); }
java
public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) { List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size()); for(Integer serverId: serverIds) { clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue)); } return new VectorClock(clockEntries, timestamp); }
[ "public", "static", "VectorClock", "makeClock", "(", "Set", "<", "Integer", ">", "serverIds", ",", "long", "clockValue", ",", "long", "timestamp", ")", "{", "List", "<", "ClockEntry", ">", "clockEntries", "=", "new", "ArrayList", "<", "ClockEntry", ">", "(",...
Generates a vector clock with the provided values @param serverIds servers in the clock @param clockValue value of the clock for each server entry @param timestamp ts value to be set for the clock @return
[ "Generates", "a", "vector", "clock", "with", "the", "provided", "values" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/versioning/VectorClockUtils.java#L137-L143
train
voldemort/voldemort
src/java/voldemort/server/protocol/admin/AdminServiceRequestHandler.java
AdminServiceRequestHandler.swapStore
private String swapStore(String storeName, String directory) throws VoldemortException { ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore, storeRepository, storeName); if(!Utils.isReadableDir(directory)) throw new VoldemortException("Store directory '" + directory + "' is not a readable directory."); String currentDirPath = store.getCurrentDirPath(); logger.info("Swapping RO store '" + storeName + "' to version directory '" + directory + "'"); store.swapFiles(directory); logger.info("Swapping swapped RO store '" + storeName + "' to version directory '" + directory + "'"); return currentDirPath; }
java
private String swapStore(String storeName, String directory) throws VoldemortException { ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore, storeRepository, storeName); if(!Utils.isReadableDir(directory)) throw new VoldemortException("Store directory '" + directory + "' is not a readable directory."); String currentDirPath = store.getCurrentDirPath(); logger.info("Swapping RO store '" + storeName + "' to version directory '" + directory + "'"); store.swapFiles(directory); logger.info("Swapping swapped RO store '" + storeName + "' to version directory '" + directory + "'"); return currentDirPath; }
[ "private", "String", "swapStore", "(", "String", "storeName", ",", "String", "directory", ")", "throws", "VoldemortException", "{", "ReadOnlyStorageEngine", "store", "=", "getReadOnlyStorageEngine", "(", "metadataStore", ",", "storeRepository", ",", "storeName", ")", ...
Given a read-only store name and a directory, swaps it in while returning the directory path being swapped out @param storeName The name of the read-only store @param directory The directory being swapped in @return The directory path which was swapped out @throws VoldemortException
[ "Given", "a", "read", "-", "only", "store", "name", "and", "a", "directory", "swaps", "it", "in", "while", "returning", "the", "directory", "path", "being", "swapped", "out" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/AdminServiceRequestHandler.java#L996-L1015
train
voldemort/voldemort
src/java/voldemort/server/protocol/admin/AdminServiceRequestHandler.java
AdminServiceRequestHandler.isCompleteRequest
@Override public boolean isCompleteRequest(ByteBuffer buffer) { DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer)); try { int dataSize = inputStream.readInt(); if(logger.isTraceEnabled()) logger.trace("In isCompleteRequest, dataSize: " + dataSize + ", buffer position: " + buffer.position()); if(dataSize == -1) return true; // Here we skip over the data (without reading it in) and // move our position to just past it. buffer.position(buffer.position() + dataSize); return true; } catch(Exception e) { // This could also occur if the various methods we call into // re-throw a corrupted value error as some other type of exception. // For example, updating the position on a buffer past its limit // throws an InvalidArgumentException. if(logger.isTraceEnabled()) logger.trace("In isCompleteRequest, probable partial read occurred: " + e); return false; } }
java
@Override public boolean isCompleteRequest(ByteBuffer buffer) { DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer)); try { int dataSize = inputStream.readInt(); if(logger.isTraceEnabled()) logger.trace("In isCompleteRequest, dataSize: " + dataSize + ", buffer position: " + buffer.position()); if(dataSize == -1) return true; // Here we skip over the data (without reading it in) and // move our position to just past it. buffer.position(buffer.position() + dataSize); return true; } catch(Exception e) { // This could also occur if the various methods we call into // re-throw a corrupted value error as some other type of exception. // For example, updating the position on a buffer past its limit // throws an InvalidArgumentException. if(logger.isTraceEnabled()) logger.trace("In isCompleteRequest, probable partial read occurred: " + e); return false; } }
[ "@", "Override", "public", "boolean", "isCompleteRequest", "(", "ByteBuffer", "buffer", ")", "{", "DataInputStream", "inputStream", "=", "new", "DataInputStream", "(", "new", "ByteBufferBackedInputStream", "(", "buffer", ")", ")", ";", "try", "{", "int", "dataSize...
This method is used by non-blocking code to determine if the give buffer represents a complete request. Because the non-blocking code can by definition not just block waiting for more data, it's possible to get partial reads, and this identifies that case. @param buffer Buffer to check; the buffer is reset to position 0 before calling this method and the caller must reset it after the call returns @return True if the buffer holds a complete request, false otherwise
[ "This", "method", "is", "used", "by", "non", "-", "blocking", "code", "to", "determine", "if", "the", "give", "buffer", "represents", "a", "complete", "request", ".", "Because", "the", "non", "-", "blocking", "code", "can", "by", "definition", "not", "just...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/AdminServiceRequestHandler.java#L1720-L1749
train
voldemort/voldemort
src/java/voldemort/store/routed/PipelineRoutedStats.java
PipelineRoutedStats.unregisterJmxIfRequired
public synchronized void unregisterJmxIfRequired() { referenceCount--; if (isRegistered == true && referenceCount <= 0) { JmxUtils.unregisterMbean(this.jmxObjectName); isRegistered = false; } }
java
public synchronized void unregisterJmxIfRequired() { referenceCount--; if (isRegistered == true && referenceCount <= 0) { JmxUtils.unregisterMbean(this.jmxObjectName); isRegistered = false; } }
[ "public", "synchronized", "void", "unregisterJmxIfRequired", "(", ")", "{", "referenceCount", "--", ";", "if", "(", "isRegistered", "==", "true", "&&", "referenceCount", "<=", "0", ")", "{", "JmxUtils", ".", "unregisterMbean", "(", "this", ".", "jmxObjectName", ...
Last caller of this method will unregister the Mbean. All callers decrement the counter.
[ "Last", "caller", "of", "this", "method", "will", "unregister", "the", "Mbean", ".", "All", "callers", "decrement", "the", "counter", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/PipelineRoutedStats.java#L148-L154
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.toBinaryString
public static String toBinaryString(byte[] bytes) { StringBuilder buffer = new StringBuilder(); for(byte b: bytes) { String bin = Integer.toBinaryString(0xFF & b); bin = bin.substring(0, Math.min(bin.length(), 8)); for(int j = 0; j < 8 - bin.length(); j++) { buffer.append('0'); } buffer.append(bin); } return buffer.toString(); }
java
public static String toBinaryString(byte[] bytes) { StringBuilder buffer = new StringBuilder(); for(byte b: bytes) { String bin = Integer.toBinaryString(0xFF & b); bin = bin.substring(0, Math.min(bin.length(), 8)); for(int j = 0; j < 8 - bin.length(); j++) { buffer.append('0'); } buffer.append(bin); } return buffer.toString(); }
[ "public", "static", "String", "toBinaryString", "(", "byte", "[", "]", "bytes", ")", "{", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "byte", "b", ":", "bytes", ")", "{", "String", "bin", "=", "Integer", ".", "toB...
Translate the given byte array into a string of 1s and 0s @param bytes The bytes to translate @return The string
[ "Translate", "the", "given", "byte", "array", "into", "a", "string", "of", "1s", "and", "0s" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L93-L106
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.copy
public static byte[] copy(byte[] array, int from, int to) { if(to - from < 0) { return new byte[0]; } else { byte[] a = new byte[to - from]; System.arraycopy(array, from, a, 0, to - from); return a; } }
java
public static byte[] copy(byte[] array, int from, int to) { if(to - from < 0) { return new byte[0]; } else { byte[] a = new byte[to - from]; System.arraycopy(array, from, a, 0, to - from); return a; } }
[ "public", "static", "byte", "[", "]", "copy", "(", "byte", "[", "]", "array", ",", "int", "from", ",", "int", "to", ")", "{", "if", "(", "to", "-", "from", "<", "0", ")", "{", "return", "new", "byte", "[", "0", "]", ";", "}", "else", "{", "...
Copy the specified bytes into a new array @param array The array to copy from @param from The index in the array to begin copying from @param to The least index not copied @return A new byte[] containing the copied bytes
[ "Copy", "the", "specified", "bytes", "into", "a", "new", "array" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L140-L148
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.readInt
public static int readInt(byte[] bytes, int offset) { return (((bytes[offset + 0] & 0xff) << 24) | ((bytes[offset + 1] & 0xff) << 16) | ((bytes[offset + 2] & 0xff) << 8) | (bytes[offset + 3] & 0xff)); }
java
public static int readInt(byte[] bytes, int offset) { return (((bytes[offset + 0] & 0xff) << 24) | ((bytes[offset + 1] & 0xff) << 16) | ((bytes[offset + 2] & 0xff) << 8) | (bytes[offset + 3] & 0xff)); }
[ "public", "static", "int", "readInt", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ")", "{", "return", "(", "(", "(", "bytes", "[", "offset", "+", "0", "]", "&", "0xff", ")", "<<", "24", ")", "|", "(", "(", "bytes", "[", "offset", "+",...
Read an int from the byte array starting at the given offset @param bytes The byte array to read from @param offset The offset to start reading at @return The int read
[ "Read", "an", "int", "from", "the", "byte", "array", "starting", "at", "the", "given", "offset" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L179-L182
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.readUnsignedInt
public static long readUnsignedInt(byte[] bytes, int offset) { return (((bytes[offset + 0] & 0xffL) << 24) | ((bytes[offset + 1] & 0xffL) << 16) | ((bytes[offset + 2] & 0xffL) << 8) | (bytes[offset + 3] & 0xffL)); }
java
public static long readUnsignedInt(byte[] bytes, int offset) { return (((bytes[offset + 0] & 0xffL) << 24) | ((bytes[offset + 1] & 0xffL) << 16) | ((bytes[offset + 2] & 0xffL) << 8) | (bytes[offset + 3] & 0xffL)); }
[ "public", "static", "long", "readUnsignedInt", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ")", "{", "return", "(", "(", "(", "bytes", "[", "offset", "+", "0", "]", "&", "0xff", "L", ")", "<<", "24", ")", "|", "(", "(", "bytes", "[", ...
Read an unsigned integer from the given byte array @param bytes The bytes to read from @param offset The offset to begin reading at @return The integer as a long
[ "Read", "an", "unsigned", "integer", "from", "the", "given", "byte", "array" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L191-L194
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.readBytes
public static long readBytes(byte[] bytes, int offset, int numBytes) { int shift = 0; long value = 0; for(int i = offset + numBytes - 1; i >= offset; i--) { value |= (bytes[i] & 0xFFL) << shift; shift += 8; } return value; }
java
public static long readBytes(byte[] bytes, int offset, int numBytes) { int shift = 0; long value = 0; for(int i = offset + numBytes - 1; i >= offset; i--) { value |= (bytes[i] & 0xFFL) << shift; shift += 8; } return value; }
[ "public", "static", "long", "readBytes", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "int", "numBytes", ")", "{", "int", "shift", "=", "0", ";", "long", "value", "=", "0", ";", "for", "(", "int", "i", "=", "offset", "+", "numBytes", ...
Read the given number of bytes into a long @param bytes The byte array to read from @param offset The offset at which to begin reading @param numBytes The number of bytes to read @return The long value read
[ "Read", "the", "given", "number", "of", "bytes", "into", "a", "long" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L221-L229
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.writeShort
public static void writeShort(byte[] bytes, short value, int offset) { bytes[offset] = (byte) (0xFF & (value >> 8)); bytes[offset + 1] = (byte) (0xFF & value); }
java
public static void writeShort(byte[] bytes, short value, int offset) { bytes[offset] = (byte) (0xFF & (value >> 8)); bytes[offset + 1] = (byte) (0xFF & value); }
[ "public", "static", "void", "writeShort", "(", "byte", "[", "]", "bytes", ",", "short", "value", ",", "int", "offset", ")", "{", "bytes", "[", "offset", "]", "=", "(", "byte", ")", "(", "0xFF", "&", "(", "value", ">>", "8", ")", ")", ";", "bytes"...
Write a short to the byte array starting at the given offset @param bytes The byte array @param value The short to write @param offset The offset to begin writing at
[ "Write", "a", "short", "to", "the", "byte", "array", "starting", "at", "the", "given", "offset" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L238-L241
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.writeUnsignedShort
public static void writeUnsignedShort(byte[] bytes, int value, int offset) { bytes[offset] = (byte) (0xFF & (value >> 8)); bytes[offset + 1] = (byte) (0xFF & value); }
java
public static void writeUnsignedShort(byte[] bytes, int value, int offset) { bytes[offset] = (byte) (0xFF & (value >> 8)); bytes[offset + 1] = (byte) (0xFF & value); }
[ "public", "static", "void", "writeUnsignedShort", "(", "byte", "[", "]", "bytes", ",", "int", "value", ",", "int", "offset", ")", "{", "bytes", "[", "offset", "]", "=", "(", "byte", ")", "(", "0xFF", "&", "(", "value", ">>", "8", ")", ")", ";", "...
Write an unsigned short to the byte array starting at the given offset @param bytes The byte array @param value The short to write @param offset The offset to begin writing at
[ "Write", "an", "unsigned", "short", "to", "the", "byte", "array", "starting", "at", "the", "given", "offset" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L250-L253
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.writeInt
public static void writeInt(byte[] bytes, int value, int offset) { bytes[offset] = (byte) (0xFF & (value >> 24)); bytes[offset + 1] = (byte) (0xFF & (value >> 16)); bytes[offset + 2] = (byte) (0xFF & (value >> 8)); bytes[offset + 3] = (byte) (0xFF & value); }
java
public static void writeInt(byte[] bytes, int value, int offset) { bytes[offset] = (byte) (0xFF & (value >> 24)); bytes[offset + 1] = (byte) (0xFF & (value >> 16)); bytes[offset + 2] = (byte) (0xFF & (value >> 8)); bytes[offset + 3] = (byte) (0xFF & value); }
[ "public", "static", "void", "writeInt", "(", "byte", "[", "]", "bytes", ",", "int", "value", ",", "int", "offset", ")", "{", "bytes", "[", "offset", "]", "=", "(", "byte", ")", "(", "0xFF", "&", "(", "value", ">>", "24", ")", ")", ";", "bytes", ...
Write an int to the byte array starting at the given offset @param bytes The byte array @param value The int to write @param offset The offset to begin writing at
[ "Write", "an", "int", "to", "the", "byte", "array", "starting", "at", "the", "given", "offset" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L262-L267
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.writeBytes
public static void writeBytes(byte[] bytes, long value, int offset, int numBytes) { int shift = 0; for(int i = offset + numBytes - 1; i >= offset; i--) { bytes[i] = (byte) (0xFF & (value >> shift)); shift += 8; } }
java
public static void writeBytes(byte[] bytes, long value, int offset, int numBytes) { int shift = 0; for(int i = offset + numBytes - 1; i >= offset; i--) { bytes[i] = (byte) (0xFF & (value >> shift)); shift += 8; } }
[ "public", "static", "void", "writeBytes", "(", "byte", "[", "]", "bytes", ",", "long", "value", ",", "int", "offset", ",", "int", "numBytes", ")", "{", "int", "shift", "=", "0", ";", "for", "(", "int", "i", "=", "offset", "+", "numBytes", "-", "1",...
Write the given number of bytes out to the array @param bytes The array to write to @param value The value to write from @param offset the offset into the array @param numBytes The number of bytes to write
[ "Write", "the", "given", "number", "of", "bytes", "out", "to", "the", "array" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L295-L301
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.numberOfBytesRequired
public static byte numberOfBytesRequired(long number) { if(number < 0) number = -number; for(byte i = 1; i <= SIZE_OF_LONG; i++) if(number < (1L << (8 * i))) return i; throw new IllegalStateException("Should never happen."); }
java
public static byte numberOfBytesRequired(long number) { if(number < 0) number = -number; for(byte i = 1; i <= SIZE_OF_LONG; i++) if(number < (1L << (8 * i))) return i; throw new IllegalStateException("Should never happen."); }
[ "public", "static", "byte", "numberOfBytesRequired", "(", "long", "number", ")", "{", "if", "(", "number", "<", "0", ")", "number", "=", "-", "number", ";", "for", "(", "byte", "i", "=", "1", ";", "i", "<=", "SIZE_OF_LONG", ";", "i", "++", ")", "if...
The number of bytes required to hold the given number @param number The number being checked. @return The required number of bytes (must be 8 or less)
[ "The", "number", "of", "bytes", "required", "to", "hold", "the", "given", "number" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L309-L316
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.read
public static void read(InputStream stream, byte[] buffer) throws IOException { int read = 0; while(read < buffer.length) { int newlyRead = stream.read(buffer, read, buffer.length - read); if(newlyRead == -1) throw new EOFException("Attempt to read " + buffer.length + " bytes failed due to EOF."); read += newlyRead; } }
java
public static void read(InputStream stream, byte[] buffer) throws IOException { int read = 0; while(read < buffer.length) { int newlyRead = stream.read(buffer, read, buffer.length - read); if(newlyRead == -1) throw new EOFException("Attempt to read " + buffer.length + " bytes failed due to EOF."); read += newlyRead; } }
[ "public", "static", "void", "read", "(", "InputStream", "stream", ",", "byte", "[", "]", "buffer", ")", "throws", "IOException", "{", "int", "read", "=", "0", ";", "while", "(", "read", "<", "buffer", ".", "length", ")", "{", "int", "newlyRead", "=", ...
Read exactly buffer.length bytes from the stream into the buffer @param stream The stream to read from @param buffer The buffer to read into
[ "Read", "exactly", "buffer", ".", "length", "bytes", "from", "the", "stream", "into", "the", "buffer" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L366-L375
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.getBytes
public static byte[] getBytes(String string, String encoding) { try { return string.getBytes(encoding); } catch(UnsupportedEncodingException e) { throw new IllegalArgumentException(encoding + " is not a known encoding name.", e); } }
java
public static byte[] getBytes(String string, String encoding) { try { return string.getBytes(encoding); } catch(UnsupportedEncodingException e) { throw new IllegalArgumentException(encoding + " is not a known encoding name.", e); } }
[ "public", "static", "byte", "[", "]", "getBytes", "(", "String", "string", ",", "String", "encoding", ")", "{", "try", "{", "return", "string", ".", "getBytes", "(", "encoding", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", ...
Translate the string to bytes using the given encoding @param string The string to translate @param encoding The encoding to use @return The bytes that make up the string
[ "Translate", "the", "string", "to", "bytes", "using", "the", "given", "encoding" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L384-L390
train
voldemort/voldemort
src/java/voldemort/utils/ByteUtils.java
ByteUtils.getString
public static String getString(byte[] bytes, String encoding) { try { return new String(bytes, encoding); } catch(UnsupportedEncodingException e) { throw new IllegalArgumentException(encoding + " is not a known encoding name.", e); } }
java
public static String getString(byte[] bytes, String encoding) { try { return new String(bytes, encoding); } catch(UnsupportedEncodingException e) { throw new IllegalArgumentException(encoding + " is not a known encoding name.", e); } }
[ "public", "static", "String", "getString", "(", "byte", "[", "]", "bytes", ",", "String", "encoding", ")", "{", "try", "{", "return", "new", "String", "(", "bytes", ",", "encoding", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "...
Create a string from bytes using the given encoding @param bytes The bytes to create a string from @param encoding The encoding of the string @return The created string
[ "Create", "a", "string", "from", "bytes", "using", "the", "given", "encoding" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L399-L405
train
voldemort/voldemort
src/java/voldemort/store/stats/RequestCounter.java
RequestCounter.addRequest
public void addRequest(long timeNS, long numEmptyResponses, long valueBytes, long keyBytes, long getAllAggregatedCount) { // timing instrumentation (trace only) long startTimeNs = 0; if(logger.isTraceEnabled()) { startTimeNs = System.nanoTime(); } long currentTime = time.milliseconds(); timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime); emptyResponseKeysSensor.record(numEmptyResponses, currentTime); valueBytesSensor.record(valueBytes, currentTime); keyBytesSensor.record(keyBytes, currentTime); getAllKeysCountSensor.record(getAllAggregatedCount, currentTime); // timing instrumentation (trace only) if(logger.isTraceEnabled()) { logger.trace("addRequest took " + (System.nanoTime() - startTimeNs) + " ns."); } }
java
public void addRequest(long timeNS, long numEmptyResponses, long valueBytes, long keyBytes, long getAllAggregatedCount) { // timing instrumentation (trace only) long startTimeNs = 0; if(logger.isTraceEnabled()) { startTimeNs = System.nanoTime(); } long currentTime = time.milliseconds(); timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime); emptyResponseKeysSensor.record(numEmptyResponses, currentTime); valueBytesSensor.record(valueBytes, currentTime); keyBytesSensor.record(keyBytes, currentTime); getAllKeysCountSensor.record(getAllAggregatedCount, currentTime); // timing instrumentation (trace only) if(logger.isTraceEnabled()) { logger.trace("addRequest took " + (System.nanoTime() - startTimeNs) + " ns."); } }
[ "public", "void", "addRequest", "(", "long", "timeNS", ",", "long", "numEmptyResponses", ",", "long", "valueBytes", ",", "long", "keyBytes", ",", "long", "getAllAggregatedCount", ")", "{", "// timing instrumentation (trace only)", "long", "startTimeNs", "=", "0", ";...
Detailed request to track additional data about PUT, GET and GET_ALL @param timeNS The time in nanoseconds that the operation took to complete @param numEmptyResponses For GET and GET_ALL, how many keys were no values found @param valueBytes Total number of bytes across all versions of values' bytes @param keyBytes Total number of bytes in the keys @param getAllAggregatedCount Total number of keys returned for getAll calls
[ "Detailed", "request", "to", "track", "additional", "data", "about", "PUT", "GET", "and", "GET_ALL" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/RequestCounter.java#L268-L291
train
voldemort/voldemort
src/java/voldemort/store/routed/Pipeline.java
Pipeline.addEvent
public void addEvent(Event event) { if(event == null) throw new IllegalStateException("event must be non-null"); if(logger.isTraceEnabled()) logger.trace("Adding event " + event); eventQueue.add(event); }
java
public void addEvent(Event event) { if(event == null) throw new IllegalStateException("event must be non-null"); if(logger.isTraceEnabled()) logger.trace("Adding event " + event); eventQueue.add(event); }
[ "public", "void", "addEvent", "(", "Event", "event", ")", "{", "if", "(", "event", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"event must be non-null\"", ")", ";", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "logger", ...
Add an event to the queue. It will be processed in the order received. @param event Event
[ "Add", "an", "event", "to", "the", "queue", ".", "It", "will", "be", "processed", "in", "the", "order", "received", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/Pipeline.java#L141-L149
train
voldemort/voldemort
src/java/voldemort/store/routed/Pipeline.java
Pipeline.execute
public void execute() { try { while(true) { Event event = null; try { event = eventQueue.poll(timeout, unit); } catch(InterruptedException e) { throw new InsufficientOperationalNodesException(operation.getSimpleName() + " operation interrupted!", e); } if(event == null) throw new VoldemortException(operation.getSimpleName() + " returned a null event"); if(event.equals(Event.ERROR)) { if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, events complete due to error"); break; } else if(event.equals(Event.COMPLETED)) { if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, events complete"); break; } Action action = eventActions.get(event); if(action == null) throw new IllegalStateException("action was null for event " + event); if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, action " + action.getClass().getSimpleName() + " to handle " + event + " event"); action.execute(this); } } finally { finished = true; } }
java
public void execute() { try { while(true) { Event event = null; try { event = eventQueue.poll(timeout, unit); } catch(InterruptedException e) { throw new InsufficientOperationalNodesException(operation.getSimpleName() + " operation interrupted!", e); } if(event == null) throw new VoldemortException(operation.getSimpleName() + " returned a null event"); if(event.equals(Event.ERROR)) { if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, events complete due to error"); break; } else if(event.equals(Event.COMPLETED)) { if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, events complete"); break; } Action action = eventActions.get(event); if(action == null) throw new IllegalStateException("action was null for event " + event); if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, action " + action.getClass().getSimpleName() + " to handle " + event + " event"); action.execute(this); } } finally { finished = true; } }
[ "public", "void", "execute", "(", ")", "{", "try", "{", "while", "(", "true", ")", "{", "Event", "event", "=", "null", ";", "try", "{", "event", "=", "eventQueue", ".", "poll", "(", "timeout", ",", "unit", ")", ";", "}", "catch", "(", "InterruptedE...
Process events in the order as they were received. <p/> The overall time to process the events must be within the bounds of the timeout or an {@link InsufficientOperationalNodesException} will be thrown.
[ "Process", "events", "in", "the", "order", "as", "they", "were", "received", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/Pipeline.java#L173-L217
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.createModelMBean
public static ModelMBean createModelMBean(Object o) { try { ModelMBean mbean = new RequiredModelMBean(); JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class); String description = annotation == null ? "" : annotation.description(); ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(), description, extractAttributeInfo(o), new ModelMBeanConstructorInfo[0], extractOperationInfo(o), new ModelMBeanNotificationInfo[0]); mbean.setModelMBeanInfo(info); mbean.setManagedResource(o, "ObjectReference"); return mbean; } catch(MBeanException e) { throw new VoldemortException(e); } catch(InvalidTargetObjectTypeException e) { throw new VoldemortException(e); } catch(InstanceNotFoundException e) { throw new VoldemortException(e); } }
java
public static ModelMBean createModelMBean(Object o) { try { ModelMBean mbean = new RequiredModelMBean(); JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class); String description = annotation == null ? "" : annotation.description(); ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(), description, extractAttributeInfo(o), new ModelMBeanConstructorInfo[0], extractOperationInfo(o), new ModelMBeanNotificationInfo[0]); mbean.setModelMBeanInfo(info); mbean.setManagedResource(o, "ObjectReference"); return mbean; } catch(MBeanException e) { throw new VoldemortException(e); } catch(InvalidTargetObjectTypeException e) { throw new VoldemortException(e); } catch(InstanceNotFoundException e) { throw new VoldemortException(e); } }
[ "public", "static", "ModelMBean", "createModelMBean", "(", "Object", "o", ")", "{", "try", "{", "ModelMBean", "mbean", "=", "new", "RequiredModelMBean", "(", ")", ";", "JmxManaged", "annotation", "=", "o", ".", "getClass", "(", ")", ".", "getAnnotation", "("...
Create a model mbean from an object using the description given in the Jmx annotation if present. Only operations are supported so far, no attributes, constructors, or notifications @param o The object to create an MBean for @return The ModelMBean for the given object
[ "Create", "a", "model", "mbean", "from", "an", "object", "using", "the", "description", "given", "in", "the", "Jmx", "annotation", "if", "present", ".", "Only", "operations", "are", "supported", "so", "far", "no", "attributes", "constructors", "or", "notificat...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L81-L103
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.extractOperationInfo
public static ModelMBeanOperationInfo[] extractOperationInfo(Object object) { ArrayList<ModelMBeanOperationInfo> infos = new ArrayList<ModelMBeanOperationInfo>(); for(Method m: object.getClass().getMethods()) { JmxOperation jmxOperation = m.getAnnotation(JmxOperation.class); JmxGetter jmxGetter = m.getAnnotation(JmxGetter.class); JmxSetter jmxSetter = m.getAnnotation(JmxSetter.class); if(jmxOperation != null || jmxGetter != null || jmxSetter != null) { String description = ""; int visibility = 1; int impact = MBeanOperationInfo.UNKNOWN; if(jmxOperation != null) { description = jmxOperation.description(); impact = jmxOperation.impact(); } else if(jmxGetter != null) { description = jmxGetter.description(); impact = MBeanOperationInfo.INFO; visibility = 4; } else if(jmxSetter != null) { description = jmxSetter.description(); impact = MBeanOperationInfo.ACTION; visibility = 4; } ModelMBeanOperationInfo info = new ModelMBeanOperationInfo(m.getName(), description, extractParameterInfo(m), m.getReturnType() .getName(), impact); info.getDescriptor().setField("visibility", Integer.toString(visibility)); infos.add(info); } } return infos.toArray(new ModelMBeanOperationInfo[infos.size()]); }
java
public static ModelMBeanOperationInfo[] extractOperationInfo(Object object) { ArrayList<ModelMBeanOperationInfo> infos = new ArrayList<ModelMBeanOperationInfo>(); for(Method m: object.getClass().getMethods()) { JmxOperation jmxOperation = m.getAnnotation(JmxOperation.class); JmxGetter jmxGetter = m.getAnnotation(JmxGetter.class); JmxSetter jmxSetter = m.getAnnotation(JmxSetter.class); if(jmxOperation != null || jmxGetter != null || jmxSetter != null) { String description = ""; int visibility = 1; int impact = MBeanOperationInfo.UNKNOWN; if(jmxOperation != null) { description = jmxOperation.description(); impact = jmxOperation.impact(); } else if(jmxGetter != null) { description = jmxGetter.description(); impact = MBeanOperationInfo.INFO; visibility = 4; } else if(jmxSetter != null) { description = jmxSetter.description(); impact = MBeanOperationInfo.ACTION; visibility = 4; } ModelMBeanOperationInfo info = new ModelMBeanOperationInfo(m.getName(), description, extractParameterInfo(m), m.getReturnType() .getName(), impact); info.getDescriptor().setField("visibility", Integer.toString(visibility)); infos.add(info); } } return infos.toArray(new ModelMBeanOperationInfo[infos.size()]); }
[ "public", "static", "ModelMBeanOperationInfo", "[", "]", "extractOperationInfo", "(", "Object", "object", ")", "{", "ArrayList", "<", "ModelMBeanOperationInfo", ">", "infos", "=", "new", "ArrayList", "<", "ModelMBeanOperationInfo", ">", "(", ")", ";", "for", "(", ...
Extract all operations and attributes from the given object that have been annotated with the Jmx annotation. Operations are all methods that are marked with the JmxOperation annotation. @param object The object to process @return An array of operations taken from the object
[ "Extract", "all", "operations", "and", "attributes", "from", "the", "given", "object", "that", "have", "been", "annotated", "with", "the", "Jmx", "annotation", ".", "Operations", "are", "all", "methods", "that", "are", "marked", "with", "the", "JmxOperation", ...
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L113-L146
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.extractParameterInfo
public static MBeanParameterInfo[] extractParameterInfo(Method m) { Class<?>[] types = m.getParameterTypes(); Annotation[][] annotations = m.getParameterAnnotations(); MBeanParameterInfo[] params = new MBeanParameterInfo[types.length]; for(int i = 0; i < params.length; i++) { boolean hasAnnotation = false; for(int j = 0; j < annotations[i].length; j++) { if(annotations[i][j] instanceof JmxParam) { JmxParam param = (JmxParam) annotations[i][j]; params[i] = new MBeanParameterInfo(param.name(), types[i].getName(), param.description()); hasAnnotation = true; break; } } if(!hasAnnotation) { params[i] = new MBeanParameterInfo("", types[i].getName(), ""); } } return params; }
java
public static MBeanParameterInfo[] extractParameterInfo(Method m) { Class<?>[] types = m.getParameterTypes(); Annotation[][] annotations = m.getParameterAnnotations(); MBeanParameterInfo[] params = new MBeanParameterInfo[types.length]; for(int i = 0; i < params.length; i++) { boolean hasAnnotation = false; for(int j = 0; j < annotations[i].length; j++) { if(annotations[i][j] instanceof JmxParam) { JmxParam param = (JmxParam) annotations[i][j]; params[i] = new MBeanParameterInfo(param.name(), types[i].getName(), param.description()); hasAnnotation = true; break; } } if(!hasAnnotation) { params[i] = new MBeanParameterInfo("", types[i].getName(), ""); } } return params; }
[ "public", "static", "MBeanParameterInfo", "[", "]", "extractParameterInfo", "(", "Method", "m", ")", "{", "Class", "<", "?", ">", "[", "]", "types", "=", "m", ".", "getParameterTypes", "(", ")", ";", "Annotation", "[", "]", "[", "]", "annotations", "=", ...
Extract the parameters from a method using the Jmx annotation if present, or just the raw types otherwise @param m The method to extract parameters from @return An array of parameter infos
[ "Extract", "the", "parameters", "from", "a", "method", "using", "the", "Jmx", "annotation", "if", "present", "or", "just", "the", "raw", "types", "otherwise" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L207-L229
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.createObjectName
public static ObjectName createObjectName(String domain, String type) { try { return new ObjectName(domain + ":type=" + type); } catch(MalformedObjectNameException e) { throw new VoldemortException(e); } }
java
public static ObjectName createObjectName(String domain, String type) { try { return new ObjectName(domain + ":type=" + type); } catch(MalformedObjectNameException e) { throw new VoldemortException(e); } }
[ "public", "static", "ObjectName", "createObjectName", "(", "String", "domain", ",", "String", "type", ")", "{", "try", "{", "return", "new", "ObjectName", "(", "domain", "+", "\":type=\"", "+", "type", ")", ";", "}", "catch", "(", "MalformedObjectNameException...
Create a JMX ObjectName @param domain The domain of the object @param type The type of the object @return An ObjectName representing the name
[ "Create", "a", "JMX", "ObjectName" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L238-L244
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.getClassName
public static String getClassName(Class<?> c) { String name = c.getName(); return name.substring(name.lastIndexOf('.') + 1, name.length()); }
java
public static String getClassName(Class<?> c) { String name = c.getName(); return name.substring(name.lastIndexOf('.') + 1, name.length()); }
[ "public", "static", "String", "getClassName", "(", "Class", "<", "?", ">", "c", ")", "{", "String", "name", "=", "c", ".", "getName", "(", ")", ";", "return", "name", ".", "substring", "(", "name", ".", "lastIndexOf", "(", "'", "'", ")", "+", "1", ...
Get the class name without the package @param c The class name with package @return the class name without the package
[ "Get", "the", "class", "name", "without", "the", "package" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L273-L276
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.registerMbean
public static void registerMbean(Object mbean, ObjectName name) { registerMbean(ManagementFactory.getPlatformMBeanServer(), JmxUtils.createModelMBean(mbean), name); }
java
public static void registerMbean(Object mbean, ObjectName name) { registerMbean(ManagementFactory.getPlatformMBeanServer(), JmxUtils.createModelMBean(mbean), name); }
[ "public", "static", "void", "registerMbean", "(", "Object", "mbean", ",", "ObjectName", "name", ")", "{", "registerMbean", "(", "ManagementFactory", ".", "getPlatformMBeanServer", "(", ")", ",", "JmxUtils", ".", "createModelMBean", "(", "mbean", ")", ",", "name"...
Register the given mbean with the platform mbean server @param mbean The mbean to register @param name The name to register under
[ "Register", "the", "given", "mbean", "with", "the", "platform", "mbean", "server" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L284-L288
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.registerMbean
public static ObjectName registerMbean(String typeName, Object obj) { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()), typeName); registerMbean(server, JmxUtils.createModelMBean(obj), name); return name; }
java
public static ObjectName registerMbean(String typeName, Object obj) { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()), typeName); registerMbean(server, JmxUtils.createModelMBean(obj), name); return name; }
[ "public", "static", "ObjectName", "registerMbean", "(", "String", "typeName", ",", "Object", "obj", ")", "{", "MBeanServer", "server", "=", "ManagementFactory", ".", "getPlatformMBeanServer", "(", ")", ";", "ObjectName", "name", "=", "JmxUtils", ".", "createObject...
Register the given object under the package name of the object's class with the given type name. this method using the platform mbean server as returned by ManagementFactory.getPlatformMBeanServer() @param typeName The name of the type to register @param obj The object to register as an mbean
[ "Register", "the", "given", "object", "under", "the", "package", "name", "of", "the", "object", "s", "class", "with", "the", "given", "type", "name", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L300-L306
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.registerMbean
public static void registerMbean(MBeanServer server, ModelMBean mbean, ObjectName name) { try { synchronized(LOCK) { if(server.isRegistered(name)) JmxUtils.unregisterMbean(server, name); server.registerMBean(mbean, name); } } catch(Exception e) { logger.error("Error registering mbean:", e); } }
java
public static void registerMbean(MBeanServer server, ModelMBean mbean, ObjectName name) { try { synchronized(LOCK) { if(server.isRegistered(name)) JmxUtils.unregisterMbean(server, name); server.registerMBean(mbean, name); } } catch(Exception e) { logger.error("Error registering mbean:", e); } }
[ "public", "static", "void", "registerMbean", "(", "MBeanServer", "server", ",", "ModelMBean", "mbean", ",", "ObjectName", "name", ")", "{", "try", "{", "synchronized", "(", "LOCK", ")", "{", "if", "(", "server", ".", "isRegistered", "(", "name", ")", ")", ...
Register the given mbean with the server @param server The server to register with @param mbean The mbean to register @param name The name to register under
[ "Register", "the", "given", "mbean", "with", "the", "server" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L315-L325
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.unregisterMbean
public static void unregisterMbean(MBeanServer server, ObjectName name) { try { server.unregisterMBean(name); } catch(Exception e) { logger.error("Error unregistering mbean", e); } }
java
public static void unregisterMbean(MBeanServer server, ObjectName name) { try { server.unregisterMBean(name); } catch(Exception e) { logger.error("Error unregistering mbean", e); } }
[ "public", "static", "void", "unregisterMbean", "(", "MBeanServer", "server", ",", "ObjectName", "name", ")", "{", "try", "{", "server", ".", "unregisterMBean", "(", "name", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", ...
Unregister the mbean with the given name @param server The server to unregister from @param name The name of the mbean to unregister
[ "Unregister", "the", "mbean", "with", "the", "given", "name" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L333-L339
train
voldemort/voldemort
src/java/voldemort/utils/JmxUtils.java
JmxUtils.unregisterMbean
public static void unregisterMbean(ObjectName name) { try { ManagementFactory.getPlatformMBeanServer().unregisterMBean(name); } catch(Exception e) { logger.error("Error unregistering mbean", e); } }
java
public static void unregisterMbean(ObjectName name) { try { ManagementFactory.getPlatformMBeanServer().unregisterMBean(name); } catch(Exception e) { logger.error("Error unregistering mbean", e); } }
[ "public", "static", "void", "unregisterMbean", "(", "ObjectName", "name", ")", "{", "try", "{", "ManagementFactory", ".", "getPlatformMBeanServer", "(", ")", ".", "unregisterMBean", "(", "name", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logge...
Unregister the mbean with the given name from the platform mbean server @param name The name of the mbean to unregister
[ "Unregister", "the", "mbean", "with", "the", "given", "name", "from", "the", "platform", "mbean", "server" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L346-L352
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyUtils.java
ReadOnlyUtils.isFormatCorrect
public static boolean isFormatCorrect(String fileName, ReadOnlyStorageFormat format) { switch(format) { case READONLY_V0: case READONLY_V1: if(fileName.matches("^[\\d]+_[\\d]+\\.(data|index)")) { return true; } else { return false; } case READONLY_V2: if(fileName.matches("^[\\d]+_[\\d]+_[\\d]+\\.(data|index)")) { return true; } else { return false; } default: throw new VoldemortException("Format type not supported"); } }
java
public static boolean isFormatCorrect(String fileName, ReadOnlyStorageFormat format) { switch(format) { case READONLY_V0: case READONLY_V1: if(fileName.matches("^[\\d]+_[\\d]+\\.(data|index)")) { return true; } else { return false; } case READONLY_V2: if(fileName.matches("^[\\d]+_[\\d]+_[\\d]+\\.(data|index)")) { return true; } else { return false; } default: throw new VoldemortException("Format type not supported"); } }
[ "public", "static", "boolean", "isFormatCorrect", "(", "String", "fileName", ",", "ReadOnlyStorageFormat", "format", ")", "{", "switch", "(", "format", ")", "{", "case", "READONLY_V0", ":", "case", "READONLY_V1", ":", "if", "(", "fileName", ".", "matches", "("...
Given a file name and read-only storage format, tells whether the file name format is correct @param fileName The name of the file @param format The RO format @return true if file format is correct, else false
[ "Given", "a", "file", "name", "and", "read", "-", "only", "storage", "format", "tells", "whether", "the", "file", "name", "format", "is", "correct" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyUtils.java#L53-L73
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyUtils.java
ReadOnlyUtils.getChunkId
public static int getChunkId(String fileName) { Pattern pattern = Pattern.compile("_[\\d]+\\."); Matcher matcher = pattern.matcher(fileName); if(matcher.find()) { return new Integer(fileName.substring(matcher.start() + 1, matcher.end() - 1)); } else { throw new VoldemortException("Could not extract out chunk id from " + fileName); } }
java
public static int getChunkId(String fileName) { Pattern pattern = Pattern.compile("_[\\d]+\\."); Matcher matcher = pattern.matcher(fileName); if(matcher.find()) { return new Integer(fileName.substring(matcher.start() + 1, matcher.end() - 1)); } else { throw new VoldemortException("Could not extract out chunk id from " + fileName); } }
[ "public", "static", "int", "getChunkId", "(", "String", "fileName", ")", "{", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "\"_[\\\\d]+\\\\.\"", ")", ";", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "fileName", ")", ";", "if", ...
Returns the chunk id for the file name @param fileName The file name @return Chunk id
[ "Returns", "the", "chunk", "id", "for", "the", "file", "name" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyUtils.java#L103-L112
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyUtils.java
ReadOnlyUtils.getCurrentVersion
public static File getCurrentVersion(File storeDirectory) { File latestDir = getLatestDir(storeDirectory); if(latestDir != null) return latestDir; File[] versionDirs = getVersionDirs(storeDirectory); if(versionDirs == null || versionDirs.length == 0) { return null; } else { return findKthVersionedDir(versionDirs, versionDirs.length - 1, versionDirs.length - 1)[0]; } }
java
public static File getCurrentVersion(File storeDirectory) { File latestDir = getLatestDir(storeDirectory); if(latestDir != null) return latestDir; File[] versionDirs = getVersionDirs(storeDirectory); if(versionDirs == null || versionDirs.length == 0) { return null; } else { return findKthVersionedDir(versionDirs, versionDirs.length - 1, versionDirs.length - 1)[0]; } }
[ "public", "static", "File", "getCurrentVersion", "(", "File", "storeDirectory", ")", "{", "File", "latestDir", "=", "getLatestDir", "(", "storeDirectory", ")", ";", "if", "(", "latestDir", "!=", "null", ")", "return", "latestDir", ";", "File", "[", "]", "ver...
Retrieve the dir pointed to by 'latest' symbolic-link or the current version dir @return Current version directory, else null
[ "Retrieve", "the", "dir", "pointed", "to", "by", "latest", "symbolic", "-", "link", "or", "the", "current", "version", "dir" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyUtils.java#L120-L131
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyUtils.java
ReadOnlyUtils.checkVersionDirName
public static boolean checkVersionDirName(File versionDir) { return (versionDir.isDirectory() && versionDir.getName().contains("version-") && !versionDir.getName() .endsWith(".bak")); }
java
public static boolean checkVersionDirName(File versionDir) { return (versionDir.isDirectory() && versionDir.getName().contains("version-") && !versionDir.getName() .endsWith(".bak")); }
[ "public", "static", "boolean", "checkVersionDirName", "(", "File", "versionDir", ")", "{", "return", "(", "versionDir", ".", "isDirectory", "(", ")", "&&", "versionDir", ".", "getName", "(", ")", ".", "contains", "(", "\"version-\"", ")", "&&", "!", "version...
Checks if the name of the file follows the version-n format @param versionDir The directory @return Returns true if the name is correct, else false
[ "Checks", "if", "the", "name", "of", "the", "file", "follows", "the", "version", "-", "n", "format" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyUtils.java#L162-L165
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyUtils.java
ReadOnlyUtils.getVersionId
private static long getVersionId(String versionDir) { try { return Long.parseLong(versionDir.replace("version-", "")); } catch(NumberFormatException e) { logger.trace("Cannot parse version directory to obtain id " + versionDir); return -1; } }
java
private static long getVersionId(String versionDir) { try { return Long.parseLong(versionDir.replace("version-", "")); } catch(NumberFormatException e) { logger.trace("Cannot parse version directory to obtain id " + versionDir); return -1; } }
[ "private", "static", "long", "getVersionId", "(", "String", "versionDir", ")", "{", "try", "{", "return", "Long", ".", "parseLong", "(", "versionDir", ".", "replace", "(", "\"version-\"", ",", "\"\"", ")", ")", ";", "}", "catch", "(", "NumberFormatException"...
Extracts the version id from a string @param versionDir The string @return Returns the version id of the directory, else -1
[ "Extracts", "the", "version", "id", "from", "a", "string" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyUtils.java#L183-L190
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyUtils.java
ReadOnlyUtils.getVersionDirs
public static File[] getVersionDirs(File rootDir, final long minId, final long maxId) { return rootDir.listFiles(new FileFilter() { public boolean accept(File pathName) { if(checkVersionDirName(pathName)) { long versionId = getVersionId(pathName); if(versionId != -1 && versionId <= maxId && versionId >= minId) { return true; } } return false; } }); }
java
public static File[] getVersionDirs(File rootDir, final long minId, final long maxId) { return rootDir.listFiles(new FileFilter() { public boolean accept(File pathName) { if(checkVersionDirName(pathName)) { long versionId = getVersionId(pathName); if(versionId != -1 && versionId <= maxId && versionId >= minId) { return true; } } return false; } }); }
[ "public", "static", "File", "[", "]", "getVersionDirs", "(", "File", "rootDir", ",", "final", "long", "minId", ",", "final", "long", "maxId", ")", "{", "return", "rootDir", ".", "listFiles", "(", "new", "FileFilter", "(", ")", "{", "public", "boolean", "...
Returns all the version directories present in the root directory specified @param rootDir The parent directory @param maxId The @return An array of version directories
[ "Returns", "all", "the", "version", "directories", "present", "in", "the", "root", "directory", "specified" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyUtils.java#L211-L224
train
voldemort/voldemort
src/java/voldemort/server/VoldemortServer.java
VoldemortServer.stopInner
@Override protected void stopInner() throws VoldemortException { List<VoldemortException> exceptions = new ArrayList<VoldemortException>(); logger.info("Stopping services:" + getIdentityNode().getId()); /* Stop in reverse order */ exceptions.addAll(stopOnlineServices()); for(VoldemortService service: Utils.reversed(basicServices)) { try { service.stop(); } catch(VoldemortException e) { exceptions.add(e); logger.error(e); } } logger.info("All services stopped for Node:" + getIdentityNode().getId()); if(exceptions.size() > 0) throw exceptions.get(0); // release lock of jvm heap JNAUtils.tryMunlockall(); }
java
@Override protected void stopInner() throws VoldemortException { List<VoldemortException> exceptions = new ArrayList<VoldemortException>(); logger.info("Stopping services:" + getIdentityNode().getId()); /* Stop in reverse order */ exceptions.addAll(stopOnlineServices()); for(VoldemortService service: Utils.reversed(basicServices)) { try { service.stop(); } catch(VoldemortException e) { exceptions.add(e); logger.error(e); } } logger.info("All services stopped for Node:" + getIdentityNode().getId()); if(exceptions.size() > 0) throw exceptions.get(0); // release lock of jvm heap JNAUtils.tryMunlockall(); }
[ "@", "Override", "protected", "void", "stopInner", "(", ")", "throws", "VoldemortException", "{", "List", "<", "VoldemortException", ">", "exceptions", "=", "new", "ArrayList", "<", "VoldemortException", ">", "(", ")", ";", "logger", ".", "info", "(", "\"Stopp...
Attempt to shutdown the server. As much shutdown as possible will be completed, even if intermediate errors are encountered. @throws VoldemortException
[ "Attempt", "to", "shutdown", "the", "server", ".", "As", "much", "shutdown", "as", "possible", "will", "be", "completed", "even", "if", "intermediate", "errors", "are", "encountered", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/VoldemortServer.java#L502-L523
train
voldemort/voldemort
src/java/voldemort/store/readonly/chunk/ChunkedFileSet.java
ChunkedFileSet.getReplicaTypeForPartition
private int getReplicaTypeForPartition(int partitionId) { List<Integer> routingPartitionList = routingStrategy.getReplicatingPartitionList(partitionId); // Determine if we should host this partition, and if so, whether we are a primary, // secondary or n-ary replica for it int correctReplicaType = -1; for (int replica = 0; replica < routingPartitionList.size(); replica++) { if(nodePartitionIds.contains(routingPartitionList.get(replica))) { // This means the partitionId currently being iterated on should be hosted // by this node. Let's remember its replica type in order to make sure the // files we have are properly named. correctReplicaType = replica; break; } } return correctReplicaType; }
java
private int getReplicaTypeForPartition(int partitionId) { List<Integer> routingPartitionList = routingStrategy.getReplicatingPartitionList(partitionId); // Determine if we should host this partition, and if so, whether we are a primary, // secondary or n-ary replica for it int correctReplicaType = -1; for (int replica = 0; replica < routingPartitionList.size(); replica++) { if(nodePartitionIds.contains(routingPartitionList.get(replica))) { // This means the partitionId currently being iterated on should be hosted // by this node. Let's remember its replica type in order to make sure the // files we have are properly named. correctReplicaType = replica; break; } } return correctReplicaType; }
[ "private", "int", "getReplicaTypeForPartition", "(", "int", "partitionId", ")", "{", "List", "<", "Integer", ">", "routingPartitionList", "=", "routingStrategy", ".", "getReplicatingPartitionList", "(", "partitionId", ")", ";", "// Determine if we should host this partition...
Given a partition ID, determine which replica of this partition is hosted by the current node, if any. Note: This is an implementation detail of the READONLY_V2 naming scheme, and should not be used outside of that scope. @param partitionId for which we want to know the replica type @return the requested partition's replica type (which ranges from 0 to replication factor -1) if the partition is hosted on the current node, or -1 if the requested partition is not hosted on this node.
[ "Given", "a", "partition", "ID", "determine", "which", "replica", "of", "this", "partition", "is", "hosted", "by", "the", "current", "node", "if", "any", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/chunk/ChunkedFileSet.java#L261-L278
train
voldemort/voldemort
src/java/voldemort/store/readonly/chunk/ChunkedFileSet.java
ChunkedFileSet.renameReadOnlyV2Files
private void renameReadOnlyV2Files(int masterPartitionId, int correctReplicaType) { for (int replica = 0; replica < routingStrategy.getNumReplicas(); replica++) { if (replica != correctReplicaType) { int chunkId = 0; while (true) { String fileName = Integer.toString(masterPartitionId) + "_" + Integer.toString(replica) + "_" + Integer.toString(chunkId); File index = getIndexFile(fileName); File data = getDataFile(fileName); if(index.exists() && data.exists()) { // We found files with the "wrong" replica type, so let's rename them String correctFileName = Integer.toString(masterPartitionId) + "_" + Integer.toString(correctReplicaType) + "_" + Integer.toString(chunkId); File indexWithCorrectReplicaType = getIndexFile(correctFileName); File dataWithCorrectReplicaType = getDataFile(correctFileName); Utils.move(index, indexWithCorrectReplicaType); Utils.move(data, dataWithCorrectReplicaType); // Maybe change this to DEBUG? logger.info("Renamed files with wrong replica type: " + index.getAbsolutePath() + "|data -> " + indexWithCorrectReplicaType.getName() + "|data"); } else if(index.exists() ^ data.exists()) { throw new VoldemortException("One of the following does not exist: " + index.toString() + " or " + data.toString() + "."); } else { // The files don't exist, or we've gone over all available chunks, // so let's move on. break; } chunkId++; } } } }
java
private void renameReadOnlyV2Files(int masterPartitionId, int correctReplicaType) { for (int replica = 0; replica < routingStrategy.getNumReplicas(); replica++) { if (replica != correctReplicaType) { int chunkId = 0; while (true) { String fileName = Integer.toString(masterPartitionId) + "_" + Integer.toString(replica) + "_" + Integer.toString(chunkId); File index = getIndexFile(fileName); File data = getDataFile(fileName); if(index.exists() && data.exists()) { // We found files with the "wrong" replica type, so let's rename them String correctFileName = Integer.toString(masterPartitionId) + "_" + Integer.toString(correctReplicaType) + "_" + Integer.toString(chunkId); File indexWithCorrectReplicaType = getIndexFile(correctFileName); File dataWithCorrectReplicaType = getDataFile(correctFileName); Utils.move(index, indexWithCorrectReplicaType); Utils.move(data, dataWithCorrectReplicaType); // Maybe change this to DEBUG? logger.info("Renamed files with wrong replica type: " + index.getAbsolutePath() + "|data -> " + indexWithCorrectReplicaType.getName() + "|data"); } else if(index.exists() ^ data.exists()) { throw new VoldemortException("One of the following does not exist: " + index.toString() + " or " + data.toString() + "."); } else { // The files don't exist, or we've gone over all available chunks, // so let's move on. break; } chunkId++; } } } }
[ "private", "void", "renameReadOnlyV2Files", "(", "int", "masterPartitionId", ",", "int", "correctReplicaType", ")", "{", "for", "(", "int", "replica", "=", "0", ";", "replica", "<", "routingStrategy", ".", "getNumReplicas", "(", ")", ";", "replica", "++", ")",...
This function looks for files with the "wrong" replica type in their name, and if it finds any, renames them. Those files may have ended up on this server either because: - 1. We restored them from another server, where they were named according to another replica type. Or, - 2. The {@link voldemort.store.readonly.mr.azkaban.VoldemortBuildAndPushJob} and the {@link voldemort.store.readonly.fetcher.HdfsFetcher} are operating in 'build.primary.replicas.only' mode, so they only ever built and fetched replica 0 of any given file. Note: This is an implementation detail of the READONLY_V2 naming scheme, and should not be used outside of that scope. @param masterPartitionId partition ID of the "primary replica" @param correctReplicaType replica number which should be found on the current node for the provided masterPartitionId.
[ "This", "function", "looks", "for", "files", "with", "the", "wrong", "replica", "type", "in", "their", "name", "and", "if", "it", "finds", "any", "renames", "them", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/chunk/ChunkedFileSet.java#L299-L340
train
voldemort/voldemort
src/java/voldemort/store/readonly/chunk/ChunkedFileSet.java
ChunkedFileSet.keyToStorageFormat
public byte[] keyToStorageFormat(byte[] key) { switch(getReadOnlyStorageFormat()) { case READONLY_V0: case READONLY_V1: return ByteUtils.md5(key); case READONLY_V2: return ByteUtils.copy(ByteUtils.md5(key), 0, 2 * ByteUtils.SIZE_OF_INT); default: throw new VoldemortException("Unknown read-only storage format"); } }
java
public byte[] keyToStorageFormat(byte[] key) { switch(getReadOnlyStorageFormat()) { case READONLY_V0: case READONLY_V1: return ByteUtils.md5(key); case READONLY_V2: return ByteUtils.copy(ByteUtils.md5(key), 0, 2 * ByteUtils.SIZE_OF_INT); default: throw new VoldemortException("Unknown read-only storage format"); } }
[ "public", "byte", "[", "]", "keyToStorageFormat", "(", "byte", "[", "]", "key", ")", "{", "switch", "(", "getReadOnlyStorageFormat", "(", ")", ")", "{", "case", "READONLY_V0", ":", "case", "READONLY_V1", ":", "return", "ByteUtils", ".", "md5", "(", "key", ...
Converts the key to the format in which it is stored for searching @param key Byte array of the key @return The format stored in the index file
[ "Converts", "the", "key", "to", "the", "format", "in", "which", "it", "is", "stored", "for", "searching" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/chunk/ChunkedFileSet.java#L529-L540
train
voldemort/voldemort
src/java/voldemort/store/readonly/chunk/ChunkedFileSet.java
ChunkedFileSet.getChunkForKey
public int getChunkForKey(byte[] key) throws IllegalStateException { if(numChunks == 0) { throw new IllegalStateException("The ChunkedFileSet is closed."); } switch(storageFormat) { case READONLY_V0: { return ReadOnlyUtils.chunk(ByteUtils.md5(key), numChunks); } case READONLY_V1: { if(nodePartitionIds == null) { throw new IllegalStateException("nodePartitionIds is null."); } List<Integer> routingPartitionList = routingStrategy.getPartitionList(key); routingPartitionList.retainAll(nodePartitionIds); if(routingPartitionList.size() != 1) { throw new IllegalStateException("The key does not belong on this node."); } return chunkIdToChunkStart.get(routingPartitionList.get(0)) + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(routingPartitionList.get(0))); } case READONLY_V2: { List<Integer> routingPartitionList = routingStrategy.getPartitionList(key); Pair<Integer, Integer> bucket = null; for(int replicaType = 0; replicaType < routingPartitionList.size(); replicaType++) { if(nodePartitionIds == null) { throw new IllegalStateException("nodePartitionIds is null."); } if(nodePartitionIds.contains(routingPartitionList.get(replicaType))) { if(bucket == null) { bucket = Pair.create(routingPartitionList.get(0), replicaType); } else { throw new IllegalStateException("Found more than one replica for a given partition on the current node!"); } } } if(bucket == null) { throw new IllegalStateException("The key does not belong on this node."); } Integer chunkStart = chunkIdToChunkStart.get(bucket); if (chunkStart == null) { throw new IllegalStateException("chunkStart is null."); } return chunkStart + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(bucket)); } default: { throw new IllegalStateException("Unsupported storageFormat: " + storageFormat); } } }
java
public int getChunkForKey(byte[] key) throws IllegalStateException { if(numChunks == 0) { throw new IllegalStateException("The ChunkedFileSet is closed."); } switch(storageFormat) { case READONLY_V0: { return ReadOnlyUtils.chunk(ByteUtils.md5(key), numChunks); } case READONLY_V1: { if(nodePartitionIds == null) { throw new IllegalStateException("nodePartitionIds is null."); } List<Integer> routingPartitionList = routingStrategy.getPartitionList(key); routingPartitionList.retainAll(nodePartitionIds); if(routingPartitionList.size() != 1) { throw new IllegalStateException("The key does not belong on this node."); } return chunkIdToChunkStart.get(routingPartitionList.get(0)) + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(routingPartitionList.get(0))); } case READONLY_V2: { List<Integer> routingPartitionList = routingStrategy.getPartitionList(key); Pair<Integer, Integer> bucket = null; for(int replicaType = 0; replicaType < routingPartitionList.size(); replicaType++) { if(nodePartitionIds == null) { throw new IllegalStateException("nodePartitionIds is null."); } if(nodePartitionIds.contains(routingPartitionList.get(replicaType))) { if(bucket == null) { bucket = Pair.create(routingPartitionList.get(0), replicaType); } else { throw new IllegalStateException("Found more than one replica for a given partition on the current node!"); } } } if(bucket == null) { throw new IllegalStateException("The key does not belong on this node."); } Integer chunkStart = chunkIdToChunkStart.get(bucket); if (chunkStart == null) { throw new IllegalStateException("chunkStart is null."); } return chunkStart + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(bucket)); } default: { throw new IllegalStateException("Unsupported storageFormat: " + storageFormat); } } }
[ "public", "int", "getChunkForKey", "(", "byte", "[", "]", "key", ")", "throws", "IllegalStateException", "{", "if", "(", "numChunks", "==", "0", ")", "{", "throw", "new", "IllegalStateException", "(", "\"The ChunkedFileSet is closed.\"", ")", ";", "}", "switch",...
Given a particular key, first converts its to the storage format and then determines which chunk it belongs to @param key Byte array of keys @return Chunk id @throws IllegalStateException if unable to find the chunk id for the given key
[ "Given", "a", "particular", "key", "first", "converts", "its", "to", "the", "storage", "format", "and", "then", "determines", "which", "chunk", "it", "belongs", "to" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/chunk/ChunkedFileSet.java#L568-L626
train
voldemort/voldemort
src/java/voldemort/tools/ReadOnlyReplicationHelperCLI.java
ReadOnlyReplicationHelperCLI.parseAndCompare
private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) { List<String> sourceFileNames = new ArrayList<String>(); for(String fileName: fileNames) { String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL); if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) { sourceFileNames.add(fileName); } } return sourceFileNames; }
java
private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) { List<String> sourceFileNames = new ArrayList<String>(); for(String fileName: fileNames) { String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL); if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) { sourceFileNames.add(fileName); } } return sourceFileNames; }
[ "private", "static", "List", "<", "String", ">", "parseAndCompare", "(", "List", "<", "String", ">", "fileNames", ",", "int", "masterPartitionId", ")", "{", "List", "<", "String", ">", "sourceFileNames", "=", "new", "ArrayList", "<", "String", ">", "(", ")...
This method take a list of fileName of the type partitionId_Replica_Chunk and returns file names that match the regular expression masterPartitionId_
[ "This", "method", "take", "a", "list", "of", "fileName", "of", "the", "type", "partitionId_Replica_Chunk", "and", "returns", "file", "names", "that", "match", "the", "regular", "expression", "masterPartitionId_" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/ReadOnlyReplicationHelperCLI.java#L151-L160
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java
ReadOnlyStorageEngine.getChunkIdToNumChunks
@JmxGetter(name = "getChunkIdToNumChunks", description = "Returns a string representation of the map of chunk id to number of chunks") public String getChunkIdToNumChunks() { StringBuilder builder = new StringBuilder(); for(Entry<Object, Integer> entry: fileSet.getChunkIdToNumChunks().entrySet()) { builder.append(entry.getKey().toString() + " - " + entry.getValue().toString() + ", "); } return builder.toString(); }
java
@JmxGetter(name = "getChunkIdToNumChunks", description = "Returns a string representation of the map of chunk id to number of chunks") public String getChunkIdToNumChunks() { StringBuilder builder = new StringBuilder(); for(Entry<Object, Integer> entry: fileSet.getChunkIdToNumChunks().entrySet()) { builder.append(entry.getKey().toString() + " - " + entry.getValue().toString() + ", "); } return builder.toString(); }
[ "@", "JmxGetter", "(", "name", "=", "\"getChunkIdToNumChunks\"", ",", "description", "=", "\"Returns a string representation of the map of chunk id to number of chunks\"", ")", "public", "String", "getChunkIdToNumChunks", "(", ")", "{", "StringBuilder", "builder", "=", "new",...
Returns a string representation of map of chunk id to number of chunks @return String of map of chunk id to number of chunks
[ "Returns", "a", "string", "representation", "of", "map", "of", "chunk", "id", "to", "number", "of", "chunks" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java#L171-L178
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java
ReadOnlyStorageEngine.open
public void open(File versionDir) { /* acquire modification lock */ fileModificationLock.writeLock().lock(); try { /* check that the store is currently closed */ if(isOpen) throw new IllegalStateException("Attempt to open already open store."); // Find version directory from symbolic link or max version id if(versionDir == null) { versionDir = ReadOnlyUtils.getCurrentVersion(storeDir); if(versionDir == null) versionDir = new File(storeDir, "version-0"); } // Set the max version id long versionId = ReadOnlyUtils.getVersionId(versionDir); if(versionId == -1) { throw new VoldemortException("Unable to parse id from version directory " + versionDir.getAbsolutePath()); } Utils.mkdirs(versionDir); // Validate symbolic link, and create it if it doesn't already exist Utils.symlink(versionDir.getAbsolutePath(), storeDir.getAbsolutePath() + File.separator + "latest"); this.fileSet = new ChunkedFileSet(versionDir, routingStrategy, nodeId, maxValueBufferAllocationSize); storeVersionManager.syncInternalStateFromFileSystem(false); this.lastSwapped = System.currentTimeMillis(); this.isOpen = true; } catch(IOException e) { logger.error("Error in opening store", e); } finally { fileModificationLock.writeLock().unlock(); } }
java
public void open(File versionDir) { /* acquire modification lock */ fileModificationLock.writeLock().lock(); try { /* check that the store is currently closed */ if(isOpen) throw new IllegalStateException("Attempt to open already open store."); // Find version directory from symbolic link or max version id if(versionDir == null) { versionDir = ReadOnlyUtils.getCurrentVersion(storeDir); if(versionDir == null) versionDir = new File(storeDir, "version-0"); } // Set the max version id long versionId = ReadOnlyUtils.getVersionId(versionDir); if(versionId == -1) { throw new VoldemortException("Unable to parse id from version directory " + versionDir.getAbsolutePath()); } Utils.mkdirs(versionDir); // Validate symbolic link, and create it if it doesn't already exist Utils.symlink(versionDir.getAbsolutePath(), storeDir.getAbsolutePath() + File.separator + "latest"); this.fileSet = new ChunkedFileSet(versionDir, routingStrategy, nodeId, maxValueBufferAllocationSize); storeVersionManager.syncInternalStateFromFileSystem(false); this.lastSwapped = System.currentTimeMillis(); this.isOpen = true; } catch(IOException e) { logger.error("Error in opening store", e); } finally { fileModificationLock.writeLock().unlock(); } }
[ "public", "void", "open", "(", "File", "versionDir", ")", "{", "/* acquire modification lock */", "fileModificationLock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "/* check that the store is currently closed */", "if", "(", "isOpen", ")", ...
Open the store with the version directory specified. If null is specified we open the directory with the maximum version @param versionDir Version Directory to open. If null, we open the max versioned / latest directory
[ "Open", "the", "store", "with", "the", "version", "directory", "specified", ".", "If", "null", "is", "specified", "we", "open", "the", "directory", "with", "the", "maximum", "version" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java#L187-L222
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java
ReadOnlyStorageEngine.getLastSwapped
@JmxGetter(name = "lastSwapped", description = "Time in milliseconds since the store was swapped") public long getLastSwapped() { long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped; return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0; }
java
@JmxGetter(name = "lastSwapped", description = "Time in milliseconds since the store was swapped") public long getLastSwapped() { long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped; return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0; }
[ "@", "JmxGetter", "(", "name", "=", "\"lastSwapped\"", ",", "description", "=", "\"Time in milliseconds since the store was swapped\"", ")", "public", "long", "getLastSwapped", "(", ")", "{", "long", "timeSinceLastSwap", "=", "System", ".", "currentTimeMillis", "(", "...
Time since last time the store was swapped @return Time in milliseconds since the store was swapped
[ "Time", "since", "last", "time", "the", "store", "was", "swapped" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java#L277-L281
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java
ReadOnlyStorageEngine.close
@Override public void close() throws VoldemortException { logger.debug("Close called for read-only store."); this.fileModificationLock.writeLock().lock(); try { if(isOpen) { this.isOpen = false; fileSet.close(); } else { logger.debug("Attempt to close already closed store " + getName()); } } finally { this.fileModificationLock.writeLock().unlock(); } }
java
@Override public void close() throws VoldemortException { logger.debug("Close called for read-only store."); this.fileModificationLock.writeLock().lock(); try { if(isOpen) { this.isOpen = false; fileSet.close(); } else { logger.debug("Attempt to close already closed store " + getName()); } } finally { this.fileModificationLock.writeLock().unlock(); } }
[ "@", "Override", "public", "void", "close", "(", ")", "throws", "VoldemortException", "{", "logger", ".", "debug", "(", "\"Close called for read-only store.\"", ")", ";", "this", ".", "fileModificationLock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", "...
Close the store.
[ "Close", "the", "store", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java#L286-L301
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java
ReadOnlyStorageEngine.swapFiles
@JmxOperation(description = "swapFiles changes this store to use the new data directory") public void swapFiles(String newStoreDirectory) { logger.info("Swapping files for store '" + getName() + "' to " + newStoreDirectory); File newVersionDir = new File(newStoreDirectory); if(!newVersionDir.exists()) throw new VoldemortException("File " + newVersionDir.getAbsolutePath() + " does not exist."); if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir))) throw new VoldemortException("Invalid version folder name '" + newVersionDir + "'. Either parent directory is incorrect or format(version-n) is incorrect"); // retrieve previous version for (a) check if last write is winning // (b) if failure, rollback use File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir); if(previousVersionDir == null) throw new VoldemortException("Could not find any latest directory to swap with in store '" + getName() + "'"); long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir); long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir); if(newVersionId == -1 || previousVersionId == -1) throw new VoldemortException("Unable to parse folder names (" + newVersionDir.getName() + "," + previousVersionDir.getName() + ") since format(version-n) is incorrect"); // check if we're greater than latest since we want last write to win if(previousVersionId > newVersionId) { logger.info("No swap required since current latest version " + previousVersionId + " is greater than swap version " + newVersionId); deleteBackups(); return; } logger.info("Acquiring write lock on '" + getName() + "':"); fileModificationLock.writeLock().lock(); boolean success = false; try { close(); logger.info("Opening primary files for store '" + getName() + "' at " + newStoreDirectory); // open the latest store open(newVersionDir); success = true; } finally { try { // we failed to do the swap, attempt a rollback to last version if(!success) rollback(previousVersionDir); } finally { fileModificationLock.writeLock().unlock(); if(success) logger.info("Swap operation completed successfully on store " + getName() + ", releasing lock."); else logger.error("Swap operation failed."); } } // okay we have released the lock and the store is now open again, it is // safe to do a potentially slow delete if we have one too many backups deleteBackups(); }
java
@JmxOperation(description = "swapFiles changes this store to use the new data directory") public void swapFiles(String newStoreDirectory) { logger.info("Swapping files for store '" + getName() + "' to " + newStoreDirectory); File newVersionDir = new File(newStoreDirectory); if(!newVersionDir.exists()) throw new VoldemortException("File " + newVersionDir.getAbsolutePath() + " does not exist."); if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir))) throw new VoldemortException("Invalid version folder name '" + newVersionDir + "'. Either parent directory is incorrect or format(version-n) is incorrect"); // retrieve previous version for (a) check if last write is winning // (b) if failure, rollback use File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir); if(previousVersionDir == null) throw new VoldemortException("Could not find any latest directory to swap with in store '" + getName() + "'"); long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir); long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir); if(newVersionId == -1 || previousVersionId == -1) throw new VoldemortException("Unable to parse folder names (" + newVersionDir.getName() + "," + previousVersionDir.getName() + ") since format(version-n) is incorrect"); // check if we're greater than latest since we want last write to win if(previousVersionId > newVersionId) { logger.info("No swap required since current latest version " + previousVersionId + " is greater than swap version " + newVersionId); deleteBackups(); return; } logger.info("Acquiring write lock on '" + getName() + "':"); fileModificationLock.writeLock().lock(); boolean success = false; try { close(); logger.info("Opening primary files for store '" + getName() + "' at " + newStoreDirectory); // open the latest store open(newVersionDir); success = true; } finally { try { // we failed to do the swap, attempt a rollback to last version if(!success) rollback(previousVersionDir); } finally { fileModificationLock.writeLock().unlock(); if(success) logger.info("Swap operation completed successfully on store " + getName() + ", releasing lock."); else logger.error("Swap operation failed."); } } // okay we have released the lock and the store is now open again, it is // safe to do a potentially slow delete if we have one too many backups deleteBackups(); }
[ "@", "JmxOperation", "(", "description", "=", "\"swapFiles changes this store to use the new data directory\"", ")", "public", "void", "swapFiles", "(", "String", "newStoreDirectory", ")", "{", "logger", ".", "info", "(", "\"Swapping files for store '\"", "+", "getName", ...
Swap the current version folder for a new one @param newStoreDirectory The path to the new version directory
[ "Swap", "the", "current", "version", "folder", "for", "a", "new", "one" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java#L308-L374
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java
ReadOnlyStorageEngine.deleteBackups
private void deleteBackups() { File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId()); if(storeDirList != null && storeDirList.length > (numBackups + 1)) { // delete ALL old directories asynchronously File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList, 0, storeDirList.length - (numBackups + 1) - 1); if(extraBackups != null) { for(File backUpFile: extraBackups) { deleteAsync(backUpFile); } } } }
java
private void deleteBackups() { File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId()); if(storeDirList != null && storeDirList.length > (numBackups + 1)) { // delete ALL old directories asynchronously File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList, 0, storeDirList.length - (numBackups + 1) - 1); if(extraBackups != null) { for(File backUpFile: extraBackups) { deleteAsync(backUpFile); } } } }
[ "private", "void", "deleteBackups", "(", ")", "{", "File", "[", "]", "storeDirList", "=", "ReadOnlyUtils", ".", "getVersionDirs", "(", "storeDir", ",", "0L", ",", "getCurrentVersionId", "(", ")", ")", ";", "if", "(", "storeDirList", "!=", "null", "&&", "st...
Delete all backups asynchronously
[ "Delete", "all", "backups", "asynchronously" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java#L379-L393
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java
ReadOnlyStorageEngine.deleteAsync
private void deleteAsync(final File file) { new Thread(new Runnable() { @Override public void run() { try { try { logger.info("Waiting for " + deleteBackupMs + " milliseconds before deleting " + file.getAbsolutePath()); Thread.sleep(deleteBackupMs); } catch(InterruptedException e) { logger.warn("Did not sleep enough before deleting backups"); } logger.info("Deleting file " + file.getAbsolutePath()); Utils.rm(file); logger.info("Deleting of " + file.getAbsolutePath() + " completed successfully."); storeVersionManager.syncInternalStateFromFileSystem(true); } catch(Exception e) { logger.error("Exception during deleteAsync for path: " + file, e); } } }, "background-file-delete").start(); }
java
private void deleteAsync(final File file) { new Thread(new Runnable() { @Override public void run() { try { try { logger.info("Waiting for " + deleteBackupMs + " milliseconds before deleting " + file.getAbsolutePath()); Thread.sleep(deleteBackupMs); } catch(InterruptedException e) { logger.warn("Did not sleep enough before deleting backups"); } logger.info("Deleting file " + file.getAbsolutePath()); Utils.rm(file); logger.info("Deleting of " + file.getAbsolutePath() + " completed successfully."); storeVersionManager.syncInternalStateFromFileSystem(true); } catch(Exception e) { logger.error("Exception during deleteAsync for path: " + file, e); } } }, "background-file-delete").start(); }
[ "private", "void", "deleteAsync", "(", "final", "File", "file", ")", "{", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "try", "{", "logger", ".", "info", "(", "\"Waiting ...
Delete the given file in a separate thread @param file The file to delete
[ "Delete", "the", "given", "file", "in", "a", "separate", "thread" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java#L400-L423
train
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java
ReadOnlyStorageEngine.rollback
public void rollback(File rollbackToDir) { logger.info("Rolling back store '" + getName() + "'"); fileModificationLock.writeLock().lock(); try { if(rollbackToDir == null) throw new VoldemortException("Version directory specified to rollback is null"); if(!rollbackToDir.exists()) throw new VoldemortException("Version directory " + rollbackToDir.getAbsolutePath() + " specified to rollback does not exist"); long versionId = ReadOnlyUtils.getVersionId(rollbackToDir); if(versionId == -1) throw new VoldemortException("Cannot parse version id"); File[] backUpDirs = ReadOnlyUtils.getVersionDirs(storeDir, versionId, Long.MAX_VALUE); if(backUpDirs == null || backUpDirs.length <= 1) { logger.warn("No rollback performed since there are no back-up directories"); return; } backUpDirs = ReadOnlyUtils.findKthVersionedDir(backUpDirs, 0, backUpDirs.length - 1); if(isOpen) close(); // open the rollback directory open(rollbackToDir); // back-up all other directories DateFormat df = new SimpleDateFormat("MM-dd-yyyy"); for(int index = 1; index < backUpDirs.length; index++) { Utils.move(backUpDirs[index], new File(storeDir, backUpDirs[index].getName() + "." + df.format(new Date()) + ".bak")); } } finally { fileModificationLock.writeLock().unlock(); logger.info("Rollback operation completed on '" + getName() + "', releasing lock."); } }
java
public void rollback(File rollbackToDir) { logger.info("Rolling back store '" + getName() + "'"); fileModificationLock.writeLock().lock(); try { if(rollbackToDir == null) throw new VoldemortException("Version directory specified to rollback is null"); if(!rollbackToDir.exists()) throw new VoldemortException("Version directory " + rollbackToDir.getAbsolutePath() + " specified to rollback does not exist"); long versionId = ReadOnlyUtils.getVersionId(rollbackToDir); if(versionId == -1) throw new VoldemortException("Cannot parse version id"); File[] backUpDirs = ReadOnlyUtils.getVersionDirs(storeDir, versionId, Long.MAX_VALUE); if(backUpDirs == null || backUpDirs.length <= 1) { logger.warn("No rollback performed since there are no back-up directories"); return; } backUpDirs = ReadOnlyUtils.findKthVersionedDir(backUpDirs, 0, backUpDirs.length - 1); if(isOpen) close(); // open the rollback directory open(rollbackToDir); // back-up all other directories DateFormat df = new SimpleDateFormat("MM-dd-yyyy"); for(int index = 1; index < backUpDirs.length; index++) { Utils.move(backUpDirs[index], new File(storeDir, backUpDirs[index].getName() + "." + df.format(new Date()) + ".bak")); } } finally { fileModificationLock.writeLock().unlock(); logger.info("Rollback operation completed on '" + getName() + "', releasing lock."); } }
[ "public", "void", "rollback", "(", "File", "rollbackToDir", ")", "{", "logger", ".", "info", "(", "\"Rolling back store '\"", "+", "getName", "(", ")", "+", "\"'\"", ")", ";", "fileModificationLock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", ...
Rollback to the specified push version @param rollbackToDir The version directory to rollback to
[ "Rollback", "to", "the", "specified", "push", "version" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyStorageEngine.java#L441-L480
train
voldemort/voldemort
src/java/voldemort/rest/RestRequestValidator.java
RestRequestValidator.hasTimeOutHeader
protected boolean hasTimeOutHeader() { boolean result = false; String timeoutValStr = this.request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS); if(timeoutValStr != null) { try { this.parsedTimeoutInMs = Long.parseLong(timeoutValStr); if(this.parsedTimeoutInMs < 0) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Time out cannot be negative "); } else { result = true; } } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect timeout parameter. Cannot parse this to long: " + timeoutValStr, nfe); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect timeout parameter. Cannot parse this to long: " + timeoutValStr); } } else { logger.error("Error when validating request. Missing timeout parameter."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing timeout parameter."); } return result; }
java
protected boolean hasTimeOutHeader() { boolean result = false; String timeoutValStr = this.request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS); if(timeoutValStr != null) { try { this.parsedTimeoutInMs = Long.parseLong(timeoutValStr); if(this.parsedTimeoutInMs < 0) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Time out cannot be negative "); } else { result = true; } } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect timeout parameter. Cannot parse this to long: " + timeoutValStr, nfe); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect timeout parameter. Cannot parse this to long: " + timeoutValStr); } } else { logger.error("Error when validating request. Missing timeout parameter."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing timeout parameter."); } return result; }
[ "protected", "boolean", "hasTimeOutHeader", "(", ")", "{", "boolean", "result", "=", "false", ";", "String", "timeoutValStr", "=", "this", ".", "request", ".", "getHeader", "(", "RestMessageHeaders", ".", "X_VOLD_REQUEST_TIMEOUT_MS", ")", ";", "if", "(", "timeou...
Retrieve and validate the timeout value from the REST request. "X_VOLD_REQUEST_TIMEOUT_MS" is the timeout header. @return true if present, false if missing
[ "Retrieve", "and", "validate", "the", "timeout", "value", "from", "the", "REST", "request", ".", "X_VOLD_REQUEST_TIMEOUT_MS", "is", "the", "timeout", "header", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestRequestValidator.java#L67-L98
train
voldemort/voldemort
src/java/voldemort/rest/RestRequestValidator.java
RestRequestValidator.parseRoutingCodeHeader
protected void parseRoutingCodeHeader() { String rtCode = this.request.getHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE); if(rtCode != null) { try { int routingTypeCode = Integer.parseInt(rtCode); this.parsedRoutingType = RequestRoutingType.getRequestRoutingType(routingTypeCode); } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect routing type parameter. Cannot parse this to long: " + rtCode, nfe); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect routing type parameter. Cannot parse this to long: " + rtCode); } catch(VoldemortException ve) { logger.error("Exception when validating request. Incorrect routing type code: " + rtCode, ve); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect routing type code: " + rtCode); } } }
java
protected void parseRoutingCodeHeader() { String rtCode = this.request.getHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE); if(rtCode != null) { try { int routingTypeCode = Integer.parseInt(rtCode); this.parsedRoutingType = RequestRoutingType.getRequestRoutingType(routingTypeCode); } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect routing type parameter. Cannot parse this to long: " + rtCode, nfe); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect routing type parameter. Cannot parse this to long: " + rtCode); } catch(VoldemortException ve) { logger.error("Exception when validating request. Incorrect routing type code: " + rtCode, ve); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect routing type code: " + rtCode); } } }
[ "protected", "void", "parseRoutingCodeHeader", "(", ")", "{", "String", "rtCode", "=", "this", ".", "request", ".", "getHeader", "(", "RestMessageHeaders", ".", "X_VOLD_ROUTING_TYPE_CODE", ")", ";", "if", "(", "rtCode", "!=", "null", ")", "{", "try", "{", "i...
Retrieve the routing type value from the REST request. "X_VOLD_ROUTING_TYPE_CODE" is the routing type header. By default, the routing code is set to NORMAL TODO REST-Server 1. Change the header name to a better name. 2. Assumes that integer is passed in the header
[ "Retrieve", "the", "routing", "type", "value", "from", "the", "REST", "request", ".", "X_VOLD_ROUTING_TYPE_CODE", "is", "the", "routing", "type", "header", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestRequestValidator.java#L110-L133
train
voldemort/voldemort
src/java/voldemort/rest/RestRequestValidator.java
RestRequestValidator.hasTimeStampHeader
protected boolean hasTimeStampHeader() { String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS); boolean result = false; if(originTime != null) { try { // TODO: remove the originTime field from request header, // because coordinator should not accept the request origin time // from the client.. In this commit, we only changed // "this.parsedRequestOriginTimeInMs" from // "Long.parseLong(originTime)" to current system time, // The reason that we did not remove the field from request // header right now, is because this commit is a quick fix for // internal performance test to be available as soon as // possible. this.parsedRequestOriginTimeInMs = System.currentTimeMillis(); if(this.parsedRequestOriginTimeInMs < 0) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Origin time cannot be negative "); } else { result = true; } } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect origin time parameter. Cannot parse this to long: " + originTime, nfe); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect origin time parameter. Cannot parse this to long: " + originTime); } } else { logger.error("Error when validating request. Missing origin time parameter."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing origin time parameter."); } return result; }
java
protected boolean hasTimeStampHeader() { String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS); boolean result = false; if(originTime != null) { try { // TODO: remove the originTime field from request header, // because coordinator should not accept the request origin time // from the client.. In this commit, we only changed // "this.parsedRequestOriginTimeInMs" from // "Long.parseLong(originTime)" to current system time, // The reason that we did not remove the field from request // header right now, is because this commit is a quick fix for // internal performance test to be available as soon as // possible. this.parsedRequestOriginTimeInMs = System.currentTimeMillis(); if(this.parsedRequestOriginTimeInMs < 0) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Origin time cannot be negative "); } else { result = true; } } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect origin time parameter. Cannot parse this to long: " + originTime, nfe); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect origin time parameter. Cannot parse this to long: " + originTime); } } else { logger.error("Error when validating request. Missing origin time parameter."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing origin time parameter."); } return result; }
[ "protected", "boolean", "hasTimeStampHeader", "(", ")", "{", "String", "originTime", "=", "request", ".", "getHeader", "(", "RestMessageHeaders", ".", "X_VOLD_REQUEST_ORIGIN_TIME_MS", ")", ";", "boolean", "result", "=", "false", ";", "if", "(", "originTime", "!=",...
Retrieve and validate the timestamp value from the REST request. "X_VOLD_REQUEST_ORIGIN_TIME_MS" is timestamp header TODO REST-Server 1. Change Time stamp header to a better name. @return true if present, false if missing
[ "Retrieve", "and", "validate", "the", "timestamp", "value", "from", "the", "REST", "request", ".", "X_VOLD_REQUEST_ORIGIN_TIME_MS", "is", "timestamp", "header" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestRequestValidator.java#L143-L183
train
voldemort/voldemort
src/java/voldemort/rest/RestRequestValidator.java
RestRequestValidator.hasVectorClock
protected boolean hasVectorClock(boolean isVectorClockOptional) { boolean result = false; String vectorClockHeader = this.request.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK); if(vectorClockHeader != null) { ObjectMapper mapper = new ObjectMapper(); try { VectorClockWrapper vcWrapper = mapper.readValue(vectorClockHeader, VectorClockWrapper.class); this.parsedVectorClock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp()); result = true; } catch(Exception e) { logger.error("Exception while parsing and constructing vector clock", e); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Invalid Vector Clock"); } } else if(!isVectorClockOptional) { logger.error("Error when validating request. Missing Vector Clock"); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing Vector Clock"); } else { result = true; } return result; }
java
protected boolean hasVectorClock(boolean isVectorClockOptional) { boolean result = false; String vectorClockHeader = this.request.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK); if(vectorClockHeader != null) { ObjectMapper mapper = new ObjectMapper(); try { VectorClockWrapper vcWrapper = mapper.readValue(vectorClockHeader, VectorClockWrapper.class); this.parsedVectorClock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp()); result = true; } catch(Exception e) { logger.error("Exception while parsing and constructing vector clock", e); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Invalid Vector Clock"); } } else if(!isVectorClockOptional) { logger.error("Error when validating request. Missing Vector Clock"); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing Vector Clock"); } else { result = true; } return result; }
[ "protected", "boolean", "hasVectorClock", "(", "boolean", "isVectorClockOptional", ")", "{", "boolean", "result", "=", "false", ";", "String", "vectorClockHeader", "=", "this", ".", "request", ".", "getHeader", "(", "RestMessageHeaders", ".", "X_VOLD_VECTOR_CLOCK", ...
Retrieve and validate vector clock value from the REST request. "X_VOLD_VECTOR_CLOCK" is the vector clock header. @return true if present, false if missing
[ "Retrieve", "and", "validate", "vector", "clock", "value", "from", "the", "REST", "request", ".", "X_VOLD_VECTOR_CLOCK", "is", "the", "vector", "clock", "header", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestRequestValidator.java#L191-L219
train
voldemort/voldemort
src/java/voldemort/rest/RestRequestValidator.java
RestRequestValidator.hasKey
protected boolean hasKey() { boolean result = false; String requestURI = this.request.getUri(); parseKeys(requestURI); if(this.parsedKeys != null) { result = true; } else { logger.error("Error when validating request. No key specified."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Error: No key specified !"); } return result; }
java
protected boolean hasKey() { boolean result = false; String requestURI = this.request.getUri(); parseKeys(requestURI); if(this.parsedKeys != null) { result = true; } else { logger.error("Error when validating request. No key specified."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Error: No key specified !"); } return result; }
[ "protected", "boolean", "hasKey", "(", ")", "{", "boolean", "result", "=", "false", ";", "String", "requestURI", "=", "this", ".", "request", ".", "getUri", "(", ")", ";", "parseKeys", "(", "requestURI", ")", ";", "if", "(", "this", ".", "parsedKeys", ...
Retrieve and validate the key from the REST request. @return true if present, false if missing
[ "Retrieve", "and", "validate", "the", "key", "from", "the", "REST", "request", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestRequestValidator.java#L226-L240
train
voldemort/voldemort
src/java/voldemort/rest/RestRequestValidator.java
RestRequestValidator.isStoreValid
protected boolean isStoreValid() { boolean result = false; String requestURI = this.request.getUri(); this.storeName = parseStoreName(requestURI); if(storeName != null) { result = true; } else { logger.error("Error when validating request. Missing store name."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing store name. Critical error."); } return result; }
java
protected boolean isStoreValid() { boolean result = false; String requestURI = this.request.getUri(); this.storeName = parseStoreName(requestURI); if(storeName != null) { result = true; } else { logger.error("Error when validating request. Missing store name."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing store name. Critical error."); } return result; }
[ "protected", "boolean", "isStoreValid", "(", ")", "{", "boolean", "result", "=", "false", ";", "String", "requestURI", "=", "this", ".", "request", ".", "getUri", "(", ")", ";", "this", ".", "storeName", "=", "parseStoreName", "(", "requestURI", ")", ";", ...
Retrieve and validate store name from the REST request. @return true if valid, false otherwise
[ "Retrieve", "and", "validate", "store", "name", "from", "the", "REST", "request", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestRequestValidator.java#L275-L288
train
voldemort/voldemort
src/java/voldemort/rest/RestRequestValidator.java
RestRequestValidator.debugLog
protected void debugLog(String operationType, Long receivedTimeInMs) { long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs); int numVectorClockEntries = (this.parsedVectorClock == null ? 0 : this.parsedVectorClock.getVersionMap() .size()); logger.debug("Received a new request. Operation type: " + operationType + " , Key(s): " + keysHexString(this.parsedKeys) + " , Store: " + this.storeName + " , Origin time (in ms): " + (this.parsedRequestOriginTimeInMs) + " , Request received at time(in ms): " + receivedTimeInMs + " , Num vector clock entries: " + numVectorClockEntries + " , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): " + durationInMs); }
java
protected void debugLog(String operationType, Long receivedTimeInMs) { long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs); int numVectorClockEntries = (this.parsedVectorClock == null ? 0 : this.parsedVectorClock.getVersionMap() .size()); logger.debug("Received a new request. Operation type: " + operationType + " , Key(s): " + keysHexString(this.parsedKeys) + " , Store: " + this.storeName + " , Origin time (in ms): " + (this.parsedRequestOriginTimeInMs) + " , Request received at time(in ms): " + receivedTimeInMs + " , Num vector clock entries: " + numVectorClockEntries + " , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): " + durationInMs); }
[ "protected", "void", "debugLog", "(", "String", "operationType", ",", "Long", "receivedTimeInMs", ")", "{", "long", "durationInMs", "=", "receivedTimeInMs", "-", "(", "this", ".", "parsedRequestOriginTimeInMs", ")", ";", "int", "numVectorClockEntries", "=", "(", "...
Prints a debug log message that details the time taken for the Http request to be parsed by the coordinator @param operationType @param receivedTimeInMs
[ "Prints", "a", "debug", "log", "message", "that", "details", "the", "time", "taken", "for", "the", "Http", "request", "to", "be", "parsed", "by", "the", "coordinator" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestRequestValidator.java#L321-L334
train
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/fetcher/HdfsFetcher.java
HdfsFetcher.fetch
@Deprecated @Override public File fetch(String source, String dest, long diskQuotaSizeInKB) throws Exception { return fetchFromSource(source, dest, null, null, -1, diskQuotaSizeInKB, null); }
java
@Deprecated @Override public File fetch(String source, String dest, long diskQuotaSizeInKB) throws Exception { return fetchFromSource(source, dest, null, null, -1, diskQuotaSizeInKB, null); }
[ "@", "Deprecated", "@", "Override", "public", "File", "fetch", "(", "String", "source", ",", "String", "dest", ",", "long", "diskQuotaSizeInKB", ")", "throws", "Exception", "{", "return", "fetchFromSource", "(", "source", ",", "dest", ",", "null", ",", "null...
Used for unit tests only. FIXME: Refactor test code with dependency injection or scope restrictions so this function is not public. @deprecated Do not use for production code, use {@link #fetch(String, String, voldemort.server.protocol.admin.AsyncOperationStatus, String, long, voldemort.store.metadata.MetadataStore, Long diskQuotaSizeInKB)} instead.
[ "Used", "for", "unit", "tests", "only", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/fetcher/HdfsFetcher.java#L178-L182
train
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/fetcher/HdfsFetcher.java
HdfsFetcher.main
public static void main(String[] args) throws Exception { if(args.length < 1) Utils.croak("USAGE: java " + HdfsFetcher.class.getName() + " url [keytab-location kerberos-username hadoop-config-path [destDir]]"); String url = args[0]; VoldemortConfig config = new VoldemortConfig(-1, ""); HdfsFetcher fetcher = new HdfsFetcher(config); String destDir = null; Long diskQuotaSizeInKB; if(args.length >= 4) { fetcher.voldemortConfig.setReadOnlyKeytabPath(args[1]); fetcher.voldemortConfig.setReadOnlyKerberosUser(args[2]); fetcher.voldemortConfig.setHadoopConfigPath(args[3]); } if(args.length >= 5) destDir = args[4]; if(args.length >= 6) diskQuotaSizeInKB = Long.parseLong(args[5]); else diskQuotaSizeInKB = null; // for testing we want to be able to download a single file allowFetchingOfSingleFile = true; FileSystem fs = HadoopUtils.getHadoopFileSystem(fetcher.voldemortConfig, url); Path p = new Path(url); FileStatus status = fs.listStatus(p)[0]; long size = status.getLen(); long start = System.currentTimeMillis(); if(destDir == null) destDir = System.getProperty("java.io.tmpdir") + File.separator + start; File location = fetcher.fetch(url, destDir, null, null, -1, null, diskQuotaSizeInKB); double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start); NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); System.out.println("Fetch to " + location + " completed: " + nf.format(rate / (1024.0 * 1024.0)) + " MB/sec."); fs.close(); }
java
public static void main(String[] args) throws Exception { if(args.length < 1) Utils.croak("USAGE: java " + HdfsFetcher.class.getName() + " url [keytab-location kerberos-username hadoop-config-path [destDir]]"); String url = args[0]; VoldemortConfig config = new VoldemortConfig(-1, ""); HdfsFetcher fetcher = new HdfsFetcher(config); String destDir = null; Long diskQuotaSizeInKB; if(args.length >= 4) { fetcher.voldemortConfig.setReadOnlyKeytabPath(args[1]); fetcher.voldemortConfig.setReadOnlyKerberosUser(args[2]); fetcher.voldemortConfig.setHadoopConfigPath(args[3]); } if(args.length >= 5) destDir = args[4]; if(args.length >= 6) diskQuotaSizeInKB = Long.parseLong(args[5]); else diskQuotaSizeInKB = null; // for testing we want to be able to download a single file allowFetchingOfSingleFile = true; FileSystem fs = HadoopUtils.getHadoopFileSystem(fetcher.voldemortConfig, url); Path p = new Path(url); FileStatus status = fs.listStatus(p)[0]; long size = status.getLen(); long start = System.currentTimeMillis(); if(destDir == null) destDir = System.getProperty("java.io.tmpdir") + File.separator + start; File location = fetcher.fetch(url, destDir, null, null, -1, null, diskQuotaSizeInKB); double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start); NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); System.out.println("Fetch to " + location + " completed: " + nf.format(rate / (1024.0 * 1024.0)) + " MB/sec."); fs.close(); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "if", "(", "args", ".", "length", "<", "1", ")", "Utils", ".", "croak", "(", "\"USAGE: java \"", "+", "HdfsFetcher", ".", "class", ".", "getName", "("...
Main method for testing fetching
[ "Main", "method", "for", "testing", "fetching" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/fetcher/HdfsFetcher.java#L487-L532
train
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceTaskInfo.java
RebalanceTaskInfo.getPartitionStoreMoves
public synchronized int getPartitionStoreMoves() { int count = 0; for (List<Integer> entry : storeToPartitionIds.values()) count += entry.size(); return count; }
java
public synchronized int getPartitionStoreMoves() { int count = 0; for (List<Integer> entry : storeToPartitionIds.values()) count += entry.size(); return count; }
[ "public", "synchronized", "int", "getPartitionStoreMoves", "(", ")", "{", "int", "count", "=", "0", ";", "for", "(", "List", "<", "Integer", ">", "entry", ":", "storeToPartitionIds", ".", "values", "(", ")", ")", "count", "+=", "entry", ".", "size", "(",...
Total count of partition-stores moved in this task. @return number of partition stores moved in this task.
[ "Total", "count", "of", "partition", "-", "stores", "moved", "in", "this", "task", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceTaskInfo.java#L156-L161
train
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceTaskInfo.java
RebalanceTaskInfo.getPartitionStoreCount
public synchronized int getPartitionStoreCount() { int count = 0; for (String store : storeToPartitionIds.keySet()) { count += storeToPartitionIds.get(store).size(); } return count; }
java
public synchronized int getPartitionStoreCount() { int count = 0; for (String store : storeToPartitionIds.keySet()) { count += storeToPartitionIds.get(store).size(); } return count; }
[ "public", "synchronized", "int", "getPartitionStoreCount", "(", ")", "{", "int", "count", "=", "0", ";", "for", "(", "String", "store", ":", "storeToPartitionIds", ".", "keySet", "(", ")", ")", "{", "count", "+=", "storeToPartitionIds", ".", "get", "(", "s...
Returns the total count of partitions across all stores. @return returns the total count of partitions across all stores.
[ "Returns", "the", "total", "count", "of", "partitions", "across", "all", "stores", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceTaskInfo.java#L196-L202
train
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceTaskInfo.java
RebalanceTaskInfo.taskListToString
public static String taskListToString(List<RebalanceTaskInfo> infos) { StringBuffer sb = new StringBuffer(); for (RebalanceTaskInfo info : infos) { sb.append("\t").append(info.getDonorId()).append(" -> ").append(info.getStealerId()).append(" : ["); for (String storeName : info.getPartitionStores()) { sb.append("{").append(storeName).append(" : ").append(info.getPartitionIds(storeName)).append("}"); } sb.append("]").append(Utils.NEWLINE); } return sb.toString(); }
java
public static String taskListToString(List<RebalanceTaskInfo> infos) { StringBuffer sb = new StringBuffer(); for (RebalanceTaskInfo info : infos) { sb.append("\t").append(info.getDonorId()).append(" -> ").append(info.getStealerId()).append(" : ["); for (String storeName : info.getPartitionStores()) { sb.append("{").append(storeName).append(" : ").append(info.getPartitionIds(storeName)).append("}"); } sb.append("]").append(Utils.NEWLINE); } return sb.toString(); }
[ "public", "static", "String", "taskListToString", "(", "List", "<", "RebalanceTaskInfo", ">", "infos", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "for", "(", "RebalanceTaskInfo", "info", ":", "infos", ")", "{", "sb", ".", "a...
Pretty prints a task list of rebalancing tasks. @param infos list of rebalancing tasks (RebalancePartitionsInfo) @return pretty-printed string
[ "Pretty", "prints", "a", "task", "list", "of", "rebalancing", "tasks", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceTaskInfo.java#L231-L241
train
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/AvroStoreBuilderMapper.java
AvroStoreBuilderMapper.map
@Override public void map(GenericData.Record record, AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector, Reporter reporter) throws IOException { byte[] keyBytes = null; byte[] valBytes = null; Object keyRecord = null; Object valRecord = null; try { keyRecord = record.get(keyField); valRecord = record.get(valField); keyBytes = keySerializer.toBytes(keyRecord); valBytes = valueSerializer.toBytes(valRecord); this.collectorWrapper.setCollector(collector); this.mapper.map(keyBytes, valBytes, this.collectorWrapper); recordCounter++; } catch (OutOfMemoryError oom) { logger.error(oomErrorMessage(reporter)); if (keyBytes == null) { logger.error("keyRecord caused OOM!"); } else { logger.error("keyRecord: " + keyRecord); logger.error("valRecord: " + (valBytes == null ? "caused OOM" : valRecord)); } throw new VoldemortException(oomErrorMessage(reporter), oom); } }
java
@Override public void map(GenericData.Record record, AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector, Reporter reporter) throws IOException { byte[] keyBytes = null; byte[] valBytes = null; Object keyRecord = null; Object valRecord = null; try { keyRecord = record.get(keyField); valRecord = record.get(valField); keyBytes = keySerializer.toBytes(keyRecord); valBytes = valueSerializer.toBytes(valRecord); this.collectorWrapper.setCollector(collector); this.mapper.map(keyBytes, valBytes, this.collectorWrapper); recordCounter++; } catch (OutOfMemoryError oom) { logger.error(oomErrorMessage(reporter)); if (keyBytes == null) { logger.error("keyRecord caused OOM!"); } else { logger.error("keyRecord: " + keyRecord); logger.error("valRecord: " + (valBytes == null ? "caused OOM" : valRecord)); } throw new VoldemortException(oomErrorMessage(reporter), oom); } }
[ "@", "Override", "public", "void", "map", "(", "GenericData", ".", "Record", "record", ",", "AvroCollector", "<", "Pair", "<", "ByteBuffer", ",", "ByteBuffer", ">", ">", "collector", ",", "Reporter", "reporter", ")", "throws", "IOException", "{", "byte", "["...
Create the voldemort key and value from the input Avro record by extracting the key and value and map it out for each of the responsible voldemort nodes The output value is the node_id & partition_id of the responsible node followed by serialized value
[ "Create", "the", "voldemort", "key", "and", "value", "from", "the", "input", "Avro", "record", "by", "extracting", "the", "key", "and", "value", "and", "map", "it", "out", "for", "each", "of", "the", "responsible", "voldemort", "nodes" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/AvroStoreBuilderMapper.java#L113-L142
train
voldemort/voldemort
src/java/voldemort/store/readonly/io/jna/mman.java
mman.mmap
public static Pointer mmap(long len, int prot, int flags, int fildes, long off) throws IOException { // we don't really have a need to change the recommended pointer. Pointer addr = new Pointer(0); Pointer result = Delegate.mmap(addr, new NativeLong(len), prot, flags, fildes, new NativeLong(off)); if(Pointer.nativeValue(result) == -1) { if(logger.isDebugEnabled()) logger.debug(errno.strerror()); throw new IOException("mmap failed: " + errno.strerror()); } return result; }
java
public static Pointer mmap(long len, int prot, int flags, int fildes, long off) throws IOException { // we don't really have a need to change the recommended pointer. Pointer addr = new Pointer(0); Pointer result = Delegate.mmap(addr, new NativeLong(len), prot, flags, fildes, new NativeLong(off)); if(Pointer.nativeValue(result) == -1) { if(logger.isDebugEnabled()) logger.debug(errno.strerror()); throw new IOException("mmap failed: " + errno.strerror()); } return result; }
[ "public", "static", "Pointer", "mmap", "(", "long", "len", ",", "int", "prot", ",", "int", "flags", ",", "int", "fildes", ",", "long", "off", ")", "throws", "IOException", "{", "// we don't really have a need to change the recommended pointer.", "Pointer", "addr", ...
Map the given region of the given file descriptor into memory. Returns a Pointer to the newly mapped memory throws an IOException on error.
[ "Map", "the", "given", "region", "of", "the", "given", "file", "descriptor", "into", "memory", ".", "Returns", "a", "Pointer", "to", "the", "newly", "mapped", "memory", "throws", "an", "IOException", "on", "error", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/io/jna/mman.java#L36-L57
train
voldemort/voldemort
src/java/voldemort/store/readonly/io/jna/mman.java
mman.mlock
public static void mlock(Pointer addr, long len) { int res = Delegate.mlock(addr, new NativeLong(len)); if(res != 0) { if(logger.isDebugEnabled()) { logger.debug("Mlock failed probably because of insufficient privileges, errno:" + errno.strerror() + ", return value:" + res); } } else { if(logger.isDebugEnabled()) logger.debug("Mlock successfull"); } }
java
public static void mlock(Pointer addr, long len) { int res = Delegate.mlock(addr, new NativeLong(len)); if(res != 0) { if(logger.isDebugEnabled()) { logger.debug("Mlock failed probably because of insufficient privileges, errno:" + errno.strerror() + ", return value:" + res); } } else { if(logger.isDebugEnabled()) logger.debug("Mlock successfull"); } }
[ "public", "static", "void", "mlock", "(", "Pointer", "addr", ",", "long", "len", ")", "{", "int", "res", "=", "Delegate", ".", "mlock", "(", "addr", ",", "new", "NativeLong", "(", "len", ")", ")", ";", "if", "(", "res", "!=", "0", ")", "{", "if",...
Lock the given region. Does not report failures.
[ "Lock", "the", "given", "region", ".", "Does", "not", "report", "failures", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/io/jna/mman.java#L80-L94
train
voldemort/voldemort
src/java/voldemort/store/readonly/io/jna/mman.java
mman.munlock
public static void munlock(Pointer addr, long len) { if(Delegate.munlock(addr, new NativeLong(len)) != 0) { if(logger.isDebugEnabled()) logger.debug("munlocking failed with errno:" + errno.strerror()); } else { if(logger.isDebugEnabled()) logger.debug("munlocking region"); } }
java
public static void munlock(Pointer addr, long len) { if(Delegate.munlock(addr, new NativeLong(len)) != 0) { if(logger.isDebugEnabled()) logger.debug("munlocking failed with errno:" + errno.strerror()); } else { if(logger.isDebugEnabled()) logger.debug("munlocking region"); } }
[ "public", "static", "void", "munlock", "(", "Pointer", "addr", ",", "long", "len", ")", "{", "if", "(", "Delegate", ".", "munlock", "(", "addr", ",", "new", "NativeLong", "(", "len", ")", ")", "!=", "0", ")", "{", "if", "(", "logger", ".", "isDebug...
Unlock the given region. Does not report failures.
[ "Unlock", "the", "given", "region", ".", "Does", "not", "report", "failures", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/io/jna/mman.java#L99-L108
train
voldemort/voldemort
src/java/voldemort/serialization/json/JsonTypeDefinition.java
JsonTypeDefinition.projectionType
public JsonTypeDefinition projectionType(String... properties) { if(this.getType() instanceof Map<?, ?>) { Map<?, ?> type = (Map<?, ?>) getType(); Arrays.sort(properties); Map<String, Object> newType = new LinkedHashMap<String, Object>(); for(String prop: properties) newType.put(prop, type.get(prop)); return new JsonTypeDefinition(newType); } else { throw new IllegalArgumentException("Cannot take the projection of a type that is not a Map."); } }
java
public JsonTypeDefinition projectionType(String... properties) { if(this.getType() instanceof Map<?, ?>) { Map<?, ?> type = (Map<?, ?>) getType(); Arrays.sort(properties); Map<String, Object> newType = new LinkedHashMap<String, Object>(); for(String prop: properties) newType.put(prop, type.get(prop)); return new JsonTypeDefinition(newType); } else { throw new IllegalArgumentException("Cannot take the projection of a type that is not a Map."); } }
[ "public", "JsonTypeDefinition", "projectionType", "(", "String", "...", "properties", ")", "{", "if", "(", "this", ".", "getType", "(", ")", "instanceof", "Map", "<", "?", ",", "?", ">", ")", "{", "Map", "<", "?", ",", "?", ">", "type", "=", "(", "...
Get the type created by selecting only a subset of properties from this type. The type must be a map for this to work @param properties The properties to select @return The new type definition
[ "Get", "the", "type", "created", "by", "selecting", "only", "a", "subset", "of", "properties", "from", "this", "type", ".", "The", "type", "must", "be", "a", "map", "for", "this", "to", "work" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/serialization/json/JsonTypeDefinition.java#L96-L107
train
voldemort/voldemort
src/java/voldemort/server/protocol/admin/BufferedUpdatePartitionEntriesStreamRequestHandler.java
BufferedUpdatePartitionEntriesStreamRequestHandler.writeBufferedValsToStorage
private void writeBufferedValsToStorage() { List<Versioned<byte[]>> obsoleteVals = storageEngine.multiVersionPut(currBufferedKey, currBufferedVals); // log Obsolete versions in debug mode if(logger.isDebugEnabled() && obsoleteVals.size() > 0) { logger.debug("updateEntries (Streaming multi-version-put) rejected these versions as obsolete : " + StoreUtils.getVersions(obsoleteVals) + " for key " + currBufferedKey); } currBufferedVals = new ArrayList<Versioned<byte[]>>(VALS_BUFFER_EXPECTED_SIZE); }
java
private void writeBufferedValsToStorage() { List<Versioned<byte[]>> obsoleteVals = storageEngine.multiVersionPut(currBufferedKey, currBufferedVals); // log Obsolete versions in debug mode if(logger.isDebugEnabled() && obsoleteVals.size() > 0) { logger.debug("updateEntries (Streaming multi-version-put) rejected these versions as obsolete : " + StoreUtils.getVersions(obsoleteVals) + " for key " + currBufferedKey); } currBufferedVals = new ArrayList<Versioned<byte[]>>(VALS_BUFFER_EXPECTED_SIZE); }
[ "private", "void", "writeBufferedValsToStorage", "(", ")", "{", "List", "<", "Versioned", "<", "byte", "[", "]", ">", ">", "obsoleteVals", "=", "storageEngine", ".", "multiVersionPut", "(", "currBufferedKey", ",", "currBufferedVals", ")", ";", "// log Obsolete ver...
Persists the current set of versions buffered for the current key into storage, using the multiVersionPut api NOTE: Now, it could be that the stream broke off and has more pending versions. For now, we simply commit what we have to disk. A better design would rely on in-stream markers to do the flushing to storage.
[ "Persists", "the", "current", "set", "of", "versions", "buffered", "for", "the", "current", "key", "into", "storage", "using", "the", "multiVersionPut", "api" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/BufferedUpdatePartitionEntriesStreamRequestHandler.java#L66-L75
train
voldemort/voldemort
src/java/voldemort/server/rebalance/Rebalancer.java
Rebalancer.acquireRebalancingPermit
public synchronized boolean acquireRebalancingPermit(int nodeId) { boolean added = rebalancePermits.add(nodeId); logger.info("Acquiring rebalancing permit for node id " + nodeId + ", returned: " + added); return added; }
java
public synchronized boolean acquireRebalancingPermit(int nodeId) { boolean added = rebalancePermits.add(nodeId); logger.info("Acquiring rebalancing permit for node id " + nodeId + ", returned: " + added); return added; }
[ "public", "synchronized", "boolean", "acquireRebalancingPermit", "(", "int", "nodeId", ")", "{", "boolean", "added", "=", "rebalancePermits", ".", "add", "(", "nodeId", ")", ";", "logger", ".", "info", "(", "\"Acquiring rebalancing permit for node id \"", "+", "node...
Acquire a permit for a particular node id so as to allow rebalancing @param nodeId The id of the node for which we are acquiring a permit @return Returns true if permit acquired, false if the permit is already held by someone
[ "Acquire", "a", "permit", "for", "a", "particular", "node", "id", "so", "as", "to", "allow", "rebalancing" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/rebalance/Rebalancer.java#L91-L96
train
voldemort/voldemort
src/java/voldemort/server/rebalance/Rebalancer.java
Rebalancer.releaseRebalancingPermit
public synchronized void releaseRebalancingPermit(int nodeId) { boolean removed = rebalancePermits.remove(nodeId); logger.info("Releasing rebalancing permit for node id " + nodeId + ", returned: " + removed); if(!removed) throw new VoldemortException(new IllegalStateException("Invalid state, must hold a " + "permit to release")); }
java
public synchronized void releaseRebalancingPermit(int nodeId) { boolean removed = rebalancePermits.remove(nodeId); logger.info("Releasing rebalancing permit for node id " + nodeId + ", returned: " + removed); if(!removed) throw new VoldemortException(new IllegalStateException("Invalid state, must hold a " + "permit to release")); }
[ "public", "synchronized", "void", "releaseRebalancingPermit", "(", "int", "nodeId", ")", "{", "boolean", "removed", "=", "rebalancePermits", ".", "remove", "(", "nodeId", ")", ";", "logger", ".", "info", "(", "\"Releasing rebalancing permit for node id \"", "+", "no...
Release the rebalancing permit for a particular node id @param nodeId The node id whose permit we want to release
[ "Release", "the", "rebalancing", "permit", "for", "a", "particular", "node", "id" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/rebalance/Rebalancer.java#L103-L109
train
voldemort/voldemort
src/java/voldemort/server/rebalance/Rebalancer.java
Rebalancer.swapROStores
private void swapROStores(List<String> swappedStoreNames, boolean useSwappedStoreNames) { try { for(StoreDefinition storeDef: metadataStore.getStoreDefList()) { // Only pick up the RO stores if(storeDef.getType().compareTo(ReadOnlyStorageConfiguration.TYPE_NAME) == 0) { if(useSwappedStoreNames && !swappedStoreNames.contains(storeDef.getName())) { continue; } ReadOnlyStorageEngine engine = (ReadOnlyStorageEngine) storeRepository.getStorageEngine(storeDef.getName()); if(engine == null) { throw new VoldemortException("Could not find storage engine for " + storeDef.getName() + " to swap "); } logger.info("Swapping RO store " + storeDef.getName()); // Time to swap this store - Could have used admin client, // but why incur the overhead? engine.swapFiles(engine.getCurrentDirPath()); // Add to list of stores already swapped if(!useSwappedStoreNames) swappedStoreNames.add(storeDef.getName()); } } } catch(Exception e) { logger.error("Error while swapping RO store"); throw new VoldemortException(e); } }
java
private void swapROStores(List<String> swappedStoreNames, boolean useSwappedStoreNames) { try { for(StoreDefinition storeDef: metadataStore.getStoreDefList()) { // Only pick up the RO stores if(storeDef.getType().compareTo(ReadOnlyStorageConfiguration.TYPE_NAME) == 0) { if(useSwappedStoreNames && !swappedStoreNames.contains(storeDef.getName())) { continue; } ReadOnlyStorageEngine engine = (ReadOnlyStorageEngine) storeRepository.getStorageEngine(storeDef.getName()); if(engine == null) { throw new VoldemortException("Could not find storage engine for " + storeDef.getName() + " to swap "); } logger.info("Swapping RO store " + storeDef.getName()); // Time to swap this store - Could have used admin client, // but why incur the overhead? engine.swapFiles(engine.getCurrentDirPath()); // Add to list of stores already swapped if(!useSwappedStoreNames) swappedStoreNames.add(storeDef.getName()); } } } catch(Exception e) { logger.error("Error while swapping RO store"); throw new VoldemortException(e); } }
[ "private", "void", "swapROStores", "(", "List", "<", "String", ">", "swappedStoreNames", ",", "boolean", "useSwappedStoreNames", ")", "{", "try", "{", "for", "(", "StoreDefinition", "storeDef", ":", "metadataStore", ".", "getStoreDefList", "(", ")", ")", "{", ...
Goes through all the RO Stores in the plan and swaps it @param swappedStoreNames Names of stores already swapped @param useSwappedStoreNames Swap only the previously swapped stores ( Happens during error )
[ "Goes", "through", "all", "the", "RO", "Stores", "in", "the", "plan", "and", "swaps", "it" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/rebalance/Rebalancer.java#L336-L370
train
voldemort/voldemort
src/java/voldemort/server/rebalance/Rebalancer.java
Rebalancer.changeClusterAndStores
private void changeClusterAndStores(String clusterKey, final Cluster cluster, String storesKey, final List<StoreDefinition> storeDefs) { metadataStore.writeLock.lock(); try { VectorClock updatedVectorClock = ((VectorClock) metadataStore.get(clusterKey, null) .get(0) .getVersion()).incremented(metadataStore.getNodeId(), System.currentTimeMillis()); metadataStore.put(clusterKey, Versioned.value((Object) cluster, updatedVectorClock)); // now put new stores updatedVectorClock = ((VectorClock) metadataStore.get(storesKey, null) .get(0) .getVersion()).incremented(metadataStore.getNodeId(), System.currentTimeMillis()); metadataStore.put(storesKey, Versioned.value((Object) storeDefs, updatedVectorClock)); } catch(Exception e) { logger.info("Error while changing cluster to " + cluster + "for key " + clusterKey); throw new VoldemortException(e); } finally { metadataStore.writeLock.unlock(); } }
java
private void changeClusterAndStores(String clusterKey, final Cluster cluster, String storesKey, final List<StoreDefinition> storeDefs) { metadataStore.writeLock.lock(); try { VectorClock updatedVectorClock = ((VectorClock) metadataStore.get(clusterKey, null) .get(0) .getVersion()).incremented(metadataStore.getNodeId(), System.currentTimeMillis()); metadataStore.put(clusterKey, Versioned.value((Object) cluster, updatedVectorClock)); // now put new stores updatedVectorClock = ((VectorClock) metadataStore.get(storesKey, null) .get(0) .getVersion()).incremented(metadataStore.getNodeId(), System.currentTimeMillis()); metadataStore.put(storesKey, Versioned.value((Object) storeDefs, updatedVectorClock)); } catch(Exception e) { logger.info("Error while changing cluster to " + cluster + "for key " + clusterKey); throw new VoldemortException(e); } finally { metadataStore.writeLock.unlock(); } }
[ "private", "void", "changeClusterAndStores", "(", "String", "clusterKey", ",", "final", "Cluster", "cluster", ",", "String", "storesKey", ",", "final", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "metadataStore", ".", "writeLock", ".", "lock", "(...
Updates the cluster and store metadata atomically This is required during rebalance and expansion into a new zone since we have to update the store def along with the cluster def. @param cluster The cluster metadata information @param storeDefs The stores metadata information
[ "Updates", "the", "cluster", "and", "store", "metadata", "atomically" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/rebalance/Rebalancer.java#L381-L406
train
voldemort/voldemort
src/java/voldemort/server/rebalance/Rebalancer.java
Rebalancer.rebalanceNode
public int rebalanceNode(final RebalanceTaskInfo stealInfo) { final RebalanceTaskInfo info = metadataStore.getRebalancerState() .find(stealInfo.getDonorId()); // Do we have the plan in the state? if(info == null) { throw new VoldemortException("Could not find plan " + stealInfo + " in the server state on " + metadataStore.getNodeId()); } else if(!info.equals(stealInfo)) { // If we do have the plan, is it the same throw new VoldemortException("The plan in server state " + info + " is not the same as the process passed " + stealInfo); } else if(!acquireRebalancingPermit(stealInfo.getDonorId())) { // Both are same, now try to acquire a lock for the donor node throw new AlreadyRebalancingException("Node " + metadataStore.getNodeId() + " is already rebalancing from donor " + info.getDonorId() + " with info " + info); } // Acquired lock successfully, start rebalancing... int requestId = asyncService.getUniqueRequestId(); // Why do we pass 'info' instead of 'stealInfo'? So that we can change // the state as the stores finish rebalance asyncService.submitOperation(requestId, new StealerBasedRebalanceAsyncOperation(this, voldemortConfig, metadataStore, requestId, info)); return requestId; }
java
public int rebalanceNode(final RebalanceTaskInfo stealInfo) { final RebalanceTaskInfo info = metadataStore.getRebalancerState() .find(stealInfo.getDonorId()); // Do we have the plan in the state? if(info == null) { throw new VoldemortException("Could not find plan " + stealInfo + " in the server state on " + metadataStore.getNodeId()); } else if(!info.equals(stealInfo)) { // If we do have the plan, is it the same throw new VoldemortException("The plan in server state " + info + " is not the same as the process passed " + stealInfo); } else if(!acquireRebalancingPermit(stealInfo.getDonorId())) { // Both are same, now try to acquire a lock for the donor node throw new AlreadyRebalancingException("Node " + metadataStore.getNodeId() + " is already rebalancing from donor " + info.getDonorId() + " with info " + info); } // Acquired lock successfully, start rebalancing... int requestId = asyncService.getUniqueRequestId(); // Why do we pass 'info' instead of 'stealInfo'? So that we can change // the state as the stores finish rebalance asyncService.submitOperation(requestId, new StealerBasedRebalanceAsyncOperation(this, voldemortConfig, metadataStore, requestId, info)); return requestId; }
[ "public", "int", "rebalanceNode", "(", "final", "RebalanceTaskInfo", "stealInfo", ")", "{", "final", "RebalanceTaskInfo", "info", "=", "metadataStore", ".", "getRebalancerState", "(", ")", ".", "find", "(", "stealInfo", ".", "getDonorId", "(", ")", ")", ";", "...
This function is responsible for starting the actual async rebalance operation. This is run if this node is the stealer node <br> We also assume that the check that this server is in rebalancing state has been done at a higher level @param stealInfo Partition info to steal @return Returns a id identifying the async operation
[ "This", "function", "is", "responsible", "for", "starting", "the", "actual", "async", "rebalance", "operation", ".", "This", "is", "run", "if", "this", "node", "is", "the", "stealer", "node" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/rebalance/Rebalancer.java#L420-L453
train
voldemort/voldemort
src/java/voldemort/server/niosocket/AsyncRequestHandler.java
AsyncRequestHandler.prepForWrite
protected void prepForWrite(SelectionKey selectionKey) { if(logger.isTraceEnabled()) traceInputBufferState("About to clear read buffer"); if(requestHandlerFactory.shareReadWriteBuffer() == false) { inputStream.clear(); } if(logger.isTraceEnabled()) traceInputBufferState("Cleared read buffer"); outputStream.getBuffer().flip(); selectionKey.interestOps(SelectionKey.OP_WRITE); }
java
protected void prepForWrite(SelectionKey selectionKey) { if(logger.isTraceEnabled()) traceInputBufferState("About to clear read buffer"); if(requestHandlerFactory.shareReadWriteBuffer() == false) { inputStream.clear(); } if(logger.isTraceEnabled()) traceInputBufferState("Cleared read buffer"); outputStream.getBuffer().flip(); selectionKey.interestOps(SelectionKey.OP_WRITE); }
[ "protected", "void", "prepForWrite", "(", "SelectionKey", "selectionKey", ")", "{", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "traceInputBufferState", "(", "\"About to clear read buffer\"", ")", ";", "if", "(", "requestHandlerFactory", ".", "shareRe...
Flips the output buffer, and lets the Selector know we're ready to write. @param selectionKey
[ "Flips", "the", "output", "buffer", "and", "lets", "the", "Selector", "know", "we", "re", "ready", "to", "write", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/niosocket/AsyncRequestHandler.java#L92-L105
train