forked from k8sgateway/k8sgateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
envoy.go
705 lines (608 loc) · 16.5 KB
/
envoy.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
package services
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync/atomic"
"text/template"
"time"
"github.com/solo-io/gloo/projects/gloo/pkg/defaults"
"github.com/onsi/ginkgo"
"github.com/onsi/ginkgo/config"
. "github.com/onsi/gomega"
errors "github.com/rotisserie/eris"
"github.com/solo-io/go-utils/log"
)
const (
containerName = "e2e_envoy"
DefaultProxyName = "default~proxy"
)
var adminPort = uint32(20000)
var bindPort = uint32(10080)
func NextBindPort() uint32 {
return AdvanceBindPort(&bindPort)
}
func AdvanceBindPort(p *uint32) uint32 {
return atomic.AddUint32(p, 1) + uint32(config.GinkgoConfig.ParallelNode*1000)
}
type EnvoyBootstrapBuilder interface {
Build(ei *EnvoyInstance) string
}
type templateBootstrapBuilder struct {
template *template.Template
}
func (tbb *templateBootstrapBuilder) Build(ei *EnvoyInstance) string {
var b bytes.Buffer
if err := tbb.template.Execute(&b, ei); err != nil {
panic(err)
}
return b.String()
}
type fileBootstrapBuilder struct {
file string
}
func (fbb *fileBootstrapBuilder) Build(ei *EnvoyInstance) string {
templateBytes, err := ioutil.ReadFile(fbb.file)
if err != nil {
panic(err)
}
parsedTemplate := template.Must(template.New(fbb.file).Parse(string(templateBytes)))
var b bytes.Buffer
if err := parsedTemplate.Execute(&b, ei); err != nil {
panic(err)
}
return b.String()
}
const envoyConfigTemplate = `
layered_runtime:
layers:
- name: static_layer
static_layer:
upstream:
healthy_panic_threshold:
value: 0
- name: admin_layer
admin_layer: {}
node:
cluster: ingress
id: {{.ID}}
metadata:
role: {{.Role}}
static_resources:
clusters:
- name: xds_cluster
connect_timeout: 5.000s
load_assignment:
cluster_name: xds_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: {{.GlooAddr}}
port_value: {{.Port}}
http2_protocol_options: {}
type: STATIC
- name: rest_xds_cluster
connect_timeout: 5.000s
load_assignment:
cluster_name: rest_xds_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: {{.GlooAddr}}
port_value: {{.RestXdsPort}}
upstream_connection_options:
tcp_keepalive: {}
type: STRICT_DNS
respect_dns_ttl: true
{{if .RatelimitAddr}}
- name: ratelimit_cluster
connect_timeout: 5.000s
load_assignment:
cluster_name: ratelimit_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: {{.RatelimitAddr}}
port_value: {{.RatelimitPort}}
http2_protocol_options: {}
type: STATIC
{{end}}
{{if .AccessLogAddr}}
- name: access_log_cluster
connect_timeout: 5.000s
load_assignment:
cluster_name: access_log_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: {{.AccessLogAddr}}
port_value: {{.AccessLogPort}}
http2_protocol_options: {}
type: STATIC
{{end}}
- name: aws_sts_cluster
connect_timeout: 5.000s
type: LOGICAL_DNS
lb_policy: ROUND_ROBIN
load_assignment:
cluster_name: aws_sts_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
port_value: 443
address: sts.amazonaws.com
transport_socket:
name: envoy.transport_sockets.tls
typed_config:
"@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
sni: sts.amazonaws.com
dynamic_resources:
ads_config:
transport_api_version: {{ .ApiVersion }}
api_type: GRPC
grpc_services:
- envoy_grpc: {cluster_name: xds_cluster}
cds_config:
resource_api_version: {{ .ApiVersion }}
ads: {}
lds_config:
resource_api_version: {{ .ApiVersion }}
ads: {}
admin:
access_log_path: /dev/null
address:
socket_address:
address: 0.0.0.0
port_value: {{.AdminPort}}
`
var defaultBootstrapTemplate = template.Must(template.New("bootstrap").Parse(envoyConfigTemplate))
type EnvoyFactory struct {
envoypath string
tmpdir string
useDocker bool
instances []*EnvoyInstance
}
func getEnvoyImageTag() string {
eit := os.Getenv("ENVOY_IMAGE_TAG")
if eit != "" {
return eit
}
// get project base
gomod, err := exec.Command("go", "env", "GOMOD").CombinedOutput()
Expect(err).NotTo(HaveOccurred())
gomodfile := strings.TrimSpace(string(gomod))
projectbase, _ := filepath.Split(gomodfile)
makefile := filepath.Join(projectbase, "Makefile")
inFile, err := os.Open(makefile)
Expect(err).NotTo(HaveOccurred())
defer inFile.Close()
const prefix = "ENVOY_GLOO_IMAGE ?= quay.io/solo-io/envoy-gloo:"
scanner := bufio.NewScanner(inFile)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, prefix) {
return strings.TrimSpace(strings.TrimPrefix(line, prefix))
}
}
return ""
}
func NewEnvoyFactory() (*EnvoyFactory, error) {
// if an envoy binary is explicitly specified
// use it
envoyPath := os.Getenv("ENVOY_BINARY")
if envoyPath != "" {
log.Printf("Using envoy from environment variable: %s", envoyPath)
return &EnvoyFactory{
envoypath: envoyPath,
}, nil
}
// maybe it is in the path?!
// only try to use local path if FETCH_ENVOY_BINARY is not set;
// there are two options:
// - you are using local envoy binary you just built and want to test (don't set the variable)
// - you want to use the envoy version gloo is shipped with (set the variable)
if os.Getenv("FETCH_ENVOY_BINARY") != "" {
envoyPath, err := exec.LookPath("envoy")
if err == nil {
log.Printf("Using envoy from PATH: %s", envoyPath)
return &EnvoyFactory{
envoypath: envoyPath,
}, nil
}
}
switch runtime.GOOS {
case "darwin":
log.Printf("Using docker to run envoy")
return &EnvoyFactory{useDocker: true}, nil
case "linux":
// try to grab one form docker...
tmpdir, err := ioutil.TempDir(os.Getenv("HELPER_TMP"), "envoy")
if err != nil {
return nil, err
}
envoyImageTag := getEnvoyImageTag()
if envoyImageTag == "" {
panic("Must set the ENVOY_IMAGE_TAG env var. Find valid tag names here https://quay.io/repository/solo-io/gloo-envoy-wrapper?tab=tags")
}
log.Printf("Using envoy docker image tag: %s", envoyImageTag)
bash := fmt.Sprintf(`
set -ex
CID=$(docker run -d quay.io/solo-io/envoy-gloo:%s /bin/bash -c exit)
# just print the image sha for repoducibility
echo "Using Envoy Image:"
docker inspect quay.io/solo-io/envoy-gloo:%s -f "{{.RepoDigests}}"
docker cp $CID:/usr/local/bin/envoy .
docker rm $CID
`, envoyImageTag, envoyImageTag)
scriptfile := filepath.Join(tmpdir, "getenvoy.sh")
ioutil.WriteFile(scriptfile, []byte(bash), 0755)
cmd := exec.Command("bash", scriptfile)
cmd.Dir = tmpdir
cmd.Stdout = ginkgo.GinkgoWriter
cmd.Stderr = ginkgo.GinkgoWriter
if err := cmd.Run(); err != nil {
return nil, err
}
return &EnvoyFactory{
envoypath: filepath.Join(tmpdir, "envoy"),
tmpdir: tmpdir,
}, nil
default:
return nil, errors.New("Unsupported OS: " + runtime.GOOS)
}
}
func (ef *EnvoyFactory) EnvoyPath() string {
return ef.envoypath
}
func (ef *EnvoyFactory) Clean() error {
if ef == nil {
return nil
}
if ef.tmpdir != "" {
os.RemoveAll(ef.tmpdir)
}
instances := ef.instances
ef.instances = nil
for _, ei := range instances {
ei.Clean()
}
return nil
}
func (ei *EnvoyInstance) EnvoyConfigDump() (string, error) {
adminUrl := fmt.Sprintf("http://%s:%d/config_dump",
ei.LocalAddr(),
ei.AdminPort)
response, err := http.Get(adminUrl)
if err != nil {
return "", err
}
configDumpBytes := new(bytes.Buffer)
defer response.Body.Close()
if _, err := io.Copy(configDumpBytes, response.Body); err != nil {
return "", err
}
return configDumpBytes.String(), nil
}
type EnvoyInstance struct {
AccessLogAddr string
AccessLogPort uint32
RatelimitAddr string
RatelimitPort uint32
ID string
Role string
envoypath string
envoycfg string
logs *bytes.Buffer
cmd *exec.Cmd
UseDocker bool
GlooAddr string // address for gloo and services
Port uint32
RestXdsPort uint32
AdminPort uint32
// Path to access logs for binary run
AccessLogs string
// Envoy API Version to use, default to V3
ApiVersion string
DockerOptions
}
// Extra options for running in docker
type DockerOptions struct {
// Extra volume arguments
Volumes []string
// Extra env arguments.
// see https://docs.docker.com/engine/reference/run/#env-environment-variables for more info
Env []string
}
func (ef *EnvoyFactory) MustEnvoyInstance() *EnvoyInstance {
envoyInstance, err := ef.NewEnvoyInstance()
Expect(err).NotTo(HaveOccurred())
return envoyInstance
}
func (ef *EnvoyFactory) NewEnvoyInstance() (*EnvoyInstance, error) {
gloo := "127.0.0.1"
if ef.useDocker {
var err error
gloo, err = localAddr()
if err != nil {
return nil, err
}
}
ei := &EnvoyInstance{
envoypath: ef.envoypath,
UseDocker: ef.useDocker,
GlooAddr: gloo,
AccessLogAddr: gloo,
AdminPort: atomic.AddUint32(&adminPort, 1) + uint32(config.GinkgoConfig.ParallelNode*1000),
ApiVersion: "V3",
}
ef.instances = append(ef.instances, ei)
return ei, nil
}
func (ei *EnvoyInstance) RunWithId(id string) error {
ei.ID = id
return ei.RunWithRole(DefaultProxyName, 8081)
}
func (ei *EnvoyInstance) Run(port int) error {
return ei.RunWithRole(DefaultProxyName, port)
}
func (ei *EnvoyInstance) RunWith(eic EnvoyInstanceConfig) error {
return ei.runWithAll(eic, &templateBootstrapBuilder{
template: defaultBootstrapTemplate,
})
}
func (ei *EnvoyInstance) RunWithRole(role string, port int) error {
eic := &envoyInstanceConfig{
role: role,
port: uint32(port),
context: context.TODO(),
}
boostrapBuilder := &templateBootstrapBuilder{
template: defaultBootstrapTemplate,
}
return ei.runWithAll(eic, boostrapBuilder)
}
func (ei *EnvoyInstance) RunWithRoleAndRestXds(role string, glooPort, restXdsPort int) error {
eic := &envoyInstanceConfig{
role: role,
port: uint32(glooPort),
restXdsPort: uint32(restXdsPort),
context: context.TODO(),
}
boostrapBuilder := &templateBootstrapBuilder{
template: defaultBootstrapTemplate,
}
return ei.runWithAll(eic, boostrapBuilder)
}
func (ei *EnvoyInstance) RunWithConfigFile(port int, configFile string) error {
eic := &envoyInstanceConfig{
role: "gloo-system~gateway-proxy",
port: uint32(port),
context: context.TODO(),
}
boostrapBuilder := &fileBootstrapBuilder{
file: configFile,
}
return ei.runWithAll(eic, boostrapBuilder)
}
type EnvoyInstanceConfig interface {
Role() string
Port() uint32
RestXdsPort() uint32
Context() context.Context
}
type envoyInstanceConfig struct {
role string
port uint32
restXdsPort uint32
context context.Context
}
func (eic *envoyInstanceConfig) Role() string {
return eic.role
}
func (eic *envoyInstanceConfig) Port() uint32 {
return eic.port
}
func (eic *envoyInstanceConfig) RestXdsPort() uint32 {
return eic.restXdsPort
}
func (eic *envoyInstanceConfig) Context() context.Context {
return eic.context
}
func (ei *EnvoyInstance) runWithAll(eic EnvoyInstanceConfig, bootstrapBuilder EnvoyBootstrapBuilder) error {
go func() {
<-eic.Context().Done()
ei.Clean()
}()
if ei.ID == "" {
ei.ID = "ingress~for-testing"
}
ei.Role = eic.Role()
ei.Port = eic.Port()
ei.RestXdsPort = eic.RestXdsPort()
ei.envoycfg = bootstrapBuilder.Build(ei)
if ei.UseDocker {
return ei.runContainer(eic.Context())
}
args := []string{"--config-yaml", ei.envoycfg, "--disable-hot-restart", "--log-level", "debug"}
// run directly
cmd := exec.CommandContext(eic.Context(), ei.envoypath, args...)
buf := &bytes.Buffer{}
ei.logs = buf
w := io.MultiWriter(ginkgo.GinkgoWriter, buf)
cmd.Stdout = w
cmd.Stderr = w
runner := Runner{Sourcepath: ei.envoypath, ComponentName: "ENVOY"}
cmd, err := runner.run(cmd)
if err != nil {
return err
}
ei.cmd = cmd
err = ei.waitForEnvoyToBeRunning()
if err != nil {
return err
}
return nil
}
func (ei *EnvoyInstance) Binary() string {
return ei.envoypath
}
func (ei *EnvoyInstance) LocalAddr() string {
return ei.GlooAddr
}
func (ei *EnvoyInstance) EnablePanicMode() error {
return ei.setRuntimeConfiguration(fmt.Sprintf("upstream.healthy_panic_threshold=%d", 100))
}
func (ei *EnvoyInstance) DisablePanicMode() error {
return ei.setRuntimeConfiguration(fmt.Sprintf("upstream.healthy_panic_threshold=%d", 0))
}
func (ei *EnvoyInstance) setRuntimeConfiguration(queryParameters string) error {
_, err := http.Post(fmt.Sprintf("http://localhost:%d/runtime_modify?%s", ei.AdminPort, queryParameters), "", nil)
return err
}
func (ei *EnvoyInstance) Clean() {
if ei == nil {
return
}
http.Post(fmt.Sprintf("http://localhost:%d/quitquitquit", ei.AdminPort), "", nil)
if ei.cmd != nil {
ei.cmd.Process.Kill()
ei.cmd.Wait()
}
if ei.UseDocker {
// No need to handle the error here as the call to quitquitquit above should kill and exit the container
// This is just a backup to make sure it really gets deleted
stopContainer()
}
}
func (ei *EnvoyInstance) runContainer(ctx context.Context) error {
envoyImageTag := getEnvoyImageTag()
if envoyImageTag == "" {
return errors.New("Must set the ENVOY_IMAGE_TAG env var. Find valid tag names here https://quay.io/repository/solo-io/gloo-envoy-wrapper?tab=tags")
}
image := "quay.io/solo-io/gloo-envoy-wrapper:" + envoyImageTag
args := []string{"run", "--rm", "--name", containerName,
"-p", fmt.Sprintf("%d:%d", defaults.HttpPort, defaults.HttpPort),
"-p", fmt.Sprintf("%d:%d", defaults.HttpsPort, defaults.HttpsPort),
"-p", fmt.Sprintf("%d:%d", ei.AdminPort, ei.AdminPort),
}
for _, volume := range ei.DockerOptions.Volumes {
args = append(args, "-v", volume)
}
for _, env := range ei.DockerOptions.Env {
args = append(args, "-e", env)
}
args = append(args,
"--entrypoint=envoy",
image,
"--disable-hot-restart",
"--log-level", "debug",
"--config-yaml", ei.envoycfg,
)
fmt.Fprintln(ginkgo.GinkgoWriter, args)
cmd := exec.CommandContext(ctx, "docker", args...)
cmd.Stdout = ginkgo.GinkgoWriter
cmd.Stderr = ginkgo.GinkgoWriter
if err := cmd.Start(); err != nil {
return errors.Wrap(err, "Unable to start envoy container")
}
// cmd.Run() is entering an infinite loop here (not sure why).
// This is a temporary workaround to poll the container until the admin port is ready for traffic
return ei.waitForEnvoyToBeRunning()
}
func (ei *EnvoyInstance) waitForEnvoyToBeRunning() error {
pingInterval := time.Tick(time.Second)
pingDuration := time.Second * 15
pingEndpoint := fmt.Sprintf("localhost:%d", ei.AdminPort)
ctx, cancel := context.WithTimeout(context.Background(), pingDuration)
defer cancel()
for {
select {
case <-ctx.Done():
return errors.Errorf("timed out waiting for envoy on %s", pingEndpoint)
case <-pingInterval:
conn, _ := net.Dial("tcp", pingEndpoint)
if conn != nil {
conn.Close()
return nil
}
continue
}
}
}
func stopContainer() error {
cmd := exec.Command("docker", "stop", containerName)
cmd.Stdout = ginkgo.GinkgoWriter
cmd.Stderr = ginkgo.GinkgoWriter
err := cmd.Run()
if err != nil {
return errors.Wrap(err, "Error stopping container "+containerName)
}
return nil
}
func localAddr() (string, error) {
ip := os.Getenv("GLOO_IP")
if ip != "" {
return ip, nil
}
// go over network interfaces
ifaces, err := net.Interfaces()
if err != nil {
return "", err
}
for _, i := range ifaces {
if (i.Flags&net.FlagUp == 0) ||
(i.Flags&net.FlagLoopback != 0) ||
(i.Flags&net.FlagPointToPoint != 0) {
continue
}
addrs, err := i.Addrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
if v.IP.To4() != nil {
return v.IP.String(), nil
}
case *net.IPAddr:
if v.IP.To4() != nil {
return v.IP.String(), nil
}
}
}
}
return "", errors.New("unable to find Gloo IP")
}
func (ei *EnvoyInstance) Logs() (string, error) {
if ei.UseDocker {
logsArgs := []string{"logs", containerName}
cmd := exec.Command("docker", logsArgs...)
byt, err := cmd.CombinedOutput()
if err != nil {
return "", errors.Wrap(err, "Unable to fetch logs from envoy container")
}
return string(byt), nil
}
return ei.logs.String(), nil
}