code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
private void init() {
logger.info("metadata init().");
writeLock.lock();
try {
// Required keys
initCache(CLUSTER_KEY);
// If stores definition storage engine is not null, initialize metadata
// Add the mapping from key to the storage engine used
if(this.storeDefinitionsStorageEngine != null) {
initStoreDefinitions(null);
} else {
initCache(STORES_KEY);
}
// Initialize system store in the metadata cache
initSystemCache();
initSystemRoutingStrategies(getCluster());
// Initialize with default if not present
initCache(SLOP_STREAMING_ENABLED_KEY, true);
initCache(PARTITION_STREAMING_ENABLED_KEY, true);
initCache(READONLY_FETCH_ENABLED_KEY, true);
initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true);
initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>()));
initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString());
initCache(REBALANCING_SOURCE_CLUSTER_XML, null);
initCache(REBALANCING_SOURCE_STORES_XML, null);
} finally {
writeLock.unlock();
}
} | java |
private void initStoreDefinitions(Version storesXmlVersion) {
if(this.storeDefinitionsStorageEngine == null) {
throw new VoldemortException("The store definitions directory is empty");
}
String allStoreDefinitions = "<stores>";
Version finalStoresXmlVersion = null;
if(storesXmlVersion != null) {
finalStoresXmlVersion = storesXmlVersion;
}
this.storeNames.clear();
ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries();
// Some test setups may result in duplicate entries for 'store' element.
// Do the de-dup here
Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>();
Version maxVersion = null;
while(storesIterator.hasNext()) {
Pair<String, Versioned<String>> storeDetail = storesIterator.next();
String storeName = storeDetail.getFirst();
Versioned<String> versionedStoreDef = storeDetail.getSecond();
storeNameToDefMap.put(storeName, versionedStoreDef);
Version curVersion = versionedStoreDef.getVersion();
// Get the highest version from all the store entries
if(maxVersion == null) {
maxVersion = curVersion;
} else if(maxVersion.compare(curVersion) == Occurred.BEFORE) {
maxVersion = curVersion;
}
}
// If the specified version is null, assign highest Version to
// 'stores.xml' key
if(finalStoresXmlVersion == null) {
finalStoresXmlVersion = maxVersion;
}
// Go through all the individual stores and update metadata
for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) {
String storeName = storeEntry.getKey();
Versioned<String> versionedStoreDef = storeEntry.getValue();
// Add all the store names to the list of storeNames
this.storeNames.add(storeName);
this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(),
versionedStoreDef.getVersion()));
}
Collections.sort(this.storeNames);
for(String storeName: this.storeNames) {
Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName);
// Stitch together to form the complete store definition list.
allStoreDefinitions += versionedStoreDef.getValue();
}
allStoreDefinitions += "</stores>";
// Update cache with the composite store definition list.
metadataCache.put(STORES_KEY,
convertStringToObject(STORES_KEY,
new Versioned<String>(allStoreDefinitions,
finalStoresXmlVersion)));
} | java |
private void resetStoreDefinitions(Set<String> storeNamesToDelete) {
// Clear entries in the metadata cache
for(String storeName: storeNamesToDelete) {
this.metadataCache.remove(storeName);
this.storeDefinitionsStorageEngine.delete(storeName, null);
this.storeNames.remove(storeName);
}
} | java |
private synchronized void initSystemCache() {
List<StoreDefinition> value = storeMapper.readStoreList(new StringReader(SystemStoreConstants.SYSTEM_STORE_SCHEMA));
metadataCache.put(SYSTEM_STORES_KEY, new Versioned<Object>(value));
} | java |
public List<Versioned<V>> getWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {
validateTimeout(requestWrapper.getRoutingTimeoutInMs());
for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) {
try {
long startTimeInMs = System.currentTimeMillis();
String keyHexString = "";
if(logger.isDebugEnabled()) {
ByteArray key = (ByteArray) requestWrapper.getKey();
keyHexString = RestUtils.getKeyHexString(key);
debugLogStart("GET",
requestWrapper.getRequestOriginTimeInMs(),
startTimeInMs,
keyHexString);
}
List<Versioned<V>> items = store.get(requestWrapper);
if(logger.isDebugEnabled()) {
int vcEntrySize = 0;
for(Versioned<V> vc: items) {
vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size();
}
debugLogEnd("GET",
requestWrapper.getRequestOriginTimeInMs(),
startTimeInMs,
System.currentTimeMillis(),
keyHexString,
vcEntrySize);
}
return items;
} catch(InvalidMetadataException e) {
logger.info("Received invalid metadata exception during get [ " + e.getMessage()
+ " ] on store '" + storeName + "'. Rebootstrapping");
bootStrap();
}
}
throw new VoldemortException(this.metadataRefreshAttempts
+ " metadata refresh attempts failed.");
} | java |
public Version putWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {
validateTimeout(requestWrapper.getRoutingTimeoutInMs());
List<Versioned<V>> versionedValues;
long startTime = System.currentTimeMillis();
String keyHexString = "";
if(logger.isDebugEnabled()) {
ByteArray key = (ByteArray) requestWrapper.getKey();
keyHexString = RestUtils.getKeyHexString(key);
logger.debug("PUT requested for key: " + keyHexString + " , for store: "
+ this.storeName + " at time(in ms): " + startTime
+ " . Nested GET and PUT VERSION requests to follow ---");
}
// We use the full timeout for doing the Get. In this, we're being
// optimistic that the subsequent put might be faster such that all the
// steps might finish within the allotted time
requestWrapper.setResolveConflicts(true);
versionedValues = getWithCustomTimeout(requestWrapper);
Versioned<V> versioned = getItemOrThrow(requestWrapper.getKey(), null, versionedValues);
long endTime = System.currentTimeMillis();
if(versioned == null)
versioned = Versioned.value(requestWrapper.getRawValue(), new VectorClock());
else
versioned.setObject(requestWrapper.getRawValue());
// This should not happen unless there's a bug in the
// getWithCustomTimeout
long timeLeft = requestWrapper.getRoutingTimeoutInMs() - (endTime - startTime);
if(timeLeft <= 0) {
throw new StoreTimeoutException("PUT request timed out");
}
CompositeVersionedPutVoldemortRequest<K, V> putVersionedRequestObject = new CompositeVersionedPutVoldemortRequest<K, V>(requestWrapper.getKey(),
versioned,
timeLeft);
putVersionedRequestObject.setRequestOriginTimeInMs(requestWrapper.getRequestOriginTimeInMs());
Version result = putVersionedWithCustomTimeout(putVersionedRequestObject);
long endTimeInMs = System.currentTimeMillis();
if(logger.isDebugEnabled()) {
logger.debug("PUT response received for key: " + keyHexString + " , for store: "
+ this.storeName + " at time(in ms): " + endTimeInMs);
}
return result;
} | java |
public Version putVersionedWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper)
throws ObsoleteVersionException {
validateTimeout(requestWrapper.getRoutingTimeoutInMs());
for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) {
try {
String keyHexString = "";
long startTimeInMs = System.currentTimeMillis();
if(logger.isDebugEnabled()) {
ByteArray key = (ByteArray) requestWrapper.getKey();
keyHexString = RestUtils.getKeyHexString(key);
debugLogStart("PUT_VERSION",
requestWrapper.getRequestOriginTimeInMs(),
startTimeInMs,
keyHexString);
}
store.put(requestWrapper);
if(logger.isDebugEnabled()) {
debugLogEnd("PUT_VERSION",
requestWrapper.getRequestOriginTimeInMs(),
startTimeInMs,
System.currentTimeMillis(),
keyHexString,
0);
}
return requestWrapper.getValue().getVersion();
} catch(InvalidMetadataException e) {
logger.info("Received invalid metadata exception during put [ " + e.getMessage()
+ " ] on store '" + storeName + "'. Rebootstrapping");
bootStrap();
}
}
throw new VoldemortException(this.metadataRefreshAttempts
+ " metadata refresh attempts failed.");
} | java |
public Map<K, List<Versioned<V>>> getAllWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {
validateTimeout(requestWrapper.getRoutingTimeoutInMs());
Map<K, List<Versioned<V>>> items = null;
for(int attempts = 0;; attempts++) {
if(attempts >= this.metadataRefreshAttempts)
throw new VoldemortException(this.metadataRefreshAttempts
+ " metadata refresh attempts failed.");
try {
String KeysHexString = "";
long startTimeInMs = System.currentTimeMillis();
if(logger.isDebugEnabled()) {
Iterable<ByteArray> keys = (Iterable<ByteArray>) requestWrapper.getIterableKeys();
KeysHexString = getKeysHexString(keys);
debugLogStart("GET_ALL",
requestWrapper.getRequestOriginTimeInMs(),
startTimeInMs,
KeysHexString);
}
items = store.getAll(requestWrapper);
if(logger.isDebugEnabled()) {
int vcEntrySize = 0;
for(List<Versioned<V>> item: items.values()) {
for(Versioned<V> vc: item) {
vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size();
}
}
debugLogEnd("GET_ALL",
requestWrapper.getRequestOriginTimeInMs(),
startTimeInMs,
System.currentTimeMillis(),
KeysHexString,
vcEntrySize);
}
return items;
} catch(InvalidMetadataException e) {
logger.info("Received invalid metadata exception during getAll [ "
+ e.getMessage() + " ] on store '" + storeName + "'. Rebootstrapping");
bootStrap();
}
}
} | java |
public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) {
List<Versioned<V>> versionedValues;
validateTimeout(deleteRequestObject.getRoutingTimeoutInMs());
boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true;
String keyHexString = "";
if(!hasVersion) {
long startTimeInMs = System.currentTimeMillis();
if(logger.isDebugEnabled()) {
ByteArray key = (ByteArray) deleteRequestObject.getKey();
keyHexString = RestUtils.getKeyHexString(key);
logger.debug("DELETE without version requested for key: " + keyHexString
+ " , for store: " + this.storeName + " at time(in ms): "
+ startTimeInMs + " . Nested GET and DELETE requests to follow ---");
}
// We use the full timeout for doing the Get. In this, we're being
// optimistic that the subsequent delete might be faster all the
// steps might finish within the allotted time
deleteRequestObject.setResolveConflicts(true);
versionedValues = getWithCustomTimeout(deleteRequestObject);
Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(),
null,
versionedValues);
if(versioned == null) {
return false;
}
long timeLeft = deleteRequestObject.getRoutingTimeoutInMs()
- (System.currentTimeMillis() - startTimeInMs);
// This should not happen unless there's a bug in the
// getWithCustomTimeout
if(timeLeft < 0) {
throw new StoreTimeoutException("DELETE request timed out");
}
// Update the version and the new timeout
deleteRequestObject.setVersion(versioned.getVersion());
deleteRequestObject.setRoutingTimeoutInMs(timeLeft);
}
long deleteVersionStartTimeInNs = System.currentTimeMillis();
if(logger.isDebugEnabled()) {
ByteArray key = (ByteArray) deleteRequestObject.getKey();
keyHexString = RestUtils.getKeyHexString(key);
debugLogStart("DELETE",
deleteRequestObject.getRequestOriginTimeInMs(),
deleteVersionStartTimeInNs,
keyHexString);
}
boolean result = store.delete(deleteRequestObject);
if(logger.isDebugEnabled()) {
debugLogEnd("DELETE",
deleteRequestObject.getRequestOriginTimeInMs(),
deleteVersionStartTimeInNs,
System.currentTimeMillis(),
keyHexString,
0);
}
if(!hasVersion && logger.isDebugEnabled()) {
logger.debug("DELETE without version response received for key: " + keyHexString
+ ", for store: " + this.storeName + " at time(in ms): "
+ System.currentTimeMillis());
}
return result;
} | java |
private void debugLogStart(String operationType,
Long originTimeInMS,
Long requestReceivedTimeInMs,
String keyString) {
long durationInMs = requestReceivedTimeInMs - originTimeInMS;
logger.debug("Received a new request. Operation Type: " + operationType + " , key(s): "
+ keyString + " , Store: " + this.storeName + " , Origin time (in ms): "
+ originTimeInMS + " . Request received at time(in ms): "
+ requestReceivedTimeInMs
+ " , Duration from RESTClient to CoordinatorFatClient(in ms): "
+ durationInMs);
} | java |
private void debugLogEnd(String operationType,
Long OriginTimeInMs,
Long RequestStartTimeInMs,
Long ResponseReceivedTimeInMs,
String keyString,
int numVectorClockEntries) {
long durationInMs = ResponseReceivedTimeInMs - RequestStartTimeInMs;
logger.debug("Received a response from voldemort server for Operation Type: "
+ operationType
+ " , For key(s): "
+ keyString
+ " , Store: "
+ this.storeName
+ " , Origin time of request (in ms): "
+ OriginTimeInMs
+ " , Response received at time (in ms): "
+ ResponseReceivedTimeInMs
+ " . Request sent at(in ms): "
+ RequestStartTimeInMs
+ " , Num vector clock entries: "
+ numVectorClockEntries
+ " , Duration from CoordinatorFatClient back to CoordinatorFatClient(in ms): "
+ durationInMs);
} | java |
public static Node updateNode(Node node, List<Integer> partitionsList) {
return new Node(node.getId(),
node.getHost(),
node.getHttpPort(),
node.getSocketPort(),
node.getAdminPort(),
node.getZoneId(),
partitionsList);
} | java |
public static Node addPartitionToNode(final Node node, Integer donatedPartition) {
return UpdateClusterUtils.addPartitionsToNode(node, Sets.newHashSet(donatedPartition));
} | java |
public static Node removePartitionFromNode(final Node node, Integer donatedPartition) {
return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition));
} | java |
public static Node addPartitionsToNode(final Node node, final Set<Integer> donatedPartitions) {
List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());
deepCopy.addAll(donatedPartitions);
Collections.sort(deepCopy);
return updateNode(node, deepCopy);
} | java |
public static Node removePartitionsFromNode(final Node node,
final Set<Integer> donatedPartitions) {
List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());
deepCopy.removeAll(donatedPartitions);
return updateNode(node, deepCopy);
} | java |
public static Cluster createUpdatedCluster(Cluster currentCluster,
int stealerNodeId,
List<Integer> donatedPartitions) {
Cluster updatedCluster = Cluster.cloneCluster(currentCluster);
// Go over every donated partition one by one
for(int donatedPartition: donatedPartitions) {
// Gets the donor Node that owns this donated partition
Node donorNode = updatedCluster.getNodeForPartitionId(donatedPartition);
Node stealerNode = updatedCluster.getNodeById(stealerNodeId);
if(donorNode == stealerNode) {
// Moving to the same location = No-op
continue;
}
// Update the list of partitions for this node
donorNode = removePartitionFromNode(donorNode, donatedPartition);
stealerNode = addPartitionToNode(stealerNode, donatedPartition);
// Sort the nodes
updatedCluster = updateCluster(updatedCluster,
Lists.newArrayList(donorNode, stealerNode));
}
return updatedCluster;
} | java |
public static void main(String[] args) {
DirectoryIterator iter = new DirectoryIterator(args);
while(iter.hasNext())
System.out.println(iter.next().getAbsolutePath());
} | java |
private void verifyClusterStoreDefinition() {
if(SystemStoreConstants.isSystemStore(storeDefinition.getName())) {
// TODO: Once "todo" in StorageService.initSystemStores is complete,
// this early return can be removed and verification can be enabled
// for system stores.
return;
}
Set<Integer> clusterZoneIds = cluster.getZoneIds();
if(clusterZoneIds.size() > 1) { // Zoned
Map<Integer, Integer> zoneRepFactor = storeDefinition.getZoneReplicationFactor();
Set<Integer> storeDefZoneIds = zoneRepFactor.keySet();
if(!clusterZoneIds.equals(storeDefZoneIds)) {
throw new VoldemortException("Zone IDs in cluster (" + clusterZoneIds
+ ") are incongruent with zone IDs in store defs ("
+ storeDefZoneIds + ")");
}
for(int zoneId: clusterZoneIds) {
if(zoneRepFactor.get(zoneId) > cluster.getNumberOfNodesInZone(zoneId)) {
throw new VoldemortException("Not enough nodes ("
+ cluster.getNumberOfNodesInZone(zoneId)
+ ") in zone with id " + zoneId
+ " for replication factor of "
+ zoneRepFactor.get(zoneId) + ".");
}
}
} else { // Non-zoned
if(storeDefinition.getReplicationFactor() > cluster.getNumberOfNodes()) {
System.err.println(storeDefinition);
System.err.println(cluster);
throw new VoldemortException("Not enough nodes (" + cluster.getNumberOfNodes()
+ ") for replication factor of "
+ storeDefinition.getReplicationFactor() + ".");
}
}
} | java |
public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {
// this is all the partitions the key replicates to.
List<Integer> partitionIds = getReplicatingPartitionList(key);
for(Integer partitionId: partitionIds) {
// check which of the replicating partitions belongs to the node in
// question
if(getNodeIdForPartitionId(partitionId) == nodeId) {
return partitionId;
}
}
return null;
} | java |
private List<Integer> getNodeIdListForPartitionIdList(List<Integer> partitionIds)
throws VoldemortException {
List<Integer> nodeIds = new ArrayList<Integer>(partitionIds.size());
for(Integer partitionId: partitionIds) {
int nodeId = getNodeIdForPartitionId(partitionId);
if(nodeIds.contains(nodeId)) {
throw new VoldemortException("Node ID " + nodeId + " already in list of Node IDs.");
} else {
nodeIds.add(nodeId);
}
}
return nodeIds;
} | java |
public boolean checkKeyBelongsToNode(byte[] key, int nodeId) {
List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds();
List<Integer> replicatingPartitions = getReplicatingPartitionList(key);
// remove all partitions from the list, except those that belong to the
// node
replicatingPartitions.retainAll(nodePartitions);
return replicatingPartitions.size() > 0;
} | java |
public static List<Integer> checkKeyBelongsToPartition(byte[] key,
Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,
Cluster cluster,
StoreDefinition storeDef) {
List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,
cluster)
.getPartitionList(key);
List<Integer> nodesToPush = Lists.newArrayList();
for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {
List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())
.getPartitionIds();
if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,
nodePartitions,
stealNodeToMap.getSecond())) {
nodesToPush.add(stealNodeToMap.getFirst());
}
}
return nodesToPush;
} | java |
public synchronized void maybeThrottle(int eventsSeen) {
if (maxRatePerSecond > 0) {
long now = time.milliseconds();
try {
rateSensor.record(eventsSeen, now);
} catch (QuotaViolationException e) {
// If we're over quota, we calculate how long to sleep to compensate.
double currentRate = e.getValue();
if (currentRate > this.maxRatePerSecond) {
double excessRate = currentRate - this.maxRatePerSecond;
long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND);
if(logger.isDebugEnabled()) {
logger.debug("Throttler quota exceeded:\n" +
"eventsSeen \t= " + eventsSeen + " in this call of maybeThrotte(),\n" +
"currentRate \t= " + currentRate + " events/sec,\n" +
"maxRatePerSecond \t= " + this.maxRatePerSecond + " events/sec,\n" +
"excessRate \t= " + excessRate + " events/sec,\n" +
"sleeping for \t" + sleepTimeMs + " ms to compensate.\n" +
"rateConfig.timeWindowMs() = " + rateConfig.timeWindowMs());
}
if (sleepTimeMs > rateConfig.timeWindowMs()) {
logger.warn("Throttler sleep time (" + sleepTimeMs + " ms) exceeds " +
"window size (" + rateConfig.timeWindowMs() + " ms). This will likely " +
"result in not being able to honor the rate limit accurately.");
// When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size
// too high could cause this problem.
}
time.sleep(sleepTimeMs);
} else if (logger.isDebugEnabled()) {
logger.debug("Weird. Got QuotaValidationException but measured rate not over rateLimit: " +
"currentRate = " + currentRate + " , rateLimit = " + this.maxRatePerSecond);
}
}
}
} | java |
public List<NodeValue<K, V>> getRepairs(List<NodeValue<K, V>> nodeValues) {
int size = nodeValues.size();
if(size <= 1)
return Collections.emptyList();
Map<K, List<NodeValue<K, V>>> keyToNodeValues = Maps.newHashMap();
for(NodeValue<K, V> nodeValue: nodeValues) {
List<NodeValue<K, V>> keyNodeValues = keyToNodeValues.get(nodeValue.getKey());
if(keyNodeValues == null) {
keyNodeValues = Lists.newArrayListWithCapacity(5);
keyToNodeValues.put(nodeValue.getKey(), keyNodeValues);
}
keyNodeValues.add(nodeValue);
}
List<NodeValue<K, V>> result = Lists.newArrayList();
for(List<NodeValue<K, V>> keyNodeValues: keyToNodeValues.values())
result.addAll(singleKeyGetRepairs(keyNodeValues));
return result;
} | java |
public static List<Versioned<byte[]>> resolveVersions(List<Versioned<byte[]>> values) {
List<Versioned<byte[]>> resolvedVersions = new ArrayList<Versioned<byte[]>>(values.size());
// Go over all the values and determine whether the version is
// acceptable
for(Versioned<byte[]> value: values) {
Iterator<Versioned<byte[]>> iter = resolvedVersions.iterator();
boolean obsolete = false;
// Compare the current version with a set of accepted versions
while(iter.hasNext()) {
Versioned<byte[]> curr = iter.next();
Occurred occurred = value.getVersion().compare(curr.getVersion());
if(occurred == Occurred.BEFORE) {
obsolete = true;
break;
} else if(occurred == Occurred.AFTER) {
iter.remove();
}
}
if(!obsolete) {
// else update the set of accepted versions
resolvedVersions.add(value);
}
}
return resolvedVersions;
} | java |
public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {
List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());
for(Integer serverId: serverIds) {
clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));
}
return new VectorClock(clockEntries, timestamp);
} | java |
private String swapStore(String storeName, String directory) throws VoldemortException {
ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore,
storeRepository,
storeName);
if(!Utils.isReadableDir(directory))
throw new VoldemortException("Store directory '" + directory
+ "' is not a readable directory.");
String currentDirPath = store.getCurrentDirPath();
logger.info("Swapping RO store '" + storeName + "' to version directory '" + directory
+ "'");
store.swapFiles(directory);
logger.info("Swapping swapped RO store '" + storeName + "' to version directory '"
+ directory + "'");
return currentDirPath;
} | java |
@Override
public boolean isCompleteRequest(ByteBuffer buffer) {
DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));
try {
int dataSize = inputStream.readInt();
if(logger.isTraceEnabled())
logger.trace("In isCompleteRequest, dataSize: " + dataSize + ", buffer position: "
+ buffer.position());
if(dataSize == -1)
return true;
// Here we skip over the data (without reading it in) and
// move our position to just past it.
buffer.position(buffer.position() + dataSize);
return true;
} catch(Exception e) {
// This could also occur if the various methods we call into
// re-throw a corrupted value error as some other type of exception.
// For example, updating the position on a buffer past its limit
// throws an InvalidArgumentException.
if(logger.isTraceEnabled())
logger.trace("In isCompleteRequest, probable partial read occurred: " + e);
return false;
}
} | java |
public synchronized void unregisterJmxIfRequired() {
referenceCount--;
if (isRegistered == true && referenceCount <= 0) {
JmxUtils.unregisterMbean(this.jmxObjectName);
isRegistered = false;
}
} | java |
public static String toBinaryString(byte[] bytes) {
StringBuilder buffer = new StringBuilder();
for(byte b: bytes) {
String bin = Integer.toBinaryString(0xFF & b);
bin = bin.substring(0, Math.min(bin.length(), 8));
for(int j = 0; j < 8 - bin.length(); j++) {
buffer.append('0');
}
buffer.append(bin);
}
return buffer.toString();
} | java |
public static byte[] copy(byte[] array, int from, int to) {
if(to - from < 0) {
return new byte[0];
} else {
byte[] a = new byte[to - from];
System.arraycopy(array, from, a, 0, to - from);
return a;
}
} | java |
public static int readInt(byte[] bytes, int offset) {
return (((bytes[offset + 0] & 0xff) << 24) | ((bytes[offset + 1] & 0xff) << 16)
| ((bytes[offset + 2] & 0xff) << 8) | (bytes[offset + 3] & 0xff));
} | java |
public static long readUnsignedInt(byte[] bytes, int offset) {
return (((bytes[offset + 0] & 0xffL) << 24) | ((bytes[offset + 1] & 0xffL) << 16)
| ((bytes[offset + 2] & 0xffL) << 8) | (bytes[offset + 3] & 0xffL));
} | java |
public static long readBytes(byte[] bytes, int offset, int numBytes) {
int shift = 0;
long value = 0;
for(int i = offset + numBytes - 1; i >= offset; i--) {
value |= (bytes[i] & 0xFFL) << shift;
shift += 8;
}
return value;
} | java |
public static void writeShort(byte[] bytes, short value, int offset) {
bytes[offset] = (byte) (0xFF & (value >> 8));
bytes[offset + 1] = (byte) (0xFF & value);
} | java |
public static void writeUnsignedShort(byte[] bytes, int value, int offset) {
bytes[offset] = (byte) (0xFF & (value >> 8));
bytes[offset + 1] = (byte) (0xFF & value);
} | java |
public static void writeInt(byte[] bytes, int value, int offset) {
bytes[offset] = (byte) (0xFF & (value >> 24));
bytes[offset + 1] = (byte) (0xFF & (value >> 16));
bytes[offset + 2] = (byte) (0xFF & (value >> 8));
bytes[offset + 3] = (byte) (0xFF & value);
} | java |
public static void writeBytes(byte[] bytes, long value, int offset, int numBytes) {
int shift = 0;
for(int i = offset + numBytes - 1; i >= offset; i--) {
bytes[i] = (byte) (0xFF & (value >> shift));
shift += 8;
}
} | java |
public static byte numberOfBytesRequired(long number) {
if(number < 0)
number = -number;
for(byte i = 1; i <= SIZE_OF_LONG; i++)
if(number < (1L << (8 * i)))
return i;
throw new IllegalStateException("Should never happen.");
} | java |
public static void read(InputStream stream, byte[] buffer) throws IOException {
int read = 0;
while(read < buffer.length) {
int newlyRead = stream.read(buffer, read, buffer.length - read);
if(newlyRead == -1)
throw new EOFException("Attempt to read " + buffer.length
+ " bytes failed due to EOF.");
read += newlyRead;
}
} | java |
public static byte[] getBytes(String string, String encoding) {
try {
return string.getBytes(encoding);
} catch(UnsupportedEncodingException e) {
throw new IllegalArgumentException(encoding + " is not a known encoding name.", e);
}
} | java |
public static String getString(byte[] bytes, String encoding) {
try {
return new String(bytes, encoding);
} catch(UnsupportedEncodingException e) {
throw new IllegalArgumentException(encoding + " is not a known encoding name.", e);
}
} | java |
public void addRequest(long timeNS,
long numEmptyResponses,
long valueBytes,
long keyBytes,
long getAllAggregatedCount) {
// timing instrumentation (trace only)
long startTimeNs = 0;
if(logger.isTraceEnabled()) {
startTimeNs = System.nanoTime();
}
long currentTime = time.milliseconds();
timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);
emptyResponseKeysSensor.record(numEmptyResponses, currentTime);
valueBytesSensor.record(valueBytes, currentTime);
keyBytesSensor.record(keyBytes, currentTime);
getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);
// timing instrumentation (trace only)
if(logger.isTraceEnabled()) {
logger.trace("addRequest took " + (System.nanoTime() - startTimeNs) + " ns.");
}
} | java |
public void addEvent(Event event) {
if(event == null)
throw new IllegalStateException("event must be non-null");
if(logger.isTraceEnabled())
logger.trace("Adding event " + event);
eventQueue.add(event);
} | java |
public void execute() {
try {
while(true) {
Event event = null;
try {
event = eventQueue.poll(timeout, unit);
} catch(InterruptedException e) {
throw new InsufficientOperationalNodesException(operation.getSimpleName()
+ " operation interrupted!", e);
}
if(event == null)
throw new VoldemortException(operation.getSimpleName()
+ " returned a null event");
if(event.equals(Event.ERROR)) {
if(logger.isTraceEnabled())
logger.trace(operation.getSimpleName()
+ " request, events complete due to error");
break;
} else if(event.equals(Event.COMPLETED)) {
if(logger.isTraceEnabled())
logger.trace(operation.getSimpleName() + " request, events complete");
break;
}
Action action = eventActions.get(event);
if(action == null)
throw new IllegalStateException("action was null for event " + event);
if(logger.isTraceEnabled())
logger.trace(operation.getSimpleName() + " request, action "
+ action.getClass().getSimpleName() + " to handle " + event
+ " event");
action.execute(this);
}
} finally {
finished = true;
}
} | java |
public static ModelMBean createModelMBean(Object o) {
try {
ModelMBean mbean = new RequiredModelMBean();
JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);
String description = annotation == null ? "" : annotation.description();
ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),
description,
extractAttributeInfo(o),
new ModelMBeanConstructorInfo[0],
extractOperationInfo(o),
new ModelMBeanNotificationInfo[0]);
mbean.setModelMBeanInfo(info);
mbean.setManagedResource(o, "ObjectReference");
return mbean;
} catch(MBeanException e) {
throw new VoldemortException(e);
} catch(InvalidTargetObjectTypeException e) {
throw new VoldemortException(e);
} catch(InstanceNotFoundException e) {
throw new VoldemortException(e);
}
} | java |
public static ModelMBeanOperationInfo[] extractOperationInfo(Object object) {
ArrayList<ModelMBeanOperationInfo> infos = new ArrayList<ModelMBeanOperationInfo>();
for(Method m: object.getClass().getMethods()) {
JmxOperation jmxOperation = m.getAnnotation(JmxOperation.class);
JmxGetter jmxGetter = m.getAnnotation(JmxGetter.class);
JmxSetter jmxSetter = m.getAnnotation(JmxSetter.class);
if(jmxOperation != null || jmxGetter != null || jmxSetter != null) {
String description = "";
int visibility = 1;
int impact = MBeanOperationInfo.UNKNOWN;
if(jmxOperation != null) {
description = jmxOperation.description();
impact = jmxOperation.impact();
} else if(jmxGetter != null) {
description = jmxGetter.description();
impact = MBeanOperationInfo.INFO;
visibility = 4;
} else if(jmxSetter != null) {
description = jmxSetter.description();
impact = MBeanOperationInfo.ACTION;
visibility = 4;
}
ModelMBeanOperationInfo info = new ModelMBeanOperationInfo(m.getName(),
description,
extractParameterInfo(m),
m.getReturnType()
.getName(), impact);
info.getDescriptor().setField("visibility", Integer.toString(visibility));
infos.add(info);
}
}
return infos.toArray(new ModelMBeanOperationInfo[infos.size()]);
} | java |
public static MBeanParameterInfo[] extractParameterInfo(Method m) {
Class<?>[] types = m.getParameterTypes();
Annotation[][] annotations = m.getParameterAnnotations();
MBeanParameterInfo[] params = new MBeanParameterInfo[types.length];
for(int i = 0; i < params.length; i++) {
boolean hasAnnotation = false;
for(int j = 0; j < annotations[i].length; j++) {
if(annotations[i][j] instanceof JmxParam) {
JmxParam param = (JmxParam) annotations[i][j];
params[i] = new MBeanParameterInfo(param.name(),
types[i].getName(),
param.description());
hasAnnotation = true;
break;
}
}
if(!hasAnnotation) {
params[i] = new MBeanParameterInfo("", types[i].getName(), "");
}
}
return params;
} | java |
public static ObjectName createObjectName(String domain, String type) {
try {
return new ObjectName(domain + ":type=" + type);
} catch(MalformedObjectNameException e) {
throw new VoldemortException(e);
}
} | java |
public static String getClassName(Class<?> c) {
String name = c.getName();
return name.substring(name.lastIndexOf('.') + 1, name.length());
} | java |
public static void registerMbean(Object mbean, ObjectName name) {
registerMbean(ManagementFactory.getPlatformMBeanServer(),
JmxUtils.createModelMBean(mbean),
name);
} | java |
public static ObjectName registerMbean(String typeName, Object obj) {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()),
typeName);
registerMbean(server, JmxUtils.createModelMBean(obj), name);
return name;
} | java |
public static void registerMbean(MBeanServer server, ModelMBean mbean, ObjectName name) {
try {
synchronized(LOCK) {
if(server.isRegistered(name))
JmxUtils.unregisterMbean(server, name);
server.registerMBean(mbean, name);
}
} catch(Exception e) {
logger.error("Error registering mbean:", e);
}
} | java |
public static void unregisterMbean(MBeanServer server, ObjectName name) {
try {
server.unregisterMBean(name);
} catch(Exception e) {
logger.error("Error unregistering mbean", e);
}
} | java |
public static void unregisterMbean(ObjectName name) {
try {
ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);
} catch(Exception e) {
logger.error("Error unregistering mbean", e);
}
} | java |
public static boolean isFormatCorrect(String fileName, ReadOnlyStorageFormat format) {
switch(format) {
case READONLY_V0:
case READONLY_V1:
if(fileName.matches("^[\\d]+_[\\d]+\\.(data|index)")) {
return true;
} else {
return false;
}
case READONLY_V2:
if(fileName.matches("^[\\d]+_[\\d]+_[\\d]+\\.(data|index)")) {
return true;
} else {
return false;
}
default:
throw new VoldemortException("Format type not supported");
}
} | java |
public static int getChunkId(String fileName) {
Pattern pattern = Pattern.compile("_[\\d]+\\.");
Matcher matcher = pattern.matcher(fileName);
if(matcher.find()) {
return new Integer(fileName.substring(matcher.start() + 1, matcher.end() - 1));
} else {
throw new VoldemortException("Could not extract out chunk id from " + fileName);
}
} | java |
public static File getCurrentVersion(File storeDirectory) {
File latestDir = getLatestDir(storeDirectory);
if(latestDir != null)
return latestDir;
File[] versionDirs = getVersionDirs(storeDirectory);
if(versionDirs == null || versionDirs.length == 0) {
return null;
} else {
return findKthVersionedDir(versionDirs, versionDirs.length - 1, versionDirs.length - 1)[0];
}
} | java |
public static boolean checkVersionDirName(File versionDir) {
return (versionDir.isDirectory() && versionDir.getName().contains("version-") && !versionDir.getName()
.endsWith(".bak"));
} | java |
private static long getVersionId(String versionDir) {
try {
return Long.parseLong(versionDir.replace("version-", ""));
} catch(NumberFormatException e) {
logger.trace("Cannot parse version directory to obtain id " + versionDir);
return -1;
}
} | java |
public static File[] getVersionDirs(File rootDir, final long minId, final long maxId) {
return rootDir.listFiles(new FileFilter() {
public boolean accept(File pathName) {
if(checkVersionDirName(pathName)) {
long versionId = getVersionId(pathName);
if(versionId != -1 && versionId <= maxId && versionId >= minId) {
return true;
}
}
return false;
}
});
} | java |
@Override
protected void stopInner() throws VoldemortException {
List<VoldemortException> exceptions = new ArrayList<VoldemortException>();
logger.info("Stopping services:" + getIdentityNode().getId());
/* Stop in reverse order */
exceptions.addAll(stopOnlineServices());
for(VoldemortService service: Utils.reversed(basicServices)) {
try {
service.stop();
} catch(VoldemortException e) {
exceptions.add(e);
logger.error(e);
}
}
logger.info("All services stopped for Node:" + getIdentityNode().getId());
if(exceptions.size() > 0)
throw exceptions.get(0);
// release lock of jvm heap
JNAUtils.tryMunlockall();
} | java |
private int getReplicaTypeForPartition(int partitionId) {
List<Integer> routingPartitionList = routingStrategy.getReplicatingPartitionList(partitionId);
// Determine if we should host this partition, and if so, whether we are a primary,
// secondary or n-ary replica for it
int correctReplicaType = -1;
for (int replica = 0; replica < routingPartitionList.size(); replica++) {
if(nodePartitionIds.contains(routingPartitionList.get(replica))) {
// This means the partitionId currently being iterated on should be hosted
// by this node. Let's remember its replica type in order to make sure the
// files we have are properly named.
correctReplicaType = replica;
break;
}
}
return correctReplicaType;
} | java |
private void renameReadOnlyV2Files(int masterPartitionId, int correctReplicaType) {
for (int replica = 0; replica < routingStrategy.getNumReplicas(); replica++) {
if (replica != correctReplicaType) {
int chunkId = 0;
while (true) {
String fileName = Integer.toString(masterPartitionId) + "_"
+ Integer.toString(replica) + "_"
+ Integer.toString(chunkId);
File index = getIndexFile(fileName);
File data = getDataFile(fileName);
if(index.exists() && data.exists()) {
// We found files with the "wrong" replica type, so let's rename them
String correctFileName = Integer.toString(masterPartitionId) + "_"
+ Integer.toString(correctReplicaType) + "_"
+ Integer.toString(chunkId);
File indexWithCorrectReplicaType = getIndexFile(correctFileName);
File dataWithCorrectReplicaType = getDataFile(correctFileName);
Utils.move(index, indexWithCorrectReplicaType);
Utils.move(data, dataWithCorrectReplicaType);
// Maybe change this to DEBUG?
logger.info("Renamed files with wrong replica type: "
+ index.getAbsolutePath() + "|data -> "
+ indexWithCorrectReplicaType.getName() + "|data");
} else if(index.exists() ^ data.exists()) {
throw new VoldemortException("One of the following does not exist: "
+ index.toString()
+ " or "
+ data.toString() + ".");
} else {
// The files don't exist, or we've gone over all available chunks,
// so let's move on.
break;
}
chunkId++;
}
}
}
} | java |
public byte[] keyToStorageFormat(byte[] key) {
switch(getReadOnlyStorageFormat()) {
case READONLY_V0:
case READONLY_V1:
return ByteUtils.md5(key);
case READONLY_V2:
return ByteUtils.copy(ByteUtils.md5(key), 0, 2 * ByteUtils.SIZE_OF_INT);
default:
throw new VoldemortException("Unknown read-only storage format");
}
} | java |
public int getChunkForKey(byte[] key) throws IllegalStateException {
if(numChunks == 0) {
throw new IllegalStateException("The ChunkedFileSet is closed.");
}
switch(storageFormat) {
case READONLY_V0: {
return ReadOnlyUtils.chunk(ByteUtils.md5(key), numChunks);
}
case READONLY_V1: {
if(nodePartitionIds == null) {
throw new IllegalStateException("nodePartitionIds is null.");
}
List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);
routingPartitionList.retainAll(nodePartitionIds);
if(routingPartitionList.size() != 1) {
throw new IllegalStateException("The key does not belong on this node.");
}
return chunkIdToChunkStart.get(routingPartitionList.get(0))
+ ReadOnlyUtils.chunk(ByteUtils.md5(key),
chunkIdToNumChunks.get(routingPartitionList.get(0)));
}
case READONLY_V2: {
List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);
Pair<Integer, Integer> bucket = null;
for(int replicaType = 0; replicaType < routingPartitionList.size(); replicaType++) {
if(nodePartitionIds == null) {
throw new IllegalStateException("nodePartitionIds is null.");
}
if(nodePartitionIds.contains(routingPartitionList.get(replicaType))) {
if(bucket == null) {
bucket = Pair.create(routingPartitionList.get(0), replicaType);
} else {
throw new IllegalStateException("Found more than one replica for a given partition on the current node!");
}
}
}
if(bucket == null) {
throw new IllegalStateException("The key does not belong on this node.");
}
Integer chunkStart = chunkIdToChunkStart.get(bucket);
if (chunkStart == null) {
throw new IllegalStateException("chunkStart is null.");
}
return chunkStart + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(bucket));
}
default: {
throw new IllegalStateException("Unsupported storageFormat: " + storageFormat);
}
}
} | java |
private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) {
List<String> sourceFileNames = new ArrayList<String>();
for(String fileName: fileNames) {
String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL);
if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) {
sourceFileNames.add(fileName);
}
}
return sourceFileNames;
} | java |
@JmxGetter(name = "getChunkIdToNumChunks", description = "Returns a string representation of the map of chunk id to number of chunks")
public String getChunkIdToNumChunks() {
StringBuilder builder = new StringBuilder();
for(Entry<Object, Integer> entry: fileSet.getChunkIdToNumChunks().entrySet()) {
builder.append(entry.getKey().toString() + " - " + entry.getValue().toString() + ", ");
}
return builder.toString();
} | java |
public void open(File versionDir) {
/* acquire modification lock */
fileModificationLock.writeLock().lock();
try {
/* check that the store is currently closed */
if(isOpen)
throw new IllegalStateException("Attempt to open already open store.");
// Find version directory from symbolic link or max version id
if(versionDir == null) {
versionDir = ReadOnlyUtils.getCurrentVersion(storeDir);
if(versionDir == null)
versionDir = new File(storeDir, "version-0");
}
// Set the max version id
long versionId = ReadOnlyUtils.getVersionId(versionDir);
if(versionId == -1) {
throw new VoldemortException("Unable to parse id from version directory "
+ versionDir.getAbsolutePath());
}
Utils.mkdirs(versionDir);
// Validate symbolic link, and create it if it doesn't already exist
Utils.symlink(versionDir.getAbsolutePath(), storeDir.getAbsolutePath() + File.separator + "latest");
this.fileSet = new ChunkedFileSet(versionDir, routingStrategy, nodeId, maxValueBufferAllocationSize);
storeVersionManager.syncInternalStateFromFileSystem(false);
this.lastSwapped = System.currentTimeMillis();
this.isOpen = true;
} catch(IOException e) {
logger.error("Error in opening store", e);
} finally {
fileModificationLock.writeLock().unlock();
}
} | java |
@JmxGetter(name = "lastSwapped", description = "Time in milliseconds since the store was swapped")
public long getLastSwapped() {
long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;
return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;
} | java |
@Override
public void close() throws VoldemortException {
logger.debug("Close called for read-only store.");
this.fileModificationLock.writeLock().lock();
try {
if(isOpen) {
this.isOpen = false;
fileSet.close();
} else {
logger.debug("Attempt to close already closed store " + getName());
}
} finally {
this.fileModificationLock.writeLock().unlock();
}
} | java |
@JmxOperation(description = "swapFiles changes this store to use the new data directory")
public void swapFiles(String newStoreDirectory) {
logger.info("Swapping files for store '" + getName() + "' to " + newStoreDirectory);
File newVersionDir = new File(newStoreDirectory);
if(!newVersionDir.exists())
throw new VoldemortException("File " + newVersionDir.getAbsolutePath()
+ " does not exist.");
if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir)))
throw new VoldemortException("Invalid version folder name '"
+ newVersionDir
+ "'. Either parent directory is incorrect or format(version-n) is incorrect");
// retrieve previous version for (a) check if last write is winning
// (b) if failure, rollback use
File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir);
if(previousVersionDir == null)
throw new VoldemortException("Could not find any latest directory to swap with in store '"
+ getName() + "'");
long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir);
long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir);
if(newVersionId == -1 || previousVersionId == -1)
throw new VoldemortException("Unable to parse folder names (" + newVersionDir.getName()
+ "," + previousVersionDir.getName()
+ ") since format(version-n) is incorrect");
// check if we're greater than latest since we want last write to win
if(previousVersionId > newVersionId) {
logger.info("No swap required since current latest version " + previousVersionId
+ " is greater than swap version " + newVersionId);
deleteBackups();
return;
}
logger.info("Acquiring write lock on '" + getName() + "':");
fileModificationLock.writeLock().lock();
boolean success = false;
try {
close();
logger.info("Opening primary files for store '" + getName() + "' at "
+ newStoreDirectory);
// open the latest store
open(newVersionDir);
success = true;
} finally {
try {
// we failed to do the swap, attempt a rollback to last version
if(!success)
rollback(previousVersionDir);
} finally {
fileModificationLock.writeLock().unlock();
if(success)
logger.info("Swap operation completed successfully on store " + getName()
+ ", releasing lock.");
else
logger.error("Swap operation failed.");
}
}
// okay we have released the lock and the store is now open again, it is
// safe to do a potentially slow delete if we have one too many backups
deleteBackups();
} | java |
private void deleteBackups() {
File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());
if(storeDirList != null && storeDirList.length > (numBackups + 1)) {
// delete ALL old directories asynchronously
File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,
0,
storeDirList.length
- (numBackups + 1) - 1);
if(extraBackups != null) {
for(File backUpFile: extraBackups) {
deleteAsync(backUpFile);
}
}
}
} | java |
private void deleteAsync(final File file) {
new Thread(new Runnable() {
@Override
public void run() {
try {
try {
logger.info("Waiting for " + deleteBackupMs
+ " milliseconds before deleting " + file.getAbsolutePath());
Thread.sleep(deleteBackupMs);
} catch(InterruptedException e) {
logger.warn("Did not sleep enough before deleting backups");
}
logger.info("Deleting file " + file.getAbsolutePath());
Utils.rm(file);
logger.info("Deleting of " + file.getAbsolutePath()
+ " completed successfully.");
storeVersionManager.syncInternalStateFromFileSystem(true);
} catch(Exception e) {
logger.error("Exception during deleteAsync for path: " + file, e);
}
}
}, "background-file-delete").start();
} | java |
public void rollback(File rollbackToDir) {
logger.info("Rolling back store '" + getName() + "'");
fileModificationLock.writeLock().lock();
try {
if(rollbackToDir == null)
throw new VoldemortException("Version directory specified to rollback is null");
if(!rollbackToDir.exists())
throw new VoldemortException("Version directory " + rollbackToDir.getAbsolutePath()
+ " specified to rollback does not exist");
long versionId = ReadOnlyUtils.getVersionId(rollbackToDir);
if(versionId == -1)
throw new VoldemortException("Cannot parse version id");
File[] backUpDirs = ReadOnlyUtils.getVersionDirs(storeDir, versionId, Long.MAX_VALUE);
if(backUpDirs == null || backUpDirs.length <= 1) {
logger.warn("No rollback performed since there are no back-up directories");
return;
}
backUpDirs = ReadOnlyUtils.findKthVersionedDir(backUpDirs, 0, backUpDirs.length - 1);
if(isOpen)
close();
// open the rollback directory
open(rollbackToDir);
// back-up all other directories
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
for(int index = 1; index < backUpDirs.length; index++) {
Utils.move(backUpDirs[index], new File(storeDir, backUpDirs[index].getName() + "."
+ df.format(new Date()) + ".bak"));
}
} finally {
fileModificationLock.writeLock().unlock();
logger.info("Rollback operation completed on '" + getName() + "', releasing lock.");
}
} | java |
protected boolean hasTimeOutHeader() {
boolean result = false;
String timeoutValStr = this.request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS);
if(timeoutValStr != null) {
try {
this.parsedTimeoutInMs = Long.parseLong(timeoutValStr);
if(this.parsedTimeoutInMs < 0) {
RestErrorHandler.writeErrorResponse(messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Time out cannot be negative ");
} else {
result = true;
}
} catch(NumberFormatException nfe) {
logger.error("Exception when validating request. Incorrect timeout parameter. Cannot parse this to long: "
+ timeoutValStr,
nfe);
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Incorrect timeout parameter. Cannot parse this to long: "
+ timeoutValStr);
}
} else {
logger.error("Error when validating request. Missing timeout parameter.");
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Missing timeout parameter.");
}
return result;
} | java |
protected void parseRoutingCodeHeader() {
String rtCode = this.request.getHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE);
if(rtCode != null) {
try {
int routingTypeCode = Integer.parseInt(rtCode);
this.parsedRoutingType = RequestRoutingType.getRequestRoutingType(routingTypeCode);
} catch(NumberFormatException nfe) {
logger.error("Exception when validating request. Incorrect routing type parameter. Cannot parse this to long: "
+ rtCode,
nfe);
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Incorrect routing type parameter. Cannot parse this to long: "
+ rtCode);
} catch(VoldemortException ve) {
logger.error("Exception when validating request. Incorrect routing type code: "
+ rtCode, ve);
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Incorrect routing type code: " + rtCode);
}
}
} | java |
protected boolean hasTimeStampHeader() {
String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS);
boolean result = false;
if(originTime != null) {
try {
// TODO: remove the originTime field from request header,
// because coordinator should not accept the request origin time
// from the client.. In this commit, we only changed
// "this.parsedRequestOriginTimeInMs" from
// "Long.parseLong(originTime)" to current system time,
// The reason that we did not remove the field from request
// header right now, is because this commit is a quick fix for
// internal performance test to be available as soon as
// possible.
this.parsedRequestOriginTimeInMs = System.currentTimeMillis();
if(this.parsedRequestOriginTimeInMs < 0) {
RestErrorHandler.writeErrorResponse(messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Origin time cannot be negative ");
} else {
result = true;
}
} catch(NumberFormatException nfe) {
logger.error("Exception when validating request. Incorrect origin time parameter. Cannot parse this to long: "
+ originTime,
nfe);
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Incorrect origin time parameter. Cannot parse this to long: "
+ originTime);
}
} else {
logger.error("Error when validating request. Missing origin time parameter.");
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Missing origin time parameter.");
}
return result;
} | java |
protected boolean hasVectorClock(boolean isVectorClockOptional) {
boolean result = false;
String vectorClockHeader = this.request.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK);
if(vectorClockHeader != null) {
ObjectMapper mapper = new ObjectMapper();
try {
VectorClockWrapper vcWrapper = mapper.readValue(vectorClockHeader,
VectorClockWrapper.class);
this.parsedVectorClock = new VectorClock(vcWrapper.getVersions(),
vcWrapper.getTimestamp());
result = true;
} catch(Exception e) {
logger.error("Exception while parsing and constructing vector clock", e);
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Invalid Vector Clock");
}
} else if(!isVectorClockOptional) {
logger.error("Error when validating request. Missing Vector Clock");
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Missing Vector Clock");
} else {
result = true;
}
return result;
} | java |
protected boolean hasKey() {
boolean result = false;
String requestURI = this.request.getUri();
parseKeys(requestURI);
if(this.parsedKeys != null) {
result = true;
} else {
logger.error("Error when validating request. No key specified.");
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Error: No key specified !");
}
return result;
} | java |
protected boolean isStoreValid() {
boolean result = false;
String requestURI = this.request.getUri();
this.storeName = parseStoreName(requestURI);
if(storeName != null) {
result = true;
} else {
logger.error("Error when validating request. Missing store name.");
RestErrorHandler.writeErrorResponse(this.messageEvent,
HttpResponseStatus.BAD_REQUEST,
"Missing store name. Critical error.");
}
return result;
} | java |
protected void debugLog(String operationType, Long receivedTimeInMs) {
long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs);
int numVectorClockEntries = (this.parsedVectorClock == null ? 0
: this.parsedVectorClock.getVersionMap()
.size());
logger.debug("Received a new request. Operation type: " + operationType + " , Key(s): "
+ keysHexString(this.parsedKeys) + " , Store: " + this.storeName
+ " , Origin time (in ms): " + (this.parsedRequestOriginTimeInMs)
+ " , Request received at time(in ms): " + receivedTimeInMs
+ " , Num vector clock entries: " + numVectorClockEntries
+ " , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): "
+ durationInMs);
} | java |
@Deprecated
@Override
public File fetch(String source, String dest, long diskQuotaSizeInKB) throws Exception {
return fetchFromSource(source, dest, null, null, -1, diskQuotaSizeInKB, null);
} | java |
public static void main(String[] args) throws Exception {
if(args.length < 1)
Utils.croak("USAGE: java " + HdfsFetcher.class.getName()
+ " url [keytab-location kerberos-username hadoop-config-path [destDir]]");
String url = args[0];
VoldemortConfig config = new VoldemortConfig(-1, "");
HdfsFetcher fetcher = new HdfsFetcher(config);
String destDir = null;
Long diskQuotaSizeInKB;
if(args.length >= 4) {
fetcher.voldemortConfig.setReadOnlyKeytabPath(args[1]);
fetcher.voldemortConfig.setReadOnlyKerberosUser(args[2]);
fetcher.voldemortConfig.setHadoopConfigPath(args[3]);
}
if(args.length >= 5)
destDir = args[4];
if(args.length >= 6)
diskQuotaSizeInKB = Long.parseLong(args[5]);
else
diskQuotaSizeInKB = null;
// for testing we want to be able to download a single file
allowFetchingOfSingleFile = true;
FileSystem fs = HadoopUtils.getHadoopFileSystem(fetcher.voldemortConfig, url);
Path p = new Path(url);
FileStatus status = fs.listStatus(p)[0];
long size = status.getLen();
long start = System.currentTimeMillis();
if(destDir == null)
destDir = System.getProperty("java.io.tmpdir") + File.separator + start;
File location = fetcher.fetch(url, destDir, null, null, -1, null, diskQuotaSizeInKB);
double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start);
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
System.out.println("Fetch to " + location + " completed: "
+ nf.format(rate / (1024.0 * 1024.0)) + " MB/sec.");
fs.close();
} | java |
public synchronized int getPartitionStoreMoves() {
int count = 0;
for (List<Integer> entry : storeToPartitionIds.values())
count += entry.size();
return count;
} | java |
public synchronized int getPartitionStoreCount() {
int count = 0;
for (String store : storeToPartitionIds.keySet()) {
count += storeToPartitionIds.get(store).size();
}
return count;
} | java |
public static String taskListToString(List<RebalanceTaskInfo> infos) {
StringBuffer sb = new StringBuffer();
for (RebalanceTaskInfo info : infos) {
sb.append("\t").append(info.getDonorId()).append(" -> ").append(info.getStealerId()).append(" : [");
for (String storeName : info.getPartitionStores()) {
sb.append("{").append(storeName).append(" : ").append(info.getPartitionIds(storeName)).append("}");
}
sb.append("]").append(Utils.NEWLINE);
}
return sb.toString();
} | java |
@Override
public void map(GenericData.Record record,
AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector,
Reporter reporter) throws IOException {
byte[] keyBytes = null;
byte[] valBytes = null;
Object keyRecord = null;
Object valRecord = null;
try {
keyRecord = record.get(keyField);
valRecord = record.get(valField);
keyBytes = keySerializer.toBytes(keyRecord);
valBytes = valueSerializer.toBytes(valRecord);
this.collectorWrapper.setCollector(collector);
this.mapper.map(keyBytes, valBytes, this.collectorWrapper);
recordCounter++;
} catch (OutOfMemoryError oom) {
logger.error(oomErrorMessage(reporter));
if (keyBytes == null) {
logger.error("keyRecord caused OOM!");
} else {
logger.error("keyRecord: " + keyRecord);
logger.error("valRecord: " + (valBytes == null ? "caused OOM" : valRecord));
}
throw new VoldemortException(oomErrorMessage(reporter), oom);
}
} | java |
public static Pointer mmap(long len, int prot, int flags, int fildes, long off)
throws IOException {
// we don't really have a need to change the recommended pointer.
Pointer addr = new Pointer(0);
Pointer result = Delegate.mmap(addr,
new NativeLong(len),
prot,
flags,
fildes,
new NativeLong(off));
if(Pointer.nativeValue(result) == -1) {
if(logger.isDebugEnabled())
logger.debug(errno.strerror());
throw new IOException("mmap failed: " + errno.strerror());
}
return result;
} | java |
public static void mlock(Pointer addr, long len) {
int res = Delegate.mlock(addr, new NativeLong(len));
if(res != 0) {
if(logger.isDebugEnabled()) {
logger.debug("Mlock failed probably because of insufficient privileges, errno:"
+ errno.strerror() + ", return value:" + res);
}
} else {
if(logger.isDebugEnabled())
logger.debug("Mlock successfull");
}
} | java |
public static void munlock(Pointer addr, long len) {
if(Delegate.munlock(addr, new NativeLong(len)) != 0) {
if(logger.isDebugEnabled())
logger.debug("munlocking failed with errno:" + errno.strerror());
} else {
if(logger.isDebugEnabled())
logger.debug("munlocking region");
}
} | java |
public JsonTypeDefinition projectionType(String... properties) {
if(this.getType() instanceof Map<?, ?>) {
Map<?, ?> type = (Map<?, ?>) getType();
Arrays.sort(properties);
Map<String, Object> newType = new LinkedHashMap<String, Object>();
for(String prop: properties)
newType.put(prop, type.get(prop));
return new JsonTypeDefinition(newType);
} else {
throw new IllegalArgumentException("Cannot take the projection of a type that is not a Map.");
}
} | java |
private void writeBufferedValsToStorage() {
List<Versioned<byte[]>> obsoleteVals = storageEngine.multiVersionPut(currBufferedKey,
currBufferedVals);
// log Obsolete versions in debug mode
if(logger.isDebugEnabled() && obsoleteVals.size() > 0) {
logger.debug("updateEntries (Streaming multi-version-put) rejected these versions as obsolete : "
+ StoreUtils.getVersions(obsoleteVals) + " for key " + currBufferedKey);
}
currBufferedVals = new ArrayList<Versioned<byte[]>>(VALS_BUFFER_EXPECTED_SIZE);
} | java |
public synchronized boolean acquireRebalancingPermit(int nodeId) {
boolean added = rebalancePermits.add(nodeId);
logger.info("Acquiring rebalancing permit for node id " + nodeId + ", returned: " + added);
return added;
} | java |
public synchronized void releaseRebalancingPermit(int nodeId) {
boolean removed = rebalancePermits.remove(nodeId);
logger.info("Releasing rebalancing permit for node id " + nodeId + ", returned: " + removed);
if(!removed)
throw new VoldemortException(new IllegalStateException("Invalid state, must hold a "
+ "permit to release"));
} | java |
private void swapROStores(List<String> swappedStoreNames, boolean useSwappedStoreNames) {
try {
for(StoreDefinition storeDef: metadataStore.getStoreDefList()) {
// Only pick up the RO stores
if(storeDef.getType().compareTo(ReadOnlyStorageConfiguration.TYPE_NAME) == 0) {
if(useSwappedStoreNames && !swappedStoreNames.contains(storeDef.getName())) {
continue;
}
ReadOnlyStorageEngine engine = (ReadOnlyStorageEngine) storeRepository.getStorageEngine(storeDef.getName());
if(engine == null) {
throw new VoldemortException("Could not find storage engine for "
+ storeDef.getName() + " to swap ");
}
logger.info("Swapping RO store " + storeDef.getName());
// Time to swap this store - Could have used admin client,
// but why incur the overhead?
engine.swapFiles(engine.getCurrentDirPath());
// Add to list of stores already swapped
if(!useSwappedStoreNames)
swappedStoreNames.add(storeDef.getName());
}
}
} catch(Exception e) {
logger.error("Error while swapping RO store");
throw new VoldemortException(e);
}
} | java |
private void changeClusterAndStores(String clusterKey,
final Cluster cluster,
String storesKey,
final List<StoreDefinition> storeDefs) {
metadataStore.writeLock.lock();
try {
VectorClock updatedVectorClock = ((VectorClock) metadataStore.get(clusterKey, null)
.get(0)
.getVersion()).incremented(metadataStore.getNodeId(),
System.currentTimeMillis());
metadataStore.put(clusterKey, Versioned.value((Object) cluster, updatedVectorClock));
// now put new stores
updatedVectorClock = ((VectorClock) metadataStore.get(storesKey, null)
.get(0)
.getVersion()).incremented(metadataStore.getNodeId(),
System.currentTimeMillis());
metadataStore.put(storesKey, Versioned.value((Object) storeDefs, updatedVectorClock));
} catch(Exception e) {
logger.info("Error while changing cluster to " + cluster + "for key " + clusterKey);
throw new VoldemortException(e);
} finally {
metadataStore.writeLock.unlock();
}
} | java |
public int rebalanceNode(final RebalanceTaskInfo stealInfo) {
final RebalanceTaskInfo info = metadataStore.getRebalancerState()
.find(stealInfo.getDonorId());
// Do we have the plan in the state?
if(info == null) {
throw new VoldemortException("Could not find plan " + stealInfo
+ " in the server state on " + metadataStore.getNodeId());
} else if(!info.equals(stealInfo)) {
// If we do have the plan, is it the same
throw new VoldemortException("The plan in server state " + info
+ " is not the same as the process passed " + stealInfo);
} else if(!acquireRebalancingPermit(stealInfo.getDonorId())) {
// Both are same, now try to acquire a lock for the donor node
throw new AlreadyRebalancingException("Node " + metadataStore.getNodeId()
+ " is already rebalancing from donor "
+ info.getDonorId() + " with info " + info);
}
// Acquired lock successfully, start rebalancing...
int requestId = asyncService.getUniqueRequestId();
// Why do we pass 'info' instead of 'stealInfo'? So that we can change
// the state as the stores finish rebalance
asyncService.submitOperation(requestId,
new StealerBasedRebalanceAsyncOperation(this,
voldemortConfig,
metadataStore,
requestId,
info));
return requestId;
} | java |
protected void prepForWrite(SelectionKey selectionKey) {
if(logger.isTraceEnabled())
traceInputBufferState("About to clear read buffer");
if(requestHandlerFactory.shareReadWriteBuffer() == false) {
inputStream.clear();
}
if(logger.isTraceEnabled())
traceInputBufferState("Cleared read buffer");
outputStream.getBuffer().flip();
selectionKey.interestOps(SelectionKey.OP_WRITE);
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.