forked from couchbaselabs/cbgb
/
compact.go
349 lines (316 loc) · 9.74 KB
/
compact.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
347
348
349
package main
import (
"fmt"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"unsafe"
"github.com/steveyen/gkvlite"
)
func (s *bucketstore) Compact() error {
s.diskLock.Lock()
defer s.diskLock.Unlock()
bsf := s.BSF()
if bsf.file == nil { // We're in memory-only mode.
return nil
}
compactPath := bsf.path + ".compact"
if err := s.compactGo(bsf, compactPath); err != nil {
atomic.AddInt64(&s.stats.CompactErrors, 1)
return err
}
atomic.AddInt64(&s.stats.Compacts, 1)
return nil
}
func (s *bucketstore) compactGo(bsf *bucketstorefile, compactPath string) error {
// TODO: Should cleanup all old, previous attempts to rescue disk space.
os.Remove(compactPath) // Clean up any previous attempts.
compactFile, err := fileService.OpenFile(compactPath, os.O_RDWR|os.O_CREATE|os.O_EXCL)
if err != nil {
return err
}
defer func() {
if compactFile != nil {
compactFile.Close()
os.Remove(compactPath)
}
}()
compactStore, err := gkvlite.NewStore(compactFile)
if err != nil {
return err
}
// TODO: Parametrize writeEvery.
writeEvery := 1000
lastChanges := make(map[uint16]*gkvlite.Item) // Last items in changes colls.
collNames := bsf.store.GetCollectionNames() // Names of collections to process.
collRest := make([]string, 0, len(collNames)) // Names of unprocessed collections.
vbids := make([]uint16, 0, len(collNames)) // VBucket id's that we processed.
// Process compaction in a few steps: first, unlocked,
// snapshot-based collection copying meant to handle most of each
// vbucket's data; and then, locked copying of any vbucket
// mutations (deltas) that happened in the meantime. Then, while
// still holding all vbucket collection locks, we copy any
// remaining non-vbucket collections and atomically swap the files.
for _, collName := range collNames {
if !strings.HasSuffix(collName, COLL_SUFFIX_CHANGES) {
if !strings.HasSuffix(collName, COLL_SUFFIX_KEYS) {
// It's neither a changes nor a keys collection.
collRest = append(collRest, collName)
}
continue
}
vbid, lastChange, err :=
s.copyVBucketColls(bsf, collName, compactStore, writeEvery)
if err != nil {
return err
}
lastChanges[uint16(vbid)] = lastChange
vbids = append(vbids, uint16(vbid))
}
return s.copyBucketStoreDeltas(bsf, compactStore,
vbids, 0, lastChanges, writeEvery, func() (err error) {
// Copy any remaining (simple) collections (lifke COLL_VBMETA).
err = s.copyRemainingColls(bsf, collRest, compactStore, writeEvery)
if err != nil {
return err
}
err = compactStore.Flush()
if err != nil {
return err
}
compactFile.Close()
return s.compactSwapFile(bsf, compactPath) // The last step.
})
}
func (s *bucketstore) compactSwapFile(bsf *bucketstorefile, compactPath string) error {
idx, ver, err := parseStoreFileName(filepath.Base(bsf.path), STORE_FILE_SUFFIX)
if err != nil {
return err
}
nextName := makeStoreFileName(idx, ver+1, STORE_FILE_SUFFIX)
nextPath := path.Join(filepath.Dir(bsf.path), nextName)
if err = os.Rename(compactPath, nextPath); err != nil {
return err
}
nextFile, err := fileService.OpenFile(nextPath, os.O_RDWR|os.O_CREATE)
if err != nil {
return err
}
nextBSF := NewBucketStoreFile(nextPath, nextFile, bsf.stats)
nextStore, err := gkvlite.NewStore(nextBSF)
if err != nil {
// TODO: Rollback the previous *.orig rename.
return err
}
nextBSF.store = nextStore
atomic.StorePointer(&s.bsf, unsafe.Pointer(nextBSF))
bsf.apply(func() {
bsf.purge = true // Mark the old file as purgable.
})
return nil
}
func copyColl(srcColl *gkvlite.Collection, dstColl *gkvlite.Collection,
writeEvery int) (numItems uint64, lastItem *gkvlite.Item, err error) {
minItem, err := srcColl.MinItem(true)
if err != nil {
return 0, nil, err
}
if minItem == nil {
return 0, nil, nil
}
var errVisit error = nil
err = srcColl.VisitItemsAscend(minItem.Key, true, func(i *gkvlite.Item) bool {
if errVisit = dstColl.SetItem(i); errVisit != nil {
return false
}
numItems++
lastItem = i
if writeEvery > 0 && numItems%uint64(writeEvery) == 0 {
if errVisit = dstColl.Write(); errVisit != nil {
return false
}
}
return true
})
if err != nil {
return 0, nil, err
}
if errVisit != nil {
return 0, nil, errVisit
}
return numItems, lastItem, nil
}
func copyDelta(lastChangeCAS []byte, cName string, kName string,
srcStore *gkvlite.Store, dstStore *gkvlite.Store,
writeEvery int) (numVisits uint64, err error) {
cSrc := srcStore.GetCollection(cName)
cDst := dstStore.GetCollection(cName)
kDst := dstStore.GetCollection(kName)
if cSrc == nil || cDst == nil || kDst == nil {
return 0, fmt.Errorf("compact copyDelta missing colls: %v, %v",
cName, kName)
}
var errVisit error
err = cSrc.VisitItemsAscend(lastChangeCAS, true, func(cItem *gkvlite.Item) bool {
numVisits++
if numVisits <= 1 {
return true
}
if errVisit = cDst.SetItem(cItem); errVisit != nil {
return false
}
// Update the keys index with the latest change.
i := &item{}
if errVisit = i.fromValueBytes(cItem.Val); errVisit != nil {
return false
}
if i.key == nil || len(i.key) <= 0 {
return true // A nil/empty key means a metadata change.
}
if i.isDeletion() {
if _, errVisit = kDst.Delete(i.key); errVisit != nil {
return false
}
} else {
if errVisit = kDst.Set(i.key, cItem.Key); errVisit != nil {
return false
}
}
// Persist to storage as needed.
if writeEvery > 0 && numVisits%uint64(writeEvery) == 0 {
if errVisit = cDst.Write(); errVisit != nil {
return false
}
if errVisit = kDst.Write(); errVisit != nil {
return false
}
}
return true
})
if err != nil {
return 0, err
}
if errVisit != nil {
return 0, errVisit
}
return numVisits, nil
}
func (s *bucketstore) copyVBucketColls(bsf *bucketstorefile,
collName string, compactStore *gkvlite.Store, writeEvery int) (
uint16, *gkvlite.Item, error) {
vbidStr := collName[0 : len(collName)-len(COLL_SUFFIX_CHANGES)]
vbid, err := strconv.Atoi(vbidStr)
if err != nil {
return 0, nil, err
}
if vbid < 0 || vbid > MAX_VBID {
return 0, nil, fmt.Errorf("compact vbid out of range: %v, vbid: %v",
bsf.path, vbid)
}
cName := fmt.Sprintf("%v%s", vbid, COLL_SUFFIX_CHANGES)
kName := fmt.Sprintf("%v%s", vbid, COLL_SUFFIX_KEYS)
cDest := compactStore.SetCollection(cName, nil)
kDest := compactStore.SetCollection(kName, nil)
if cDest == nil || kDest == nil {
return 0, nil, fmt.Errorf("compact could not create colls for vbid: %v",
vbid)
}
cCurr := s.coll(cName) // The c prefix in cFooBar means 'changes'.
kCurr := s.coll(kName) // The k prefix in kFooBar means 'keys'.
if cCurr == nil || kCurr == nil {
return 0, nil, fmt.Errorf("compact source colls missing: %v, vbid: %v",
bsf.path, vbid)
}
// Get a consistent snapshot (keys reflect all changes) of the
// keys & changes collections.
ps := s.partitions[uint16(vbid)]
if ps == nil {
return 0, nil, fmt.Errorf("compact missing partition for vbid: %v", vbid)
}
var currSnapshot *gkvlite.Store
ps.mutate(func(key, changes *gkvlite.Collection) {
currSnapshot = bsf.store.Snapshot()
})
if currSnapshot == nil {
return 0, nil, fmt.Errorf("compact source snapshot failed: %v, vbid: %v",
bsf.path, vbid)
}
cCurrSnapshot := currSnapshot.GetCollection(cName)
kCurrSnapshot := currSnapshot.GetCollection(kName)
if cCurrSnapshot == nil || kCurrSnapshot == nil {
return 0, nil, fmt.Errorf("compact missing colls from snapshot: %v, vbid: %v",
bsf.path, vbid)
}
// TODO: Record stats on # changes processed.
_, lastChange, err := copyColl(cCurrSnapshot, cDest, writeEvery)
if err != nil {
return 0, nil, err
}
// TODO: Record stats on # keys processed.
_, _, err = copyColl(kCurrSnapshot, kDest, writeEvery)
if err != nil {
return 0, nil, err
}
return uint16(vbid), lastChange, err
}
func (s *bucketstore) copyRemainingColls(bsf *bucketstorefile,
collRest []string, compactStore *gkvlite.Store, writeEvery int) error {
currSnapshot := bsf.store.Snapshot()
if currSnapshot == nil {
return fmt.Errorf("compact source snapshot failed: %v", bsf.path)
}
for _, collName := range collRest {
collCurr := currSnapshot.GetCollection(collName)
if collCurr == nil {
return fmt.Errorf("compact rest coll missing: %v, collName: %v",
bsf.path, collName)
}
collNext := compactStore.SetCollection(collName, nil)
if collCurr == nil {
return fmt.Errorf("compact rest dest missing: %v, collName: %v",
bsf.path, collName)
}
_, _, err := copyColl(collCurr, collNext, writeEvery)
if err != nil {
return err
}
}
return nil
}
// Copy any mutations that concurrently just came in. We use
// recursion to naturally have a phase of pausing & copying,
// and then unpausing as the recursion unwinds.
func (s *bucketstore) copyBucketStoreDeltas(bsf *bucketstorefile,
compactStore *gkvlite.Store, vbids []uint16, vbidIdx int,
lastChanges map[uint16]*gkvlite.Item, writeEvery int,
done func() error) (err error) {
if vbidIdx >= len(vbids) {
return done() // Callback while we have all the locks.
}
vbid := vbids[vbidIdx]
cName := fmt.Sprintf("%v%s", vbid, COLL_SUFFIX_CHANGES)
kName := fmt.Sprintf("%v%s", vbid, COLL_SUFFIX_KEYS)
ps := s.partitions[vbid]
if ps == nil {
return fmt.Errorf("compact missing parititon for vbid: %v", vbid)
}
ps.collsPauseSwap(func() (*gkvlite.Collection, *gkvlite.Collection) {
_, err = copyDelta(lastChanges[vbid].Key, cName, kName,
bsf.store.Snapshot(), compactStore, writeEvery)
if err != nil {
return s.coll(kName), s.coll(cName)
}
err = s.copyBucketStoreDeltas(bsf, compactStore,
vbids, vbidIdx+1, lastChanges, writeEvery, done)
if err != nil {
return s.coll(kName), s.coll(cName)
}
// If it all succeeded, then we will provide new
// collections to be used as we unwind / unpause.
return s.coll(kName), s.coll(cName)
})
return err
}