This repository has been archived by the owner on Aug 3, 2020. It is now read-only.
forked from ligato/vpp-agent
/
kvdb.go
87 lines (71 loc) · 2.26 KB
/
kvdb.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
package client
import (
"fmt"
"path"
"strings"
"github.com/ligato/cn-infra/datasync"
"github.com/ligato/cn-infra/db/keyval"
"github.com/ligato/cn-infra/logging"
"github.com/ligato/cn-infra/servicelabel"
)
// KVDBClient provides client access to the KVDB server.
type KVDBClient struct {
keyval.CoreBrokerWatcher
serviceLabel string
}
func NewKVDBClient(kvdb keyval.CoreBrokerWatcher, serviceLabel string) *KVDBClient {
return &KVDBClient{
CoreBrokerWatcher: kvdb,
serviceLabel: serviceLabel,
}
}
func (k *KVDBClient) Put(key string, data []byte, opts ...datasync.PutOption) (err error) {
key, err = k.completeFullKey(key)
if err != nil {
return err
}
logging.Debugf("KVDBClient.Put: %s", key)
return k.CoreBrokerWatcher.Put(key, data, opts...)
}
func (k *KVDBClient) GetValue(key string) (data []byte, found bool, revision int64, err error) {
key, err = k.completeFullKey(key)
if err != nil {
return nil, false, 0, err
}
logging.Debugf("KVDBClient.GetValue: %s", key)
return k.CoreBrokerWatcher.GetValue(key)
}
func (k *KVDBClient) ListValues(prefix string) (keyval.BytesKeyValIterator, error) {
prefix = ensureAllAgentsPrefix(prefix)
logging.Debugf("KVDBClient.ListValues: %s", prefix)
return k.CoreBrokerWatcher.ListValues(prefix)
}
func (k *KVDBClient) ListKeys(prefix string) (keyval.BytesKeyIterator, error) {
prefix = ensureAllAgentsPrefix(prefix)
logging.Debugf("KVDBClient.ListKeys: %s", prefix)
return k.CoreBrokerWatcher.ListKeys(prefix)
}
func (k *KVDBClient) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) {
key, err = k.completeFullKey(key)
if err != nil {
return false, err
}
logging.Debugf("KVDBClient.Delete: %s", key)
return k.CoreBrokerWatcher.Delete(key, opts...)
}
func (k *KVDBClient) completeFullKey(key string) (string, error) {
if strings.HasPrefix(key, servicelabel.GetAllAgentsPrefix()) {
return key, nil
}
if k.serviceLabel == "" {
return "", fmt.Errorf("service label is not defined, cannot get complete key")
}
key = path.Join(servicelabel.GetAllAgentsPrefix(), k.serviceLabel, key)
return key, nil
}
func ensureAllAgentsPrefix(key string) string {
if strings.HasPrefix(key, servicelabel.GetAllAgentsPrefix()) {
return key
}
return path.Join(servicelabel.GetAllAgentsPrefix(), key)
}