forked from lotusdblabs/lotusdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
discard.go
225 lines (200 loc) · 5.31 KB
/
discard.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
package lotusdb
import (
"encoding/binary"
"errors"
"io"
"path/filepath"
"sort"
"sync"
"github.com/flower-corp/lotusdb/index"
"github.com/flower-corp/lotusdb/ioselector"
"github.com/flower-corp/lotusdb/logfile"
"github.com/flower-corp/lotusdb/logger"
)
const discardRecordSize = 12
// ErrDiscardNoSpace no enough space for discard file.
var ErrDiscardNoSpace = errors.New("not enough space can be allocated for the discard file")
// Discard is used to record total size and discarded size in a log file.
// Mainly for value log compaction.
type discard struct {
sync.Mutex
once *sync.Once
valChan chan [][]byte
file ioselector.IOSelector
freeList []int64 // contains file offset that can be allocated
location map[uint32]int64 // offset of each fid
}
func newDiscard(path, name string) (*discard, error) {
fname := filepath.Join(path, name)
fsize := 1 << 12
file, err := ioselector.NewMMapSelector(fname, int64(fsize))
if err != nil {
return nil, err
}
var freeList []int64
var offset int64
location := make(map[uint32]int64)
for {
// read fid and total is enough.
buf := make([]byte, 8)
if _, err := file.Read(buf, offset); err != nil {
if err == io.EOF || err == logfile.ErrEndOfEntry {
break
}
return nil, err
}
fid := binary.LittleEndian.Uint32(buf[:4])
total := binary.LittleEndian.Uint32(buf[4:8])
if fid == 0 && total == 0 {
freeList = append(freeList, offset)
} else {
location[fid] = offset
}
offset += discardRecordSize
}
d := &discard{
once: new(sync.Once),
valChan: make(chan [][]byte, 1024),
file: file,
freeList: freeList,
location: location,
}
go d.listenUpdates()
return d, nil
}
// CCL means compaction cnadidate list.
// iterate and find the file with most discarded data,
// there are 341 records at most, no need to worry about the performance.
func (d *discard) getCCL(activeFid uint32, ratio float64) ([]uint32, error) {
var offset int64
var ccl []uint32
d.Lock()
defer d.Unlock()
for {
buf := make([]byte, discardRecordSize)
_, err := d.file.Read(buf, offset)
if err != nil {
if err == io.EOF || err == logfile.ErrEndOfEntry {
break
}
return nil, err
}
offset += discardRecordSize
fid := binary.LittleEndian.Uint32(buf[:4])
total := binary.LittleEndian.Uint32(buf[4:8])
discard := binary.LittleEndian.Uint32(buf[8:12])
var curRatio float64
if total != 0 && discard != 0 {
curRatio = float64(discard) / float64(total)
}
if curRatio >= ratio && fid != activeFid {
ccl = append(ccl, fid)
}
}
// sort in ascending order, guarantee the older file will compact firstly.
sort.Slice(ccl, func(i, j int) bool {
return ccl[i] < ccl[j]
})
return ccl, nil
}
func (d *discard) listenUpdates() {
for {
select {
case oldVal, ok := <-d.valChan:
if !ok {
if err := d.file.Close(); err != nil {
logger.Errorf("close discard file err: %v", err)
}
return
}
counts := make(map[uint32]int)
for _, buf := range oldVal {
meta := index.DecodeMeta(buf)
counts[meta.Fid] += meta.EntrySize
}
for fid, size := range counts {
d.incrDiscard(fid, size)
}
}
}
}
func (d *discard) closeChan() {
d.once.Do(func() { close(d.valChan) })
}
func (d *discard) setTotal(fid uint32, totalSize uint32) {
d.Lock()
defer d.Unlock()
if _, ok := d.location[fid]; ok {
return
}
offset, err := d.alloc(fid)
if err != nil {
logger.Errorf("discard file allocate err: %+v", err)
return
}
buf := make([]byte, 8)
binary.LittleEndian.PutUint32(buf[:4], fid)
binary.LittleEndian.PutUint32(buf[4:8], totalSize)
if _, err = d.file.Write(buf, offset); err != nil {
logger.Errorf("incr value in discard err: %v", err)
return
}
}
func (d *discard) clear(fid uint32) {
d.incr(fid, -1)
d.Lock()
if offset, ok := d.location[fid]; ok {
d.freeList = append(d.freeList, offset)
delete(d.location, fid)
}
d.Unlock()
}
func (d *discard) incrDiscard(fid uint32, delta int) {
if delta > 0 {
d.incr(fid, delta)
}
}
// format of discard file` record:
// +-------+--------------+----------------+ +-------+--------------+----------------+
// | fid | total size | discarded size | | fid | total size | discarded size |
// +-------+--------------+----------------+ +-------+--------------+----------------+
// 0-------4--------------8---------------12 12------16------------20----------------24
func (d *discard) incr(fid uint32, delta int) {
d.Lock()
defer d.Unlock()
offset, err := d.alloc(fid)
if err != nil {
logger.Errorf("discard file allocate err: %+v", err)
return
}
var buf []byte
if delta > 0 {
buf = make([]byte, 4)
offset += 8
if _, err := d.file.Read(buf, offset); err != nil {
logger.Errorf("incr value in discard err:%v", err)
return
}
v := binary.LittleEndian.Uint32(buf)
binary.LittleEndian.PutUint32(buf, v+uint32(delta))
} else {
buf = make([]byte, discardRecordSize)
}
if _, err := d.file.Write(buf, offset); err != nil {
logger.Errorf("incr value in discard err:%v", err)
return
}
}
// must hold the lock before invoking
func (d *discard) alloc(fid uint32) (int64, error) {
if offset, ok := d.location[fid]; ok {
return offset, nil
}
if len(d.freeList) == 0 {
return 0, ErrDiscardNoSpace
}
offset := d.freeList[len(d.freeList)-1]
d.freeList = d.freeList[:len(d.freeList)-1]
d.location[fid] = offset
return offset, nil
}