forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
etcd.go
78 lines (66 loc) · 1.68 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
package remote
import (
"crypto/md5"
"fmt"
"strings"
etcdapi "github.com/coreos/etcd/client"
"golang.org/x/net/context"
)
func etcdFactory(conf map[string]string) (Client, error) {
path, ok := conf["path"]
if !ok {
return nil, fmt.Errorf("missing 'path' configuration")
}
endpoints, ok := conf["endpoints"]
if !ok || endpoints == "" {
return nil, fmt.Errorf("missing 'endpoints' configuration")
}
config := etcdapi.Config{
Endpoints: strings.Split(endpoints, " "),
}
if username, ok := conf["username"]; ok && username != "" {
config.Username = username
}
if password, ok := conf["password"]; ok && password != "" {
config.Password = password
}
client, err := etcdapi.New(config)
if err != nil {
return nil, err
}
return &EtcdClient{
Client: client,
Path: path,
}, nil
}
// EtcdClient is a remote client that stores data in etcd.
type EtcdClient struct {
Client etcdapi.Client
Path string
}
func (c *EtcdClient) Get() (*Payload, error) {
resp, err := etcdapi.NewKeysAPI(c.Client).Get(context.Background(), c.Path, &etcdapi.GetOptions{Quorum: true})
if err != nil {
if err, ok := err.(etcdapi.Error); ok && err.Code == etcdapi.ErrorCodeKeyNotFound {
return nil, nil
}
return nil, err
}
if resp.Node.Dir {
return nil, fmt.Errorf("path is a directory")
}
data := []byte(resp.Node.Value)
md5 := md5.Sum(data)
return &Payload{
Data: data,
MD5: md5[:],
}, nil
}
func (c *EtcdClient) Put(data []byte) error {
_, err := etcdapi.NewKeysAPI(c.Client).Set(context.Background(), c.Path, string(data), nil)
return err
}
func (c *EtcdClient) Delete() error {
_, err := etcdapi.NewKeysAPI(c.Client).Delete(context.Background(), c.Path, nil)
return err
}