forked from hashicorp/vault
/
zookeeper.go
196 lines (167 loc) · 4.82 KB
/
zookeeper.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
package physical
import (
"fmt"
"sort"
"strings"
"time"
"github.com/armon/go-metrics"
"github.com/samuel/go-zookeeper/zk"
)
// ZookeeperBackend is a physical backend that stores data at specific
// prefix within Zookeeper. It is used in production situations as
// it allows Vault to run on multiple machines in a highly-available manner.
type ZookeeperBackend struct {
path string
client *zk.Conn
}
// newZookeeperBackend constructs a Zookeeper backend using the given API client
// and the prefix in the KV store.
func newZookeeperBackend(conf map[string]string) (Backend, error) {
// Get the path in Zookeeper
path, ok := conf["path"]
if !ok {
path = "vault/"
}
// Ensure path is suffixed and prefixed (zk requires prefix /)
if !strings.HasSuffix(path, "/") {
path += "/"
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
// Configure the client, default to localhost instance
var machines string
machines, ok = conf["address"]
if !ok {
machines = "localhost:2181"
}
// Attempt to create the ZK client
client, _, err := zk.Connect(strings.Split(machines, ","), time.Second)
if err != nil {
return nil, fmt.Errorf("client setup failed: %v", err)
}
// Setup the backend
c := &ZookeeperBackend{
path: path,
client: client,
}
return c, nil
}
// ensurePath is used to create each node in the path hierarchy.
// We avoid calling this optimistically, and invoke it when we get
// an error during an operation
func (c *ZookeeperBackend) ensurePath(path string, value []byte) error {
nodes := strings.Split(path, "/")
acl := zk.WorldACL(zk.PermAll)
fullPath := ""
for index, node := range nodes {
if strings.TrimSpace(node) != "" {
fullPath += "/" + node
isLastNode := index+1 == len(nodes)
// set parent nodes to nil, leaf to value
// this block reduces round trips by being smart on the leaf create/set
if exists, _, _ := c.client.Exists(fullPath); !isLastNode && !exists {
if _, err := c.client.Create(fullPath, nil, int32(0), acl); err != nil {
return err
}
} else if isLastNode && !exists {
if _, err := c.client.Create(fullPath, value, int32(0), acl); err != nil {
return err
}
} else if isLastNode && exists {
if _, err := c.client.Set(fullPath, value, int32(-1)); err != nil {
return err
}
}
}
}
return nil
}
// deletePath is a helper that will recursively delete
// a given path
func (c *ZookeeperBackend) deletePath(path string) error {
children, _, _ := c.client.Children(path)
for _, childPath := range children {
err := c.deletePath(path + "/" + childPath)
if err != nil {
return err
}
}
err := c.client.Delete(path, -1)
if err != nil {
return err
}
return nil
}
// Put is used to insert or update an entry
func (c *ZookeeperBackend) Put(entry *Entry) error {
defer metrics.MeasureSince([]string{"zookeeper", "put"}, time.Now())
// Attempt to set the full path
fullPath := c.path + entry.Key
_, err := c.client.Set(fullPath, entry.Value, -1)
// If we get ErrNoNode, we need to construct the path hierarchy
if err == zk.ErrNoNode {
return c.ensurePath(fullPath, entry.Value)
}
return err
}
// Get is used to fetch an entry
func (c *ZookeeperBackend) Get(key string) (*Entry, error) {
defer metrics.MeasureSince([]string{"zookeeper", "get"}, time.Now())
// Attempt to read the full path
fullPath := c.path + key
value, _, err := c.client.Get(fullPath)
// Ignore if the node does not exist
if err == zk.ErrNoNode {
err = nil
}
if err != nil {
return nil, err
}
// Handle a non-existing value
if value == nil {
return nil, nil
}
ent := &Entry{
Key: key,
Value: value,
}
return ent, nil
}
// Delete is used to permanently delete an entry
func (c *ZookeeperBackend) Delete(key string) error {
defer metrics.MeasureSince([]string{"zookeeper", "delete"}, time.Now())
// Delete the full path
fullPath := c.path + key
err := c.deletePath(fullPath)
// Mask if the node does not exist
if err == zk.ErrNoNode {
err = nil
}
return err
}
// List is used ot list all the keys under a given
// prefix, up to the next prefix.
func (c *ZookeeperBackend) List(prefix string) ([]string, error) {
defer metrics.MeasureSince([]string{"zookeeper", "list"}, time.Now())
// Query the children at the full path
fullPath := strings.TrimSuffix(c.path+prefix, "/")
result, _, err := c.client.Children(fullPath)
// If the path nodes are missing, no children!
if err == zk.ErrNoNode {
return []string{}, nil
}
children := []string{}
for _, key := range result {
children = append(children, key)
// Check if this entry has any child entries,
// and append the slash which is what Vault depends on
// for iteration
nodeChildren, _, _ := c.client.Children(fullPath + "/" + key)
if nodeChildren != nil && len(nodeChildren) > 0 {
children = append(children, key+"/")
}
}
sort.Strings(children)
return children, nil
}