forked from istio/istio
/
setup.go
488 lines (416 loc) · 13.2 KB
/
setup.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
// Copyright 2017 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package env
import (
"encoding/json"
"fmt"
"log"
"net/http"
"testing"
"time"
"github.com/gogo/googleapis/google/rpc"
mixerpb "istio.io/api/mixer/v1"
"istio.io/istio/pkg/test"
)
// TestSetup store data for a test.
type TestSetup struct {
t *testing.T
epoch int
mfConf *MixerFilterConf
ports *Ports
envoy *Envoy
mixer *MixerServer
backend *HTTPServer
testName uint16
stress bool
noMixer bool
noProxy bool
noBackend bool
disableHotRestart bool
checkDict bool
FiltersBeforeMixer string
// EnvoyTemplate is the bootstrap config used by envoy.
EnvoyTemplate string
// EnvoyParams contain extra envoy parameters to pass in the CLI (cluster, node)
EnvoyParams []string
// EnvoyConfigOpt allows passing additional parameters to the EnvoyTemplate
EnvoyConfigOpt map[string]interface{}
// IstioSrc is the base directory of istio sources. May be set for finding testdata or
// other files in the source tree
IstioSrc string
// IstioOut is the base output directory.
IstioOut string
// AccessLogPath is the access log path for Envoy
AccessLogPath string
// expected source.uid attribute at the mixer gRPC metadata
mixerSourceUID string
// Dir is the working dir for envoy
Dir string
}
// NewTestSetup creates a new test setup
// "name" has to be defined in ports.go
func NewTestSetup(name uint16, t *testing.T) *TestSetup {
return &TestSetup{
t: t,
mfConf: GetDefaultMixerFilterConf(),
ports: NewPorts(name),
testName: name,
AccessLogPath: "/tmp/envoy-access.log",
}
}
// MfConfig get Mixer filter config
func (s *TestSetup) MfConfig() *MixerFilterConf {
return s.mfConf
}
// Ports get ports object
func (s *TestSetup) Ports() *Ports {
return s.ports
}
// SetMixerCheckReferenced set Referenced in mocked Check response
func (s *TestSetup) SetMixerCheckReferenced(ref *mixerpb.ReferencedAttributes) {
s.mixer.checkReferenced = ref
}
// SetMixerQuotaReferenced set Referenced in mocked Quota response
func (s *TestSetup) SetMixerQuotaReferenced(ref *mixerpb.ReferencedAttributes) {
s.mixer.quotaReferenced = ref
}
// SetMixerCheckStatus set Status in mocked Check response
func (s *TestSetup) SetMixerCheckStatus(status rpc.Status) {
s.mixer.check.rStatus = status
}
// SetMixerRouteDirective sets the route directive for Check precondition
func (s *TestSetup) SetMixerRouteDirective(directive *mixerpb.RouteDirective) {
s.mixer.directive = directive
}
// SetMixerQuotaStatus set Status in mocked Quota response
func (s *TestSetup) SetMixerQuotaStatus(status rpc.Status) {
s.mixer.quota.rStatus = status
}
// SetMixerQuotaLimit set mock quota limit
func (s *TestSetup) SetMixerQuotaLimit(limit int64) {
s.mixer.quotaLimit = limit
}
// GetMixerQuotaCount get the number of Quota calls.
func (s *TestSetup) GetMixerQuotaCount() int {
return s.mixer.quota.Count()
}
// GetMixerCheckCount get the number of Check calls.
func (s *TestSetup) GetMixerCheckCount() int {
return s.mixer.check.Count()
}
// GetMixerReportCount get the number of Report calls.
func (s *TestSetup) GetMixerReportCount() int {
return s.mixer.report.Count()
}
// SetStress set the stress flag
func (s *TestSetup) SetStress(stress bool) {
s.stress = stress
}
// SetCheckDict set the checkDict flag
func (s *TestSetup) SetCheckDict(checkDict bool) {
s.checkDict = checkDict
}
// SetNoMixer set NoMixer flag
func (s *TestSetup) SetNoMixer(no bool) {
s.noMixer = no
}
// SetFiltersBeforeMixer sets the configurations of the filters before the Mixer filter
func (s *TestSetup) SetFiltersBeforeMixer(filters string) {
s.FiltersBeforeMixer = filters
}
// SetDisableHotRestart sets whether disable the HotRestart feature of Envoy
func (s *TestSetup) SetDisableHotRestart(disable bool) {
s.disableHotRestart = disable
}
// SetNoProxy set NoProxy flag
func (s *TestSetup) SetNoProxy(no bool) {
s.noProxy = no
}
// SetNoBackend set NoMixer flag
func (s *TestSetup) SetNoBackend(no bool) {
s.noBackend = no
}
// SetMixerSourceUID sets the expected source.uid at the mixer server gRPC metadata
func (s *TestSetup) SetMixerSourceUID(uid string) {
s.mixerSourceUID = uid
}
// SetUp setups Envoy, Mixer, and Backend server for test.
func (s *TestSetup) SetUp() error {
var err error
s.envoy, err = s.NewEnvoy()
if err != nil {
log.Printf("unable to create Envoy %v", err)
return err
}
err = s.envoy.Start()
if err != nil {
return err
}
if !s.noMixer {
s.mixer, err = NewMixerServer(s.ports.MixerPort, s.stress, s.checkDict, s.mixerSourceUID)
if err != nil {
log.Printf("unable to create mixer server %v", err)
} else {
errCh := s.mixer.Start()
if err = <-errCh; err != nil {
log.Fatalf("mixer start failed %v", err)
}
}
}
if !s.noBackend {
s.backend, err = NewHTTPServer(s.ports.BackendPort)
if err != nil {
log.Printf("unable to create HTTP server %v", err)
} else {
errCh := s.backend.Start()
if err = <-errCh; err != nil {
log.Fatalf("backend server start failed %v", err)
}
}
}
s.WaitEnvoyReady()
return nil
}
// TearDown shutdown the servers.
func (s *TestSetup) TearDown() {
if err := s.envoy.Stop(); err != nil {
s.t.Errorf("error quitting envoy: %v", err)
}
s.envoy.TearDown()
if s.mixer != nil {
s.mixer.Stop()
}
if s.backend != nil {
s.backend.Stop()
}
}
// LastRequestHeaders returns last backend request headers
func (s *TestSetup) LastRequestHeaders() http.Header {
if s.backend != nil {
return s.backend.LastRequestHeaders()
}
return nil
}
// ReStartEnvoy restarts Envoy
func (s *TestSetup) ReStartEnvoy() {
// don't stop envoy before starting the new one since we use hot restart
oldEnvoy := s.envoy
s.ports = NewEnvoyPorts(s.ports, s.testName)
log.Printf("new allocated ports are %v:", s.ports)
var err error
s.epoch++
s.envoy, err = s.NewEnvoy()
if err != nil {
s.t.Errorf("unable to re-start envoy %v", err)
return
}
err = s.envoy.Start()
if err != nil {
s.t.Fatalf("unable to re-start envoy %v", err)
}
s.WaitEnvoyReady()
_ = oldEnvoy.Stop()
}
// VerifyCheckCount verifies the number of Check calls.
func (s *TestSetup) VerifyCheckCount(tag string, expected int) {
s.t.Helper()
test.Eventually(s.t, "VerifyCheckCount", func() bool {
return s.mixer.check.Count() == expected
})
}
// VerifyReportCount verifies the number of Report calls.
func (s *TestSetup) VerifyReportCount(tag string, expected int) {
s.t.Helper()
test.Eventually(s.t, "VerifyReportCount", func() bool {
return s.mixer.report.Count() == expected
})
}
// VerifyCheck verifies Check request data.
func (s *TestSetup) VerifyCheck(tag string, result string) {
s.t.Helper()
bag := <-s.mixer.check.ch
if err := Verify(bag, result); err != nil {
s.t.Fatalf("Failed to verify %s check: %v\n, Attributes: %+v",
tag, err, bag)
}
}
// VerifyReport verifies Report request data.
func (s *TestSetup) VerifyReport(tag string, result string) {
s.t.Helper()
bag := <-s.mixer.report.ch
if err := Verify(bag, result); err != nil {
s.t.Fatalf("Failed to verify %s report: %v\n, Attributes: %+v",
tag, err, bag)
}
}
// VerifyTwoReports verifies two Report bags, in any order.
func (s *TestSetup) VerifyTwoReports(tag string, result1, result2 string) {
s.t.Helper()
bag1 := <-s.mixer.report.ch
bag2 := <-s.mixer.report.ch
if err1 := Verify(bag1, result1); err1 != nil {
// try the other way
if err2 := Verify(bag1, result2); err2 != nil {
s.t.Fatalf("Failed to verify %s report: %v\n%v\n, Attributes: %+v",
tag, err1, err2, bag1)
} else if err3 := Verify(bag2, result1); err3 != nil {
s.t.Fatalf("Failed to verify %s report: %v\n, Attributes: %+v",
tag, err3, bag2)
}
} else if err4 := Verify(bag2, result2); err4 != nil {
s.t.Fatalf("Failed to verify %s report: %v\n, Attributes: %+v",
tag, err4, bag2)
}
}
// VerifyQuota verified Quota request data.
func (s *TestSetup) VerifyQuota(tag string, name string, amount int64) {
s.t.Helper()
<-s.mixer.quota.ch
if s.mixer.qma.Quota != name {
s.t.Fatalf("Failed to verify %s quota name: %v, expected: %v\n",
tag, s.mixer.qma.Quota, name)
}
if s.mixer.qma.Amount != amount {
s.t.Fatalf("Failed to verify %s quota amount: %v, expected: %v\n",
tag, s.mixer.qma.Amount, amount)
}
}
// WaitForStatsUpdateAndGetStats waits for waitDuration seconds to let Envoy update stats, and sends
// request to Envoy for stats. Returns stats response.
func (s *TestSetup) WaitForStatsUpdateAndGetStats(waitDuration int) (string, error) {
time.Sleep(time.Duration(waitDuration) * time.Second)
statsURL := fmt.Sprintf("http://localhost:%d/stats?format=json&usedonly", s.Ports().AdminPort)
code, respBody, err := HTTPGet(statsURL)
if err != nil {
return "", fmt.Errorf("sending stats request returns an error: %v", err)
}
if code != 200 {
return "", fmt.Errorf("sending stats request returns unexpected status code: %d", code)
}
return respBody, nil
}
type statEntry struct {
Name string `json:"name"`
Value int `json:"value"`
}
type stats struct {
StatList []statEntry `json:"stats"`
}
// WaitEnvoyReady waits until envoy receives and applies all config
func (s *TestSetup) WaitEnvoyReady() {
// Sometimes on circle CI, connection is refused even when envoy reports warm clusters and listeners...
// Inject a 1 second delay to force readiness
time.Sleep(1 * time.Second)
delay := 200 * time.Millisecond
total := 3 * time.Second
var stats map[string]int
for attempt := 0; attempt < int(total/delay); attempt++ {
statsURL := fmt.Sprintf("http://localhost:%d/stats?format=json&usedonly", s.Ports().AdminPort)
code, respBody, errGet := HTTPGet(statsURL)
if errGet == nil && code == 200 {
stats = s.unmarshalStats(respBody)
warmingListeners, hasListeners := stats["listener_manager.total_listeners_warming"]
warmingClusters, hasClusters := stats["cluster_manager.warming_clusters"]
if hasListeners && hasClusters && warmingListeners == 0 && warmingClusters == 0 {
return
}
}
time.Sleep(delay)
}
s.t.Fatalf("envoy failed to get ready: %v", stats)
}
// UnmarshalStats Unmarshals Envoy stats from JSON format into a map, where stats name is
// key, and stats value is value.
func (s *TestSetup) unmarshalStats(statsJSON string) map[string]int {
statsMap := make(map[string]int)
var statsArray stats
if err := json.Unmarshal([]byte(statsJSON), &statsArray); err != nil {
s.t.Fatalf("unable to unmarshal stats from json")
}
for _, v := range statsArray.StatList {
statsMap[v.Name] = v.Value
}
return statsMap
}
// VerifyStats verifies Envoy stats.
func (s *TestSetup) VerifyStats(expectedStats map[string]int) {
s.t.Helper()
check := func(actualStatsMap map[string]int) error {
for eStatsName, eStatsValue := range expectedStats {
aStatsValue, ok := actualStatsMap[eStatsName]
if !ok && eStatsValue != 0 {
return fmt.Errorf("failed to find expected stat %s", eStatsName)
}
if aStatsValue != eStatsValue {
return fmt.Errorf("stats %s does not match. expected vs actual: %d vs %d",
eStatsName, eStatsValue, aStatsValue)
}
log.Printf("stat %s is matched. value is %d", eStatsName, eStatsValue)
}
return nil
}
delay := 200 * time.Millisecond
total := 3 * time.Second
var err error
for attempt := 0; attempt < int(total/delay); attempt++ {
statsURL := fmt.Sprintf("http://localhost:%d/stats?format=json&usedonly", s.Ports().AdminPort)
code, respBody, errGet := HTTPGet(statsURL)
if errGet != nil {
log.Printf("sending stats request returns an error: %v", errGet)
} else if code != 200 {
log.Printf("sending stats request returns unexpected status code: %d", code)
} else {
actualStatsMap := s.unmarshalStats(respBody)
if err = check(actualStatsMap); err == nil {
return
}
log.Printf("failed to verify stats: %v", err)
}
time.Sleep(delay)
}
s.t.Errorf("failed to find expected stats: %v", err)
}
// VerifyStatsLT verifies that Envoy stats contains stat expectedStat, whose value is less than
// expectedStatVal.
func (s *TestSetup) VerifyStatsLT(actualStats string, expectedStat string, expectedStatVal int) {
s.t.Helper()
actualStatsMap := s.unmarshalStats(actualStats)
aStatsValue, ok := actualStatsMap[expectedStat]
if !ok {
s.t.Fatalf("Failed to find expected Stat %s\n", expectedStat)
} else if aStatsValue >= expectedStatVal {
s.t.Fatalf("Stat %s does not match. Expected value < %d, actual stat value is %d",
expectedStat, expectedStatVal, aStatsValue)
} else {
log.Printf("stat %s is matched. %d < %d", expectedStat, aStatsValue, expectedStatVal)
}
}
// DrainMixerAllChannels drain all channels
func (s *TestSetup) DrainMixerAllChannels() {
go func() {
for {
<-s.mixer.check.ch
}
}()
go func() {
for {
<-s.mixer.report.ch
}
}()
go func() {
for {
<-s.mixer.quota.ch
}
}()
}