forked from nutsdb/nutsdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.go
346 lines (289 loc) · 7.71 KB
/
merge.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright 2023 The nutsdb Author. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nutsdb
import (
"bytes"
"errors"
"fmt"
"io"
"math"
"os"
"time"
"github.com/xujiajun/utils/strconv2"
)
var ErrDontNeedMerge = errors.New("the number of files waiting to be merged is at least 2")
func (db *DB) Merge() error {
db.mergeStartCh <- struct{}{}
return <-db.mergeEndCh
}
// Merge removes dirty data and reduce data redundancy,following these steps:
//
// 1. Filter delete or expired entry.
//
// 2. Write entry to activeFile if the key not exist,if exist miss this write operation.
//
// 3. Filter the entry which is committed.
//
// 4. At last remove the merged files.
//
// Caveat: merge is Called means starting multiple write transactions, and it
// will affect the other write request. so execute it at the appropriate time.
func (db *DB) merge() error {
var (
off int64
pendingMergeFIds []int
)
// to prevent the initiation of multiple merges simultaneously.
db.mu.Lock()
if db.isMerging {
db.mu.Unlock()
return ErrIsMerging
}
db.isMerging = true
defer func() {
db.isMerging = false
}()
_, pendingMergeFIds = db.getMaxFileIDAndFileIDs()
if len(pendingMergeFIds) < 2 {
db.mu.Unlock()
return ErrDontNeedMerge
}
db.MaxFileID++
if !db.opt.SyncEnable && db.opt.RWMode == MMap {
if err := db.ActiveFile.rwManager.Sync(); err != nil {
db.mu.Unlock()
return err
}
}
if err := db.ActiveFile.rwManager.Release(); err != nil {
db.mu.Unlock()
return err
}
var err error
path := getDataPath(db.MaxFileID, db.opt.Dir)
db.ActiveFile, err = db.fm.getDataFile(path, db.opt.SegmentSize)
if err != nil {
db.mu.Unlock()
return err
}
db.ActiveFile.fileID = db.MaxFileID
db.mu.Unlock()
mergingPath := make([]string, len(pendingMergeFIds))
for i, pendingMergeFId := range pendingMergeFIds {
off = 0
path := getDataPath(int64(pendingMergeFId), db.opt.Dir)
fr, err := newFileRecovery(path, db.opt.BufferSizeOfRecovery)
if err != nil {
return err
}
for {
if entry, err := fr.readEntry(off); err == nil {
if entry == nil {
break
}
if entry.isFilter() {
off += entry.Size()
if off >= db.opt.SegmentSize {
break
}
continue
}
// Due to the lack of concurrency safety in the index,
// there is a possibility that a race condition might occur when the merge goroutine reads the index,
// while a transaction is being committed, causing modifications to the index.
// To address this issue, we need to use a transaction to perform this operation.
err := db.Update(func(tx *Tx) error {
// check if we have a new entry with same key and bucket
if ok := db.isPendingMergeEntry(entry); ok {
bucket, err := db.bm.GetBucketById(entry.Meta.BucketId)
if err != nil {
return err
}
bucketName := bucket.Name
if entry.Meta.Flag == DataLPushFlag {
return tx.LPushRaw(bucketName, entry.Key, entry.Value)
}
if entry.Meta.Flag == DataRPushFlag {
return tx.RPushRaw(bucketName, entry.Key, entry.Value)
}
return tx.put(
bucketName,
entry.Key,
entry.Value,
entry.Meta.TTL,
entry.Meta.Flag,
entry.Meta.Timestamp,
entry.Meta.Ds,
)
}
return nil
})
if err != nil {
_ = fr.release()
return err
}
off += entry.Size()
if off >= db.opt.SegmentSize {
break
}
} else {
if errors.Is(err, io.EOF) || errors.Is(err, ErrIndexOutOfBound) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, ErrHeaderSizeOutOfBounds) {
break
}
return fmt.Errorf("when merge operation build hintIndex readAt err: %s", err)
}
}
err = fr.release()
if err != nil {
return err
}
mergingPath[i] = path
}
db.mu.Lock()
defer db.mu.Unlock()
for i := 0; i < len(mergingPath); i++ {
if err := os.Remove(mergingPath[i]); err != nil {
return fmt.Errorf("when merge err: %s", err)
}
}
return nil
}
func (db *DB) mergeWorker() {
var ticker *time.Ticker
if db.opt.MergeInterval != 0 {
ticker = time.NewTicker(db.opt.MergeInterval)
} else {
ticker = time.NewTicker(math.MaxInt)
ticker.Stop()
}
for {
select {
case <-db.mergeStartCh:
db.mergeEndCh <- db.merge()
// if automatic merging is enabled, then after a manual merge
// the t needs to be reset.
if db.opt.MergeInterval != 0 {
ticker.Reset(db.opt.MergeInterval)
}
case <-ticker.C:
_ = db.merge()
case <-db.mergeWorkCloseCh:
return
}
}
}
func (db *DB) isPendingMergeEntry(entry *Entry) bool {
bucket, err := db.bm.GetBucketById(entry.Meta.BucketId)
if err != nil {
return false
}
bucketId := bucket.Id
switch {
case entry.IsBelongsToBPlusTree():
return db.isPendingBtreeEntry(bucketId, entry)
case entry.IsBelongsToList():
return db.isPendingListEntry(bucketId, entry)
case entry.IsBelongsToSet():
return db.isPendingSetEntry(bucketId, entry)
case entry.IsBelongsToSortSet():
return db.isPendingZSetEntry(bucketId, entry)
}
return false
}
func (db *DB) isPendingBtreeEntry(bucketId BucketId, entry *Entry) bool {
idx, exist := db.Index.bTree.exist(bucketId)
if !exist {
return false
}
r, ok := idx.Find(entry.Key)
if !ok {
return false
}
if r.IsExpired() {
db.tm.del(bucketId, string(entry.Key))
idx.Delete(entry.Key)
return false
}
if r.TxID != entry.Meta.TxID || r.Timestamp != entry.Meta.Timestamp {
return false
}
return true
}
func (db *DB) isPendingSetEntry(bucketId BucketId, entry *Entry) bool {
setIdx, exist := db.Index.set.exist(bucketId)
if !exist {
return false
}
isMember, err := setIdx.SIsMember(string(entry.Key), entry.Value)
if err != nil || !isMember {
return false
}
return true
}
func (db *DB) isPendingZSetEntry(bucketId BucketId, entry *Entry) bool {
key, score := splitStringFloat64Str(string(entry.Key), SeparatorForZSetKey)
sortedSetIdx, exist := db.Index.sortedSet.exist(bucketId)
if !exist {
return false
}
s, err := sortedSetIdx.ZScore(key, entry.Value)
if err != nil || s != score {
return false
}
return true
}
func (db *DB) isPendingListEntry(bucketId BucketId, entry *Entry) bool {
var userKeyStr string
var curSeq uint64
var userKey []byte
if entry.Meta.Flag == DataExpireListFlag {
userKeyStr = string(entry.Key)
list, exist := db.Index.list.exist(bucketId)
if !exist {
return false
}
if _, ok := list.Items[userKeyStr]; !ok {
return false
}
t, _ := strconv2.StrToInt64(string(entry.Value))
ttl := uint32(t)
if _, ok := list.TTL[userKeyStr]; !ok {
return false
}
if list.TTL[userKeyStr] != ttl || list.TimeStamp[userKeyStr] != entry.Meta.Timestamp {
return false
}
return true
}
if entry.Meta.Flag == DataLPushFlag || entry.Meta.Flag == DataRPushFlag {
userKey, curSeq = decodeListKey(entry.Key)
userKeyStr = string(userKey)
list, exist := db.Index.list.exist(bucketId)
if !exist {
return false
}
if _, ok := list.Items[userKeyStr]; !ok {
return false
}
r, ok := list.Items[userKeyStr].Find(ConvertUint64ToBigEndianBytes(curSeq))
if !ok {
return false
}
if !bytes.Equal(r.Key, entry.Key) || r.TxID != entry.Meta.TxID || r.Timestamp != entry.Meta.Timestamp {
return false
}
return true
}
return false
}