idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
147,900
private void init ( ) { logger . info ( "metadata init()." ) ; writeLock . lock ( ) ; try { initCache ( CLUSTER_KEY ) ; if ( this . storeDefinitionsStorageEngine != null ) { initStoreDefinitions ( null ) ; } else { initCache ( STORES_KEY ) ; } initSystemCache ( ) ; initSystemRoutingStrategies ( getCluster ( ) ) ; initC...
Initializes the metadataCache for MetadataStore
147,901
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 ) { finalS...
Function to go through all the store definitions contained in the STORES directory and
147,902
private void resetStoreDefinitions ( Set < String > storeNamesToDelete ) { for ( String storeName : storeNamesToDelete ) { this . metadataCache . remove ( storeName ) ; this . storeDefinitionsStorageEngine . delete ( storeName , null ) ; this . storeNames . remove ( storeName ) ; } }
Function to clear all the metadata related to the given store definitions . This is needed when a put on stores . xml is called thus replacing the existing state .
147,903
private synchronized void initSystemCache ( ) { List < StoreDefinition > value = storeMapper . readStoreList ( new StringReader ( SystemStoreConstants . SYSTEM_STORE_SCHEMA ) ) ; metadataCache . put ( SYSTEM_STORES_KEY , new Versioned < Object > ( value ) ) ; }
Initialize the metadata cache with system store list
147,904
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 ( ) ; ...
Performs a get operation with the specified composite request object
147,905
public Version putWithCustomTimeout ( CompositeVoldemortRequest < K , V > requestWrapper ) { validateTimeout ( requestWrapper . getRoutingTimeoutInMs ( ) ) ; List < Versioned < V > > versionedValues ; long startTime = System . currentTimeMillis ( ) ; String keyHexString = "" ; if ( logger . isDebugEnabled ( ) ) { ByteA...
Performs a put operation with the specified composite request object
147,906
public Version putVersionedWithCustomTimeout ( CompositeVoldemortRequest < K , V > requestWrapper ) throws ObsoleteVersionException { validateTimeout ( requestWrapper . getRoutingTimeoutInMs ( ) ) ; for ( int attempts = 0 ; attempts < this . metadataRefreshAttempts ; attempts ++ ) { try { String keyHexString = "" ; lon...
Performs a Versioned put operation with the specified composite request object
147,907
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 . metadataRef...
Performs a get all operation with the specified composite request object
147,908
public boolean deleteWithCustomTimeout ( CompositeVoldemortRequest < K , V > deleteRequestObject ) { List < Versioned < V > > versionedValues ; validateTimeout ( deleteRequestObject . getRoutingTimeoutInMs ( ) ) ; boolean hasVersion = deleteRequestObject . getVersion ( ) == null ? false : true ; String keyHexString = "...
Performs a delete operation with the specified composite request object
147,909
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 . sto...
Traces the duration between origin time in the http Request and time just before being processed by the fat client
147,910
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 Opera...
Traces the time taken just by the fat client inside Coordinator to process this request
147,911
public static Node updateNode ( Node node , List < Integer > partitionsList ) { return new Node ( node . getId ( ) , node . getHost ( ) , node . getHttpPort ( ) , node . getSocketPort ( ) , node . getAdminPort ( ) , node . getZoneId ( ) , partitionsList ) ; }
Creates a replica of the node with the new partitions list
147,912
public static Node addPartitionToNode ( final Node node , Integer donatedPartition ) { return UpdateClusterUtils . addPartitionsToNode ( node , Sets . newHashSet ( donatedPartition ) ) ; }
Add a partition to the node provided
147,913
public static Node removePartitionFromNode ( final Node node , Integer donatedPartition ) { return UpdateClusterUtils . removePartitionsFromNode ( node , Sets . newHashSet ( donatedPartition ) ) ; }
Remove a partition from the node provided
147,914
public static Node addPartitionsToNode ( final Node node , final Set < Integer > donatedPartitions ) { List < Integer > deepCopy = new ArrayList < Integer > ( node . getPartitionIds ( ) ) ; deepCopy . addAll ( donatedPartitions ) ; Collections . sort ( deepCopy ) ; return updateNode ( node , deepCopy ) ; }
Add the set of partitions to the node provided
147,915
public static Node removePartitionsFromNode ( final Node node , final Set < Integer > donatedPartitions ) { List < Integer > deepCopy = new ArrayList < Integer > ( node . getPartitionIds ( ) ) ; deepCopy . removeAll ( donatedPartitions ) ; return updateNode ( node , deepCopy ) ; }
Remove the set of partitions from the node provided
147,916
public static Cluster createUpdatedCluster ( Cluster currentCluster , int stealerNodeId , List < Integer > donatedPartitions ) { Cluster updatedCluster = Cluster . cloneCluster ( currentCluster ) ; for ( int donatedPartition : donatedPartitions ) { Node donorNode = updatedCluster . getNodeForPartitionId ( donatedPartit...
Updates the existing cluster such that we remove partitions mentioned from the stealer node and add them to the donor node
147,917
public static void main ( String [ ] args ) { DirectoryIterator iter = new DirectoryIterator ( args ) ; while ( iter . hasNext ( ) ) System . out . println ( iter . next ( ) . getAbsolutePath ( ) ) ; }
Command line method to walk the directories provided on the command line and print out their contents
147,918
private void verifyClusterStoreDefinition ( ) { if ( SystemStoreConstants . isSystemStore ( storeDefinition . getName ( ) ) ) { return ; } Set < Integer > clusterZoneIds = cluster . getZoneIds ( ) ; if ( clusterZoneIds . size ( ) > 1 ) { Map < Integer , Integer > zoneRepFactor = storeDefinition . getZoneReplicationFact...
Verify that cluster is congruent to store def wrt zones .
147,919
public Integer getNodesPartitionIdForKey ( int nodeId , final byte [ ] key ) { List < Integer > partitionIds = getReplicatingPartitionList ( key ) ; for ( Integer partitionId : partitionIds ) { if ( getNodeIdForPartitionId ( partitionId ) == nodeId ) { return partitionId ; } } return null ; }
Determines the partition ID that replicates the key on the given node .
147,920
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 . con...
Converts from partitionId to nodeId . The list of partition IDs partitionIds is expected to be a replicating partition list i . e . the mapping from partition ID to node ID should be one to one .
147,921
public boolean checkKeyBelongsToNode ( byte [ ] key , int nodeId ) { List < Integer > nodePartitions = cluster . getNodeById ( nodeId ) . getPartitionIds ( ) ; List < Integer > replicatingPartitions = getReplicatingPartitionList ( key ) ; replicatingPartitions . retainAll ( nodePartitions ) ; return replicatingPartitio...
Determines if the key replicates to the given node
147,922
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 , cl...
Given a key and a list of steal infos give back a list of stealer node ids which will steal this .
147,923
public synchronized void maybeThrottle ( int eventsSeen ) { if ( maxRatePerSecond > 0 ) { long now = time . milliseconds ( ) ; try { rateSensor . record ( eventsSeen , now ) ; } catch ( QuotaViolationException e ) { double currentRate = e . getValue ( ) ; if ( currentRate > this . maxRatePerSecond ) { double excessRate...
Sleeps if necessary to slow down the caller .
147,924
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 ) { Li...
Compute the repair set from the given values and nodes
147,925
public static List < Versioned < byte [ ] > > resolveVersions ( List < Versioned < byte [ ] > > values ) { List < Versioned < byte [ ] > > resolvedVersions = new ArrayList < Versioned < byte [ ] > > ( values . size ( ) ) ; for ( Versioned < byte [ ] > value : values ) { Iterator < Versioned < byte [ ] > > iter = resolv...
Given a set of versions constructs a resolved list of versions based on the compare function above
147,926
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 ) ) ; } re...
Generates a vector clock with the provided values
147,927
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 ...
Given a read - only store name and a directory swaps it in while returning the directory path being swapped out
147,928
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 posit...
This method is used by non - blocking code to determine if the give buffer represents a complete request . Because the non - blocking code can by definition not just block waiting for more data it s possible to get partial reads and this identifies that case .
147,929
public synchronized void unregisterJmxIfRequired ( ) { referenceCount -- ; if ( isRegistered == true && referenceCount <= 0 ) { JmxUtils . unregisterMbean ( this . jmxObjectName ) ; isRegistered = false ; } }
Last caller of this method will unregister the Mbean . All callers decrement the counter .
147,930
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 ...
Translate the given byte array into a string of 1s and 0s
147,931
public static byte [ ] copy ( byte [ ] array , int from , int to ) { if ( to - from < 0 ) { return new byte [ 0 ] ; } else { byte [ ] a = new byte [ to - from ] ; System . arraycopy ( array , from , a , 0 , to - from ) ; return a ; } }
Copy the specified bytes into a new array
147,932
public static int readInt ( byte [ ] bytes , int offset ) { return ( ( ( bytes [ offset + 0 ] & 0xff ) << 24 ) | ( ( bytes [ offset + 1 ] & 0xff ) << 16 ) | ( ( bytes [ offset + 2 ] & 0xff ) << 8 ) | ( bytes [ offset + 3 ] & 0xff ) ) ; }
Read an int from the byte array starting at the given offset
147,933
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 ) ) ; }
Read an unsigned integer from the given byte array
147,934
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 ; }
Read the given number of bytes into a long
147,935
public static void writeShort ( byte [ ] bytes , short value , int offset ) { bytes [ offset ] = ( byte ) ( 0xFF & ( value >> 8 ) ) ; bytes [ offset + 1 ] = ( byte ) ( 0xFF & value ) ; }
Write a short to the byte array starting at the given offset
147,936
public static void writeUnsignedShort ( byte [ ] bytes , int value , int offset ) { bytes [ offset ] = ( byte ) ( 0xFF & ( value >> 8 ) ) ; bytes [ offset + 1 ] = ( byte ) ( 0xFF & value ) ; }
Write an unsigned short to the byte array starting at the given offset
147,937
public static void writeInt ( byte [ ] bytes , int value , int offset ) { bytes [ offset ] = ( byte ) ( 0xFF & ( value >> 24 ) ) ; bytes [ offset + 1 ] = ( byte ) ( 0xFF & ( value >> 16 ) ) ; bytes [ offset + 2 ] = ( byte ) ( 0xFF & ( value >> 8 ) ) ; bytes [ offset + 3 ] = ( byte ) ( 0xFF & value ) ; }
Write an int to the byte array starting at the given offset
147,938
public static void writeBytes ( byte [ ] bytes , long value , int offset , int numBytes ) { int shift = 0 ; for ( int i = offset + numBytes - 1 ; i >= offset ; i -- ) { bytes [ i ] = ( byte ) ( 0xFF & ( value >> shift ) ) ; shift += 8 ; } }
Write the given number of bytes out to the array
147,939
public static byte numberOfBytesRequired ( long number ) { if ( number < 0 ) number = - number ; for ( byte i = 1 ; i <= SIZE_OF_LONG ; i ++ ) if ( number < ( 1L << ( 8 * i ) ) ) return i ; throw new IllegalStateException ( "Should never happen." ) ; }
The number of bytes required to hold the given number
147,940
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...
Read exactly buffer . length bytes from the stream into the buffer
147,941
public static byte [ ] getBytes ( String string , String encoding ) { try { return string . getBytes ( encoding ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalArgumentException ( encoding + " is not a known encoding name." , e ) ; } }
Translate the string to bytes using the given encoding
147,942
public static String getString ( byte [ ] bytes , String encoding ) { try { return new String ( bytes , encoding ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalArgumentException ( encoding + " is not a known encoding name." , e ) ; } }
Create a string from bytes using the given encoding
147,943
public void addRequest ( long timeNS , long numEmptyResponses , long valueBytes , long keyBytes , long getAllAggregatedCount ) { long startTimeNs = 0 ; if ( logger . isTraceEnabled ( ) ) { startTimeNs = System . nanoTime ( ) ; } long currentTime = time . milliseconds ( ) ; timeSensor . record ( ( double ) timeNS / vold...
Detailed request to track additional data about PUT GET and GET_ALL
147,944
public void addEvent ( Event event ) { if ( event == null ) throw new IllegalStateException ( "event must be non-null" ) ; if ( logger . isTraceEnabled ( ) ) logger . trace ( "Adding event " + event ) ; eventQueue . add ( event ) ; }
Add an event to the queue . It will be processed in the order received .
147,945
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 VoldemortEx...
Process events in the order as they were received .
147,946
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 (...
Create a model mbean from an object using the description given in the Jmx annotation if present . Only operations are supported so far no attributes constructors or notifications
147,947
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 ...
Extract all operations and attributes from the given object that have been annotated with the Jmx annotation . Operations are all methods that are marked with the JmxOperation annotation .
147,948
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 ++ ) { boo...
Extract the parameters from a method using the Jmx annotation if present or just the raw types otherwise
147,949
public static ObjectName createObjectName ( String domain , String type ) { try { return new ObjectName ( domain + ":type=" + type ) ; } catch ( MalformedObjectNameException e ) { throw new VoldemortException ( e ) ; } }
Create a JMX ObjectName
147,950
public static String getClassName ( Class < ? > c ) { String name = c . getName ( ) ; return name . substring ( name . lastIndexOf ( '.' ) + 1 , name . length ( ) ) ; }
Get the class name without the package
147,951
public static void registerMbean ( Object mbean , ObjectName name ) { registerMbean ( ManagementFactory . getPlatformMBeanServer ( ) , JmxUtils . createModelMBean ( mbean ) , name ) ; }
Register the given mbean with the platform mbean server
147,952
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 ) , n...
Register the given object under the package name of the object s class with the given type name .
147,953
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 mbea...
Register the given mbean with the server
147,954
public static void unregisterMbean ( MBeanServer server , ObjectName name ) { try { server . unregisterMBean ( name ) ; } catch ( Exception e ) { logger . error ( "Error unregistering mbean" , e ) ; } }
Unregister the mbean with the given name
147,955
public static void unregisterMbean ( ObjectName name ) { try { ManagementFactory . getPlatformMBeanServer ( ) . unregisterMBean ( name ) ; } catch ( Exception e ) { logger . error ( "Error unregistering mbean" , e ) ; } }
Unregister the mbean with the given name from the platform mbean server
147,956
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]+...
Given a file name and read - only storage format tells whether the file name format is correct
147,957
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...
Returns the chunk id for the file name
147,958
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 findKthVersione...
Retrieve the dir pointed to by latest symbolic - link or the current version dir
147,959
public static boolean checkVersionDirName ( File versionDir ) { return ( versionDir . isDirectory ( ) && versionDir . getName ( ) . contains ( "version-" ) && ! versionDir . getName ( ) . endsWith ( ".bak" ) ) ; }
Checks if the name of the file follows the version - n format
147,960
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 ; } }
Extracts the version id from a string
147,961
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 &&...
Returns all the version directories present in the root directory specified
147,962
protected void stopInner ( ) throws VoldemortException { List < VoldemortException > exceptions = new ArrayList < VoldemortException > ( ) ; logger . info ( "Stopping services:" + getIdentityNode ( ) . getId ( ) ) ; exceptions . addAll ( stopOnlineServices ( ) ) ; for ( VoldemortService service : Utils . reversed ( bas...
Attempt to shutdown the server . As much shutdown as possible will be completed even if intermediate errors are encountered .
147,963
private int getReplicaTypeForPartition ( int partitionId ) { List < Integer > routingPartitionList = routingStrategy . getReplicatingPartitionList ( partitionId ) ; int correctReplicaType = - 1 ; for ( int replica = 0 ; replica < routingPartitionList . size ( ) ; replica ++ ) { if ( nodePartitionIds . contains ( routin...
Given a partition ID determine which replica of this partition is hosted by the current node if any .
147,964
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 ) + "_" + Int...
This function looks for files with the wrong replica type in their name and if it finds any renames them .
147,965
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 ( "Unkn...
Converts the key to the format in which it is stored for searching
147,966
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 ( nod...
Given a particular key first converts its to the storage format and then determines which chunk it belongs to
147,967
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 ( partitionIdRep...
This method take a list of fileName of the type partitionId_Replica_Chunk and returns file names that match the regular expression masterPartitionId_
147,968
@ 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 ( ...
Returns a string representation of map of chunk id to number of chunks
147,969
public void open ( File versionDir ) { fileModificationLock . writeLock ( ) . lock ( ) ; try { if ( isOpen ) throw new IllegalStateException ( "Attempt to open already open store." ) ; if ( versionDir == null ) { versionDir = ReadOnlyUtils . getCurrentVersion ( storeDir ) ; if ( versionDir == null ) versionDir = new Fi...
Open the store with the version directory specified . If null is specified we open the directory with the maximum version
147,970
@ 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 ; }
Time since last time the store was swapped
147,971
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 ( ) ) ; } }...
Close the store .
147,972
@ 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 . exi...
Swap the current version folder for a new one
147,973
private void deleteBackups ( ) { File [ ] storeDirList = ReadOnlyUtils . getVersionDirs ( storeDir , 0L , getCurrentVersionId ( ) ) ; if ( storeDirList != null && storeDirList . length > ( numBackups + 1 ) ) { File [ ] extraBackups = ReadOnlyUtils . findKthVersionedDir ( storeDirList , 0 , storeDirList . length - ( num...
Delete all backups asynchronously
147,974
private void deleteAsync ( final File file ) { new Thread ( new Runnable ( ) { public void run ( ) { try { try { logger . info ( "Waiting for " + deleteBackupMs + " milliseconds before deleting " + file . getAbsolutePath ( ) ) ; Thread . sleep ( deleteBackupMs ) ; } catch ( InterruptedException e ) { logger . warn ( "D...
Delete the given file in a separate thread
147,975
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...
Rollback to the specified push version
147,976
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 ) { RestErrorHan...
Retrieve and validate the timeout value from the REST request . X_VOLD_REQUEST_TIMEOUT_MS is the timeout header .
147,977
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 ) ; } cat...
Retrieve the routing type value from the REST request . X_VOLD_ROUTING_TYPE_CODE is the routing type header .
147,978
protected boolean hasTimeStampHeader ( ) { String originTime = request . getHeader ( RestMessageHeaders . X_VOLD_REQUEST_ORIGIN_TIME_MS ) ; boolean result = false ; if ( originTime != null ) { try { this . parsedRequestOriginTimeInMs = System . currentTimeMillis ( ) ; if ( this . parsedRequestOriginTimeInMs < 0 ) { Res...
Retrieve and validate the timestamp value from the REST request . X_VOLD_REQUEST_ORIGIN_TIME_MS is timestamp header
147,979
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 ....
Retrieve and validate vector clock value from the REST request . X_VOLD_VECTOR_CLOCK is the vector clock header .
147,980
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 . messageE...
Retrieve and validate the key from the REST request .
147,981
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 . writeErrorRe...
Retrieve and validate store name from the REST request .
147,982
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 req...
Prints a debug log message that details the time taken for the Http request to be parsed by the coordinator
147,983
public File fetch ( String source , String dest , long diskQuotaSizeInKB ) throws Exception { return fetchFromSource ( source , dest , null , null , - 1 , diskQuotaSizeInKB , null ) ; }
Used for unit tests only .
147,984
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 , "" ) ; H...
Main method for testing fetching
147,985
public synchronized int getPartitionStoreMoves ( ) { int count = 0 ; for ( List < Integer > entry : storeToPartitionIds . values ( ) ) count += entry . size ( ) ; return count ; }
Total count of partition - stores moved in this task .
147,986
public synchronized int getPartitionStoreCount ( ) { int count = 0 ; for ( String store : storeToPartitionIds . keySet ( ) ) { count += storeToPartitionIds . get ( store ) . size ( ) ; } return count ; }
Returns the total count of partitions across all stores .
147,987
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 : i...
Pretty prints a task list of rebalancing tasks .
147,988
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 = reco...
Create the voldemort key and value from the input Avro record by extracting the key and value and map it out for each of the responsible voldemort nodes
147,989
public static Pointer mmap ( long len , int prot , int flags , int fildes , long off ) throws IOException { 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 ( logge...
Map the given region of the given file descriptor into memory . Returns a Pointer to the newly mapped memory throws an IOException on error .
147,990
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 {...
Lock the given region . Does not report failures .
147,991
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" ) ; ...
Unlock the given region . Does not report failures .
147,992
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 ) new...
Get the type created by selecting only a subset of properties from this type . The type must be a map for this to work
147,993
private void writeBufferedValsToStorage ( ) { List < Versioned < byte [ ] > > obsoleteVals = storageEngine . multiVersionPut ( currBufferedKey , currBufferedVals ) ; if ( logger . isDebugEnabled ( ) && obsoleteVals . size ( ) > 0 ) { logger . debug ( "updateEntries (Streaming multi-version-put) rejected these versions ...
Persists the current set of versions buffered for the current key into storage using the multiVersionPut api
147,994
public synchronized boolean acquireRebalancingPermit ( int nodeId ) { boolean added = rebalancePermits . add ( nodeId ) ; logger . info ( "Acquiring rebalancing permit for node id " + nodeId + ", returned: " + added ) ; return added ; }
Acquire a permit for a particular node id so as to allow rebalancing
147,995
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...
Release the rebalancing permit for a particular node id
147,996
private void swapROStores ( List < String > swappedStoreNames , boolean useSwappedStoreNames ) { try { for ( StoreDefinition storeDef : metadataStore . getStoreDefList ( ) ) { if ( storeDef . getType ( ) . compareTo ( ReadOnlyStorageConfiguration . TYPE_NAME ) == 0 ) { if ( useSwappedStoreNames && ! swappedStoreNames ....
Goes through all the RO Stores in the plan and swaps it
147,997
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 ( ) ) . inc...
Updates the cluster and store metadata atomically
147,998
public int rebalanceNode ( final RebalanceTaskInfo stealInfo ) { final RebalanceTaskInfo info = metadataStore . getRebalancerState ( ) . find ( stealInfo . getDonorId ( ) ) ; if ( info == null ) { throw new VoldemortException ( "Could not find plan " + stealInfo + " in the server state on " + metadataStore . getNodeId ...
This function is responsible for starting the actual async rebalance operation . This is run if this node is the stealer node
147,999
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 ...
Flips the output buffer and lets the Selector know we re ready to write .