forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathotelarrow_test.go
1196 lines (1003 loc) · 35.4 KB
/
otelarrow_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 The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package otelarrowexporter
import (
"context"
"fmt"
"io"
"net"
"net/http"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
arrowpb "github.com/open-telemetry/otel-arrow/api/experimental/arrow/v1"
arrowpbMock "github.com/open-telemetry/otel-arrow/api/experimental/arrow/v1/mock"
arrowRecord "github.com/open-telemetry/otel-arrow/pkg/otel/arrow_record"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/client"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/component/componenttest"
"go.opentelemetry.io/collector/config/configauth"
"go.opentelemetry.io/collector/config/configgrpc"
"go.opentelemetry.io/collector/config/configopaque"
"go.opentelemetry.io/collector/config/configtls"
"go.opentelemetry.io/collector/exporter"
"go.opentelemetry.io/collector/exporter/exportertest"
"go.opentelemetry.io/collector/extension"
"go.opentelemetry.io/collector/extension/extensionauth"
"go.opentelemetry.io/collector/pdata/plog"
"go.opentelemetry.io/collector/pdata/plog/plogotlp"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
"go.opentelemetry.io/collector/pdata/ptrace"
"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
"go.uber.org/mock/gomock"
"go.uber.org/zap/zaptest"
"golang.org/x/net/http2/hpack"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/durationpb"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/otelarrowexporter/internal/arrow/grpcmock"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/otelarrow/testdata"
)
type mockReceiver struct {
srv *grpc.Server
ln net.Listener
requestCount *atomic.Int32
totalItems *atomic.Int32
mux sync.Mutex
metadata metadata.MD
exportError error
}
func (r *mockReceiver) getMetadata() metadata.MD {
r.mux.Lock()
defer r.mux.Unlock()
return r.metadata
}
func (r *mockReceiver) setExportError(err error) {
r.mux.Lock()
defer r.mux.Unlock()
r.exportError = err
}
type mockTracesReceiver struct {
ptraceotlp.UnimplementedGRPCServer
mockReceiver
exportResponse func() ptraceotlp.ExportResponse
lastRequest ptrace.Traces
hasMetadata bool
spanCountByMetadata map[string]int
}
func (r *mockTracesReceiver) Export(ctx context.Context, req ptraceotlp.ExportRequest) (ptraceotlp.ExportResponse, error) {
r.requestCount.Add(int32(1))
td := req.Traces()
r.totalItems.Add(int32(td.SpanCount()))
r.mux.Lock()
defer r.mux.Unlock()
r.metadata, _ = metadata.FromIncomingContext(ctx)
if r.hasMetadata {
v1 := r.metadata.Get("key1")
v2 := r.metadata.Get("key2")
hashKey := fmt.Sprintf("%s|%s", v1, v2)
r.spanCountByMetadata[hashKey] += (td.SpanCount())
}
r.lastRequest = td
return r.exportResponse(), r.exportError
}
func (r *mockTracesReceiver) getLastRequest() ptrace.Traces {
r.mux.Lock()
defer r.mux.Unlock()
return r.lastRequest
}
func (r *mockTracesReceiver) setExportResponse(fn func() ptraceotlp.ExportResponse) {
r.mux.Lock()
defer r.mux.Unlock()
r.exportResponse = fn
}
func otelArrowTracesReceiverOnGRPCServer(ln net.Listener, useTLS bool) (*mockTracesReceiver, error) {
sopts := []grpc.ServerOption{}
if useTLS {
_, currentFile, _, _ := runtime.Caller(0)
basepath := filepath.Dir(currentFile)
certpath := filepath.Join(basepath, filepath.Join("testdata", "test_cert.pem"))
keypath := filepath.Join(basepath, filepath.Join("testdata", "test_key.pem"))
creds, err := credentials.NewServerTLSFromFile(certpath, keypath)
if err != nil {
return nil, err
}
sopts = append(sopts, grpc.Creds(creds))
}
rcv := &mockTracesReceiver{
mockReceiver: mockReceiver{
srv: grpc.NewServer(sopts...),
ln: ln,
requestCount: &atomic.Int32{},
totalItems: &atomic.Int32{},
},
exportResponse: ptraceotlp.NewExportResponse,
}
ptraceotlp.RegisterGRPCServer(rcv.srv, rcv)
return rcv, nil
}
func (r *mockTracesReceiver) start() {
go func() {
_ = r.srv.Serve(r.ln)
}()
}
type mockLogsReceiver struct {
plogotlp.UnimplementedGRPCServer
mockReceiver
exportResponse func() plogotlp.ExportResponse
lastRequest plog.Logs
}
func (r *mockLogsReceiver) Export(ctx context.Context, req plogotlp.ExportRequest) (plogotlp.ExportResponse, error) {
r.requestCount.Add(int32(1))
ld := req.Logs()
r.totalItems.Add(int32(ld.LogRecordCount()))
r.mux.Lock()
defer r.mux.Unlock()
r.lastRequest = ld
r.metadata, _ = metadata.FromIncomingContext(ctx)
return r.exportResponse(), r.exportError
}
func (r *mockLogsReceiver) getLastRequest() plog.Logs {
r.mux.Lock()
defer r.mux.Unlock()
return r.lastRequest
}
func (r *mockLogsReceiver) setExportResponse(fn func() plogotlp.ExportResponse) {
r.mux.Lock()
defer r.mux.Unlock()
r.exportResponse = fn
}
func otelArrowLogsReceiverOnGRPCServer(ln net.Listener) *mockLogsReceiver {
rcv := &mockLogsReceiver{
mockReceiver: mockReceiver{
srv: grpc.NewServer(),
requestCount: &atomic.Int32{},
totalItems: &atomic.Int32{},
},
exportResponse: plogotlp.NewExportResponse,
}
// Now run it as a gRPC server
plogotlp.RegisterGRPCServer(rcv.srv, rcv)
go func() {
_ = rcv.srv.Serve(ln)
}()
return rcv
}
type mockMetricsReceiver struct {
pmetricotlp.UnimplementedGRPCServer
mockReceiver
exportResponse func() pmetricotlp.ExportResponse
lastRequest pmetric.Metrics
}
func (r *mockMetricsReceiver) Export(ctx context.Context, req pmetricotlp.ExportRequest) (pmetricotlp.ExportResponse, error) {
md := req.Metrics()
r.requestCount.Add(int32(1))
r.totalItems.Add(int32(md.DataPointCount()))
r.mux.Lock()
defer r.mux.Unlock()
r.lastRequest = md
r.metadata, _ = metadata.FromIncomingContext(ctx)
return r.exportResponse(), r.exportError
}
func (r *mockMetricsReceiver) getLastRequest() pmetric.Metrics {
r.mux.Lock()
defer r.mux.Unlock()
return r.lastRequest
}
func (r *mockMetricsReceiver) setExportResponse(fn func() pmetricotlp.ExportResponse) {
r.mux.Lock()
defer r.mux.Unlock()
r.exportResponse = fn
}
func otelArrowMetricsReceiverOnGRPCServer(ln net.Listener) *mockMetricsReceiver {
rcv := &mockMetricsReceiver{
mockReceiver: mockReceiver{
srv: grpc.NewServer(),
requestCount: &atomic.Int32{},
totalItems: &atomic.Int32{},
},
exportResponse: pmetricotlp.NewExportResponse,
}
// Now run it as a gRPC server
pmetricotlp.RegisterGRPCServer(rcv.srv, rcv)
go func() {
_ = rcv.srv.Serve(ln)
}()
return rcv
}
type hostWithExtensions struct {
component.Host
exts map[component.ID]component.Component
}
func newHostWithExtensions(exts map[component.ID]component.Component) component.Host {
return &hostWithExtensions{
Host: componenttest.NewNopHost(),
exts: exts,
}
}
func (h *hostWithExtensions) GetExtensions() map[component.ID]component.Component {
return h.exts
}
type testAuthExtension struct {
extension.Extension
prc credentials.PerRPCCredentials
}
func newTestAuthExtension(t *testing.T, mdf func(ctx context.Context) map[string]string) extensionauth.Client {
ctrl := gomock.NewController(t)
prc := grpcmock.NewMockPerRPCCredentials(ctrl)
prc.EXPECT().RequireTransportSecurity().AnyTimes().Return(false)
prc.EXPECT().GetRequestMetadata(gomock.Any(), gomock.Any()).AnyTimes().DoAndReturn(
func(ctx context.Context, _ ...string) (map[string]string, error) {
return mdf(ctx), nil
},
)
return &testAuthExtension{
prc: prc,
}
}
func (a *testAuthExtension) RoundTripper(_ http.RoundTripper) (http.RoundTripper, error) {
return nil, fmt.Errorf("unused")
}
func (a *testAuthExtension) PerRPCCredentials() (credentials.PerRPCCredentials, error) {
return a.prc, nil
}
func TestSendTraces(t *testing.T) {
// Start an OTel-Arrow receiver.
ln, err := net.Listen("tcp", "localhost:")
require.NoError(t, err, "Failed to find an available address to run the gRPC server: %v", err)
rcv, _ := otelArrowTracesReceiverOnGRPCServer(ln, false)
rcv.start()
// Also closes the connection.
defer rcv.srv.GracefulStop()
// Start an OTLP exporter and point to the receiver.
factory := NewFactory()
authID := component.NewID(component.MustNewType("testauth"))
expectedHeader := []string{"header-value"}
cfg := factory.CreateDefaultConfig().(*Config)
// Disable queuing to ensure that we execute the request when calling ConsumeTraces
// otherwise we will not see any errors.
cfg.QueueSettings.Enabled = false
cfg.ClientConfig = configgrpc.ClientConfig{
Endpoint: ln.Addr().String(),
TLSSetting: configtls.ClientConfig{
Insecure: true,
},
Headers: map[string]configopaque.String{
"header": configopaque.String(expectedHeader[0]),
},
Auth: &configauth.Authentication{
AuthenticatorID: authID,
},
}
// This test fails w/ Arrow enabled because the function
// passed to newTestAuthExtension() below requires it the
// caller's context, and the newStream doesn't have it.
cfg.Arrow.Disabled = true
set := exportertest.NewNopSettings(factory.Type())
set.BuildInfo.Description = "Collector"
set.BuildInfo.Version = "1.2.3test"
exp, err := factory.CreateTraces(context.Background(), set, cfg)
require.NoError(t, err)
require.NotNil(t, exp)
defer func() {
assert.NoError(t, exp.Shutdown(context.Background()))
}()
host := newHostWithExtensions(
map[component.ID]component.Component{
authID: newTestAuthExtension(t, func(ctx context.Context) map[string]string {
return map[string]string{
"callerid": client.FromContext(ctx).Metadata.Get("in_callerid")[0],
}
}),
},
)
assert.NoError(t, exp.Start(context.Background(), host))
// Ensure that initially there is no data in the receiver.
assert.EqualValues(t, 0, rcv.requestCount.Load())
newCallerContext := func(value string) context.Context {
return client.NewContext(context.Background(),
client.Info{
Metadata: client.NewMetadata(map[string][]string{
"in_callerid": {value},
}),
},
)
}
const caller1 = "caller1"
const caller2 = "caller2"
callCtx1 := newCallerContext(caller1)
callCtx2 := newCallerContext(caller2)
// Send empty trace.
td := ptrace.NewTraces()
assert.NoError(t, exp.ConsumeTraces(callCtx1, td))
// Wait until it is received.
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 0
}, 10*time.Second, 5*time.Millisecond)
// Ensure it was received empty.
assert.EqualValues(t, 0, rcv.totalItems.Load())
md := rcv.getMetadata()
// Expect caller1 and the static header
require.EqualValues(t, expectedHeader, md.Get("header"))
require.EqualValues(t, []string{caller1}, md.Get("callerid"))
// A trace with 2 spans.
td = testdata.GenerateTraces(2)
err = exp.ConsumeTraces(callCtx2, td)
assert.NoError(t, err)
// Wait until it is received.
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 1
}, 10*time.Second, 5*time.Millisecond)
// Verify received span.
assert.EqualValues(t, 2, rcv.totalItems.Load())
assert.EqualValues(t, 2, rcv.requestCount.Load())
assert.EqualValues(t, td, rcv.getLastRequest())
// Test the static metadata
md = rcv.getMetadata()
require.EqualValues(t, expectedHeader, md.Get("header"))
require.Len(t, md.Get("User-Agent"), 1)
require.Contains(t, md.Get("User-Agent")[0], "Collector/1.2.3test")
// Test the caller's dynamic metadata
require.EqualValues(t, []string{caller2}, md.Get("callerid"))
// Return partial success
rcv.setExportResponse(func() ptraceotlp.ExportResponse {
response := ptraceotlp.NewExportResponse()
partialSuccess := response.PartialSuccess()
partialSuccess.SetErrorMessage("Some spans were not ingested")
partialSuccess.SetRejectedSpans(1)
return response
})
// A request with 2 Trace entries.
td = testdata.GenerateTraces(2)
// PartialSuccess is not an error.
err = exp.ConsumeTraces(callCtx1, td)
assert.NoError(t, err)
}
func TestSendTracesWhenEndpointHasHttpScheme(t *testing.T) {
tests := []struct {
name string
useTLS bool
scheme string
gRPCClientSettings configgrpc.ClientConfig
}{
{
name: "Use https scheme",
useTLS: true,
scheme: "https://",
gRPCClientSettings: configgrpc.ClientConfig{},
},
{
name: "Use http scheme",
useTLS: false,
scheme: "http://",
gRPCClientSettings: configgrpc.ClientConfig{
TLSSetting: configtls.ClientConfig{
Insecure: true,
},
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// Start an OTel-Arrow receiver.
ln, err := net.Listen("tcp", "localhost:")
require.NoError(t, err, "Failed to find an available address to run the gRPC server: %v", err)
rcv, err := otelArrowTracesReceiverOnGRPCServer(ln, test.useTLS)
rcv.start()
require.NoError(t, err, "Failed to start mock OTLP receiver")
// Also closes the connection.
defer rcv.srv.GracefulStop()
// Start an OTLP exporter and point to the receiver.
factory := NewFactory()
cfg := factory.CreateDefaultConfig().(*Config)
cfg.ClientConfig = test.gRPCClientSettings
cfg.ClientConfig.Endpoint = test.scheme + ln.Addr().String()
cfg.Arrow.MaxStreamLifetime = 100 * time.Second
if test.useTLS {
cfg.ClientConfig.TLSSetting.InsecureSkipVerify = true
}
set := exportertest.NewNopSettings(factory.Type())
exp, err := factory.CreateTraces(context.Background(), set, cfg)
require.NoError(t, err)
require.NotNil(t, exp)
defer func() {
assert.NoError(t, exp.Shutdown(context.Background()))
}()
host := componenttest.NewNopHost()
assert.NoError(t, exp.Start(context.Background(), host))
// Ensure that initially there is no data in the receiver.
assert.EqualValues(t, 0, rcv.requestCount.Load())
// Send empty trace.
td := ptrace.NewTraces()
assert.NoError(t, exp.ConsumeTraces(context.Background(), td))
// Wait until it is received.
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 0
}, 10*time.Second, 5*time.Millisecond)
// Ensure it was received empty.
assert.EqualValues(t, 0, rcv.totalItems.Load())
})
}
}
func TestSendMetrics(t *testing.T) {
// Start an OTel-Arrow receiver.
ln, err := net.Listen("tcp", "localhost:")
require.NoError(t, err, "Failed to find an available address to run the gRPC server: %v", err)
rcv := otelArrowMetricsReceiverOnGRPCServer(ln)
// Also closes the connection.
defer rcv.srv.GracefulStop()
// Start an OTLP exporter and point to the receiver.
factory := NewFactory()
cfg := factory.CreateDefaultConfig().(*Config)
// Disable queuing to ensure that we execute the request when calling ConsumeMetrics
// otherwise we will not see any errors.
cfg.QueueSettings.Enabled = false
cfg.RetryConfig.Enabled = false
cfg.ClientConfig = configgrpc.ClientConfig{
Endpoint: ln.Addr().String(),
TLSSetting: configtls.ClientConfig{
Insecure: true,
},
Headers: map[string]configopaque.String{
"header": "header-value",
},
}
cfg.Arrow.MaxStreamLifetime = 100 * time.Second
set := exportertest.NewNopSettings(factory.Type())
set.BuildInfo.Description = "Collector"
set.BuildInfo.Version = "1.2.3test"
exp, err := factory.CreateMetrics(context.Background(), set, cfg)
require.NoError(t, err)
require.NotNil(t, exp)
defer func() {
assert.NoError(t, exp.Shutdown(context.Background()))
}()
host := componenttest.NewNopHost()
assert.NoError(t, exp.Start(context.Background(), host))
// Ensure that initially there is no data in the receiver.
assert.EqualValues(t, 0, rcv.requestCount.Load())
// Send empty metric.
md := pmetric.NewMetrics()
assert.NoError(t, exp.ConsumeMetrics(context.Background(), md))
// Wait until it is received.
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 0
}, 10*time.Second, 5*time.Millisecond)
// Ensure it was received empty.
assert.EqualValues(t, 0, rcv.totalItems.Load())
// Send two metrics.
md = testdata.GenerateMetrics(2)
err = exp.ConsumeMetrics(context.Background(), md)
assert.NoError(t, err)
// Wait until it is received.
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 1
}, 10*time.Second, 5*time.Millisecond)
expectedHeader := []string{"header-value"}
// Verify received metrics.
assert.EqualValues(t, uint32(2), rcv.requestCount.Load())
assert.EqualValues(t, uint32(4), rcv.totalItems.Load())
assert.EqualValues(t, md, rcv.getLastRequest())
mdata := rcv.getMetadata()
require.EqualValues(t, expectedHeader, mdata.Get("header"))
require.Len(t, mdata.Get("User-Agent"), 1)
require.Contains(t, mdata.Get("User-Agent")[0], "Collector/1.2.3test")
st := status.New(codes.InvalidArgument, "Invalid argument")
rcv.setExportError(st.Err())
// Send two metrics..
md = testdata.GenerateMetrics(2)
err = exp.ConsumeMetrics(context.Background(), md)
assert.Error(t, err)
rcv.setExportError(nil)
// Return partial success
rcv.setExportResponse(func() pmetricotlp.ExportResponse {
response := pmetricotlp.NewExportResponse()
partialSuccess := response.PartialSuccess()
partialSuccess.SetErrorMessage("Some data points were not ingested")
partialSuccess.SetRejectedDataPoints(1)
return response
})
// Send two metrics.
md = testdata.GenerateMetrics(2)
assert.NoError(t, exp.ConsumeMetrics(context.Background(), md))
}
func TestSendTraceDataServerDownAndUp(t *testing.T) {
// Find the addr, but don't start the server.
ln, err := net.Listen("tcp", "localhost:")
require.NoError(t, err, "Failed to find an available address to run the gRPC server: %v", err)
// Start an OTel-Arrow exporter and point to the receiver.
factory := NewFactory()
cfg := factory.CreateDefaultConfig().(*Config)
// Disable queuing to ensure that we execute the request when calling ConsumeTraces
// otherwise we will not see the error.
cfg.QueueSettings.Enabled = false
cfg.ClientConfig = configgrpc.ClientConfig{
Endpoint: ln.Addr().String(),
TLSSetting: configtls.ClientConfig{
Insecure: true,
},
// Need to wait for every request blocking until either request timeouts or succeed.
// Do not rely on external retry logic here, if that is intended set InitialInterval to 100ms.
WaitForReady: true,
}
cfg.Arrow.MaxStreamLifetime = 100 * time.Second
set := exportertest.NewNopSettings(factory.Type())
exp, err := factory.CreateTraces(context.Background(), set, cfg)
require.NoError(t, err)
require.NotNil(t, exp)
defer func() {
assert.NoError(t, exp.Shutdown(context.Background()))
}()
host := componenttest.NewNopHost()
assert.NoError(t, exp.Start(context.Background(), host))
// A trace with 2 spans.
td := testdata.GenerateTraces(2)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
assert.Error(t, exp.ConsumeTraces(ctx, td))
assert.EqualValues(t, context.DeadlineExceeded, ctx.Err())
cancel()
ctx, cancel = context.WithTimeout(context.Background(), 1*time.Second)
assert.Error(t, exp.ConsumeTraces(ctx, td))
assert.EqualValues(t, context.DeadlineExceeded, ctx.Err())
cancel()
startServerAndMakeRequest(t, exp, td, ln)
ctx, cancel = context.WithTimeout(context.Background(), 1*time.Second)
assert.Error(t, exp.ConsumeTraces(ctx, td))
assert.EqualValues(t, context.DeadlineExceeded, ctx.Err())
cancel()
// First call to startServerAndMakeRequest closed the connection. There is a race condition here that the
// port may be reused, if this gets flaky rethink what to do.
ln, err = net.Listen("tcp", ln.Addr().String())
require.NoError(t, err, "Failed to find an available address to run the gRPC server: %v", err)
startServerAndMakeRequest(t, exp, td, ln)
ctx, cancel = context.WithTimeout(context.Background(), 1*time.Second)
assert.Error(t, exp.ConsumeTraces(ctx, td))
assert.EqualValues(t, context.DeadlineExceeded, ctx.Err())
cancel()
}
func TestSendTraceDataServerStartWhileRequest(t *testing.T) {
// Find the addr, but don't start the server.
ln, err := net.Listen("tcp", "localhost:")
require.NoError(t, err, "Failed to find an available address to run the gRPC server: %v", err)
// Start an OTel-Arrow exporter and point to the receiver.
factory := NewFactory()
cfg := factory.CreateDefaultConfig().(*Config)
cfg.ClientConfig = configgrpc.ClientConfig{
Endpoint: ln.Addr().String(),
TLSSetting: configtls.ClientConfig{
Insecure: true,
},
}
cfg.Arrow.MaxStreamLifetime = 100 * time.Second
set := exportertest.NewNopSettings(factory.Type())
exp, err := factory.CreateTraces(context.Background(), set, cfg)
require.NoError(t, err)
require.NotNil(t, exp)
defer func() {
assert.NoError(t, exp.Shutdown(context.Background()))
}()
host := componenttest.NewNopHost()
assert.NoError(t, exp.Start(context.Background(), host))
// A trace with 2 spans.
td := testdata.GenerateTraces(2)
done := make(chan bool, 1)
defer close(done)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
go func() {
assert.NoError(t, exp.ConsumeTraces(ctx, td))
done <- true
}()
time.Sleep(2 * time.Second)
rcv, _ := otelArrowTracesReceiverOnGRPCServer(ln, false)
rcv.start()
defer rcv.srv.GracefulStop()
// Wait until one of the conditions below triggers.
select {
case <-ctx.Done():
t.Fail()
case <-done:
assert.NoError(t, ctx.Err())
}
cancel()
}
func TestSendTracesOnResourceExhaustion(t *testing.T) {
ln, err := net.Listen("tcp", "localhost:")
require.NoError(t, err)
rcv, _ := otelArrowTracesReceiverOnGRPCServer(ln, false)
rcv.setExportError(status.Error(codes.ResourceExhausted, "resource exhausted"))
rcv.start()
defer rcv.srv.GracefulStop()
factory := NewFactory()
cfg := factory.CreateDefaultConfig().(*Config)
cfg.RetryConfig.InitialInterval = 0
cfg.ClientConfig = configgrpc.ClientConfig{
Endpoint: ln.Addr().String(),
TLSSetting: configtls.ClientConfig{
Insecure: true,
},
}
cfg.Arrow.MaxStreamLifetime = 100 * time.Second
set := exportertest.NewNopSettings(factory.Type())
exp, err := factory.CreateTraces(context.Background(), set, cfg)
require.NoError(t, err)
require.NotNil(t, exp)
defer func() {
assert.NoError(t, exp.Shutdown(context.Background()))
}()
host := componenttest.NewNopHost()
assert.NoError(t, exp.Start(context.Background(), host))
assert.EqualValues(t, 0, rcv.requestCount.Load())
td := ptrace.NewTraces()
assert.NoError(t, exp.ConsumeTraces(context.Background(), td))
assert.Never(t, func() bool {
return rcv.requestCount.Load() > 1
}, 1*time.Second, 5*time.Millisecond, "Should not retry if RetryInfo is not included into status details by the server.")
rcv.requestCount.Swap(0)
st := status.New(codes.ResourceExhausted, "resource exhausted")
st, _ = st.WithDetails(&errdetails.RetryInfo{
RetryDelay: durationpb.New(100 * time.Millisecond),
})
rcv.setExportError(st.Err())
assert.NoError(t, exp.ConsumeTraces(context.Background(), td))
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 1
}, 10*time.Second, 5*time.Millisecond, "Should retry if RetryInfo is included into status details by the server.")
}
func startServerAndMakeRequest(t *testing.T, exp exporter.Traces, td ptrace.Traces, ln net.Listener) {
rcv, _ := otelArrowTracesReceiverOnGRPCServer(ln, false)
rcv.start()
defer rcv.srv.GracefulStop()
// Ensure that initially there is no data in the receiver.
assert.EqualValues(t, 0, rcv.requestCount.Load())
// Clone the request and store as expected.
expectedData := ptrace.NewTraces()
td.CopyTo(expectedData)
// Resend the request, this should succeed.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
assert.NoError(t, exp.ConsumeTraces(ctx, td))
cancel()
// Wait until it is received.
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 0
}, 10*time.Second, 5*time.Millisecond)
// Verify received span.
assert.EqualValues(t, 2, rcv.totalItems.Load())
assert.EqualValues(t, expectedData, rcv.getLastRequest())
}
func TestSendLogData(t *testing.T) {
// Start an OTel-Arrow receiver.
ln, err := net.Listen("tcp", "localhost:")
require.NoError(t, err, "Failed to find an available address to run the gRPC server: %v", err)
rcv := otelArrowLogsReceiverOnGRPCServer(ln)
// Also closes the connection.
defer rcv.srv.GracefulStop()
// Start an OTel-Arrow exporter and point to the receiver.
factory := NewFactory()
cfg := factory.CreateDefaultConfig().(*Config)
// Disable queuing to ensure that we execute the request when calling ConsumeLogs
// otherwise we will not see any errors.
cfg.QueueSettings.Enabled = false
cfg.ClientConfig = configgrpc.ClientConfig{
Endpoint: ln.Addr().String(),
TLSSetting: configtls.ClientConfig{
Insecure: true,
},
}
cfg.Arrow.MaxStreamLifetime = 100 * time.Second
set := exportertest.NewNopSettings(factory.Type())
set.BuildInfo.Description = "Collector"
set.BuildInfo.Version = "1.2.3test"
exp, err := factory.CreateLogs(context.Background(), set, cfg)
require.NoError(t, err)
require.NotNil(t, exp)
defer func() {
assert.NoError(t, exp.Shutdown(context.Background()))
}()
host := componenttest.NewNopHost()
assert.NoError(t, exp.Start(context.Background(), host))
// Ensure that initially there is no data in the receiver.
assert.EqualValues(t, 0, rcv.requestCount.Load())
// Send empty request.
ld := plog.NewLogs()
assert.NoError(t, exp.ConsumeLogs(context.Background(), ld))
// Wait until it is received.
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 0
}, 10*time.Second, 5*time.Millisecond)
// Ensure it was received empty.
assert.EqualValues(t, 0, rcv.totalItems.Load())
// A request with 2 log entries.
ld = testdata.GenerateLogs(2)
err = exp.ConsumeLogs(context.Background(), ld)
assert.NoError(t, err)
// Wait until it is received.
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 1
}, 10*time.Second, 5*time.Millisecond)
// Verify received logs.
assert.EqualValues(t, 2, rcv.requestCount.Load())
assert.EqualValues(t, 2, rcv.totalItems.Load())
assert.EqualValues(t, ld, rcv.getLastRequest())
md := rcv.getMetadata()
require.Len(t, md.Get("User-Agent"), 1)
require.Contains(t, md.Get("User-Agent")[0], "Collector/1.2.3test")
st := status.New(codes.InvalidArgument, "Invalid argument")
rcv.setExportError(st.Err())
// A request with 2 log entries.
ld = testdata.GenerateLogs(2)
err = exp.ConsumeLogs(context.Background(), ld)
assert.Error(t, err)
rcv.setExportError(nil)
// Return partial success
rcv.setExportResponse(func() plogotlp.ExportResponse {
response := plogotlp.NewExportResponse()
partialSuccess := response.PartialSuccess()
partialSuccess.SetErrorMessage("Some log records were not ingested")
partialSuccess.SetRejectedLogRecords(1)
return response
})
// A request with 2 log entries.
ld = testdata.GenerateLogs(2)
err = exp.ConsumeLogs(context.Background(), ld)
assert.NoError(t, err)
}
// TestSendArrowTracesNotSupported tests a successful OTel-Arrow export w/
// and without Arrow, w/ WaitForReady and without.
func TestSendArrowTracesNotSupported(t *testing.T) {
for _, waitForReady := range []bool{true, false} {
for _, available := range []bool{true, false} {
t.Run(fmt.Sprintf("waitForReady=%v available=%v", waitForReady, available),
func(t *testing.T) { testSendArrowTraces(t, waitForReady, available) })
}
}
}
func testSendArrowTraces(t *testing.T, clientWaitForReady, streamServiceAvailable bool) {
// Start an OTel-Arrow receiver.
ln, err := net.Listen("tcp", "127.0.0.1:")
require.NoError(t, err, "Failed to find an available address to run the gRPC server: %v", err)
// Start an OTel-Arrow exporter and point to the receiver.
factory := NewFactory()
authID := component.NewID(component.MustNewType("testauth"))
expectedHeader := []string{"arrow-ftw"}
cfg := factory.CreateDefaultConfig().(*Config)
cfg.ClientConfig = configgrpc.ClientConfig{
Endpoint: ln.Addr().String(),
TLSSetting: configtls.ClientConfig{
Insecure: true,
},
WaitForReady: clientWaitForReady,
Headers: map[string]configopaque.String{
"header": configopaque.String(expectedHeader[0]),
},
Auth: &configauth.Authentication{
AuthenticatorID: authID,
},
}
// Arrow client is enabled, but the server doesn't support it.
cfg.Arrow.NumStreams = 1
cfg.Arrow.MaxStreamLifetime = 100 * time.Second
cfg.QueueSettings.Enabled = false
set := exportertest.NewNopSettings(factory.Type())
set.TelemetrySettings.Logger = zaptest.NewLogger(t)
exp, err := factory.CreateTraces(context.Background(), set, cfg)
require.NoError(t, err)
require.NotNil(t, exp)
type isUserCall struct{}
host := newHostWithExtensions(
map[component.ID]component.Component{
authID: newTestAuthExtension(t, func(ctx context.Context) map[string]string {
if ctx.Value(isUserCall{}) == nil {
return nil
}
return map[string]string{
"callerid": "arrow",
}
}),
},
)
assert.NoError(t, exp.Start(context.Background(), host))
rcv, _ := otelArrowTracesReceiverOnGRPCServer(ln, false)
defer func() {
// Shutdown before GracefulStop, because otherwise we
// wait for a full stream lifetime instead of closing
// after requests are served.
assert.NoError(t, exp.Shutdown(context.Background()))
rcv.srv.GracefulStop()
}()
if streamServiceAvailable {
rcv.startStreamMockArrowTraces(t, okStatusFor)
}
// Delay the server start, slightly.
go func() {
time.Sleep(100 * time.Millisecond)
rcv.start()
}()
// Send two trace items.
td := testdata.GenerateTraces(2)
// Set the context key indicating this is per-request state,
// so the auth extension returns data.
err = exp.ConsumeTraces(context.WithValue(context.Background(), isUserCall{}, true), td)
assert.NoError(t, err)
// Wait until it is received.
assert.Eventually(t, func() bool {
return rcv.requestCount.Load() > 0
}, 10*time.Second, 5*time.Millisecond)
// Verify two items, one request received.
assert.EqualValues(t, int32(2), rcv.totalItems.Load())
assert.EqualValues(t, int32(1), rcv.requestCount.Load())
assert.EqualValues(t, td, rcv.getLastRequest())
// Expect the correct metadata, with or without arrow.
md := rcv.getMetadata()