-
Notifications
You must be signed in to change notification settings - Fork 18.6k
/
boltdb.go
250 lines (216 loc) · 5.74 KB
/
boltdb.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
package boltdb
import (
"bytes"
"encoding/binary"
"errors"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
store "github.com/docker/docker/libnetwork/internal/kvstore"
bolt "go.etcd.io/bbolt"
)
var (
// ErrBoltBucketOptionMissing is thrown when boltBcuket config option is missing
ErrBoltBucketOptionMissing = errors.New("boltBucket config option missing")
)
const filePerm = 0o644
// BoltDB type implements the Store interface
type BoltDB struct {
mu sync.Mutex
client *bolt.DB
boltBucket []byte
dbIndex uint64
path string
timeout time.Duration
}
const (
libkvmetadatalen = 8
transientTimeout = time.Duration(10) * time.Second
)
// New opens a new BoltDB connection to the specified path and bucket
func New(endpoint string, options *store.Config) (store.Store, error) {
if (options == nil) || (len(options.Bucket) == 0) {
return nil, ErrBoltBucketOptionMissing
}
dir, _ := filepath.Split(endpoint)
if err := os.MkdirAll(dir, 0o750); err != nil {
return nil, err
}
db, err := bolt.Open(endpoint, filePerm, &bolt.Options{
Timeout: options.ConnectionTimeout,
})
if err != nil {
return nil, err
}
timeout := transientTimeout
if options.ConnectionTimeout != 0 {
timeout = options.ConnectionTimeout
}
b := &BoltDB{
client: db,
path: endpoint,
boltBucket: []byte(options.Bucket),
timeout: timeout,
}
return b, nil
}
// Put the key, value pair. index number metadata is prepended to the value
func (b *BoltDB) Put(key string, value []byte) error {
b.mu.Lock()
defer b.mu.Unlock()
return b.client.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists(b.boltBucket)
if err != nil {
return err
}
dbIndex := atomic.AddUint64(&b.dbIndex, 1)
dbval := make([]byte, libkvmetadatalen)
binary.LittleEndian.PutUint64(dbval, dbIndex)
dbval = append(dbval, value...)
return bucket.Put([]byte(key), dbval)
})
}
// Exists checks if the key exists inside the store
func (b *BoltDB) Exists(key string) (bool, error) {
b.mu.Lock()
defer b.mu.Unlock()
var exists bool
err := b.client.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.boltBucket)
if bucket == nil {
return store.ErrKeyNotFound
}
exists = len(bucket.Get([]byte(key))) > 0
return nil
})
if err != nil {
return false, err
}
if !exists {
return false, store.ErrKeyNotFound
}
return true, nil
}
// List returns the range of keys starting with the passed in prefix
func (b *BoltDB) List(keyPrefix string) ([]*store.KVPair, error) {
b.mu.Lock()
defer b.mu.Unlock()
var kv []*store.KVPair
err := b.client.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.boltBucket)
if bucket == nil {
return store.ErrKeyNotFound
}
cursor := bucket.Cursor()
prefix := []byte(keyPrefix)
for key, v := cursor.Seek(prefix); bytes.HasPrefix(key, prefix); key, v = cursor.Next() {
dbIndex := binary.LittleEndian.Uint64(v[:libkvmetadatalen])
v = v[libkvmetadatalen:]
val := make([]byte, len(v))
copy(val, v)
kv = append(kv, &store.KVPair{
Key: string(key),
Value: val,
LastIndex: dbIndex,
})
}
return nil
})
if err != nil {
return nil, err
}
if len(kv) == 0 {
return nil, store.ErrKeyNotFound
}
return kv, nil
}
// AtomicDelete deletes a value at "key" if the key
// has not been modified in the meantime, throws an
// error if this is the case
func (b *BoltDB) AtomicDelete(key string, previous *store.KVPair) error {
b.mu.Lock()
defer b.mu.Unlock()
if previous == nil {
return store.ErrPreviousNotSpecified
}
return b.client.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.boltBucket)
if bucket == nil {
return store.ErrKeyNotFound
}
val := bucket.Get([]byte(key))
if val == nil {
return store.ErrKeyNotFound
}
dbIndex := binary.LittleEndian.Uint64(val[:libkvmetadatalen])
if dbIndex != previous.LastIndex {
return store.ErrKeyModified
}
return bucket.Delete([]byte(key))
})
}
// Delete deletes a value at "key". Unlike AtomicDelete it doesn't check
// whether the deleted key is at a specific version before deleting.
func (b *BoltDB) Delete(key string) error {
b.mu.Lock()
defer b.mu.Unlock()
return b.client.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.boltBucket)
if bucket == nil || bucket.Get([]byte(key)) == nil {
return store.ErrKeyNotFound
}
return bucket.Delete([]byte(key))
})
}
// AtomicPut puts a value at "key" if the key has not been
// modified since the last Put, throws an error if this is the case
func (b *BoltDB) AtomicPut(key string, value []byte, previous *store.KVPair) (*store.KVPair, error) {
b.mu.Lock()
defer b.mu.Unlock()
var dbIndex uint64
dbval := make([]byte, libkvmetadatalen)
err := b.client.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.boltBucket)
if bucket == nil {
if previous != nil {
return store.ErrKeyNotFound
}
var err error
bucket, err = tx.CreateBucket(b.boltBucket)
if err != nil {
return err
}
}
// AtomicPut is equivalent to Put if previous is nil and the Ky
// doesn't exist in the DB.
val := bucket.Get([]byte(key))
if previous == nil && len(val) != 0 {
return store.ErrKeyExists
}
if previous != nil {
if len(val) == 0 {
return store.ErrKeyNotFound
}
dbIndex = binary.LittleEndian.Uint64(val[:libkvmetadatalen])
if dbIndex != previous.LastIndex {
return store.ErrKeyModified
}
}
dbIndex = atomic.AddUint64(&b.dbIndex, 1)
binary.LittleEndian.PutUint64(dbval, b.dbIndex)
dbval = append(dbval, value...)
return bucket.Put([]byte(key), dbval)
})
if err != nil {
return nil, err
}
return &store.KVPair{Key: key, Value: value, LastIndex: dbIndex}, nil
}
// Close the db connection to the BoltDB
func (b *BoltDB) Close() {
b.mu.Lock()
defer b.mu.Unlock()
b.client.Close()
}