-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathaggregator_test.go
2203 lines (1974 loc) · 70.4 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
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 Tigera, Inc. 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 aggregator_test
import (
"fmt"
"strings"
"testing"
"time"
. "github.com/onsi/gomega"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
googleproto "google.golang.org/protobuf/proto"
"github.com/projectcalico/calico/goldmane/pkg/aggregator"
"github.com/projectcalico/calico/goldmane/pkg/internal/utils"
"github.com/projectcalico/calico/goldmane/pkg/testutils"
"github.com/projectcalico/calico/goldmane/pkg/types"
"github.com/projectcalico/calico/goldmane/proto"
"github.com/projectcalico/calico/libcalico-go/lib/logutils"
)
var (
waitTimeout = 5 * time.Second
retryTime = 25 * time.Millisecond
)
var (
agg *aggregator.LogAggregator
c *clock
)
// initialNow is time.Now() at the start of the test. This must be
// large enough that initialNow - numBuckets * aggregationWindowSecs is positive.
const initialNow = 1000
func setupTest(t *testing.T, opts ...aggregator.Option) func() {
// Register gomega with test.
RegisterTestingT(t)
// Hook logrus into testing.T
utils.ConfigureLogging("DEBUG")
logCancel := logutils.RedirectLogrusToTestingT(t)
agg = aggregator.NewLogAggregator(opts...)
return func() {
agg.Stop()
agg = nil
c = nil
logCancel()
}
}
func ExpectFlowsEqual(t *testing.T, expected, actual *proto.Flow, additionalMsg ...string) {
if !googleproto.Equal(expected, actual) {
msg := fmt.Sprintf("\nExpected:\n\t%v\nActual:\n\t%v", expected, actual)
for _, m := range additionalMsg {
msg += "\n" + m
}
t.Error(msg)
}
}
func TestList(t *testing.T) {
c := newClock(initialNow)
now := c.Now().Unix()
opts := []aggregator.Option{
aggregator.WithRolloverTime(1 * time.Second),
aggregator.WithNowFunc(c.Now),
}
defer setupTest(t, opts...)()
// Start the aggregator.
go agg.Run(now)
// Ingest a flow log.
fl := &proto.Flow{
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
DestName: "test-dst",
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
Policies: &proto.PolicyTrace{
EnforcedPolicies: []*proto.PolicyHit{
{
Kind: proto.PolicyKind_NetworkPolicy,
Name: "cluster-dns",
Namespace: "kube-system",
Tier: "test-tier",
Action: proto.Action_Allow,
PolicyIndex: 0,
RuleIndex: 1,
},
},
},
},
StartTime: now - 15,
EndTime: now,
SourceLabels: []string{"key=valueSource"},
DestLabels: []string{"key=valueDest"},
BytesIn: 100,
BytesOut: 200,
PacketsIn: 10,
PacketsOut: 20,
NumConnectionsStarted: 1,
}
agg.Receive(types.ProtoToFlow(fl))
// Expect the aggregator to have received it.
var flows []*proto.FlowResult
var meta *proto.ListMetadata
var err error
Eventually(func() error {
var results *proto.FlowListResult
results, err = agg.List(&proto.FlowListRequest{})
meta, flows = results.Meta, results.Flows
if len(flows) == 1 {
return nil
}
return fmt.Errorf("expected 1 flow, got %d", len(flows))
}, waitTimeout, retryTime, "Didn't receive flow").ShouldNot(HaveOccurred())
Expect(meta.TotalResults).Should(BeEquivalentTo(1))
Expect(meta.TotalResults).Should(BeEquivalentTo(1))
// Expect aggregation to have happened.
exp := proto.Flow{
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
DestName: "test-dst",
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
Policies: &proto.PolicyTrace{
EnforcedPolicies: []*proto.PolicyHit{
{
Kind: proto.PolicyKind_NetworkPolicy,
Name: "cluster-dns",
Namespace: "kube-system",
Tier: "test-tier",
Action: proto.Action_Allow,
PolicyIndex: 0,
RuleIndex: 1,
},
},
},
},
StartTime: flows[0].Flow.StartTime,
EndTime: flows[0].Flow.EndTime,
SourceLabels: []string{"key=valueSource"},
DestLabels: []string{"key=valueDest"},
BytesIn: 100,
BytesOut: 200,
PacketsIn: 10,
PacketsOut: 20,
NumConnectionsStarted: 1,
}
ExpectFlowsEqual(t, &exp, flows[0].Flow)
id := flows[0].Id
// Send another copy of the flow log.
agg.Receive(types.ProtoToFlow(fl))
// Expect the aggregator to have received it. Aggregation of new flows
// happens asynchonously, so we may need to wait a few ms for it.
Eventually(func() error {
var results *proto.FlowListResult
results, err = agg.List(&proto.FlowListRequest{})
flows = results.Flows
if err != nil {
return err
}
if len(flows) != 1 {
return fmt.Errorf("Expected 1 flow, got %d", len(flows))
}
if flows[0].Flow.NumConnectionsStarted != 2 {
return fmt.Errorf("Expected 2 connections, got %d", flows[0].Flow.NumConnectionsStarted)
}
return nil
}, waitTimeout, retryTime, "Incorrect flow output").Should(BeNil())
// Expect aggregation to have happened.
exp.NumConnectionsStarted = 2
exp.BytesIn = 200
exp.BytesOut = 400
exp.PacketsIn = 20
exp.PacketsOut = 40
ExpectFlowsEqual(t, &exp, flows[0].Flow)
// ID should be unchanged.
Expect(flows[0].Id).To(Equal(id))
// Wait for the aggregator to rollover.
time.Sleep(1001 * time.Millisecond)
// Send another flow log.
agg.Receive(types.ProtoToFlow(fl))
// Expect the aggregator to have received it. This should be added to a new bucket,
// but aggregated into the same flow on read.
Eventually(func() error {
var results *proto.FlowListResult
results, err = agg.List(&proto.FlowListRequest{})
flows = results.Flows
if err != nil {
return err
}
if len(flows) != 1 {
return fmt.Errorf("Expected 1 flow, got %d", len(flows))
}
if flows[0].Flow.NumConnectionsStarted != 3 {
return fmt.Errorf("Expected 3 connections, got %d", flows[0].Flow.NumConnectionsStarted)
}
return nil
}, waitTimeout, retryTime, "Incorrect flow output").Should(BeNil())
exp2 := proto.Flow{
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
DestName: "test-dst",
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
Policies: &proto.PolicyTrace{
EnforcedPolicies: []*proto.PolicyHit{
{
Kind: proto.PolicyKind_NetworkPolicy,
Name: "cluster-dns",
Namespace: "kube-system",
Tier: "test-tier",
Action: proto.Action_Allow,
PolicyIndex: 0,
RuleIndex: 1,
},
},
},
},
StartTime: flows[0].Flow.StartTime,
EndTime: flows[0].Flow.EndTime,
SourceLabels: []string{"key=valueSource"},
DestLabels: []string{"key=valueDest"},
BytesIn: 300,
BytesOut: 600,
PacketsIn: 30,
PacketsOut: 60,
NumConnectionsStarted: 3,
}
ExpectFlowsEqual(t, &exp2, flows[0].Flow)
// ID should be unchanged.
Expect(flows[0].Id).To(Equal(int64(id)))
}
func TestLabelMerge(t *testing.T) {
// Create a clock and rollover controller.
c := newClock(initialNow)
roller := &rolloverController{
ch: make(chan time.Time),
aggregationWindowSecs: 1,
clock: c,
}
opts := []aggregator.Option{
aggregator.WithRolloverTime(1 * time.Second),
aggregator.WithRolloverFunc(roller.After),
aggregator.WithNowFunc(c.Now),
}
defer setupTest(t, opts...)()
go agg.Run(c.Now().Unix())
// Create 10 flows, each with one common label and one unique label.
// All other fields are the same.
base := testutils.NewRandomFlow(c.Now().Unix() - 1)
for i := range 10 {
fl := googleproto.Clone(base).(*proto.Flow)
fl.SourceLabels = []string{"common=src", fmt.Sprintf("unique-src=%d", i)}
fl.DestLabels = []string{"common=dst", fmt.Sprintf("unique-dest=%d", i)}
agg.Receive(types.ProtoToFlow(fl))
}
// Query for the flow, and expect that labels are properly aggregated. We should see
// the common label, but not the unique labels.
var flows []*proto.FlowResult
var err error
Eventually(func() error {
var results *proto.FlowListResult
results, err = agg.List(&proto.FlowListRequest{})
flows = results.Flows
if err != nil {
return err
}
if len(flows) != 1 {
return fmt.Errorf("Expected 1 flow, got %d", len(flows))
}
if flows[0].Flow.NumConnectionsCompleted != base.NumConnectionsCompleted*10 {
return fmt.Errorf("Expected %d connections, got %d", base.NumConnectionsCompleted*10, flows[0].Flow.NumConnectionsCompleted)
}
return nil
}, waitTimeout, retryTime, "Didn't receive flow").ShouldNot(HaveOccurred())
Expect(flows[0].Flow.SourceLabels).To(ConsistOf("common=src"))
Expect(flows[0].Flow.DestLabels).To(ConsistOf("common=dst"))
}
// TestRotation tests that the aggregator correctly rotates out old flows.
func TestRotation(t *testing.T) {
// Create a clock and rollover controller.
c := newClock(initialNow)
now := c.Now().Unix()
roller := &rolloverController{
ch: make(chan time.Time),
aggregationWindowSecs: 1,
clock: c,
}
opts := []aggregator.Option{
aggregator.WithRolloverTime(1 * time.Second),
aggregator.WithRolloverFunc(roller.After),
aggregator.WithNowFunc(c.Now),
}
defer setupTest(t, opts...)()
go agg.Run(now)
// Create a Flow. This test relies on an understanding of the underlying bucket ring:
// - The index contains two extra buckets, one currently filling, and one in the future.
// - We place this flow one bucket earlier than the currently filling bucket.
// - As such, the flow should be rotated out after sizeOf(ring) - 2 rollovers.
fl := &proto.Flow{
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
DestName: "test-dst",
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
Policies: &proto.PolicyTrace{EnforcedPolicies: []*proto.PolicyHit{}},
},
StartTime: now - 1,
EndTime: now,
BytesIn: 100,
BytesOut: 200,
PacketsIn: 10,
PacketsOut: 20,
NumConnectionsStarted: 1,
}
agg.Receive(types.ProtoToFlow(fl))
// We should be able to read it back.
var flows []*proto.FlowResult
var err error
Eventually(func() error {
var results *proto.FlowListResult
results, err = agg.List(&proto.FlowListRequest{})
flows = results.Flows
if err != nil {
return err
}
if len(flows) != 1 {
return fmt.Errorf("Expected 1 flow, got %d", len(flows))
}
return nil
}, waitTimeout, retryTime, "Didn't receive flow").ShouldNot(HaveOccurred())
// ID should is non-deterministic, but should be consistent.
flowID := flows[0].Id
Expect(flowID).To(BeNumerically(">", 0))
// Rollover the aggregator until we push the flow out of the window.
roller.rolloverAndAdvanceClock(237)
// The flow should still be here.
Eventually(func() error {
var results *proto.FlowListResult
results, err = agg.List(&proto.FlowListRequest{})
flows = results.Flows
if err != nil {
return err
}
if len(flows) != 1 {
return fmt.Errorf("Expected 1 flow, got %d", len(flows))
}
return nil
}, waitTimeout, retryTime, "Flow rotated out too early").ShouldNot(HaveOccurred())
// ID should be unchanged.
Expect(flows[0].Id).To(Equal(flowID))
// This one should do it.
roller.rolloverAndAdvanceClock(1)
// We should no longer be able to read the flow.
Consistently(func() int {
var results *proto.FlowListResult
results, _ = agg.List(&proto.FlowListRequest{})
flows = results.Flows
return len(flows)
}, waitTimeout, retryTime).Should(Equal(0), "Flow did not rotate out")
}
func TestManyFlows(t *testing.T) {
c := newClock(initialNow)
now := c.Now().Unix()
opts := []aggregator.Option{
aggregator.WithRolloverTime(1 * time.Second),
aggregator.WithNowFunc(c.Now),
}
defer setupTest(t, opts...)()
go agg.Run(now)
// Create 20k flows and send them as fast as we can. See how the aggregator handles it.
fl := &proto.Flow{
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
DestName: "test-dst",
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
Policies: &proto.PolicyTrace{EnforcedPolicies: []*proto.PolicyHit{}},
},
StartTime: now - 15,
EndTime: now,
BytesIn: 100,
BytesOut: 200,
PacketsIn: 10,
PacketsOut: 20,
NumConnectionsStarted: 1,
}
for range 20000 {
agg.Receive(types.ProtoToFlow(fl))
}
// Query for the flow.
var flows []*proto.FlowResult
var meta *proto.ListMetadata
Eventually(func() bool {
var results *proto.FlowListResult
results, _ = agg.List(&proto.FlowListRequest{})
meta = results.Meta
flows = results.Flows
if len(flows) != 1 {
return false
}
return flows[0].Flow.NumConnectionsStarted == 20000
}, waitTimeout, retryTime, "Didn't reach 20k flows: %d", len(flows)).Should(BeTrue())
Expect(meta.TotalPages).To(BeEquivalentTo(1))
Expect(meta.TotalResults).To(BeEquivalentTo(1))
}
func TestPagination(t *testing.T) {
c := newClock(initialNow)
now := c.Now().Unix()
opts := []aggregator.Option{
aggregator.WithRolloverTime(1 * time.Second),
aggregator.WithNowFunc(c.Now),
}
defer setupTest(t, opts...)()
go agg.Run(now)
// Create 30 different flows.
for i := range 30 {
fl := &proto.Flow{
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
// Each flow is to a unique destination, thus making the flow unique.
DestName: fmt.Sprintf("test-dst-%d", i),
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
Policies: &proto.PolicyTrace{EnforcedPolicies: []*proto.PolicyHit{}},
},
// Give each flow a unique time stamp, for deterministic ordering.
StartTime: now - int64(i) - 1,
EndTime: now - int64(i),
BytesIn: 100,
BytesOut: 200,
PacketsIn: 10,
PacketsOut: 20,
NumConnectionsStarted: 1,
}
agg.Receive(types.ProtoToFlow(fl))
}
// Query without pagination.
var flows []*proto.FlowResult
var err error
Eventually(func() error {
var results *proto.FlowListResult
results, err = agg.List(&proto.FlowListRequest{})
_, flows = results.Meta, results.Flows
if err != nil {
return err
}
if len(flows) != 30 {
return fmt.Errorf("Expected 30 flows, got %d", len(flows))
}
return nil
}, waitTimeout, retryTime, "Didn't receive all flows").ShouldNot(HaveOccurred())
// Query with a page size of 5, encompassing the entire time range.
results, err := agg.List(&proto.FlowListRequest{
PageSize: 5,
StartTimeGte: now - 30,
StartTimeLt: now + 1,
})
page0 := results.Flows
require.NoError(t, err)
require.Len(t, page0, 5, "Page 0 should have 5 flows")
require.Equal(t, int64(now-1), page0[0].Flow.StartTime)
require.Equal(t, int64(now-5), page0[4].Flow.StartTime)
require.NotEqual(t, page0[0].Id, page0[4].Id, "should have unique flow IDs")
// Query the third page - should be a different 5 flows (skipping page 2).
results, err = agg.List(&proto.FlowListRequest{
PageSize: 5,
Page: 2,
StartTimeGte: now - 30,
StartTimeLt: now + 1,
})
meta := results.Meta
page2 := results.Flows
require.NoError(t, err)
require.Len(t, page2, 5, "Page 2 should have 5 flows")
require.Equal(t, int64(989), page2[0].Flow.StartTime)
require.Equal(t, int64(985), page2[4].Flow.StartTime)
require.Equal(t, int64(6), meta.TotalPages, "Should have 6 pages")
require.Equal(t, int64(30), meta.TotalResults, "Should have 30 results")
// We can't assert on the actual values of the ID, but they should be
// unique and incrementing.
require.Equal(t, page2[0].Id+4, page2[4].Id)
// Pages should not be equal.
require.NotEqual(t, page0, page2, "Page 0 and 2 should not be equal")
// Query the third page again. It should be consistent (since no new data).
results, err = agg.List(&proto.FlowListRequest{
PageSize: 5,
Page: 2,
StartTimeGte: now - 30,
StartTimeLt: now + 1,
})
page2Again := results.Flows
require.NoError(t, err)
require.Equal(t, page2, page2Again, "Page 2 and 2 should be equal on second query")
}
func TestTimeRanges(t *testing.T) {
c := newClock(initialNow)
now := c.Now().Unix()
opts := []aggregator.Option{
aggregator.WithRolloverTime(1 * time.Second),
aggregator.WithNowFunc(c.Now),
}
prepareFlows := func() {
// Create a flow spread across a range of buckets within the aggregator.
// 60 buckes of 1s each means we want one flow per second for 60s.
for i := range 60 {
startTime := now - int64(i) + 1
endTime := startTime + 1
fl := &proto.Flow{
// Start one rollover period into the future, since that is how the aggregator works.
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
DestName: "test-dst",
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
Policies: &proto.PolicyTrace{EnforcedPolicies: []*proto.PolicyHit{}},
},
StartTime: startTime,
EndTime: endTime,
BytesIn: 100,
BytesOut: 200,
PacketsIn: 10,
PacketsOut: 20,
NumConnectionsStarted: 1,
}
agg.Receive(types.ProtoToFlow(fl))
}
}
type testCase struct {
name string
query *proto.FlowListRequest
expectedNumConnectionsStarted int
expectNoMatch bool
expectErr bool
}
tests := []testCase{
{
// This should return up until "now", which doesn't include flows currently being aggregated.
// i.e., it will exclude flows in the current and future buckets.
name: "All flows",
query: &proto.FlowListRequest{},
expectedNumConnectionsStarted: 58,
},
{
// This sets the time range explicitly, to include flows currently being aggregated and flows that
// are seen as from the "future" by the aggregator.
name: "All flows, including current + future",
query: &proto.FlowListRequest{StartTimeLt: now + 2},
expectedNumConnectionsStarted: 60,
},
{
name: "10s of flows",
query: &proto.FlowListRequest{StartTimeGte: now - 10, StartTimeLt: now},
expectedNumConnectionsStarted: 10,
},
{
name: "10s of flows, starting in the future",
query: &proto.FlowListRequest{StartTimeGte: now + 10, StartTimeLt: now + 20},
// Should return no flows, since the query is in the future.
expectNoMatch: true,
},
{
name: "5s of flows",
query: &proto.FlowListRequest{StartTimeGte: now - 12, StartTimeLt: now - 7},
expectedNumConnectionsStarted: 5,
},
{
name: "end time before start time",
query: &proto.FlowListRequest{StartTimeGte: now - 7, StartTimeLt: now - 12},
// Should return no flows, since the query covers 0s.
expectNoMatch: true,
expectErr: true,
},
{
name: "relative time range, last 10s",
query: &proto.FlowListRequest{StartTimeGte: -10},
expectedNumConnectionsStarted: 10,
},
{
name: "relative time range, 15s window",
query: &proto.FlowListRequest{StartTimeGte: -20, StartTimeLt: -5},
expectedNumConnectionsStarted: 15,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
defer setupTest(t, opts...)()
go agg.Run(now)
// Create flows.
prepareFlows()
// Run the query, and check how many flows we get back.
var flows []*proto.FlowResult
if !test.expectNoMatch {
// Should return one aggregated flow that sums the component flows.
Eventually(func() bool {
var results *proto.FlowListResult
results, _ = agg.List(test.query)
flows = results.Flows
return len(flows) == 1
}, waitTimeout, retryTime, "Didn't receive flow").Should(BeTrue())
Eventually(func() bool {
var results *proto.FlowListResult
results, _ = agg.List(test.query)
flows = results.Flows
return flows[0].Flow.NumConnectionsStarted == int64(test.expectedNumConnectionsStarted)
}, waitTimeout, retryTime).Should(
BeTrue(),
fmt.Sprintf("Expected %d to equal %d", flows[0].Flow.NumConnectionsStarted, test.expectedNumConnectionsStarted),
)
// Verify other fields are aggregated correctly.
exp := proto.Flow{
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
DestName: "test-dst",
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
Policies: &proto.PolicyTrace{EnforcedPolicies: []*proto.PolicyHit{}},
},
StartTime: flows[0].Flow.StartTime,
EndTime: flows[0].Flow.EndTime,
BytesIn: 100 * int64(test.expectedNumConnectionsStarted),
BytesOut: 200 * int64(test.expectedNumConnectionsStarted),
PacketsIn: 10 * int64(test.expectedNumConnectionsStarted),
PacketsOut: 20 * int64(test.expectedNumConnectionsStarted),
NumConnectionsStarted: int64(test.expectedNumConnectionsStarted),
}
ExpectFlowsEqual(t, &exp, flows[0].Flow)
} else {
// Should consistently return no flows.
for range 10 {
results, err := agg.List(test.query)
if test.expectErr {
require.Error(t, err)
require.Nil(t, results)
} else {
require.NoError(t, err)
require.Len(t, results.Flows, 0)
}
time.Sleep(10 * time.Millisecond)
}
}
})
}
}
func TestSink(t *testing.T) {
t.Run("Basic", func(t *testing.T) {
c := newClock(initialNow)
now := c.Now().Unix()
// Configure the aggregator with a test sink.
sink := &testSink{buckets: []*aggregator.FlowCollection{}}
roller := &rolloverController{
ch: make(chan time.Time),
aggregationWindowSecs: 1,
clock: c,
}
pushIndex := 10
bucketsToCombine := 20
opts := []aggregator.Option{
aggregator.WithRolloverTime(1 * time.Second),
aggregator.WithRolloverFunc(roller.After),
aggregator.WithNowFunc(c.Now),
aggregator.WithBucketsToCombine(bucketsToCombine),
aggregator.WithPushIndex(pushIndex),
}
defer setupTest(t, opts...)()
// Start the aggregator, and rollover to trigger an emission.
// We shouldn't see any buckets pushed to the sink, as we haven't sent any flows.
go agg.Run(now)
// Set the sink. Setting the Sink is asynchronous and triggers a check for flow emission - as such,
// we need to wait for this to complete before we can start sending flows.
Eventually(agg.SetSink(sink), waitTimeout, retryTime).Should(BeClosed())
roller.rolloverAndAdvanceClock(1)
require.Len(t, sink.buckets, 0)
// Write some data into the aggregator in a way that will trigger an emission on the next rollover.
// Write a flow that will trigger an emission, since it's within the push index.
fl := testutils.NewRandomFlow(now - int64(pushIndex))
agg.Receive(types.ProtoToFlow(fl))
// Wait for the flow to be received.
Eventually(func() error {
results, err := agg.List(&proto.FlowListRequest{})
if err != nil {
return nil
}
if len(results.Flows) < 1 {
return fmt.Errorf("Expected a flow, got none")
}
return nil
}, waitTimeout, retryTime).ShouldNot(HaveOccurred(), "Didn't receive flow")
// Rollover to trigger the emission. This will mark all buckets from -50 to -30 as emitted.
roller.rolloverAndAdvanceClock(1)
Eventually(func() int {
return len(sink.buckets)
}, waitTimeout, retryTime).Should(Equal(1), "Expected 1 bucket to be pushed to the sink")
require.Len(t, sink.buckets[0].Flows, 1, "Expected 1 flow in the bucket")
sink.buckets = []*aggregator.FlowCollection{}
// We've rolled over once. The next emission should happen after
// bucktsToCombine more rollovers, which is the point at which the first bucket
// not included in the previous emission will become eligible.
nextEmission := bucketsToCombine
// Place 5 new flow logs in the first 5 buckets of the ring.
flowStart := roller.now() + 1 - 4
flowEnd := roller.now() + 2
for i := range 5 {
fl := &proto.Flow{
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
DestName: "test-dst",
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
Policies: &proto.PolicyTrace{EnforcedPolicies: []*proto.PolicyHit{}},
},
StartTime: roller.now() + 1 - int64(i),
EndTime: roller.now() + 2 - int64(i),
BytesIn: 100,
BytesOut: 200,
PacketsIn: 10,
PacketsOut: 20,
NumConnectionsStarted: 1,
}
agg.Receive(types.ProtoToFlow(fl))
}
// Wait for all flows to be received.
time.Sleep(10 * time.Millisecond)
// Rollover until we trigger the next emission. The flows we added above
// won't appear in this emission, since they are in the first 5 buckets which
// haven't reached the emission window yet.
roller.rolloverAndAdvanceClock(nextEmission - 1)
require.Len(t, sink.buckets, 0)
// Rollover until we trigger the next emission. This time, the flows we added above will be present.
roller.rolloverAndAdvanceClock(1)
Eventually(func() int {
return len(sink.buckets)
}, waitTimeout, retryTime).Should(Equal(1), "Expected 1 bucket to be pushed to the sink")
// We expect the collection to have been aggregated across 20 intervals, for a total of 20 seconds.
require.Equal(t, int64(1012), sink.buckets[0].EndTime)
require.Equal(t, int64(992), sink.buckets[0].StartTime)
require.Equal(t, int64(20), sink.buckets[0].EndTime-sink.buckets[0].StartTime)
// Expect the bucket to have aggregated to a single flow, since all flows are identical.
require.Len(t, sink.buckets[0].Flows, 1)
// Statistics should be aggregated correctly.
exp := proto.Flow{
Key: &proto.FlowKey{
SourceName: "test-src",
SourceNamespace: "test-ns",
DestName: "test-dst",
DestNamespace: "test-dst-ns",
Proto: "tcp",
Action: proto.Action_Allow,
},
StartTime: flowStart,
EndTime: flowEnd,
BytesIn: 500,
BytesOut: 1000,
PacketsIn: 50,
PacketsOut: 100,
NumConnectionsStarted: 5,
}
flow := sink.buckets[0].Flows[0]
require.NotNil(t, flow)
require.Equal(t, *types.ProtoToFlow(&exp), flow)
})
// This test verifies that the aggregator handles publishing multiple buckets of Flows if there are
// multiple buckets worth of flows that haven't been published yet.
t.Run("PushMultiple", func(t *testing.T) {
c := newClock(initialNow)
now := c.Now().Unix()
// Configure the aggregator with a test sink.
sink := &testSink{buckets: []*aggregator.FlowCollection{}}
roller := &rolloverController{
ch: make(chan time.Time),
aggregationWindowSecs: 1,
clock: c,
}
pushIndex := 10
bucketsToCombine := 20
opts := []aggregator.Option{
aggregator.WithRolloverTime(1 * time.Second),
aggregator.WithRolloverFunc(roller.After),
aggregator.WithNowFunc(c.Now),
aggregator.WithBucketsToCombine(bucketsToCombine),
aggregator.WithPushIndex(pushIndex),
}
defer setupTest(t, opts...)()
// Start the aggregator, and rollover to trigger an emission.
// We shouldn't see any buckets pushed to the sink, as we haven't sent any flows.
go agg.Run(now)
// Set the sink. Setting the Sink is asynchronous and triggers a check for flow emission - as such,
// we need to wait for this to complete before we can start sending flows.
Eventually(agg.SetSink(sink), waitTimeout, retryTime).Should(BeClosed())
// Load up the aggregator with Flow data across a widge range of buckets, spanning
// multiple emission windows.
for i := range 100 {
fl := testutils.NewRandomFlow(now - int64(pushIndex) - int64(i))
agg.Receive(types.ProtoToFlow(fl))
}
// Wait for the flows to be received.
Eventually(func() error {
results, err := agg.List(&proto.FlowListRequest{})
if err != nil {
logrus.Infof("Got %d flows", len(results.Flows))
return nil
}
if len(results.Flows) < 80 {
logrus.Infof("Got %d flows", len(results.Flows))
return fmt.Errorf("Expected 80 flows, got %d", len(results.Flows))
}
return nil
}, waitTimeout, retryTime).ShouldNot(HaveOccurred())
// Rollover, which should trigger an emission. Since we're combining 20 buckets, and we're filling 100,
// we expect to see 5 emissions.
roller.rolloverAndAdvanceClock(1)
Eventually(func() int {
return len(sink.buckets)
}, waitTimeout, retryTime).Should(Equal(5), "Expected 5 buckets to be pushed to the sink")
// We shouldn't see any more emissions.
for range 400 {
roller.rolloverAndAdvanceClock(1)
require.Len(t, sink.buckets, 5, "Unexpected bucket pushed to sink")
}
})
// This test verifies that the aggregator handles publishing multiple buckets of Flows if there is no
// sink configured, but a sink is added later.
t.Run("AddSink", func(t *testing.T) {
c := newClock(initialNow)
now := c.Now().Unix()
// Configure the aggregator with a test sink.
sink := &testSink{buckets: []*aggregator.FlowCollection{}}
roller := &rolloverController{
ch: make(chan time.Time),
aggregationWindowSecs: 1,
clock: c,
}
pushIndex := 10
bucketsToCombine := 20
opts := []aggregator.Option{
aggregator.WithRolloverTime(1 * time.Second),
aggregator.WithRolloverFunc(roller.After),
aggregator.WithNowFunc(c.Now),
aggregator.WithBucketsToCombine(bucketsToCombine),
aggregator.WithPushIndex(pushIndex),
}
defer setupTest(t, opts...)()
// Start the aggregator, and rollover to trigger an emission.
// We shouldn't see any buckets pushed to the sink, as we haven't sent any flows.
go agg.Run(now)
// Load up the aggregator with Flow data across a widge range of buckets, spanning
// multiple emission windows.
for i := range 100 {
fl := testutils.NewRandomFlow(now - int64(pushIndex) - int64(i))
agg.Receive(types.ProtoToFlow(fl))
}
// Wait for the flows to be received.
Eventually(func() error {
results, err := agg.List(&proto.FlowListRequest{})
if err != nil {
return nil
}
if len(results.Flows) < 80 {
return fmt.Errorf("Expected 80 flows, got %d", len(results.Flows))
}
return nil
}, waitTimeout, retryTime).ShouldNot(HaveOccurred())
// Rollover. Since we haven't provided a Sink, we shouldn't see any emissions.
roller.rolloverAndAdvanceClock(1)
Consistently(func() int {
return len(sink.buckets)
}, waitTimeout, retryTime).Should(Equal(0), "Unexpected bucket pushed to sink")
// Set the sink. Setting the Sink is asynchronous and triggers a check for flow emission - as such,
// we need to wait for this to complete before we can start sending flows.
Eventually(agg.SetSink(sink), waitTimeout, retryTime).Should(BeClosed())
// We should see the emissions now.
Eventually(func() int {
return len(sink.buckets)
}, waitTimeout, retryTime).Should(Equal(5), "Expected 5 buckets to be pushed to the sink")
})
}
// TestBucketDrift makes sure that the aggregator is able to account for its internal array of
// aggregation buckets slowly drifting with respect to time.Now(). This can happen due to the time taken to process
// other operations on the shared main goroutine, and is accounted for by adjusting the the next rollover time.
func TestBucketDrift(t *testing.T) {
// Create a clock and rollover controller.
c := newClock(initialNow)