-
Notifications
You must be signed in to change notification settings - Fork 4
/
segment.go
312 lines (257 loc) · 5.65 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package wal
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"os"
)
const eofIndicator int32 = -1
const segmentMapFlushInterval = 200
type segment struct {
// 64bit atomic vars need to be first for proper alignment on 32bit platforms
offset uint64
startIdx uint64
idx uint64
count uint64
fileName string
version int32
segmentMap *segmentMap
f *os.File
buf bytes.Buffer
logger logger
}
func newSegment(fileName string, idx uint64, logger logger) (*segment, error) {
f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return nil, err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, err
}
s := &segment{
startIdx: idx,
idx: idx,
f: f,
fileName: fileName,
logger: logger,
segmentMap: newSegmentMap(),
offset: uint64(fi.Size()),
}
segmentMapFn := swapExtension(fileName, "map")
if fi.Size() == 0 {
err := s.writeHeader()
if err != nil {
s.close()
return nil, err
}
s.segmentMap.set(s.idx, s.offset)
err = s.segmentMap.flush(segmentMapFn)
if err != nil {
return nil, err
}
s.logf("created %s at %d", s.fileName, s.idx)
} else {
err := s.segmentMap.load(segmentMapFn)
if err != nil {
return nil, err
}
s.logf("re-opened %s at %d", s.fileName, s.idx)
}
return s, nil
}
func (s *segment) logf(f string, args ...interface{}) {
if s.logger == nil {
return
}
s.logger.Output(2, fmt.Sprintf(f, args...))
}
func (s *segment) finish() error {
err := s.writeTrailer()
if err != nil {
s.logf("ERROR: writeTrailer - %s", err)
}
return s.close()
}
func (s *segment) close() error {
return s.f.Close()
}
func (s *segment) writeHeader() error {
err := binary.Write(s.f, binary.BigEndian, int32(s.version))
if err != nil {
return err
}
s.offset += 4
return nil
}
func (s *segment) writeTrailer() error {
err := binary.Write(s.f, binary.BigEndian, eofIndicator)
if err != nil {
return err
}
s.offset += 4
return nil
}
func (s *segment) appendFastInner(idx uint64, entry EntryWriterTo) (uint32, error) {
var buf [16]byte
size := 4 /* CRC */ + 8 /* ID */ + uint32(entry.Len())
binary.BigEndian.PutUint32(buf[:4], size)
binary.BigEndian.PutUint32(buf[4:8], entry.CRC())
binary.BigEndian.PutUint64(buf[8:16], uint64(idx))
_, err := s.buf.Write(buf[:])
if err != nil {
return size, err
}
_, err = entry.WriteTo(&s.buf)
if err != nil {
return size, err
}
return size, nil
}
func (s *segment) appendInner(idx uint64, entry []byte, crc uint32) (uint32, error) {
var buf [16]byte
size := 4 /* CRC */ + 8 /* ID */ + uint32(len(entry))
binary.BigEndian.PutUint32(buf[:4], size)
binary.BigEndian.PutUint32(buf[4:8], crc)
binary.BigEndian.PutUint64(buf[8:16], uint64(idx))
_, err := s.buf.Write(buf[:])
if err != nil {
return 0, err
}
_, err = s.buf.Write(entry)
if err != nil {
return 0, err
}
return size, nil
}
func (s *segment) append(entries []EntryWriterTo) (uint64, error) {
var err error
var totalBytes int
var segmentMapItems [][2]uint64
s.buf.Reset()
idx := s.idx
count := s.count
offset := s.offset
for _, entry := range entries {
size, err := s.appendFastInner(idx, entry)
if err != nil {
goto exit
}
if count%segmentMapFlushInterval == 0 {
segmentMapItems = append(segmentMapItems, [2]uint64{idx, offset})
}
idx++
count++
offset += 4 + uint64(size)
}
// TODO: (WAL) can we use writev here to avoid copying?
// https://github.com/golang/go/issues/13451
//
// only write to the file once
totalBytes, err = s.f.Write(s.buf.Bytes())
if err != nil {
goto exit
}
s.idx = idx
s.offset += uint64(totalBytes)
s.count += count
if len(segmentMapItems) > 0 {
for _, item := range segmentMapItems {
s.segmentMap.set(item[0], item[1])
}
err = s.segmentMap.flush(swapExtension(s.fileName, "map"))
if err != nil {
goto exit
}
}
exit:
return s.idx, err
}
func (s *segment) appendBytes(entries [][]byte, crcs []uint32) (uint64, error) {
var err error
var totalBytes int
var segmentMapItems [][2]uint64
s.buf.Reset()
idx := s.idx
count := s.count
offset := s.offset
for i, entry := range entries {
size, err := s.appendInner(idx, entry, crcs[i])
if err != nil {
goto exit
}
if count%segmentMapFlushInterval == 0 {
segmentMapItems = append(segmentMapItems, [2]uint64{idx, offset})
}
idx++
count++
offset += 4 + uint64(size)
}
// TODO: (WAL) can we use writev here to avoid copying?
// https://github.com/golang/go/issues/13451
//
// only write to the file once
totalBytes, err = s.f.Write(s.buf.Bytes())
if err != nil {
goto exit
}
s.idx = idx
s.offset += uint64(totalBytes)
s.count += count
if len(segmentMapItems) > 0 {
for _, item := range segmentMapItems {
s.segmentMap.set(item[0], item[1])
}
err = s.segmentMap.flush(swapExtension(s.fileName, "map"))
if err != nil {
goto exit
}
}
exit:
return s.idx, err
}
func (s *segment) sync() error {
if s.f == nil {
return nil
}
return s.f.Sync()
}
func (s *segment) size() int64 {
return int64(s.offset)
}
func getLastSegmentIdx(fn string) (uint64, error) {
mapFn := swapExtension(fn, "map")
segmentMap := newSegmentMap()
err := segmentMap.load(mapFn)
if err != nil {
return 0, err
}
f, err := os.OpenFile(fn, os.O_RDONLY, 0600)
if err != nil {
return 0, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return 0, err
}
size := uint64(fi.Size())
offset := segmentMap.lastOffset()
_, err = f.Seek(int64(offset), 0)
if err != nil {
return 0, err
}
r := bufio.NewReader(f)
var idx uint64
for offset < size {
totalBytes, e, _, err := readOne(r)
if err != nil {
return 0, err
}
offset += totalBytes
idx = e.ID
}
return idx, nil
}