forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
boltbk.go
383 lines (344 loc) · 9.54 KB
/
boltbk.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
/*
Copyright 2015 Gravitational, Inc.
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 boltbk
import (
"encoding/json"
"path/filepath"
"sort"
"sync"
"time"
"github.com/boltdb/bolt"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
)
const (
// keysBoltFile is the BoltDB database file, usually stored in data_dir
keysBoltFile = "keys.db"
// openTimeout determines for how long BoltDB will wait before giving up
// opening the locked DB file
openTimeout = 5 * time.Second
// openFileMode flag is passed to db.Open()
openFileMode = 0600
)
// BoltBackend is a boltdb-based backend used in tests and standalone mode
type BoltBackend struct {
sync.Mutex
db *bolt.DB
clock clockwork.Clock
locks map[string]time.Time
}
// GetName() is a part of the backend API and returns the name of this backend
// as shown in 'storage/type' section of Teleport YAML config
func GetName() string {
return "bolt"
}
// New initializes and returns a fully created BoltDB backend. It's
// a properly implemented Backend.NewFunc, part of a backend API
func New(params backend.Params) (backend.Backend, error) {
// look at 'path' parameter, if it's missing use 'data_dir' (default):
path := params.GetString("path")
if len(path) == 0 {
path = params.GetString(teleport.DataDirParameterName)
}
// still nothing? return an error:
if path == "" {
return nil, trace.BadParameter("BoltDB backend: 'path' is not set")
}
if !utils.IsDir(path) {
return nil, trace.BadParameter("%v is not a valid directory", path)
}
path, err := filepath.Abs(filepath.Join(path, keysBoltFile))
if err != nil {
return nil, trace.Wrap(err)
}
db, err := bolt.Open(path, openFileMode, &bolt.Options{Timeout: openTimeout})
if err != nil {
if err == bolt.ErrTimeout {
return nil, trace.Errorf("Local storage is locked. Another instance is running? (%v)", path)
}
return nil, trace.Wrap(err)
}
return &BoltBackend{
locks: make(map[string]time.Time),
clock: clockwork.NewRealClock(),
db: db,
}, nil
}
// Clock returns clock assigned to the backend
func (b *BoltBackend) Clock() clockwork.Clock {
return b.clock
}
// Close closes the backend resources
func (b *BoltBackend) Close() error {
return b.db.Close()
}
func (b *BoltBackend) GetKeys(path []string) ([]string, error) {
keys, err := b.getKeys(path)
if err != nil {
if trace.IsNotFound(err) {
return nil, nil
}
return nil, trace.Wrap(err)
}
// now do an iteration to expire keys
for _, key := range keys {
b.GetVal(path, key)
}
keys, err = b.getKeys(path)
if err != nil {
return nil, trace.Wrap(err)
}
sort.Sort(sort.StringSlice(keys))
return keys, nil
}
func (b *BoltBackend) UpsertVal(path []string, key string, val []byte, ttl time.Duration) error {
return b.upsertVal(path, key, val, ttl)
}
func (b *BoltBackend) CreateVal(bucket []string, key string, val []byte, ttl time.Duration) error {
v := &kv{
Created: b.clock.Now().UTC(),
Value: val,
TTL: ttl,
}
bytes, err := json.Marshal(v)
if err != nil {
return trace.Wrap(err)
}
err = b.createKey(bucket, key, bytes)
return trace.Wrap(err)
}
func (b *BoltBackend) upsertVal(path []string, key string, val []byte, ttl time.Duration) error {
v := &kv{
Created: b.clock.Now().UTC(),
Value: val,
TTL: ttl,
}
bytes, err := json.Marshal(v)
if err != nil {
return trace.Wrap(err)
}
return b.upsertKey(path, key, bytes)
}
func (b *BoltBackend) GetVal(path []string, key string) ([]byte, error) {
var val []byte
if err := b.getKey(path, key, &val); err != nil {
return nil, trace.Wrap(err)
}
var k *kv
if err := json.Unmarshal(val, &k); err != nil {
return nil, trace.Wrap(err)
}
if k.TTL != 0 && b.clock.Now().UTC().Sub(k.Created) > k.TTL {
if err := b.deleteKey(path, key); err != nil {
return nil, err
}
return nil, trace.NotFound("%v: %v not found", path, key)
}
return k.Value, nil
}
func (b *BoltBackend) DeleteKey(path []string, key string) error {
b.Lock()
defer b.Unlock()
return b.deleteKey(path, key)
}
func (b *BoltBackend) DeleteBucket(path []string, bucket string) error {
b.Lock()
defer b.Unlock()
return b.deleteBucket(path, bucket)
}
func (b *BoltBackend) deleteBucket(buckets []string, bucket string) error {
return b.db.Update(func(tx *bolt.Tx) error {
if len(buckets) == 0 {
return boltErr(tx.DeleteBucket([]byte(bucket)))
}
bkt, err := GetBucket(tx, buckets)
if err != nil {
return trace.Wrap(err)
}
if bkt.Bucket([]byte(bucket)) == nil {
return trace.NotFound("%v not found", bucket)
}
return boltErr(bkt.DeleteBucket([]byte(bucket)))
})
}
func (b *BoltBackend) deleteKey(buckets []string, key string) error {
return b.db.Update(func(tx *bolt.Tx) error {
bkt, err := GetBucket(tx, buckets)
if err != nil {
return trace.Wrap(err)
}
if bkt.Get([]byte(key)) == nil {
return trace.NotFound("%v is not found", key)
}
return boltErr(bkt.Delete([]byte(key)))
})
}
func (b *BoltBackend) upsertKey(buckets []string, key string, bytes []byte) error {
return b.db.Update(func(tx *bolt.Tx) error {
bkt, err := UpsertBucket(tx, buckets)
if err != nil {
return trace.Wrap(err)
}
return boltErr(bkt.Put([]byte(key), bytes))
})
}
func (b *BoltBackend) createKey(buckets []string, key string, bytes []byte) error {
return b.db.Update(func(tx *bolt.Tx) error {
bkt, err := UpsertBucket(tx, buckets)
if err != nil {
return trace.Wrap(err)
}
val := bkt.Get([]byte(key))
if val != nil {
return trace.AlreadyExists("'%v' already exists", key)
}
return boltErr(bkt.Put([]byte(key), bytes))
})
}
func (b *BoltBackend) upsertJSONKey(buckets []string, key string, val interface{}) error {
bytes, err := json.Marshal(val)
if err != nil {
return trace.Wrap(err)
}
return b.db.Update(func(tx *bolt.Tx) error {
bkt, err := UpsertBucket(tx, buckets)
if err != nil {
return trace.Wrap(err)
}
return boltErr(bkt.Put([]byte(key), bytes))
})
}
func (b *BoltBackend) getJSONKey(buckets []string, key string, val interface{}) error {
return b.db.View(func(tx *bolt.Tx) error {
bkt, err := GetBucket(tx, buckets)
if err != nil {
return trace.Wrap(err)
}
bytes := bkt.Get([]byte(key))
if bytes == nil {
return trace.NotFound("%v %v not found", buckets, key)
}
return json.Unmarshal(bytes, val)
})
}
func (b *BoltBackend) getKey(buckets []string, key string, val *[]byte) error {
return b.db.View(func(tx *bolt.Tx) error {
bkt, err := GetBucket(tx, buckets)
if err != nil {
return trace.Wrap(err)
}
bytes := bkt.Get([]byte(key))
if bytes == nil {
_, err := GetBucket(tx, append(buckets, key))
if err == nil {
return trace.BadParameter("key %q is a bucket", key)
}
return trace.NotFound("%v %v not found", buckets, key)
}
*val = make([]byte, len(bytes))
copy(*val, bytes)
return nil
})
}
func (b *BoltBackend) getKeys(buckets []string) ([]string, error) {
out := []string{}
err := b.db.View(func(tx *bolt.Tx) error {
bkt, err := GetBucket(tx, buckets)
if err != nil {
return trace.Wrap(err)
}
c := bkt.Cursor()
for k, _ := c.First(); k != nil; k, _ = c.Next() {
out = append(out, string(k))
}
return nil
})
if err != nil {
return nil, trace.Wrap(boltErr(err))
}
return out, nil
}
func UpsertBucket(b *bolt.Tx, buckets []string) (*bolt.Bucket, error) {
bkt, err := b.CreateBucketIfNotExists([]byte(buckets[0]))
if err != nil {
return nil, trace.Wrap(err)
}
for _, key := range buckets[1:] {
bkt, err = bkt.CreateBucketIfNotExists([]byte(key))
if err != nil {
return nil, trace.Wrap(err)
}
}
return bkt, nil
}
func GetBucket(b *bolt.Tx, buckets []string) (*bolt.Bucket, error) {
bkt := b.Bucket([]byte(buckets[0]))
if bkt == nil {
return nil, trace.NotFound("bucket %v not found", buckets[0])
}
for _, key := range buckets[1:] {
bkt = bkt.Bucket([]byte(key))
if bkt == nil {
return nil, trace.NotFound("bucket %v not found", key)
}
}
return bkt, nil
}
func (b *BoltBackend) AcquireLock(token string, ttl time.Duration) error {
for {
b.Lock()
expires, ok := b.locks[token]
if ok && (expires.IsZero() || expires.After(b.clock.Now().UTC())) {
b.Unlock()
b.clock.Sleep(100 * time.Millisecond)
} else {
if ttl == 0 {
b.locks[token] = time.Time{}
} else {
b.locks[token] = b.clock.Now().UTC().Add(ttl)
}
b.Unlock()
return nil
}
}
}
func (b *BoltBackend) ReleaseLock(token string) error {
b.Lock()
defer b.Unlock()
expires, ok := b.locks[token]
if !ok || (!expires.IsZero() && expires.Before(b.clock.Now().UTC())) {
return trace.NotFound("lock %v is deleted or expired", token)
}
delete(b.locks, token)
return nil
}
type kv struct {
Created time.Time `json:"created"`
TTL time.Duration `json:"ttl"`
Value []byte `json:"val"`
}
func boltErr(err error) error {
if err == bolt.ErrBucketNotFound {
return trace.NotFound(err.Error())
}
if err == bolt.ErrBucketExists {
return trace.AlreadyExists(err.Error())
}
if err == bolt.ErrDatabaseNotOpen {
return trace.ConnectionProblem(err, "database is not open")
}
return err
}