-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
kv.go
534 lines (446 loc) · 12.2 KB
/
kv.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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package bolt
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"time"
errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors"
"github.com/influxdata/influxdb/v2/kit/tracing"
"github.com/influxdata/influxdb/v2/kv"
"github.com/influxdata/influxdb/v2/kv/migration"
"github.com/influxdata/influxdb/v2/kv/migration/all"
"github.com/influxdata/influxdb/v2/pkg/fs"
bolt "go.etcd.io/bbolt"
"go.uber.org/zap"
)
// check that *KVStore implement kv.SchemaStore interface.
var _ kv.SchemaStore = (*KVStore)(nil)
// KVStore is a kv.Store backed by boltdb.
type KVStore struct {
path string
mu sync.RWMutex
db *bolt.DB
log *zap.Logger
noSync bool
}
type KVOption func(*KVStore)
// WithNoSync WARNING: this is useful for tests only
// this skips fsyncing on every commit to improve
// write performance in exchange for no guarantees
// that the db will persist.
func WithNoSync(s *KVStore) {
s.noSync = true
}
// NewKVStore returns an instance of KVStore with the file at
// the provided path.
func NewKVStore(log *zap.Logger, path string, opts ...KVOption) *KVStore {
store := &KVStore{
path: path,
log: log,
}
for _, opt := range opts {
opt(store)
}
return store
}
// tempPath returns the path to the temporary file used by Restore().
func (s *KVStore) tempPath() string {
return s.path + ".tmp"
}
// Open creates boltDB file it doesn't exists and opens it otherwise.
func (s *KVStore) Open(ctx context.Context) error {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
// Ensure the required directory structure exists.
if err := os.MkdirAll(filepath.Dir(s.path), 0700); err != nil {
return fmt.Errorf("unable to create directory %s: %v", s.path, err)
}
if _, err := os.Stat(s.path); err != nil && !os.IsNotExist(err) {
return err
}
// Remove any temporary file created during a failed restore.
if err := os.Remove(s.tempPath()); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("unable to remove boltdb partial restore file: %w", err)
}
// Open database file.
if err := s.openDB(); err != nil {
return fmt.Errorf("unable to open boltdb file %v", err)
}
s.log.Info("Resources opened", zap.String("path", s.path))
return nil
}
func (s *KVStore) openDB() (err error) {
if s.db, err = bolt.Open(s.path, 0600, &bolt.Options{Timeout: 1 * time.Second}); err != nil {
return fmt.Errorf("unable to open boltdb file %v", err)
}
s.db.NoSync = s.noSync
return nil
}
// Close the connection to the bolt database
func (s *KVStore) Close() error {
if db := s.DB(); db != nil {
return db.Close()
}
return nil
}
func (s *KVStore) RLock() {
s.mu.RLock()
}
func (s *KVStore) RUnlock() {
s.mu.RUnlock()
}
// DB returns a reference to the current Bolt database.
func (s *KVStore) DB() *bolt.DB {
s.mu.RLock()
defer s.mu.RUnlock()
return s.db
}
// Flush removes all bolt keys within each bucket.
func (s *KVStore) Flush(ctx context.Context) {
_ = s.DB().Update(
func(tx *bolt.Tx) error {
return tx.ForEach(func(name []byte, b *bolt.Bucket) error {
s.cleanBucket(tx, b)
return nil
})
},
)
}
func (s *KVStore) cleanBucket(tx *bolt.Tx, b *bolt.Bucket) {
// nested bucket recursion base case:
if b == nil {
return
}
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
_ = v
if err := c.Delete(); err != nil {
// clean out nexted buckets
s.cleanBucket(tx, b.Bucket(k))
}
}
}
// WithDB sets the boltdb on the store.
func (s *KVStore) WithDB(db *bolt.DB) {
s.mu.Lock()
defer s.mu.Unlock()
s.db = db
}
// View opens up a view transaction against the store.
func (s *KVStore) View(ctx context.Context, fn func(tx kv.Tx) error) error {
span, ctx := tracing.StartSpanFromContext(ctx)
defer span.Finish()
err := s.DB().View(func(tx *bolt.Tx) error {
return fn(&Tx{
tx: tx,
ctx: ctx,
})
})
return errors2.BoltToInfluxError(err)
}
// Update opens up an update transaction against the store.
func (s *KVStore) Update(ctx context.Context, fn func(tx kv.Tx) error) error {
span, ctx := tracing.StartSpanFromContext(ctx)
defer span.Finish()
err := s.DB().Update(func(tx *bolt.Tx) error {
return fn(&Tx{
tx: tx,
ctx: ctx,
})
})
return errors2.BoltToInfluxError(err)
}
// CreateBucket creates a bucket in the underlying boltdb store if it
// does not already exist
func (s *KVStore) CreateBucket(ctx context.Context, name []byte) error {
return s.DB().Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists(name)
return errors2.BoltToInfluxError(err)
})
}
// DeleteBucket creates a bucket in the underlying boltdb store if it
// does not already exist
func (s *KVStore) DeleteBucket(ctx context.Context, name []byte) error {
return s.DB().Update(func(tx *bolt.Tx) error {
if err := tx.DeleteBucket(name); err != nil && !errors.Is(err, bolt.ErrBucketNotFound) {
return errors2.BoltToInfluxError(err)
}
return nil
})
}
// Backup copies all K:Vs to a writer, in BoltDB format.
func (s *KVStore) Backup(ctx context.Context, w io.Writer) error {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
return s.DB().View(func(tx *bolt.Tx) error {
_, err := tx.WriteTo(w)
return errors2.BoltToInfluxError(err)
})
}
// Restore replaces the underlying database with the data from r.
func (s *KVStore) Restore(ctx context.Context, r io.Reader) error {
if err := func() error {
f, err := os.Create(s.tempPath())
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(f, r); err != nil {
return err
} else if err := f.Sync(); err != nil {
return err
} else if err := f.Close(); err != nil {
return err
}
// Run the migrations on the restored database prior to swapping it in.
if err := s.migrateRestored(ctx); err != nil {
return err
}
// Swap and reopen under lock.
s.mu.Lock()
defer s.mu.Unlock()
if err := s.db.Close(); err != nil {
return err
}
// Atomically swap temporary file with current DB file.
if err := fs.RenameFileWithReplacement(s.tempPath(), s.path); err != nil {
return err
}
// Reopen with new database file.
return s.openDB()
}(); err != nil {
os.Remove(s.tempPath()) // clean up on error
return err
}
return nil
}
// migrateRestored opens the database at the temporary path and applies the
// migrations to it. The database at the temporary path is closed after the
// migrations are complete. This should be used as part of the restore
// operation, prior to swapping the restored database with the active database.
func (s *KVStore) migrateRestored(ctx context.Context) error {
restoredClient := NewClient(s.log.With(zap.String("service", "restored bolt")))
restoredClient.Path = s.tempPath()
if err := restoredClient.Open(ctx); err != nil {
return err
}
defer restoredClient.Close()
restoredKV := NewKVStore(s.log.With(zap.String("service", "restored kvstore-bolt")), s.tempPath())
restoredKV.WithDB(restoredClient.DB())
migrator, err := migration.NewMigrator(
s.log.With(zap.String("service", "bolt restore migrations")),
restoredKV,
all.Migrations[:]...,
)
if err != nil {
return err
}
return migrator.Up(ctx)
}
// Tx is a light wrapper around a boltdb transaction. It implements kv.Tx.
type Tx struct {
tx *bolt.Tx
ctx context.Context
}
// Context returns the context for the transaction.
func (tx *Tx) Context() context.Context {
return tx.ctx
}
// WithContext sets the context for the transaction.
func (tx *Tx) WithContext(ctx context.Context) {
tx.ctx = ctx
}
// Bucket retrieves the bucket named b.
func (tx *Tx) Bucket(b []byte) (kv.Bucket, error) {
bkt := tx.tx.Bucket(b)
if bkt == nil {
return nil, fmt.Errorf("bucket %q: %w", string(b), kv.ErrBucketNotFound)
}
return &Bucket{
bucket: bkt,
}, nil
}
// Bucket implements kv.Bucket.
type Bucket struct {
bucket *bolt.Bucket
}
// Get retrieves the value at the provided key.
func (b *Bucket) Get(key []byte) ([]byte, error) {
val := b.bucket.Get(key)
if len(val) == 0 {
return nil, kv.ErrKeyNotFound
}
return val, nil
}
// GetBatch retrieves the values for the provided keys.
func (b *Bucket) GetBatch(keys ...[]byte) ([][]byte, error) {
values := make([][]byte, len(keys))
for idx, key := range keys {
val := b.bucket.Get(key)
if len(val) == 0 {
continue
}
values[idx] = val
}
return values, nil
}
// Put sets the value at the provided key.
func (b *Bucket) Put(key []byte, value []byte) error {
err := b.bucket.Put(key, value)
if err == bolt.ErrTxNotWritable {
return kv.ErrTxNotWritable
}
return errors2.BoltToInfluxError(err)
}
// Delete removes the provided key.
func (b *Bucket) Delete(key []byte) error {
err := b.bucket.Delete(key)
if err == bolt.ErrTxNotWritable {
return kv.ErrTxNotWritable
}
return errors2.BoltToInfluxError(err)
}
// ForwardCursor retrieves a cursor for iterating through the entries
// in the key value store in a given direction (ascending / descending).
func (b *Bucket) ForwardCursor(seek []byte, opts ...kv.CursorOption) (kv.ForwardCursor, error) {
var (
cursor = b.bucket.Cursor()
config = kv.NewCursorConfig(opts...)
key, value []byte
)
if len(seek) == 0 && config.Direction == kv.CursorDescending {
seek, _ = cursor.Last()
}
key, value = cursor.Seek(seek)
if config.Prefix != nil && !bytes.HasPrefix(seek, config.Prefix) {
return nil, fmt.Errorf("seek bytes %q not prefixed with %q: %w", string(seek), string(config.Prefix), kv.ErrSeekMissingPrefix)
}
c := &Cursor{
cursor: cursor,
config: config,
}
// only remember first seeked item if not skipped
if !config.SkipFirst {
c.key = key
c.value = value
}
return c, nil
}
// Cursor retrieves a cursor for iterating through the entries
// in the key value store.
func (b *Bucket) Cursor(opts ...kv.CursorHint) (kv.Cursor, error) {
return &Cursor{
cursor: b.bucket.Cursor(),
}, nil
}
// Cursor is a struct for iterating through the entries
// in the key value store.
type Cursor struct {
cursor *bolt.Cursor
// previously seeked key/value
key, value []byte
config kv.CursorConfig
closed bool
seen int
}
// Close sets the closed to closed
func (c *Cursor) Close() error {
c.closed = true
return nil
}
// Seek seeks for the first key that matches the prefix provided.
func (c *Cursor) Seek(prefix []byte) ([]byte, []byte) {
if c.closed {
return nil, nil
}
k, v := c.cursor.Seek(prefix)
if len(k) == 0 && len(v) == 0 {
return nil, nil
}
return k, v
}
// First retrieves the first key value pair in the bucket.
func (c *Cursor) First() ([]byte, []byte) {
if c.closed {
return nil, nil
}
k, v := c.cursor.First()
if len(k) == 0 && len(v) == 0 {
return nil, nil
}
return k, v
}
// Last retrieves the last key value pair in the bucket.
func (c *Cursor) Last() ([]byte, []byte) {
if c.closed {
return nil, nil
}
k, v := c.cursor.Last()
if len(k) == 0 && len(v) == 0 {
return nil, nil
}
return k, v
}
// Next retrieves the next key in the bucket.
func (c *Cursor) Next() (k []byte, v []byte) {
if c.closed ||
c.atLimit() ||
(c.key != nil && c.missingPrefix(c.key)) {
return nil, nil
}
// get and unset previously seeked values if they exist
k, v, c.key, c.value = c.key, c.value, nil, nil
if len(k) > 0 || len(v) > 0 {
c.seen++
return
}
next := c.cursor.Next
if c.config.Direction == kv.CursorDescending {
next = c.cursor.Prev
}
k, v = next()
if (len(k) == 0 && len(v) == 0) || c.missingPrefix(k) {
return nil, nil
}
c.seen++
return k, v
}
// Prev retrieves the previous key in the bucket.
func (c *Cursor) Prev() (k []byte, v []byte) {
if c.closed ||
c.atLimit() ||
(c.key != nil && c.missingPrefix(c.key)) {
return nil, nil
}
// get and unset previously seeked values if they exist
k, v, c.key, c.value = c.key, c.value, nil, nil
if len(k) > 0 && len(v) > 0 {
c.seen++
return
}
prev := c.cursor.Prev
if c.config.Direction == kv.CursorDescending {
prev = c.cursor.Next
}
k, v = prev()
if (len(k) == 0 && len(v) == 0) || c.missingPrefix(k) {
return nil, nil
}
c.seen++
return k, v
}
func (c *Cursor) missingPrefix(key []byte) bool {
return c.config.Prefix != nil && !bytes.HasPrefix(key, c.config.Prefix)
}
func (c *Cursor) atLimit() bool {
return c.config.Limit != nil && c.seen >= *c.config.Limit
}
// Err always returns nil as nothing can go wrong™ during iteration
func (c *Cursor) Err() error {
return nil
}