-
Notifications
You must be signed in to change notification settings - Fork 444
/
consul.go
304 lines (255 loc) · 6.68 KB
/
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
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
package services
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"syscall"
"io/ioutil"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/gexec"
"github.com/hashicorp/consul/api"
"github.com/solo-io/go-utils/log"
)
const consulDockerImage = "consul:1.5.2"
type ConsulFactory struct {
consulPath string
tmpdir string
}
type serviceDef struct {
Service *consulService `json:"service"`
}
type consulService struct {
ID string `json:"id"`
Name string `json:"name"`
Port uint32 `json:"port"`
Tags []string `json:"tags"`
Address string `json:"address"`
}
func NewConsulFactory() (*ConsulFactory, error) {
consulPath := os.Getenv("CONSUL_BINARY")
if consulPath != "" {
return &ConsulFactory{
consulPath: consulPath,
}, nil
}
consulPath, err := exec.LookPath("consul")
if err == nil {
log.Printf("Using consul from PATH: %s", consulPath)
return &ConsulFactory{
consulPath: consulPath,
}, nil
}
// try to grab one from docker...
tmpdir, err := os.MkdirTemp(os.Getenv("HELPER_TMP"), "consul")
if err != nil {
return nil, err
}
bash := fmt.Sprintf(`
set -ex
CID=$(docker run -d %s /bin/sh -c exit)
# just print the image sha for repoducibility
echo "Using Consul Image:"
docker inspect %s -f "{{.RepoDigests}}"
docker cp $CID:/bin/consul .
docker rm -f $CID
`, consulDockerImage, consulDockerImage)
scriptFile := filepath.Join(tmpdir, "get_consul.sh")
err = ioutil.WriteFile(scriptFile, []byte(bash), 0755)
if err != nil {
return nil, err
}
cmd := exec.Command("bash", scriptFile)
cmd.Dir = tmpdir
cmd.Stdout = GinkgoWriter
cmd.Stderr = GinkgoWriter
if err := cmd.Run(); err != nil {
return nil, err
}
return &ConsulFactory{
consulPath: filepath.Join(tmpdir, "consul"),
tmpdir: tmpdir,
}, nil
}
func (cf *ConsulFactory) Clean() error {
if cf == nil {
return nil
}
if cf.tmpdir != "" {
_ = os.RemoveAll(cf.tmpdir)
}
return nil
}
func (cf *ConsulFactory) MustConsulInstance() *ConsulInstance {
instance, err := cf.NewConsulInstance()
ExpectWithOffset(1, err).NotTo(HaveOccurred())
return instance
}
func (cf *ConsulFactory) NewConsulInstance() (*ConsulInstance, error) {
// try to grab one form docker...
tmpdir, err := ioutil.TempDir(os.Getenv("HELPER_TMP"), "consul")
if err != nil {
return nil, err
}
cfgDir := filepath.Join(tmpdir, "config")
err = os.Mkdir(cfgDir, 0755)
if err != nil {
return nil, err
}
cmd := exec.Command(cf.consulPath, "agent", "-dev", "--client=0.0.0.0", "-config-dir", cfgDir,
"-node", "consul-dev")
cmd.Dir = cf.tmpdir
cmd.Stdout = GinkgoWriter
cmd.Stderr = GinkgoWriter
return &ConsulInstance{
consulPath: cf.consulPath,
tmpdir: tmpdir,
cfgDir: cfgDir,
cmd: cmd,
registeredServices: map[string]*serviceDef{},
}, nil
}
type ConsulInstance struct {
consulPath string
tmpdir string
cfgDir string
cmd *exec.Cmd
session *gexec.Session
registeredServices map[string]*serviceDef
client *api.Client
}
func (i *ConsulInstance) AddConfig(svcId, content string) error {
fileName := filepath.Join(i.cfgDir, svcId+".json")
return ioutil.WriteFile(fileName, []byte(content), 0644)
}
func (i *ConsulInstance) AddConfigFromStruct(svcId string, cfg interface{}) error {
content, err := json.Marshal(cfg)
if err != nil {
return err
}
return i.AddConfig(svcId, string(content))
}
func (i *ConsulInstance) ReloadConfig() error {
err := i.cmd.Process.Signal(syscall.SIGHUP)
if err != nil {
return err
}
return nil
}
func (i *ConsulInstance) Silence() {
i.cmd.Stdout = nil
i.cmd.Stderr = nil
}
// Run starts the ConsulInstance
// When the provided context is Done, the ConsulInstance is cleaned up
func (i *ConsulInstance) Run(ctx context.Context) error {
go func() {
// Ensure the ConsulInstance is cleaned up when the Run context is completed
<-ctx.Done()
i.Clean()
}()
var err error
i.session, err = gexec.Start(i.cmd, GinkgoWriter, GinkgoWriter)
if err != nil {
return err
}
EventuallyWithOffset(1, i.session.Out, "5s").Should(gbytes.Say("New leader elected"))
return nil
}
func (i *ConsulInstance) withClient() *ConsulInstance {
client, err := api.NewClient(api.DefaultConfig())
Expect(err).NotTo(HaveOccurred())
i.client = client
return i
}
func (i *ConsulInstance) Binary() string {
return i.consulPath
}
// Clean stops the ConsulInstance
func (i *ConsulInstance) Clean() {
if i == nil {
return
}
if i.session != nil {
i.session.Kill()
}
if i.cmd != nil && i.cmd.Process != nil {
i.cmd.Process.Kill()
}
if i.tmpdir != "" {
_ = os.RemoveAll(i.tmpdir)
}
}
func (i *ConsulInstance) RegisterService(svcName, svcId, address string, tags []string, port uint32) error {
svcDef := &serviceDef{
Service: &consulService{
ID: svcId,
Name: svcName,
Address: address,
Tags: tags,
Port: port,
},
}
i.registeredServices[svcId] = svcDef
err := i.AddConfigFromStruct(svcId, svcDef)
if err != nil {
return err
}
return i.ReloadConfig()
}
// RegisterLiveService While it may be tempting to just reload all config using `consul reload` or marshalling new json and
// sending SIGHUP to the process (per https://www.consul.io/commands/reload), it is preferable to live update
// using the consul APIs as this is a more realistic flow and doesn't fire our watches too actively (which can
// both make debugging hard and hide bugs)
func (i *ConsulInstance) RegisterLiveService(svcName, svcId, address string, tags []string, port uint32) error {
svcDef := &serviceDef{
Service: &consulService{
ID: svcId,
Name: svcName,
Address: address,
Tags: tags,
Port: port,
},
}
content, err := json.Marshal(svcDef.Service)
if err != nil {
return err
}
fileName := filepath.Join(i.cfgDir, svcId+".json")
err = os.Remove(fileName) // ensure we upsert the config update
if err != nil && !os.IsNotExist(err) {
return err
}
err = ioutil.WriteFile(fileName, content, 0644)
if err != nil {
return err
}
cmd := exec.Command("curl", "--request", "PUT", "--data", fmt.Sprintf("@%s", fileName), "0.0.0.0:8500/v1/agent/service/register")
cmd.Dir = i.tmpdir
cmd.Stdout = GinkgoWriter
cmd.Stderr = GinkgoWriter
if err := cmd.Run(); err != nil {
return err
}
return nil
}
// Put wraps the Consul KV Put API call
func (i *ConsulInstance) Put(key string, value []byte) error {
kvp := &api.KVPair{
Key: key,
Value: value,
}
_, err := i.Client().KV().Put(kvp, &api.WriteOptions{})
return err
}
// Client returns the Consul API client, constructing one if necessary
func (i *ConsulInstance) Client() *api.Client {
if i.client == nil {
i = i.withClient()
}
return i.client
}