/
aggregator_test.go
543 lines (482 loc) · 19.5 KB
/
aggregator_test.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
/*
Copyright 2018 Heptio Inc.
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 aggregation
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"testing"
"testing/iotest"
"time"
"github.com/kylelemons/godebug/pretty"
"github.com/vmware-tanzu/sonobuoy/pkg/backplane/ca/authtest"
"github.com/vmware-tanzu/sonobuoy/pkg/plugin"
pluginutils "github.com/vmware-tanzu/sonobuoy/pkg/plugin/driver/utils"
"github.com/vmware-tanzu/sonobuoy/pkg/tarball"
)
func TestAggregation(t *testing.T) {
expected := []plugin.ExpectedResult{
{NodeName: "node1", ResultType: "systemd_logs"},
}
withAggregator(t, expected, func(agg *Aggregator, srv *authtest.Server) {
URL, err := NodeResultURL(srv.URL, "node1", "systemd_logs")
if err != nil {
t.Fatalf("couldn't get test server URL: %v", err)
}
resp := doRequest(t, srv.Client(), "PUT", URL, []byte("foo"))
if resp.StatusCode != 200 {
body, _ := ioutil.ReadAll(resp.Body)
t.Errorf("Got (%v) response from server: %v", resp.StatusCode, string(body))
}
if result, ok := agg.Results["systemd_logs/node1"]; ok {
bytes, err := ioutil.ReadFile(path.Join(agg.OutputDir, result.Path(), defaultFilename))
if string(bytes) != "foo" {
t.Errorf("results for node1 incorrect (got %v): %v", string(bytes), err)
}
} else {
t.Errorf("AggregationServer didn't record a result for node1. Got: %+v", agg.Results)
}
})
}
func TestAggregation_noExtension(t *testing.T) {
expected := []plugin.ExpectedResult{
{NodeName: "node1", ResultType: "systemd_logs"},
}
withAggregator(t, expected, func(agg *Aggregator, srv *authtest.Server) {
URL, err := NodeResultURL(srv.URL, "node1", "systemd_logs")
if err != nil {
t.Fatalf("couldn't get test server URL: %v", err)
}
resp := doRequest(t, srv.Client(), "PUT", URL, []byte("foo"))
if resp.StatusCode != 200 {
body, _ := ioutil.ReadAll(resp.Body)
t.Errorf("Got (%v) response from server: %v", resp.StatusCode, string(body))
}
if result, ok := agg.Results["systemd_logs/node1"]; ok {
bytes, err := ioutil.ReadFile(path.Join(agg.OutputDir, result.Path(), defaultFilename))
if string(bytes) != "foo" {
t.Errorf("results for node1 incorrect (got %v): %v", string(bytes), err)
}
} else {
t.Errorf("AggregationServer didn't record a result for node1. Got: %+v", agg.Results)
}
})
}
func TestAggregation_tarfile(t *testing.T) {
expected := []plugin.ExpectedResult{
{ResultType: "e2e", NodeName: "global"},
}
fileBytes := []byte("foo")
tarBytes := makeTarWithContents(t, "inside_tar.txt", fileBytes)
withAggregator(t, expected, func(agg *Aggregator, srv *authtest.Server) {
URL, err := GlobalResultURL(srv.URL, "e2e")
if err != nil {
t.Fatalf("couldn't get test server URL: %v", err)
}
headers := http.Header{}
headers.Add("content-type", "application/gzip")
resp := doRequestWithHeaders(t, srv.Client(), "PUT", URL, tarBytes, headers)
if resp.StatusCode != 200 {
body, _ := ioutil.ReadAll(resp.Body)
t.Errorf("Got (%v) response from server: %v", resp.StatusCode, string(body))
}
if result, ok := agg.Results["e2e/global"]; ok {
realBytes, err := ioutil.ReadFile(path.Join(agg.OutputDir, result.Path(), "inside_tar.txt"))
if err != nil || bytes.Compare(realBytes, fileBytes) != 0 {
t.Logf("results e2e tests incorrect (got %v, expected %v): %v", string(realBytes), string(fileBytes), err)
output, _ := exec.Command("ls", "-lR", agg.OutputDir).CombinedOutput()
t.Log(string(output))
t.Fail()
}
} else {
t.Errorf("AggregationServer didn't record a result for e2e tests. Got: %+v", agg.Results)
for k, v := range agg.Results {
t.Logf("Result %q: %+v\n", k, v)
}
}
})
}
func TestAggregation_wrongnodes(t *testing.T) {
expected := []plugin.ExpectedResult{
{NodeName: "node1", ResultType: "systemd_logs"},
}
withAggregator(t, expected, func(agg *Aggregator, srv *authtest.Server) {
URL, err := NodeResultURL(srv.URL, "randomnodename", "systemd_logs")
if err != nil {
t.Fatalf("couldn't get test server URL: %v", err)
}
resp := doRequest(t, srv.Client(), "PUT", URL, []byte("foo"))
if resp.StatusCode != 403 {
t.Errorf("Expected a 403 forbidden for checking in an unexpected node, got %v", resp.StatusCode)
}
if _, ok := agg.Results["systemd_logs/node10"]; ok {
t.Fatal("Aggregator accepted a result from an unexpected host")
}
})
}
func TestAggregation_duplicates(t *testing.T) {
expected := []plugin.ExpectedResult{
{NodeName: "node1", ResultType: "systemd_logs"},
{NodeName: "node12", ResultType: "systemd_logs"},
}
withAggregator(t, expected, func(agg *Aggregator, srv *authtest.Server) {
URL, err := NodeResultURL(srv.URL, "node1", "systemd_logs")
if err != nil {
t.Fatalf("couldn't get test server URL: %v", err)
}
// Check in a node
resp := doRequest(t, srv.Client(), "PUT", URL, []byte("foo"))
if resp.StatusCode != 200 {
t.Errorf("Got non-200 response from server: %v", resp.StatusCode)
}
// Check in the same node again, should conflict
resp = doRequest(t, srv.Client(), "PUT", URL, []byte("foo"))
if resp.StatusCode != 409 {
t.Errorf("Expected a 409 conflict for checking in a duplicate node, got %v", resp.StatusCode)
}
if _, ok := agg.Results["node10"]; ok {
t.Fatal("Aggregator accepted a result from an unexpected host")
}
})
}
func TestAggregation_duplicatesWithErrors(t *testing.T) {
// Setup aggregator with expected results and preload the test data/info
// that we want to transmit/compare against.
dir, err := ioutil.TempDir("", "sonobuoy_server_test")
if err != nil {
t.Fatalf("Could not create temp directory: %v", err)
}
defer os.RemoveAll(dir)
outpath := filepath.Join(dir, "systemd_logs", "results", "node1", "fakeLogData.txt")
testDataPath := "./testdata/fakeLogData.txt"
testinfo, err := os.Stat(testDataPath)
if err != nil {
t.Fatalf("Could not stat test file: %v", err)
}
testDataReader, err := os.Open(testDataPath)
if err != nil {
t.Fatalf("Could not open test data file: %v", err)
}
defer testDataReader.Close()
expected := []plugin.ExpectedResult{
{NodeName: "node1", ResultType: "systemd_logs"},
{NodeName: "node12", ResultType: "systemd_logs"},
}
agg := NewAggregator(dir, expected)
// Send first result and force an error in processing.
errReader := iotest.TimeoutReader(testDataReader)
err = agg.processResult(&plugin.Result{Body: errReader, NodeName: "node1", ResultType: "systemd_logs", Filename: "fakeLogData.txt"})
if err == nil {
t.Fatal("Expected error processing this due to reading error, instead got nil.")
}
// Confirm results are recorded but they are partial results.
realinfo, err := os.Stat(outpath)
if err != nil {
t.Fatalf("Could not stat output file: %v", err)
}
if realinfo.Size() == testinfo.Size() {
t.Fatal("Expected truncated results for first result (simulating error), but got all the data.")
}
// Retry the result without an error this time.
_, err = testDataReader.Seek(0, 0)
if err != nil {
t.Fatalf("Could not rewind test data file: %v", err)
}
err = agg.processResult(&plugin.Result{Body: testDataReader, NodeName: "node1", ResultType: "systemd_logs", Filename: "fakeLogData.txt"})
if err != nil {
t.Errorf("Expected no error processing this result, got %v", err)
}
// Confirm the new results overwrite the old ones.
realinfo, err = os.Stat(outpath)
if err != nil {
t.Fatalf("Could not stat output file: %v", err)
}
if realinfo.Size() != testinfo.Size() {
t.Errorf("Expected all the data to be transmitted. Expected data size %v but got %v.", testinfo.Size(), realinfo.Size())
}
}
// TestAggregation_RetryWindow ensures that the server Wait() method
// gives clients a chance to retry if their results were not processed correctly.
func TestAggregation_RetryWindow(t *testing.T) {
// Setup aggregator with expected results and preload the test data/info
// that we want to transmit/compare against.
dir, err := ioutil.TempDir("", "sonobuoy_server_test")
if err != nil {
t.Fatalf("Could not create temp directory: %v", err)
}
defer os.RemoveAll(dir)
testRetryWindow := 1 * time.Second
testBufferDuration := 200 * time.Millisecond
expected := []plugin.ExpectedResult{
{NodeName: "node1", ResultType: "systemd_logs"},
}
testCases := []struct {
desc string
postProcessSleep time.Duration
simulateErr bool
expectExtraWait time.Duration
}{
{
desc: "Error causes us to wait at least the retry window",
simulateErr: true,
expectExtraWait: testRetryWindow,
}, {
desc: "Retry window is sliding",
simulateErr: true,
postProcessSleep: 500 * time.Millisecond,
expectExtraWait: 500 * time.Millisecond,
}, {
desc: "Retry window can slide to 0",
simulateErr: true,
postProcessSleep: testRetryWindow,
expectExtraWait: 0,
}, {
desc: "No retry window without error",
simulateErr: false,
expectExtraWait: 0,
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
agg := NewAggregator(dir, expected)
// Shorten retry window for testing.
agg.retryWindow = testRetryWindow
testDataPath := "./testdata/fakeLogData.txt"
testDataReader, err := os.Open(testDataPath)
if err != nil {
t.Fatalf("Could not open test data file: %v", err)
}
defer testDataReader.Close()
var r io.Reader
if tc.simulateErr {
r = iotest.TimeoutReader(testDataReader)
} else {
r = strings.NewReader("foo")
}
err = agg.processResult(&plugin.Result{Body: r, NodeName: "node1", ResultType: "systemd_logs"})
if err == nil && tc.simulateErr {
t.Fatal("Expected error processing this due to reading error, instead got nil.")
}
// check time before/after wait and ensure it is greater than the retryWindow.
time.Sleep(tc.postProcessSleep)
start := time.Now()
agg.Wait(make(chan bool))
waitTime := time.Now().Sub(start)
// Add buffer to avoid raciness due to processing time.
diffTime := waitTime - tc.expectExtraWait
if diffTime > testBufferDuration || diffTime < -1*testBufferDuration {
t.Errorf("Expected Wait() to wait the duration %v (+/- %v), instead waited %v", tc.expectExtraWait, testBufferDuration, waitTime)
}
})
}
}
func TestAggregation_errors(t *testing.T) {
expected := []plugin.ExpectedResult{
{ResultType: "e2e", NodeName: "global"},
}
withAggregator(t, expected, func(agg *Aggregator, srv *authtest.Server) {
resultsCh := make(chan *plugin.Result)
go agg.IngestResults(context.TODO(), resultsCh)
// Send an error
resultsCh <- pluginutils.MakeErrorResult("e2e", map[string]interface{}{"error": "foo"}, "global")
agg.Wait(make(chan bool))
if result, ok := agg.Results["e2e/global"]; ok {
bytes, err := ioutil.ReadFile(path.Join(agg.OutputDir, result.Path(), "error.json"))
if err != nil || string(bytes) != `{"error":"foo"}` {
t.Errorf("results for e2e plugin incorrect (got %v): %v", string(bytes), err)
}
} else {
t.Errorf("Aggregator didn't record error result from e2e plugin, got %v", agg.Results)
}
})
}
func TestProcessProgressUpdates(t *testing.T) {
defaultExpectedResults := []plugin.ExpectedResult{
{ResultType: "type1", NodeName: "global"},
{ResultType: "type2", NodeName: "node1"},
{ResultType: "type2", NodeName: "node2"},
}
type singleProgressEvent struct {
progressUpdate plugin.ProgressUpdate
expectedErr string
expectedHTTPCode int
expectedProgressUpdates map[string]plugin.ProgressUpdate
}
testCases := []struct {
desc string
expectedResults []plugin.ExpectedResult
// each test run will loop through processing a series of updates
events []singleProgressEvent
}{
{
desc: "Unexpected progress update results in Forbidden",
expectedResults: defaultExpectedResults,
events: []singleProgressEvent{
{
progressUpdate: plugin.ProgressUpdate{PluginName: "foo", Node: "bar"},
expectedHTTPCode: http.StatusForbidden,
expectedErr: "progress update for foo/bar unexpected",
},
},
}, {
desc: "Latest updates get updated even with errors before and after",
expectedResults: defaultExpectedResults,
events: []singleProgressEvent{
{
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "hi"},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "hi"}},
},
{
progressUpdate: plugin.ProgressUpdate{PluginName: "foo", Node: "bar"},
expectedHTTPCode: http.StatusForbidden,
expectedErr: "progress update for foo/bar unexpected",
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "hi"}},
},
{
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "bye"},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "bye"}},
},
{
progressUpdate: plugin.ProgressUpdate{PluginName: "foo", Node: "bar"},
expectedHTTPCode: http.StatusForbidden,
expectedErr: "progress update for foo/bar unexpected",
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "bye"}},
},
},
}, {
desc: "Append to progress",
expectedResults: defaultExpectedResults,
events: []singleProgressEvent{
{
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "hi", AppendTotals: true},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "hi"}},
}, {
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "msg2", AppendTotals: true, AppendCompleted: 3, AppendFailing: []string{"foo"}},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "msg2", Total: 4, Completed: 3, Failures: []string{"foo"}}},
}, {
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "msg3", AppendTotals: true, AppendCompleted: 4},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "msg3", Total: 8, Completed: 7, Failures: []string{"foo"}}},
}, {
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "msg4", AppendTotals: true, AppendCompleted: 5, AppendFailing: []string{"bar"}},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "msg4", Total: 14, Completed: 12, Failures: []string{"foo", "bar"}}},
},
},
}, {
desc: "Append to progress",
expectedResults: defaultExpectedResults,
events: []singleProgressEvent{
{
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "hi", AppendTotals: true},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "hi"}},
}, {
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "msg2", AppendTotals: true, AppendCompleted: 3, AppendFailing: []string{"foo"}},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "msg2", Total: 4, Completed: 3, Failures: []string{"foo"}}},
}, {
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "NO_APPEND", Total: 33, Completed: 33},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "NO_APPEND", Total: 33, Completed: 33}},
}, {
progressUpdate: plugin.ProgressUpdate{PluginName: "type1", Node: "global", Message: "final", AppendTotals: true, AppendCompleted: 4},
expectedProgressUpdates: map[string]plugin.ProgressUpdate{"type1/global": {PluginName: "type1", Node: "global", Message: "final", Total: 37, Completed: 37}},
},
},
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
withAggregator(t, tc.expectedResults, func(agg *Aggregator, srv *authtest.Server) {
for _, v := range tc.events {
err := agg.processProgressUpdate(v.progressUpdate)
// Check error string
if err != nil && len(v.expectedErr) == 0 {
t.Fatalf("Expected nil error but got %q", err)
}
if err == nil && len(v.expectedErr) > 0 {
t.Fatalf("Expected error %q but got nil", v.expectedErr)
}
if err != nil && fmt.Sprint(err) != v.expectedErr {
t.Fatalf("Expected error to be %q but got %q", v.expectedErr, err)
}
// Check http status of the call
if v.expectedHTTPCode > 0 {
herr, ok := err.(*httpError)
if !ok {
t.Errorf("Expected HTTP error with status %v but got a type %T: %v", v.expectedHTTPCode, err, err)
} else if herr.HttpCode() != v.expectedHTTPCode {
t.Errorf("Expected error with HTTP code %v but got %v", v.expectedHTTPCode, herr.HttpCode())
}
}
// Check the result of the update
if diff := pretty.Compare(agg.LatestProgressUpdates, v.expectedProgressUpdates); diff != "" {
t.Errorf("Unexpected difference in the LatestProgressUpdates:\n\n%s\n", diff)
}
}
})
})
}
}
func withAggregator(t *testing.T, expected []plugin.ExpectedResult, callback func(*Aggregator, *authtest.Server)) {
dir, err := ioutil.TempDir("", "sonobuoy_server_test")
if err != nil {
t.Fatal("Could not create temp directory")
return
}
defer os.RemoveAll(dir)
agg := NewAggregator(dir, expected)
handler := NewHandler(agg.HandleHTTPResult, agg.HandleHTTPProgressUpdate)
srv := authtest.NewTLSServer(handler, t)
defer srv.Close()
// Run the server, ensuring it's fully stopped before returning
callback(agg, srv)
}
// Create a gzipped tar file with the given filename (and contents) inside it,
// return the raw bytes for that tar file.
func makeTarWithContents(t *testing.T, filename string, fileContents []byte) (tarbytes []byte) {
dir, err := ioutil.TempDir("", "sonobuoy_server_test")
if err != nil {
t.Fatalf("Could not create temp directory: %v", err)
return
}
defer os.RemoveAll(dir)
tardir := path.Join(dir, "results")
err = os.Mkdir(tardir, 0755)
if err != nil {
t.Fatalf("Could not create results directory %v: %v", tardir, err)
return
}
filepath := path.Join(tardir, filename)
tarfile := path.Join(dir, "results.tar.gz")
err = ioutil.WriteFile(filepath, fileContents, 0644)
if err != nil {
t.Fatalf("Could not write to temp file %v: %v", filepath, err)
return
}
err = tarball.DirToTarball(tardir, tarfile, true)
if err != nil {
t.Fatalf("Could not create tar file %v: %v", tarfile, err)
return
}
tarbytes, err = ioutil.ReadFile(tarfile)
if err != nil {
t.Fatalf("Could not read created tar file %v: %v", tarfile, err)
return
}
return tarbytes
}