-
Notifications
You must be signed in to change notification settings - Fork 174
/
server_test.go
1649 lines (1440 loc) · 44.2 KB
/
server_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
package veneur
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/golang/protobuf/proto"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stripe/veneur/v14/forwardrpc"
"github.com/stripe/veneur/v14/protocol"
"github.com/stripe/veneur/v14/samplers"
"github.com/stripe/veneur/v14/samplers/metricpb"
"github.com/stripe/veneur/v14/sinks"
"github.com/stripe/veneur/v14/sinks/blackhole"
"github.com/stripe/veneur/v14/ssf"
"github.com/stripe/veneur/v14/tdigest"
"github.com/stripe/veneur/v14/trace"
"github.com/stripe/veneur/v14/trace/metrics"
"github.com/stripe/veneur/v14/util"
"github.com/zenazn/goji/graceful"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
)
const ε = .00002
const DefaultFlushInterval = 50 * time.Millisecond
const DefaultServerTimeout = 100 * time.Millisecond
var DebugMode bool
func seedRand() {
seed := time.Now().Unix()
logrus.New().WithFields(logrus.Fields{
"randSeed": seed,
}).Info("Re-seeding random number generator")
rand.Seed(seed)
}
func TestMain(m *testing.M) {
flag.Parse()
DebugMode = flag.Lookup("test.v").Value.(flag.Getter).Get().(bool)
os.Exit(m.Run())
}
// set up a boilerplate local config for later use
func localConfig() Config {
return generateConfig("http://localhost")
}
// set up a boilerplate global config for later use
func globalConfig() Config {
return generateConfig("")
}
// generateConfig is not called config to avoid
// accidental variable shadowing
func generateConfig(forwardAddr string) Config {
return Config{
Debug: DebugMode,
Hostname: "localhost",
// Use a shorter interval for tests
Interval: DefaultFlushInterval,
MetricMaxLength: 4096,
Percentiles: []float64{.5, .75, .99},
Aggregates: []string{"min", "max", "count"},
ReadBufferSizeBytes: 2097152,
StatsdListenAddresses: []util.Url{{
Value: &url.URL{
Scheme: "udp",
Host: "localhost:0",
},
}},
HTTPAddress: "localhost:0",
GrpcAddress: "localhost:0",
ForwardAddress: forwardAddr,
NumWorkers: 4,
// Use only one reader, so that we can run tests
// on platforms which do not support SO_REUSEPORT
NumReaders: 1,
NumSpanWorkers: 2,
// Currently this points nowhere, which is intentional.
// We don't need internal metrics for the tests, and they make testing
// more complicated.
StatsAddress: "localhost:8125",
SentryDsn: util.StringSecret{Value: ""},
// Don't use the default port 8128: Veneur sends its own traces there, causing failures
SsfListenAddresses: []util.Url{{
Value: &url.URL{
Scheme: "udp",
Host: "127.0.0.1:0",
},
}},
TraceMaxLengthBytes: 4096,
}
}
func generateMetrics() (metricValues []float64, expectedMetrics map[string]float64) {
metricValues = []float64{1.0, 2.0, 7.0, 8.0, 100.0}
expectedMetrics = map[string]float64{
"a.b.c.max": 100,
"a.b.c.min": 1,
// Count is normalized by second
// so 5 values/50ms = 100 values/s
"a.b.c.count": float64(len(metricValues)) * float64(time.Second) / float64(DefaultFlushInterval),
// tdigest approximation causes this to be off by 1
"a.b.c.50percentile": 6,
"a.b.c.75percentile": 42,
"a.b.c.99percentile": 98,
}
return metricValues, expectedMetrics
}
// setupVeneurServer creates a local server from the specified config
// and starts listening for requests. It returns the server for
// inspection. If no metricSink or spanSink are provided then a
// `black hole` sink will be used so that flushes to these sinks do
// "nothing".
func setupVeneurServer(t testing.TB, config Config, transport http.RoundTripper, mSink sinks.MetricSink, sSink sinks.SpanSink, traceClient *trace.Client) *Server {
logger := logrus.New()
server, err := NewFromConfig(ServerConfig{
Logger: logger,
Config: config,
})
if err != nil {
t.Fatal(err)
}
if transport != nil {
server.HTTPClient.Transport = transport
}
// Make sure we don't send internal metrics when testing:
trace.NeutralizeClient(server.TraceClient)
server.TraceClient = traceClient
if mSink == nil {
// Install a blackhole sink if we have no other sinks
bhs, _ := blackhole.NewBlackholeMetricSink()
mSink = bhs
}
server.metricSinks = append(server.metricSinks, internalMetricSink{
sink: mSink,
})
if sSink == nil {
// Install a blackhole sink if we have no other sinks
bhs, _ := blackhole.NewBlackholeSpanSink()
sSink = bhs
}
server.spanSinks = append(server.spanSinks, sSink)
server.Start()
return server
}
type channelMetricSink struct {
metricsChannel chan []samplers.InterMetric
}
// NewChannelMetricSink creates a new channelMetricSink. This sink writes any
// flushed metrics to its `metricsChannel` such that the test can inspect
// the metrics for correctness.
func NewChannelMetricSink(ch chan []samplers.InterMetric) (*channelMetricSink, error) {
return &channelMetricSink{
metricsChannel: ch,
}, nil
}
func (c *channelMetricSink) Name() string {
return "channel"
}
func (c *channelMetricSink) Kind() string {
return "channel"
}
func (c *channelMetricSink) Start(*trace.Client) error {
return nil
}
func (c *channelMetricSink) Flush(ctx context.Context, metrics []samplers.InterMetric) (sinks.MetricFlushResult, error) {
// Put the whole slice in since many tests want to see all of them and we
// don't want them to have to loop over and wait on empty or something
c.metricsChannel <- metrics
return sinks.MetricFlushResult{}, nil
}
func (c *channelMetricSink) FlushOtherSamples(ctx context.Context, events []ssf.SSFSample) {
// Do nothing.
}
// fixture sets up a mock Datadog API server and Veneur
type fixture struct {
api *httptest.Server
server *Server
interval time.Duration
}
func newFixture(t testing.TB, config Config, mSink sinks.MetricSink, sSink sinks.SpanSink) *fixture {
// Set up a remote server (the API that we're sending the data to)
// (e.g. Datadog)
f := &fixture{nil, &Server{}, config.Interval}
if config.NumWorkers == 0 {
config.NumWorkers = 1
}
f.server = setupVeneurServer(t, config, nil, mSink, sSink, nil)
return f
}
func (f *fixture) Close() {
// Make it safe to close this more than once, jic
if f.server != nil {
f.server.Shutdown()
f.server = nil
}
}
// TestLocalServerUnaggregatedMetrics tests the behavior of
// the veneur client when operating without a global veneur
// instance (ie, when sending data directly to the remote server)
func TestLocalServerUnaggregatedMetrics(t *testing.T) {
metricValues, _ := generateMetrics()
config := localConfig()
metricsChan := make(chan []samplers.InterMetric, 10)
cms, _ := NewChannelMetricSink(metricsChan)
defer close(metricsChan)
f := newFixture(t, config, cms, nil)
defer f.Close()
for _, value := range metricValues {
f.server.Workers[0].ProcessMetric(&samplers.UDPMetric{
MetricKey: samplers.MetricKey{
Name: "a.b.c",
Type: "histogram",
},
Value: value,
Digest: 12345,
SampleRate: 1.0,
Scope: samplers.LocalOnly,
})
}
f.server.Flush(context.TODO())
interMetrics := <-metricsChan
assert.Equal(t, 6, len(interMetrics), "incorrect number of elements in the flushed series on the remote server")
}
func TestGlobalServerFlush(t *testing.T) {
metricValues, expectedMetrics := generateMetrics()
config := globalConfig()
metricsChan := make(chan []samplers.InterMetric, 10)
cms, _ := NewChannelMetricSink(metricsChan)
defer close(metricsChan)
f := newFixture(t, config, cms, nil)
defer f.Close()
for _, value := range metricValues {
f.server.Workers[0].ProcessMetric(&samplers.UDPMetric{
MetricKey: samplers.MetricKey{
Name: "a.b.c",
Type: "histogram",
},
Value: value,
Digest: 12345,
SampleRate: 1.0,
Scope: samplers.LocalOnly,
})
}
f.server.Flush(context.TODO())
interMetrics := <-metricsChan
assert.Equal(t, len(expectedMetrics), len(interMetrics), "incorrect number of elements in the flushed series on the remote server")
}
// TestLocalServerMixedMetrics ensures that stuff tagged as local only or local parts of mixed
// scope metrics are sent directly to sinks while global metrics are forwarded.
func TestLocalServerMixedMetrics(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var HistogramValues = []float64{1.0, 2.0, 7.0, 8.0, 100.0}
// Number of events observed (in 50ms interval)
var HistogramCountRaw = len(HistogramValues)
// Normalize to events/second
// Explicitly convert to int to avoid confusing Stringer behavior
var HistogramCountNormalized = float64(HistogramCountRaw) * float64(time.Second) / float64(DefaultFlushInterval)
// Number of events observed
const CounterNumEvents = 40
expectedMetrics := map[string]float64{
// 40 events/50ms = 800 events/s
"x.y.z": CounterNumEvents * float64(time.Second) / float64(DefaultFlushInterval),
"a.b.c.max": 100,
"a.b.c.min": 1,
// Count is normalized by second
// so 5 values/50ms = 100 values/s
"a.b.c.count": float64(HistogramCountNormalized),
}
// This represents the global veneur instance, which receives request from
// the local veneur instances, aggregates the data, and sends it to the remote API
// (e.g. Datadog)
globalVeneur := grpc.NewServer()
server := forwardrpc.NewMockForwardServer(ctrl)
forwardrpc.RegisterForwardServer(globalVeneur, server)
listener, err := net.Listen("tcp", "0.0.0.0:0")
assert.NoError(t, err)
defer globalVeneur.GracefulStop()
go globalVeneur.Serve(listener)
metricsChannel := make(chan *metricpb.Metric, 1)
server.EXPECT().SendMetricsV2(gomock.Any()).AnyTimes().
Do(func(server forwardrpc.Forward_SendMetricsV2Server) {
for {
metric, err := server.Recv()
if err == io.EOF {
break
}
assert.NoError(t, err)
metricsChannel <- metric
}
close(metricsChannel)
server.SendAndClose(&emptypb.Empty{})
})
config := localConfig()
config.ForwardAddress = listener.Addr().String()
f := newFixture(t, config, nil, nil)
defer f.Close()
// Create non-local metrics that should be passed to the global veneur instance
for _, value := range HistogramValues {
f.server.Workers[0].ProcessMetric(&samplers.UDPMetric{
MetricKey: samplers.MetricKey{
Name: "a.b.c",
Type: "histogram",
},
Value: value,
Digest: 12345,
SampleRate: 1.0,
Scope: samplers.MixedScope,
})
}
// Create local-only metrics that should be passed directly to the remote API
for i := 0; i < CounterNumEvents; i++ {
f.server.Workers[0].ProcessMetric(&samplers.UDPMetric{
MetricKey: samplers.MetricKey{
Name: "x.y.z",
Type: "counter",
},
Value: 1.0,
Digest: 12345,
SampleRate: 1.0,
Scope: samplers.LocalOnly,
})
}
f.server.Flush(context.Background())
metric := <-metricsChannel
assert.Equal(t, metricpb.Type_Histogram, metric.Type)
// the global veneur instance should get valid data
td := tdigest.NewMergingFromData(metric.GetHistogram().TDigest)
assert.Equal(t, expectedMetrics["a.b.c.min"], td.Min(), "Minimum value is incorrect")
assert.Equal(t, expectedMetrics["a.b.c.max"], td.Max(), "Maximum value is incorrect")
// The remote server receives the raw count, *not* the normalized count
assert.InEpsilon(t, HistogramCountRaw, td.Count(), ε)
assert.InEpsilon(t, 100, td.Max(), ε)
assert.InEpsilon(t, 1, td.Min(), ε)
assert.InEpsilon(t, 7, td.Quantile(.5), 0.2)
assert.InEpsilon(t, 1.777, td.ReciprocalSum(), 0.01)
}
func TestSplitBytes(t *testing.T) {
seedRand()
buf := make([]byte, 1000)
for i := 0; i < 1000; i++ {
// we construct a string of random length which is approximately 1/3rd A
// and the other 2/3rds B
buf = buf[:rand.Intn(cap(buf))]
for i := range buf {
if rand.Intn(3) == 0 {
buf[i] = 'A'
} else {
buf[i] = 'B'
}
}
checkBufferSplit(t, buf)
buf = buf[:cap(buf)]
}
// also test pathological cases that the fuzz is unlikely to find
checkBufferSplit(t, nil)
checkBufferSplit(t, []byte{})
}
func checkBufferSplit(t *testing.T, buf []byte) {
var testSplit [][]byte
sb := samplers.NewSplitBytes(buf, 'A')
for sb.Next() {
testSplit = append(testSplit, sb.Chunk())
}
// now compare our split to the "real" implementation of split
assert.EqualValues(t, bytes.Split(buf, []byte{'A'}), testSplit, "should have split %s correctly", buf)
}
func readTestKeysCerts() (map[string]string, error) {
// reads the insecure test keys and certificates in fixtures
// generated with: Run the testdata/_bin/generate_certs.sh
// script (tested on macOS Catalina) to re-generate the CA and
// certs).
pems := map[string]string{}
pemFileNames := []string{
"cacert.pem",
"clientcert_correct.pem",
"clientcert_wrong.pem",
"clientkey.pem",
"wrongkey.pem",
"servercert.pem",
"serverkey.pem",
}
for _, fileName := range pemFileNames {
b, err := ioutil.ReadFile(filepath.Join("testdata", fileName))
if err != nil {
return nil, err
}
pems[fileName] = string(b)
}
return pems, nil
}
// TestTCPConfig checks that invalid configurations are errors
func TestTCPConfig(t *testing.T) {
config := localConfig()
logger := logrus.New()
logger.Out = ioutil.Discard
config.StatsdListenAddresses = []util.Url{{
Value: &url.URL{
Scheme: "tcp",
Host: "localhost:8129",
},
}}
config.TLSKey = util.StringSecret{Value: "somekey"}
config.TLSCertificate = ""
_, err := NewFromConfig(ServerConfig{
Logger: logger,
Config: config,
})
if err == nil {
t.Error("key without certificate is a config error")
}
pems, err := readTestKeysCerts()
if err != nil {
t.Fatal("could not read test keys/certs:", err)
}
config.TLSKey = util.StringSecret{Value: pems["serverkey.pem"]}
config.TLSCertificate = "somecert"
_, err = NewFromConfig(ServerConfig{
Logger: logger,
Config: config,
})
if err == nil {
t.Error("invalid key and certificate is a config error")
}
config.TLSKey = util.StringSecret{Value: pems["serverkey.pem"]}
config.TLSCertificate = pems["servercert.pem"]
_, err = NewFromConfig(ServerConfig{
Logger: logger,
Config: config,
})
if err != nil {
t.Error("expected valid config")
}
}
func sendTCPMetrics(a *net.TCPAddr, tlsConfig *tls.Config, f *fixture) error {
// TODO: attempt to ensure the accept goroutine opens the port before we attempt to connect
// connect and send stats in two parts
var conn net.Conn
var err error
// Need to construct an address based on "localhost", as
// that's the name that the TLS certs are issued for:
addr := fmt.Sprintf("localhost:%d", a.Port)
if tlsConfig != nil {
conn, err = tls.Dial("tcp", addr, tlsConfig)
} else {
conn, err = net.Dial("tcp", addr)
}
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Write([]byte("page.views:1|c\npage.views:1|c\n"))
if err != nil {
return err
}
err = conn.Close()
if err != nil {
return err
}
// check that the server received the stats; HACK: sleep to ensure workers process before flush
time.Sleep(20 * time.Millisecond)
if f.server.Workers[0].MetricsProcessedCount() < 1 {
return fmt.Errorf("metrics were not processed")
}
return nil
}
func TestUDPMetrics(t *testing.T) {
config := localConfig()
config.NumWorkers = 1
config.Interval = time.Duration(time.Minute)
config.StatsdListenAddresses = []util.Url{{
Value: &url.URL{
Scheme: "udp",
Host: "127.0.0.1:0",
},
}}
ch := make(chan []samplers.InterMetric, 20)
sink, _ := NewChannelMetricSink(ch)
f := newFixture(t, config, sink, nil)
defer f.Close()
addr := f.server.StatsdListenAddrs[0]
conn := connectToAddress(t, "udp", addr.String(), 20*time.Millisecond)
conn.Write([]byte("foo.bar:1|c|#baz:gorch"))
ctx, cancel := context.WithTimeout(context.TODO(), 500*time.Millisecond)
defer cancel()
keepFlushing(ctx, f.server)
metrics := <-ch
require.Equal(t, 1, len(metrics), "we got a single metric")
assert.Equal(t, "foo.bar", metrics[0].Name, "worker processed the metric")
}
func TestUnixSocketMetrics(t *testing.T) {
tdir := t.TempDir()
config := localConfig()
config.NumWorkers = 1
config.Interval = time.Duration(time.Minute)
path := filepath.Join(tdir, "testdatagram.sock")
config.StatsdListenAddresses = []util.Url{{
Value: &url.URL{
Scheme: "unixgram",
Path: path,
},
}}
ch := make(chan []samplers.InterMetric, 20)
sink, _ := NewChannelMetricSink(ch)
f := newFixture(t, config, sink, nil)
defer f.Close()
conn := connectToAddress(t, "unixgram", path, 500*time.Millisecond)
defer conn.Close()
t.Log("Writing the first metric")
_, err := conn.Write([]byte("foo.bar:1|c|#baz:gorch"))
ctx, firstCancel := context.WithTimeout(context.TODO(), 500*time.Millisecond)
defer firstCancel()
keepFlushing(ctx, f.server)
if assert.NoError(t, err) {
metrics := <-ch
require.Equal(t, 1, len(metrics), "we sent a single metric")
assert.Equal(t, "foo.bar", metrics[0].Name, "worker processed the first metric")
}
t.Log("Writing the second metric")
_, err = conn.Write([]byte("foo.baz:1|c|#baz:gorch"))
secondCtx, secondCancel := context.WithTimeout(ctx, 20*time.Millisecond)
defer secondCancel()
keepFlushing(secondCtx, f.server)
if assert.NoError(t, err) {
metrics := <-ch
require.Equal(t, 1, len(metrics), "we sent a single metric")
assert.Equal(t, "foo.baz", metrics[0].Name, "worker processed the second metric")
}
}
func TestAbstractUnixSocketMetrics(t *testing.T) {
config := localConfig()
config.NumWorkers = 1
config.Interval = time.Duration(time.Minute)
path := "@abstract.sock"
defer os.RemoveAll(path)
config.StatsdListenAddresses = []util.Url{{
Value: &url.URL{
Scheme: "unixgram",
Path: path,
},
}}
ch := make(chan []samplers.InterMetric, 20)
sink, _ := NewChannelMetricSink(ch)
f := newFixture(t, config, sink, nil)
defer f.Close()
conn := connectToAddress(t, "unixgram", path, 500*time.Millisecond)
defer conn.Close()
t.Log("Writing the first metric")
_, err := conn.Write([]byte("foo.bar:1|c|#baz:gorch"))
ctx, firstCancel := context.WithTimeout(context.TODO(), 500*time.Millisecond)
defer firstCancel()
keepFlushing(ctx, f.server)
if assert.NoError(t, err) {
metrics := <-ch
require.Equal(t, 1, len(metrics), "we sent a single metric")
assert.Equal(t, "foo.bar", metrics[0].Name, "worker processed the first metric")
}
t.Log("Writing the second metric")
_, err = conn.Write([]byte("foo.baz:1|c|#baz:gorch"))
secondCtx, secondCancel := context.WithTimeout(ctx, 20*time.Millisecond)
defer secondCancel()
keepFlushing(secondCtx, f.server)
if assert.NoError(t, err) {
metrics := <-ch
require.Equal(t, 1, len(metrics), "we sent a single metric")
assert.Equal(t, "foo.baz", metrics[0].Name, "worker processed the second metric")
}
}
func TestMultipleUDPSockets(t *testing.T) {
config := localConfig()
config.NumWorkers = 1
config.StatsdListenAddresses = []util.Url{{
Value: &url.URL{
Scheme: "udp",
Host: "127.0.0.1:0",
},
}, {
Value: &url.URL{
Scheme: "udp",
Host: "127.0.0.1:0",
},
}}
ch := make(chan []samplers.InterMetric, 20)
sink, _ := NewChannelMetricSink(ch)
f := newFixture(t, config, sink, nil)
defer f.Close()
addr1 := f.server.StatsdListenAddrs[0]
addr2 := f.server.StatsdListenAddrs[1]
conn1 := connectToAddress(t, "udp", addr1.String(), 20*time.Millisecond)
defer conn1.Close()
conn1.Write([]byte("foo.bar:1|c|#baz:gorch"))
{
ctx, cancel := context.WithTimeout(context.TODO(), 500*time.Millisecond)
defer cancel()
keepFlushing(ctx, f.server)
metrics := <-ch
require.Equal(t, 1, len(metrics), "we got a single metric")
assert.Equal(t, "foo.bar", metrics[0].Name, "worker processed the metric")
cancel()
}
conn2 := connectToAddress(t, "udp", addr2.String(), 20*time.Millisecond)
defer conn2.Close()
conn2.Write([]byte("foo.bar:1|c|#baz:gorch"))
{
ctx, cancel := context.WithTimeout(context.TODO(), 500*time.Millisecond)
defer cancel()
keepFlushing(ctx, f.server)
metrics := <-ch
require.Equal(t, 1, len(metrics), "we got a single metric")
assert.Equal(t, "foo.bar", metrics[0].Name, "worker processed the metric")
}
}
func TestUDPMetricsSSF(t *testing.T) {
config := localConfig()
config.NumWorkers = 1
config.Interval = time.Duration(time.Minute)
config.SsfListenAddresses = []util.Url{{
Value: &url.URL{
Scheme: "udp",
Host: "127.0.0.1:0",
},
}}
ch := make(chan []samplers.InterMetric, 20)
sink, _ := NewChannelMetricSink(ch)
f := newFixture(t, config, sink, nil)
defer f.Close()
addr := f.server.SSFListenAddrs[0]
conn := connectToAddress(t, "udp", addr.String(), 20*time.Millisecond)
defer conn.Close()
testSample := &ssf.SSFSpan{}
testMetric := &ssf.SSFSample{}
testMetric.Name = "test.metric"
testMetric.Metric = ssf.SSFSample_COUNTER
testMetric.Value = 1
testMetric.Tags = make(map[string]string)
testMetric.Tags["tag"] = "tagValue"
testSample.Metrics = append(testSample.Metrics, testMetric)
packet, err := proto.Marshal(testSample)
assert.NoError(t, err)
conn.Write(packet)
// unfortunately, we don't know when the UDP packet made it,
// so we'll have to wait a little while here:
ctx, cancel := context.WithTimeout(context.TODO(), 500*time.Millisecond)
defer cancel()
keepFlushing(ctx, f.server)
metrics := <-ch
require.Equal(t, 1, len(metrics), "we got a single metric")
assert.Equal(t, "test.metric", metrics[0].Name, "worker processed the metric")
}
func connectToAddress(t *testing.T, network string, addr string, timeout time.Duration) net.Conn {
ch := make(chan net.Conn)
go func() {
for {
conn, err := net.Dial(network, addr)
if err != nil {
time.Sleep(30 * time.Microsecond)
continue
}
ch <- conn
return
}
}()
select {
case conn := <-ch:
return conn
case <-time.After(timeout):
t.Fatalf("timed out connecting after %v", timeout)
}
return nil // this should not be reached
}
// keepFlushing flushes a veneur server in a tight loop until the
// context is canceled.
func keepFlushing(ctx context.Context, server *Server) {
go func() {
for {
select {
case <-ctx.Done():
return
default:
server.Flush(ctx)
time.Sleep(time.Millisecond)
}
}
}()
}
func TestUNIXMetricsSSF(t *testing.T) {
ctx := context.TODO()
tdir := t.TempDir()
config := localConfig()
config.NumWorkers = 1
config.Interval = time.Duration(time.Minute)
path := filepath.Join(tdir, "test.sock")
config.SsfListenAddresses = []util.Url{{
Value: &url.URL{
Scheme: "unix",
Path: path,
}},
}
ch := make(chan []samplers.InterMetric, 20)
sink, _ := NewChannelMetricSink(ch)
f := newFixture(t, config, sink, nil)
defer f.Close()
conn := connectToAddress(t, "unix", path, 500*time.Millisecond)
defer conn.Close()
testSpan := &ssf.SSFSpan{}
testMetric := &ssf.SSFSample{}
testMetric.Name = "test.metric"
testMetric.Metric = ssf.SSFSample_COUNTER
testMetric.Value = 1
testMetric.Tags = make(map[string]string)
testMetric.Tags["tag"] = "tagValue"
testSpan.Metrics = append(testSpan.Metrics, testMetric)
t.Log("Writing the first metric")
_, err := protocol.WriteSSF(conn, testSpan)
firstCtx, firstCancel := context.WithTimeout(ctx, 20*time.Millisecond)
defer firstCancel()
keepFlushing(firstCtx, f.server)
if assert.NoError(t, err) {
metrics := <-ch
require.Equal(t, 1, len(metrics), "we sent a single metric")
assert.Equal(t, "test.metric", metrics[0].Name, "worker processed the first metric")
}
firstCancel() // stop flushing like mad
t.Log("Writing the second metric")
secondCtx, secondCancel := context.WithTimeout(ctx, 20*time.Millisecond)
defer secondCancel()
_, err = protocol.WriteSSF(conn, testSpan)
keepFlushing(secondCtx, f.server)
if assert.NoError(t, err) {
metrics := <-ch
require.Equal(t, 1, len(metrics), "we sent a single metric")
assert.Equal(t, "test.metric", metrics[0].Name, "worker processed the second metric")
}
}
func TestIgnoreLongUDPMetrics(t *testing.T) {
config := localConfig()
config.NumWorkers = 1
config.MetricMaxLength = 31
config.Interval = time.Duration(time.Minute)
config.StatsdListenAddresses = []util.Url{{
Value: &url.URL{
Scheme: "udp",
Host: "127.0.0.1:0",
},
}}
f := newFixture(t, config, nil, nil)
defer f.Close()
conn := connectToAddress(t, "udp", f.server.StatsdListenAddrs[0].String(), 20*time.Millisecond)
defer conn.Close()
// nb this metric is bad because it's too long based on the `MetricMaxLength`
// we set above!
conn.Write([]byte("foo.bar:1|c|#baz:gorch,long:tag,is:long"))
// Add a bit of delay to ensure things get processed
time.Sleep(20 * time.Millisecond)
assert.Equal(t, int64(0), f.server.Workers[0].processed, "worker did not process a metric")
}
// TestTCPMetrics checks that a server can accept metrics over a TCP socket.
func TestTCPMetrics(t *testing.T) {
pems, err := readTestKeysCerts()
if err != nil {
t.Fatal("could not read test keys/certs:", err)
}
// all supported TCP connection modes
serverConfigs := []struct {
name string
serverKey string
serverCertificate string
authorityCertificate string
expectedConnectResults [4]bool
}{
{"TCP", "", "", "", [4]bool{true, false, false, false}},
{"encrypted", pems["serverkey.pem"], pems["servercert.pem"], "",
[4]bool{false, true, true, true}},
{"authenticated", pems["serverkey.pem"], pems["servercert.pem"], pems["cacert.pem"],
[4]bool{false, false, false, true}},
}
// load all the various keys and certificates for the client
trustServerCA := x509.NewCertPool()
ok := trustServerCA.AppendCertsFromPEM([]byte(pems["cacert.pem"]))
if !ok {
t.Fatal("could not load server certificate")
}
wrongCert, err := tls.X509KeyPair(
[]byte(pems["clientcert_wrong.pem"]), []byte(pems["wrongkey.pem"]))
if err != nil {
t.Fatal("could not load wrong client cert/key:", err)
}
wrongConfig := &tls.Config{
RootCAs: trustServerCA,
Certificates: []tls.Certificate{wrongCert},
}
correctCert, err := tls.X509KeyPair(
[]byte(pems["clientcert_correct.pem"]), []byte(pems["clientkey.pem"]))
if err != nil {
t.Fatal("could not load correct client cert/key:", err)
}
correctConfig := &tls.Config{
RootCAs: trustServerCA,
Certificates: []tls.Certificate{correctCert},
}
// all supported client configurations
clientConfigs := []struct {
name string
tlsConfig *tls.Config
}{
{"TCP", nil},
{"TLS no cert", &tls.Config{RootCAs: trustServerCA}},
{"TLS wrong cert", wrongConfig},
{"TLS correct cert", correctConfig},
}
for _, entry := range serverConfigs {
serverConfig := entry
t.Run(serverConfig.name, func(t *testing.T) {
config := localConfig()
config.Interval = time.Duration(time.Minute)
config.NumWorkers = 1
config.StatsdListenAddresses = []util.Url{{
Value: &url.URL{
Scheme: "tcp",
Host: "127.0.0.1:0",
},
}}
config.TLSKey = util.StringSecret{Value: serverConfig.serverKey}
config.TLSCertificate = serverConfig.serverCertificate
config.TLSAuthorityCertificate = serverConfig.authorityCertificate
f := newFixture(t, config, nil, nil)
defer f.Close() // ensure shutdown if the test aborts
addr := f.server.StatsdListenAddrs[0].(*net.TCPAddr)
// attempt to connect and send stats with each of the client configurations
for i, clientConfig := range clientConfigs {
expectedSuccess := serverConfig.expectedConnectResults[i]
err := sendTCPMetrics(addr, clientConfig.tlsConfig, f)
if err != nil {
if expectedSuccess {
t.Errorf("server config: '%s' client config: '%s' failed: %s",
serverConfig.name, clientConfig.name, err.Error())
} else {
fmt.Printf("SUCCESS server config: '%s' client config: '%s' got expected error: %s\n",
serverConfig.name, clientConfig.name, err.Error())
}
} else if !expectedSuccess {
t.Errorf("server config: '%s' client config: '%s' worked; should fail!",
serverConfig.name, clientConfig.name)
} else {
fmt.Printf("SUCCESS server config: '%s' client config: '%s'\n",
serverConfig.name, clientConfig.name)
}
}
})
}
}
// TestHandleTCPGoroutineTimeout verifies that an idle TCP connection doesn't block forever.
func TestHandleTCPGoroutineTimeout(t *testing.T) {
const readTimeout = 30 * time.Millisecond
s := &Server{
logger: logrus.NewEntry(logrus.New()),
tcpReadTimeout: readTimeout,
Workers: []*Worker{{
logger: logrus.New(),
PacketChan: make(chan samplers.UDPMetric, 1),
}},
}
// make a real TCP connection ... to ourselves