-
Notifications
You must be signed in to change notification settings - Fork 4
/
cursor.go
241 lines (201 loc) · 4.22 KB
/
cursor.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
package wal
import (
"bufio"
"encoding/binary"
"fmt"
"io"
"os"
"sync/atomic"
"time"
"github.com/mreiferson/wal/internal/util"
)
// Entry contains the body and metadata for an entry in the log
type Entry struct {
CRC uint32
ID uint64
Body []byte
}
// Cursor references a position in the log specified by a segment number and index
// and exposes a channel to receive entries
//
// A Cursor should call Close when no longer in use
type Cursor interface {
ReadCh() <-chan Entry
Reset() (uint64, error)
Close() error
}
type cursor struct {
// 64bit atomic vars need to be first for proper alignment on 32bit platforms
offset uint64
startIdx uint64
idx uint64
segmentNum uint64
wal *wal
version int32
f *os.File
r *bufio.Reader
readCh chan Entry
resetFlag int32
resetRespCh chan uint64
closeCh chan struct{}
wg util.WaitGroupWrapper
logger logger
}
func newCursor(w *wal, segmentNum uint64, idx uint64, offset uint64, logger logger) (Cursor, error) {
c := &cursor{
wal: w,
offset: offset,
startIdx: idx,
idx: idx,
segmentNum: segmentNum,
readCh: make(chan Entry, 100), // TODO: (WAL) benchmark different buffer sizes
resetRespCh: make(chan uint64),
closeCh: make(chan struct{}),
logger: logger,
}
c.wg.Wrap(c.readLoop)
return c, nil
}
func (c *cursor) logf(f string, args ...interface{}) {
if c.logger == nil {
return
}
c.logger.Output(2, fmt.Sprintf(f, args...))
}
func (c *cursor) ReadCh() <-chan Entry {
return c.readCh
}
func (c *cursor) Reset() (uint64, error) {
atomic.StoreInt32(&c.resetFlag, 1)
for {
select {
case v := <-c.resetRespCh:
return v, nil
default:
time.Sleep(time.Millisecond)
}
c.wal.writeCond.Broadcast()
}
}
func (c *cursor) Close() error {
close(c.closeCh)
c.wg.Wait()
return nil
}
func (c *cursor) openFile() error {
fn := segmentFileName(c.wal.dataPath, c.wal.name, c.segmentNum)
c.logf("opening %s", fn)
f, err := os.OpenFile(fn, os.O_RDONLY, 0600)
if err != nil {
return err
}
c.f = f
c.r = bufio.NewReader(c.f)
return c.readHeader()
}
func (c *cursor) isAtTail() bool {
return c.segmentNum == c.wal.segmentNum && c.offset == c.wal.segmentOffset
}
func (c *cursor) maybeWait() {
c.wal.writeCond.L.Lock()
for c.isAtTail() {
c.wal.writeCond.Wait()
if atomic.CompareAndSwapInt32(&c.resetFlag, 1, 0) {
c.segmentNum = c.wal.segmentNum
c.offset = c.wal.segment.offset
c.idx = c.wal.segment.idx
c.f.Close()
c.f = nil
c.resetRespCh <- c.idx
}
}
c.wal.writeCond.L.Unlock()
}
func (c *cursor) readLoop() {
for {
if c.f == nil {
err := c.openFile()
if err != nil {
c.logf("ERROR: %s", err)
c.roll()
continue
}
}
c.maybeWait()
totalBytes, e, roll, err := readOne(c.r)
if err != nil {
c.logf("ERROR: readOne - %s", err)
c.roll()
continue
}
if roll {
c.roll()
continue
}
c.idx++
c.offset += totalBytes
if e.ID < c.startIdx {
select {
case <-c.closeCh:
goto exit
default:
}
continue
}
select {
case c.readCh <- e:
case <-c.closeCh:
goto exit
}
}
exit:
}
func (c *cursor) roll() {
// TODO: (WAL) if we roll past the end, signal write segment roll?
c.f.Close()
c.f = nil
c.segmentNum++
c.offset = 0
c.wal.rollCond.L.Lock()
for c.segmentNum > c.wal.segmentNum {
c.wal.rollCond.Wait()
}
c.wal.rollCond.L.Unlock()
}
func (c *cursor) readHeader() error {
var buf [4]byte
_, err := c.f.ReadAt(buf[:], 0)
if err != nil {
return err
}
c.version = int32(binary.BigEndian.Uint32(buf[:]))
if c.offset == 0 {
c.offset = 4
}
_, err = c.f.Seek(int64(c.offset), 0)
return err
}
func readOne(r io.Reader) (uint64, Entry, bool, error) {
var buf [4]byte
_, err := io.ReadFull(r, buf[:])
if err != nil {
return 0, Entry{}, false, err
}
size := int32(binary.BigEndian.Uint32(buf[:]))
if size == eofIndicator {
return 0, Entry{}, true, nil
}
data := make([]byte, size)
_, err = io.ReadFull(r, data)
if err != nil {
return 0, Entry{}, false, err
}
return 4 + uint64(size), sliceToEntry(data), false, nil
}
func sliceToEntry(data []byte) Entry {
return Entry{
CRC: binary.BigEndian.Uint32(data[:4]),
ID: binary.BigEndian.Uint64(data[4:12]),
Body: data[12:],
}
}