zhangzengfei
2021-11-12 33cc2473a3d6ca941717c557f8e72b9904fbdc4f
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package boltcache
 
import (
    "errors"
    "github.com/boltdb/bolt"
    "strconv"
    "time"
)
 
const (
    // Permissions to use on the db file. This is only used if the
    // database file does not exist and needs to be created.
    dbFileMode = 0600
)
 
var (
    // Bucket names we perform transactions in
    dbConf = []byte(confBucket)
 
    // An error indicating a given key does not exist
    ErrKeyNotFound    = errors.New("not found")
    ErrLogNotFound    = errors.New("log not found")
    ErrBucketNotFound = errors.New("bucket not found")
)
 
// BoltStore provides access to BoltDB for Raft to store and retrieve
// log entries. It also provides key/value storage, and can be used as
// a LogStore and StableStore.
type BoltStore struct {
    // conn is the underlying handle to the db.
    conn *bolt.DB
 
    // The path to the Bolt database file
    path string
}
 
// Options contains all the configuration used to open the BoltDB
type Options struct {
    // Path is the file path to the BoltDB to use
    Path string
 
    // BoltOptions contains any specific BoltDB options you might
    // want to specify [e.g. open timeout]
    BoltOptions *bolt.Options
 
    // NoSync causes the database to skip fsync calls after each
    // write to the log. This is unsafe, so it should be used
    // with caution.
    NoSync bool
}
 
// readOnly returns true if the contained bolt options say to open
// the DB in readOnly mode [this can be useful to tools that want
// to examine the log]
func (o *Options) readOnly() bool {
    return o != nil && o.BoltOptions != nil && o.BoltOptions.ReadOnly
}
 
// NewBoltStore takes a file path and returns a connected Raft backend.
func NewBoltStore(path string) (*BoltStore, error) {
    return New(Options{Path: path})
}
 
// New uses the supplied options to open the BoltDB and prepare it for use as a raft backend.
func New(options Options) (*BoltStore, error) {
    // Try to connect
    handle, err := bolt.Open(options.Path, dbFileMode, options.BoltOptions)
    if err != nil {
        return nil, err
    }
    handle.NoSync = options.NoSync
 
    // Create the new store
    store := &BoltStore{
        conn: handle,
        path: options.Path,
    }
 
    // If the store was opened read-only, don't try and create buckets
    if !options.readOnly() {
        // Set up our buckets
        if err := store.initialize(); err != nil {
            store.Close()
            return nil, err
        }
    }
    return store, nil
}
 
// initialize is used to set up all of the buckets.
func (b *BoltStore) initialize() error {
    tx, err := b.conn.Begin(true)
    if err != nil {
        return err
    }
    defer tx.Rollback()
 
    if _, err := tx.CreateBucketIfNotExists(dbConf); err != nil {
        return err
    }
 
    return tx.Commit()
}
 
// Close is used to gracefully close the DB connection.
func (b *BoltStore) Close() error {
    return b.conn.Close()
}
 
// FirstIndex returns the first known index from the Raft log.
func (b *BoltStore) FirstIndex(bucketName string) (uint64, error) {
    tx, err := b.conn.Begin(false)
    if err != nil {
        return 0, err
    }
    defer tx.Rollback()
 
    bucket := tx.Bucket([]byte(bucketName))
    if bucket == nil {
        return 0, ErrBucketNotFound
    }
 
    curs := bucket.Cursor()
    if first, _ := curs.First(); first == nil {
        return 0, nil
    } else {
        return bytesToUint64(first), nil
    }
}
 
// LastIndex returns the last known index from the Raft log.
func (b *BoltStore) LastIndex(bucketName string) (uint64, error) {
    tx, err := b.conn.Begin(false)
    if err != nil {
        return 0, err
    }
    defer tx.Rollback()
    bucket := tx.Bucket([]byte(bucketName))
    if bucket == nil {
        return 0, ErrBucketNotFound
    }
    curs := bucket.Cursor()
    if last, _ := curs.Last(); last == nil {
        return 0, nil
    } else {
        return bytesToUint64(last), nil
    }
}
 
// GetLog is used to retrieve a log from BoltDB at a given index.
func (b *BoltStore) GetLog(bucketName string, idx uint64, log *Log) error {
    tx, err := b.conn.Begin(false)
    if err != nil {
        return err
    }
    defer tx.Rollback()
 
    bucket := tx.Bucket([]byte(bucketName))
    if bucket == nil {
        return ErrBucketNotFound
    }
    val := bucket.Get(uint64ToBytes(idx))
 
    if val == nil {
        return ErrLogNotFound
    }
    return decodeMsgPack(val, log)
}
 
func (b *BoltStore) GetConfLog(idx uint64, clog *confLog) error {
    tx, err := b.conn.Begin(false)
    if err != nil {
        return err
    }
    defer tx.Rollback()
 
    bucket := tx.Bucket([]byte(confBucket))
    val := bucket.Get(uint64ToBytes(idx))
 
    if val == nil {
        return ErrLogNotFound
    }
    return decodeMsgPack(val, clog)
}
 
// StoreLog is used to store a single raft log
func (b *BoltStore) StoreLog(bucketName string, log *Log) error {
    return b.StoreLogs(bucketName, []*Log{log})
}
 
// StoreLogs is used to store a set of raft logs
func (b *BoltStore) StoreLogs(bucketName string, logs []*Log) error {
    tx, err := b.conn.Begin(true)
    if err != nil {
        return err
    }
    defer tx.Rollback()
 
    for _, log := range logs {
        key := uint64ToBytes(log.Index)
        val, err := encodeMsgPack(log)
        if err != nil {
            return err
        }
        bucket := tx.Bucket([]byte(bucketName))
        if bucket == nil {
            bucket, err = tx.CreateBucket([]byte(bucketName))
            if err != nil {
                return err
            }
        }
        if err := bucket.Put(key, val.Bytes()); err != nil {
            return err
        }
    }
 
    return tx.Commit()
}
 
// DeleteRange is used to delete logs within a given range inclusively.
func (b *BoltStore) DeleteRange(bucketName string, min, max uint64) error {
    minKey := uint64ToBytes(min)
 
    tx, err := b.conn.Begin(true)
    if err != nil {
        return err
    }
    defer tx.Rollback()
 
    curs := tx.Bucket([]byte(bucketName)).Cursor()
    for k, _ := curs.Seek(minKey); k != nil; k, _ = curs.Next() {
        // Handle out-of-range log index
        if bytesToUint64(k) > max {
            break
        }
 
        // Delete in-range log index
        if err := curs.Delete(); err != nil {
            return err
        }
    }
 
    return tx.Commit()
}
 
func (b *BoltStore) ForEach(f func(v []byte) error) {
    tx, err := b.conn.Begin(true)
    if err != nil {
        return
    }
    defer tx.Rollback()
 
    start, _ := b.FirstIndex(confBucket)
    end, _ := b.LastIndex(confBucket)
 
    for ; start <= end; start++ {
        bucketName := bucketPre + strconv.Itoa(int(start))
        bucket := tx.Bucket([]byte(bucketName))
        if bucket == nil {
            return
        }
 
        bucket.ForEach(func(k, v []byte) error {
            log := &Log{}
            err := decodeMsgPack(v, log)
            f(log.Data)
            return err
        })
    }
}
 
func (b *BoltStore) Delete(lc *LogCon) error {
    tx, err := b.conn.Begin(true)
    if err != nil {
        return err
    }
    defer tx.Rollback()
    bucket := tx.Bucket([]byte(lc.conf.BucketName))
    dc := false
    if bucket != nil {
        if lc.Log != nil {
            if dErr := bucket.Delete(uint64ToBytes(lc.Log.Index)); dErr != nil {
                return dErr
            }
        }
 
        size := 0
        bucket.ForEach(func(k, v []byte) error {
            size++
            return nil
        })
        if size == 0 {
            dc = true
        }
    } else {
        dc = true
    }
    if dc {
        cb := tx.Bucket([]byte(confBucket))
        if cb != nil {
            cbSize := 0
            cb.ForEach(func(k, v []byte) error {
                cbSize++
                return nil
            })
            if cbSize > 1 {
                if dErr := cb.Delete(uint64ToBytes(uint64(lc.conf.Index))); dErr != nil {
                    return dErr
                }
            }
        }
    }
    tx.Commit()
    return nil
}
 
func (b *BoltStore) UpdateTime(bucketName string, t time.Time) error {
    tx, err := b.conn.Begin(true)
    if err != nil {
        return err
    }
    defer tx.Rollback()
    bucket := tx.Bucket([]byte(confBucket))
    if bucket != nil {
        flag := false
        bucket.ForEach(func(k, v []byte) error {
            cLog := &confLog{}
            if de := decodeMsgPack(v, cLog); de == nil {
                if cLog.BucketName == bucketName {
                    cLog.UpdateTime = t
                    cLog.Index = int(bytesToUint64(k))
                    val, err := encodeMsgPack(cLog)
                    if err == nil {
                        if bucket.Put(k, val.Bytes()) == nil {
                            flag = true
                        }
                    }
                }
            }
            return nil
        })
        if !flag {
            return errors.New("conf表中未找到" + bucketName)
        }
    } else {
        return ErrBucketNotFound
    }
    tx.Commit()
    return nil
}
 
func (b *BoltStore) Clean(conf *Config) ([]string, []string, error) {
    type kConfLog struct {
        k   []byte
        log *confLog
    }
    tx, err := b.conn.Begin(true)
    if err != nil {
        return nil, nil, err
    }
    defer tx.Rollback()
    bucket := tx.Bucket([]byte(confBucket))
    var delBucketNames []string
    var delErrBucketNames []string
    if bucket != nil {
        var allCLogs []*kConfLog
        bucket.ForEach(func(k, v []byte) error {
            cLog := &confLog{}
            if e := decodeMsgPack(v, cLog); e == nil {
                allCLogs = append(allCLogs, &kConfLog{
                    k:   k,
                    log: cLog,
                })
            }
            return nil
        })
        var leftClogs []*kConfLog
        if len(allCLogs) > conf.bucketLimit {
            arr := allCLogs[:len(allCLogs)-conf.bucketLimit]
            leftClogs = allCLogs[len(allCLogs)-conf.bucketLimit:]
            for _, a := range arr {
                if de := tx.DeleteBucket([]byte(a.log.BucketName)); de != nil {
                    delErrBucketNames = append(delErrBucketNames, a.log.BucketName)
                } else {
                    bucket.Delete(a.k)
                    delBucketNames = append(delBucketNames, a.log.BucketName)
                }
            }
        } else {
            leftClogs = allCLogs
        }
        if len(leftClogs) > 1 {
            leftClogs = leftClogs[:len(leftClogs)-1]
            for _, a := range leftClogs {
                if int(time.Now().Sub(a.log.UpdateTime).Hours()) > conf.keepDays*24 {
                    if de := tx.DeleteBucket([]byte(a.log.BucketName)); de != nil {
                        delErrBucketNames = append(delErrBucketNames, a.log.BucketName)
                    } else {
                        bucket.Delete(a.k)
                        delBucketNames = append(delBucketNames, a.log.BucketName)
                    }
                }
            }
        }
 
    } else {
        return nil, nil, errors.New("bucket not found")
    }
    tx.Commit()
    return delBucketNames, delErrBucketNames, nil
}
 
// Set is used to set a key/value set outside of the raft log
func (b *BoltStore) Set(k, v []byte) error {
    tx, err := b.conn.Begin(true)
    if err != nil {
        return err
    }
    defer tx.Rollback()
 
    bucket := tx.Bucket(dbConf)
    if err := bucket.Put(k, v); err != nil {
        return err
    }
 
    return tx.Commit()
}
 
func (b *BoltStore) Size(bucketName string) (int, error) {
    tx, err := b.conn.Begin(false)
    if err != nil {
        return 0, err
    }
    defer tx.Rollback()
 
    bucket := tx.Bucket([]byte(bucketName))
    if bucket == nil {
        return 0, ErrBucketNotFound
    }
    size := 0
    bucket.ForEach(func(k, v []byte) error {
        size++
        return nil
    })
    return size, nil
}
 
// Get is used to retrieve a value from the k/v store by key
func (b *BoltStore) Get(k []byte) ([]byte, error) {
    tx, err := b.conn.Begin(false)
    if err != nil {
        return nil, err
    }
    defer tx.Rollback()
 
    bucket := tx.Bucket(dbConf)
    val := bucket.Get(k)
 
    if val == nil {
        return nil, ErrKeyNotFound
    }
    return append([]byte(nil), val...), nil
}
 
// SetUint64 is like Set, but handles uint64 values
func (b *BoltStore) SetUint64(key []byte, val uint64) error {
    return b.Set(key, uint64ToBytes(val))
}
 
// GetUint64 is like Get, but handles uint64 values
func (b *BoltStore) GetUint64(key []byte) (uint64, error) {
    val, err := b.Get(key)
    if err != nil {
        return 0, err
    }
    return bytesToUint64(val), nil
}
 
// Sync performs an fsync on the database file handle. This is not necessary
// under normal operation unless NoSync is enabled, in which this forces the
// database file to sync against the disk.
func (b *BoltStore) Sync() error {
    return b.conn.Sync()
}