forked from kelseyhightower/confd
/
client.go
96 lines (85 loc) · 2.01 KB
/
client.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
package consul
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"net/http"
"path"
"strings"
"github.com/hashicorp/consul/api"
)
// Client provides a wrapper around the consulkv client
type ConsulClient struct {
client *api.KV
}
// NewConsulClient returns a new client to Consul for the given address
func New(nodes []string, scheme, cert, key, caCert string) (*ConsulClient, error) {
conf := api.DefaultConfig()
conf.Scheme = scheme
if len(nodes) > 0 {
conf.Address = nodes[0]
}
tlsConfig := &tls.Config{}
if cert != "" && key != "" {
clientCert, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{clientCert}
tlsConfig.BuildNameToCertificate()
}
if caCert != "" {
ca, err := ioutil.ReadFile(caCert)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(ca)
tlsConfig.RootCAs = caCertPool
}
conf.HttpClient.Transport = &http.Transport{
TLSClientConfig: tlsConfig,
}
client, err := api.NewClient(conf)
if err != nil {
return nil, err
}
return &ConsulClient{client.KV()}, nil
}
// GetValues queries Consul for keys
func (c *ConsulClient) GetValues(keys []string) (map[string]string, error) {
vars := make(map[string]string)
for _, key := range keys {
key := strings.TrimPrefix(key, "/")
pairs, _, err := c.client.List(key, nil)
if err != nil {
return vars, err
}
for _, p := range pairs {
vars[path.Join("/", p.Key)] = string(p.Value)
}
}
return vars, nil
}
type watchResponse struct {
waitIndex uint64
err error
}
func (c *ConsulClient) WatchPrefix(prefix string, waitIndex uint64, stopChan chan bool) (uint64, error) {
respChan := make(chan watchResponse)
go func() {
opts := api.QueryOptions{
WaitIndex: waitIndex,
}
_, meta, err := c.client.List(prefix, &opts)
respChan <- watchResponse{meta.LastIndex, err}
}()
for {
select {
case <-stopChan:
return waitIndex, nil
case r := <-respChan:
return r.waitIndex, r.err
}
}
}