repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
voldemort/voldemort | src/java/voldemort/utils/ReflectUtils.java | ReflectUtils.callConstructor | public static <T> T callConstructor(Class<T> klass) {
return callConstructor(klass, new Class<?>[0], new Object[0]);
} | java | public static <T> T callConstructor(Class<T> klass) {
return callConstructor(klass, new Class<?>[0], new Object[0]);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"callConstructor",
"(",
"Class",
"<",
"T",
">",
"klass",
")",
"{",
"return",
"callConstructor",
"(",
"klass",
",",
"new",
"Class",
"<",
"?",
">",
"[",
"0",
"]",
",",
"new",
"Object",
"[",
"0",
"]",
")",
";"... | Call the no-arg constructor for the given class
@param <T> The type of the thing to construct
@param klass The class
@return The constructed thing | [
"Call",
"the",
"no",
"-",
"arg",
"constructor",
"for",
"the",
"given",
"class"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ReflectUtils.java#L85-L87 | train |
voldemort/voldemort | src/java/voldemort/utils/ReflectUtils.java | ReflectUtils.callConstructor | public static <T> T callConstructor(Class<T> klass, Object[] args) {
Class<?>[] klasses = new Class[args.length];
for(int i = 0; i < args.length; i++)
klasses[i] = args[i].getClass();
return callConstructor(klass, klasses, args);
} | java | public static <T> T callConstructor(Class<T> klass, Object[] args) {
Class<?>[] klasses = new Class[args.length];
for(int i = 0; i < args.length; i++)
klasses[i] = args[i].getClass();
return callConstructor(klass, klasses, args);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"callConstructor",
"(",
"Class",
"<",
"T",
">",
"klass",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"klasses",
"=",
"new",
"Class",
"[",
"args",
".",
"length",
"]",
";",
... | Call the constructor for the given class, inferring the correct types for
the arguments. This could be confusing if there are multiple constructors
with the same number of arguments and the values themselves don't
disambiguate.
@param klass The class to construct
@param args The arguments
@return The constructed value | [
"Call",
"the",
"constructor",
"for",
"the",
"given",
"class",
"inferring",
"the",
"correct",
"types",
"for",
"the",
"arguments",
".",
"This",
"could",
"be",
"confusing",
"if",
"there",
"are",
"multiple",
"constructors",
"with",
"the",
"same",
"number",
"of",
... | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ReflectUtils.java#L99-L104 | train |
voldemort/voldemort | src/java/voldemort/utils/ReflectUtils.java | ReflectUtils.callMethod | public static <T> Object callMethod(Object obj,
Class<T> c,
String name,
Class<?>[] classes,
Object[] args) {
try {
Method m = getMethod(c, name, classes);
return m.invoke(obj, args);
} catch(InvocationTargetException e) {
throw getCause(e);
} catch(IllegalAccessException e) {
throw new IllegalStateException(e);
}
} | java | public static <T> Object callMethod(Object obj,
Class<T> c,
String name,
Class<?>[] classes,
Object[] args) {
try {
Method m = getMethod(c, name, classes);
return m.invoke(obj, args);
} catch(InvocationTargetException e) {
throw getCause(e);
} catch(IllegalAccessException e) {
throw new IllegalStateException(e);
}
} | [
"public",
"static",
"<",
"T",
">",
"Object",
"callMethod",
"(",
"Object",
"obj",
",",
"Class",
"<",
"T",
">",
"c",
",",
"String",
"name",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"classes",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"try",
"{",
"... | Call the named method
@param obj The object to call the method on
@param c The class of the object
@param name The name of the method
@param args The method arguments
@return The result of the method | [
"Call",
"the",
"named",
"method"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ReflectUtils.java#L137-L150 | train |
voldemort/voldemort | src/java/voldemort/utils/ReflectUtils.java | ReflectUtils.getMethod | public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {
try {
return c.getMethod(name, argTypes);
} catch(NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
} | java | public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {
try {
return c.getMethod(name, argTypes);
} catch(NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
} | [
"public",
"static",
"<",
"T",
">",
"Method",
"getMethod",
"(",
"Class",
"<",
"T",
">",
"c",
",",
"String",
"name",
",",
"Class",
"<",
"?",
">",
"...",
"argTypes",
")",
"{",
"try",
"{",
"return",
"c",
".",
"getMethod",
"(",
"name",
",",
"argTypes",
... | Get the named method from the class
@param c The class to get the method from
@param name The method name
@param argTypes The argument types
@return The method | [
"Get",
"the",
"named",
"method",
"from",
"the",
"class"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ReflectUtils.java#L160-L166 | train |
voldemort/voldemort | src/java/voldemort/server/storage/prunejob/VersionedPutPruneJob.java | VersionedPutPruneJob.pruneNonReplicaEntries | public static List<Versioned<byte[]>> pruneNonReplicaEntries(List<Versioned<byte[]>> vals,
List<Integer> keyReplicas,
MutableBoolean didPrune) {
List<Versioned<byte[]>> prunedVals = new ArrayList<Versioned<byte[]>>(vals.size());
for(Versioned<byte[]> val: vals) {
VectorClock clock = (VectorClock) val.getVersion();
List<ClockEntry> clockEntries = new ArrayList<ClockEntry>();
for(ClockEntry clockEntry: clock.getEntries()) {
if(keyReplicas.contains((int) clockEntry.getNodeId())) {
clockEntries.add(clockEntry);
} else {
didPrune.setValue(true);
}
}
prunedVals.add(new Versioned<byte[]>(val.getValue(),
new VectorClock(clockEntries, clock.getTimestamp())));
}
return prunedVals;
} | java | public static List<Versioned<byte[]>> pruneNonReplicaEntries(List<Versioned<byte[]>> vals,
List<Integer> keyReplicas,
MutableBoolean didPrune) {
List<Versioned<byte[]>> prunedVals = new ArrayList<Versioned<byte[]>>(vals.size());
for(Versioned<byte[]> val: vals) {
VectorClock clock = (VectorClock) val.getVersion();
List<ClockEntry> clockEntries = new ArrayList<ClockEntry>();
for(ClockEntry clockEntry: clock.getEntries()) {
if(keyReplicas.contains((int) clockEntry.getNodeId())) {
clockEntries.add(clockEntry);
} else {
didPrune.setValue(true);
}
}
prunedVals.add(new Versioned<byte[]>(val.getValue(),
new VectorClock(clockEntries, clock.getTimestamp())));
}
return prunedVals;
} | [
"public",
"static",
"List",
"<",
"Versioned",
"<",
"byte",
"[",
"]",
">",
">",
"pruneNonReplicaEntries",
"(",
"List",
"<",
"Versioned",
"<",
"byte",
"[",
"]",
">",
">",
"vals",
",",
"List",
"<",
"Integer",
">",
"keyReplicas",
",",
"MutableBoolean",
"didP... | Remove all non replica clock entries from the list of versioned values
provided
@param vals list of versioned values to prune replicas from
@param keyReplicas list of current replicas for the given key
@param didPrune flag to mark if we did actually prune something
@return pruned list | [
"Remove",
"all",
"non",
"replica",
"clock",
"entries",
"from",
"the",
"list",
"of",
"versioned",
"values",
"provided"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/storage/prunejob/VersionedPutPruneJob.java#L181-L199 | train |
voldemort/voldemort | src/java/voldemort/serialization/ObjectSerializer.java | ObjectSerializer.toBytes | public byte[] toBytes(T object) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(stream);
out.writeObject(object);
return stream.toByteArray();
} catch(IOException e) {
throw new SerializationException(e);
}
} | java | public byte[] toBytes(T object) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(stream);
out.writeObject(object);
return stream.toByteArray();
} catch(IOException e) {
throw new SerializationException(e);
}
} | [
"public",
"byte",
"[",
"]",
"toBytes",
"(",
"T",
"object",
")",
"{",
"try",
"{",
"ByteArrayOutputStream",
"stream",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"ObjectOutputStream",
"out",
"=",
"new",
"ObjectOutputStream",
"(",
"stream",
")",
";",
"o... | Transform the given object into an array of bytes
@param object The object to be serialized
@return The bytes created from serializing the object | [
"Transform",
"the",
"given",
"object",
"into",
"an",
"array",
"of",
"bytes"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/serialization/ObjectSerializer.java#L40-L49 | train |
voldemort/voldemort | src/java/voldemort/serialization/ObjectSerializer.java | ObjectSerializer.toObject | @SuppressWarnings("unchecked")
public T toObject(byte[] bytes) {
try {
return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
} catch(IOException e) {
throw new SerializationException(e);
} catch(ClassNotFoundException c) {
throw new SerializationException(c);
}
} | java | @SuppressWarnings("unchecked")
public T toObject(byte[] bytes) {
try {
return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
} catch(IOException e) {
throw new SerializationException(e);
} catch(ClassNotFoundException c) {
throw new SerializationException(c);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"T",
"toObject",
"(",
"byte",
"[",
"]",
"bytes",
")",
"{",
"try",
"{",
"return",
"(",
"T",
")",
"new",
"ObjectInputStream",
"(",
"new",
"ByteArrayInputStream",
"(",
"bytes",
")",
")",
".",
"re... | Transform the given bytes into an object.
@param bytes The bytes to construct the object from
@return The object constructed | [
"Transform",
"the",
"given",
"bytes",
"into",
"an",
"object",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/serialization/ObjectSerializer.java#L57-L66 | train |
voldemort/voldemort | src/java/voldemort/server/protocol/vold/VoldemortNativeRequestHandler.java | VoldemortNativeRequestHandler.isCompleteRequest | @Override
public boolean isCompleteRequest(final ByteBuffer buffer) throws VoldemortException {
DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));
try {
byte opCode = inputStream.readByte();
// Store Name
inputStream.readUTF();
// Store routing type
getRoutingType(inputStream);
switch(opCode) {
case VoldemortOpCode.GET_VERSION_OP_CODE:
if(!GetVersionRequestHandler.isCompleteRequest(inputStream, buffer))
return false;
break;
case VoldemortOpCode.GET_OP_CODE:
if(!GetRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))
return false;
break;
case VoldemortOpCode.GET_ALL_OP_CODE:
if(!GetAllRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))
return false;
break;
case VoldemortOpCode.PUT_OP_CODE: {
if(!PutRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))
return false;
break;
}
case VoldemortOpCode.DELETE_OP_CODE: {
if(!DeleteRequestHandler.isCompleteRequest(inputStream, buffer))
return false;
break;
}
default:
throw new VoldemortException(" Unrecognized Voldemort OpCode " + opCode);
}
// This should not happen, if we reach here and if buffer has more
// data, there is something wrong.
if(buffer.hasRemaining()) {
logger.info("Probably a client bug, Discarding additional bytes in isCompleteRequest. Opcode: "
+ opCode + ", remaining bytes: " + buffer.remaining());
}
return true;
} catch(IOException 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.isDebugEnabled())
logger.debug("Probable partial read occurred causing exception", e);
return false;
}
} | java | @Override
public boolean isCompleteRequest(final ByteBuffer buffer) throws VoldemortException {
DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));
try {
byte opCode = inputStream.readByte();
// Store Name
inputStream.readUTF();
// Store routing type
getRoutingType(inputStream);
switch(opCode) {
case VoldemortOpCode.GET_VERSION_OP_CODE:
if(!GetVersionRequestHandler.isCompleteRequest(inputStream, buffer))
return false;
break;
case VoldemortOpCode.GET_OP_CODE:
if(!GetRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))
return false;
break;
case VoldemortOpCode.GET_ALL_OP_CODE:
if(!GetAllRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))
return false;
break;
case VoldemortOpCode.PUT_OP_CODE: {
if(!PutRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))
return false;
break;
}
case VoldemortOpCode.DELETE_OP_CODE: {
if(!DeleteRequestHandler.isCompleteRequest(inputStream, buffer))
return false;
break;
}
default:
throw new VoldemortException(" Unrecognized Voldemort OpCode " + opCode);
}
// This should not happen, if we reach here and if buffer has more
// data, there is something wrong.
if(buffer.hasRemaining()) {
logger.info("Probably a client bug, Discarding additional bytes in isCompleteRequest. Opcode: "
+ opCode + ", remaining bytes: " + buffer.remaining());
}
return true;
} catch(IOException 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.isDebugEnabled())
logger.debug("Probable partial read occurred causing exception", e);
return false;
}
} | [
"@",
"Override",
"public",
"boolean",
"isCompleteRequest",
"(",
"final",
"ByteBuffer",
"buffer",
")",
"throws",
"VoldemortException",
"{",
"DataInputStream",
"inputStream",
"=",
"new",
"DataInputStream",
"(",
"new",
"ByteBufferBackedInputStream",
"(",
"buffer",
")",
"... | This is pretty ugly. We end up mimicking the request logic here, so this
needs to stay in sync with handleRequest. | [
"This",
"is",
"pretty",
"ugly",
".",
"We",
"end",
"up",
"mimicking",
"the",
"request",
"logic",
"here",
"so",
"this",
"needs",
"to",
"stay",
"in",
"sync",
"with",
"handleRequest",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/vold/VoldemortNativeRequestHandler.java#L161-L216 | train |
voldemort/voldemort | src/java/voldemort/utils/WriteThroughCache.java | WriteThroughCache.put | @Override
synchronized public V put(K key, V value) {
V oldValue = this.get(key);
try {
super.put(key, value);
writeBack(key, value);
return oldValue;
} catch(Exception e) {
super.put(key, oldValue);
writeBack(key, oldValue);
throw new VoldemortException("Failed to put(" + key + ", " + value
+ ") in write through cache", e);
}
} | java | @Override
synchronized public V put(K key, V value) {
V oldValue = this.get(key);
try {
super.put(key, value);
writeBack(key, value);
return oldValue;
} catch(Exception e) {
super.put(key, oldValue);
writeBack(key, oldValue);
throw new VoldemortException("Failed to put(" + key + ", " + value
+ ") in write through cache", e);
}
} | [
"@",
"Override",
"synchronized",
"public",
"V",
"put",
"(",
"K",
"key",
",",
"V",
"value",
")",
"{",
"V",
"oldValue",
"=",
"this",
".",
"get",
"(",
"key",
")",
";",
"try",
"{",
"super",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"writeBack",... | Updates the value in HashMap and writeBack as Atomic step | [
"Updates",
"the",
"value",
"in",
"HashMap",
"and",
"writeBack",
"as",
"Atomic",
"step"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/WriteThroughCache.java#L55-L68 | train |
voldemort/voldemort | src/java/voldemort/store/readonly/checksum/CheckSum.java | CheckSum.update | public void update(int number) {
byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_INT];
ByteUtils.writeInt(numberInBytes, number, 0);
update(numberInBytes);
} | java | public void update(int number) {
byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_INT];
ByteUtils.writeInt(numberInBytes, number, 0);
update(numberInBytes);
} | [
"public",
"void",
"update",
"(",
"int",
"number",
")",
"{",
"byte",
"[",
"]",
"numberInBytes",
"=",
"new",
"byte",
"[",
"ByteUtils",
".",
"SIZE_OF_INT",
"]",
";",
"ByteUtils",
".",
"writeInt",
"(",
"numberInBytes",
",",
"number",
",",
"0",
")",
";",
"u... | Update the underlying buffer using the integer
@param number number to be stored in checksum buffer | [
"Update",
"the",
"underlying",
"buffer",
"using",
"the",
"integer"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/checksum/CheckSum.java#L64-L68 | train |
voldemort/voldemort | src/java/voldemort/store/readonly/checksum/CheckSum.java | CheckSum.update | public void update(short number) {
byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_SHORT];
ByteUtils.writeShort(numberInBytes, number, 0);
update(numberInBytes);
} | java | public void update(short number) {
byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_SHORT];
ByteUtils.writeShort(numberInBytes, number, 0);
update(numberInBytes);
} | [
"public",
"void",
"update",
"(",
"short",
"number",
")",
"{",
"byte",
"[",
"]",
"numberInBytes",
"=",
"new",
"byte",
"[",
"ByteUtils",
".",
"SIZE_OF_SHORT",
"]",
";",
"ByteUtils",
".",
"writeShort",
"(",
"numberInBytes",
",",
"number",
",",
"0",
")",
";"... | Update the underlying buffer using the short
@param number number to be stored in checksum buffer | [
"Update",
"the",
"underlying",
"buffer",
"using",
"the",
"short"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/checksum/CheckSum.java#L75-L79 | train |
voldemort/voldemort | src/java/voldemort/store/routed/action/AsyncPutSynchronizer.java | AsyncPutSynchronizer.tryDelegateSlop | public synchronized boolean tryDelegateSlop(Node node) {
if(asyncCallbackShouldSendhint) {
return false;
} else {
slopDestinations.put(node, true);
return true;
}
} | java | public synchronized boolean tryDelegateSlop(Node node) {
if(asyncCallbackShouldSendhint) {
return false;
} else {
slopDestinations.put(node, true);
return true;
}
} | [
"public",
"synchronized",
"boolean",
"tryDelegateSlop",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"asyncCallbackShouldSendhint",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"slopDestinations",
".",
"put",
"(",
"node",
",",
"true",
")",
";",
"return",... | Try to delegate the responsibility of sending slops to master
@param node The node that slop should eventually be pushed to
@return true if master accept the responsibility; false if master does
not accept | [
"Try",
"to",
"delegate",
"the",
"responsibility",
"of",
"sending",
"slops",
"to",
"master"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/action/AsyncPutSynchronizer.java#L64-L71 | train |
voldemort/voldemort | src/java/voldemort/store/routed/action/AsyncPutSynchronizer.java | AsyncPutSynchronizer.tryDelegateResponseHandling | public synchronized boolean tryDelegateResponseHandling(Response<ByteArray, Object> response) {
if(responseHandlingCutoff) {
return false;
} else {
responseQueue.offer(response);
this.notifyAll();
return true;
}
} | java | public synchronized boolean tryDelegateResponseHandling(Response<ByteArray, Object> response) {
if(responseHandlingCutoff) {
return false;
} else {
responseQueue.offer(response);
this.notifyAll();
return true;
}
} | [
"public",
"synchronized",
"boolean",
"tryDelegateResponseHandling",
"(",
"Response",
"<",
"ByteArray",
",",
"Object",
">",
"response",
")",
"{",
"if",
"(",
"responseHandlingCutoff",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"responseQueue",
".",
"offer... | try to delegate the master to handle the response
@param response
@return true if the master accepted the response; false if the master
didn't accept | [
"try",
"to",
"delegate",
"the",
"master",
"to",
"handle",
"the",
"response"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/action/AsyncPutSynchronizer.java#L87-L95 | train |
voldemort/voldemort | src/java/voldemort/store/routed/action/AsyncPutSynchronizer.java | AsyncPutSynchronizer.responseQueuePoll | public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,
TimeUnit timeUnit)
throws InterruptedException {
long timeoutMs = timeUnit.toMillis(timeout);
long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;
while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {
long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());
if(logger.isDebugEnabled()) {
logger.debug("Start waiting for response queue with timeoutMs: " + timeoutMs);
}
this.wait(remainingMs);
if(logger.isDebugEnabled()) {
logger.debug("End waiting for response queue with timeoutMs: " + timeoutMs);
}
}
return responseQueue.poll();
} | java | public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,
TimeUnit timeUnit)
throws InterruptedException {
long timeoutMs = timeUnit.toMillis(timeout);
long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;
while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {
long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());
if(logger.isDebugEnabled()) {
logger.debug("Start waiting for response queue with timeoutMs: " + timeoutMs);
}
this.wait(remainingMs);
if(logger.isDebugEnabled()) {
logger.debug("End waiting for response queue with timeoutMs: " + timeoutMs);
}
}
return responseQueue.poll();
} | [
"public",
"synchronized",
"Response",
"<",
"ByteArray",
",",
"Object",
">",
"responseQueuePoll",
"(",
"long",
"timeout",
",",
"TimeUnit",
"timeUnit",
")",
"throws",
"InterruptedException",
"{",
"long",
"timeoutMs",
"=",
"timeUnit",
".",
"toMillis",
"(",
"timeout",... | poll the response queue for response
@param timeout timeout amount
@param timeUnit timeUnit of timeout
@return same result of BlockQueue.poll(long, TimeUnit)
@throws InterruptedException | [
"poll",
"the",
"response",
"queue",
"for",
"response"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/action/AsyncPutSynchronizer.java#L105-L121 | train |
voldemort/voldemort | contrib/restclient/src/java/voldemort/restclient/RESTClientConfig.java | RESTClientConfig.setProperties | private void setProperties(Properties properties) {
Props props = new Props(properties);
if(props.containsKey(ClientConfig.ENABLE_JMX_PROPERTY)) {
this.setEnableJmx(props.getBoolean(ClientConfig.ENABLE_JMX_PROPERTY));
}
if(props.containsKey(ClientConfig.BOOTSTRAP_URLS_PROPERTY)) {
List<String> urls = props.getList(ClientConfig.BOOTSTRAP_URLS_PROPERTY);
if(urls.size() > 0) {
setHttpBootstrapURL(urls.get(0));
}
}
if(props.containsKey(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY)) {
setMaxR2ConnectionPoolSize(props.getInt(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY,
maxR2ConnectionPoolSize));
}
if(props.containsKey(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY))
this.setTimeoutMs(props.getLong(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY, timeoutMs),
TimeUnit.MILLISECONDS);
// By default, make all the timeouts equal to routing timeout
timeoutConfig = new TimeoutConfig(timeoutMs, false);
if(props.containsKey(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY))
timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE,
props.getInt(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY));
if(props.containsKey(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY))
timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_OP_CODE,
props.getInt(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY));
if(props.containsKey(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY)) {
long putTimeoutMs = props.getInt(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY);
timeoutConfig.setOperationTimeout(VoldemortOpCode.PUT_OP_CODE, putTimeoutMs);
// By default, use the same thing for getVersions() also
timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE, putTimeoutMs);
}
// of course, if someone overrides it, we will respect that
if(props.containsKey(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY))
timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE,
props.getInt(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY));
if(props.containsKey(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY))
timeoutConfig.setOperationTimeout(VoldemortOpCode.DELETE_OP_CODE,
props.getInt(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY));
if(props.containsKey(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY))
timeoutConfig.setPartialGetAllAllowed(props.getBoolean(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY));
} | java | private void setProperties(Properties properties) {
Props props = new Props(properties);
if(props.containsKey(ClientConfig.ENABLE_JMX_PROPERTY)) {
this.setEnableJmx(props.getBoolean(ClientConfig.ENABLE_JMX_PROPERTY));
}
if(props.containsKey(ClientConfig.BOOTSTRAP_URLS_PROPERTY)) {
List<String> urls = props.getList(ClientConfig.BOOTSTRAP_URLS_PROPERTY);
if(urls.size() > 0) {
setHttpBootstrapURL(urls.get(0));
}
}
if(props.containsKey(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY)) {
setMaxR2ConnectionPoolSize(props.getInt(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY,
maxR2ConnectionPoolSize));
}
if(props.containsKey(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY))
this.setTimeoutMs(props.getLong(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY, timeoutMs),
TimeUnit.MILLISECONDS);
// By default, make all the timeouts equal to routing timeout
timeoutConfig = new TimeoutConfig(timeoutMs, false);
if(props.containsKey(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY))
timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE,
props.getInt(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY));
if(props.containsKey(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY))
timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_OP_CODE,
props.getInt(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY));
if(props.containsKey(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY)) {
long putTimeoutMs = props.getInt(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY);
timeoutConfig.setOperationTimeout(VoldemortOpCode.PUT_OP_CODE, putTimeoutMs);
// By default, use the same thing for getVersions() also
timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE, putTimeoutMs);
}
// of course, if someone overrides it, we will respect that
if(props.containsKey(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY))
timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE,
props.getInt(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY));
if(props.containsKey(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY))
timeoutConfig.setOperationTimeout(VoldemortOpCode.DELETE_OP_CODE,
props.getInt(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY));
if(props.containsKey(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY))
timeoutConfig.setPartialGetAllAllowed(props.getBoolean(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY));
} | [
"private",
"void",
"setProperties",
"(",
"Properties",
"properties",
")",
"{",
"Props",
"props",
"=",
"new",
"Props",
"(",
"properties",
")",
";",
"if",
"(",
"props",
".",
"containsKey",
"(",
"ClientConfig",
".",
"ENABLE_JMX_PROPERTY",
")",
")",
"{",
"this",... | Set the values using the specified Properties object.
@param properties Properties object containing specific property values
for the RESTClient config
Note: We're using the same property names as that in ClientConfig
for backwards compatibility. | [
"Set",
"the",
"values",
"using",
"the",
"specified",
"Properties",
"object",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/restclient/src/java/voldemort/restclient/RESTClientConfig.java#L76-L128 | train |
voldemort/voldemort | src/java/voldemort/rest/coordinator/config/CoordinatorConfig.java | CoordinatorConfig.setProperties | private void setProperties(Properties properties) {
Props props = new Props(properties);
if(props.containsKey(BOOTSTRAP_URLS_PROPERTY)) {
setBootstrapURLs(props.getList(BOOTSTRAP_URLS_PROPERTY));
}
if(props.containsKey(FAT_CLIENTS_CONFIG_SOURCE)) {
setFatClientConfigSource(StoreClientConfigSource.get(props.getString(FAT_CLIENTS_CONFIG_SOURCE)));
}
if(props.containsKey(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY)) {
setFatClientConfigPath(props.getString(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY));
}
if(props.containsKey(METADATA_CHECK_INTERVAL_IN_MS)) {
setMetadataCheckIntervalInMs(props.getInt(METADATA_CHECK_INTERVAL_IN_MS));
}
if(props.containsKey(NETTY_SERVER_PORT)) {
setServerPort(props.getInt(NETTY_SERVER_PORT));
}
if(props.containsKey(NETTY_SERVER_BACKLOG)) {
setNettyServerBacklog(props.getInt(NETTY_SERVER_BACKLOG));
}
if(props.containsKey(COORDINATOR_CORE_THREADS)) {
setCoordinatorCoreThreads(props.getInt(COORDINATOR_CORE_THREADS));
}
if(props.containsKey(COORDINATOR_MAX_THREADS)) {
setCoordinatorMaxThreads(props.getInt(COORDINATOR_MAX_THREADS));
}
if(props.containsKey(COORDINATOR_QUEUED_REQUESTS)) {
setCoordinatorQueuedRequestsSize(props.getInt(COORDINATOR_QUEUED_REQUESTS));
}
if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH)) {
setHttpMessageDecoderMaxInitialLength(props.getInt(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH));
}
if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE)) {
setHttpMessageDecoderMaxHeaderSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE));
}
if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE)) {
setHttpMessageDecoderMaxChunkSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE));
}
if(props.containsKey(ADMIN_ENABLE)) {
setAdminServiceEnabled(props.getBoolean(ADMIN_ENABLE));
}
if(props.containsKey(ADMIN_PORT)) {
setAdminPort(props.getInt(ADMIN_PORT));
}
} | java | private void setProperties(Properties properties) {
Props props = new Props(properties);
if(props.containsKey(BOOTSTRAP_URLS_PROPERTY)) {
setBootstrapURLs(props.getList(BOOTSTRAP_URLS_PROPERTY));
}
if(props.containsKey(FAT_CLIENTS_CONFIG_SOURCE)) {
setFatClientConfigSource(StoreClientConfigSource.get(props.getString(FAT_CLIENTS_CONFIG_SOURCE)));
}
if(props.containsKey(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY)) {
setFatClientConfigPath(props.getString(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY));
}
if(props.containsKey(METADATA_CHECK_INTERVAL_IN_MS)) {
setMetadataCheckIntervalInMs(props.getInt(METADATA_CHECK_INTERVAL_IN_MS));
}
if(props.containsKey(NETTY_SERVER_PORT)) {
setServerPort(props.getInt(NETTY_SERVER_PORT));
}
if(props.containsKey(NETTY_SERVER_BACKLOG)) {
setNettyServerBacklog(props.getInt(NETTY_SERVER_BACKLOG));
}
if(props.containsKey(COORDINATOR_CORE_THREADS)) {
setCoordinatorCoreThreads(props.getInt(COORDINATOR_CORE_THREADS));
}
if(props.containsKey(COORDINATOR_MAX_THREADS)) {
setCoordinatorMaxThreads(props.getInt(COORDINATOR_MAX_THREADS));
}
if(props.containsKey(COORDINATOR_QUEUED_REQUESTS)) {
setCoordinatorQueuedRequestsSize(props.getInt(COORDINATOR_QUEUED_REQUESTS));
}
if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH)) {
setHttpMessageDecoderMaxInitialLength(props.getInt(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH));
}
if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE)) {
setHttpMessageDecoderMaxHeaderSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE));
}
if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE)) {
setHttpMessageDecoderMaxChunkSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE));
}
if(props.containsKey(ADMIN_ENABLE)) {
setAdminServiceEnabled(props.getBoolean(ADMIN_ENABLE));
}
if(props.containsKey(ADMIN_PORT)) {
setAdminPort(props.getInt(ADMIN_PORT));
}
} | [
"private",
"void",
"setProperties",
"(",
"Properties",
"properties",
")",
"{",
"Props",
"props",
"=",
"new",
"Props",
"(",
"properties",
")",
";",
"if",
"(",
"props",
".",
"containsKey",
"(",
"BOOTSTRAP_URLS_PROPERTY",
")",
")",
"{",
"setBootstrapURLs",
"(",
... | Set the values using the specified Properties object
@param properties Properties object containing specific property values
for the Coordinator config | [
"Set",
"the",
"values",
"using",
"the",
"specified",
"Properties",
"object"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/config/CoordinatorConfig.java#L115-L173 | train |
voldemort/voldemort | src/java/voldemort/rest/coordinator/config/CoordinatorConfig.java | CoordinatorConfig.setBootstrapURLs | public CoordinatorConfig setBootstrapURLs(List<String> bootstrapUrls) {
this.bootstrapURLs = Utils.notNull(bootstrapUrls);
if(this.bootstrapURLs.size() <= 0)
throw new IllegalArgumentException("Must provide at least one bootstrap URL.");
return this;
} | java | public CoordinatorConfig setBootstrapURLs(List<String> bootstrapUrls) {
this.bootstrapURLs = Utils.notNull(bootstrapUrls);
if(this.bootstrapURLs.size() <= 0)
throw new IllegalArgumentException("Must provide at least one bootstrap URL.");
return this;
} | [
"public",
"CoordinatorConfig",
"setBootstrapURLs",
"(",
"List",
"<",
"String",
">",
"bootstrapUrls",
")",
"{",
"this",
".",
"bootstrapURLs",
"=",
"Utils",
".",
"notNull",
"(",
"bootstrapUrls",
")",
";",
"if",
"(",
"this",
".",
"bootstrapURLs",
".",
"size",
"... | Sets the bootstrap URLs used by the different Fat clients inside the
Coordinator
@param bootstrapUrls list of bootstrap URLs defining which cluster to
connect to
@return modified CoordinatorConfig | [
"Sets",
"the",
"bootstrap",
"URLs",
"used",
"by",
"the",
"different",
"Fat",
"clients",
"inside",
"the",
"Coordinator"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/config/CoordinatorConfig.java#L189-L194 | train |
voldemort/voldemort | src/java/voldemort/store/slop/HintedHandoff.java | HintedHandoff.sendOneAsyncHint | private void sendOneAsyncHint(final ByteArray slopKey,
final Versioned<byte[]> slopVersioned,
final List<Node> nodesToTry) {
Node nodeToHostHint = null;
boolean foundNode = false;
while(nodesToTry.size() > 0) {
nodeToHostHint = nodesToTry.remove(0);
if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {
foundNode = true;
break;
}
}
if(!foundNode) {
Slop slop = slopSerializer.toObject(slopVersioned.getValue());
logger.error("Trying to send an async hint but used up all nodes. key: "
+ slop.getKey() + " version: " + slopVersioned.getVersion().toString());
return;
}
final Node node = nodeToHostHint;
int nodeId = node.getId();
NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);
Utils.notNull(nonblockingStore);
final Long startNs = System.nanoTime();
NonblockingStoreCallback callback = new NonblockingStoreCallback() {
@Override
public void requestComplete(Object result, long requestTime) {
Slop slop = null;
boolean loggerDebugEnabled = logger.isDebugEnabled();
if(loggerDebugEnabled) {
slop = slopSerializer.toObject(slopVersioned.getValue());
}
Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,
slopKey,
result,
requestTime);
if(response.getValue() instanceof Exception
&& !(response.getValue() instanceof ObsoleteVersionException)) {
if(!failedNodes.contains(node))
failedNodes.add(node);
if(response.getValue() instanceof UnreachableStoreException) {
UnreachableStoreException use = (UnreachableStoreException) response.getValue();
if(loggerDebugEnabled) {
logger.debug("Write of key " + slop.getKey() + " for "
+ slop.getNodeId() + " to node " + node
+ " failed due to unreachable: " + use.getMessage());
}
failureDetector.recordException(node, (System.nanoTime() - startNs)
/ Time.NS_PER_MS, use);
}
sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);
}
if(loggerDebugEnabled)
logger.debug("Slop write of key " + slop.getKey() + " for node "
+ slop.getNodeId() + " to node " + node + " succeeded in "
+ (System.nanoTime() - startNs) + " ns");
failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);
}
};
nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);
} | java | private void sendOneAsyncHint(final ByteArray slopKey,
final Versioned<byte[]> slopVersioned,
final List<Node> nodesToTry) {
Node nodeToHostHint = null;
boolean foundNode = false;
while(nodesToTry.size() > 0) {
nodeToHostHint = nodesToTry.remove(0);
if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {
foundNode = true;
break;
}
}
if(!foundNode) {
Slop slop = slopSerializer.toObject(slopVersioned.getValue());
logger.error("Trying to send an async hint but used up all nodes. key: "
+ slop.getKey() + " version: " + slopVersioned.getVersion().toString());
return;
}
final Node node = nodeToHostHint;
int nodeId = node.getId();
NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);
Utils.notNull(nonblockingStore);
final Long startNs = System.nanoTime();
NonblockingStoreCallback callback = new NonblockingStoreCallback() {
@Override
public void requestComplete(Object result, long requestTime) {
Slop slop = null;
boolean loggerDebugEnabled = logger.isDebugEnabled();
if(loggerDebugEnabled) {
slop = slopSerializer.toObject(slopVersioned.getValue());
}
Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,
slopKey,
result,
requestTime);
if(response.getValue() instanceof Exception
&& !(response.getValue() instanceof ObsoleteVersionException)) {
if(!failedNodes.contains(node))
failedNodes.add(node);
if(response.getValue() instanceof UnreachableStoreException) {
UnreachableStoreException use = (UnreachableStoreException) response.getValue();
if(loggerDebugEnabled) {
logger.debug("Write of key " + slop.getKey() + " for "
+ slop.getNodeId() + " to node " + node
+ " failed due to unreachable: " + use.getMessage());
}
failureDetector.recordException(node, (System.nanoTime() - startNs)
/ Time.NS_PER_MS, use);
}
sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);
}
if(loggerDebugEnabled)
logger.debug("Slop write of key " + slop.getKey() + " for node "
+ slop.getNodeId() + " to node " + node + " succeeded in "
+ (System.nanoTime() - startNs) + " ns");
failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);
}
};
nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);
} | [
"private",
"void",
"sendOneAsyncHint",
"(",
"final",
"ByteArray",
"slopKey",
",",
"final",
"Versioned",
"<",
"byte",
"[",
"]",
">",
"slopVersioned",
",",
"final",
"List",
"<",
"Node",
">",
"nodesToTry",
")",
"{",
"Node",
"nodeToHostHint",
"=",
"null",
";",
... | A callback that handles requestComplete event from NIO selector manager
Will try any possible nodes and pass itself as callback util all nodes
are exhausted
@param slopKey
@param slopVersioned
@param nodesToTry List of nodes to try to contact. Will become shorter
after each callback | [
"A",
"callback",
"that",
"handles",
"requestComplete",
"event",
"from",
"NIO",
"selector",
"manager",
"Will",
"try",
"any",
"possible",
"nodes",
"and",
"pass",
"itself",
"as",
"callback",
"util",
"all",
"nodes",
"are",
"exhausted"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/slop/HintedHandoff.java#L127-L194 | train |
voldemort/voldemort | src/java/voldemort/store/readonly/ExternalSorter.java | ExternalSorter.sorted | public Iterable<V> sorted(Iterator<V> input) {
ExecutorService executor = new ThreadPoolExecutor(this.numThreads,
this.numThreads,
1000L,
TimeUnit.MILLISECONDS,
new SynchronousQueue<Runnable>(),
new CallerRunsPolicy());
final AtomicInteger count = new AtomicInteger(0);
final List<File> tempFiles = Collections.synchronizedList(new ArrayList<File>());
while(input.hasNext()) {
final int segmentId = count.getAndIncrement();
final long segmentStartMs = System.currentTimeMillis();
logger.info("Segment " + segmentId + ": filling sort buffer for segment...");
@SuppressWarnings("unchecked")
final V[] buffer = (V[]) new Object[internalSortSize];
int segmentSizeIter = 0;
for(; segmentSizeIter < internalSortSize && input.hasNext(); segmentSizeIter++)
buffer[segmentSizeIter] = input.next();
final int segmentSize = segmentSizeIter;
logger.info("Segment " + segmentId + ": sort buffer filled...adding to sort queue.");
// sort and write out asynchronously
executor.execute(new Runnable() {
public void run() {
logger.info("Segment " + segmentId + ": sorting buffer.");
long start = System.currentTimeMillis();
Arrays.sort(buffer, 0, segmentSize, comparator);
long elapsed = System.currentTimeMillis() - start;
logger.info("Segment " + segmentId + ": sort completed in " + elapsed
+ " ms, writing to temp file.");
// write out values to a temp file
try {
File tempFile = File.createTempFile("segment-", ".dat", tempDir);
tempFile.deleteOnExit();
tempFiles.add(tempFile);
OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile),
bufferSize);
if(gzip)
os = new GZIPOutputStream(os);
DataOutputStream output = new DataOutputStream(os);
for(int i = 0; i < segmentSize; i++)
writeValue(output, buffer[i]);
output.close();
} catch(IOException e) {
throw new VoldemortException(e);
}
long segmentElapsed = System.currentTimeMillis() - segmentStartMs;
logger.info("Segment " + segmentId + ": completed processing of segment in "
+ segmentElapsed + " ms.");
}
});
}
// wait for all sorting to complete
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// create iterator over sorted values
return new DefaultIterable<V>(new ExternalSorterIterator(tempFiles, bufferSize
/ tempFiles.size()));
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
} | java | public Iterable<V> sorted(Iterator<V> input) {
ExecutorService executor = new ThreadPoolExecutor(this.numThreads,
this.numThreads,
1000L,
TimeUnit.MILLISECONDS,
new SynchronousQueue<Runnable>(),
new CallerRunsPolicy());
final AtomicInteger count = new AtomicInteger(0);
final List<File> tempFiles = Collections.synchronizedList(new ArrayList<File>());
while(input.hasNext()) {
final int segmentId = count.getAndIncrement();
final long segmentStartMs = System.currentTimeMillis();
logger.info("Segment " + segmentId + ": filling sort buffer for segment...");
@SuppressWarnings("unchecked")
final V[] buffer = (V[]) new Object[internalSortSize];
int segmentSizeIter = 0;
for(; segmentSizeIter < internalSortSize && input.hasNext(); segmentSizeIter++)
buffer[segmentSizeIter] = input.next();
final int segmentSize = segmentSizeIter;
logger.info("Segment " + segmentId + ": sort buffer filled...adding to sort queue.");
// sort and write out asynchronously
executor.execute(new Runnable() {
public void run() {
logger.info("Segment " + segmentId + ": sorting buffer.");
long start = System.currentTimeMillis();
Arrays.sort(buffer, 0, segmentSize, comparator);
long elapsed = System.currentTimeMillis() - start;
logger.info("Segment " + segmentId + ": sort completed in " + elapsed
+ " ms, writing to temp file.");
// write out values to a temp file
try {
File tempFile = File.createTempFile("segment-", ".dat", tempDir);
tempFile.deleteOnExit();
tempFiles.add(tempFile);
OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile),
bufferSize);
if(gzip)
os = new GZIPOutputStream(os);
DataOutputStream output = new DataOutputStream(os);
for(int i = 0; i < segmentSize; i++)
writeValue(output, buffer[i]);
output.close();
} catch(IOException e) {
throw new VoldemortException(e);
}
long segmentElapsed = System.currentTimeMillis() - segmentStartMs;
logger.info("Segment " + segmentId + ": completed processing of segment in "
+ segmentElapsed + " ms.");
}
});
}
// wait for all sorting to complete
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// create iterator over sorted values
return new DefaultIterable<V>(new ExternalSorterIterator(tempFiles, bufferSize
/ tempFiles.size()));
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
} | [
"public",
"Iterable",
"<",
"V",
">",
"sorted",
"(",
"Iterator",
"<",
"V",
">",
"input",
")",
"{",
"ExecutorService",
"executor",
"=",
"new",
"ThreadPoolExecutor",
"(",
"this",
".",
"numThreads",
",",
"this",
".",
"numThreads",
",",
"1000L",
",",
"TimeUnit"... | Produce an iterator over the input values in sorted order. Sorting will
occur in the fixed space configured in the constructor, data will be
dumped to disk as necessary.
@param input An iterator over the input values
@return An iterator over the values | [
"Produce",
"an",
"iterator",
"over",
"the",
"input",
"values",
"in",
"sorted",
"order",
".",
"Sorting",
"will",
"occur",
"in",
"the",
"fixed",
"space",
"configured",
"in",
"the",
"constructor",
"data",
"will",
"be",
"dumped",
"to",
"disk",
"as",
"necessary",... | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ExternalSorter.java#L162-L227 | train |
voldemort/voldemort | src/java/voldemort/store/routed/action/PerformParallelPutRequests.java | PerformParallelPutRequests.processResponse | private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {
if(response == null) {
logger.warn("RoutingTimedout on waiting for async ops; parallelResponseToWait: "
+ numNodesPendingResponse + "; preferred-1: " + (preferred - 1)
+ "; quorumOK: " + quorumSatisfied + "; zoneOK: " + zonesSatisfied);
} else {
numNodesPendingResponse = numNodesPendingResponse - 1;
numResponsesGot = numResponsesGot + 1;
if(response.getValue() instanceof Exception
&& !(response.getValue() instanceof ObsoleteVersionException)) {
if(logger.isDebugEnabled()) {
logger.debug("PUT {key:" + key + "} handling async put error");
}
if(response.getValue() instanceof QuotaExceededException) {
/**
* TODO Not sure if we need to count this Exception for
* stats or silently ignore and just log a warning. While
* QuotaExceededException thrown from other places mean the
* operation failed, this one does not fail the operation
* but instead stores slops. Introduce a new Exception in
* client side to just monitor how mamy Async writes fail on
* exceeding Quota?
*
*/
if(logger.isDebugEnabled()) {
logger.debug("Received quota exceeded exception after a successful "
+ pipeline.getOperation().getSimpleName() + " call on node "
+ response.getNode().getId() + ", store '"
+ pipelineData.getStoreName() + "', master-node '"
+ pipelineData.getMaster().getId() + "'");
}
} else if(handleResponseError(response, pipeline, failureDetector)) {
if(logger.isDebugEnabled()) {
logger.debug("PUT {key:" + key
+ "} severe async put error, exiting parallel put stage");
}
return;
}
if(PipelineRoutedStore.isSlopableFailure(response.getValue())
|| response.getValue() instanceof QuotaExceededException) {
/**
* We want to slop ParallelPuts which fail due to
* QuotaExceededException.
*
* TODO Though this is not the right way of doing things, in
* order to avoid inconsistencies and data loss, we chose to
* slop the quota failed parallel puts.
*
* As a long term solution - 1) either Quota management
* should be hidden completely in a routing layer like
* Coordinator or 2) the Server should be able to
* distinguish between serial and parallel puts and should
* only quota for serial puts
*
*/
pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());
}
if(logger.isDebugEnabled()) {
logger.debug("PUT {key:" + key + "} handled async put error");
}
} else {
pipelineData.incrementSuccesses();
failureDetector.recordSuccess(response.getNode(), response.getRequestTime());
pipelineData.getZoneResponses().add(response.getNode().getZoneId());
}
}
} | java | private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {
if(response == null) {
logger.warn("RoutingTimedout on waiting for async ops; parallelResponseToWait: "
+ numNodesPendingResponse + "; preferred-1: " + (preferred - 1)
+ "; quorumOK: " + quorumSatisfied + "; zoneOK: " + zonesSatisfied);
} else {
numNodesPendingResponse = numNodesPendingResponse - 1;
numResponsesGot = numResponsesGot + 1;
if(response.getValue() instanceof Exception
&& !(response.getValue() instanceof ObsoleteVersionException)) {
if(logger.isDebugEnabled()) {
logger.debug("PUT {key:" + key + "} handling async put error");
}
if(response.getValue() instanceof QuotaExceededException) {
/**
* TODO Not sure if we need to count this Exception for
* stats or silently ignore and just log a warning. While
* QuotaExceededException thrown from other places mean the
* operation failed, this one does not fail the operation
* but instead stores slops. Introduce a new Exception in
* client side to just monitor how mamy Async writes fail on
* exceeding Quota?
*
*/
if(logger.isDebugEnabled()) {
logger.debug("Received quota exceeded exception after a successful "
+ pipeline.getOperation().getSimpleName() + " call on node "
+ response.getNode().getId() + ", store '"
+ pipelineData.getStoreName() + "', master-node '"
+ pipelineData.getMaster().getId() + "'");
}
} else if(handleResponseError(response, pipeline, failureDetector)) {
if(logger.isDebugEnabled()) {
logger.debug("PUT {key:" + key
+ "} severe async put error, exiting parallel put stage");
}
return;
}
if(PipelineRoutedStore.isSlopableFailure(response.getValue())
|| response.getValue() instanceof QuotaExceededException) {
/**
* We want to slop ParallelPuts which fail due to
* QuotaExceededException.
*
* TODO Though this is not the right way of doing things, in
* order to avoid inconsistencies and data loss, we chose to
* slop the quota failed parallel puts.
*
* As a long term solution - 1) either Quota management
* should be hidden completely in a routing layer like
* Coordinator or 2) the Server should be able to
* distinguish between serial and parallel puts and should
* only quota for serial puts
*
*/
pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());
}
if(logger.isDebugEnabled()) {
logger.debug("PUT {key:" + key + "} handled async put error");
}
} else {
pipelineData.incrementSuccesses();
failureDetector.recordSuccess(response.getNode(), response.getRequestTime());
pipelineData.getZoneResponses().add(response.getNode().getZoneId());
}
}
} | [
"private",
"void",
"processResponse",
"(",
"Response",
"<",
"ByteArray",
",",
"Object",
">",
"response",
",",
"Pipeline",
"pipeline",
")",
"{",
"if",
"(",
"response",
"==",
"null",
")",
"{",
"logger",
".",
"warn",
"(",
"\"RoutingTimedout on waiting for async ops... | Process the response by reporting proper log and feeding failure
detectors
@param response
@param pipeline | [
"Process",
"the",
"response",
"by",
"reporting",
"proper",
"log",
"and",
"feeding",
"failure",
"detectors"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/action/PerformParallelPutRequests.java#L381-L450 | train |
voldemort/voldemort | src/java/voldemort/store/routed/action/PerformParallelPutRequests.java | PerformParallelPutRequests.isZonesSatisfied | private boolean isZonesSatisfied() {
boolean zonesSatisfied = false;
if(pipelineData.getZonesRequired() == null) {
zonesSatisfied = true;
} else {
int numZonesSatisfied = pipelineData.getZoneResponses().size();
if(numZonesSatisfied >= (pipelineData.getZonesRequired() + 1)) {
zonesSatisfied = true;
}
}
return zonesSatisfied;
} | java | private boolean isZonesSatisfied() {
boolean zonesSatisfied = false;
if(pipelineData.getZonesRequired() == null) {
zonesSatisfied = true;
} else {
int numZonesSatisfied = pipelineData.getZoneResponses().size();
if(numZonesSatisfied >= (pipelineData.getZonesRequired() + 1)) {
zonesSatisfied = true;
}
}
return zonesSatisfied;
} | [
"private",
"boolean",
"isZonesSatisfied",
"(",
")",
"{",
"boolean",
"zonesSatisfied",
"=",
"false",
";",
"if",
"(",
"pipelineData",
".",
"getZonesRequired",
"(",
")",
"==",
"null",
")",
"{",
"zonesSatisfied",
"=",
"true",
";",
"}",
"else",
"{",
"int",
"num... | Check if zone count policy is satisfied
@return whether zone is satisfied | [
"Check",
"if",
"zone",
"count",
"policy",
"is",
"satisfied"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/action/PerformParallelPutRequests.java#L466-L477 | train |
voldemort/voldemort | src/java/voldemort/client/ClientConfig.java | ClientConfig.setIdleConnectionTimeout | public ClientConfig setIdleConnectionTimeout(long idleConnectionTimeout, TimeUnit unit) {
if (idleConnectionTimeout <= 0) {
this.idleConnectionTimeoutMs = -1;
} else {
if(unit.toMinutes(idleConnectionTimeout) < 10) {
throw new IllegalArgumentException("idleConnectionTimeout should be minimum of 10 minutes");
}
this.idleConnectionTimeoutMs = unit.toMillis(idleConnectionTimeout);
}
return this;
} | java | public ClientConfig setIdleConnectionTimeout(long idleConnectionTimeout, TimeUnit unit) {
if (idleConnectionTimeout <= 0) {
this.idleConnectionTimeoutMs = -1;
} else {
if(unit.toMinutes(idleConnectionTimeout) < 10) {
throw new IllegalArgumentException("idleConnectionTimeout should be minimum of 10 minutes");
}
this.idleConnectionTimeoutMs = unit.toMillis(idleConnectionTimeout);
}
return this;
} | [
"public",
"ClientConfig",
"setIdleConnectionTimeout",
"(",
"long",
"idleConnectionTimeout",
",",
"TimeUnit",
"unit",
")",
"{",
"if",
"(",
"idleConnectionTimeout",
"<=",
"0",
")",
"{",
"this",
".",
"idleConnectionTimeoutMs",
"=",
"-",
"1",
";",
"}",
"else",
"{",
... | Set the timeout for idle connections. Voldemort client caches all
connections to the Voldemort server. This setting allows the a connection
to be dropped, if it is idle for more than this time.
This could be useful in the following cases 1) Voldemort client is not
directly connected to the server and is connected via a proxy or
firewall. The Proxy or firewall could drop the connection silently. If
the connection is dropped, then client will see operations fail with a
timeout. Setting this property enables the Voldemort client to tear down
the connection before a firewall could drop it. 2) Voldemort server
caches the connection and each connection has an associated memory cost.
Setting this property on all clients, enable the clients to prune the
connections and there by freeing up the server connections.
throws IllegalArgumentException if the timeout is less than 10 minutes.
Currently it can't be set below 10 minutes to avoid the racing risk of
contention between connection checkout and selector trying to close it.
This is intended for low throughput scenarios.
@param idleConnectionTimeout
zero or negative number to disable the feature ( default -1)
timeout
@param unit {@link TimeUnit}
@return ClientConfig object for chained set
throws {@link IllegalArgumentException} if the timeout is greater
than 0, but less than 10 minutes. | [
"Set",
"the",
"timeout",
"for",
"idle",
"connections",
".",
"Voldemort",
"client",
"caches",
"all",
"connections",
"to",
"the",
"Voldemort",
"server",
".",
"This",
"setting",
"allows",
"the",
"a",
"connection",
"to",
"be",
"dropped",
"if",
"it",
"is",
"idle"... | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/ClientConfig.java#L617-L627 | train |
voldemort/voldemort | src/java/voldemort/client/ClientConfig.java | ClientConfig.setNodeBannagePeriod | @Deprecated
public ClientConfig setNodeBannagePeriod(int nodeBannagePeriod, TimeUnit unit) {
this.failureDetectorBannagePeriod = unit.toMillis(nodeBannagePeriod);
return this;
} | java | @Deprecated
public ClientConfig setNodeBannagePeriod(int nodeBannagePeriod, TimeUnit unit) {
this.failureDetectorBannagePeriod = unit.toMillis(nodeBannagePeriod);
return this;
} | [
"@",
"Deprecated",
"public",
"ClientConfig",
"setNodeBannagePeriod",
"(",
"int",
"nodeBannagePeriod",
",",
"TimeUnit",
"unit",
")",
"{",
"this",
".",
"failureDetectorBannagePeriod",
"=",
"unit",
".",
"toMillis",
"(",
"nodeBannagePeriod",
")",
";",
"return",
"this",
... | The period of time to ban a node that gives an error on an operation.
@param nodeBannagePeriod The period of time to ban the node
@param unit The time unit of the given value
@deprecated Use {@link #setFailureDetectorBannagePeriod(long)} instead | [
"The",
"period",
"of",
"time",
"to",
"ban",
"a",
"node",
"that",
"gives",
"an",
"error",
"on",
"an",
"operation",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/ClientConfig.java#L721-L725 | train |
voldemort/voldemort | src/java/voldemort/client/ClientConfig.java | ClientConfig.setThreadIdleTime | @Deprecated
public ClientConfig setThreadIdleTime(long threadIdleTime, TimeUnit unit) {
this.threadIdleMs = unit.toMillis(threadIdleTime);
return this;
} | java | @Deprecated
public ClientConfig setThreadIdleTime(long threadIdleTime, TimeUnit unit) {
this.threadIdleMs = unit.toMillis(threadIdleTime);
return this;
} | [
"@",
"Deprecated",
"public",
"ClientConfig",
"setThreadIdleTime",
"(",
"long",
"threadIdleTime",
",",
"TimeUnit",
"unit",
")",
"{",
"this",
".",
"threadIdleMs",
"=",
"unit",
".",
"toMillis",
"(",
"threadIdleTime",
")",
";",
"return",
"this",
";",
"}"
] | The amount of time to keep an idle client thread alive
@param threadIdleTime | [
"The",
"amount",
"of",
"time",
"to",
"keep",
"an",
"idle",
"client",
"thread",
"alive"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/ClientConfig.java#L862-L866 | train |
voldemort/voldemort | src/java/voldemort/store/socket/clientrequest/ClientRequestExecutorPool.java | ClientRequestExecutorPool.close | @Override
public void close(SocketDestination destination) {
factory.setLastClosedTimestamp(destination);
queuedPool.reset(destination);
} | java | @Override
public void close(SocketDestination destination) {
factory.setLastClosedTimestamp(destination);
queuedPool.reset(destination);
} | [
"@",
"Override",
"public",
"void",
"close",
"(",
"SocketDestination",
"destination",
")",
"{",
"factory",
".",
"setLastClosedTimestamp",
"(",
"destination",
")",
";",
"queuedPool",
".",
"reset",
"(",
"destination",
")",
";",
"}"
] | Reset the pool of resources for a specific destination. Idle resources
will be destroyed. Checked out resources that are subsequently checked in
will be destroyed. Newly created resources can be checked in to
reestablish resources for the specific destination. | [
"Reset",
"the",
"pool",
"of",
"resources",
"for",
"a",
"specific",
"destination",
".",
"Idle",
"resources",
"will",
"be",
"destroyed",
".",
"Checked",
"out",
"resources",
"that",
"are",
"subsequently",
"checked",
"in",
"will",
"be",
"destroyed",
".",
"Newly",
... | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/socket/clientrequest/ClientRequestExecutorPool.java#L269-L273 | train |
voldemort/voldemort | src/java/voldemort/store/socket/clientrequest/ClientRequestExecutorPool.java | ClientRequestExecutorPool.close | @Override
public void close() {
// unregister MBeans
if(stats != null) {
try {
if(this.jmxEnabled)
JmxUtils.unregisterMbean(getAggregateMetricName());
} catch(Exception e) {}
stats.close();
}
factory.close();
queuedPool.close();
} | java | @Override
public void close() {
// unregister MBeans
if(stats != null) {
try {
if(this.jmxEnabled)
JmxUtils.unregisterMbean(getAggregateMetricName());
} catch(Exception e) {}
stats.close();
}
factory.close();
queuedPool.close();
} | [
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"{",
"// unregister MBeans",
"if",
"(",
"stats",
"!=",
"null",
")",
"{",
"try",
"{",
"if",
"(",
"this",
".",
"jmxEnabled",
")",
"JmxUtils",
".",
"unregisterMbean",
"(",
"getAggregateMetricName",
"(",
")... | Permanently close the ClientRequestExecutor pool. Resources subsequently
checked in will be destroyed. | [
"Permanently",
"close",
"the",
"ClientRequestExecutor",
"pool",
".",
"Resources",
"subsequently",
"checked",
"in",
"will",
"be",
"destroyed",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/socket/clientrequest/ClientRequestExecutorPool.java#L279-L291 | train |
voldemort/voldemort | contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/HadoopStoreBuilderUtils.java | HadoopStoreBuilderUtils.readFileContents | public static String readFileContents(FileSystem fs, Path path, int bufferSize)
throws IOException {
if(bufferSize <= 0)
return new String();
FSDataInputStream input = fs.open(path);
byte[] buffer = new byte[bufferSize];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
while(true) {
int read = input.read(buffer);
if(read < 0) {
break;
} else {
buffer = ByteUtils.copy(buffer, 0, read);
}
stream.write(buffer);
}
return new String(stream.toByteArray());
} | java | public static String readFileContents(FileSystem fs, Path path, int bufferSize)
throws IOException {
if(bufferSize <= 0)
return new String();
FSDataInputStream input = fs.open(path);
byte[] buffer = new byte[bufferSize];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
while(true) {
int read = input.read(buffer);
if(read < 0) {
break;
} else {
buffer = ByteUtils.copy(buffer, 0, read);
}
stream.write(buffer);
}
return new String(stream.toByteArray());
} | [
"public",
"static",
"String",
"readFileContents",
"(",
"FileSystem",
"fs",
",",
"Path",
"path",
",",
"int",
"bufferSize",
")",
"throws",
"IOException",
"{",
"if",
"(",
"bufferSize",
"<=",
"0",
")",
"return",
"new",
"String",
"(",
")",
";",
"FSDataInputStream... | Given a filesystem, path and buffer-size, read the file contents and
presents it as a string
@param fs Underlying filesystem
@param path The file to read
@param bufferSize The buffer size to use for reading
@return The contents of the file as a string
@throws IOException | [
"Given",
"a",
"filesystem",
"path",
"and",
"buffer",
"-",
"size",
"read",
"the",
"file",
"contents",
"and",
"presents",
"it",
"as",
"a",
"string"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/HadoopStoreBuilderUtils.java#L52-L73 | train |
voldemort/voldemort | contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/HadoopStoreBuilderUtils.java | HadoopStoreBuilderUtils.getDataChunkFiles | public static FileStatus[] getDataChunkFiles(FileSystem fs,
Path path,
final int partitionId,
final int replicaType) throws IOException {
return fs.listStatus(path, new PathFilter() {
public boolean accept(Path input) {
if(input.getName().matches("^" + Integer.toString(partitionId) + "_"
+ Integer.toString(replicaType) + "_[\\d]+\\.data")) {
return true;
} else {
return false;
}
}
});
} | java | public static FileStatus[] getDataChunkFiles(FileSystem fs,
Path path,
final int partitionId,
final int replicaType) throws IOException {
return fs.listStatus(path, new PathFilter() {
public boolean accept(Path input) {
if(input.getName().matches("^" + Integer.toString(partitionId) + "_"
+ Integer.toString(replicaType) + "_[\\d]+\\.data")) {
return true;
} else {
return false;
}
}
});
} | [
"public",
"static",
"FileStatus",
"[",
"]",
"getDataChunkFiles",
"(",
"FileSystem",
"fs",
",",
"Path",
"path",
",",
"final",
"int",
"partitionId",
",",
"final",
"int",
"replicaType",
")",
"throws",
"IOException",
"{",
"return",
"fs",
".",
"listStatus",
"(",
... | Given a filesystem and path to a node, gets all the files which belong to
a partition and replica type
Works only for {@link ReadOnlyStorageFormat.READONLY_V2}
@param fs Underlying filesystem
@param path The node directory path
@param partitionId The partition id for which we get the files
@param replicaType The replica type
@return Returns list of files of this partition, replicaType
@throws IOException | [
"Given",
"a",
"filesystem",
"and",
"path",
"to",
"a",
"node",
"gets",
"all",
"the",
"files",
"which",
"belong",
"to",
"a",
"partition",
"and",
"replica",
"type"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/HadoopStoreBuilderUtils.java#L88-L103 | train |
voldemort/voldemort | src/java/voldemort/store/routed/action/PerformSerialRequests.java | PerformSerialRequests.isSatisfied | private boolean isSatisfied() {
if(pipelineData.getZonesRequired() != null) {
return ((pipelineData.getSuccesses() >= required) && (pipelineData.getZoneResponses()
.size() >= (pipelineData.getZonesRequired() + 1)));
} else {
return pipelineData.getSuccesses() >= required;
}
} | java | private boolean isSatisfied() {
if(pipelineData.getZonesRequired() != null) {
return ((pipelineData.getSuccesses() >= required) && (pipelineData.getZoneResponses()
.size() >= (pipelineData.getZonesRequired() + 1)));
} else {
return pipelineData.getSuccesses() >= required;
}
} | [
"private",
"boolean",
"isSatisfied",
"(",
")",
"{",
"if",
"(",
"pipelineData",
".",
"getZonesRequired",
"(",
")",
"!=",
"null",
")",
"{",
"return",
"(",
"(",
"pipelineData",
".",
"getSuccesses",
"(",
")",
">=",
"required",
")",
"&&",
"(",
"pipelineData",
... | Checks whether every property except 'preferred' is satisfied
@return | [
"Checks",
"whether",
"every",
"property",
"except",
"preferred",
"is",
"satisfied"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/routed/action/PerformSerialRequests.java#L74-L81 | train |
voldemort/voldemort | src/java/voldemort/client/rebalance/RebalanceBatchPlan.java | RebalanceBatchPlan.getCrossZonePartitionStoreMoves | public int getCrossZonePartitionStoreMoves() {
int xzonePartitionStoreMoves = 0;
for (RebalanceTaskInfo info : batchPlan) {
Node donorNode = finalCluster.getNodeById(info.getDonorId());
Node stealerNode = finalCluster.getNodeById(info.getStealerId());
if(donorNode.getZoneId() != stealerNode.getZoneId()) {
xzonePartitionStoreMoves += info.getPartitionStoreMoves();
}
}
return xzonePartitionStoreMoves;
} | java | public int getCrossZonePartitionStoreMoves() {
int xzonePartitionStoreMoves = 0;
for (RebalanceTaskInfo info : batchPlan) {
Node donorNode = finalCluster.getNodeById(info.getDonorId());
Node stealerNode = finalCluster.getNodeById(info.getStealerId());
if(donorNode.getZoneId() != stealerNode.getZoneId()) {
xzonePartitionStoreMoves += info.getPartitionStoreMoves();
}
}
return xzonePartitionStoreMoves;
} | [
"public",
"int",
"getCrossZonePartitionStoreMoves",
"(",
")",
"{",
"int",
"xzonePartitionStoreMoves",
"=",
"0",
";",
"for",
"(",
"RebalanceTaskInfo",
"info",
":",
"batchPlan",
")",
"{",
"Node",
"donorNode",
"=",
"finalCluster",
".",
"getNodeById",
"(",
"info",
"... | Determines total number of partition-stores moved across zones.
@return number of cross zone partition-store moves | [
"Determines",
"total",
"number",
"of",
"partition",
"-",
"stores",
"moved",
"across",
"zones",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceBatchPlan.java#L150-L162 | train |
voldemort/voldemort | src/java/voldemort/client/rebalance/RebalanceBatchPlan.java | RebalanceBatchPlan.getDonorId | protected int getDonorId(StoreRoutingPlan currentSRP,
StoreRoutingPlan finalSRP,
int stealerZoneId,
int stealerNodeId,
int stealerPartitionId) {
int stealerZoneNAry = finalSRP.getZoneNaryForNodesPartition(stealerZoneId,
stealerNodeId,
stealerPartitionId);
int donorZoneId;
if(currentSRP.zoneNAryExists(stealerZoneId, stealerZoneNAry, stealerPartitionId)) {
// Steal from local n-ary (since one exists).
donorZoneId = stealerZoneId;
} else {
// Steal from zone that hosts primary partition Id.
int currentMasterNodeId = currentSRP.getNodeIdForPartitionId(stealerPartitionId);
donorZoneId = currentCluster.getNodeById(currentMasterNodeId).getZoneId();
}
return currentSRP.getNodeIdForZoneNary(donorZoneId, stealerZoneNAry, stealerPartitionId);
} | java | protected int getDonorId(StoreRoutingPlan currentSRP,
StoreRoutingPlan finalSRP,
int stealerZoneId,
int stealerNodeId,
int stealerPartitionId) {
int stealerZoneNAry = finalSRP.getZoneNaryForNodesPartition(stealerZoneId,
stealerNodeId,
stealerPartitionId);
int donorZoneId;
if(currentSRP.zoneNAryExists(stealerZoneId, stealerZoneNAry, stealerPartitionId)) {
// Steal from local n-ary (since one exists).
donorZoneId = stealerZoneId;
} else {
// Steal from zone that hosts primary partition Id.
int currentMasterNodeId = currentSRP.getNodeIdForPartitionId(stealerPartitionId);
donorZoneId = currentCluster.getNodeById(currentMasterNodeId).getZoneId();
}
return currentSRP.getNodeIdForZoneNary(donorZoneId, stealerZoneNAry, stealerPartitionId);
} | [
"protected",
"int",
"getDonorId",
"(",
"StoreRoutingPlan",
"currentSRP",
",",
"StoreRoutingPlan",
"finalSRP",
",",
"int",
"stealerZoneId",
",",
"int",
"stealerNodeId",
",",
"int",
"stealerPartitionId",
")",
"{",
"int",
"stealerZoneNAry",
"=",
"finalSRP",
".",
"getZo... | Decide which donor node to steal from. This is a policy implementation.
I.e., in the future, additional policies could be considered. At that
time, this method should be overridden in a sub-class, or a policy object
ought to implement this algorithm.
Current policy:
1) If possible, a stealer node that is the zone n-ary in the finalCluster
steals from the zone n-ary in the currentCluster in the same zone.
2) If there are no partition-stores to steal in the same zone (i.e., this
is the "zone expansion" use case), then a differnt policy must be used.
The stealer node that is the zone n-ary in the finalCluster determines
which pre-existing zone in the currentCluster hosts the primary partition
id for the partition-store. The stealer then steals the zone n-ary from
that pre-existing zone.
This policy avoids unnecessary cross-zone moves and distributes the load
of cross-zone moves approximately-uniformly across pre-existing zones.
Other policies to consider:
- For zone expansion, steal all partition-stores from one specific
pre-existing zone.
- Replace heuristic to approximately uniformly distribute load among
existing zones to something more concrete (i.e. track steals from each
pre-existing zone and forcibly balance them).
- Select a single donor for all replicas in a new zone. This will require
donor-based rebalancing to be run (at least for this specific part of the
plan). This would reduce the number of donor-side scans of data. (But
still send replication factor copies over the WAN.) This would require
apparatus in the RebalanceController to work.
- Set up some sort of chain-replication in which a single stealer in the
new zone steals some replica from a pre-exising zone, and then other
n-aries in the new zone steal from the single cross-zone stealer in the
zone. This would require apparatus in the RebalanceController to work.
@param currentSRP
@param finalSRP
@param stealerZoneId
@param stealerNodeId
@param stealerPartitionId
@return the node id of the donor for this partition Id. | [
"Decide",
"which",
"donor",
"node",
"to",
"steal",
"from",
".",
"This",
"is",
"a",
"policy",
"implementation",
".",
"I",
".",
"e",
".",
"in",
"the",
"future",
"additional",
"policies",
"could",
"be",
"considered",
".",
"At",
"that",
"time",
"this",
"meth... | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceBatchPlan.java#L351-L372 | train |
voldemort/voldemort | src/java/voldemort/rest/RestErrorHandler.java | RestErrorHandler.handleExceptions | protected void handleExceptions(MessageEvent messageEvent, Exception exception) {
logger.error("Unknown exception. Internal Server Error.", exception);
writeErrorResponse(messageEvent,
HttpResponseStatus.INTERNAL_SERVER_ERROR,
"Internal Server Error");
} | java | protected void handleExceptions(MessageEvent messageEvent, Exception exception) {
logger.error("Unknown exception. Internal Server Error.", exception);
writeErrorResponse(messageEvent,
HttpResponseStatus.INTERNAL_SERVER_ERROR,
"Internal Server Error");
} | [
"protected",
"void",
"handleExceptions",
"(",
"MessageEvent",
"messageEvent",
",",
"Exception",
"exception",
")",
"{",
"logger",
".",
"error",
"(",
"\"Unknown exception. Internal Server Error.\"",
",",
"exception",
")",
";",
"writeErrorResponse",
"(",
"messageEvent",
",... | Exceptions specific to each operation is handled in the corresponding
subclass. At this point we don't know the reason behind this exception.
@param exception | [
"Exceptions",
"specific",
"to",
"each",
"operation",
"is",
"handled",
"in",
"the",
"corresponding",
"subclass",
".",
"At",
"this",
"point",
"we",
"don",
"t",
"know",
"the",
"reason",
"behind",
"this",
"exception",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestErrorHandler.java#L25-L30 | train |
voldemort/voldemort | src/java/voldemort/rest/RestErrorHandler.java | RestErrorHandler.writeErrorResponse | public static void writeErrorResponse(MessageEvent messageEvent,
HttpResponseStatus status,
String message) {
// Create the Response object
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
response.setContent(ChannelBuffers.copiedBuffer("Failure: " + status.toString() + ". "
+ message + "\r\n", CharsetUtil.UTF_8));
response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
// Write the response to the Netty Channel
messageEvent.getChannel().write(response);
} | java | public static void writeErrorResponse(MessageEvent messageEvent,
HttpResponseStatus status,
String message) {
// Create the Response object
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
response.setContent(ChannelBuffers.copiedBuffer("Failure: " + status.toString() + ". "
+ message + "\r\n", CharsetUtil.UTF_8));
response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
// Write the response to the Netty Channel
messageEvent.getChannel().write(response);
} | [
"public",
"static",
"void",
"writeErrorResponse",
"(",
"MessageEvent",
"messageEvent",
",",
"HttpResponseStatus",
"status",
",",
"String",
"message",
")",
"{",
"// Create the Response object",
"HttpResponse",
"response",
"=",
"new",
"DefaultHttpResponse",
"(",
"HTTP_1_1",... | Writes all error responses to the client.
TODO REST-Server 1. collect error stats
@param messageEvent - for retrieving the channel details
@param status - error code
@param message - error message | [
"Writes",
"all",
"error",
"responses",
"to",
"the",
"client",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestErrorHandler.java#L41-L54 | train |
voldemort/voldemort | src/java/voldemort/rest/RestPutRequestValidator.java | RestPutRequestValidator.parseAndValidateRequest | @Override
public boolean parseAndValidateRequest() {
boolean result = false;
if(!super.parseAndValidateRequest() || !hasVectorClock(this.isVectorClockOptional)
|| !hasContentLength() || !hasContentType()) {
result = false;
} else {
result = true;
}
return result;
} | java | @Override
public boolean parseAndValidateRequest() {
boolean result = false;
if(!super.parseAndValidateRequest() || !hasVectorClock(this.isVectorClockOptional)
|| !hasContentLength() || !hasContentType()) {
result = false;
} else {
result = true;
}
return result;
} | [
"@",
"Override",
"public",
"boolean",
"parseAndValidateRequest",
"(",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"if",
"(",
"!",
"super",
".",
"parseAndValidateRequest",
"(",
")",
"||",
"!",
"hasVectorClock",
"(",
"this",
".",
"isVectorClockOptional",
"... | Validations specific to PUT | [
"Validations",
"specific",
"to",
"PUT"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestPutRequestValidator.java#L78-L89 | train |
voldemort/voldemort | src/java/voldemort/rest/RestPutRequestValidator.java | RestPutRequestValidator.hasContentLength | protected boolean hasContentLength() {
boolean result = false;
String contentLength = this.request.getHeader(RestMessageHeaders.CONTENT_LENGTH);
if(contentLength != null) {
try {
Long.parseLong(contentLength);
result = true;
} catch(NumberFormatException nfe) {
logger.error("Exception when validating put request. Incorrect content length parameter. Cannot parse this to long: "
+ contentLength + ". Details: " + nfe.getMessage(),
nfe);
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Incorrect content length parameter. Cannot parse this to long: "
+ contentLength + ". Details: "
+ nfe.getMessage());
}
} else {
logger.error("Error when validating put request. Missing Content-Length header.");
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Missing Content-Length header");
}
return result;
} | java | protected boolean hasContentLength() {
boolean result = false;
String contentLength = this.request.getHeader(RestMessageHeaders.CONTENT_LENGTH);
if(contentLength != null) {
try {
Long.parseLong(contentLength);
result = true;
} catch(NumberFormatException nfe) {
logger.error("Exception when validating put request. Incorrect content length parameter. Cannot parse this to long: "
+ contentLength + ". Details: " + nfe.getMessage(),
nfe);
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Incorrect content length parameter. Cannot parse this to long: "
+ contentLength + ". Details: "
+ nfe.getMessage());
}
} else {
logger.error("Error when validating put request. Missing Content-Length header.");
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Missing Content-Length header");
}
return result;
} | [
"protected",
"boolean",
"hasContentLength",
"(",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"String",
"contentLength",
"=",
"this",
".",
"request",
".",
"getHeader",
"(",
"RestMessageHeaders",
".",
"CONTENT_LENGTH",
")",
";",
"if",
"(",
"contentLength",
... | Retrieves and validates the content length from the REST request.
@return true if has content length | [
"Retrieves",
"and",
"validates",
"the",
"content",
"length",
"from",
"the",
"REST",
"request",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestPutRequestValidator.java#L96-L121 | train |
voldemort/voldemort | src/java/voldemort/rest/RestPutRequestValidator.java | RestPutRequestValidator.hasContentType | protected boolean hasContentType() {
boolean result = false;
if(this.request.getHeader(RestMessageHeaders.CONTENT_TYPE) != null) {
result = true;
} else {
logger.error("Error when validating put request. Missing Content-Type header.");
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Missing Content-Type header");
}
return result;
} | java | protected boolean hasContentType() {
boolean result = false;
if(this.request.getHeader(RestMessageHeaders.CONTENT_TYPE) != null) {
result = true;
} else {
logger.error("Error when validating put request. Missing Content-Type header.");
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Missing Content-Type header");
}
return result;
} | [
"protected",
"boolean",
"hasContentType",
"(",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"if",
"(",
"this",
".",
"request",
".",
"getHeader",
"(",
"RestMessageHeaders",
".",
"CONTENT_TYPE",
")",
"!=",
"null",
")",
"{",
"result",
"=",
"true",
";",
... | Retrieves and validates the content type from the REST requests
@return true if has content type. | [
"Retrieves",
"and",
"validates",
"the",
"content",
"type",
"from",
"the",
"REST",
"requests"
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestPutRequestValidator.java#L128-L140 | train |
voldemort/voldemort | src/java/voldemort/rest/RestPutRequestValidator.java | RestPutRequestValidator.parseValue | private void parseValue() {
ChannelBuffer content = this.request.getContent();
this.parsedValue = new byte[content.capacity()];
content.readBytes(parsedValue);
} | java | private void parseValue() {
ChannelBuffer content = this.request.getContent();
this.parsedValue = new byte[content.capacity()];
content.readBytes(parsedValue);
} | [
"private",
"void",
"parseValue",
"(",
")",
"{",
"ChannelBuffer",
"content",
"=",
"this",
".",
"request",
".",
"getContent",
"(",
")",
";",
"this",
".",
"parsedValue",
"=",
"new",
"byte",
"[",
"content",
".",
"capacity",
"(",
")",
"]",
";",
"content",
"... | Retrieve the value from the REST request body.
TODO: REST-Server value cannot be null ( null/empty string ?) | [
"Retrieve",
"the",
"value",
"from",
"the",
"REST",
"request",
"body",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestPutRequestValidator.java#L147-L151 | train |
voldemort/voldemort | contrib/hadoop-store-builder/src/java/voldemort/store/readonly/swapper/HdfsFailedFetchLock.java | HdfsFailedFetchLock.handleIOException | private void handleIOException(IOException e, String action, int attempt)
throws VoldemortException, InterruptedException {
if ( // any of the following happens, we need to bubble up
// FileSystem instance got closed, somehow
e.getMessage().contains("Filesystem closed") ||
// HDFS permission issues
ExceptionUtils.recursiveClassEquals(e, AccessControlException.class)) {
throw new VoldemortException("Got an IOException we cannot recover from while trying to " +
action + ". Attempt # " + attempt + "/" + maxAttempts + ". Will not try again.", e);
} else {
logFailureAndWait(action, IO_EXCEPTION, attempt, e);
}
} | java | private void handleIOException(IOException e, String action, int attempt)
throws VoldemortException, InterruptedException {
if ( // any of the following happens, we need to bubble up
// FileSystem instance got closed, somehow
e.getMessage().contains("Filesystem closed") ||
// HDFS permission issues
ExceptionUtils.recursiveClassEquals(e, AccessControlException.class)) {
throw new VoldemortException("Got an IOException we cannot recover from while trying to " +
action + ". Attempt # " + attempt + "/" + maxAttempts + ". Will not try again.", e);
} else {
logFailureAndWait(action, IO_EXCEPTION, attempt, e);
}
} | [
"private",
"void",
"handleIOException",
"(",
"IOException",
"e",
",",
"String",
"action",
",",
"int",
"attempt",
")",
"throws",
"VoldemortException",
",",
"InterruptedException",
"{",
"if",
"(",
"// any of the following happens, we need to bubble up",
"// FileSystem instanc... | This function is intended to detect the subset of IOException which are not
considered recoverable, in which case we want to bubble up the exception, instead
of retrying.
@throws VoldemortException | [
"This",
"function",
"is",
"intended",
"to",
"detect",
"the",
"subset",
"of",
"IOException",
"which",
"are",
"not",
"considered",
"recoverable",
"in",
"which",
"case",
"we",
"want",
"to",
"bubble",
"up",
"the",
"exception",
"instead",
"of",
"retrying",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/swapper/HdfsFailedFetchLock.java#L186-L198 | train |
voldemort/voldemort | src/java/voldemort/cluster/failuredetector/AbstractFailureDetector.java | AbstractFailureDetector.setAvailable | private boolean setAvailable(NodeStatus nodeStatus, boolean isAvailable) {
synchronized(nodeStatus) {
boolean previous = nodeStatus.isAvailable();
nodeStatus.setAvailable(isAvailable);
nodeStatus.setLastChecked(getConfig().getTime().getMilliseconds());
return previous;
}
} | java | private boolean setAvailable(NodeStatus nodeStatus, boolean isAvailable) {
synchronized(nodeStatus) {
boolean previous = nodeStatus.isAvailable();
nodeStatus.setAvailable(isAvailable);
nodeStatus.setLastChecked(getConfig().getTime().getMilliseconds());
return previous;
}
} | [
"private",
"boolean",
"setAvailable",
"(",
"NodeStatus",
"nodeStatus",
",",
"boolean",
"isAvailable",
")",
"{",
"synchronized",
"(",
"nodeStatus",
")",
"{",
"boolean",
"previous",
"=",
"nodeStatus",
".",
"isAvailable",
"(",
")",
";",
"nodeStatus",
".",
"setAvail... | We need to distinguish the case where we're newly available and the case
where we're already available. So we check the node status before we
update it and return it to the caller.
@param isAvailable True to set to available, false to make unavailable
@return Previous value of isAvailable | [
"We",
"need",
"to",
"distinguish",
"the",
"case",
"where",
"we",
"re",
"newly",
"available",
"and",
"the",
"case",
"where",
"we",
"re",
"already",
"available",
".",
"So",
"we",
"check",
"the",
"node",
"status",
"before",
"we",
"update",
"it",
"and",
"ret... | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/cluster/failuredetector/AbstractFailureDetector.java#L273-L282 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsDir | public static void acceptsDir(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_D, OPT_DIR), "directory path for input/output")
.withRequiredArg()
.describedAs("dir-path")
.ofType(String.class);
} | java | public static void acceptsDir(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_D, OPT_DIR), "directory path for input/output")
.withRequiredArg()
.describedAs("dir-path")
.ofType(String.class);
} | [
"public",
"static",
"void",
"acceptsDir",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"acceptsAll",
"(",
"Arrays",
".",
"asList",
"(",
"OPT_D",
",",
"OPT_DIR",
")",
",",
"\"directory path for input/output\"",
")",
".",
"withRequiredArg",
"(",
")",
... | Adds OPT_D | OPT_DIR option to OptionParser, with one argument.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"Adds",
"OPT_D",
"|",
"OPT_DIR",
"option",
"to",
"OptionParser",
"with",
"one",
"argument",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L148-L153 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsFile | public static void acceptsFile(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_F, OPT_FILE), "file path for input/output")
.withRequiredArg()
.describedAs("file-path")
.ofType(String.class);
} | java | public static void acceptsFile(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_F, OPT_FILE), "file path for input/output")
.withRequiredArg()
.describedAs("file-path")
.ofType(String.class);
} | [
"public",
"static",
"void",
"acceptsFile",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"acceptsAll",
"(",
"Arrays",
".",
"asList",
"(",
"OPT_F",
",",
"OPT_FILE",
")",
",",
"\"file path for input/output\"",
")",
".",
"withRequiredArg",
"(",
")",
"."... | Adds OPT_F | OPT_FILE option to OptionParser, with one argument.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"Adds",
"OPT_F",
"|",
"OPT_FILE",
"option",
"to",
"OptionParser",
"with",
"one",
"argument",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L161-L166 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsFormat | public static void acceptsFormat(OptionParser parser) {
parser.accepts(OPT_FORMAT, "format of key or entry, could be hex, json or binary")
.withRequiredArg()
.describedAs("hex | json | binary")
.ofType(String.class);
} | java | public static void acceptsFormat(OptionParser parser) {
parser.accepts(OPT_FORMAT, "format of key or entry, could be hex, json or binary")
.withRequiredArg()
.describedAs("hex | json | binary")
.ofType(String.class);
} | [
"public",
"static",
"void",
"acceptsFormat",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"accepts",
"(",
"OPT_FORMAT",
",",
"\"format of key or entry, could be hex, json or binary\"",
")",
".",
"withRequiredArg",
"(",
")",
".",
"describedAs",
"(",
"\"hex |... | Adds OPT_FORMAT option to OptionParser, with one argument.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"Adds",
"OPT_FORMAT",
"option",
"to",
"OptionParser",
"with",
"one",
"argument",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L174-L179 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsNodeSingle | public static void acceptsNodeSingle(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), "node id")
.withRequiredArg()
.describedAs("node-id")
.ofType(Integer.class);
} | java | public static void acceptsNodeSingle(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), "node id")
.withRequiredArg()
.describedAs("node-id")
.ofType(Integer.class);
} | [
"public",
"static",
"void",
"acceptsNodeSingle",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"acceptsAll",
"(",
"Arrays",
".",
"asList",
"(",
"OPT_N",
",",
"OPT_NODE",
")",
",",
"\"node id\"",
")",
".",
"withRequiredArg",
"(",
")",
".",
"describe... | Adds OPT_N | OPT_NODE option to OptionParser, with one argument.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"Adds",
"OPT_N",
"|",
"OPT_NODE",
"option",
"to",
"OptionParser",
"with",
"one",
"argument",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L187-L192 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsUrl | public static void acceptsUrl(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), "bootstrap url")
.withRequiredArg()
.describedAs("url")
.ofType(String.class);
} | java | public static void acceptsUrl(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), "bootstrap url")
.withRequiredArg()
.describedAs("url")
.ofType(String.class);
} | [
"public",
"static",
"void",
"acceptsUrl",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"acceptsAll",
"(",
"Arrays",
".",
"asList",
"(",
"OPT_U",
",",
"OPT_URL",
")",
",",
"\"bootstrap url\"",
")",
".",
"withRequiredArg",
"(",
")",
".",
"describedA... | Adds OPT_U | OPT_URL option to OptionParser, with one argument.
@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",
"one",
"argument",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L213-L218 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsZone | public static void acceptsZone(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_Z, OPT_ZONE), "zone id")
.withRequiredArg()
.describedAs("zone-id")
.ofType(Integer.class);
} | java | public static void acceptsZone(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_Z, OPT_ZONE), "zone id")
.withRequiredArg()
.describedAs("zone-id")
.ofType(Integer.class);
} | [
"public",
"static",
"void",
"acceptsZone",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"acceptsAll",
"(",
"Arrays",
".",
"asList",
"(",
"OPT_Z",
",",
"OPT_ZONE",
")",
",",
"\"zone id\"",
")",
".",
"withRequiredArg",
"(",
")",
".",
"describedAs",
... | Adds OPT_Z | OPT_ZONE option to OptionParser, with one argument.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"Adds",
"OPT_Z",
"|",
"OPT_ZONE",
"option",
"to",
"OptionParser",
"with",
"one",
"argument",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L226-L231 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsHex | public static void acceptsHex(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_X, OPT_HEX), "fetch key/entry by key value of hex type")
.withRequiredArg()
.describedAs("key-list")
.withValuesSeparatedBy(',')
.ofType(String.class);
} | java | public static void acceptsHex(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_X, OPT_HEX), "fetch key/entry by key value of hex type")
.withRequiredArg()
.describedAs("key-list")
.withValuesSeparatedBy(',')
.ofType(String.class);
} | [
"public",
"static",
"void",
"acceptsHex",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"acceptsAll",
"(",
"Arrays",
".",
"asList",
"(",
"OPT_X",
",",
"OPT_HEX",
")",
",",
"\"fetch key/entry by key value of hex type\"",
")",
".",
"withRequiredArg",
"(",
... | Adds OPT_X | OPT_HEX option to OptionParser, with multiple arguments.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"Adds",
"OPT_X",
"|",
"OPT_HEX",
"option",
"to",
"OptionParser",
"with",
"multiple",
"arguments",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L239-L245 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsJson | public static void acceptsJson(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),
"fetch key/entry by key value of json type")
.withRequiredArg()
.describedAs("key-list")
.withValuesSeparatedBy(',')
.ofType(String.class);
} | java | public static void acceptsJson(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),
"fetch key/entry by key value of json type")
.withRequiredArg()
.describedAs("key-list")
.withValuesSeparatedBy(',')
.ofType(String.class);
} | [
"public",
"static",
"void",
"acceptsJson",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"acceptsAll",
"(",
"Arrays",
".",
"asList",
"(",
"OPT_J",
",",
"OPT_JSON",
")",
",",
"\"fetch key/entry by key value of json type\"",
")",
".",
"withRequiredArg",
"(... | Adds OPT_J | OPT_JSON option to OptionParser, with multiple arguments.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"Adds",
"OPT_J",
"|",
"OPT_JSON",
"option",
"to",
"OptionParser",
"with",
"multiple",
"arguments",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L253-L260 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsNodeMultiple | public static void acceptsNodeMultiple(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), "node id list")
.withRequiredArg()
.describedAs("node-id-list")
.withValuesSeparatedBy(',')
.ofType(Integer.class);
} | java | public static void acceptsNodeMultiple(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), "node id list")
.withRequiredArg()
.describedAs("node-id-list")
.withValuesSeparatedBy(',')
.ofType(Integer.class);
} | [
"public",
"static",
"void",
"acceptsNodeMultiple",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"acceptsAll",
"(",
"Arrays",
".",
"asList",
"(",
"OPT_N",
",",
"OPT_NODE",
")",
",",
"\"node id list\"",
")",
".",
"withRequiredArg",
"(",
")",
".",
"d... | Adds OPT_N | OPT_NODE option to OptionParser, with multiple arguments.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"Adds",
"OPT_N",
"|",
"OPT_NODE",
"option",
"to",
"OptionParser",
"with",
"multiple",
"arguments",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L268-L274 | train |
voldemort/voldemort | src/java/voldemort/tools/admin/AdminParserUtils.java | AdminParserUtils.acceptsPartition | public static void acceptsPartition(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_P, OPT_PARTITION), "partition id list")
.withRequiredArg()
.describedAs("partition-id-list")
.withValuesSeparatedBy(',')
.ofType(Integer.class);
} | java | public static void acceptsPartition(OptionParser parser) {
parser.acceptsAll(Arrays.asList(OPT_P, OPT_PARTITION), "partition id list")
.withRequiredArg()
.describedAs("partition-id-list")
.withValuesSeparatedBy(',')
.ofType(Integer.class);
} | [
"public",
"static",
"void",
"acceptsPartition",
"(",
"OptionParser",
"parser",
")",
"{",
"parser",
".",
"acceptsAll",
"(",
"Arrays",
".",
"asList",
"(",
"OPT_P",
",",
"OPT_PARTITION",
")",
",",
"\"partition id list\"",
")",
".",
"withRequiredArg",
"(",
")",
".... | Adds OPT_P | OPT_PARTITION option to OptionParser, with multiple
arguments.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"Adds",
"OPT_P",
"|",
"OPT_PARTITION",
"option",
"to",
"OptionParser",
"with",
"multiple",
"arguments",
"."
] | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminParserUtils.java#L283-L289 | train |
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",
... | 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 | train |
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",
... | 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 | train |
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",
"("... | 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 | train |
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 cons... | 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 | train |
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. Th... | 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 | train |
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 | train |
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",... | 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 | train |
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",
")",
".",
... | 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 | train |
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",
"(",
"S... | 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 | train |
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",
".... | 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 | train |
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",
"+=",
"partitionStoresMigrat... | 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 | train |
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",
"partitionStoreR... | 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 | train |
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",
")",
"/",
... | 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 | train |
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",
"... | 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 | train |
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",
",",... | 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 | train |
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",
")",... | 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 | train |
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",
"S... | 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 | train |
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",
"(",
... | 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 | train |
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",
"InputStreamRe... | 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 | train |
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",
")",
... | 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 | train |
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\"",
")",
";",
"comm... | 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 | train |
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",
"(",
")",
... | 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 | train |
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",
"(",
")",... | 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",
"Commi... | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/BaseStreamingClient.java#L648-L733 | train |
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",
"(... | 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 | train |
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",
"!=",
... | 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 | train |
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",
"(... | 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 | train |
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\"",
")",
";",
... | 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 | train |
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",
... | 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 | train |
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 ... | 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 | train |
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",
"... | 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 | train |
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",
"(",
")",
";",
"... | 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 | train |
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",
"("... | 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 | train |
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... | 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 | train |
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",
"="... | 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 | train |
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",
"(",
")",
";",
"}",
"FileInputStr... | 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 | train |
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",
"(",
")",
")",
";",
"Li... | 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 | train |
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",
"(",
"requiredRepFac... | 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 | train |
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",
"(",
")",... | 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 | train |
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",
... | 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 | train |
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",
"]... | 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 | train |
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",
"... | 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 | train |
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",
"<"... | 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",... | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L406-L450 | train |
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"... | 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 | train |
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... | 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 | train |
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",
"VectorClo... | 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 | train |
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",
... | 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 | train |
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",
"(",
"!... | 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 | train |
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",
",",
... | 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 | train |
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",
"(",
"sto... | 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 | train |
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... | 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 | train |
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"... | 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",
"serv... | a7dbdea58032021361680faacf2782cf981c5332 | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L1142-L1152 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.