id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
160,900
voldemort/voldemort
src/java/voldemort/tools/admin/AdminParserUtils.java
AdminParserUtils.checkRequired
public static void checkRequired(OptionSet options, String opt) throws VoldemortException { List<String> opts = Lists.newArrayList(); opts.add(opt); checkRequired(options, opts); }
java
public static void checkRequired(OptionSet options, String opt) throws VoldemortException { List<String> opts = Lists.newArrayList(); opts.add(opt); checkRequired(options, opts); }
[ "public", "static", "void", "checkRequired", "(", "OptionSet", "options", ",", "String", "opt", ")", "throws", "VoldemortException", "{", "List", "<", "String", ">", "opts", "=", "Lists", ".", "newArrayList", "(", ")", ";", "opts", ".", "add", "(", "opt", ")", ";", "checkRequired", "(", "options", ",", "opts", ")", ";", "}" ]
Checks if the required option exists. @param options OptionSet to checked @param opt Required option to check @throws VoldemortException
[ "Checks", "if", "the", "required", "option", "exists", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L312-L316
160,901
voldemort/voldemort
src/java/voldemort/tools/admin/AdminParserUtils.java
AdminParserUtils.checkRequired
public static void checkRequired(OptionSet options, String opt1, String opt2) throws VoldemortException { List<String> opts = Lists.newArrayList(); opts.add(opt1); opts.add(opt2); checkRequired(options, opts); }
java
public static void checkRequired(OptionSet options, String opt1, String opt2) throws VoldemortException { List<String> opts = Lists.newArrayList(); opts.add(opt1); opts.add(opt2); checkRequired(options, opts); }
[ "public", "static", "void", "checkRequired", "(", "OptionSet", "options", ",", "String", "opt1", ",", "String", "opt2", ")", "throws", "VoldemortException", "{", "List", "<", "String", ">", "opts", "=", "Lists", ".", "newArrayList", "(", ")", ";", "opts", ".", "add", "(", "opt1", ")", ";", "opts", ".", "add", "(", "opt2", ")", ";", "checkRequired", "(", "options", ",", "opts", ")", ";", "}" ]
Checks if there's exactly one option that exists among all possible opts. @param options OptionSet to checked @param opt1 Possible required option to check @param opt2 Possible required option to check @throws VoldemortException
[ "Checks", "if", "there", "s", "exactly", "one", "option", "that", "exists", "among", "all", "possible", "opts", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L326-L332
160,902
voldemort/voldemort
src/java/voldemort/tools/admin/AdminParserUtils.java
AdminParserUtils.checkRequired
public static void checkRequired(OptionSet options, List<String> opts) throws VoldemortException { List<String> optCopy = Lists.newArrayList(); for(String opt: opts) { if(options.has(opt)) { optCopy.add(opt); } } if(optCopy.size() < 1) { System.err.println("Please specify one of the following options:"); for(String opt: opts) { System.err.println("--" + opt); } Utils.croak("Missing required option."); } if(optCopy.size() > 1) { System.err.println("Conflicting options:"); for(String opt: optCopy) { System.err.println("--" + opt); } Utils.croak("Conflicting options detected."); } }
java
public static void checkRequired(OptionSet options, List<String> opts) throws VoldemortException { List<String> optCopy = Lists.newArrayList(); for(String opt: opts) { if(options.has(opt)) { optCopy.add(opt); } } if(optCopy.size() < 1) { System.err.println("Please specify one of the following options:"); for(String opt: opts) { System.err.println("--" + opt); } Utils.croak("Missing required option."); } if(optCopy.size() > 1) { System.err.println("Conflicting options:"); for(String opt: optCopy) { System.err.println("--" + opt); } Utils.croak("Conflicting options detected."); } }
[ "public", "static", "void", "checkRequired", "(", "OptionSet", "options", ",", "List", "<", "String", ">", "opts", ")", "throws", "VoldemortException", "{", "List", "<", "String", ">", "optCopy", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "String", "opt", ":", "opts", ")", "{", "if", "(", "options", ".", "has", "(", "opt", ")", ")", "{", "optCopy", ".", "add", "(", "opt", ")", ";", "}", "}", "if", "(", "optCopy", ".", "size", "(", ")", "<", "1", ")", "{", "System", ".", "err", ".", "println", "(", "\"Please specify one of the following options:\"", ")", ";", "for", "(", "String", "opt", ":", "opts", ")", "{", "System", ".", "err", ".", "println", "(", "\"--\"", "+", "opt", ")", ";", "}", "Utils", ".", "croak", "(", "\"Missing required option.\"", ")", ";", "}", "if", "(", "optCopy", ".", "size", "(", ")", ">", "1", ")", "{", "System", ".", "err", ".", "println", "(", "\"Conflicting options:\"", ")", ";", "for", "(", "String", "opt", ":", "optCopy", ")", "{", "System", ".", "err", ".", "println", "(", "\"--\"", "+", "opt", ")", ";", "}", "Utils", ".", "croak", "(", "\"Conflicting options detected.\"", ")", ";", "}", "}" ]
Checks if there's exactly one option that exists among all opts. @param options OptionSet to checked @param opts List of options to be checked @throws VoldemortException
[ "Checks", "if", "there", "s", "exactly", "one", "option", "that", "exists", "among", "all", "opts", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L359-L381
160,903
voldemort/voldemort
src/java/voldemort/rest/coordinator/RestCoordinatorRequestHandler.java
RestCoordinatorRequestHandler.registerRequest
@Override protected void registerRequest(RestRequestValidator requestValidator, ChannelHandlerContext ctx, MessageEvent messageEvent) { // At this point we know the request is valid and we have a // error handler. So we construct the composite Voldemort // request object. CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject(); if(requestObject != null) { DynamicTimeoutStoreClient<ByteArray, byte[]> storeClient = null; if(!requestValidator.getStoreName().equalsIgnoreCase(RestMessageHeaders.SCHEMATA_STORE)) { storeClient = this.fatClientMap.get(requestValidator.getStoreName()); if(storeClient == null) { logger.error("Error when getting store. Non Existing store client."); RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Non Existing store client. Critical error."); return; } } else { requestObject.setOperationType(VoldemortOpCode.GET_METADATA_OP_CODE); } CoordinatorStoreClientRequest coordinatorRequest = new CoordinatorStoreClientRequest(requestObject, storeClient); Channels.fireMessageReceived(ctx, coordinatorRequest); } }
java
@Override protected void registerRequest(RestRequestValidator requestValidator, ChannelHandlerContext ctx, MessageEvent messageEvent) { // At this point we know the request is valid and we have a // error handler. So we construct the composite Voldemort // request object. CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject(); if(requestObject != null) { DynamicTimeoutStoreClient<ByteArray, byte[]> storeClient = null; if(!requestValidator.getStoreName().equalsIgnoreCase(RestMessageHeaders.SCHEMATA_STORE)) { storeClient = this.fatClientMap.get(requestValidator.getStoreName()); if(storeClient == null) { logger.error("Error when getting store. Non Existing store client."); RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Non Existing store client. Critical error."); return; } } else { requestObject.setOperationType(VoldemortOpCode.GET_METADATA_OP_CODE); } CoordinatorStoreClientRequest coordinatorRequest = new CoordinatorStoreClientRequest(requestObject, storeClient); Channels.fireMessageReceived(ctx, coordinatorRequest); } }
[ "@", "Override", "protected", "void", "registerRequest", "(", "RestRequestValidator", "requestValidator", ",", "ChannelHandlerContext", "ctx", ",", "MessageEvent", "messageEvent", ")", "{", "// At this point we know the request is valid and we have a", "// error handler. So we construct the composite Voldemort", "// request object.", "CompositeVoldemortRequest", "<", "ByteArray", ",", "byte", "[", "]", ">", "requestObject", "=", "requestValidator", ".", "constructCompositeVoldemortRequestObject", "(", ")", ";", "if", "(", "requestObject", "!=", "null", ")", "{", "DynamicTimeoutStoreClient", "<", "ByteArray", ",", "byte", "[", "]", ">", "storeClient", "=", "null", ";", "if", "(", "!", "requestValidator", ".", "getStoreName", "(", ")", ".", "equalsIgnoreCase", "(", "RestMessageHeaders", ".", "SCHEMATA_STORE", ")", ")", "{", "storeClient", "=", "this", ".", "fatClientMap", ".", "get", "(", "requestValidator", ".", "getStoreName", "(", ")", ")", ";", "if", "(", "storeClient", "==", "null", ")", "{", "logger", ".", "error", "(", "\"Error when getting store. Non Existing store client.\"", ")", ";", "RestErrorHandler", ".", "writeErrorResponse", "(", "messageEvent", ",", "HttpResponseStatus", ".", "BAD_REQUEST", ",", "\"Non Existing store client. Critical error.\"", ")", ";", "return", ";", "}", "}", "else", "{", "requestObject", ".", "setOperationType", "(", "VoldemortOpCode", ".", "GET_METADATA_OP_CODE", ")", ";", "}", "CoordinatorStoreClientRequest", "coordinatorRequest", "=", "new", "CoordinatorStoreClientRequest", "(", "requestObject", ",", "storeClient", ")", ";", "Channels", ".", "fireMessageReceived", "(", "ctx", ",", "coordinatorRequest", ")", ";", "}", "}" ]
Constructs a valid request and passes it on to the next handler. It also creates the 'StoreClient' object corresponding to the store name specified in the REST request. @param requestValidator The Validator object used to construct the request object @param ctx Context of the Netty channel @param messageEvent Message Event used to write the response / exception
[ "Constructs", "a", "valid", "request", "and", "passes", "it", "on", "to", "the", "next", "handler", ".", "It", "also", "creates", "the", "StoreClient", "object", "corresponding", "to", "the", "store", "name", "specified", "in", "the", "REST", "request", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/RestCoordinatorRequestHandler.java#L39-L72
160,904
voldemort/voldemort
src/java/voldemort/rest/RestDeleteErrorHandler.java
RestDeleteErrorHandler.handleExceptions
@Override public void handleExceptions(MessageEvent messageEvent, Exception exception) { if(exception instanceof InvalidMetadataException) { logger.error("Exception when deleting. The requested key does not exist in this partition", exception); writeErrorResponse(messageEvent, HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE, "The requested key does not exist in this partition"); } else if(exception instanceof PersistenceFailureException) { logger.error("Exception when deleting. Operation failed", exception); writeErrorResponse(messageEvent, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Operation failed"); } else if(exception instanceof UnsupportedOperationException) { logger.error("Exception when deleting. Operation not supported in read-only store ", exception); writeErrorResponse(messageEvent, HttpResponseStatus.METHOD_NOT_ALLOWED, "Operation not supported in read-only store"); } else if(exception instanceof StoreTimeoutException) { String errorDescription = "DELETE Request timed out: " + exception.getMessage(); logger.error(errorDescription); writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription); } else if(exception instanceof InsufficientOperationalNodesException) { String errorDescription = "DELETE Request failed: " + exception.getMessage(); logger.error(errorDescription); writeErrorResponse(messageEvent, HttpResponseStatus.INTERNAL_SERVER_ERROR, errorDescription); } else { super.handleExceptions(messageEvent, exception); } }
java
@Override public void handleExceptions(MessageEvent messageEvent, Exception exception) { if(exception instanceof InvalidMetadataException) { logger.error("Exception when deleting. The requested key does not exist in this partition", exception); writeErrorResponse(messageEvent, HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE, "The requested key does not exist in this partition"); } else if(exception instanceof PersistenceFailureException) { logger.error("Exception when deleting. Operation failed", exception); writeErrorResponse(messageEvent, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Operation failed"); } else if(exception instanceof UnsupportedOperationException) { logger.error("Exception when deleting. Operation not supported in read-only store ", exception); writeErrorResponse(messageEvent, HttpResponseStatus.METHOD_NOT_ALLOWED, "Operation not supported in read-only store"); } else if(exception instanceof StoreTimeoutException) { String errorDescription = "DELETE Request timed out: " + exception.getMessage(); logger.error(errorDescription); writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription); } else if(exception instanceof InsufficientOperationalNodesException) { String errorDescription = "DELETE Request failed: " + exception.getMessage(); logger.error(errorDescription); writeErrorResponse(messageEvent, HttpResponseStatus.INTERNAL_SERVER_ERROR, errorDescription); } else { super.handleExceptions(messageEvent, exception); } }
[ "@", "Override", "public", "void", "handleExceptions", "(", "MessageEvent", "messageEvent", ",", "Exception", "exception", ")", "{", "if", "(", "exception", "instanceof", "InvalidMetadataException", ")", "{", "logger", ".", "error", "(", "\"Exception when deleting. The requested key does not exist in this partition\"", ",", "exception", ")", ";", "writeErrorResponse", "(", "messageEvent", ",", "HttpResponseStatus", ".", "REQUESTED_RANGE_NOT_SATISFIABLE", ",", "\"The requested key does not exist in this partition\"", ")", ";", "}", "else", "if", "(", "exception", "instanceof", "PersistenceFailureException", ")", "{", "logger", ".", "error", "(", "\"Exception when deleting. Operation failed\"", ",", "exception", ")", ";", "writeErrorResponse", "(", "messageEvent", ",", "HttpResponseStatus", ".", "INTERNAL_SERVER_ERROR", ",", "\"Operation failed\"", ")", ";", "}", "else", "if", "(", "exception", "instanceof", "UnsupportedOperationException", ")", "{", "logger", ".", "error", "(", "\"Exception when deleting. Operation not supported in read-only store \"", ",", "exception", ")", ";", "writeErrorResponse", "(", "messageEvent", ",", "HttpResponseStatus", ".", "METHOD_NOT_ALLOWED", ",", "\"Operation not supported in read-only store\"", ")", ";", "}", "else", "if", "(", "exception", "instanceof", "StoreTimeoutException", ")", "{", "String", "errorDescription", "=", "\"DELETE Request timed out: \"", "+", "exception", ".", "getMessage", "(", ")", ";", "logger", ".", "error", "(", "errorDescription", ")", ";", "writeErrorResponse", "(", "messageEvent", ",", "HttpResponseStatus", ".", "REQUEST_TIMEOUT", ",", "errorDescription", ")", ";", "}", "else", "if", "(", "exception", "instanceof", "InsufficientOperationalNodesException", ")", "{", "String", "errorDescription", "=", "\"DELETE Request failed: \"", "+", "exception", ".", "getMessage", "(", ")", ";", "logger", ".", "error", "(", "errorDescription", ")", ";", "writeErrorResponse", "(", "messageEvent", ",", "HttpResponseStatus", ".", "INTERNAL_SERVER_ERROR", ",", "errorDescription", ")", ";", "}", "else", "{", "super", ".", "handleExceptions", "(", "messageEvent", ",", "exception", ")", ";", "}", "}" ]
Handle exceptions thrown by the storage. Exceptions specific to DELETE go here. Pass other exceptions to the parent class. TODO REST-Server Add a new exception for this condition - server busy with pending requests. queue is full
[ "Handle", "exceptions", "thrown", "by", "the", "storage", ".", "Exceptions", "specific", "to", "DELETE", "go", "here", ".", "Pass", "other", "exceptions", "to", "the", "parent", "class", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestDeleteErrorHandler.java#L22-L55
160,905
voldemort/voldemort
src/java/voldemort/store/stats/StoreStats.java
StoreStats.recordPutTimeAndSize
public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) { recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0); }
java
public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) { recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0); }
[ "public", "void", "recordPutTimeAndSize", "(", "long", "timeNS", ",", "long", "valueSize", ",", "long", "keySize", ")", "{", "recordTime", "(", "Tracked", ".", "PUT", ",", "timeNS", ",", "0", ",", "valueSize", ",", "keySize", ",", "0", ")", ";", "}" ]
Record the duration of a put operation, along with the size of the values returned.
[ "Record", "the", "duration", "of", "a", "put", "operation", "along", "with", "the", "size", "of", "the", "values", "returned", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/StoreStats.java#L104-L106
160,906
voldemort/voldemort
src/java/voldemort/store/stats/StoreStats.java
StoreStats.recordGetAllTime
public void recordGetAllTime(long timeNS, int requested, int returned, long totalValueBytes, long totalKeyBytes) { recordTime(Tracked.GET_ALL, timeNS, requested - returned, totalValueBytes, totalKeyBytes, requested); }
java
public void recordGetAllTime(long timeNS, int requested, int returned, long totalValueBytes, long totalKeyBytes) { recordTime(Tracked.GET_ALL, timeNS, requested - returned, totalValueBytes, totalKeyBytes, requested); }
[ "public", "void", "recordGetAllTime", "(", "long", "timeNS", ",", "int", "requested", ",", "int", "returned", ",", "long", "totalValueBytes", ",", "long", "totalKeyBytes", ")", "{", "recordTime", "(", "Tracked", ".", "GET_ALL", ",", "timeNS", ",", "requested", "-", "returned", ",", "totalValueBytes", ",", "totalKeyBytes", ",", "requested", ")", ";", "}" ]
Record the duration of a get_all operation, along with how many values were requested, how may were actually returned and the size of the values returned.
[ "Record", "the", "duration", "of", "a", "get_all", "operation", "along", "with", "how", "many", "values", "were", "requested", "how", "may", "were", "actually", "returned", "and", "the", "size", "of", "the", "values", "returned", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/StoreStats.java#L130-L141
160,907
voldemort/voldemort
src/java/voldemort/store/stats/StoreStats.java
StoreStats.recordTime
private void recordTime(Tracked op, long timeNS, long numEmptyResponses, long valueSize, long keySize, long getAllAggregateRequests) { counters.get(op).addRequest(timeNS, numEmptyResponses, valueSize, keySize, getAllAggregateRequests); if (logger.isTraceEnabled() && !storeName.contains("aggregate") && !storeName.contains("voldsys$")) logger.trace("Store '" + storeName + "' logged a " + op.toString() + " request taking " + ((double) timeNS / voldemort.utils.Time.NS_PER_MS) + " ms"); }
java
private void recordTime(Tracked op, long timeNS, long numEmptyResponses, long valueSize, long keySize, long getAllAggregateRequests) { counters.get(op).addRequest(timeNS, numEmptyResponses, valueSize, keySize, getAllAggregateRequests); if (logger.isTraceEnabled() && !storeName.contains("aggregate") && !storeName.contains("voldsys$")) logger.trace("Store '" + storeName + "' logged a " + op.toString() + " request taking " + ((double) timeNS / voldemort.utils.Time.NS_PER_MS) + " ms"); }
[ "private", "void", "recordTime", "(", "Tracked", "op", ",", "long", "timeNS", ",", "long", "numEmptyResponses", ",", "long", "valueSize", ",", "long", "keySize", ",", "long", "getAllAggregateRequests", ")", "{", "counters", ".", "get", "(", "op", ")", ".", "addRequest", "(", "timeNS", ",", "numEmptyResponses", ",", "valueSize", ",", "keySize", ",", "getAllAggregateRequests", ")", ";", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", "&&", "!", "storeName", ".", "contains", "(", "\"aggregate\"", ")", "&&", "!", "storeName", ".", "contains", "(", "\"voldsys$\"", ")", ")", "logger", ".", "trace", "(", "\"Store '\"", "+", "storeName", "+", "\"' logged a \"", "+", "op", ".", "toString", "(", ")", "+", "\" request taking \"", "+", "(", "(", "double", ")", "timeNS", "/", "voldemort", ".", "utils", ".", "Time", ".", "NS_PER_MS", ")", "+", "\" ms\"", ")", ";", "}" ]
Method to service public recording APIs @param op Operation being tracked @param timeNS Duration of operation @param numEmptyResponses Number of empty responses being sent back, i.e.: requested keys for which there were no values (GET and GET_ALL only) @param valueSize Size in bytes of the value @param keySize Size in bytes of the key @param getAllAggregateRequests Total of amount of keys requested in the operation (GET_ALL only)
[ "Method", "to", "service", "public", "recording", "APIs" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/StoreStats.java#L154-L169
160,908
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/utils/VoldemortUtils.java
VoldemortUtils.getCommaSeparatedStringValues
public static List<String> getCommaSeparatedStringValues(String paramValue, String type) { List<String> commaSeparatedProps = Lists.newArrayList(); for(String url: Utils.COMMA_SEP.split(paramValue.trim())) if(url.trim().length() > 0) commaSeparatedProps.add(url); if(commaSeparatedProps.size() == 0) { throw new RuntimeException("Number of " + type + " should be greater than zero"); } return commaSeparatedProps; }
java
public static List<String> getCommaSeparatedStringValues(String paramValue, String type) { List<String> commaSeparatedProps = Lists.newArrayList(); for(String url: Utils.COMMA_SEP.split(paramValue.trim())) if(url.trim().length() > 0) commaSeparatedProps.add(url); if(commaSeparatedProps.size() == 0) { throw new RuntimeException("Number of " + type + " should be greater than zero"); } return commaSeparatedProps; }
[ "public", "static", "List", "<", "String", ">", "getCommaSeparatedStringValues", "(", "String", "paramValue", ",", "String", "type", ")", "{", "List", "<", "String", ">", "commaSeparatedProps", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "String", "url", ":", "Utils", ".", "COMMA_SEP", ".", "split", "(", "paramValue", ".", "trim", "(", ")", ")", ")", "if", "(", "url", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "0", ")", "commaSeparatedProps", ".", "add", "(", "url", ")", ";", "if", "(", "commaSeparatedProps", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "RuntimeException", "(", "\"Number of \"", "+", "type", "+", "\" should be greater than zero\"", ")", ";", "}", "return", "commaSeparatedProps", ";", "}" ]
Given the comma separated list of properties as a string, splits it multiple strings @param paramValue Concatenated string @param type Type of parameter ( to throw exception ) @return List of string properties
[ "Given", "the", "comma", "separated", "list", "of", "properties", "as", "a", "string", "splits", "it", "multiple", "strings" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/utils/VoldemortUtils.java#L47-L57
160,909
voldemort/voldemort
src/java/voldemort/rest/coordinator/CoordinatorProxyService.java
CoordinatorProxyService.initializeFatClient
private synchronized void initializeFatClient(String storeName, Properties storeClientProps) { // updates the coordinator metadata with recent stores and cluster xml updateCoordinatorMetadataWithLatestState(); logger.info("Creating a Fat client for store: " + storeName); SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(), storeClientProps); if(this.fatClientMap == null) { this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>(); } DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName, fatClientFactory, 1, this.coordinatorMetadata.getStoreDefs(), this.coordinatorMetadata.getClusterXmlStr()); this.fatClientMap.put(storeName, fatClient); }
java
private synchronized void initializeFatClient(String storeName, Properties storeClientProps) { // updates the coordinator metadata with recent stores and cluster xml updateCoordinatorMetadataWithLatestState(); logger.info("Creating a Fat client for store: " + storeName); SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(), storeClientProps); if(this.fatClientMap == null) { this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>(); } DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName, fatClientFactory, 1, this.coordinatorMetadata.getStoreDefs(), this.coordinatorMetadata.getClusterXmlStr()); this.fatClientMap.put(storeName, fatClient); }
[ "private", "synchronized", "void", "initializeFatClient", "(", "String", "storeName", ",", "Properties", "storeClientProps", ")", "{", "// updates the coordinator metadata with recent stores and cluster xml", "updateCoordinatorMetadataWithLatestState", "(", ")", ";", "logger", ".", "info", "(", "\"Creating a Fat client for store: \"", "+", "storeName", ")", ";", "SocketStoreClientFactory", "fatClientFactory", "=", "getFatClientFactory", "(", "this", ".", "coordinatorConfig", ".", "getBootstrapURLs", "(", ")", ",", "storeClientProps", ")", ";", "if", "(", "this", ".", "fatClientMap", "==", "null", ")", "{", "this", ".", "fatClientMap", "=", "new", "HashMap", "<", "String", ",", "DynamicTimeoutStoreClient", "<", "ByteArray", ",", "byte", "[", "]", ">", ">", "(", ")", ";", "}", "DynamicTimeoutStoreClient", "<", "ByteArray", ",", "byte", "[", "]", ">", "fatClient", "=", "new", "DynamicTimeoutStoreClient", "<", "ByteArray", ",", "byte", "[", "]", ">", "(", "storeName", ",", "fatClientFactory", ",", "1", ",", "this", ".", "coordinatorMetadata", ".", "getStoreDefs", "(", ")", ",", "this", ".", "coordinatorMetadata", ".", "getClusterXmlStr", "(", ")", ")", ";", "this", ".", "fatClientMap", ".", "put", "(", "storeName", ",", "fatClient", ")", ";", "}" ]
Initialize the fat client for the given store. 1. Updates the coordinatorMetadata 2.Gets the new store configs from the config file 3.Creates a new @SocketStoreClientFactory 4. Subsequently caches the @StoreClient obtained from the factory. This is synchronized because if Coordinator Admin is already doing some change we want the AsyncMetadataVersionManager to wait. @param storeName
[ "Initialize", "the", "fat", "client", "for", "the", "given", "store", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/CoordinatorProxyService.java#L104-L122
160,910
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceBatchPlanProgressBar.java
RebalanceBatchPlanProgressBar.completeTask
synchronized public void completeTask(int taskId, int partitionStoresMigrated) { tasksInFlight.remove(taskId); numTasksCompleted++; numPartitionStoresMigrated += partitionStoresMigrated; updateProgressBar(); }
java
synchronized public void completeTask(int taskId, int partitionStoresMigrated) { tasksInFlight.remove(taskId); numTasksCompleted++; numPartitionStoresMigrated += partitionStoresMigrated; updateProgressBar(); }
[ "synchronized", "public", "void", "completeTask", "(", "int", "taskId", ",", "int", "partitionStoresMigrated", ")", "{", "tasksInFlight", ".", "remove", "(", "taskId", ")", ";", "numTasksCompleted", "++", ";", "numPartitionStoresMigrated", "+=", "partitionStoresMigrated", ";", "updateProgressBar", "(", ")", ";", "}" ]
Called whenever a rebalance task completes. This means one task is done and some number of partition stores have been migrated. @param taskId @param partitionStoresMigrated Number of partition stores moved by this completed task.
[ "Called", "whenever", "a", "rebalance", "task", "completes", ".", "This", "means", "one", "task", "is", "done", "and", "some", "number", "of", "partition", "stores", "have", "been", "migrated", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceBatchPlanProgressBar.java#L82-L89
160,911
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalanceBatchPlanProgressBar.java
RebalanceBatchPlanProgressBar.getPrettyProgressBar
synchronized public String getPrettyProgressBar() { StringBuilder sb = new StringBuilder(); double taskRate = numTasksCompleted / (double) totalTaskCount; double partitionStoreRate = numPartitionStoresMigrated / (double) totalPartitionStoreCount; long deltaTimeMs = System.currentTimeMillis() - startTimeMs; long taskTimeRemainingMs = Long.MAX_VALUE; if(taskRate > 0) { taskTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / taskRate) - 1.0)); } long partitionStoreTimeRemainingMs = Long.MAX_VALUE; if(partitionStoreRate > 0) { partitionStoreTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / partitionStoreRate) - 1.0)); } // Title line sb.append("Progress update on rebalancing batch " + batchId).append(Utils.NEWLINE); // Tasks in flight update sb.append("There are currently " + tasksInFlight.size() + " rebalance tasks executing: ") .append(tasksInFlight) .append(".") .append(Utils.NEWLINE); // Tasks completed update sb.append("\t" + numTasksCompleted + " out of " + totalTaskCount + " rebalance tasks complete.") .append(Utils.NEWLINE) .append("\t") .append(decimalFormatter.format(taskRate * 100.0)) .append("% done, estimate ") .append(taskTimeRemainingMs) .append(" ms (") .append(TimeUnit.MILLISECONDS.toMinutes(taskTimeRemainingMs)) .append(" minutes) remaining.") .append(Utils.NEWLINE); // Partition-stores migrated update sb.append("\t" + numPartitionStoresMigrated + " out of " + totalPartitionStoreCount + " partition-stores migrated.") .append(Utils.NEWLINE) .append("\t") .append(decimalFormatter.format(partitionStoreRate * 100.0)) .append("% done, estimate ") .append(partitionStoreTimeRemainingMs) .append(" ms (") .append(TimeUnit.MILLISECONDS.toMinutes(partitionStoreTimeRemainingMs)) .append(" minutes) remaining.") .append(Utils.NEWLINE); return sb.toString(); }
java
synchronized public String getPrettyProgressBar() { StringBuilder sb = new StringBuilder(); double taskRate = numTasksCompleted / (double) totalTaskCount; double partitionStoreRate = numPartitionStoresMigrated / (double) totalPartitionStoreCount; long deltaTimeMs = System.currentTimeMillis() - startTimeMs; long taskTimeRemainingMs = Long.MAX_VALUE; if(taskRate > 0) { taskTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / taskRate) - 1.0)); } long partitionStoreTimeRemainingMs = Long.MAX_VALUE; if(partitionStoreRate > 0) { partitionStoreTimeRemainingMs = (long) (deltaTimeMs * ((1.0 / partitionStoreRate) - 1.0)); } // Title line sb.append("Progress update on rebalancing batch " + batchId).append(Utils.NEWLINE); // Tasks in flight update sb.append("There are currently " + tasksInFlight.size() + " rebalance tasks executing: ") .append(tasksInFlight) .append(".") .append(Utils.NEWLINE); // Tasks completed update sb.append("\t" + numTasksCompleted + " out of " + totalTaskCount + " rebalance tasks complete.") .append(Utils.NEWLINE) .append("\t") .append(decimalFormatter.format(taskRate * 100.0)) .append("% done, estimate ") .append(taskTimeRemainingMs) .append(" ms (") .append(TimeUnit.MILLISECONDS.toMinutes(taskTimeRemainingMs)) .append(" minutes) remaining.") .append(Utils.NEWLINE); // Partition-stores migrated update sb.append("\t" + numPartitionStoresMigrated + " out of " + totalPartitionStoreCount + " partition-stores migrated.") .append(Utils.NEWLINE) .append("\t") .append(decimalFormatter.format(partitionStoreRate * 100.0)) .append("% done, estimate ") .append(partitionStoreTimeRemainingMs) .append(" ms (") .append(TimeUnit.MILLISECONDS.toMinutes(partitionStoreTimeRemainingMs)) .append(" minutes) remaining.") .append(Utils.NEWLINE); return sb.toString(); }
[ "synchronized", "public", "String", "getPrettyProgressBar", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "double", "taskRate", "=", "numTasksCompleted", "/", "(", "double", ")", "totalTaskCount", ";", "double", "partitionStoreRate", "=", "numPartitionStoresMigrated", "/", "(", "double", ")", "totalPartitionStoreCount", ";", "long", "deltaTimeMs", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "startTimeMs", ";", "long", "taskTimeRemainingMs", "=", "Long", ".", "MAX_VALUE", ";", "if", "(", "taskRate", ">", "0", ")", "{", "taskTimeRemainingMs", "=", "(", "long", ")", "(", "deltaTimeMs", "*", "(", "(", "1.0", "/", "taskRate", ")", "-", "1.0", ")", ")", ";", "}", "long", "partitionStoreTimeRemainingMs", "=", "Long", ".", "MAX_VALUE", ";", "if", "(", "partitionStoreRate", ">", "0", ")", "{", "partitionStoreTimeRemainingMs", "=", "(", "long", ")", "(", "deltaTimeMs", "*", "(", "(", "1.0", "/", "partitionStoreRate", ")", "-", "1.0", ")", ")", ";", "}", "// Title line", "sb", ".", "append", "(", "\"Progress update on rebalancing batch \"", "+", "batchId", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "// Tasks in flight update", "sb", ".", "append", "(", "\"There are currently \"", "+", "tasksInFlight", ".", "size", "(", ")", "+", "\" rebalance tasks executing: \"", ")", ".", "append", "(", "tasksInFlight", ")", ".", "append", "(", "\".\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "// Tasks completed update", "sb", ".", "append", "(", "\"\\t\"", "+", "numTasksCompleted", "+", "\" out of \"", "+", "totalTaskCount", "+", "\" rebalance tasks complete.\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ".", "append", "(", "\"\\t\"", ")", ".", "append", "(", "decimalFormatter", ".", "format", "(", "taskRate", "*", "100.0", ")", ")", ".", "append", "(", "\"% done, estimate \"", ")", ".", "append", "(", "taskTimeRemainingMs", ")", ".", "append", "(", "\" ms (\"", ")", ".", "append", "(", "TimeUnit", ".", "MILLISECONDS", ".", "toMinutes", "(", "taskTimeRemainingMs", ")", ")", ".", "append", "(", "\" minutes) remaining.\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "// Partition-stores migrated update", "sb", ".", "append", "(", "\"\\t\"", "+", "numPartitionStoresMigrated", "+", "\" out of \"", "+", "totalPartitionStoreCount", "+", "\" partition-stores migrated.\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ".", "append", "(", "\"\\t\"", ")", ".", "append", "(", "decimalFormatter", ".", "format", "(", "partitionStoreRate", "*", "100.0", ")", ")", ".", "append", "(", "\"% done, estimate \"", ")", ".", "append", "(", "partitionStoreTimeRemainingMs", ")", ".", "append", "(", "\" ms (\"", ")", ".", "append", "(", "TimeUnit", ".", "MILLISECONDS", ".", "toMinutes", "(", "partitionStoreTimeRemainingMs", ")", ")", ".", "append", "(", "\" minutes) remaining.\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Construct a pretty string documenting progress for this batch plan thus far. @return pretty string documenting progress
[ "Construct", "a", "pretty", "string", "documenting", "progress", "for", "this", "batch", "plan", "thus", "far", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceBatchPlanProgressBar.java#L97-L145
160,912
voldemort/voldemort
src/java/voldemort/server/protocol/admin/FetchStreamRequestHandler.java
FetchStreamRequestHandler.progressInfoMessage
protected void progressInfoMessage(final String tag) { if(logger.isInfoEnabled()) { long totalTimeS = (System.currentTimeMillis() - startTimeMs) / Time.MS_PER_SECOND; logger.info(tag + " : scanned " + scanned + " and fetched " + fetched + " for store '" + storageEngine.getName() + "' partitionIds:" + partitionIds + " in " + totalTimeS + " s"); } }
java
protected void progressInfoMessage(final String tag) { if(logger.isInfoEnabled()) { long totalTimeS = (System.currentTimeMillis() - startTimeMs) / Time.MS_PER_SECOND; logger.info(tag + " : scanned " + scanned + " and fetched " + fetched + " for store '" + storageEngine.getName() + "' partitionIds:" + partitionIds + " in " + totalTimeS + " s"); } }
[ "protected", "void", "progressInfoMessage", "(", "final", "String", "tag", ")", "{", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "long", "totalTimeS", "=", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "startTimeMs", ")", "/", "Time", ".", "MS_PER_SECOND", ";", "logger", ".", "info", "(", "tag", "+", "\" : scanned \"", "+", "scanned", "+", "\" and fetched \"", "+", "fetched", "+", "\" for store '\"", "+", "storageEngine", ".", "getName", "(", ")", "+", "\"' partitionIds:\"", "+", "partitionIds", "+", "\" in \"", "+", "totalTimeS", "+", "\" s\"", ")", ";", "}", "}" ]
Progress info message @param tag Message that precedes progress info. Indicate 'keys' or 'entries'.
[ "Progress", "info", "message" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/FetchStreamRequestHandler.java#L175-L183
160,913
voldemort/voldemort
src/java/voldemort/server/protocol/admin/FetchStreamRequestHandler.java
FetchStreamRequestHandler.sendMessage
protected void sendMessage(DataOutputStream outputStream, Message message) throws IOException { long startNs = System.nanoTime(); ProtoUtils.writeMessage(outputStream, message); if(streamStats != null) { streamStats.reportNetworkTime(operation, Utils.elapsedTimeNs(startNs, System.nanoTime())); } }
java
protected void sendMessage(DataOutputStream outputStream, Message message) throws IOException { long startNs = System.nanoTime(); ProtoUtils.writeMessage(outputStream, message); if(streamStats != null) { streamStats.reportNetworkTime(operation, Utils.elapsedTimeNs(startNs, System.nanoTime())); } }
[ "protected", "void", "sendMessage", "(", "DataOutputStream", "outputStream", ",", "Message", "message", ")", "throws", "IOException", "{", "long", "startNs", "=", "System", ".", "nanoTime", "(", ")", ";", "ProtoUtils", ".", "writeMessage", "(", "outputStream", ",", "message", ")", ";", "if", "(", "streamStats", "!=", "null", ")", "{", "streamStats", ".", "reportNetworkTime", "(", "operation", ",", "Utils", ".", "elapsedTimeNs", "(", "startNs", ",", "System", ".", "nanoTime", "(", ")", ")", ")", ";", "}", "}" ]
Helper method to send message on outputStream and account for network time stats. @param outputStream @param message @throws IOException
[ "Helper", "method", "to", "send", "message", "on", "outputStream", "and", "account", "for", "network", "time", "stats", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/FetchStreamRequestHandler.java#L206-L213
160,914
voldemort/voldemort
src/java/voldemort/server/protocol/admin/FetchStreamRequestHandler.java
FetchStreamRequestHandler.reportStorageOpTime
protected void reportStorageOpTime(long startNs) { if(streamStats != null) { streamStats.reportStreamingScan(operation); streamStats.reportStorageTime(operation, Utils.elapsedTimeNs(startNs, System.nanoTime())); } }
java
protected void reportStorageOpTime(long startNs) { if(streamStats != null) { streamStats.reportStreamingScan(operation); streamStats.reportStorageTime(operation, Utils.elapsedTimeNs(startNs, System.nanoTime())); } }
[ "protected", "void", "reportStorageOpTime", "(", "long", "startNs", ")", "{", "if", "(", "streamStats", "!=", "null", ")", "{", "streamStats", ".", "reportStreamingScan", "(", "operation", ")", ";", "streamStats", ".", "reportStorageTime", "(", "operation", ",", "Utils", ".", "elapsedTimeNs", "(", "startNs", ",", "System", ".", "nanoTime", "(", ")", ")", ")", ";", "}", "}" ]
Helper method to track storage operations & time via StreamingStats. @param startNs
[ "Helper", "method", "to", "track", "storage", "operations", "&", "time", "via", "StreamingStats", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/FetchStreamRequestHandler.java#L220-L226
160,915
voldemort/voldemort
src/java/voldemort/server/socket/SocketServer.java
SocketServer.awaitStartupCompletion
public void awaitStartupCompletion() { try { Object obj = startedStatusQueue.take(); if(obj instanceof Throwable) throw new VoldemortException((Throwable) obj); } catch(InterruptedException e) { // this is okay, if we are interrupted we can stop waiting } }
java
public void awaitStartupCompletion() { try { Object obj = startedStatusQueue.take(); if(obj instanceof Throwable) throw new VoldemortException((Throwable) obj); } catch(InterruptedException e) { // this is okay, if we are interrupted we can stop waiting } }
[ "public", "void", "awaitStartupCompletion", "(", ")", "{", "try", "{", "Object", "obj", "=", "startedStatusQueue", ".", "take", "(", ")", ";", "if", "(", "obj", "instanceof", "Throwable", ")", "throw", "new", "VoldemortException", "(", "(", "Throwable", ")", "obj", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "// this is okay, if we are interrupted we can stop waiting", "}", "}" ]
Blocks until the server has started successfully or an exception is thrown. @throws VoldemortException if a problem occurs during start-up wrapping the original exception.
[ "Blocks", "until", "the", "server", "has", "started", "successfully", "or", "an", "exception", "is", "thrown", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/socket/SocketServer.java#L258-L266
160,916
voldemort/voldemort
src/java/voldemort/client/protocol/admin/StreamingClient.java
StreamingClient.streamingSlopPut
protected synchronized void streamingSlopPut(ByteArray key, Versioned<byte[]> value, String storeName, int failedNodeId) throws IOException { Slop slop = new Slop(storeName, Slop.Operation.PUT, key, value.getValue(), null, failedNodeId, new Date()); ByteArray slopKey = slop.makeKey(); Versioned<byte[]> slopValue = new Versioned<byte[]>(slopSerializer.toBytes(slop), value.getVersion()); Node failedNode = adminClient.getAdminClientCluster().getNodeById(failedNodeId); HandoffToAnyStrategy slopRoutingStrategy = new HandoffToAnyStrategy(adminClient.getAdminClientCluster(), true, failedNode.getZoneId()); // node Id which will receive the slop int slopDestination = slopRoutingStrategy.routeHint(failedNode).get(0).getId(); VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder() .setKey(ProtoUtils.encodeBytes(slopKey)) .setVersioned(ProtoUtils.encodeVersioned(slopValue)) .build(); VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder() .setStore(SLOP_STORE) .setPartitionEntry(partitionEntry); DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair<String, Integer>(SLOP_STORE, slopDestination)); if(nodeIdStoreInitialized.get(new Pair<String, Integer>(SLOP_STORE, slopDestination))) { ProtoUtils.writeMessage(outputStream, updateRequest.build()); } else { ProtoUtils.writeMessage(outputStream, VAdminProto.VoldemortAdminRequest.newBuilder() .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES) .setUpdatePartitionEntries(updateRequest) .build()); outputStream.flush(); nodeIdStoreInitialized.put(new Pair<String, Integer>(SLOP_STORE, slopDestination), true); } throttler.maybeThrottle(1); }
java
protected synchronized void streamingSlopPut(ByteArray key, Versioned<byte[]> value, String storeName, int failedNodeId) throws IOException { Slop slop = new Slop(storeName, Slop.Operation.PUT, key, value.getValue(), null, failedNodeId, new Date()); ByteArray slopKey = slop.makeKey(); Versioned<byte[]> slopValue = new Versioned<byte[]>(slopSerializer.toBytes(slop), value.getVersion()); Node failedNode = adminClient.getAdminClientCluster().getNodeById(failedNodeId); HandoffToAnyStrategy slopRoutingStrategy = new HandoffToAnyStrategy(adminClient.getAdminClientCluster(), true, failedNode.getZoneId()); // node Id which will receive the slop int slopDestination = slopRoutingStrategy.routeHint(failedNode).get(0).getId(); VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder() .setKey(ProtoUtils.encodeBytes(slopKey)) .setVersioned(ProtoUtils.encodeVersioned(slopValue)) .build(); VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder() .setStore(SLOP_STORE) .setPartitionEntry(partitionEntry); DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair<String, Integer>(SLOP_STORE, slopDestination)); if(nodeIdStoreInitialized.get(new Pair<String, Integer>(SLOP_STORE, slopDestination))) { ProtoUtils.writeMessage(outputStream, updateRequest.build()); } else { ProtoUtils.writeMessage(outputStream, VAdminProto.VoldemortAdminRequest.newBuilder() .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES) .setUpdatePartitionEntries(updateRequest) .build()); outputStream.flush(); nodeIdStoreInitialized.put(new Pair<String, Integer>(SLOP_STORE, slopDestination), true); } throttler.maybeThrottle(1); }
[ "protected", "synchronized", "void", "streamingSlopPut", "(", "ByteArray", "key", ",", "Versioned", "<", "byte", "[", "]", ">", "value", ",", "String", "storeName", ",", "int", "failedNodeId", ")", "throws", "IOException", "{", "Slop", "slop", "=", "new", "Slop", "(", "storeName", ",", "Slop", ".", "Operation", ".", "PUT", ",", "key", ",", "value", ".", "getValue", "(", ")", ",", "null", ",", "failedNodeId", ",", "new", "Date", "(", ")", ")", ";", "ByteArray", "slopKey", "=", "slop", ".", "makeKey", "(", ")", ";", "Versioned", "<", "byte", "[", "]", ">", "slopValue", "=", "new", "Versioned", "<", "byte", "[", "]", ">", "(", "slopSerializer", ".", "toBytes", "(", "slop", ")", ",", "value", ".", "getVersion", "(", ")", ")", ";", "Node", "failedNode", "=", "adminClient", ".", "getAdminClientCluster", "(", ")", ".", "getNodeById", "(", "failedNodeId", ")", ";", "HandoffToAnyStrategy", "slopRoutingStrategy", "=", "new", "HandoffToAnyStrategy", "(", "adminClient", ".", "getAdminClientCluster", "(", ")", ",", "true", ",", "failedNode", ".", "getZoneId", "(", ")", ")", ";", "// node Id which will receive the slop", "int", "slopDestination", "=", "slopRoutingStrategy", ".", "routeHint", "(", "failedNode", ")", ".", "get", "(", "0", ")", ".", "getId", "(", ")", ";", "VAdminProto", ".", "PartitionEntry", "partitionEntry", "=", "VAdminProto", ".", "PartitionEntry", ".", "newBuilder", "(", ")", ".", "setKey", "(", "ProtoUtils", ".", "encodeBytes", "(", "slopKey", ")", ")", ".", "setVersioned", "(", "ProtoUtils", ".", "encodeVersioned", "(", "slopValue", ")", ")", ".", "build", "(", ")", ";", "VAdminProto", ".", "UpdatePartitionEntriesRequest", ".", "Builder", "updateRequest", "=", "VAdminProto", ".", "UpdatePartitionEntriesRequest", ".", "newBuilder", "(", ")", ".", "setStore", "(", "SLOP_STORE", ")", ".", "setPartitionEntry", "(", "partitionEntry", ")", ";", "DataOutputStream", "outputStream", "=", "nodeIdStoreToOutputStreamRequest", ".", "get", "(", "new", "Pair", "<", "String", ",", "Integer", ">", "(", "SLOP_STORE", ",", "slopDestination", ")", ")", ";", "if", "(", "nodeIdStoreInitialized", ".", "get", "(", "new", "Pair", "<", "String", ",", "Integer", ">", "(", "SLOP_STORE", ",", "slopDestination", ")", ")", ")", "{", "ProtoUtils", ".", "writeMessage", "(", "outputStream", ",", "updateRequest", ".", "build", "(", ")", ")", ";", "}", "else", "{", "ProtoUtils", ".", "writeMessage", "(", "outputStream", ",", "VAdminProto", ".", "VoldemortAdminRequest", ".", "newBuilder", "(", ")", ".", "setType", "(", "VAdminProto", ".", "AdminRequestType", ".", "UPDATE_PARTITION_ENTRIES", ")", ".", "setUpdatePartitionEntries", "(", "updateRequest", ")", ".", "build", "(", ")", ")", ";", "outputStream", ".", "flush", "(", ")", ";", "nodeIdStoreInitialized", ".", "put", "(", "new", "Pair", "<", "String", ",", "Integer", ">", "(", "SLOP_STORE", ",", "slopDestination", ")", ",", "true", ")", ";", "}", "throttler", ".", "maybeThrottle", "(", "1", ")", ";", "}" ]
This is a method to stream slops to "slop" store when a node is detected faulty in a streaming session @param key -- original key @param value -- original value @param storeName -- the store for which we are registering the slop @param failedNodeId -- the faulty node ID for which we register a slop @throws IOException
[ "This", "is", "a", "method", "to", "stream", "slops", "to", "slop", "store", "when", "a", "node", "is", "detected", "faulty", "in", "a", "streaming", "session" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/StreamingClient.java#L141-L192
160,917
voldemort/voldemort
src/java/voldemort/client/protocol/admin/StreamingClient.java
StreamingClient.synchronousInvokeCallback
@SuppressWarnings("rawtypes") private void synchronousInvokeCallback(Callable call) { Future future = streamingSlopResults.submit(call); try { future.get(); } catch(InterruptedException e1) { logger.error("Callback failed", e1); throw new VoldemortException("Callback failed"); } catch(ExecutionException e1) { logger.error("Callback failed during execution", e1); throw new VoldemortException("Callback failed during execution"); } }
java
@SuppressWarnings("rawtypes") private void synchronousInvokeCallback(Callable call) { Future future = streamingSlopResults.submit(call); try { future.get(); } catch(InterruptedException e1) { logger.error("Callback failed", e1); throw new VoldemortException("Callback failed"); } catch(ExecutionException e1) { logger.error("Callback failed during execution", e1); throw new VoldemortException("Callback failed during execution"); } }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "private", "void", "synchronousInvokeCallback", "(", "Callable", "call", ")", "{", "Future", "future", "=", "streamingSlopResults", ".", "submit", "(", "call", ")", ";", "try", "{", "future", ".", "get", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e1", ")", "{", "logger", ".", "error", "(", "\"Callback failed\"", ",", "e1", ")", ";", "throw", "new", "VoldemortException", "(", "\"Callback failed\"", ")", ";", "}", "catch", "(", "ExecutionException", "e1", ")", "{", "logger", ".", "error", "(", "\"Callback failed during execution\"", ",", "e1", ")", ";", "throw", "new", "VoldemortException", "(", "\"Callback failed during execution\"", ")", ";", "}", "}" ]
Helper method to synchronously invoke a callback @param call
[ "Helper", "method", "to", "synchronously", "invoke", "a", "callback" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/StreamingClient.java#L224-L243
160,918
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/hooks/http/HttpHookRunnable.java
HttpHookRunnable.handleResponse
protected void handleResponse(int responseCode, InputStream inputStream) { BufferedReader rd = null; try { // Buffer the result into a string rd = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder sb = new StringBuilder(); String line; while((line = rd.readLine()) != null) { sb.append(line); } log.info("HttpHook [" + hookName + "] received " + responseCode + " response: " + sb); } catch (IOException e) { log.error("Error while reading response for HttpHook [" + hookName + "]", e); } finally { if (rd != null) { try { rd.close(); } catch (IOException e) { // no-op } } } }
java
protected void handleResponse(int responseCode, InputStream inputStream) { BufferedReader rd = null; try { // Buffer the result into a string rd = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder sb = new StringBuilder(); String line; while((line = rd.readLine()) != null) { sb.append(line); } log.info("HttpHook [" + hookName + "] received " + responseCode + " response: " + sb); } catch (IOException e) { log.error("Error while reading response for HttpHook [" + hookName + "]", e); } finally { if (rd != null) { try { rd.close(); } catch (IOException e) { // no-op } } } }
[ "protected", "void", "handleResponse", "(", "int", "responseCode", ",", "InputStream", "inputStream", ")", "{", "BufferedReader", "rd", "=", "null", ";", "try", "{", "// Buffer the result into a string", "rd", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "inputStream", ")", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "String", "line", ";", "while", "(", "(", "line", "=", "rd", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "sb", ".", "append", "(", "line", ")", ";", "}", "log", ".", "info", "(", "\"HttpHook [\"", "+", "hookName", "+", "\"] received \"", "+", "responseCode", "+", "\" response: \"", "+", "sb", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "log", ".", "error", "(", "\"Error while reading response for HttpHook [\"", "+", "hookName", "+", "\"]\"", ",", "e", ")", ";", "}", "finally", "{", "if", "(", "rd", "!=", "null", ")", "{", "try", "{", "rd", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// no-op", "}", "}", "}", "}" ]
Can be overridden if you want to replace or supplement the debug handling for responses. @param responseCode @param inputStream
[ "Can", "be", "overridden", "if", "you", "want", "to", "replace", "or", "supplement", "the", "debug", "handling", "for", "responses", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/hooks/http/HttpHookRunnable.java#L92-L114
160,919
voldemort/voldemort
src/java/voldemort/client/protocol/admin/BaseStreamingClient.java
BaseStreamingClient.addStoreToSession
@SuppressWarnings({ "unchecked", "rawtypes" }) protected void addStoreToSession(String store) { Exception initializationException = null; storeNames.add(store); for(Node node: nodesToStream) { SocketDestination destination = null; SocketAndStreams sands = null; try { destination = new SocketDestination(node.getHost(), node.getAdminPort(), RequestFormatType.ADMIN_PROTOCOL_BUFFERS); sands = streamingSocketPool.checkout(destination); DataOutputStream outputStream = sands.getOutputStream(); DataInputStream inputStream = sands.getInputStream(); nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination); nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream); nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream); nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands); nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId()) .getValue(); } catch(Exception e) { logger.error(e); try { close(sands.getSocket()); streamingSocketPool.checkin(destination, sands); } catch(Exception ioE) { logger.error(ioE); } if(!faultyNodes.contains(node.getId())) faultyNodes.add(node.getId()); initializationException = e; } } if(initializationException != null) throw new VoldemortException(initializationException); if(store.equals("slop")) return; boolean foundStore = false; for(StoreDefinition remoteStoreDef: remoteStoreDefs) { if(remoteStoreDef.getName().equals(store)) { RoutingStrategyFactory factory = new RoutingStrategyFactory(); RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef, adminClient.getAdminClientCluster()); storeToRoutingStrategy.put(store, storeRoutingStrategy); validateSufficientNodesAvailable(blackListedNodes, remoteStoreDef); foundStore = true; break; } } if(!foundStore) { logger.error("Store Name not found on the cluster"); throw new VoldemortException("Store Name not found on the cluster"); } }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) protected void addStoreToSession(String store) { Exception initializationException = null; storeNames.add(store); for(Node node: nodesToStream) { SocketDestination destination = null; SocketAndStreams sands = null; try { destination = new SocketDestination(node.getHost(), node.getAdminPort(), RequestFormatType.ADMIN_PROTOCOL_BUFFERS); sands = streamingSocketPool.checkout(destination); DataOutputStream outputStream = sands.getOutputStream(); DataInputStream inputStream = sands.getInputStream(); nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination); nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream); nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream); nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands); nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId()) .getValue(); } catch(Exception e) { logger.error(e); try { close(sands.getSocket()); streamingSocketPool.checkin(destination, sands); } catch(Exception ioE) { logger.error(ioE); } if(!faultyNodes.contains(node.getId())) faultyNodes.add(node.getId()); initializationException = e; } } if(initializationException != null) throw new VoldemortException(initializationException); if(store.equals("slop")) return; boolean foundStore = false; for(StoreDefinition remoteStoreDef: remoteStoreDefs) { if(remoteStoreDef.getName().equals(store)) { RoutingStrategyFactory factory = new RoutingStrategyFactory(); RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef, adminClient.getAdminClientCluster()); storeToRoutingStrategy.put(store, storeRoutingStrategy); validateSufficientNodesAvailable(blackListedNodes, remoteStoreDef); foundStore = true; break; } } if(!foundStore) { logger.error("Store Name not found on the cluster"); throw new VoldemortException("Store Name not found on the cluster"); } }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "protected", "void", "addStoreToSession", "(", "String", "store", ")", "{", "Exception", "initializationException", "=", "null", ";", "storeNames", ".", "add", "(", "store", ")", ";", "for", "(", "Node", "node", ":", "nodesToStream", ")", "{", "SocketDestination", "destination", "=", "null", ";", "SocketAndStreams", "sands", "=", "null", ";", "try", "{", "destination", "=", "new", "SocketDestination", "(", "node", ".", "getHost", "(", ")", ",", "node", ".", "getAdminPort", "(", ")", ",", "RequestFormatType", ".", "ADMIN_PROTOCOL_BUFFERS", ")", ";", "sands", "=", "streamingSocketPool", ".", "checkout", "(", "destination", ")", ";", "DataOutputStream", "outputStream", "=", "sands", ".", "getOutputStream", "(", ")", ";", "DataInputStream", "inputStream", "=", "sands", ".", "getInputStream", "(", ")", ";", "nodeIdStoreToSocketRequest", ".", "put", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ",", "destination", ")", ";", "nodeIdStoreToOutputStreamRequest", ".", "put", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ",", "outputStream", ")", ";", "nodeIdStoreToInputStreamRequest", ".", "put", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ",", "inputStream", ")", ";", "nodeIdStoreToSocketAndStreams", ".", "put", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ",", "sands", ")", ";", "nodeIdStoreInitialized", ".", "put", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ",", "false", ")", ";", "remoteStoreDefs", "=", "adminClient", ".", "metadataMgmtOps", ".", "getRemoteStoreDefList", "(", "node", ".", "getId", "(", ")", ")", ".", "getValue", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "e", ")", ";", "try", "{", "close", "(", "sands", ".", "getSocket", "(", ")", ")", ";", "streamingSocketPool", ".", "checkin", "(", "destination", ",", "sands", ")", ";", "}", "catch", "(", "Exception", "ioE", ")", "{", "logger", ".", "error", "(", "ioE", ")", ";", "}", "if", "(", "!", "faultyNodes", ".", "contains", "(", "node", ".", "getId", "(", ")", ")", ")", "faultyNodes", ".", "add", "(", "node", ".", "getId", "(", ")", ")", ";", "initializationException", "=", "e", ";", "}", "}", "if", "(", "initializationException", "!=", "null", ")", "throw", "new", "VoldemortException", "(", "initializationException", ")", ";", "if", "(", "store", ".", "equals", "(", "\"slop\"", ")", ")", "return", ";", "boolean", "foundStore", "=", "false", ";", "for", "(", "StoreDefinition", "remoteStoreDef", ":", "remoteStoreDefs", ")", "{", "if", "(", "remoteStoreDef", ".", "getName", "(", ")", ".", "equals", "(", "store", ")", ")", "{", "RoutingStrategyFactory", "factory", "=", "new", "RoutingStrategyFactory", "(", ")", ";", "RoutingStrategy", "storeRoutingStrategy", "=", "factory", ".", "updateRoutingStrategy", "(", "remoteStoreDef", ",", "adminClient", ".", "getAdminClientCluster", "(", ")", ")", ";", "storeToRoutingStrategy", ".", "put", "(", "store", ",", "storeRoutingStrategy", ")", ";", "validateSufficientNodesAvailable", "(", "blackListedNodes", ",", "remoteStoreDef", ")", ";", "foundStore", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "foundStore", ")", "{", "logger", ".", "error", "(", "\"Store Name not found on the cluster\"", ")", ";", "throw", "new", "VoldemortException", "(", "\"Store Name not found on the cluster\"", ")", ";", "}", "}" ]
Add another store destination to an existing streaming session @param store the name of the store to stream to
[ "Add", "another", "store", "destination", "to", "an", "existing", "streaming", "session" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/BaseStreamingClient.java#L366-L437
160,920
voldemort/voldemort
src/java/voldemort/client/protocol/admin/BaseStreamingClient.java
BaseStreamingClient.removeStoreFromSession
@SuppressWarnings({}) public synchronized void removeStoreFromSession(List<String> storeNameToRemove) { logger.info("closing the Streaming session for a few stores"); commitToVoldemort(storeNameToRemove); cleanupSessions(storeNameToRemove); }
java
@SuppressWarnings({}) public synchronized void removeStoreFromSession(List<String> storeNameToRemove) { logger.info("closing the Streaming session for a few stores"); commitToVoldemort(storeNameToRemove); cleanupSessions(storeNameToRemove); }
[ "@", "SuppressWarnings", "(", "{", "}", ")", "public", "synchronized", "void", "removeStoreFromSession", "(", "List", "<", "String", ">", "storeNameToRemove", ")", "{", "logger", ".", "info", "(", "\"closing the Streaming session for a few stores\"", ")", ";", "commitToVoldemort", "(", "storeNameToRemove", ")", ";", "cleanupSessions", "(", "storeNameToRemove", ")", ";", "}" ]
Remove a list of stores from the session First commit all entries for these stores and then cleanup resources @param storeNameToRemove List of stores to be removed from the current streaming session
[ "Remove", "a", "list", "of", "stores", "from", "the", "session" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/BaseStreamingClient.java#L464-L472
160,921
voldemort/voldemort
src/java/voldemort/client/protocol/admin/BaseStreamingClient.java
BaseStreamingClient.blacklistNode
@SuppressWarnings({ "rawtypes", "unchecked" }) public void blacklistNode(int nodeId) { Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes(); if(blackListedNodes == null) { blackListedNodes = new ArrayList(); } blackListedNodes.add(nodeId); for(Node node: nodesInCluster) { if(node.getId() == nodeId) { nodesToStream.remove(node); break; } } for(String store: storeNames) { try { SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId)); close(sands.getSocket()); SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store, nodeId)); streamingSocketPool.checkin(destination, sands); } catch(Exception ioE) { logger.error(ioE); } } }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void blacklistNode(int nodeId) { Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes(); if(blackListedNodes == null) { blackListedNodes = new ArrayList(); } blackListedNodes.add(nodeId); for(Node node: nodesInCluster) { if(node.getId() == nodeId) { nodesToStream.remove(node); break; } } for(String store: storeNames) { try { SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId)); close(sands.getSocket()); SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store, nodeId)); streamingSocketPool.checkin(destination, sands); } catch(Exception ioE) { logger.error(ioE); } } }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "public", "void", "blacklistNode", "(", "int", "nodeId", ")", "{", "Collection", "<", "Node", ">", "nodesInCluster", "=", "adminClient", ".", "getAdminClientCluster", "(", ")", ".", "getNodes", "(", ")", ";", "if", "(", "blackListedNodes", "==", "null", ")", "{", "blackListedNodes", "=", "new", "ArrayList", "(", ")", ";", "}", "blackListedNodes", ".", "add", "(", "nodeId", ")", ";", "for", "(", "Node", "node", ":", "nodesInCluster", ")", "{", "if", "(", "node", ".", "getId", "(", ")", "==", "nodeId", ")", "{", "nodesToStream", ".", "remove", "(", "node", ")", ";", "break", ";", "}", "}", "for", "(", "String", "store", ":", "storeNames", ")", "{", "try", "{", "SocketAndStreams", "sands", "=", "nodeIdStoreToSocketAndStreams", ".", "get", "(", "new", "Pair", "(", "store", ",", "nodeId", ")", ")", ";", "close", "(", "sands", ".", "getSocket", "(", ")", ")", ";", "SocketDestination", "destination", "=", "nodeIdStoreToSocketRequest", ".", "get", "(", "new", "Pair", "(", "store", ",", "nodeId", ")", ")", ";", "streamingSocketPool", ".", "checkin", "(", "destination", ",", "sands", ")", ";", "}", "catch", "(", "Exception", "ioE", ")", "{", "logger", ".", "error", "(", "ioE", ")", ";", "}", "}", "}" ]
mark a node as blacklisted @param nodeId Integer node id of the node to be blacklisted
[ "mark", "a", "node", "as", "blacklisted" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/BaseStreamingClient.java#L608-L637
160,922
voldemort/voldemort
src/java/voldemort/client/protocol/admin/BaseStreamingClient.java
BaseStreamingClient.commitToVoldemort
@SuppressWarnings({ "unchecked", "rawtypes", "unused" }) private void commitToVoldemort(List<String> storeNamesToCommit) { if(logger.isDebugEnabled()) { logger.debug("Trying to commit to Voldemort"); } boolean hasError = false; if(nodesToStream == null || nodesToStream.size() == 0) { if(logger.isDebugEnabled()) { logger.debug("No nodes to stream to. Returning."); } return; } for(Node node: nodesToStream) { for(String store: storeNamesToCommit) { if(!nodeIdStoreInitialized.get(new Pair(store, node.getId()))) continue; nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(store, node.getId())); try { ProtoUtils.writeEndOfStream(outputStream); outputStream.flush(); DataInputStream inputStream = nodeIdStoreToInputStreamRequest.get(new Pair(store, node.getId())); VAdminProto.UpdatePartitionEntriesResponse.Builder updateResponse = ProtoUtils.readToBuilder(inputStream, VAdminProto.UpdatePartitionEntriesResponse.newBuilder()); if(updateResponse.hasError()) { hasError = true; } } catch(IOException e) { logger.error("Exception during commit", e); hasError = true; if(!faultyNodes.contains(node.getId())) faultyNodes.add(node.getId()); } } } if(streamingresults == null) { logger.warn("StreamingSession may not have been initialized since Variable streamingresults is null. Skipping callback "); return; } // remove redundant callbacks if(hasError) { logger.info("Invoking the Recovery Callback"); Future future = streamingresults.submit(recoveryCallback); try { future.get(); } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed", e1); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed during execution", e1); throw new VoldemortException("Recovery Callback failed during execution"); } } else { if(logger.isDebugEnabled()) { logger.debug("Commit successful"); logger.debug("calling checkpoint callback"); } Future future = streamingresults.submit(checkpointCallback); try { future.get(); } catch(InterruptedException e1) { logger.warn("Checkpoint callback failed!", e1); } catch(ExecutionException e1) { logger.warn("Checkpoint callback failed during execution!", e1); } } }
java
@SuppressWarnings({ "unchecked", "rawtypes", "unused" }) private void commitToVoldemort(List<String> storeNamesToCommit) { if(logger.isDebugEnabled()) { logger.debug("Trying to commit to Voldemort"); } boolean hasError = false; if(nodesToStream == null || nodesToStream.size() == 0) { if(logger.isDebugEnabled()) { logger.debug("No nodes to stream to. Returning."); } return; } for(Node node: nodesToStream) { for(String store: storeNamesToCommit) { if(!nodeIdStoreInitialized.get(new Pair(store, node.getId()))) continue; nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(store, node.getId())); try { ProtoUtils.writeEndOfStream(outputStream); outputStream.flush(); DataInputStream inputStream = nodeIdStoreToInputStreamRequest.get(new Pair(store, node.getId())); VAdminProto.UpdatePartitionEntriesResponse.Builder updateResponse = ProtoUtils.readToBuilder(inputStream, VAdminProto.UpdatePartitionEntriesResponse.newBuilder()); if(updateResponse.hasError()) { hasError = true; } } catch(IOException e) { logger.error("Exception during commit", e); hasError = true; if(!faultyNodes.contains(node.getId())) faultyNodes.add(node.getId()); } } } if(streamingresults == null) { logger.warn("StreamingSession may not have been initialized since Variable streamingresults is null. Skipping callback "); return; } // remove redundant callbacks if(hasError) { logger.info("Invoking the Recovery Callback"); Future future = streamingresults.submit(recoveryCallback); try { future.get(); } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed", e1); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed during execution", e1); throw new VoldemortException("Recovery Callback failed during execution"); } } else { if(logger.isDebugEnabled()) { logger.debug("Commit successful"); logger.debug("calling checkpoint callback"); } Future future = streamingresults.submit(checkpointCallback); try { future.get(); } catch(InterruptedException e1) { logger.warn("Checkpoint callback failed!", e1); } catch(ExecutionException e1) { logger.warn("Checkpoint callback failed during execution!", e1); } } }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", ",", "\"unused\"", "}", ")", "private", "void", "commitToVoldemort", "(", "List", "<", "String", ">", "storeNamesToCommit", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Trying to commit to Voldemort\"", ")", ";", "}", "boolean", "hasError", "=", "false", ";", "if", "(", "nodesToStream", "==", "null", "||", "nodesToStream", ".", "size", "(", ")", "==", "0", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"No nodes to stream to. Returning.\"", ")", ";", "}", "return", ";", "}", "for", "(", "Node", "node", ":", "nodesToStream", ")", "{", "for", "(", "String", "store", ":", "storeNamesToCommit", ")", "{", "if", "(", "!", "nodeIdStoreInitialized", ".", "get", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ")", ")", "continue", ";", "nodeIdStoreInitialized", ".", "put", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ",", "false", ")", ";", "DataOutputStream", "outputStream", "=", "nodeIdStoreToOutputStreamRequest", ".", "get", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ")", ";", "try", "{", "ProtoUtils", ".", "writeEndOfStream", "(", "outputStream", ")", ";", "outputStream", ".", "flush", "(", ")", ";", "DataInputStream", "inputStream", "=", "nodeIdStoreToInputStreamRequest", ".", "get", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ")", ";", "VAdminProto", ".", "UpdatePartitionEntriesResponse", ".", "Builder", "updateResponse", "=", "ProtoUtils", ".", "readToBuilder", "(", "inputStream", ",", "VAdminProto", ".", "UpdatePartitionEntriesResponse", ".", "newBuilder", "(", ")", ")", ";", "if", "(", "updateResponse", ".", "hasError", "(", ")", ")", "{", "hasError", "=", "true", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"Exception during commit\"", ",", "e", ")", ";", "hasError", "=", "true", ";", "if", "(", "!", "faultyNodes", ".", "contains", "(", "node", ".", "getId", "(", ")", ")", ")", "faultyNodes", ".", "add", "(", "node", ".", "getId", "(", ")", ")", ";", "}", "}", "}", "if", "(", "streamingresults", "==", "null", ")", "{", "logger", ".", "warn", "(", "\"StreamingSession may not have been initialized since Variable streamingresults is null. Skipping callback \"", ")", ";", "return", ";", "}", "// remove redundant callbacks", "if", "(", "hasError", ")", "{", "logger", ".", "info", "(", "\"Invoking the Recovery Callback\"", ")", ";", "Future", "future", "=", "streamingresults", ".", "submit", "(", "recoveryCallback", ")", ";", "try", "{", "future", ".", "get", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e1", ")", "{", "MARKED_BAD", "=", "true", ";", "logger", ".", "error", "(", "\"Recovery Callback failed\"", ",", "e1", ")", ";", "throw", "new", "VoldemortException", "(", "\"Recovery Callback failed\"", ")", ";", "}", "catch", "(", "ExecutionException", "e1", ")", "{", "MARKED_BAD", "=", "true", ";", "logger", ".", "error", "(", "\"Recovery Callback failed during execution\"", ",", "e1", ")", ";", "throw", "new", "VoldemortException", "(", "\"Recovery Callback failed during execution\"", ")", ";", "}", "}", "else", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Commit successful\"", ")", ";", "logger", ".", "debug", "(", "\"calling checkpoint callback\"", ")", ";", "}", "Future", "future", "=", "streamingresults", ".", "submit", "(", "checkpointCallback", ")", ";", "try", "{", "future", ".", "get", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e1", ")", "{", "logger", ".", "warn", "(", "\"Checkpoint callback failed!\"", ",", "e1", ")", ";", "}", "catch", "(", "ExecutionException", "e1", ")", "{", "logger", ".", "warn", "(", "\"Checkpoint callback failed during execution!\"", ",", "e1", ")", ";", "}", "}", "}" ]
Flush the network buffer and write all entries to the serve. then wait for an ack from the server. This is a blocking call. It is invoked on every Commit batch size of entries, It is also called on the close session call @param storeNamesToCommit List of stores to be flushed and committed
[ "Flush", "the", "network", "buffer", "and", "write", "all", "entries", "to", "the", "serve", ".", "then", "wait", "for", "an", "ack", "from", "the", "server", ".", "This", "is", "a", "blocking", "call", ".", "It", "is", "invoked", "on", "every", "Commit", "batch", "size", "of", "entries", "It", "is", "also", "called", "on", "the", "close", "session", "call" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/BaseStreamingClient.java#L648-L733
160,923
voldemort/voldemort
src/java/voldemort/client/protocol/admin/BaseStreamingClient.java
BaseStreamingClient.cleanupSessions
@SuppressWarnings({ "rawtypes", "unchecked" }) private void cleanupSessions(List<String> storeNamesToCleanUp) { logger.info("Performing cleanup"); for(String store: storeNamesToCleanUp) { for(Node node: nodesToStream) { try { SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, node.getId())); close(sands.getSocket()); SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store, node.getId())); streamingSocketPool.checkin(destination, sands); } catch(Exception ioE) { logger.error(ioE); } } } cleanedUp = true; }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) private void cleanupSessions(List<String> storeNamesToCleanUp) { logger.info("Performing cleanup"); for(String store: storeNamesToCleanUp) { for(Node node: nodesToStream) { try { SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, node.getId())); close(sands.getSocket()); SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store, node.getId())); streamingSocketPool.checkin(destination, sands); } catch(Exception ioE) { logger.error(ioE); } } } cleanedUp = true; }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "private", "void", "cleanupSessions", "(", "List", "<", "String", ">", "storeNamesToCleanUp", ")", "{", "logger", ".", "info", "(", "\"Performing cleanup\"", ")", ";", "for", "(", "String", "store", ":", "storeNamesToCleanUp", ")", "{", "for", "(", "Node", "node", ":", "nodesToStream", ")", "{", "try", "{", "SocketAndStreams", "sands", "=", "nodeIdStoreToSocketAndStreams", ".", "get", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ")", ";", "close", "(", "sands", ".", "getSocket", "(", ")", ")", ";", "SocketDestination", "destination", "=", "nodeIdStoreToSocketRequest", ".", "get", "(", "new", "Pair", "(", "store", ",", "node", ".", "getId", "(", ")", ")", ")", ";", "streamingSocketPool", ".", "checkin", "(", "destination", ",", "sands", ")", ";", "}", "catch", "(", "Exception", "ioE", ")", "{", "logger", ".", "error", "(", "ioE", ")", ";", "}", "}", "}", "cleanedUp", "=", "true", ";", "}" ]
Helper method to Close all open socket connections and checkin back to the pool @param storeNamesToCleanUp List of stores to be cleanedup from the current streaming session
[ "Helper", "method", "to", "Close", "all", "open", "socket", "connections", "and", "checkin", "back", "to", "the", "pool" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/BaseStreamingClient.java#L787-L810
160,924
voldemort/voldemort
src/java/voldemort/store/InsufficientOperationalNodesException.java
InsufficientOperationalNodesException.stripNodeIds
private static List<Integer> stripNodeIds(List<Node> nodeList) { List<Integer> nodeidList = new ArrayList<Integer>(); if(nodeList != null) { for(Node node: nodeList) { nodeidList.add(node.getId()); } } return nodeidList; }
java
private static List<Integer> stripNodeIds(List<Node> nodeList) { List<Integer> nodeidList = new ArrayList<Integer>(); if(nodeList != null) { for(Node node: nodeList) { nodeidList.add(node.getId()); } } return nodeidList; }
[ "private", "static", "List", "<", "Integer", ">", "stripNodeIds", "(", "List", "<", "Node", ">", "nodeList", ")", "{", "List", "<", "Integer", ">", "nodeidList", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "if", "(", "nodeList", "!=", "null", ")", "{", "for", "(", "Node", "node", ":", "nodeList", ")", "{", "nodeidList", ".", "add", "(", "node", ".", "getId", "(", ")", ")", ";", "}", "}", "return", "nodeidList", ";", "}" ]
Helper method to get a list of node ids. @param nodeList
[ "Helper", "method", "to", "get", "a", "list", "of", "node", "ids", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/InsufficientOperationalNodesException.java#L80-L88
160,925
voldemort/voldemort
src/java/voldemort/store/InsufficientOperationalNodesException.java
InsufficientOperationalNodesException.difference
private static List<Node> difference(List<Node> listA, List<Node> listB) { if(listA != null && listB != null) listA.removeAll(listB); return listA; }
java
private static List<Node> difference(List<Node> listA, List<Node> listB) { if(listA != null && listB != null) listA.removeAll(listB); return listA; }
[ "private", "static", "List", "<", "Node", ">", "difference", "(", "List", "<", "Node", ">", "listA", ",", "List", "<", "Node", ">", "listB", ")", "{", "if", "(", "listA", "!=", "null", "&&", "listB", "!=", "null", ")", "listA", ".", "removeAll", "(", "listB", ")", ";", "return", "listA", ";", "}" ]
Computes A-B @param listA @param listB @return
[ "Computes", "A", "-", "B" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/InsufficientOperationalNodesException.java#L97-L101
160,926
voldemort/voldemort
src/java/voldemort/serialization/avro/versioned/SchemaEvolutionValidator.java
SchemaEvolutionValidator.main
public static void main(String[] args) { if(args.length != 2) { System.out.println("Usage: SchemaEvolutionValidator pathToOldSchema pathToNewSchema"); return; } Schema oldSchema; Schema newSchema; try { oldSchema = Schema.parse(new File(args[0])); } catch(Exception ex) { oldSchema = null; System.out.println("Could not open or parse the old schema (" + args[0] + ") due to " + ex); } try { newSchema = Schema.parse(new File(args[1])); } catch(Exception ex) { newSchema = null; System.out.println("Could not open or parse the new schema (" + args[1] + ") due to " + ex); } if(oldSchema == null || newSchema == null) { return; } System.out.println("Comparing: "); System.out.println("\t" + args[0]); System.out.println("\t" + args[1]); List<Message> messages = SchemaEvolutionValidator.checkBackwardCompatibility(oldSchema, newSchema, oldSchema.getName()); Level maxLevel = Level.ALL; for(Message message: messages) { System.out.println(message.getLevel() + ": " + message.getMessage()); if(message.getLevel().isGreaterOrEqual(maxLevel)) { maxLevel = message.getLevel(); } } if(maxLevel.isGreaterOrEqual(Level.ERROR)) { System.out.println(Level.ERROR + ": The schema is not backward compatible. New clients will not be able to read existing data."); } else if(maxLevel.isGreaterOrEqual(Level.WARN)) { System.out.println(Level.WARN + ": The schema is partially backward compatible, but old clients will not be able to read data serialized in the new format."); } else { System.out.println(Level.INFO + ": The schema is backward compatible. Old and new clients will be able to read records serialized by one another."); } }
java
public static void main(String[] args) { if(args.length != 2) { System.out.println("Usage: SchemaEvolutionValidator pathToOldSchema pathToNewSchema"); return; } Schema oldSchema; Schema newSchema; try { oldSchema = Schema.parse(new File(args[0])); } catch(Exception ex) { oldSchema = null; System.out.println("Could not open or parse the old schema (" + args[0] + ") due to " + ex); } try { newSchema = Schema.parse(new File(args[1])); } catch(Exception ex) { newSchema = null; System.out.println("Could not open or parse the new schema (" + args[1] + ") due to " + ex); } if(oldSchema == null || newSchema == null) { return; } System.out.println("Comparing: "); System.out.println("\t" + args[0]); System.out.println("\t" + args[1]); List<Message> messages = SchemaEvolutionValidator.checkBackwardCompatibility(oldSchema, newSchema, oldSchema.getName()); Level maxLevel = Level.ALL; for(Message message: messages) { System.out.println(message.getLevel() + ": " + message.getMessage()); if(message.getLevel().isGreaterOrEqual(maxLevel)) { maxLevel = message.getLevel(); } } if(maxLevel.isGreaterOrEqual(Level.ERROR)) { System.out.println(Level.ERROR + ": The schema is not backward compatible. New clients will not be able to read existing data."); } else if(maxLevel.isGreaterOrEqual(Level.WARN)) { System.out.println(Level.WARN + ": The schema is partially backward compatible, but old clients will not be able to read data serialized in the new format."); } else { System.out.println(Level.INFO + ": The schema is backward compatible. Old and new clients will be able to read records serialized by one another."); } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", "!=", "2", ")", "{", "System", ".", "out", ".", "println", "(", "\"Usage: SchemaEvolutionValidator pathToOldSchema pathToNewSchema\"", ")", ";", "return", ";", "}", "Schema", "oldSchema", ";", "Schema", "newSchema", ";", "try", "{", "oldSchema", "=", "Schema", ".", "parse", "(", "new", "File", "(", "args", "[", "0", "]", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "oldSchema", "=", "null", ";", "System", ".", "out", ".", "println", "(", "\"Could not open or parse the old schema (\"", "+", "args", "[", "0", "]", "+", "\") due to \"", "+", "ex", ")", ";", "}", "try", "{", "newSchema", "=", "Schema", ".", "parse", "(", "new", "File", "(", "args", "[", "1", "]", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "newSchema", "=", "null", ";", "System", ".", "out", ".", "println", "(", "\"Could not open or parse the new schema (\"", "+", "args", "[", "1", "]", "+", "\") due to \"", "+", "ex", ")", ";", "}", "if", "(", "oldSchema", "==", "null", "||", "newSchema", "==", "null", ")", "{", "return", ";", "}", "System", ".", "out", ".", "println", "(", "\"Comparing: \"", ")", ";", "System", ".", "out", ".", "println", "(", "\"\\t\"", "+", "args", "[", "0", "]", ")", ";", "System", ".", "out", ".", "println", "(", "\"\\t\"", "+", "args", "[", "1", "]", ")", ";", "List", "<", "Message", ">", "messages", "=", "SchemaEvolutionValidator", ".", "checkBackwardCompatibility", "(", "oldSchema", ",", "newSchema", ",", "oldSchema", ".", "getName", "(", ")", ")", ";", "Level", "maxLevel", "=", "Level", ".", "ALL", ";", "for", "(", "Message", "message", ":", "messages", ")", "{", "System", ".", "out", ".", "println", "(", "message", ".", "getLevel", "(", ")", "+", "\": \"", "+", "message", ".", "getMessage", "(", ")", ")", ";", "if", "(", "message", ".", "getLevel", "(", ")", ".", "isGreaterOrEqual", "(", "maxLevel", ")", ")", "{", "maxLevel", "=", "message", ".", "getLevel", "(", ")", ";", "}", "}", "if", "(", "maxLevel", ".", "isGreaterOrEqual", "(", "Level", ".", "ERROR", ")", ")", "{", "System", ".", "out", ".", "println", "(", "Level", ".", "ERROR", "+", "\": The schema is not backward compatible. New clients will not be able to read existing data.\"", ")", ";", "}", "else", "if", "(", "maxLevel", ".", "isGreaterOrEqual", "(", "Level", ".", "WARN", ")", ")", "{", "System", ".", "out", ".", "println", "(", "Level", ".", "WARN", "+", "\": The schema is partially backward compatible, but old clients will not be able to read data serialized in the new format.\"", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "Level", ".", "INFO", "+", "\": The schema is backward compatible. Old and new clients will be able to read records serialized by one another.\"", ")", ";", "}", "}" ]
This main method provides an easy command line tool to compare two schemas.
[ "This", "main", "method", "provides", "an", "easy", "command", "line", "tool", "to", "compare", "two", "schemas", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/serialization/avro/versioned/SchemaEvolutionValidator.java#L51-L105
160,927
voldemort/voldemort
src/java/voldemort/serialization/avro/versioned/SchemaEvolutionValidator.java
SchemaEvolutionValidator.validateAllAvroSchemas
public static void validateAllAvroSchemas(SerializerDefinition avroSerDef) { Map<Integer, String> schemaVersions = avroSerDef.getAllSchemaInfoVersions(); if(schemaVersions.size() < 1) { throw new VoldemortException("No schema specified"); } for(Map.Entry<Integer, String> entry: schemaVersions.entrySet()) { Integer schemaVersionNumber = entry.getKey(); String schemaStr = entry.getValue(); try { Schema.parse(schemaStr); } catch(Exception e) { throw new VoldemortException("Unable to parse Avro schema version :" + schemaVersionNumber + ", schema string :" + schemaStr); } } }
java
public static void validateAllAvroSchemas(SerializerDefinition avroSerDef) { Map<Integer, String> schemaVersions = avroSerDef.getAllSchemaInfoVersions(); if(schemaVersions.size() < 1) { throw new VoldemortException("No schema specified"); } for(Map.Entry<Integer, String> entry: schemaVersions.entrySet()) { Integer schemaVersionNumber = entry.getKey(); String schemaStr = entry.getValue(); try { Schema.parse(schemaStr); } catch(Exception e) { throw new VoldemortException("Unable to parse Avro schema version :" + schemaVersionNumber + ", schema string :" + schemaStr); } } }
[ "public", "static", "void", "validateAllAvroSchemas", "(", "SerializerDefinition", "avroSerDef", ")", "{", "Map", "<", "Integer", ",", "String", ">", "schemaVersions", "=", "avroSerDef", ".", "getAllSchemaInfoVersions", "(", ")", ";", "if", "(", "schemaVersions", ".", "size", "(", ")", "<", "1", ")", "{", "throw", "new", "VoldemortException", "(", "\"No schema specified\"", ")", ";", "}", "for", "(", "Map", ".", "Entry", "<", "Integer", ",", "String", ">", "entry", ":", "schemaVersions", ".", "entrySet", "(", ")", ")", "{", "Integer", "schemaVersionNumber", "=", "entry", ".", "getKey", "(", ")", ";", "String", "schemaStr", "=", "entry", ".", "getValue", "(", ")", ";", "try", "{", "Schema", ".", "parse", "(", "schemaStr", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "VoldemortException", "(", "\"Unable to parse Avro schema version :\"", "+", "schemaVersionNumber", "+", "\", schema string :\"", "+", "schemaStr", ")", ";", "}", "}", "}" ]
Given an AVRO serializer definition, validates if all the avro schemas are valid i.e parseable. @param avroSerDef
[ "Given", "an", "AVRO", "serializer", "definition", "validates", "if", "all", "the", "avro", "schemas", "are", "valid", "i", ".", "e", "parseable", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/serialization/avro/versioned/SchemaEvolutionValidator.java#L826-L842
160,928
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/AbstractStoreBuilderConfigurable.java
AbstractStoreBuilderConfigurable.getPartition
public int getPartition(byte[] key, byte[] value, int numReduceTasks) { try { /** * {@link partitionId} is the Voldemort primary partition that this * record belongs to. */ int partitionId = ByteUtils.readInt(value, ByteUtils.SIZE_OF_INT); /** * This is the base number we will ultimately mod by {@link numReduceTasks} * to determine which reduce task to shuffle to. */ int magicNumber = partitionId; if (getSaveKeys() && !buildPrimaryReplicasOnly) { /** * When saveKeys is enabled (which also implies we are generating * READ_ONLY_V2 format files), then we are generating files with * a replica type, with one file per replica. * * Each replica is sent to a different reducer, and thus the * {@link magicNumber} is scaled accordingly. * * The downside to this is that it is pretty wasteful. The files * generated for each replicas are identical to one another, so * there's no point in generating them independently in many * reducers. * * This is one of the reasons why buildPrimaryReplicasOnly was * written. In this mode, we only generate the files for the * primary replica, which means the number of reducers is * minimized and {@link magicNumber} does not need to be scaled. */ int replicaType = (int) ByteUtils.readBytes(value, 2 * ByteUtils.SIZE_OF_INT, ByteUtils.SIZE_OF_BYTE); magicNumber = magicNumber * getStoreDef().getReplicationFactor() + replicaType; } if (!getReducerPerBucket()) { /** * Partition files can be split in many chunks in order to limit the * maximum file size downloaded and handled by Voldemort servers. * * {@link chunkId} represents which chunk of partition then current * record belongs to. */ int chunkId = ReadOnlyUtils.chunk(key, getNumChunks()); /** * When reducerPerBucket is disabled, all chunks are sent to a * different reducer. This increases parallelism at the expense * of adding more load on Hadoop. * * {@link magicNumber} is thus scaled accordingly, in order to * leverage the extra reducers available to us. */ magicNumber = magicNumber * getNumChunks() + chunkId; } /** * Finally, we mod {@link magicNumber} by {@link numReduceTasks}, * since the MapReduce framework expects the return of this function * to be bounded by the number of reduce tasks running in the job. */ return magicNumber % numReduceTasks; } catch (Exception e) { throw new VoldemortException("Caught exception in getPartition()!" + " key: " + ByteUtils.toHexString(key) + ", value: " + ByteUtils.toHexString(value) + ", numReduceTasks: " + numReduceTasks, e); } }
java
public int getPartition(byte[] key, byte[] value, int numReduceTasks) { try { /** * {@link partitionId} is the Voldemort primary partition that this * record belongs to. */ int partitionId = ByteUtils.readInt(value, ByteUtils.SIZE_OF_INT); /** * This is the base number we will ultimately mod by {@link numReduceTasks} * to determine which reduce task to shuffle to. */ int magicNumber = partitionId; if (getSaveKeys() && !buildPrimaryReplicasOnly) { /** * When saveKeys is enabled (which also implies we are generating * READ_ONLY_V2 format files), then we are generating files with * a replica type, with one file per replica. * * Each replica is sent to a different reducer, and thus the * {@link magicNumber} is scaled accordingly. * * The downside to this is that it is pretty wasteful. The files * generated for each replicas are identical to one another, so * there's no point in generating them independently in many * reducers. * * This is one of the reasons why buildPrimaryReplicasOnly was * written. In this mode, we only generate the files for the * primary replica, which means the number of reducers is * minimized and {@link magicNumber} does not need to be scaled. */ int replicaType = (int) ByteUtils.readBytes(value, 2 * ByteUtils.SIZE_OF_INT, ByteUtils.SIZE_OF_BYTE); magicNumber = magicNumber * getStoreDef().getReplicationFactor() + replicaType; } if (!getReducerPerBucket()) { /** * Partition files can be split in many chunks in order to limit the * maximum file size downloaded and handled by Voldemort servers. * * {@link chunkId} represents which chunk of partition then current * record belongs to. */ int chunkId = ReadOnlyUtils.chunk(key, getNumChunks()); /** * When reducerPerBucket is disabled, all chunks are sent to a * different reducer. This increases parallelism at the expense * of adding more load on Hadoop. * * {@link magicNumber} is thus scaled accordingly, in order to * leverage the extra reducers available to us. */ magicNumber = magicNumber * getNumChunks() + chunkId; } /** * Finally, we mod {@link magicNumber} by {@link numReduceTasks}, * since the MapReduce framework expects the return of this function * to be bounded by the number of reduce tasks running in the job. */ return magicNumber % numReduceTasks; } catch (Exception e) { throw new VoldemortException("Caught exception in getPartition()!" + " key: " + ByteUtils.toHexString(key) + ", value: " + ByteUtils.toHexString(value) + ", numReduceTasks: " + numReduceTasks, e); } }
[ "public", "int", "getPartition", "(", "byte", "[", "]", "key", ",", "byte", "[", "]", "value", ",", "int", "numReduceTasks", ")", "{", "try", "{", "/**\n * {@link partitionId} is the Voldemort primary partition that this\n * record belongs to.\n */", "int", "partitionId", "=", "ByteUtils", ".", "readInt", "(", "value", ",", "ByteUtils", ".", "SIZE_OF_INT", ")", ";", "/**\n * This is the base number we will ultimately mod by {@link numReduceTasks}\n * to determine which reduce task to shuffle to.\n */", "int", "magicNumber", "=", "partitionId", ";", "if", "(", "getSaveKeys", "(", ")", "&&", "!", "buildPrimaryReplicasOnly", ")", "{", "/**\n * When saveKeys is enabled (which also implies we are generating\n * READ_ONLY_V2 format files), then we are generating files with\n * a replica type, with one file per replica.\n *\n * Each replica is sent to a different reducer, and thus the\n * {@link magicNumber} is scaled accordingly.\n *\n * The downside to this is that it is pretty wasteful. The files\n * generated for each replicas are identical to one another, so\n * there's no point in generating them independently in many\n * reducers.\n *\n * This is one of the reasons why buildPrimaryReplicasOnly was\n * written. In this mode, we only generate the files for the\n * primary replica, which means the number of reducers is\n * minimized and {@link magicNumber} does not need to be scaled.\n */", "int", "replicaType", "=", "(", "int", ")", "ByteUtils", ".", "readBytes", "(", "value", ",", "2", "*", "ByteUtils", ".", "SIZE_OF_INT", ",", "ByteUtils", ".", "SIZE_OF_BYTE", ")", ";", "magicNumber", "=", "magicNumber", "*", "getStoreDef", "(", ")", ".", "getReplicationFactor", "(", ")", "+", "replicaType", ";", "}", "if", "(", "!", "getReducerPerBucket", "(", ")", ")", "{", "/**\n * Partition files can be split in many chunks in order to limit the\n * maximum file size downloaded and handled by Voldemort servers.\n *\n * {@link chunkId} represents which chunk of partition then current\n * record belongs to.\n */", "int", "chunkId", "=", "ReadOnlyUtils", ".", "chunk", "(", "key", ",", "getNumChunks", "(", ")", ")", ";", "/**\n * When reducerPerBucket is disabled, all chunks are sent to a\n * different reducer. This increases parallelism at the expense\n * of adding more load on Hadoop.\n *\n * {@link magicNumber} is thus scaled accordingly, in order to\n * leverage the extra reducers available to us.\n */", "magicNumber", "=", "magicNumber", "*", "getNumChunks", "(", ")", "+", "chunkId", ";", "}", "/**\n * Finally, we mod {@link magicNumber} by {@link numReduceTasks},\n * since the MapReduce framework expects the return of this function\n * to be bounded by the number of reduce tasks running in the job.\n */", "return", "magicNumber", "%", "numReduceTasks", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "VoldemortException", "(", "\"Caught exception in getPartition()!\"", "+", "\" key: \"", "+", "ByteUtils", ".", "toHexString", "(", "key", ")", "+", "\", value: \"", "+", "ByteUtils", ".", "toHexString", "(", "value", ")", "+", "\", numReduceTasks: \"", "+", "numReduceTasks", ",", "e", ")", ";", "}", "}" ]
This function computes which reduce task to shuffle a record to.
[ "This", "function", "computes", "which", "reduce", "task", "to", "shuffle", "a", "record", "to", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/AbstractStoreBuilderConfigurable.java#L114-L188
160,929
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/disk/HadoopStoreWriter.java
HadoopStoreWriter.initFileStreams
@NotThreadsafe private void initFileStreams(int chunkId) { /** * {@link Set#add(Object)} returns false if the element already existed in the set. * This ensures we initialize the resources for each chunk only once. */ if (chunksHandled.add(chunkId)) { try { this.indexFileSizeInBytes[chunkId] = 0L; this.valueFileSizeInBytes[chunkId] = 0L; this.checkSumDigestIndex[chunkId] = CheckSum.getInstance(checkSumType); this.checkSumDigestValue[chunkId] = CheckSum.getInstance(checkSumType); this.position[chunkId] = 0; this.taskIndexFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf), getStoreName() + "." + Integer.toString(chunkId) + "_" + this.taskId + INDEX_FILE_EXTENSION + fileExtension); this.taskValueFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf), getStoreName() + "." + Integer.toString(chunkId) + "_" + this.taskId + DATA_FILE_EXTENSION + fileExtension); if(this.fs == null) this.fs = this.taskIndexFileName[chunkId].getFileSystem(conf); if(isValidCompressionEnabled) { this.indexFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskIndexFileName[chunkId]), DEFAULT_BUFFER_SIZE))); this.valueFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskValueFileName[chunkId]), DEFAULT_BUFFER_SIZE))); } else { this.indexFileStream[chunkId] = fs.create(this.taskIndexFileName[chunkId]); this.valueFileStream[chunkId] = fs.create(this.taskValueFileName[chunkId]); } fs.setPermission(this.taskIndexFileName[chunkId], new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION)); logger.info("Setting permission to 755 for " + this.taskIndexFileName[chunkId]); fs.setPermission(this.taskValueFileName[chunkId], new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION)); logger.info("Setting permission to 755 for " + this.taskValueFileName[chunkId]); logger.info("Opening " + this.taskIndexFileName[chunkId] + " and " + this.taskValueFileName[chunkId] + " for writing."); } catch(IOException e) { throw new RuntimeException("Failed to open Input/OutputStream", e); } } }
java
@NotThreadsafe private void initFileStreams(int chunkId) { /** * {@link Set#add(Object)} returns false if the element already existed in the set. * This ensures we initialize the resources for each chunk only once. */ if (chunksHandled.add(chunkId)) { try { this.indexFileSizeInBytes[chunkId] = 0L; this.valueFileSizeInBytes[chunkId] = 0L; this.checkSumDigestIndex[chunkId] = CheckSum.getInstance(checkSumType); this.checkSumDigestValue[chunkId] = CheckSum.getInstance(checkSumType); this.position[chunkId] = 0; this.taskIndexFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf), getStoreName() + "." + Integer.toString(chunkId) + "_" + this.taskId + INDEX_FILE_EXTENSION + fileExtension); this.taskValueFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf), getStoreName() + "." + Integer.toString(chunkId) + "_" + this.taskId + DATA_FILE_EXTENSION + fileExtension); if(this.fs == null) this.fs = this.taskIndexFileName[chunkId].getFileSystem(conf); if(isValidCompressionEnabled) { this.indexFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskIndexFileName[chunkId]), DEFAULT_BUFFER_SIZE))); this.valueFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskValueFileName[chunkId]), DEFAULT_BUFFER_SIZE))); } else { this.indexFileStream[chunkId] = fs.create(this.taskIndexFileName[chunkId]); this.valueFileStream[chunkId] = fs.create(this.taskValueFileName[chunkId]); } fs.setPermission(this.taskIndexFileName[chunkId], new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION)); logger.info("Setting permission to 755 for " + this.taskIndexFileName[chunkId]); fs.setPermission(this.taskValueFileName[chunkId], new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION)); logger.info("Setting permission to 755 for " + this.taskValueFileName[chunkId]); logger.info("Opening " + this.taskIndexFileName[chunkId] + " and " + this.taskValueFileName[chunkId] + " for writing."); } catch(IOException e) { throw new RuntimeException("Failed to open Input/OutputStream", e); } } }
[ "@", "NotThreadsafe", "private", "void", "initFileStreams", "(", "int", "chunkId", ")", "{", "/**\n * {@link Set#add(Object)} returns false if the element already existed in the set.\n * This ensures we initialize the resources for each chunk only once.\n */", "if", "(", "chunksHandled", ".", "add", "(", "chunkId", ")", ")", "{", "try", "{", "this", ".", "indexFileSizeInBytes", "[", "chunkId", "]", "=", "0L", ";", "this", ".", "valueFileSizeInBytes", "[", "chunkId", "]", "=", "0L", ";", "this", ".", "checkSumDigestIndex", "[", "chunkId", "]", "=", "CheckSum", ".", "getInstance", "(", "checkSumType", ")", ";", "this", ".", "checkSumDigestValue", "[", "chunkId", "]", "=", "CheckSum", ".", "getInstance", "(", "checkSumType", ")", ";", "this", ".", "position", "[", "chunkId", "]", "=", "0", ";", "this", ".", "taskIndexFileName", "[", "chunkId", "]", "=", "new", "Path", "(", "FileOutputFormat", ".", "getOutputPath", "(", "conf", ")", ",", "getStoreName", "(", ")", "+", "\".\"", "+", "Integer", ".", "toString", "(", "chunkId", ")", "+", "\"_\"", "+", "this", ".", "taskId", "+", "INDEX_FILE_EXTENSION", "+", "fileExtension", ")", ";", "this", ".", "taskValueFileName", "[", "chunkId", "]", "=", "new", "Path", "(", "FileOutputFormat", ".", "getOutputPath", "(", "conf", ")", ",", "getStoreName", "(", ")", "+", "\".\"", "+", "Integer", ".", "toString", "(", "chunkId", ")", "+", "\"_\"", "+", "this", ".", "taskId", "+", "DATA_FILE_EXTENSION", "+", "fileExtension", ")", ";", "if", "(", "this", ".", "fs", "==", "null", ")", "this", ".", "fs", "=", "this", ".", "taskIndexFileName", "[", "chunkId", "]", ".", "getFileSystem", "(", "conf", ")", ";", "if", "(", "isValidCompressionEnabled", ")", "{", "this", ".", "indexFileStream", "[", "chunkId", "]", "=", "new", "DataOutputStream", "(", "new", "BufferedOutputStream", "(", "new", "GZIPOutputStream", "(", "fs", ".", "create", "(", "this", ".", "taskIndexFileName", "[", "chunkId", "]", ")", ",", "DEFAULT_BUFFER_SIZE", ")", ")", ")", ";", "this", ".", "valueFileStream", "[", "chunkId", "]", "=", "new", "DataOutputStream", "(", "new", "BufferedOutputStream", "(", "new", "GZIPOutputStream", "(", "fs", ".", "create", "(", "this", ".", "taskValueFileName", "[", "chunkId", "]", ")", ",", "DEFAULT_BUFFER_SIZE", ")", ")", ")", ";", "}", "else", "{", "this", ".", "indexFileStream", "[", "chunkId", "]", "=", "fs", ".", "create", "(", "this", ".", "taskIndexFileName", "[", "chunkId", "]", ")", ";", "this", ".", "valueFileStream", "[", "chunkId", "]", "=", "fs", ".", "create", "(", "this", ".", "taskValueFileName", "[", "chunkId", "]", ")", ";", "}", "fs", ".", "setPermission", "(", "this", ".", "taskIndexFileName", "[", "chunkId", "]", ",", "new", "FsPermission", "(", "HadoopStoreBuilder", ".", "HADOOP_FILE_PERMISSION", ")", ")", ";", "logger", ".", "info", "(", "\"Setting permission to 755 for \"", "+", "this", ".", "taskIndexFileName", "[", "chunkId", "]", ")", ";", "fs", ".", "setPermission", "(", "this", ".", "taskValueFileName", "[", "chunkId", "]", ",", "new", "FsPermission", "(", "HadoopStoreBuilder", ".", "HADOOP_FILE_PERMISSION", ")", ")", ";", "logger", ".", "info", "(", "\"Setting permission to 755 for \"", "+", "this", ".", "taskValueFileName", "[", "chunkId", "]", ")", ";", "logger", ".", "info", "(", "\"Opening \"", "+", "this", ".", "taskIndexFileName", "[", "chunkId", "]", "+", "\" and \"", "+", "this", ".", "taskValueFileName", "[", "chunkId", "]", "+", "\" for writing.\"", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to open Input/OutputStream\"", ",", "e", ")", ";", "}", "}", "}" ]
The MapReduce framework should operate sequentially, so thread safety shouldn't be a problem.
[ "The", "MapReduce", "framework", "should", "operate", "sequentially", "so", "thread", "safety", "shouldn", "t", "be", "a", "problem", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/disk/HadoopStoreWriter.java#L155-L204
160,930
voldemort/voldemort
src/java/voldemort/rest/RestGetRequestValidator.java
RestGetRequestValidator.parseAndValidateRequest
@Override public boolean parseAndValidateRequest() { if(!super.parseAndValidateRequest()) { return false; } isGetVersionRequest = hasGetVersionRequestHeader(); if(isGetVersionRequest && this.parsedKeys.size() > 1) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Get version request cannot have multiple keys"); return false; } return true; }
java
@Override public boolean parseAndValidateRequest() { if(!super.parseAndValidateRequest()) { return false; } isGetVersionRequest = hasGetVersionRequestHeader(); if(isGetVersionRequest && this.parsedKeys.size() > 1) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Get version request cannot have multiple keys"); return false; } return true; }
[ "@", "Override", "public", "boolean", "parseAndValidateRequest", "(", ")", "{", "if", "(", "!", "super", ".", "parseAndValidateRequest", "(", ")", ")", "{", "return", "false", ";", "}", "isGetVersionRequest", "=", "hasGetVersionRequestHeader", "(", ")", ";", "if", "(", "isGetVersionRequest", "&&", "this", ".", "parsedKeys", ".", "size", "(", ")", ">", "1", ")", "{", "RestErrorHandler", ".", "writeErrorResponse", "(", "messageEvent", ",", "HttpResponseStatus", ".", "BAD_REQUEST", ",", "\"Get version request cannot have multiple keys\"", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Validations specific to GET and GET ALL
[ "Validations", "specific", "to", "GET", "and", "GET", "ALL" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestGetRequestValidator.java#L31-L44
160,931
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/utils/HadoopUtils.java
HadoopUtils.getMetadataFromSequenceFile
public static Map<String, String> getMetadataFromSequenceFile(FileSystem fs, Path path) { try { Configuration conf = new Configuration(); conf.setInt("io.file.buffer.size", 4096); SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, new Configuration()); SequenceFile.Metadata meta = reader.getMetadata(); reader.close(); TreeMap<Text, Text> map = meta.getMetadata(); Map<String, String> values = new HashMap<String, String>(); for(Map.Entry<Text, Text> entry: map.entrySet()) values.put(entry.getKey().toString(), entry.getValue().toString()); return values; } catch(IOException e) { throw new RuntimeException(e); } }
java
public static Map<String, String> getMetadataFromSequenceFile(FileSystem fs, Path path) { try { Configuration conf = new Configuration(); conf.setInt("io.file.buffer.size", 4096); SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, new Configuration()); SequenceFile.Metadata meta = reader.getMetadata(); reader.close(); TreeMap<Text, Text> map = meta.getMetadata(); Map<String, String> values = new HashMap<String, String>(); for(Map.Entry<Text, Text> entry: map.entrySet()) values.put(entry.getKey().toString(), entry.getValue().toString()); return values; } catch(IOException e) { throw new RuntimeException(e); } }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "getMetadataFromSequenceFile", "(", "FileSystem", "fs", ",", "Path", "path", ")", "{", "try", "{", "Configuration", "conf", "=", "new", "Configuration", "(", ")", ";", "conf", ".", "setInt", "(", "\"io.file.buffer.size\"", ",", "4096", ")", ";", "SequenceFile", ".", "Reader", "reader", "=", "new", "SequenceFile", ".", "Reader", "(", "fs", ",", "path", ",", "new", "Configuration", "(", ")", ")", ";", "SequenceFile", ".", "Metadata", "meta", "=", "reader", ".", "getMetadata", "(", ")", ";", "reader", ".", "close", "(", ")", ";", "TreeMap", "<", "Text", ",", "Text", ">", "map", "=", "meta", ".", "getMetadata", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "values", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "Text", ",", "Text", ">", "entry", ":", "map", ".", "entrySet", "(", ")", ")", "values", ".", "put", "(", "entry", ".", "getKey", "(", ")", ".", "toString", "(", ")", ",", "entry", ".", "getValue", "(", ")", ".", "toString", "(", ")", ")", ";", "return", "values", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Read the metadata from a hadoop SequenceFile @param fs The filesystem to read from @param path The file to read from @return The metadata from this file
[ "Read", "the", "metadata", "from", "a", "hadoop", "SequenceFile" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/utils/HadoopUtils.java#L79-L95
160,932
voldemort/voldemort
src/java/voldemort/store/bdb/BdbNativeBackup.java
BdbNativeBackup.recordBackupSet
private void recordBackupSet(File backupDir) throws IOException { String[] filesInEnv = env.getHome().list(); SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_kk_mm_ss"); String recordFileName = "backupset-" + format.format(new Date()); File recordFile = new File(backupDir, recordFileName); if(recordFile.exists()) { recordFile.renameTo(new File(backupDir, recordFileName + ".old")); } PrintStream backupRecord = new PrintStream(new FileOutputStream(recordFile)); backupRecord.println("Lastfile:" + Long.toHexString(backupHelper.getLastFileInBackupSet())); if(filesInEnv != null) { for(String file: filesInEnv) { if(file.endsWith(BDB_EXT)) backupRecord.println(file); } } backupRecord.close(); }
java
private void recordBackupSet(File backupDir) throws IOException { String[] filesInEnv = env.getHome().list(); SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_kk_mm_ss"); String recordFileName = "backupset-" + format.format(new Date()); File recordFile = new File(backupDir, recordFileName); if(recordFile.exists()) { recordFile.renameTo(new File(backupDir, recordFileName + ".old")); } PrintStream backupRecord = new PrintStream(new FileOutputStream(recordFile)); backupRecord.println("Lastfile:" + Long.toHexString(backupHelper.getLastFileInBackupSet())); if(filesInEnv != null) { for(String file: filesInEnv) { if(file.endsWith(BDB_EXT)) backupRecord.println(file); } } backupRecord.close(); }
[ "private", "void", "recordBackupSet", "(", "File", "backupDir", ")", "throws", "IOException", "{", "String", "[", "]", "filesInEnv", "=", "env", ".", "getHome", "(", ")", ".", "list", "(", ")", ";", "SimpleDateFormat", "format", "=", "new", "SimpleDateFormat", "(", "\"yyyy_MM_dd_kk_mm_ss\"", ")", ";", "String", "recordFileName", "=", "\"backupset-\"", "+", "format", ".", "format", "(", "new", "Date", "(", ")", ")", ";", "File", "recordFile", "=", "new", "File", "(", "backupDir", ",", "recordFileName", ")", ";", "if", "(", "recordFile", ".", "exists", "(", ")", ")", "{", "recordFile", ".", "renameTo", "(", "new", "File", "(", "backupDir", ",", "recordFileName", "+", "\".old\"", ")", ")", ";", "}", "PrintStream", "backupRecord", "=", "new", "PrintStream", "(", "new", "FileOutputStream", "(", "recordFile", ")", ")", ";", "backupRecord", ".", "println", "(", "\"Lastfile:\"", "+", "Long", ".", "toHexString", "(", "backupHelper", ".", "getLastFileInBackupSet", "(", ")", ")", ")", ";", "if", "(", "filesInEnv", "!=", "null", ")", "{", "for", "(", "String", "file", ":", "filesInEnv", ")", "{", "if", "(", "file", ".", "endsWith", "(", "BDB_EXT", ")", ")", "backupRecord", ".", "println", "(", "file", ")", ";", "}", "}", "backupRecord", ".", "close", "(", ")", ";", "}" ]
Records the list of backedup files into a text file @param filesInEnv @param backupDir
[ "Records", "the", "list", "of", "backedup", "files", "into", "a", "text", "file" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/bdb/BdbNativeBackup.java#L184-L202
160,933
voldemort/voldemort
src/java/voldemort/store/bdb/BdbNativeBackup.java
BdbNativeBackup.cleanStaleFiles
private void cleanStaleFiles(File backupDir, AsyncOperationStatus status) { String[] filesInEnv = env.getHome().list(); String[] filesInBackupDir = backupDir.list(); if(filesInEnv != null && filesInBackupDir != null) { HashSet<String> envFileSet = new HashSet<String>(); for(String file: filesInEnv) envFileSet.add(file); // delete all files in backup which are currently not in environment for(String file: filesInBackupDir) { if(file.endsWith(BDB_EXT) && !envFileSet.contains(file)) { status.setStatus("Deleting stale jdb file :" + file); File staleJdbFile = new File(backupDir, file); staleJdbFile.delete(); } } } }
java
private void cleanStaleFiles(File backupDir, AsyncOperationStatus status) { String[] filesInEnv = env.getHome().list(); String[] filesInBackupDir = backupDir.list(); if(filesInEnv != null && filesInBackupDir != null) { HashSet<String> envFileSet = new HashSet<String>(); for(String file: filesInEnv) envFileSet.add(file); // delete all files in backup which are currently not in environment for(String file: filesInBackupDir) { if(file.endsWith(BDB_EXT) && !envFileSet.contains(file)) { status.setStatus("Deleting stale jdb file :" + file); File staleJdbFile = new File(backupDir, file); staleJdbFile.delete(); } } } }
[ "private", "void", "cleanStaleFiles", "(", "File", "backupDir", ",", "AsyncOperationStatus", "status", ")", "{", "String", "[", "]", "filesInEnv", "=", "env", ".", "getHome", "(", ")", ".", "list", "(", ")", ";", "String", "[", "]", "filesInBackupDir", "=", "backupDir", ".", "list", "(", ")", ";", "if", "(", "filesInEnv", "!=", "null", "&&", "filesInBackupDir", "!=", "null", ")", "{", "HashSet", "<", "String", ">", "envFileSet", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "String", "file", ":", "filesInEnv", ")", "envFileSet", ".", "(", "file", ")", ";", "// delete all files in backup which are currently not in environment", "for", "(", "String", "file", ":", "filesInBackupDir", ")", "{", "if", "(", "file", ".", "endsWith", "(", "BDB_EXT", ")", "&&", "!", "envFileSet", ".", "contains", "(", "file", ")", ")", "{", "status", ".", "setStatus", "(", "\"Deleting stale jdb file :\"", "+", "file", ")", ";", "File", "staleJdbFile", "=", "new", "File", "(", "backupDir", ",", "file", ")", ";", "staleJdbFile", ".", "delete", "(", ")", ";", "}", "}", "}", "}" ]
For recovery from the latest consistent snapshot, we should clean up the old files from the previous backup set, else we will fill the disk with useless log files @param backupDir
[ "For", "recovery", "from", "the", "latest", "consistent", "snapshot", "we", "should", "clean", "up", "the", "old", "files", "from", "the", "previous", "backup", "set", "else", "we", "will", "fill", "the", "disk", "with", "useless", "log", "files" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/bdb/BdbNativeBackup.java#L211-L227
160,934
voldemort/voldemort
src/java/voldemort/store/bdb/BdbNativeBackup.java
BdbNativeBackup.verifiedCopyFile
private void verifiedCopyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileInputStream source = null; FileOutputStream destination = null; LogVerificationInputStream verifyStream = null; try { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); verifyStream = new LogVerificationInputStream(env, source, sourceFile.getName()); final byte[] buf = new byte[LOGVERIFY_BUFSIZE]; while(true) { final int len = verifyStream.read(buf); if(len < 0) { break; } destination.write(buf, 0, len); } } finally { if(verifyStream != null) { verifyStream.close(); } if(destination != null) { destination.close(); } } }
java
private void verifiedCopyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileInputStream source = null; FileOutputStream destination = null; LogVerificationInputStream verifyStream = null; try { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); verifyStream = new LogVerificationInputStream(env, source, sourceFile.getName()); final byte[] buf = new byte[LOGVERIFY_BUFSIZE]; while(true) { final int len = verifyStream.read(buf); if(len < 0) { break; } destination.write(buf, 0, len); } } finally { if(verifyStream != null) { verifyStream.close(); } if(destination != null) { destination.close(); } } }
[ "private", "void", "verifiedCopyFile", "(", "File", "sourceFile", ",", "File", "destFile", ")", "throws", "IOException", "{", "if", "(", "!", "destFile", ".", "exists", "(", ")", ")", "{", "destFile", ".", "createNewFile", "(", ")", ";", "}", "FileInputStream", "source", "=", "null", ";", "FileOutputStream", "destination", "=", "null", ";", "LogVerificationInputStream", "verifyStream", "=", "null", ";", "try", "{", "source", "=", "new", "FileInputStream", "(", "sourceFile", ")", ";", "destination", "=", "new", "FileOutputStream", "(", "destFile", ")", ";", "verifyStream", "=", "new", "LogVerificationInputStream", "(", "env", ",", "source", ",", "sourceFile", ".", "getName", "(", ")", ")", ";", "final", "byte", "[", "]", "buf", "=", "new", "byte", "[", "LOGVERIFY_BUFSIZE", "]", ";", "while", "(", "true", ")", "{", "final", "int", "len", "=", "verifyStream", ".", "read", "(", "buf", ")", ";", "if", "(", "len", "<", "0", ")", "{", "break", ";", "}", "destination", ".", "write", "(", "buf", ",", "0", ",", "len", ")", ";", "}", "}", "finally", "{", "if", "(", "verifyStream", "!=", "null", ")", "{", "verifyStream", ".", "close", "(", ")", ";", "}", "if", "(", "destination", "!=", "null", ")", "{", "destination", ".", "close", "(", ")", ";", "}", "}", "}" ]
Copies the jdb log files, with additional verification of the checksums. @param sourceFile @param destFile @throws IOException
[ "Copies", "the", "jdb", "log", "files", "with", "additional", "verification", "of", "the", "checksums", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/bdb/BdbNativeBackup.java#L264-L295
160,935
voldemort/voldemort
src/java/voldemort/routing/ZoneRoutingStrategy.java
ZoneRoutingStrategy.getReplicatingPartitionList
@Override public List<Integer> getReplicatingPartitionList(int index) { List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas()); List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas()); // Copy Zone based Replication Factor HashMap<Integer, Integer> requiredRepFactor = new HashMap<Integer, Integer>(); requiredRepFactor.putAll(zoneReplicationFactor); // Cross-check if individual zone replication factor equals global int sum = 0; for(Integer zoneRepFactor: requiredRepFactor.values()) { sum += zoneRepFactor; } if(sum != getNumReplicas()) throw new IllegalArgumentException("Number of zone replicas is not equal to the total replication factor"); if(getPartitionToNode().length == 0) { return new ArrayList<Integer>(0); } for(int i = 0; i < getPartitionToNode().length; i++) { // add this one if we haven't already, and it can satisfy some zone // replicationFactor Node currentNode = getNodeByPartition(index); if(!preferenceNodesList.contains(currentNode)) { preferenceNodesList.add(currentNode); if(checkZoneRequirement(requiredRepFactor, currentNode.getZoneId())) replicationPartitionsList.add(index); } // if we have enough, go home if(replicationPartitionsList.size() >= getNumReplicas()) return replicationPartitionsList; // move to next clockwise slot on the ring index = (index + 1) % getPartitionToNode().length; } // we don't have enough, but that may be okay return replicationPartitionsList; }
java
@Override public List<Integer> getReplicatingPartitionList(int index) { List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas()); List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas()); // Copy Zone based Replication Factor HashMap<Integer, Integer> requiredRepFactor = new HashMap<Integer, Integer>(); requiredRepFactor.putAll(zoneReplicationFactor); // Cross-check if individual zone replication factor equals global int sum = 0; for(Integer zoneRepFactor: requiredRepFactor.values()) { sum += zoneRepFactor; } if(sum != getNumReplicas()) throw new IllegalArgumentException("Number of zone replicas is not equal to the total replication factor"); if(getPartitionToNode().length == 0) { return new ArrayList<Integer>(0); } for(int i = 0; i < getPartitionToNode().length; i++) { // add this one if we haven't already, and it can satisfy some zone // replicationFactor Node currentNode = getNodeByPartition(index); if(!preferenceNodesList.contains(currentNode)) { preferenceNodesList.add(currentNode); if(checkZoneRequirement(requiredRepFactor, currentNode.getZoneId())) replicationPartitionsList.add(index); } // if we have enough, go home if(replicationPartitionsList.size() >= getNumReplicas()) return replicationPartitionsList; // move to next clockwise slot on the ring index = (index + 1) % getPartitionToNode().length; } // we don't have enough, but that may be okay return replicationPartitionsList; }
[ "@", "Override", "public", "List", "<", "Integer", ">", "getReplicatingPartitionList", "(", "int", "index", ")", "{", "List", "<", "Node", ">", "preferenceNodesList", "=", "new", "ArrayList", "<", "Node", ">", "(", "getNumReplicas", "(", ")", ")", ";", "List", "<", "Integer", ">", "replicationPartitionsList", "=", "new", "ArrayList", "<", "Integer", ">", "(", "getNumReplicas", "(", ")", ")", ";", "// Copy Zone based Replication Factor", "HashMap", "<", "Integer", ",", "Integer", ">", "requiredRepFactor", "=", "new", "HashMap", "<", "Integer", ",", "Integer", ">", "(", ")", ";", "requiredRepFactor", ".", "putAll", "(", "zoneReplicationFactor", ")", ";", "// Cross-check if individual zone replication factor equals global", "int", "sum", "=", "0", ";", "for", "(", "Integer", "zoneRepFactor", ":", "requiredRepFactor", ".", "values", "(", ")", ")", "{", "sum", "+=", "zoneRepFactor", ";", "}", "if", "(", "sum", "!=", "getNumReplicas", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Number of zone replicas is not equal to the total replication factor\"", ")", ";", "if", "(", "getPartitionToNode", "(", ")", ".", "length", "==", "0", ")", "{", "return", "new", "ArrayList", "<", "Integer", ">", "(", "0", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "getPartitionToNode", "(", ")", ".", "length", ";", "i", "++", ")", "{", "// add this one if we haven't already, and it can satisfy some zone", "// replicationFactor", "Node", "currentNode", "=", "getNodeByPartition", "(", "index", ")", ";", "if", "(", "!", "preferenceNodesList", ".", "contains", "(", "currentNode", ")", ")", "{", "preferenceNodesList", ".", "add", "(", "currentNode", ")", ";", "if", "(", "checkZoneRequirement", "(", "requiredRepFactor", ",", "currentNode", ".", "getZoneId", "(", ")", ")", ")", "replicationPartitionsList", ".", "add", "(", "index", ")", ";", "}", "// if we have enough, go home", "if", "(", "replicationPartitionsList", ".", "size", "(", ")", ">=", "getNumReplicas", "(", ")", ")", "return", "replicationPartitionsList", ";", "// move to next clockwise slot on the ring", "index", "=", "(", "index", "+", "1", ")", "%", "getPartitionToNode", "(", ")", ".", "length", ";", "}", "// we don't have enough, but that may be okay", "return", "replicationPartitionsList", ";", "}" ]
Get the replication partitions list for the given partition. @param index Partition id for which we are generating the preference list @return The List of partitionId where this partition is replicated.
[ "Get", "the", "replication", "partitions", "list", "for", "the", "given", "partition", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/ZoneRoutingStrategy.java#L57-L98
160,936
voldemort/voldemort
src/java/voldemort/routing/ZoneRoutingStrategy.java
ZoneRoutingStrategy.checkZoneRequirement
private boolean checkZoneRequirement(HashMap<Integer, Integer> requiredRepFactor, int zoneId) { if(requiredRepFactor.containsKey(zoneId)) { if(requiredRepFactor.get(zoneId) == 0) { return false; } else { requiredRepFactor.put(zoneId, requiredRepFactor.get(zoneId) - 1); return true; } } return false; }
java
private boolean checkZoneRequirement(HashMap<Integer, Integer> requiredRepFactor, int zoneId) { if(requiredRepFactor.containsKey(zoneId)) { if(requiredRepFactor.get(zoneId) == 0) { return false; } else { requiredRepFactor.put(zoneId, requiredRepFactor.get(zoneId) - 1); return true; } } return false; }
[ "private", "boolean", "checkZoneRequirement", "(", "HashMap", "<", "Integer", ",", "Integer", ">", "requiredRepFactor", ",", "int", "zoneId", ")", "{", "if", "(", "requiredRepFactor", ".", "containsKey", "(", "zoneId", ")", ")", "{", "if", "(", "requiredRepFactor", ".", "get", "(", "zoneId", ")", "==", "0", ")", "{", "return", "false", ";", "}", "else", "{", "requiredRepFactor", ".", "put", "(", "zoneId", ",", "requiredRepFactor", ".", "get", "(", "zoneId", ")", "-", "1", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if we still need more nodes from the given zone and reduce the zoneReplicationFactor count accordingly. @param requiredRepFactor @param zoneId @return
[ "Check", "if", "we", "still", "need", "more", "nodes", "from", "the", "given", "zone", "and", "reduce", "the", "zoneReplicationFactor", "count", "accordingly", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/ZoneRoutingStrategy.java#L108-L119
160,937
voldemort/voldemort
contrib/restclient/src/java/voldemort/restclient/admin/CoordinatorAdminUtils.java
CoordinatorAdminUtils.acceptsUrlMultiple
public static void acceptsUrlMultiple(OptionParser parser) { parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), "coordinator bootstrap urls") .withRequiredArg() .describedAs("url-list") .withValuesSeparatedBy(',') .ofType(String.class); }
java
public static void acceptsUrlMultiple(OptionParser parser) { parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), "coordinator bootstrap urls") .withRequiredArg() .describedAs("url-list") .withValuesSeparatedBy(',') .ofType(String.class); }
[ "public", "static", "void", "acceptsUrlMultiple", "(", "OptionParser", "parser", ")", "{", "parser", ".", "acceptsAll", "(", "Arrays", ".", "asList", "(", "OPT_U", ",", "OPT_URL", ")", ",", "\"coordinator bootstrap urls\"", ")", ".", "withRequiredArg", "(", ")", ".", "describedAs", "(", "\"url-list\"", ")", ".", "withValuesSeparatedBy", "(", "'", "'", ")", ".", "ofType", "(", "String", ".", "class", ")", ";", "}" ]
Adds OPT_U | OPT_URL option to OptionParser, with multiple arguments. @param parser OptionParser to be modified @param required Tells if this option is required or optional
[ "Adds", "OPT_U", "|", "OPT_URL", "option", "to", "OptionParser", "with", "multiple", "arguments", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/restclient/src/java/voldemort/restclient/admin/CoordinatorAdminUtils.java#L69-L75
160,938
voldemort/voldemort
contrib/restclient/src/java/voldemort/restclient/admin/CoordinatorAdminUtils.java
CoordinatorAdminUtils.copyArrayCutFirst
public static String[] copyArrayCutFirst(String[] arr) { if(arr.length > 1) { String[] arrCopy = new String[arr.length - 1]; System.arraycopy(arr, 1, arrCopy, 0, arrCopy.length); return arrCopy; } else { return new String[0]; } }
java
public static String[] copyArrayCutFirst(String[] arr) { if(arr.length > 1) { String[] arrCopy = new String[arr.length - 1]; System.arraycopy(arr, 1, arrCopy, 0, arrCopy.length); return arrCopy; } else { return new String[0]; } }
[ "public", "static", "String", "[", "]", "copyArrayCutFirst", "(", "String", "[", "]", "arr", ")", "{", "if", "(", "arr", ".", "length", ">", "1", ")", "{", "String", "[", "]", "arrCopy", "=", "new", "String", "[", "arr", ".", "length", "-", "1", "]", ";", "System", ".", "arraycopy", "(", "arr", ",", "1", ",", "arrCopy", ",", "0", ",", "arrCopy", ".", "length", ")", ";", "return", "arrCopy", ";", "}", "else", "{", "return", "new", "String", "[", "0", "]", ";", "}", "}" ]
Utility function that copies a string array except for the first element @param arr Original array of strings @return Copied array of strings
[ "Utility", "function", "that", "copies", "a", "string", "array", "except", "for", "the", "first", "element" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/restclient/src/java/voldemort/restclient/admin/CoordinatorAdminUtils.java#L240-L248
160,939
voldemort/voldemort
contrib/restclient/src/java/voldemort/restclient/admin/CoordinatorAdminUtils.java
CoordinatorAdminUtils.copyArrayAddFirst
public static String[] copyArrayAddFirst(String[] arr, String add) { String[] arrCopy = new String[arr.length + 1]; arrCopy[0] = add; System.arraycopy(arr, 0, arrCopy, 1, arr.length); return arrCopy; }
java
public static String[] copyArrayAddFirst(String[] arr, String add) { String[] arrCopy = new String[arr.length + 1]; arrCopy[0] = add; System.arraycopy(arr, 0, arrCopy, 1, arr.length); return arrCopy; }
[ "public", "static", "String", "[", "]", "copyArrayAddFirst", "(", "String", "[", "]", "arr", ",", "String", "add", ")", "{", "String", "[", "]", "arrCopy", "=", "new", "String", "[", "arr", ".", "length", "+", "1", "]", ";", "arrCopy", "[", "0", "]", "=", "add", ";", "System", ".", "arraycopy", "(", "arr", ",", "0", ",", "arrCopy", ",", "1", ",", "arr", ".", "length", ")", ";", "return", "arrCopy", ";", "}" ]
Utility function that copies a string array and add another string to first @param arr Original array of strings @param add @return Copied array of strings
[ "Utility", "function", "that", "copies", "a", "string", "array", "and", "add", "another", "string", "to", "first" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/restclient/src/java/voldemort/restclient/admin/CoordinatorAdminUtils.java#L258-L263
160,940
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.put
@SuppressWarnings("unchecked") public void put(String key, Versioned<Object> value) { // acquire write lock writeLock.lock(); try { if(this.storeNames.contains(key) || key.equals(STORES_KEY)) { // Check for backwards compatibility List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) value.getValue(); StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions); // If the put is on the entire stores.xml key, delete the // additional stores which do not exist in the specified // stores.xml Set<String> storeNamesToDelete = new HashSet<String>(); for(String storeName: this.storeNames) { storeNamesToDelete.add(storeName); } // Add / update the list of store definitions specified in the // value StoreDefinitionsMapper mapper = new StoreDefinitionsMapper(); // Update the STORES directory and the corresponding entry in // metadata cache Set<String> specifiedStoreNames = new HashSet<String>(); for(StoreDefinition storeDef: storeDefinitions) { specifiedStoreNames.add(storeDef.getName()); String storeDefStr = mapper.writeStore(storeDef); Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr, value.getVersion()); this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, ""); // Update the metadata cache this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr, value.getVersion())); } if(key.equals(STORES_KEY)) { storeNamesToDelete.removeAll(specifiedStoreNames); resetStoreDefinitions(storeNamesToDelete); } // Re-initialize the store definitions initStoreDefinitions(value.getVersion()); // Update routing strategies updateRoutingStrategies(getCluster(), getStoreDefList()); } else if(METADATA_KEYS.contains(key)) { // try inserting into inner store first putInner(key, convertObjectToString(key, value)); // cache all keys if innerStore put succeeded metadataCache.put(key, value); // do special stuff if needed if(CLUSTER_KEY.equals(key)) { updateRoutingStrategies((Cluster) value.getValue(), getStoreDefList()); } else if(NODE_ID_KEY.equals(key)) { initNodeId(getNodeIdNoLock()); } else if(SYSTEM_STORES_KEY.equals(key)) throw new VoldemortException("Cannot overwrite system store definitions"); } else { throw new VoldemortException("Unhandled Key:" + key + " for MetadataStore put()"); } } finally { writeLock.unlock(); } }
java
@SuppressWarnings("unchecked") public void put(String key, Versioned<Object> value) { // acquire write lock writeLock.lock(); try { if(this.storeNames.contains(key) || key.equals(STORES_KEY)) { // Check for backwards compatibility List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) value.getValue(); StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions); // If the put is on the entire stores.xml key, delete the // additional stores which do not exist in the specified // stores.xml Set<String> storeNamesToDelete = new HashSet<String>(); for(String storeName: this.storeNames) { storeNamesToDelete.add(storeName); } // Add / update the list of store definitions specified in the // value StoreDefinitionsMapper mapper = new StoreDefinitionsMapper(); // Update the STORES directory and the corresponding entry in // metadata cache Set<String> specifiedStoreNames = new HashSet<String>(); for(StoreDefinition storeDef: storeDefinitions) { specifiedStoreNames.add(storeDef.getName()); String storeDefStr = mapper.writeStore(storeDef); Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr, value.getVersion()); this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, ""); // Update the metadata cache this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr, value.getVersion())); } if(key.equals(STORES_KEY)) { storeNamesToDelete.removeAll(specifiedStoreNames); resetStoreDefinitions(storeNamesToDelete); } // Re-initialize the store definitions initStoreDefinitions(value.getVersion()); // Update routing strategies updateRoutingStrategies(getCluster(), getStoreDefList()); } else if(METADATA_KEYS.contains(key)) { // try inserting into inner store first putInner(key, convertObjectToString(key, value)); // cache all keys if innerStore put succeeded metadataCache.put(key, value); // do special stuff if needed if(CLUSTER_KEY.equals(key)) { updateRoutingStrategies((Cluster) value.getValue(), getStoreDefList()); } else if(NODE_ID_KEY.equals(key)) { initNodeId(getNodeIdNoLock()); } else if(SYSTEM_STORES_KEY.equals(key)) throw new VoldemortException("Cannot overwrite system store definitions"); } else { throw new VoldemortException("Unhandled Key:" + key + " for MetadataStore put()"); } } finally { writeLock.unlock(); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "void", "put", "(", "String", "key", ",", "Versioned", "<", "Object", ">", "value", ")", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "this", ".", "storeNames", ".", "contains", "(", "key", ")", "||", "key", ".", "equals", "(", "STORES_KEY", ")", ")", "{", "// Check for backwards compatibility", "List", "<", "StoreDefinition", ">", "storeDefinitions", "=", "(", "List", "<", "StoreDefinition", ">", ")", "value", ".", "getValue", "(", ")", ";", "StoreDefinitionUtils", ".", "validateSchemasAsNeeded", "(", "storeDefinitions", ")", ";", "// If the put is on the entire stores.xml key, delete the", "// additional stores which do not exist in the specified", "// stores.xml", "Set", "<", "String", ">", "storeNamesToDelete", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "String", "storeName", ":", "this", ".", "storeNames", ")", "{", "storeNamesToDelete", ".", "add", "(", "storeName", ")", ";", "}", "// Add / update the list of store definitions specified in the", "// value", "StoreDefinitionsMapper", "mapper", "=", "new", "StoreDefinitionsMapper", "(", ")", ";", "// Update the STORES directory and the corresponding entry in", "// metadata cache", "Set", "<", "String", ">", "specifiedStoreNames", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "StoreDefinition", "storeDef", ":", "storeDefinitions", ")", "{", "specifiedStoreNames", ".", "add", "(", "storeDef", ".", "getName", "(", ")", ")", ";", "String", "storeDefStr", "=", "mapper", ".", "writeStore", "(", "storeDef", ")", ";", "Versioned", "<", "String", ">", "versionedValueStr", "=", "new", "Versioned", "<", "String", ">", "(", "storeDefStr", ",", "value", ".", "getVersion", "(", ")", ")", ";", "this", ".", "storeDefinitionsStorageEngine", ".", "put", "(", "storeDef", ".", "getName", "(", ")", ",", "versionedValueStr", ",", "\"\"", ")", ";", "// Update the metadata cache", "this", ".", "metadataCache", ".", "put", "(", "storeDef", ".", "getName", "(", ")", ",", "new", "Versioned", "<", "Object", ">", "(", "storeDefStr", ",", "value", ".", "getVersion", "(", ")", ")", ")", ";", "}", "if", "(", "key", ".", "equals", "(", "STORES_KEY", ")", ")", "{", "storeNamesToDelete", ".", "removeAll", "(", "specifiedStoreNames", ")", ";", "resetStoreDefinitions", "(", "storeNamesToDelete", ")", ";", "}", "// Re-initialize the store definitions", "initStoreDefinitions", "(", "value", ".", "getVersion", "(", ")", ")", ";", "// Update routing strategies", "updateRoutingStrategies", "(", "getCluster", "(", ")", ",", "getStoreDefList", "(", ")", ")", ";", "}", "else", "if", "(", "METADATA_KEYS", ".", "contains", "(", "key", ")", ")", "{", "// try inserting into inner store first", "putInner", "(", "key", ",", "convertObjectToString", "(", "key", ",", "value", ")", ")", ";", "// cache all keys if innerStore put succeeded", "metadataCache", ".", "put", "(", "key", ",", "value", ")", ";", "// do special stuff if needed", "if", "(", "CLUSTER_KEY", ".", "equals", "(", "key", ")", ")", "{", "updateRoutingStrategies", "(", "(", "Cluster", ")", "value", ".", "getValue", "(", ")", ",", "getStoreDefList", "(", ")", ")", ";", "}", "else", "if", "(", "NODE_ID_KEY", ".", "equals", "(", "key", ")", ")", "{", "initNodeId", "(", "getNodeIdNoLock", "(", ")", ")", ";", "}", "else", "if", "(", "SYSTEM_STORES_KEY", ".", "equals", "(", "key", ")", ")", "throw", "new", "VoldemortException", "(", "\"Cannot overwrite system store definitions\"", ")", ";", "}", "else", "{", "throw", "new", "VoldemortException", "(", "\"Unhandled Key:\"", "+", "key", "+", "\" for MetadataStore put()\"", ")", ";", "}", "}", "finally", "{", "writeLock", ".", "unlock", "(", ")", ";", "}", "}" ]
helper function to convert strings to bytes as needed. @param key @param value
[ "helper", "function", "to", "convert", "strings", "to", "bytes", "as", "needed", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L323-L396
160,941
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.updateStoreDefinitions
@SuppressWarnings("unchecked") public void updateStoreDefinitions(Versioned<byte[]> valueBytes) { // acquire write lock writeLock.lock(); try { Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(), "UTF-8"), valueBytes.getVersion()); Versioned<Object> valueObject = convertStringToObject(STORES_KEY, value); StoreDefinitionsMapper mapper = new StoreDefinitionsMapper(); List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) valueObject.getValue(); // Check for backwards compatibility StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions); StoreDefinitionUtils.validateNewStoreDefsAreNonBreaking(getStoreDefList(), storeDefinitions); // Go through each store definition and do a corresponding put for(StoreDefinition storeDef: storeDefinitions) { if(!this.storeNames.contains(storeDef.getName())) { throw new VoldemortException("Cannot update a store which does not exist !"); } String storeDefStr = mapper.writeStore(storeDef); Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr, value.getVersion()); this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, ""); // Update the metadata cache this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr, value.getVersion())); } // Re-initialize the store definitions initStoreDefinitions(value.getVersion()); // Update routing strategies // TODO: Make this more fine grained.. i.e only update listeners for // a specific store. updateRoutingStrategies(getCluster(), getStoreDefList()); } finally { writeLock.unlock(); } }
java
@SuppressWarnings("unchecked") public void updateStoreDefinitions(Versioned<byte[]> valueBytes) { // acquire write lock writeLock.lock(); try { Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(), "UTF-8"), valueBytes.getVersion()); Versioned<Object> valueObject = convertStringToObject(STORES_KEY, value); StoreDefinitionsMapper mapper = new StoreDefinitionsMapper(); List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) valueObject.getValue(); // Check for backwards compatibility StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions); StoreDefinitionUtils.validateNewStoreDefsAreNonBreaking(getStoreDefList(), storeDefinitions); // Go through each store definition and do a corresponding put for(StoreDefinition storeDef: storeDefinitions) { if(!this.storeNames.contains(storeDef.getName())) { throw new VoldemortException("Cannot update a store which does not exist !"); } String storeDefStr = mapper.writeStore(storeDef); Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr, value.getVersion()); this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, ""); // Update the metadata cache this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr, value.getVersion())); } // Re-initialize the store definitions initStoreDefinitions(value.getVersion()); // Update routing strategies // TODO: Make this more fine grained.. i.e only update listeners for // a specific store. updateRoutingStrategies(getCluster(), getStoreDefList()); } finally { writeLock.unlock(); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "void", "updateStoreDefinitions", "(", "Versioned", "<", "byte", "[", "]", ">", "valueBytes", ")", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "Versioned", "<", "String", ">", "value", "=", "new", "Versioned", "<", "String", ">", "(", "ByteUtils", ".", "getString", "(", "valueBytes", ".", "getValue", "(", ")", ",", "\"UTF-8\"", ")", ",", "valueBytes", ".", "getVersion", "(", ")", ")", ";", "Versioned", "<", "Object", ">", "valueObject", "=", "convertStringToObject", "(", "STORES_KEY", ",", "value", ")", ";", "StoreDefinitionsMapper", "mapper", "=", "new", "StoreDefinitionsMapper", "(", ")", ";", "List", "<", "StoreDefinition", ">", "storeDefinitions", "=", "(", "List", "<", "StoreDefinition", ">", ")", "valueObject", ".", "getValue", "(", ")", ";", "// Check for backwards compatibility", "StoreDefinitionUtils", ".", "validateSchemasAsNeeded", "(", "storeDefinitions", ")", ";", "StoreDefinitionUtils", ".", "validateNewStoreDefsAreNonBreaking", "(", "getStoreDefList", "(", ")", ",", "storeDefinitions", ")", ";", "// Go through each store definition and do a corresponding put", "for", "(", "StoreDefinition", "storeDef", ":", "storeDefinitions", ")", "{", "if", "(", "!", "this", ".", "storeNames", ".", "contains", "(", "storeDef", ".", "getName", "(", ")", ")", ")", "{", "throw", "new", "VoldemortException", "(", "\"Cannot update a store which does not exist !\"", ")", ";", "}", "String", "storeDefStr", "=", "mapper", ".", "writeStore", "(", "storeDef", ")", ";", "Versioned", "<", "String", ">", "versionedValueStr", "=", "new", "Versioned", "<", "String", ">", "(", "storeDefStr", ",", "value", ".", "getVersion", "(", ")", ")", ";", "this", ".", "storeDefinitionsStorageEngine", ".", "put", "(", "storeDef", ".", "getName", "(", ")", ",", "versionedValueStr", ",", "\"\"", ")", ";", "// Update the metadata cache", "this", ".", "metadataCache", ".", "put", "(", "storeDef", ".", "getName", "(", ")", ",", "new", "Versioned", "<", "Object", ">", "(", "storeDefStr", ",", "value", ".", "getVersion", "(", ")", ")", ")", ";", "}", "// Re-initialize the store definitions", "initStoreDefinitions", "(", "value", ".", "getVersion", "(", ")", ")", ";", "// Update routing strategies", "// TODO: Make this more fine grained.. i.e only update listeners for", "// a specific store.", "updateRoutingStrategies", "(", "getCluster", "(", ")", ",", "getStoreDefList", "(", ")", ")", ";", "}", "finally", "{", "writeLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Function to update store definitions. Unlike the put method, this function does not delete any existing state. It only updates the state of the stores specified in the given stores.xml @param valueBytes specifies the bytes of the stores.xml containing updates for the specified stores
[ "Function", "to", "update", "store", "definitions", ".", "Unlike", "the", "put", "method", "this", "function", "does", "not", "delete", "any", "existing", "state", ".", "It", "only", "updates", "the", "state", "of", "the", "stores", "specified", "in", "the", "given", "stores", ".", "xml" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L406-L450
160,942
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.put
@Override public void put(ByteArray keyBytes, Versioned<byte[]> valueBytes, byte[] transforms) throws VoldemortException { // acquire write lock writeLock.lock(); try { String key = ByteUtils.getString(keyBytes.get(), "UTF-8"); Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(), "UTF-8"), valueBytes.getVersion()); Versioned<Object> valueObject = convertStringToObject(key, value); this.put(key, valueObject); } finally { writeLock.unlock(); } }
java
@Override public void put(ByteArray keyBytes, Versioned<byte[]> valueBytes, byte[] transforms) throws VoldemortException { // acquire write lock writeLock.lock(); try { String key = ByteUtils.getString(keyBytes.get(), "UTF-8"); Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(), "UTF-8"), valueBytes.getVersion()); Versioned<Object> valueObject = convertStringToObject(key, value); this.put(key, valueObject); } finally { writeLock.unlock(); } }
[ "@", "Override", "public", "void", "put", "(", "ByteArray", "keyBytes", ",", "Versioned", "<", "byte", "[", "]", ">", "valueBytes", ",", "byte", "[", "]", "transforms", ")", "throws", "VoldemortException", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "String", "key", "=", "ByteUtils", ".", "getString", "(", "keyBytes", ".", "get", "(", ")", ",", "\"UTF-8\"", ")", ";", "Versioned", "<", "String", ">", "value", "=", "new", "Versioned", "<", "String", ">", "(", "ByteUtils", ".", "getString", "(", "valueBytes", ".", "getValue", "(", ")", ",", "\"UTF-8\"", ")", ",", "valueBytes", ".", "getVersion", "(", ")", ")", ";", "Versioned", "<", "Object", ">", "valueObject", "=", "convertStringToObject", "(", "key", ",", "value", ")", ";", "this", ".", "put", "(", "key", ",", "valueObject", ")", ";", "}", "finally", "{", "writeLock", ".", "unlock", "(", ")", ";", "}", "}" ]
A write through put to inner-store. @param keyBytes : keyName strings serialized as bytes eg. 'cluster.xml' @param valueBytes : versioned byte[] eg. UTF bytes for cluster xml definitions @throws VoldemortException
[ "A", "write", "through", "put", "to", "inner", "-", "store", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L484-L501
160,943
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.makeStoreDefinitionMap
private HashMap<String, StoreDefinition> makeStoreDefinitionMap(List<StoreDefinition> storeDefs) { HashMap<String, StoreDefinition> storeDefMap = new HashMap<String, StoreDefinition>(); for(StoreDefinition storeDef: storeDefs) storeDefMap.put(storeDef.getName(), storeDef); return storeDefMap; }
java
private HashMap<String, StoreDefinition> makeStoreDefinitionMap(List<StoreDefinition> storeDefs) { HashMap<String, StoreDefinition> storeDefMap = new HashMap<String, StoreDefinition>(); for(StoreDefinition storeDef: storeDefs) storeDefMap.put(storeDef.getName(), storeDef); return storeDefMap; }
[ "private", "HashMap", "<", "String", ",", "StoreDefinition", ">", "makeStoreDefinitionMap", "(", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "HashMap", "<", "String", ",", "StoreDefinition", ">", "storeDefMap", "=", "new", "HashMap", "<", "String", ",", "StoreDefinition", ">", "(", ")", ";", "for", "(", "StoreDefinition", "storeDef", ":", "storeDefs", ")", "storeDefMap", ".", "put", "(", "storeDef", ".", "getName", "(", ")", ",", "storeDef", ")", ";", "return", "storeDefMap", ";", "}" ]
Returns the list of store defs as a map @param storeDefs @return
[ "Returns", "the", "list", "of", "store", "defs", "as", "a", "map" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L828-L833
160,944
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.updateRoutingStrategies
private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) { // acquire write lock writeLock.lock(); try { VectorClock clock = new VectorClock(); if(metadataCache.containsKey(ROUTING_STRATEGY_KEY)) clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion(); logger.info("Updating routing strategy for all stores"); HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs); HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster, storeDefMap); this.metadataCache.put(ROUTING_STRATEGY_KEY, new Versioned<Object>(routingStrategyMap, clock.incremented(getNodeId(), System.currentTimeMillis()))); for(String storeName: storeNameTolisteners.keySet()) { RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName); if(updatedRoutingStrategy != null) { try { for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) { listener.updateRoutingStrategy(updatedRoutingStrategy); listener.updateStoreDefinition(storeDefMap.get(storeName)); } } catch(Exception e) { if(logger.isEnabledFor(Level.WARN)) logger.warn(e, e); } } } } finally { writeLock.unlock(); } }
java
private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) { // acquire write lock writeLock.lock(); try { VectorClock clock = new VectorClock(); if(metadataCache.containsKey(ROUTING_STRATEGY_KEY)) clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion(); logger.info("Updating routing strategy for all stores"); HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs); HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster, storeDefMap); this.metadataCache.put(ROUTING_STRATEGY_KEY, new Versioned<Object>(routingStrategyMap, clock.incremented(getNodeId(), System.currentTimeMillis()))); for(String storeName: storeNameTolisteners.keySet()) { RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName); if(updatedRoutingStrategy != null) { try { for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) { listener.updateRoutingStrategy(updatedRoutingStrategy); listener.updateStoreDefinition(storeDefMap.get(storeName)); } } catch(Exception e) { if(logger.isEnabledFor(Level.WARN)) logger.warn(e, e); } } } } finally { writeLock.unlock(); } }
[ "private", "void", "updateRoutingStrategies", "(", "Cluster", "cluster", ",", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "VectorClock", "clock", "=", "new", "VectorClock", "(", ")", ";", "if", "(", "metadataCache", ".", "containsKey", "(", "ROUTING_STRATEGY_KEY", ")", ")", "clock", "=", "(", "VectorClock", ")", "metadataCache", ".", "get", "(", "ROUTING_STRATEGY_KEY", ")", ".", "getVersion", "(", ")", ";", "logger", ".", "info", "(", "\"Updating routing strategy for all stores\"", ")", ";", "HashMap", "<", "String", ",", "StoreDefinition", ">", "storeDefMap", "=", "makeStoreDefinitionMap", "(", "storeDefs", ")", ";", "HashMap", "<", "String", ",", "RoutingStrategy", ">", "routingStrategyMap", "=", "createRoutingStrategyMap", "(", "cluster", ",", "storeDefMap", ")", ";", "this", ".", "metadataCache", ".", "put", "(", "ROUTING_STRATEGY_KEY", ",", "new", "Versioned", "<", "Object", ">", "(", "routingStrategyMap", ",", "clock", ".", "incremented", "(", "getNodeId", "(", ")", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ")", ")", ";", "for", "(", "String", "storeName", ":", "storeNameTolisteners", ".", "keySet", "(", ")", ")", "{", "RoutingStrategy", "updatedRoutingStrategy", "=", "routingStrategyMap", ".", "get", "(", "storeName", ")", ";", "if", "(", "updatedRoutingStrategy", "!=", "null", ")", "{", "try", "{", "for", "(", "MetadataStoreListener", "listener", ":", "storeNameTolisteners", ".", "get", "(", "storeName", ")", ")", "{", "listener", ".", "updateRoutingStrategy", "(", "updatedRoutingStrategy", ")", ";", "listener", ".", "updateStoreDefinition", "(", "storeDefMap", ".", "get", "(", "storeName", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "logger", ".", "isEnabledFor", "(", "Level", ".", "WARN", ")", ")", "logger", ".", "warn", "(", "e", ",", "e", ")", ";", "}", "}", "}", "}", "finally", "{", "writeLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Changes to cluster OR store definition metadata results in routing strategies changing. These changes need to be propagated to all the listeners. @param cluster The updated cluster metadata @param storeDefs The updated list of store definition
[ "Changes", "to", "cluster", "OR", "store", "definition", "metadata", "results", "in", "routing", "strategies", "changing", ".", "These", "changes", "need", "to", "be", "propagated", "to", "all", "the", "listeners", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L843-L878
160,945
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.addRebalancingState
public void addRebalancingState(final RebalanceTaskInfo stealInfo) { // acquire write lock writeLock.lock(); try { // Move into rebalancing state if(ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(), "UTF-8") .compareTo(VoldemortState.NORMAL_SERVER.toString()) == 0) { put(SERVER_STATE_KEY, VoldemortState.REBALANCING_MASTER_SERVER); initCache(SERVER_STATE_KEY); } // Add the steal information RebalancerState rebalancerState = getRebalancerState(); if(!rebalancerState.update(stealInfo)) { throw new VoldemortException("Could not add steal information " + stealInfo + " since a plan for the same donor node " + stealInfo.getDonorId() + " ( " + rebalancerState.find(stealInfo.getDonorId()) + " ) already exists"); } put(MetadataStore.REBALANCING_STEAL_INFO, rebalancerState); initCache(REBALANCING_STEAL_INFO); } finally { writeLock.unlock(); } }
java
public void addRebalancingState(final RebalanceTaskInfo stealInfo) { // acquire write lock writeLock.lock(); try { // Move into rebalancing state if(ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(), "UTF-8") .compareTo(VoldemortState.NORMAL_SERVER.toString()) == 0) { put(SERVER_STATE_KEY, VoldemortState.REBALANCING_MASTER_SERVER); initCache(SERVER_STATE_KEY); } // Add the steal information RebalancerState rebalancerState = getRebalancerState(); if(!rebalancerState.update(stealInfo)) { throw new VoldemortException("Could not add steal information " + stealInfo + " since a plan for the same donor node " + stealInfo.getDonorId() + " ( " + rebalancerState.find(stealInfo.getDonorId()) + " ) already exists"); } put(MetadataStore.REBALANCING_STEAL_INFO, rebalancerState); initCache(REBALANCING_STEAL_INFO); } finally { writeLock.unlock(); } }
[ "public", "void", "addRebalancingState", "(", "final", "RebalanceTaskInfo", "stealInfo", ")", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "// Move into rebalancing state", "if", "(", "ByteUtils", ".", "getString", "(", "get", "(", "SERVER_STATE_KEY", ",", "null", ")", ".", "get", "(", "0", ")", ".", "getValue", "(", ")", ",", "\"UTF-8\"", ")", ".", "compareTo", "(", "VoldemortState", ".", "NORMAL_SERVER", ".", "toString", "(", ")", ")", "==", "0", ")", "{", "put", "(", "SERVER_STATE_KEY", ",", "VoldemortState", ".", "REBALANCING_MASTER_SERVER", ")", ";", "initCache", "(", "SERVER_STATE_KEY", ")", ";", "}", "// Add the steal information", "RebalancerState", "rebalancerState", "=", "getRebalancerState", "(", ")", ";", "if", "(", "!", "rebalancerState", ".", "update", "(", "stealInfo", ")", ")", "{", "throw", "new", "VoldemortException", "(", "\"Could not add steal information \"", "+", "stealInfo", "+", "\" since a plan for the same donor node \"", "+", "stealInfo", ".", "getDonorId", "(", ")", "+", "\" ( \"", "+", "rebalancerState", ".", "find", "(", "stealInfo", ".", "getDonorId", "(", ")", ")", "+", "\" ) already exists\"", ")", ";", "}", "put", "(", "MetadataStore", ".", "REBALANCING_STEAL_INFO", ",", "rebalancerState", ")", ";", "initCache", "(", "REBALANCING_STEAL_INFO", ")", ";", "}", "finally", "{", "writeLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Add the steal information to the rebalancer state @param stealInfo The steal information to add
[ "Add", "the", "steal", "information", "to", "the", "rebalancer", "state" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L896-L921
160,946
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.deleteRebalancingState
public void deleteRebalancingState(RebalanceTaskInfo stealInfo) { // acquire write lock writeLock.lock(); try { RebalancerState rebalancerState = getRebalancerState(); if(!rebalancerState.remove(stealInfo)) throw new IllegalArgumentException("Couldn't find " + stealInfo + " in " + rebalancerState + " while deleting"); if(rebalancerState.isEmpty()) { logger.debug("Cleaning all rebalancing state"); cleanAllRebalancingState(); } else { put(REBALANCING_STEAL_INFO, rebalancerState); initCache(REBALANCING_STEAL_INFO); } } finally { writeLock.unlock(); } }
java
public void deleteRebalancingState(RebalanceTaskInfo stealInfo) { // acquire write lock writeLock.lock(); try { RebalancerState rebalancerState = getRebalancerState(); if(!rebalancerState.remove(stealInfo)) throw new IllegalArgumentException("Couldn't find " + stealInfo + " in " + rebalancerState + " while deleting"); if(rebalancerState.isEmpty()) { logger.debug("Cleaning all rebalancing state"); cleanAllRebalancingState(); } else { put(REBALANCING_STEAL_INFO, rebalancerState); initCache(REBALANCING_STEAL_INFO); } } finally { writeLock.unlock(); } }
[ "public", "void", "deleteRebalancingState", "(", "RebalanceTaskInfo", "stealInfo", ")", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "RebalancerState", "rebalancerState", "=", "getRebalancerState", "(", ")", ";", "if", "(", "!", "rebalancerState", ".", "remove", "(", "stealInfo", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Couldn't find \"", "+", "stealInfo", "+", "\" in \"", "+", "rebalancerState", "+", "\" while deleting\"", ")", ";", "if", "(", "rebalancerState", ".", "isEmpty", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Cleaning all rebalancing state\"", ")", ";", "cleanAllRebalancingState", "(", ")", ";", "}", "else", "{", "put", "(", "REBALANCING_STEAL_INFO", ",", "rebalancerState", ")", ";", "initCache", "(", "REBALANCING_STEAL_INFO", ")", ";", "}", "}", "finally", "{", "writeLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Delete the partition steal information from the rebalancer state @param stealInfo The steal information to delete
[ "Delete", "the", "partition", "steal", "information", "from", "the", "rebalancer", "state" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L928-L948
160,947
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.setOfflineState
public void setOfflineState(boolean setToOffline) { // acquire write lock writeLock.lock(); try { String currentState = ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(), "UTF-8"); if(setToOffline) { // from NORMAL_SERVER to OFFLINE_SERVER if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) { put(SERVER_STATE_KEY, VoldemortState.OFFLINE_SERVER); initCache(SERVER_STATE_KEY); put(SLOP_STREAMING_ENABLED_KEY, false); initCache(SLOP_STREAMING_ENABLED_KEY); put(PARTITION_STREAMING_ENABLED_KEY, false); initCache(PARTITION_STREAMING_ENABLED_KEY); put(READONLY_FETCH_ENABLED_KEY, false); initCache(READONLY_FETCH_ENABLED_KEY); } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) { logger.warn("Already in OFFLINE_SERVER state."); return; } else { logger.error("Cannot enter OFFLINE_SERVER state from " + currentState); throw new VoldemortException("Cannot enter OFFLINE_SERVER state from " + currentState); } } else { // from OFFLINE_SERVER to NORMAL_SERVER if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) { logger.warn("Already in NORMAL_SERVER state."); return; } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) { put(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER); initCache(SERVER_STATE_KEY); put(SLOP_STREAMING_ENABLED_KEY, true); initCache(SLOP_STREAMING_ENABLED_KEY); put(PARTITION_STREAMING_ENABLED_KEY, true); initCache(PARTITION_STREAMING_ENABLED_KEY); put(READONLY_FETCH_ENABLED_KEY, true); initCache(READONLY_FETCH_ENABLED_KEY); init(); initNodeId(getNodeIdNoLock()); } else { logger.error("Cannot enter NORMAL_SERVER state from " + currentState); throw new VoldemortException("Cannot enter NORMAL_SERVER state from " + currentState); } } } finally { writeLock.unlock(); } }
java
public void setOfflineState(boolean setToOffline) { // acquire write lock writeLock.lock(); try { String currentState = ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(), "UTF-8"); if(setToOffline) { // from NORMAL_SERVER to OFFLINE_SERVER if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) { put(SERVER_STATE_KEY, VoldemortState.OFFLINE_SERVER); initCache(SERVER_STATE_KEY); put(SLOP_STREAMING_ENABLED_KEY, false); initCache(SLOP_STREAMING_ENABLED_KEY); put(PARTITION_STREAMING_ENABLED_KEY, false); initCache(PARTITION_STREAMING_ENABLED_KEY); put(READONLY_FETCH_ENABLED_KEY, false); initCache(READONLY_FETCH_ENABLED_KEY); } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) { logger.warn("Already in OFFLINE_SERVER state."); return; } else { logger.error("Cannot enter OFFLINE_SERVER state from " + currentState); throw new VoldemortException("Cannot enter OFFLINE_SERVER state from " + currentState); } } else { // from OFFLINE_SERVER to NORMAL_SERVER if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) { logger.warn("Already in NORMAL_SERVER state."); return; } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) { put(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER); initCache(SERVER_STATE_KEY); put(SLOP_STREAMING_ENABLED_KEY, true); initCache(SLOP_STREAMING_ENABLED_KEY); put(PARTITION_STREAMING_ENABLED_KEY, true); initCache(PARTITION_STREAMING_ENABLED_KEY); put(READONLY_FETCH_ENABLED_KEY, true); initCache(READONLY_FETCH_ENABLED_KEY); init(); initNodeId(getNodeIdNoLock()); } else { logger.error("Cannot enter NORMAL_SERVER state from " + currentState); throw new VoldemortException("Cannot enter NORMAL_SERVER state from " + currentState); } } } finally { writeLock.unlock(); } }
[ "public", "void", "setOfflineState", "(", "boolean", "setToOffline", ")", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "String", "currentState", "=", "ByteUtils", ".", "getString", "(", "get", "(", "SERVER_STATE_KEY", ",", "null", ")", ".", "get", "(", "0", ")", ".", "getValue", "(", ")", ",", "\"UTF-8\"", ")", ";", "if", "(", "setToOffline", ")", "{", "// from NORMAL_SERVER to OFFLINE_SERVER", "if", "(", "currentState", ".", "equals", "(", "VoldemortState", ".", "NORMAL_SERVER", ".", "toString", "(", ")", ")", ")", "{", "put", "(", "SERVER_STATE_KEY", ",", "VoldemortState", ".", "OFFLINE_SERVER", ")", ";", "initCache", "(", "SERVER_STATE_KEY", ")", ";", "put", "(", "SLOP_STREAMING_ENABLED_KEY", ",", "false", ")", ";", "initCache", "(", "SLOP_STREAMING_ENABLED_KEY", ")", ";", "put", "(", "PARTITION_STREAMING_ENABLED_KEY", ",", "false", ")", ";", "initCache", "(", "PARTITION_STREAMING_ENABLED_KEY", ")", ";", "put", "(", "READONLY_FETCH_ENABLED_KEY", ",", "false", ")", ";", "initCache", "(", "READONLY_FETCH_ENABLED_KEY", ")", ";", "}", "else", "if", "(", "currentState", ".", "equals", "(", "VoldemortState", ".", "OFFLINE_SERVER", ".", "toString", "(", ")", ")", ")", "{", "logger", ".", "warn", "(", "\"Already in OFFLINE_SERVER state.\"", ")", ";", "return", ";", "}", "else", "{", "logger", ".", "error", "(", "\"Cannot enter OFFLINE_SERVER state from \"", "+", "currentState", ")", ";", "throw", "new", "VoldemortException", "(", "\"Cannot enter OFFLINE_SERVER state from \"", "+", "currentState", ")", ";", "}", "}", "else", "{", "// from OFFLINE_SERVER to NORMAL_SERVER", "if", "(", "currentState", ".", "equals", "(", "VoldemortState", ".", "NORMAL_SERVER", ".", "toString", "(", ")", ")", ")", "{", "logger", ".", "warn", "(", "\"Already in NORMAL_SERVER state.\"", ")", ";", "return", ";", "}", "else", "if", "(", "currentState", ".", "equals", "(", "VoldemortState", ".", "OFFLINE_SERVER", ".", "toString", "(", ")", ")", ")", "{", "put", "(", "SERVER_STATE_KEY", ",", "VoldemortState", ".", "NORMAL_SERVER", ")", ";", "initCache", "(", "SERVER_STATE_KEY", ")", ";", "put", "(", "SLOP_STREAMING_ENABLED_KEY", ",", "true", ")", ";", "initCache", "(", "SLOP_STREAMING_ENABLED_KEY", ")", ";", "put", "(", "PARTITION_STREAMING_ENABLED_KEY", ",", "true", ")", ";", "initCache", "(", "PARTITION_STREAMING_ENABLED_KEY", ")", ";", "put", "(", "READONLY_FETCH_ENABLED_KEY", ",", "true", ")", ";", "initCache", "(", "READONLY_FETCH_ENABLED_KEY", ")", ";", "init", "(", ")", ";", "initNodeId", "(", "getNodeIdNoLock", "(", ")", ")", ";", "}", "else", "{", "logger", ".", "error", "(", "\"Cannot enter NORMAL_SERVER state from \"", "+", "currentState", ")", ";", "throw", "new", "VoldemortException", "(", "\"Cannot enter NORMAL_SERVER state from \"", "+", "currentState", ")", ";", "}", "}", "}", "finally", "{", "writeLock", ".", "unlock", "(", ")", ";", "}", "}" ]
change server state between OFFLINE_SERVER and NORMAL_SERVER @param setToOffline True if set to OFFLINE_SERVER
[ "change", "server", "state", "between", "OFFLINE_SERVER", "and", "NORMAL_SERVER" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L955-L1005
160,948
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.addStoreDefinition
public void addStoreDefinition(StoreDefinition storeDef) { // acquire write lock writeLock.lock(); try { // Check if store already exists if(this.storeNames.contains(storeDef.getName())) { throw new VoldemortException("Store already exists !"); } // Check for backwards compatibility StoreDefinitionUtils.validateSchemaAsNeeded(storeDef); // Otherwise add to the STORES directory StoreDefinitionsMapper mapper = new StoreDefinitionsMapper(); String storeDefStr = mapper.writeStore(storeDef); Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr); this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, null); // Update the metadata cache this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr)); // Re-initialize the store definitions. This is primarily required // to re-create the value for key: 'stores.xml'. This is necessary // for backwards compatibility. initStoreDefinitions(null); updateRoutingStrategies(getCluster(), getStoreDefList()); } finally { writeLock.unlock(); } }
java
public void addStoreDefinition(StoreDefinition storeDef) { // acquire write lock writeLock.lock(); try { // Check if store already exists if(this.storeNames.contains(storeDef.getName())) { throw new VoldemortException("Store already exists !"); } // Check for backwards compatibility StoreDefinitionUtils.validateSchemaAsNeeded(storeDef); // Otherwise add to the STORES directory StoreDefinitionsMapper mapper = new StoreDefinitionsMapper(); String storeDefStr = mapper.writeStore(storeDef); Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr); this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, null); // Update the metadata cache this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr)); // Re-initialize the store definitions. This is primarily required // to re-create the value for key: 'stores.xml'. This is necessary // for backwards compatibility. initStoreDefinitions(null); updateRoutingStrategies(getCluster(), getStoreDefList()); } finally { writeLock.unlock(); } }
[ "public", "void", "addStoreDefinition", "(", "StoreDefinition", "storeDef", ")", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "// Check if store already exists", "if", "(", "this", ".", "storeNames", ".", "contains", "(", "storeDef", ".", "getName", "(", ")", ")", ")", "{", "throw", "new", "VoldemortException", "(", "\"Store already exists !\"", ")", ";", "}", "// Check for backwards compatibility", "StoreDefinitionUtils", ".", "validateSchemaAsNeeded", "(", "storeDef", ")", ";", "// Otherwise add to the STORES directory", "StoreDefinitionsMapper", "mapper", "=", "new", "StoreDefinitionsMapper", "(", ")", ";", "String", "storeDefStr", "=", "mapper", ".", "writeStore", "(", "storeDef", ")", ";", "Versioned", "<", "String", ">", "versionedValueStr", "=", "new", "Versioned", "<", "String", ">", "(", "storeDefStr", ")", ";", "this", ".", "storeDefinitionsStorageEngine", ".", "put", "(", "storeDef", ".", "getName", "(", ")", ",", "versionedValueStr", ",", "null", ")", ";", "// Update the metadata cache", "this", ".", "metadataCache", ".", "put", "(", "storeDef", ".", "getName", "(", ")", ",", "new", "Versioned", "<", "Object", ">", "(", "storeDefStr", ")", ")", ";", "// Re-initialize the store definitions. This is primarily required", "// to re-create the value for key: 'stores.xml'. This is necessary", "// for backwards compatibility.", "initStoreDefinitions", "(", "null", ")", ";", "updateRoutingStrategies", "(", "getCluster", "(", ")", ",", "getStoreDefList", "(", ")", ")", ";", "}", "finally", "{", "writeLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Function to add a new Store to the Metadata store. This involves 1. Create a new entry in the ConfigurationStorageEngine for STORES. 2. Update the metadata cache. 3. Re-create the 'stores.xml' key @param storeDef defines the new store to be created
[ "Function", "to", "add", "a", "new", "Store", "to", "the", "Metadata", "store", ".", "This", "involves" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L1018-L1049
160,949
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.deleteStoreDefinition
public void deleteStoreDefinition(String storeName) { // acquire write lock writeLock.lock(); try { // Check if store exists if(!this.storeNames.contains(storeName)) { throw new VoldemortException("Requested store to be deleted does not exist !"); } // Otherwise remove from the STORES directory. Note: The version // argument is not required here since the // ConfigurationStorageEngine simply ignores this. this.storeDefinitionsStorageEngine.delete(storeName, null); // Update the metadata cache this.metadataCache.remove(storeName); // Re-initialize the store definitions. This is primarily required // to re-create the value for key: 'stores.xml'. This is necessary // for backwards compatibility. initStoreDefinitions(null); } finally { writeLock.unlock(); } }
java
public void deleteStoreDefinition(String storeName) { // acquire write lock writeLock.lock(); try { // Check if store exists if(!this.storeNames.contains(storeName)) { throw new VoldemortException("Requested store to be deleted does not exist !"); } // Otherwise remove from the STORES directory. Note: The version // argument is not required here since the // ConfigurationStorageEngine simply ignores this. this.storeDefinitionsStorageEngine.delete(storeName, null); // Update the metadata cache this.metadataCache.remove(storeName); // Re-initialize the store definitions. This is primarily required // to re-create the value for key: 'stores.xml'. This is necessary // for backwards compatibility. initStoreDefinitions(null); } finally { writeLock.unlock(); } }
[ "public", "void", "deleteStoreDefinition", "(", "String", "storeName", ")", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "// Check if store exists", "if", "(", "!", "this", ".", "storeNames", ".", "contains", "(", "storeName", ")", ")", "{", "throw", "new", "VoldemortException", "(", "\"Requested store to be deleted does not exist !\"", ")", ";", "}", "// Otherwise remove from the STORES directory. Note: The version", "// argument is not required here since the", "// ConfigurationStorageEngine simply ignores this.", "this", ".", "storeDefinitionsStorageEngine", ".", "delete", "(", "storeName", ",", "null", ")", ";", "// Update the metadata cache", "this", ".", "metadataCache", ".", "remove", "(", "storeName", ")", ";", "// Re-initialize the store definitions. This is primarily required", "// to re-create the value for key: 'stores.xml'. This is necessary", "// for backwards compatibility.", "initStoreDefinitions", "(", "null", ")", ";", "}", "finally", "{", "writeLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Function to delete the specified store from Metadata store. This involves 1. Remove entry from the ConfigurationStorageEngine for STORES. 2. Update the metadata cache. 3. Re-create the 'stores.xml' key @param storeName specifies name of the store to be deleted.
[ "Function", "to", "delete", "the", "specified", "store", "from", "Metadata", "store", ".", "This", "involves" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L1062-L1087
160,950
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.isValidStore
public boolean isValidStore(String name) { readLock.lock(); try { if(this.storeNames.contains(name)) { return true; } return false; } finally { readLock.unlock(); } }
java
public boolean isValidStore(String name) { readLock.lock(); try { if(this.storeNames.contains(name)) { return true; } return false; } finally { readLock.unlock(); } }
[ "public", "boolean", "isValidStore", "(", "String", "name", ")", "{", "readLock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "this", ".", "storeNames", ".", "contains", "(", "name", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "finally", "{", "readLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Utility function to validate if the given store name exists in the store name list managed by MetadataStore. This is used by the Admin service for validation before serving a get-metadata request. @param name Name of the store to validate @return True if the store name exists in the 'storeNames' list. False otherwise.
[ "Utility", "function", "to", "validate", "if", "the", "given", "store", "name", "exists", "in", "the", "store", "name", "list", "managed", "by", "MetadataStore", ".", "This", "is", "used", "by", "the", "Admin", "service", "for", "validation", "before", "serving", "a", "get", "-", "metadata", "request", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L1142-L1152
160,951
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 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", "(", ")", ";", "}", "}" ]
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
160,952
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\"", ")", ";", "}", "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", ")", ")", ")", ";", "}" ]
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
160,953
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", "(", "storeName", ")", ";", "this", ".", "storeDefinitionsStorageEngine", ".", "delete", "(", "storeName", ",", "null", ")", ";", "this", ".", "storeNames", ".", "remove", "(", "storeName", ")", ";", "}", "}" ]
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
160,954
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", ")", ")", ";", "metadataCache", ".", "put", "(", "SYSTEM_STORES_KEY", ",", "new", "Versioned", "<", "Object", ">", "(", "value", ")", ")", ";", "}" ]
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
160,955
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", "(", ")", ")", ";", "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.\"", ")", ";", "}" ]
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
160,956
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", ">", ">", "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", ";", "}" ]
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
160,957
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", "(", ")", ")", ";", "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.\"", ")", ";", "}" ]
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
160,958
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", ".", "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", "(", ")", ";", "}", "}", "}" ]
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
160,959
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", ".", "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", ";", "}" ]
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
160,960
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", ".", "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", ")", ";", "}" ]
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
160,961
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", "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", ")", ";", "}" ]
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
160,962
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", ".", "getHttpPort", "(", ")", ",", "node", ".", "getSocketPort", "(", ")", ",", "node", ".", "getAdminPort", "(", ")", ",", "node", ".", "getZoneId", "(", ")", ",", "partitionsList", ")", ";", "}" ]
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
160,963
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
160,964
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
160,965
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", ".", "getPartitionIds", "(", ")", ")", ";", "deepCopy", ".", "addAll", "(", "donatedPartitions", ")", ";", "Collections", ".", "sort", "(", "deepCopy", ")", ";", "return", "updateNode", "(", "node", ",", "deepCopy", ")", ";", "}" ]
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
160,966
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", ".", "getPartitionIds", "(", ")", ")", ";", "deepCopy", ".", "removeAll", "(", "donatedPartitions", ")", ";", "return", "updateNode", "(", "node", ",", "deepCopy", ")", ";", "}" ]
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
160,967
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", "(", "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", ";", "}" ]
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
160,968
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", "(", "iter", ".", "next", "(", ")", ".", "getAbsolutePath", "(", ")", ")", ";", "}" ]
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
160,969
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 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", "(", ")", "+", "\".\"", ")", ";", "}", "}", "}" ]
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
160,970
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", ")", ";", "for", "(", "Integer", "partitionId", ":", "partitionIds", ")", "{", "// check which of the replicating partitions belongs to the node in", "// question", "if", "(", "getNodeIdForPartitionId", "(", "partitionId", ")", "==", "nodeId", ")", "{", "return", "partitionId", ";", "}", "}", "return", "null", ";", "}" ]
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
160,971
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", ">", "(", "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", ";", "}" ]
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", "node", "ID", "should", "be", "one", "to", "one", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/routing/StoreRoutingPlan.java#L238-L250
160,972
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", "<", "Integer", ">", "replicatingPartitions", "=", "getReplicatingPartitionList", "(", "key", ")", ";", "// remove all partitions from the list, except those that belong to the", "// node", "replicatingPartitions", ".", "retainAll", "(", "nodePartitions", ")", ";", "return", "replicatingPartitions", ".", "size", "(", ")", ">", "0", ";", "}" ]
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
160,973
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", ">", ">", ">", ">", "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", ";", "}" ]
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
160,974
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", "(", "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", ")", ";", "}", "}", "}", "}" ]
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
160,975
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", "<=", "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", ";", "}" ]
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
160,976
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", "[", "]", ">", ">", "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", ";", "}" ]
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
160,977
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", ">", "(", "serverIds", ".", "size", "(", ")", ")", ";", "for", "(", "Integer", "serverId", ":", "serverIds", ")", "{", "clockEntries", ".", "add", "(", "new", "ClockEntry", "(", "serverId", ".", "shortValue", "(", ")", ",", "clockValue", ")", ")", ";", "}", "return", "new", "VectorClock", "(", "clockEntries", ",", "timestamp", ")", ";", "}" ]
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
160,978
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", ")", ";", "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", ";", "}" ]
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
160,979
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", "=", "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", ";", "}", "}" ]
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", "block", "waiting", "for", "more", "data", "it", "s", "possible", "to", "get", "partial", "reads", "and", "this", "identifies", "that", "case", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/AdminServiceRequestHandler.java#L1720-L1749
160,980
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", ")", ";", "isRegistered", "=", "false", ";", "}", "}" ]
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
160,981
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", ".", "toBinaryString", "(", "0xFF", "&", "b", ")", ";", "bin", "=", "bin", ".", "substring", "(", "0", ",", "Math", ".", "min", "(", "bin", ".", "length", "(", ")", ",", "8", ")", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "8", "-", "bin", ".", "length", "(", ")", ";", "j", "++", ")", "{", "buffer", ".", "append", "(", "'", "'", ")", ";", "}", "buffer", ".", "append", "(", "bin", ")", ";", "}", "return", "buffer", ".", "toString", "(", ")", ";", "}" ]
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
160,982
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", "{", "byte", "[", "]", "a", "=", "new", "byte", "[", "to", "-", "from", "]", ";", "System", ".", "arraycopy", "(", "array", ",", "from", ",", "a", ",", "0", ",", "to", "-", "from", ")", ";", "return", "a", ";", "}", "}" ]
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
160,983
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", "+", "1", "]", "&", "0xff", ")", "<<", "16", ")", "|", "(", "(", "bytes", "[", "offset", "+", "2", "]", "&", "0xff", ")", "<<", "8", ")", "|", "(", "bytes", "[", "offset", "+", "3", "]", "&", "0xff", ")", ")", ";", "}" ]
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
160,984
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", "[", "offset", "+", "1", "]", "&", "0xff", "L", ")", "<<", "16", ")", "|", "(", "(", "bytes", "[", "offset", "+", "2", "]", "&", "0xff", "L", ")", "<<", "8", ")", "|", "(", "bytes", "[", "offset", "+", "3", "]", "&", "0xff", "L", ")", ")", ";", "}" ]
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
160,985
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", "-", "1", ";", "i", ">=", "offset", ";", "i", "--", ")", "{", "value", "|=", "(", "bytes", "[", "i", "]", "&", "0xFF", "L", ")", "<<", "shift", ";", "shift", "+=", "8", ";", "}", "return", "value", ";", "}" ]
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
160,986
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", "[", "offset", "+", "1", "]", "=", "(", "byte", ")", "(", "0xFF", "&", "value", ")", ";", "}" ]
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
160,987
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", ")", ")", ";", "bytes", "[", "offset", "+", "1", "]", "=", "(", "byte", ")", "(", "0xFF", "&", "value", ")", ";", "}" ]
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
160,988
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", "[", "offset", "+", "1", "]", "=", "(", "byte", ")", "(", "0xFF", "&", "(", "value", ">>", "16", ")", ")", ";", "bytes", "[", "offset", "+", "2", "]", "=", "(", "byte", ")", "(", "0xFF", "&", "(", "value", ">>", "8", ")", ")", ";", "bytes", "[", "offset", "+", "3", "]", "=", "(", "byte", ")", "(", "0xFF", "&", "value", ")", ";", "}" ]
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
160,989
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", ";", "i", ">=", "offset", ";", "i", "--", ")", "{", "bytes", "[", "i", "]", "=", "(", "byte", ")", "(", "0xFF", "&", "(", "value", ">>", "shift", ")", ")", ";", "shift", "+=", "8", ";", "}", "}" ]
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
160,990
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", "(", "number", "<", "(", "1L", "<<", "(", "8", "*", "i", ")", ")", ")", "return", "i", ";", "throw", "new", "IllegalStateException", "(", "\"Should never happen.\"", ")", ";", "}" ]
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
160,991
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", "=", "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", ";", "}", "}" ]
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
160,992
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", ")", "{", "throw", "new", "IllegalArgumentException", "(", "encoding", "+", "\" is not a known encoding name.\"", ",", "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
160,993
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", ")", "{", "throw", "new", "IllegalArgumentException", "(", "encoding", "+", "\" is not a known encoding name.\"", ",", "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
160,994
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", ";", "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.\"", ")", ";", "}", "}" ]
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
160,995
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", ".", "trace", "(", "\"Adding event \"", "+", "event", ")", ";", "eventQueue", ".", "add", "(", "event", ")", ";", "}" ]
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
160,996
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", "(", "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", ";", "}", "}" ]
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
160,997
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", "(", "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", ")", ";", "}", "}" ]
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", "notifications" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L81-L103
160,998
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", "(", "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", "(", ")", "]", ")", ";", "}" ]
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", "annotation", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L113-L146
160,999
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", "=", "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", ";", "}" ]
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