-
Notifications
You must be signed in to change notification settings - Fork 132
/
app.go
388 lines (348 loc) · 10.6 KB
/
app.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
package testsuite
import (
"bytes"
"context"
"crypto/rand"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"text/tabwriter"
"time"
"github.com/gogo/protobuf/jsonpb"
"github.com/hashicorp/go-multierror"
"github.com/mattn/go-zglob"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/push"
"github.com/renstrom/shortuuid"
"golang.org/x/sync/errgroup"
apimachineryYaml "k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/yaml"
"github.com/armadaproject/armada/internal/testsuite/build"
"github.com/armadaproject/armada/internal/testsuite/eventbenchmark"
"github.com/armadaproject/armada/internal/testsuite/eventlogger"
"github.com/armadaproject/armada/pkg/api"
"github.com/armadaproject/armada/pkg/client"
)
const metricsPrefix = "armada_testsuite_"
type App struct {
// Parameters passed to the CLI by the user.
Params *Params
// Out is used to write the output. Defaults to standard out,
// but can be overridden in tests to make assertions on the applications's output.
Out io.Writer
// Source of randomness. Tests can use a mocked random source in order to provide
// deterministic testing behaviour.
Random io.Reader
}
// Params struct holds all user-customizable parameters.
// Using a single struct for all CLI commands ensures that all flags are distinct
// and that they can be provided either dynamically on a command line, or
// statically in a config file that's reused between command runs.
type Params struct {
// Armada connection details.
ApiConnectionDetails *client.ApiConnectionDetails
// If non-empty, push metrics containing test results to a Prometheus push gateway with this url.
PrometheusPushGatewayUrl string
// Exported metrics are annotated with job=PrometheusPushGatewayJobName.
// Must be non-empty.
PrometheusPushGatewayJobName string
}
// New instantiates an App with default parameters, including standard output
// and cryptographically secure random source.
func New() *App {
return &App{
Params: &Params{},
Out: os.Stdout,
Random: rand.Reader,
}
}
// Version prints build information (e.g., current git commit) to the app output.
func (a *App) Version() error {
w := tabwriter.NewWriter(a.Out, 1, 1, 1, ' ', 0)
defer w.Flush()
_, _ = fmt.Fprintf(w, "Version:\t%s\n", build.ReleaseVersion)
_, _ = fmt.Fprintf(w, "Commit:\t%s\n", build.GitCommit)
_, _ = fmt.Fprintf(w, "Go version:\t%s\n", build.GoVersion)
_, _ = fmt.Fprintf(w, "Built:\t%s\n", build.BuildTime)
return nil
}
func (a *App) TestPattern(ctx context.Context, pattern string) (*TestSuiteReport, error) {
testSpecs, err := TestSpecsFromPattern(pattern)
if err != nil {
return nil, err
}
return a.RunTests(ctx, testSpecs)
}
func TestSpecsFromPattern(pattern string) ([]*api.TestSpec, error) {
filePaths, err := zglob.Glob(pattern)
if err != nil {
return nil, errors.Wrapf(err, "failed to glob test specs with pattern %s", pattern)
}
return TestSpecsFromFilePaths(filePaths)
}
func TestSpecsFromFilePaths(filePaths []string) ([]*api.TestSpec, error) {
rv := make([]*api.TestSpec, len(filePaths))
for i, filePath := range filePaths {
testSpec, err := TestSpecFromFilePath(filePath)
if err != nil {
return nil, err
}
rv[i] = testSpec
}
return rv, nil
}
func TestSpecFromFilePath(filePath string) (*api.TestSpec, error) {
testSpec := &api.TestSpec{}
yamlBytes, err := os.ReadFile(filePath)
if err != nil {
return nil, errors.WithStack(err)
}
if err := UnmarshalTestCase(yamlBytes, testSpec); err != nil {
return nil, errors.WithMessagef(err, "Could not parse file %s", filePath)
}
// Randomise job set for each test to ensure we're only getting events for this run.
fileName := filepath.Base(filePath)
fileName = strings.TrimSuffix(fileName, filepath.Ext(fileName))
testSpec.JobSetId = fileName + "-" + shortuuid.New()
// If no test name is provided, set it to be the filename.
if testSpec.Name == "" {
testSpec.Name = fileName
}
return testSpec, nil
}
type TestSuiteReport struct {
Start time.Time
Finish time.Time
TestCaseReports []*TestCaseReport
}
func (tsr *TestSuiteReport) Describe(c chan<- *prometheus.Desc) {
for _, tcr := range tsr.TestCaseReports {
tcr.Describe(c)
}
}
func (tsr *TestSuiteReport) Collect(c chan<- prometheus.Metric) {
for _, tcr := range tsr.TestCaseReports {
tcr.Collect(c)
}
}
type TestCaseReport struct {
Out *bytes.Buffer
Start time.Time
Finish time.Time
FailureReason string
BenchmarkReport *eventbenchmark.TestCaseBenchmarkReport
TestSpec *api.TestSpec
// Prometheus metric descriptions.
// Test start time in seconds since the epoch.
startTimePrometheusDesc *prometheus.Desc
// Test finish time in seconds since the epoch.
finishTimePrometheusDesc *prometheus.Desc
// Outputs 1 on test timeout.
testTimeoutPrometheusDesc *prometheus.Desc
// Outputs 1 on test failure, not including timeouts.
testFailurePrometheusDesc *prometheus.Desc
}
func NewTestCaseReport(testSpec *api.TestSpec) *TestCaseReport {
rv := &TestCaseReport{
Start: time.Now(),
TestSpec: testSpec,
}
rv.initialiseMetrics()
return rv
}
func (r *TestCaseReport) initialiseMetrics() {
r.startTimePrometheusDesc = prometheus.NewDesc(
metricsPrefix+"test_start_time",
"The time at which a test started.",
[]string{"testcase", "environment", "target"},
nil,
)
r.finishTimePrometheusDesc = prometheus.NewDesc(
metricsPrefix+"test_finish_time",
"The time at which a test finished.",
[]string{"testcase", "environment", "target"},
nil,
)
r.testTimeoutPrometheusDesc = prometheus.NewDesc(
metricsPrefix+"test_timeout",
"Outputs 1 on test timeout and 0 otherwise.",
[]string{"testcase", "environment", "target"},
nil,
)
r.testFailurePrometheusDesc = prometheus.NewDesc(
metricsPrefix+"test_failure",
"Outputs 1 on test failure, not including timeout, and 0 otherwise.",
[]string{"testcase", "environment", "target"},
nil,
)
}
func (r *TestCaseReport) Describe(c chan<- *prometheus.Desc) {
c <- r.startTimePrometheusDesc
c <- r.finishTimePrometheusDesc
c <- r.testTimeoutPrometheusDesc
c <- r.testFailurePrometheusDesc
}
func (r *TestCaseReport) Collect(c chan<- prometheus.Metric) {
c <- prometheus.MustNewConstMetric(
r.startTimePrometheusDesc,
prometheus.CounterValue,
float64(r.Start.Unix()),
r.TestSpec.Name,
r.TestSpec.Environment,
r.TestSpec.Target,
)
c <- prometheus.MustNewConstMetric(
r.finishTimePrometheusDesc,
prometheus.CounterValue,
float64(r.Finish.Unix()),
r.TestSpec.Name,
r.TestSpec.Environment,
r.TestSpec.Target,
)
// Test failures always contain either "unexpected event for job" or "error asserting failure reason".
// TODO(albin): Improve this.
testFailure := 0.0
if strings.Contains(r.FailureReason, "unexpected event for job") || strings.Contains(r.FailureReason, "error asserting failure reason") {
testFailure = 1.0
}
c <- prometheus.MustNewConstMetric(
r.testFailurePrometheusDesc,
prometheus.GaugeValue,
testFailure,
r.TestSpec.Name,
r.TestSpec.Environment,
r.TestSpec.Target,
)
// We assume that any other failures are due to timeout.
// TODO(albin): Improve this.
testTimeout := 0.0
if r.FailureReason != "" && testFailure == 0 {
testTimeout = 1.0
}
c <- prometheus.MustNewConstMetric(
r.testTimeoutPrometheusDesc,
prometheus.GaugeValue,
testTimeout,
r.TestSpec.Name,
r.TestSpec.Environment,
r.TestSpec.Target,
)
}
func (report *TestSuiteReport) NumSuccesses() int {
if report == nil {
return 0
}
rv := 0
for _, r := range report.TestCaseReports {
if r != nil && r.FailureReason == "" {
rv++
}
}
return rv
}
func (report *TestSuiteReport) NumFailures() int {
if report == nil {
return 0
}
rv := 0
for _, r := range report.TestCaseReports {
if r != nil && r.FailureReason != "" {
rv++
}
}
return rv
}
func (a *App) RunTests(ctx context.Context, testSpecs []*api.TestSpec) (*TestSuiteReport, error) {
rv := &TestSuiteReport{
Start: time.Now(),
TestCaseReports: make([]*TestCaseReport, len(testSpecs)),
}
defer func() {
rv.Finish = time.Now()
}()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
g, ctx := errgroup.WithContext(ctx)
eventLogger := eventlogger.New(make(chan *api.EventMessage), time.Second)
eventLogger.Out = a.Out
wg := sync.WaitGroup{}
wg.Add(len(testSpecs))
for i, testSpec := range testSpecs {
i := i
testRunner := TestRunner{
Out: a.Out,
apiConnectionDetails: a.Params.ApiConnectionDetails,
testSpec: testSpec,
eventLogger: eventLogger,
}
go func() {
_ = testRunner.Run(ctx)
rv.TestCaseReports[i] = testRunner.TestCaseReport
wg.Done()
}()
time.Sleep(100 * time.Millisecond)
}
fmt.Fprintf(a.Out, "---\n")
g.Go(func() error { return eventLogger.Run(ctx) })
wg.Wait()
cancel()
if err := g.Wait(); err != nil {
return nil, err
}
// Optionally push metrics.
if a.Params.PrometheusPushGatewayUrl != "" {
if err := pushTestSuiteReportMetrics(rv, a.Params.PrometheusPushGatewayUrl, a.Params.PrometheusPushGatewayJobName); err != nil {
return nil, err
}
}
return rv, nil
}
func pushTestSuiteReportMetrics(tsr *TestSuiteReport, url, job string) error {
pusher := push.New(url, job)
pusher.Collector(tsr)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := pusher.PushContext(ctx); err != nil {
return errors.WithStack(err)
}
return nil
}
// UnmarshalTestCase unmarshalls bytes into a TestSpec.
func UnmarshalTestCase(yamlBytes []byte, testSpec *api.TestSpec) error {
var result *multierror.Error
successExpectedEvents := false
successEverythingElse := false
yamlSpecSeparator := []byte("\n---\n")
docs := bytes.Split(yamlBytes, yamlSpecSeparator)
for _, docYamlBytes := range docs {
// yaml.Unmarshal can unmarshal everything,
// but leaves oneof fields empty (these are silently discarded).
if err := apimachineryYaml.NewYAMLOrJSONDecoder(bytes.NewReader(yamlBytes), 128).Decode(testSpec); err != nil {
result = multierror.Append(result, err)
} else {
successEverythingElse = true
}
// YAMLToJSON + jsonpb.Unmarshaler can unmarshal oneof fields,
// but can't unmarshal k8s pod specs.
docJsonBytes, err := yaml.YAMLToJSON(docYamlBytes)
if err != nil {
result = multierror.Append(result, err)
continue
}
unmarshaler := jsonpb.Unmarshaler{AllowUnknownFields: true}
err = unmarshaler.Unmarshal(bytes.NewReader(docJsonBytes), testSpec)
if err != nil {
result = multierror.Append(result, err)
} else {
successExpectedEvents = true
}
}
if !successExpectedEvents || !successEverythingElse {
return result.ErrorOrNil()
}
return nil
}