/
kvstores.go
466 lines (395 loc) · 13.1 KB
/
kvstores.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
package firewalldb
import (
"context"
"github.com/lightninglabs/lightning-terminal/session"
"go.etcd.io/bbolt"
)
/*
The KVStores are stored in the following structure in the KV db. Note that
the `perm` and `temp` buckets are identical in structure. The only difference is
that the `temp` bucket is cleared on restart of the db.
rules -> perm -> rule-name -> global -> {k:v}
-> sessions -> group ID -> session-kv-store -> {k:v}
-> feature-kv-stores -> feature-name -> {k:v}
-> temp -> rule-name -> global -> {k:v}
-> sessions -> group ID -> session-kv-store -> {k:v}
-> feature-kv-stores -> feature-name -> {k:v}
*/
var (
// rulesBucketKey is the key under which all things rule-kvstore
// related will fall.
rulesBucketKey = []byte("rules")
// permBucketKey is a sub bucket under the rules bucket. Everything
// stored under this key is persisted across restarts.
permBucketKey = []byte("perm")
// tempBucketKey is a sub bucket under the rules bucket. Everything
// stored under this key is cleared on restart of the db.
tempBucketKey = []byte("temp")
// globalKVStoreBucketKey is a key under which a kv store is that will
// always be available to a specific rule regardless of which session
// or feature is being evaluated.
globalKVStoreBucketKey = []byte("global")
// sessKVStoreBucketKey is the key under which a session wide kv store
// for the rule is stored.
sessKVStoreBucketKey = []byte("session-kv-store")
// featureKVStoreBucketKey is the kye under which a kv store specific
// the group id and feature name is stored.
featureKVStoreBucketKey = []byte("feature-kv-store")
)
// KVStores provides an Update and View method that will allow the caller to
// perform atomic read and write transactions on and of the key value stores
// offered the KVStoreTx.
type KVStores interface {
// Update opens a database read/write transaction and executes the
// function f with the transaction passed as a parameter. After f exits,
// if f did not error, the transaction is committed. Otherwise, if f did
// error, the transaction is rolled back. If the rollback fails, the
// original error returned by f is still returned. If the commit fails,
// the commit error is returned.
Update(f func(tx KVStoreTx) error) error
// View opens a database read transaction and executes the function f
// with the transaction passed as a parameter. After f exits, the
// transaction is rolled back. If f errors, its error is returned, not a
// rollback error (if any occur).
View(f func(tx KVStoreTx) error) error
}
// KVStoreTx represents a database transaction that can be used for both read
// and writes of the various different key value stores offered for the rule.
type KVStoreTx interface {
// Global returns a persisted global, rule-name indexed, kv store. A
// rule with a given name will have access to this store independent of
// group ID or feature.
Global() KVStore
// Local returns a persisted local kv store for the rule. Depending on
// how the implementation is initialised, this will either be under the
// group ID namespace or the group ID _and_ feature name namespace.
Local() KVStore
// GlobalTemp is similar to the Global store except that its contents
// is cleared upon restart of the database.
GlobalTemp() KVStore
// LocalTemp is similar to the Local store except that its contents is
// cleared upon restart of the database.
LocalTemp() KVStore
}
// KVStore is in interface representing a key value store. It allows us to
// abstract away the details of the data storage method.
type KVStore interface {
// Get fetches the value under the given key from the underlying kv
// store. If no value is found, nil is returned.
Get(ctx context.Context, key string) ([]byte, error)
// Set sets the given key-value pair in the underlying kv store.
Set(ctx context.Context, key string, value []byte) error
// Del deletes the value under the given key in the underlying kv store.
Del(ctx context.Context, key string) error
}
// RulesDB can be used to initialise a new rules.KVStores.
type RulesDB interface {
GetKVStores(rule string, groupID session.ID, feature string) KVStores
}
// GetKVStores constructs a new rules.KVStores backed by a bbolt db.
func (db *DB) GetKVStores(rule string, groupID session.ID,
feature string) KVStores {
return &kvStores{
DB: db,
ruleName: rule,
groupID: groupID,
featureName: feature,
}
}
// kvStores implements the rules.KVStores interface.
type kvStores struct {
*DB
ruleName string
groupID session.ID
featureName string
}
// beginTx starts db transaction. The transaction will be a read or read-write
// transaction depending on the value of the `writable` parameter.
func (s *kvStores) beginTx(writable bool) (*kvStoreTx, error) {
boltTx, err := s.Begin(writable)
if err != nil {
return nil, err
}
return &kvStoreTx{
kvStores: s,
boltTx: boltTx,
}, nil
}
// Update opens a database read/write transaction and executes the function f
// with the transaction passed as a parameter. After f exits, if f did not
// error, the transaction is committed. Otherwise, if f did error, the
// transaction is rolled back. If the rollback fails, the original error
// returned by f is still returned. If the commit fails, the commit error is
// returned.
//
// NOTE: this is part of the KVStores interface.
func (s *kvStores) Update(f func(tx KVStoreTx) error) error {
tx, err := s.beginTx(true)
if err != nil {
return err
}
// Make sure the transaction rolls back in the event of a panic.
defer func() {
if tx != nil {
_ = tx.boltTx.Rollback()
}
}()
err = f(tx)
if err != nil {
// Want to return the original error, not a rollback error if
// any occur.
_ = tx.boltTx.Rollback()
return err
}
return tx.boltTx.Commit()
}
// View opens a database read transaction and executes the function f with the
// transaction passed as a parameter. After f exits, the transaction is rolled
// back. If f errors, its error is returned, not a rollback error (if any
// occur).
//
// NOTE: this is part of the KVStores interface.
func (s *kvStores) View(f func(tx KVStoreTx) error) error {
tx, err := s.beginTx(false)
if err != nil {
return err
}
// Make sure the transaction rolls back in the event of a panic.
defer func() {
if tx != nil {
_ = tx.boltTx.Rollback()
}
}()
err = f(tx)
rollbackErr := tx.boltTx.Rollback()
if err != nil {
return err
}
if rollbackErr != nil {
return rollbackErr
}
return nil
}
// getBucketFunc defines the signature of the bucket creation/fetching function
// required by kvStoreTx. If create is true, then all the bucket (and all
// buckets leading up to the bucket) should be created if they do not already
// exist. Otherwise, if the bucket or any leading up to it does not yet exist
// then nil is returned.
type getBucketFunc func(tx *bbolt.Tx, create bool) (*bbolt.Bucket, error)
// kvStoreTx represents an open transaction of kvStores.
// This implements the KVStoreTX interface.
type kvStoreTx struct {
boltTx *bbolt.Tx
getBucket getBucketFunc
*kvStores
}
// Global gives the caller access to the global kv store of the rule.
//
// NOTE: this is part of the rules.KVStoreTx interface.
func (tx *kvStoreTx) Global() KVStore {
return &kvStoreTx{
kvStores: tx.kvStores,
boltTx: tx.boltTx,
getBucket: getGlobalRuleBucket(true, tx.ruleName),
}
}
// Local gives the caller access to the local kv store of the rule. This will
// either be a session wide kv store or a feature specific one depending on
// how the kv store was initialised.
//
// NOTE: this is part of the KVStoreTx interface.
func (tx *kvStoreTx) Local() KVStore {
fn := getSessionRuleBucket(true, tx.ruleName, tx.groupID)
if tx.featureName != "" {
fn = getSessionFeatureRuleBucket(
true, tx.ruleName, tx.groupID, tx.featureName,
)
}
return &kvStoreTx{
kvStores: tx.kvStores,
boltTx: tx.boltTx,
getBucket: fn,
}
}
// GlobalTemp gives the caller access to the temporary global kv store of the
// rule.
//
// NOTE: this is part of the KVStoreTx interface.
func (tx *kvStoreTx) GlobalTemp() KVStore {
return &kvStoreTx{
kvStores: tx.kvStores,
boltTx: tx.boltTx,
getBucket: getGlobalRuleBucket(false, tx.ruleName),
}
}
// LocalTemp gives the caller access to the temporary local kv store of the
// rule.
//
// NOTE: this is part of the KVStoreTx interface.
func (tx *kvStoreTx) LocalTemp() KVStore {
fn := getSessionRuleBucket(true, tx.ruleName, tx.groupID)
if tx.featureName != "" {
fn = getSessionFeatureRuleBucket(
false, tx.ruleName, tx.groupID, tx.featureName,
)
}
return &kvStoreTx{
kvStores: tx.kvStores,
boltTx: tx.boltTx,
getBucket: fn,
}
}
// Get fetches the value under the given key from the underlying kv store.
// If no value is found, nil is returned.
//
// NOTE: this is part of the KVStore interface.
func (tx *kvStoreTx) Get(_ context.Context, key string) ([]byte, error) {
bucket, err := tx.getBucket(tx.boltTx, false)
if err != nil {
return nil, err
}
if bucket == nil {
return nil, nil
}
return bucket.Get([]byte(key)), nil
}
// Set sets the given key-value pair in the underlying kv store.
//
// NOTE: this is part of the KVStore interface.
func (tx *kvStoreTx) Set(_ context.Context, key string, value []byte) error {
bucket, err := tx.getBucket(tx.boltTx, true)
if err != nil {
return err
}
return bucket.Put([]byte(key), value)
}
// Del deletes the value under the given key in the underlying kv store.
//
// NOTE: this is part of the .KVStore interface.
func (tx *kvStoreTx) Del(_ context.Context, key string) error {
bucket, err := tx.getBucket(tx.boltTx, false)
if err != nil {
return err
}
if bucket == nil {
return nil
}
return bucket.Delete([]byte(key))
}
func getMainBucket(tx *bbolt.Tx, create, perm bool) (*bbolt.Bucket, error) {
mainBucket, err := getBucket(tx, rulesBucketKey)
if err != nil {
return nil, err
}
key := tempBucketKey
if perm {
key = permBucketKey
}
if create {
return mainBucket.CreateBucketIfNotExists(key)
}
return mainBucket.Bucket(key), nil
}
// getRuleBucket returns a function that can be used to access the bucket for
// a given rule name. The `perm` param determines if the temporary or permanent
// store is used.
func getRuleBucket(perm bool, ruleName string) getBucketFunc {
return func(tx *bbolt.Tx, create bool) (*bbolt.Bucket, error) {
mainBucket, err := getMainBucket(tx, create, perm)
if err != nil {
return nil, err
}
if create {
return mainBucket.CreateBucketIfNotExists(
[]byte(ruleName),
)
} else if mainBucket == nil {
return nil, nil
}
return mainBucket.Bucket([]byte(ruleName)), nil
}
}
// getGlobalRuleBucket returns a function that can be used to access the global
// kv store of the given rule name. The `perm` param determines if the temporary
// or permanent store is used.
func getGlobalRuleBucket(perm bool, ruleName string) getBucketFunc {
return func(tx *bbolt.Tx, create bool) (*bbolt.Bucket, error) {
ruleBucket, err := getRuleBucket(perm, ruleName)(tx, create)
if err != nil {
return nil, err
}
if ruleBucket == nil && !create {
return nil, nil
}
if create {
return ruleBucket.CreateBucketIfNotExists(
globalKVStoreBucketKey,
)
}
return ruleBucket.Bucket(globalKVStoreBucketKey), nil
}
}
// getSessionRuleBucket returns a function that can be used to fetch the
// bucket under which a kv store for a specific rule-name and group ID is
// stored. The `perm` param determines if the temporary or permanent store is
// used.
func getSessionRuleBucket(perm bool, ruleName string,
groupID session.ID) getBucketFunc {
return func(tx *bbolt.Tx, create bool) (*bbolt.Bucket, error) {
ruleBucket, err := getRuleBucket(perm, ruleName)(tx, create)
if err != nil {
return nil, err
}
if ruleBucket == nil && !create {
return nil, nil
}
if create {
sessBucket, err := ruleBucket.CreateBucketIfNotExists(
sessKVStoreBucketKey,
)
if err != nil {
return nil, err
}
return sessBucket.CreateBucketIfNotExists(groupID[:])
}
sessBucket := ruleBucket.Bucket(sessKVStoreBucketKey)
if sessBucket == nil {
return nil, nil
}
return sessBucket.Bucket(groupID[:]), nil
}
}
// getSessionFeatureRuleBucket returns a function that can be used to fetch the
// bucket under which a kv store for a specific rule-name, group ID and
// feature name is stored. The `perm` param determines if the temporary or
// permanent store is used.
func getSessionFeatureRuleBucket(perm bool, ruleName string,
groupID session.ID, featureName string) getBucketFunc {
return func(tx *bbolt.Tx, create bool) (*bbolt.Bucket, error) {
sessBucket, err := getSessionRuleBucket(
perm, ruleName, groupID,
)(tx, create)
if err != nil {
return nil, err
}
if sessBucket == nil && !create {
return nil, nil
}
if create {
featureBucket, err := sessBucket.CreateBucketIfNotExists(
featureKVStoreBucketKey,
)
if err != nil {
return nil, err
}
return featureBucket.CreateBucketIfNotExists(
[]byte(featureName),
)
}
featureBucket := sessBucket.Bucket(featureKVStoreBucketKey)
if featureBucket == nil {
return nil, nil
}
return featureBucket.Bucket([]byte(featureName)), nil
}
}