Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package persistance
- import (
- "encoding/binary"
- "fmt"
- "hydra-dht/constants"
- pb "hydra-dht/protobuf/node"
- "hydra-dht/structures"
- "os"
- "github.com/golang/protobuf/proto"
- )
- var (
- logFile *os.File
- filePosition int64
- )
- /*
- ReadLatestObjectFromLog reads and sends the latest / last log Object inside
- the log file.
- Arguments:
- None
- Returns:
- 1. logNode = The Log node object retrieved from the log file. It will be empty
- if there is an error
- 2. error = Error object. Will be nil if no error.
- */
- func ReadLatestObjectFromLog() (*pb.LogNode, error) {
- logFile.Seek(filePosition, 0)
- sizeOfLogObjectBuffer := make([]byte, constants.LOG_OBJECT_BYTE_SIZE)
- logFile.Read(sizeOfLogObjectBuffer)
- filePosition += constants.LOG_OBJECT_BYTE_SIZE
- sizeOfLogObject, _ := binary.Uvarint(sizeOfLogObjectBuffer)
- filePosition += int64(sizeOfLogObject)
- logObjectBuffer := make([]byte, sizeOfLogObject)
- logFile.Read(logObjectBuffer)
- logObject := &pb.LogNode{}
- err := proto.Unmarshal(logObjectBuffer, logObject)
- return logObject, err
- }
- /*
- addToDHT is a helper function to the LoadDHT function. It adds the value to the
- DHT. If required it appends the value to list, else it inserts the value at the
- said position.
- Arguments:
- 1. dht - The DHT in which value is added
- 2. logObject - The object which contains value to be added, along with dhtIndex
- (the bucket in which the value is to be inserted) and bucket list index in
- which the value is to inserted.
- Please check proto Log Object defination to know more about the LogNode variable.
- */
- func addToDHT(dht *structures.DHT, logObject *pb.LogNode) {
- row := logObject.DhtIndex
- col := logObject.ListIndex
- var nodeID structures.NodeID
- copy(nodeID[:], logObject.Node.NodeId)
- n := &structures.Node{
- Key: nodeID,
- Port: int(logObject.Node.Port),
- Domain: logObject.Node.Domain,
- }
- if len(dht.Lists[row]) < int(col+1) {
- dht.Lists[row] = append(dht.Lists[row], *n)
- fmt.Println(dht.Lists[row])
- } else {
- dht.Lists[row][col] = *n
- }
- }
- /*
- LoadDHT loads the DHT by replaying the tra nsaction Log entirely.
- It performs all the operations on the DHT that have occurred in the past, hence
- getting DHT to the same state as before the crash/shut down
- Arguments: None
- Returns:
- 1. DHT - Returns the DHDT loaded from log, empty if error occurs.
- 2. error - Non nil value if some error occured in between the program.
- */
- func LoadDHT() (*structures.DHT, error) {
- var dht structures.DHT
- fi, err := logFile.Stat()
- filePosition = 0
- for {
- if filePosition >= fi.Size() {
- break
- }
- logObject, err := ReadLatestObjectFromLog()
- if err != nil {
- return &dht, err
- }
- addToDHT(&dht, logObject)
- }
- return &dht, err
- }
Add Comment
Please, Sign In to add comment