-
Notifications
You must be signed in to change notification settings - Fork 4
/
segment_map.go
126 lines (107 loc) · 2.35 KB
/
segment_map.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
package wal
import (
"bufio"
"errors"
"fmt"
"math/rand"
"os"
"github.com/mreiferson/wal/internal/atomic_rename"
"github.com/mreiferson/wal/internal/skiplist"
)
type segmentMap struct {
entries *skiplist.SkipList
}
func newSegmentMap() *segmentMap {
return &segmentMap{
entries: skiplist.NewCustomMap(func(l, r interface{}) bool {
return l.(uint64) > r.(uint64)
}),
}
}
func (sm *segmentMap) load(fn string) error {
f, err := os.OpenFile(fn, os.O_RDONLY, 0600)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
var idx uint64
var offset uint64
_, err = fmt.Sscanf(scanner.Text(), "%d %d", &idx, &offset)
if err != nil {
return err
}
sm.entries.Set(idx, offset)
}
return scanner.Err()
}
func (sm *segmentMap) locate(idx uint64) (uint64, error) {
_, value, present := sm.entries.GetGreaterOrEqual(idx)
if !present {
return 0, errors.New("not found")
}
return value.(uint64), nil
}
func (sm *segmentMap) set(idx uint64, offset uint64) {
sm.entries.Set(idx, offset)
}
func (sm *segmentMap) flush(fn string) error {
tmpFn := fmt.Sprintf("%s.%d.tmp", fn, rand.Int())
f, err := os.OpenFile(tmpFn, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return err
}
i := sm.entries.Iterator()
for i.Next() {
_, err := fmt.Fprintf(f, "%d %d\n", i.Key(), i.Value())
if err != nil {
f.Close()
return err
}
}
f.Sync()
f.Close()
return atomic_rename.Rename(tmpFn, fn)
}
func (sm *segmentMap) startIdx() uint64 {
return sm.entries.SeekToLast().Key().(uint64)
}
func (sm *segmentMap) lastOffset() uint64 {
return sm.entries.SeekToFirst().Value().(uint64)
}
func rebuildSegmentMapFromSegment(fn string) (*segmentMap, error) {
segmentMap := newSegmentMap()
f, err := os.OpenFile(fn, os.O_RDONLY, 0600)
if err != nil {
return nil, err
}
defer f.Close()
_, err = f.Seek(4, 0)
if err != nil {
return nil, err
}
r := bufio.NewReader(f)
var count uint64
var offset uint64 = 4
for {
totalBytes, e, roll, err := readOne(r)
if err != nil {
return nil, err
}
// TODO: (WAL) this isn't going to work for the current segment
if roll {
break
}
if count%segmentMapFlushInterval == 0 {
segmentMap.set(e.ID, offset)
}
offset += totalBytes
count++
}
err = segmentMap.flush(swapExtension(fn, "map"))
if err != nil {
return nil, err
}
return segmentMap, nil
}