-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment.go
131 lines (108 loc) · 2.23 KB
/
segment.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package wal
import (
"bufio"
"encoding/binary"
"fmt"
"hash/crc32"
"io"
"os"
"time"
)
// Segment represents a signgle segment file
type Segment struct {
index int
path string
size int64
fd *os.File
writer *bufio.Writer
offset []pos
currSize int64
modTime time.Time
closed bool
}
func (s *Segment) Open() error {
f, err := os.OpenFile(s.path, recoverLogPermission, 0644)
if err != nil {
return err
}
s.fd = f
return err
}
func (s *Segment) Close() error {
return s.fd.Close()
}
func (s *Segment) OnActiveBuffer(idx int) bool {
return s.offset[idx].offset > s.currSize || s.currSize == 0
}
type pos struct {
offset int64
length uint32
}
func (p *pos) EndOffset() int64 {
return p.offset + blockSize + int64(p.length)
}
func (s *Segment) Read() error {
var (
offset int64
reader = bufio.NewReader(s.fd)
)
for {
entry, err := s.ReadEntry(reader)
if err != nil {
if err == io.EOF {
break
}
return err
}
calcChecksum := crc32.ChecksumIEEE(entry.Data)
if entry.Checksum != calcChecksum {
return fmt.Errorf("checksum mismatch at offset %d", offset)
}
s.offset = append(s.offset, pos{
offset: offset,
length: entry.Length,
})
offset += int64(entry.Offset)
}
s.size = offset
_, err := s.fd.Seek(offset, io.SeekStart)
if err != nil {
return err
}
s.writer = bufio.NewWriter(s.fd)
return nil
}
func (s *Segment) ReadEntry(reader *bufio.Reader) (*LogEntry, error) {
header := make([]byte, 16)
_, err := io.ReadFull(reader, header)
if err != nil {
return nil, err
}
timestamp := int64(binary.BigEndian.Uint64(header[0:8]))
length := binary.BigEndian.Uint32(header[8:12])
checksum := binary.BigEndian.Uint32(header[12:16])
data := make([]byte, length)
_, err = io.ReadFull(reader, data)
if err != nil {
return nil, err
}
offset := int(blockSize + length)
return &LogEntry{
Offset: offset,
Timestamp: timestamp,
Checksum: checksum,
Data: data,
Length: length,
}, nil
}
func (s *Segment) SeekOffset(offset int64) (*LogEntry, error) {
_, err := s.fd.Seek(offset, io.SeekStart)
if err != nil {
return nil, err
}
reader := bufio.NewReader(s.fd)
return s.ReadEntry(reader)
}
func (s *Segment) Size() int {
return len(s.offset)
}