-
Notifications
You must be signed in to change notification settings - Fork 5
/
log_entry.go
84 lines (71 loc) · 1.66 KB
/
log_entry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package raft
import (
"bufio"
"encoding/binary"
// "fmt"
"os"
"github.com/golang/protobuf/proto"
pb "github.com/moxiaomomo/goRaft/proto"
)
// LogEntryMeta metadata of a logentry
type LogEntryMeta struct {
DataLength uint32
}
// LogEntry logentry
type LogEntry struct {
Entry *pb.LogEntry
LogPosition uint64 // position in logfile
}
// NewLogEntry creates a new logentry instance
func NewLogEntry(curterm, curindex uint64, commandname string, command []byte) *LogEntry {
lu := &LogEntry{
Entry: &pb.LogEntry{
Index: curindex,
Term: curterm,
Commandname: commandname,
Command: command,
},
}
return lu
}
// save data into file
func (l *LogEntry) dump(file *os.File) (indexend int64, err error) {
n, _ := file.Seek(0, os.SEEK_END)
w := bufio.NewWriter(file)
d, err := proto.Marshal(l.Entry)
if err != nil {
return -1, err
}
data := []byte(d)
meta := LogEntryMeta{
DataLength: uint32(len(data)),
}
err = binary.Write(w, binary.BigEndian, &meta)
if err != nil {
return -1, err
}
w.Write(data)
w.Flush()
return n + int64(binary.Size(meta)) + int64(meta.DataLength), nil
}
// load data from file
func (l *LogEntry) load(file *os.File, startIndex int64) (indexend int64, err error) {
n, _ := file.Seek(startIndex, 0)
r := bufio.NewReader(file)
meta := &LogEntryMeta{}
err = binary.Read(r, binary.BigEndian, meta)
if err != nil {
return -1, err
}
data := make([]byte, meta.DataLength)
_, err = r.Read(data)
if err != nil {
return -1, nil
}
l.Entry = &pb.LogEntry{}
err = proto.Unmarshal(data, l.Entry)
if err != nil {
return -1, err
}
return n + int64(binary.Size(meta)) + int64(meta.DataLength), nil
}