-
Notifications
You must be signed in to change notification settings - Fork 4
/
valuelog.go
283 lines (241 loc) · 6.7 KB
/
valuelog.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
package range_partition
import (
"context"
"fmt"
"sort"
"time"
"github.com/journeymidnight/autumn/range_partition/y"
"github.com/journeymidnight/autumn/streamclient"
"github.com/journeymidnight/autumn/utils"
"github.com/journeymidnight/autumn/xlog"
"github.com/opentracing/opentracing-go"
)
//replay valuelog
//compact valuelog
func (rp *RangePartition) writeValueLog(reqs []*request) ([]*Entry, valuePointer, error) {
var blocks []block
var entries []*Entry
for _, req := range reqs {
for _, e := range req.entries {
blocks = append(blocks, e.Encode())
entries = append(entries, e)
}
}
span := opentracing.GlobalTracer().StartSpan("writeValueLog")
defer span.Finish()
ctx := opentracing.ContextWithSpan(context.Background(), span)
extentID, offsets, tail, err := rp.logStream.Append(ctx, blocks, rp.opt.MustSync)
if err != nil {
return nil, valuePointer{}, err
}
//update entries
for i := range entries {
entries[i].ExtentID = extentID
entries[i].Offset = offsets[i]
if i == len(entries)-1 {
entries[i].End = tail
} else {
entries[i].End = offsets[i+1]
}
}
return entries, valuePointer{extentID: extentID, offset: tail}, nil
}
func replayLog(stream streamclient.StreamClient, replayFunc func(*Entry) (bool, error), opts ...streamclient.ReadOption) error {
iter := stream.NewLogEntryIter(opts...)
for {
ok, err := iter.HasNext()
if err != nil {
return err
}
if !ok {
break
}
data, extentID, offset, end := iter.Next()
ei, err := DecodeEntry(data)
ei.ExtentID = extentID
ei.Offset = offset
ei.End = end
if err != nil {
return err
}
next, err := replayFunc(ei)
if err != nil {
return err
}
if !next {
break
}
}
return nil
}
func discardEntry(ei *Entry, vs y.ValueStruct) bool {
if vs.Version != y.ParseTs(ei.Key) {
// Version not found. Discard.
return true
}
if isDeletedOrExpired(vs.Meta, vs.ExpiresAt) {
return true
}
return false
}
type GcTask struct {
ForceGC bool
ExIDs []uint64 //if not forceGC, pickup will choose automatically
}
const (
MAX_GC_ONCE = 3
)
func (rp *RangePartition) startGC() {
rp.gcStopper = utils.NewStopper()
rp.gcRunChan = make(chan GcTask, 1)
//only one compact goroutine
rp.gcStopper.RunWorker(func() {
for {
select {
case <-rp.gcStopper.ShouldStop():
return
case task := <-rp.gcRunChan:
//chose an extent to compact
logStreamInfo := rp.logStream.StreamInfo()
if len(logStreamInfo.ExtentIDs) < 2 {
fmt.Printf("only one extent, no extent to delete\n")
continue
}
holes := make([]uint64, 0, 3)
if task.ForceGC {
fmt.Printf("task to gc on %+v\n", task.ExIDs)
//valide task.ExIDs
idx := make(map[uint64]bool, len(logStreamInfo.ExtentIDs))
for _, exID := range logStreamInfo.ExtentIDs {
idx[exID] = true
}
for i := 0; i < len(task.ExIDs) && i < MAX_GC_ONCE; i++ {
if _, ok := idx[task.ExIDs[i]]; ok {
holes = append(holes, task.ExIDs[i])
}
}
} else {
tbls := rp.getTables()
discards := getDiscards(tbls)
//exlucde the last extent, last extent is usually a non-sealed extent
validDiscard(discards, logStreamInfo.ExtentIDs[:len(logStreamInfo.ExtentIDs)-1])
//sort discard
canndidates := make([]uint64, 0, 3)
for k := range discards {
canndidates = append(canndidates, k)
}
sort.Slice(canndidates, func(i, j int) bool {
return discards[canndidates[i]] > discards[canndidates[j]]
})
for i := 0; i < len(canndidates) && i < MAX_GC_ONCE; i++ {
exID := canndidates[i]
size, err := rp.logStream.SealedLength(exID)
if err != nil {
xlog.Logger.Errorf("get sealed length error: %v in runGC", err)
continue
}
if size == 0 {
continue
}
radio := float64(discards[exID]) / float64(size)
if radio > 0.4 {
holes = append(holes, exID)
}
}
}
if len(holes) == 0 {
fmt.Printf("no extent to delete\n")
continue
}
for i := range holes {
rp.runGC(holes[i])
}
//TODO: retry if failed
//delete extent for stream
fmt.Printf("deleted extent [%v], for stream %d\n", holes, logStreamInfo.StreamID)
//delete extent for block
pctx, cancel := context.WithTimeout(rp.gcStopper.Ctx(), time.Second*5)
if err := rp.logStream.PunchHoles(pctx, holes); err != nil {
xlog.Logger.Errorf("punch holes error: %v in runGC", err)
}
cancel()
}
}
})
}
func (rp *RangePartition) runGC(extentID uint64) {
var count, moved int
var freeSize uint64
var moveSize uint64
wb := make([]*Entry, 0, 100)
fe := func(ei *Entry) (bool, error) {
count++
if count%100000 == 0 {
xlog.Logger.Debugf("Processing entry %d", count)
}
freeSize += uint64(ei.Size())
userKey := y.ParseKey(ei.Key)
//fmt.Printf("processing %s\n", userKey)
//if small file
if (ei.Meta & uint32(BitValuePointer)) == 0 {
//fmt.Printf("discard small entry, key: %s\n", streamclient.FormatEntry(ei))
return true, nil
}
if !rp.IsUserKeyInRange(userKey) {
return true, nil
}
//startKey <= userKey < endKey
vs := rp.getValueStruct(userKey, 0) //get the latest version
if discardEntry(ei, vs) {
//fmt.Printf("discard blob entry, key: %s\n", streamclient.FormatEntry(ei))
return true, nil
}
/*
rp.Write(userKey, []byte("TEST"))
*/
utils.AssertTrue(len(vs.Value) > 0)
var vp valuePointer
vp.Decode(vs.Value)
if vp.extentID == ei.ExtentID && vp.offset == ei.Offset {
moved++
//write ne to mt
//keep seqNum
ne := ei //use the same entry
//fmt.Printf("MOVE %s\n", userKey)
if len(wb) > 4 {
//如果是GC request, 在写入log之前,还要再读一遍key, 如果有新Key已经写入, 则放弃
req, err := rp.sendToWriteCh(wb, true)
if err != nil {
return false, err
}
req.Wait() //wait for write complete and reclaim memory
wb = wb[:0]
}
wb = append(wb, ne)
moveSize += uint64(ei.Size())
}
return true, nil
}
err := replayLog(rp.logStream, fe, streamclient.WithReadFrom(extentID, 0, 1))
if err != nil {
xlog.Logger.Errorf("replayLog error: %v", err)
return
}
//flush wb
if len(wb) > 0 {
req, err := rp.sendToWriteCh(wb, true)
if err != nil {
xlog.Logger.Errorf("sendToWriteCh error: %v", err)
return
}
req.Wait()
}
err = rp.logStream.PunchHoles(context.Background(), []uint64{extentID})
if err != nil {
xlog.Logger.Errorf("PunchHoles error: %v", err)
return
}
fmt.Printf("GC: processed %d entries, %d entries moved, %v freed bytes, %v moved bytes\n", count, moved,
utils.HumanReadableSize(freeSize), utils.HumanReadableSize(moveSize))
xlog.Logger.Infof("GC: processed %d entries, %d entries moved, %d freed bytes, %d moved bytes", count, moved, freeSize, moveSize)
}