forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
etcd.go
335 lines (290 loc) · 9 KB
/
etcd.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
/*
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 etcdbk implements Etcd powered backend
package etcdbk
import (
"encoding/base64"
"sort"
"strings"
"time"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/utils"
"github.com/coreos/etcd/client"
"github.com/coreos/etcd/pkg/transport"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"golang.org/x/net/context"
)
type bk struct {
nodes []string
cfg *Config
etcdKey string
client client.Client
api client.KeysAPI
cancelC chan bool
stopC chan bool
clock clockwork.Clock
}
// Config represents JSON config for etcd backend
type Config struct {
Nodes []string `json:"peers,omitempty"`
Key string `json:"prefix,omitempty"`
TLSKeyFile string `json:"tls_key_file,omitempty"`
TLSCertFile string `json:"tls_cert_file,omitempty"`
TLSCAFile string `json:"tls_ca_file,omitempty"`
Insecure bool `json:"insecure,omitempty"`
}
// GetName returns the name of etcd backend as it appears in 'storage/type' section
// in Teleport YAML file. This function is a part of backend API
func GetName() string {
return "etcd"
}
// New returns new instance of Etcd-powered backend
func New(params backend.Params) (backend.Backend, error) {
var err error
if params == nil {
return nil, trace.BadParameter("missing etcd configuration")
}
// convert generic backend parameters structure to etcd config:
var cfg *Config
if err = utils.ObjectToStruct(params, &cfg); err != nil {
return nil, trace.BadParameter("invalid etcd configuration", err)
}
if err = cfg.Validate(); err != nil {
return nil, trace.Wrap(err)
}
b := &bk{
cfg: cfg,
nodes: cfg.Nodes,
etcdKey: cfg.Key,
cancelC: make(chan bool, 1),
stopC: make(chan bool, 1),
clock: clockwork.NewRealClock(),
}
if err = b.reconnect(); err != nil {
return nil, trace.Wrap(err)
}
// Wrap backend in a input sanitizer and return it.
return backend.NewSanitizer(b), nil
}
// Validate checks if all the parameters are present/valid
func (cfg *Config) Validate() error {
if len(cfg.Key) == 0 {
return trace.BadParameter(`etcd: missing "prefix" setting`)
}
if len(cfg.Nodes) == 0 {
return trace.BadParameter(`etcd: missing "peers" setting`)
}
if cfg.Insecure == false {
if cfg.TLSKeyFile == "" {
return trace.BadParameter(`etcd: missing "tls_key_file" setting`)
}
if cfg.TLSCertFile == "" {
return trace.BadParameter(`etcd: missing "tls_cert_file" setting`)
}
if cfg.TLSCAFile == "" {
return trace.BadParameter(`etcd: missing "tls_ca_file" setting`)
}
}
return nil
}
func (b *bk) Clock() clockwork.Clock {
return b.clock
}
func (b *bk) Close() error {
return nil
}
func (b *bk) key(keys ...string) string {
return strings.Join(append([]string{b.etcdKey}, keys...), "/")
}
func (b *bk) reconnect() error {
tlsInfo := transport.TLSInfo{
CAFile: b.cfg.TLSCAFile,
CertFile: b.cfg.TLSCertFile,
KeyFile: b.cfg.TLSKeyFile,
}
tr, err := transport.NewTransport(tlsInfo, defaults.DefaultDialTimeout)
if err != nil {
return trace.Wrap(err)
}
clt, err := client.New(client.Config{
Endpoints: b.nodes,
Transport: tr,
HeaderTimeoutPerRequest: defaults.ReadHeadersTimeout,
})
if err != nil {
return trace.Wrap(err)
}
b.client = clt
b.api = client.NewKeysAPI(b.client)
return nil
}
// GetItems fetches keys and values and returns them to the caller.
func (b *bk) GetItems(path []string) ([]backend.Item, error) {
items, err := b.getItems(b.key(path...))
if err != nil {
return nil, trace.Wrap(err)
}
return items, nil
}
// GetKeys fetches keys (and values) but only returns keys to the caller.
func (b *bk) GetKeys(path []string) ([]string, error) {
items, err := b.getItems(b.key(path...))
if err != nil {
return nil, trace.Wrap(err)
}
// Convert from []backend.Item to []string and return keys.
keys := make([]string, len(items))
for i, e := range items {
keys[i] = e.Key
}
return keys, nil
}
func (b *bk) CreateVal(path []string, key string, val []byte, ttl time.Duration) error {
_, err := b.api.Set(
context.Background(),
b.key(append(path, key)...), base64.StdEncoding.EncodeToString(val),
&client.SetOptions{PrevExist: client.PrevNoExist, TTL: ttl})
return trace.Wrap(convertErr(err))
}
// CompareAndSwapVal compares and swap values in atomic operation,
// succeeds if prevVal matches the value stored in the databases,
// requires prevVal as a non-empty value. Returns trace.CompareFailed
// in case if value did not match
func (b *bk) CompareAndSwapVal(path []string, key string, val []byte, prevVal []byte, ttl time.Duration) error {
if len(prevVal) == 0 {
return trace.BadParameter("missing prevVal parameter, to atomically create item, use CreateVal method")
}
encodedPrev := base64.StdEncoding.EncodeToString(prevVal)
_, err := b.api.Set(
context.Background(),
b.key(append(path, key)...), base64.StdEncoding.EncodeToString(val),
&client.SetOptions{PrevValue: encodedPrev, PrevExist: client.PrevExist, TTL: ttl})
err = convertErr(err)
if trace.IsNotFound(err) {
return trace.CompareFailed(err.Error())
}
return trace.Wrap(err)
}
// maxOptimisticAttempts is the number of attempts optimistic locking
const maxOptimisticAttempts = 5
func (bk *bk) UpsertItems(bucket []string, items []backend.Item) error {
return trace.BadParameter("not implemented")
}
func (b *bk) UpsertVal(path []string, key string, val []byte, ttl time.Duration) error {
_, err := b.api.Set(
context.Background(),
b.key(append(path, key)...), base64.StdEncoding.EncodeToString(val), &client.SetOptions{TTL: ttl})
return convertErr(err)
}
func (b *bk) GetVal(path []string, key string) ([]byte, error) {
re, err := b.api.Get(context.Background(), b.key(append(path, key)...), nil)
if err != nil {
return nil, convertErr(err)
}
if re.Node.Dir {
return nil, trace.BadParameter("'%v': trying to get value of bucket", key)
}
value, err := base64.StdEncoding.DecodeString(re.Node.Value)
if err != nil {
return nil, trace.Wrap(err)
}
return value, nil
}
func (b *bk) DeleteKey(path []string, key string) error {
_, err := b.api.Delete(context.Background(), b.key(append(path, key)...), nil)
return convertErr(err)
}
func (b *bk) DeleteBucket(path []string, key string) error {
_, err := b.api.Delete(context.Background(), b.key(append(path, key)...), &client.DeleteOptions{Dir: true, Recursive: true})
return convertErr(err)
}
const delayBetweenLockAttempts = 100 * time.Millisecond
func (b *bk) AcquireLock(token string, ttl time.Duration) error {
for {
_, err := b.api.Set(
context.Background(),
b.key("locks", token), "lock", &client.SetOptions{TTL: ttl, PrevExist: client.PrevNoExist})
err = convertErr(err)
if err == nil {
return nil
}
if err != nil {
if !trace.IsCompareFailed(err) && !trace.IsAlreadyExists(err) {
return trace.Wrap(err)
}
time.Sleep(delayBetweenLockAttempts)
}
}
}
func (b *bk) ReleaseLock(token string) error {
_, err := b.api.Delete(context.Background(), b.key("locks", token), nil)
return convertErr(err)
}
// getItems fetches keys and values and returns them to the caller.
func (b *bk) getItems(path string) ([]backend.Item, error) {
var vals []backend.Item
re, err := b.api.Get(context.Background(), path, nil)
if er := convertErr(err); er != nil {
if trace.IsNotFound(er) {
return vals, nil
}
return nil, trace.Wrap(er)
}
if !isDir(re.Node) {
return nil, trace.BadParameter("'%v': expected directory", path)
}
// Convert etcd response of *client.Response to backend.Item.
for _, n := range re.Node.Nodes {
valueBytes, err := base64.StdEncoding.DecodeString(n.Value)
if err != nil {
return nil, trace.Wrap(err)
}
vals = append(vals, backend.Item{
Key: suffix(n.Key),
Value: valueBytes,
})
}
// Sort and return results.
sort.Slice(vals, func(i, j int) bool {
return vals[i].Key < vals[j].Key
})
return vals, nil
}
func convertErr(e error) error {
if e == nil {
return nil
}
switch err := e.(type) {
case client.Error:
switch err.Code {
case client.ErrorCodeKeyNotFound:
return trace.NotFound(err.Error())
case client.ErrorCodeNotFile:
return trace.BadParameter(err.Error())
case client.ErrorCodeNodeExist:
return trace.AlreadyExists(err.Error())
case client.ErrorCodeTestFailed:
return trace.CompareFailed(err.Error())
}
}
return e
}
func isDir(n *client.Node) bool {
return n != nil && n.Dir == true
}
func suffix(key string) string {
vals := strings.Split(key, "/")
return vals[len(vals)-1]
}