This repository has been archived by the owner on Mar 14, 2022. It is now read-only.
forked from istio/istio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.go
381 lines (323 loc) · 10.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
// Copyright 2017 Istio Authors. All Rights Reserved.
//
// 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"
"testing"
"time"
rpc "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
filtersBeforeMixer string
noMixer bool
noProxy bool
noBackend bool
mfConfVersion string
disableHotRestart bool
// 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
}
// MixerFilterConfigV1 is version v1 for Mixer filter config.
const MixerFilterConfigV1 = "\"v1\": "
// MixerFilterConfigV2 is version v2 for Mixer filter config.
const MixerFilterConfigV2 = "\"v2\": "
// 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,
mfConfVersion: MixerFilterConfigV2,
AccessLogPath: "/tmp/envoy-access.log",
}
}
// MfConfig get Mixer filter config
func (s *TestSetup) MfConfig() *MixerFilterConf {
return s.mfConf
}
// SetMixerFilterConfVersion sets Mixer filter config version into Envoy config.
func (s *TestSetup) SetMixerFilterConfVersion(ver string) {
s.mfConfVersion = ver
}
// 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
}
// 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
}
// 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
}
// SetUp setups Envoy, Mixer, and Backend server for test.
func (s *TestSetup) SetUp() error {
var err error
s.envoy, err = s.NewEnvoy(s.stress, s.filtersBeforeMixer, s.mfConf, s.ports, s.epoch, s.mfConfVersion, s.disableHotRestart)
if err != nil {
log.Printf("unable to create Envoy %v", err)
return err
}
err = s.envoy.Start()
if err != nil {
return err
}
if !s.noProxy {
WaitForPort(s.ports.ClientProxyPort)
WaitForPort(s.ports.ServerProxyPort)
}
if !s.noMixer {
s.mixer, err = NewMixerServer(s.ports.MixerPort, s.stress)
if err != nil {
log.Printf("unable to create mixer server %v", err)
} else {
s.mixer.Start()
}
}
if !s.noBackend {
s.backend, err = NewHTTPServer(s.ports.BackendPort)
if err != nil {
log.Printf("unable to create HTTP server %v", err)
} else {
s.backend.Start()
}
}
return nil
}
// TearDown shutdown the servers.
func (s *TestSetup) TearDown() {
_ = s.envoy.Stop()
if s.mixer != nil {
s.mixer.Stop()
}
if s.backend != nil {
s.backend.Stop()
}
}
// ReStartEnvoy restarts Envoy
func (s *TestSetup) ReStartEnvoy() {
_ = s.envoy.Stop()
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(s.stress, s.filtersBeforeMixer, s.mfConf, s.ports, s.epoch, s.mfConfVersion, s.disableHotRestart)
if err != nil {
s.t.Errorf("unable to re-start Envoy %v", err)
} else {
_ = s.envoy.Start()
if !s.noProxy {
WaitForPort(s.ports.ClientProxyPort)
WaitForPort(s.ports.ServerProxyPort)
}
}
}
// VerifyCheckCount verifies the number of Check calls.
func (s *TestSetup) VerifyCheckCount(tag string, expected int) {
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) {
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) {
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) {
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)
}
}
// VerifyQuota verified Quota request data.
func (s *TestSetup) VerifyQuota(tag string, name string, amount int64) {
<-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", 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"`
}
// 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(actualStats string, expectedStats map[string]int) {
actualStatsMap := s.unmarshalStats(actualStats)
for eStatsName, eStatsValue := range expectedStats {
aStatsValue, ok := actualStatsMap[eStatsName]
if !ok {
s.t.Fatalf("Failed to find expected Stat %s\n", eStatsName)
}
if aStatsValue != eStatsValue {
s.t.Fatalf("Stats %s does not match. Expected vs Actual: %d vs %d",
eStatsName, eStatsValue, aStatsValue)
} else {
log.Printf("stat %s is matched. value is %d", eStatsName, eStatsValue)
}
}
}
// VerifyStatsLT verifies that Envoy stats contains stat expectedStat, whose value is less than
// expectedStatVal.
func (s *TestSetup) VerifyStatsLT(actualStats string, expectedStat string, expectedStatVal int) {
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
}
}()
}