-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackend_consul.go
93 lines (73 loc) · 1.69 KB
/
backend_consul.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
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
"github.com/hashicorp/consul/api"
)
type ConsulBackend struct {
path string
kv *api.KV
}
// Ensure ConsulBackend implement BackendProvider interface
var _ BackendProvider = (*ConsulBackend)(nil)
func NewConsulBackend(url, path string) (BackendProvider, error) {
config := api.DefaultConfig()
config.Scheme = "http"
config.Address = url
parts := strings.Split(url, "://")
if len(parts) == 2 {
config.Scheme = parts[0]
config.Address = parts[1]
}
client, err := api.NewClient(config)
if err != nil {
return nil, fmt.Errorf("consul client setup failed. %v", err)
}
if !strings.HasSuffix(path, "/") {
path += "/"
}
if strings.HasPrefix(path, "/") {
path = strings.TrimPrefix(path, "/")
}
c := &ConsulBackend{
kv: client.KV(),
path: path,
}
return c, nil
}
func (c *ConsulBackend) get(key string) (*api.KVPair, error) {
data, _, err := c.kv.Get(key, nil)
if err != nil {
return nil, err
}
if data == nil {
return nil, fmt.Errorf("key (%s) does not exist.", key)
}
return data, nil
}
func (c *ConsulBackend) GetRecoveryKey() ([]byte, error) {
key := c.path + recoveryKeyPath
data, err := c.get(key)
if err != nil {
return nil, err
}
return data.Value, nil
}
func (c *ConsulBackend) RecoveryConfig() (*SealConfig, error) {
key := c.path + recoverySealConfigPlaintextPath
conf := &SealConfig{}
data, _, err := c.kv.Get(key, nil)
if err != nil {
return nil, err
}
if data == nil {
return nil, fmt.Errorf("key (%s) does not exist.", key)
}
if err := json.Unmarshal(data.Value, conf); err != nil {
log.Print("failed to decode seal configuration", err)
return nil, err
}
return conf, nil
}