forked from grpc/grpc-go
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathe2e_test.go
More file actions
2772 lines (2583 loc) · 89.4 KB
/
Copy pathe2e_test.go
File metadata and controls
2772 lines (2583 loc) · 89.4 KB
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 2024 gRPC authors.
*
* 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 opentelemetry_test
import (
"context"
"fmt"
"io"
"net"
"slices"
"strconv"
"sync"
"syscall"
"testing"
"time"
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/balancer/pickfirst"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/health"
healthgrpc "google.golang.org/grpc/health/grpc_health_v1"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
otelcodes "go.opentelemetry.io/otel/codes"
oteltrace "go.opentelemetry.io/otel/trace"
v3clusterpb "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
v3corepb "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
v3endpointpb "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
v3listenerpb "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
v3routepb "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
v3clientsideweightedroundrobinpb "github.com/envoyproxy/go-control-plane/envoy/extensions/load_balancing_policies/client_side_weighted_round_robin/v3"
v3wrrlocalitypb "github.com/envoyproxy/go-control-plane/envoy/extensions/load_balancing_policies/wrr_locality/v3"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/wrapperspb"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/baggage"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/metric/metricdata"
"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest"
"go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/encoding/gzip"
experimental "google.golang.org/grpc/experimental/opentelemetry"
"google.golang.org/grpc/internal"
"google.golang.org/grpc/internal/balancer/stub"
"google.golang.org/grpc/internal/grpcsync"
"google.golang.org/grpc/internal/grpctest"
"google.golang.org/grpc/internal/stubserver"
itestutils "google.golang.org/grpc/internal/testutils"
"google.golang.org/grpc/internal/testutils/xds/e2e"
setup "google.golang.org/grpc/internal/testutils/xds/e2e/setup"
testgrpc "google.golang.org/grpc/interop/grpc_testing"
testpb "google.golang.org/grpc/interop/grpc_testing"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/orca"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/resolver/manual"
"google.golang.org/grpc/serviceconfig"
"google.golang.org/grpc/stats/opentelemetry"
"google.golang.org/grpc/stats/opentelemetry/internal/testutils"
"google.golang.org/grpc/status"
)
var defaultTestTimeout = 5 * time.Second
type s struct {
grpctest.Tester
}
func Test(t *testing.T) {
grpctest.RunSubTests(t, s{})
}
// traceSpanInfo is the information received about the trace span. It contains
// subset of information that is needed to verify if correct trace is being
// attributed to the rpc.
type traceSpanInfo struct {
spanKind string
name string
events []trace.Event
attributes []attribute.KeyValue
status otelcodes.Code
}
// defaultMetricsOptions creates default metrics options
func defaultMetricsOptions(_ *testing.T, methodAttributeFilter func(string) bool) (*opentelemetry.MetricsOptions, *metric.ManualReader) {
reader := metric.NewManualReader()
provider := metric.NewMeterProvider(metric.WithReader(reader))
metricsOptions := &opentelemetry.MetricsOptions{
MeterProvider: provider,
Metrics: opentelemetry.DefaultMetrics(),
MethodAttributeFilter: methodAttributeFilter,
}
return metricsOptions, reader
}
// defaultTraceOptions function to create default trace options
func defaultTraceOptions(_ *testing.T) (*experimental.TraceOptions, *tracetest.InMemoryExporter) {
spanExporter := tracetest.NewInMemoryExporter()
spanProcessor := trace.NewSimpleSpanProcessor(spanExporter)
tracerProvider := trace.NewTracerProvider(trace.WithSpanProcessor(spanProcessor))
textMapPropagator := propagation.NewCompositeTextMapPropagator(opentelemetry.GRPCTraceBinPropagator{})
traceOptions := &experimental.TraceOptions{
TracerProvider: tracerProvider,
TextMapPropagator: textMapPropagator,
}
return traceOptions, spanExporter
}
// setupStubServer creates a stub server with OpenTelemetry component configured on client
// and server side and returns the server.
func setupStubServer(t *testing.T, metricsOptions *opentelemetry.MetricsOptions, traceOptions *experimental.TraceOptions) *stubserver.StubServer {
ss := &stubserver.StubServer{
UnaryCallF: func(_ context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
return &testpb.SimpleResponse{Payload: &testpb.Payload{
Body: make([]byte, len(in.GetPayload().GetBody())),
}}, nil
},
FullDuplexCallF: func(stream testgrpc.TestService_FullDuplexCallServer) error {
for {
_, err := stream.Recv()
if err == io.EOF {
return nil
}
}
},
}
otelOptions := opentelemetry.Options{}
if metricsOptions != nil {
otelOptions.MetricsOptions = *metricsOptions
}
if traceOptions != nil {
otelOptions.TraceOptions = *traceOptions
}
if err := ss.Start([]grpc.ServerOption{opentelemetry.ServerOption(otelOptions)},
opentelemetry.DialOption(otelOptions)); err != nil {
t.Fatalf("Error starting endpoint server: %v", err)
}
return ss
}
// waitForTraceSpans waits until the in-memory span exporter has received the
// expected trace spans based on span name and kind. It polls the exporter at a
// short interval until the desired spans are available or the context is
// cancelled.
//
// Returns the collected spans or an error if the context deadline is exceeded
// before the expected spans are exported.
func waitForTraceSpans(ctx context.Context, exporter *tracetest.InMemoryExporter, wantSpans []traceSpanInfo) (tracetest.SpanStubs, error) {
for ; ctx.Err() == nil; <-time.After(time.Millisecond) {
spans := exporter.GetSpans()
if len(spans) < len(wantSpans) {
continue
}
missingAnySpan := false
for _, wantSpan := range wantSpans {
if !slices.ContainsFunc(spans, func(span tracetest.SpanStub) bool {
return span.Name == wantSpan.name && span.SpanKind.String() == wantSpan.spanKind
}) {
missingAnySpan = true
}
}
if !missingAnySpan {
return spans, nil
}
}
return nil, fmt.Errorf("error waiting for complete trace spans %v: %v", wantSpans, ctx.Err())
}
// validateTraces first first groups the received spans by their TraceID. For
// each trace group, it identifies the client, server, and attempt spans for
// both unary and streaming RPCs. It checks that the expected spans are
// present and that the server spans have the correct parent (attempt span).
// Finally, it compares the content of each span (name, kind, attributes,
// events) against the provided expected spans information.
func validateTraces(t *testing.T, spans tracetest.SpanStubs, wantSpanInfos []traceSpanInfo) {
// Group spans by TraceID.
traceSpans := make(map[oteltrace.TraceID][]tracetest.SpanStub)
for _, span := range spans {
traceID := span.SpanContext.TraceID()
traceSpans[traceID] = append(traceSpans[traceID], span)
}
// For each trace group, verify relationships and content.
for traceID, spans := range traceSpans {
var unaryClient, unaryServer, unaryAttempt *tracetest.SpanStub
var streamClient, streamServer, streamAttempt *tracetest.SpanStub
var isUnary, isStream bool
for _, span := range spans {
switch {
case span.Name == "Sent.grpc.testing.TestService.UnaryCall":
isUnary = true
if span.SpanKind == oteltrace.SpanKindClient {
unaryClient = &span
}
case span.Name == "Recv.grpc.testing.TestService.UnaryCall":
isUnary = true
if span.SpanKind == oteltrace.SpanKindServer {
unaryServer = &span
}
case span.Name == "Attempt.grpc.testing.TestService.UnaryCall":
isUnary = true
unaryAttempt = &span
case span.Name == "Sent.grpc.testing.TestService.FullDuplexCall":
isStream = true
if span.SpanKind == oteltrace.SpanKindClient {
streamClient = &span
}
case span.Name == "Recv.grpc.testing.TestService.FullDuplexCall":
isStream = true
if span.SpanKind == oteltrace.SpanKindServer {
streamServer = &span
}
case span.Name == "Attempt.grpc.testing.TestService.FullDuplexCall":
isStream = true
streamAttempt = &span
}
}
if isUnary {
// Verify Unary Call Spans.
if unaryClient == nil {
t.Error("Unary call client span not found")
}
if unaryServer == nil {
t.Error("Unary call server span not found")
}
if unaryAttempt == nil {
t.Error("Unary call attempt span not found")
}
// Check TraceID consistency.
if unaryClient != nil && unaryClient.SpanContext.TraceID() != traceID || unaryServer.SpanContext.TraceID() != traceID {
t.Error("Unary call spans have inconsistent TraceIDs")
}
// Check parent-child relationship via SpanID.
if unaryServer != nil && unaryServer.Parent.SpanID() != unaryAttempt.SpanContext.SpanID() {
t.Error("Unary server span parent does not match attempt span ID")
}
}
if isStream {
// Verify Streaming Call Spans.
if streamClient == nil {
t.Error("Streaming call client span not found")
}
if streamServer == nil {
t.Error("Streaming call server span not found")
}
if streamAttempt == nil {
t.Error("Streaming call attempt span not found")
}
// Check TraceID consistency.
if streamClient != nil && streamClient.SpanContext.TraceID() != traceID || streamServer.SpanContext.TraceID() != traceID {
t.Error("Streaming call spans have inconsistent TraceIDs")
}
if streamServer != nil && streamServer.Parent.SpanID() != streamAttempt.SpanContext.SpanID() {
t.Error("Streaming server span parent does not match attempt span ID")
}
}
}
// Convert spans to traceSpanInfo for cmp.Diff comparison.
actualSpanInfos := make([]traceSpanInfo, len(spans))
for i, s := range spans {
actualSpanInfos[i] = traceSpanInfo{
name: s.Name,
spanKind: s.SpanKind.String(),
attributes: s.Attributes,
events: s.Events,
status: s.Status.Code,
}
}
opts := []cmp.Option{
cmpopts.SortSlices(func(a, b traceSpanInfo) bool {
if a.name == b.name {
return a.spanKind < b.spanKind
}
return a.name < b.name
}),
cmpopts.SortSlices(func(a, b trace.Event) bool { return a.Name < b.Name }),
cmpopts.IgnoreFields(trace.Event{}, "Time"),
cmpopts.EquateComparable(attribute.KeyValue{}, attribute.Value{}, attribute.Set{}),
cmpopts.IgnoreFields(tracetest.SpanStub{}, "InstrumentationScope"),
cmp.AllowUnexported(traceSpanInfo{}),
}
if diff := cmp.Diff(wantSpanInfos, actualSpanInfos, opts...); diff != "" {
t.Errorf("Spans mismatch (-want +got):\n%s", diff)
}
}
// TestMethodAttributeFilter tests the method attribute filter. The method
// filter set should bucket the grpc.method attribute into "other" if the method
// attribute filter specifies.
func (s) TestMethodAttributeFilter(t *testing.T) {
maf := func(str string) bool {
// Will allow duplex/any other type of RPC.
return str != testgrpc.TestService_UnaryCall_FullMethodName
}
mo, reader := defaultMetricsOptions(t, maf)
ss := setupStubServer(t, mo, nil)
defer ss.Stop()
// Make a Unary and Streaming RPC. The Unary RPC should be filtered by the
// method attribute filter, and the Full Duplex (Streaming) RPC should not.
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if _, err := ss.Client.UnaryCall(ctx, &testpb.SimpleRequest{Payload: &testpb.Payload{
Body: make([]byte, 10000),
}}); err != nil {
t.Fatalf("Unexpected error from UnaryCall: %v", err)
}
stream, err := ss.Client.FullDuplexCall(ctx)
if err != nil {
t.Fatalf("ss.Client.FullDuplexCall failed: %f", err)
}
stream.CloseSend()
if _, err = stream.Recv(); err != io.EOF {
t.Fatalf("stream.Recv received an unexpected error: %v, expected an EOF error", err)
}
rm := &metricdata.ResourceMetrics{}
reader.Collect(ctx, rm)
gotMetrics := map[string]metricdata.Metrics{}
for _, sm := range rm.ScopeMetrics {
for _, m := range sm.Metrics {
gotMetrics[m.Name] = m
}
}
wantMetrics := []metricdata.Metrics{
{
Name: "grpc.client.attempt.started",
Description: "Number of client call attempts started.",
Unit: "{attempt}",
Data: metricdata.Sum[int64]{
DataPoints: []metricdata.DataPoint[int64]{
{
Attributes: attribute.NewSet(attribute.String("grpc.method", "grpc.testing.TestService/UnaryCall"), attribute.String("grpc.target", ss.Target)),
Value: 1,
},
{
Attributes: attribute.NewSet(attribute.String("grpc.method", "grpc.testing.TestService/FullDuplexCall"), attribute.String("grpc.target", ss.Target)),
Value: 1,
},
},
Temporality: metricdata.CumulativeTemporality,
IsMonotonic: true,
},
},
{
Name: "grpc.server.call.duration",
Description: "End-to-end time taken to complete a call from server transport's perspective.",
Unit: "s",
Data: metricdata.Histogram[float64]{
DataPoints: []metricdata.HistogramDataPoint[float64]{
{ // Method should go to "other" due to the method attribute filter.
Attributes: attribute.NewSet(attribute.String("grpc.method", "other"), attribute.String("grpc.status", "OK")),
Count: 1,
Bounds: testutils.DefaultLatencyBounds,
},
{
Attributes: attribute.NewSet(attribute.String("grpc.method", "grpc.testing.TestService/FullDuplexCall"), attribute.String("grpc.status", "OK")),
Count: 1,
Bounds: testutils.DefaultLatencyBounds,
},
},
Temporality: metricdata.CumulativeTemporality,
},
},
}
gotMetrics = testutils.WaitForServerMetrics(ctx, t, reader, gotMetrics, wantMetrics)
testutils.CompareMetrics(t, gotMetrics, wantMetrics)
}
// TestAllMetricsOneFunction tests emitted metrics from OpenTelemetry
// instrumentation component. It then configures a system with a gRPC Client and
// gRPC server with the OpenTelemetry Dial and Server Option configured
// specifying all the metrics provided by this package, and makes a Unary RPC
// and a Streaming RPC. These two RPCs should cause certain recording for each
// registered metric observed through a Manual Metrics Reader on the provided
// OpenTelemetry SDK's Meter Provider. It then makes an RPC that is unregistered
// on the Client (no StaticMethodCallOption set) and Server. The method
// attribute on subsequent metrics should be bucketed in "other".
func (s) TestAllMetricsOneFunction(t *testing.T) {
mo, reader := defaultMetricsOptions(t, nil)
ss := setupStubServer(t, mo, nil)
defer ss.Stop()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
// Make two RPC's, a unary RPC and a streaming RPC. These should cause
// certain metrics to be emitted, which should be observed through the
// Metric Reader.
if _, err := ss.Client.UnaryCall(ctx, &testpb.SimpleRequest{Payload: &testpb.Payload{
Body: make([]byte, 10000),
}}, grpc.UseCompressor(gzip.Name)); err != nil { // Deterministic compression.
t.Fatalf("Unexpected error from UnaryCall: %v", err)
}
stream, err := ss.Client.FullDuplexCall(ctx)
if err != nil {
t.Fatalf("ss.Client.FullDuplexCall failed: %f", err)
}
stream.CloseSend()
if _, err = stream.Recv(); err != io.EOF {
t.Fatalf("stream.Recv received an unexpected error: %v, expected an EOF error", err)
}
rm := &metricdata.ResourceMetrics{}
reader.Collect(ctx, rm)
gotMetrics := map[string]metricdata.Metrics{}
for _, sm := range rm.ScopeMetrics {
for _, m := range sm.Metrics {
gotMetrics[m.Name] = m
}
}
compressedSize := testutils.GzipCompressedMessageSize(t, &testpb.SimpleRequest{Payload: &testpb.Payload{Body: make([]byte, 10000)}})
wantMetrics := testutils.MetricData(testutils.MetricDataOptions{
Target: ss.Target,
UnaryCompressedMessageSize: float64(compressedSize),
})
gotMetrics = testutils.WaitForServerMetrics(ctx, t, reader, gotMetrics, wantMetrics)
testutils.CompareMetrics(t, gotMetrics, wantMetrics)
stream, err = ss.Client.FullDuplexCall(ctx)
if err != nil {
t.Fatalf("ss.Client.FullDuplexCall failed: %f", err)
}
stream.CloseSend()
if _, err = stream.Recv(); err != io.EOF {
t.Fatalf("stream.Recv received an unexpected error: %v, expected an EOF error", err)
}
// This Invoke doesn't pass the StaticMethodCallOption. Thus, the method
// attribute should become "other" on client side metrics. Since it is also
// not registered on the server either, it should also become "other" on the
// server metrics method attribute.
ss.CC.Invoke(ctx, "/grpc.testing.TestService/UnregisteredCall", nil, nil, []grpc.CallOption{}...)
ss.CC.Invoke(ctx, "/grpc.testing.TestService/UnregisteredCall", nil, nil, []grpc.CallOption{}...)
ss.CC.Invoke(ctx, "/grpc.testing.TestService/UnregisteredCall", nil, nil, []grpc.CallOption{}...)
rm = &metricdata.ResourceMetrics{}
reader.Collect(ctx, rm)
gotMetrics = map[string]metricdata.Metrics{}
for _, sm := range rm.ScopeMetrics {
for _, m := range sm.Metrics {
gotMetrics[m.Name] = m
}
}
unaryMethodAttr := attribute.String("grpc.method", "grpc.testing.TestService/UnaryCall")
duplexMethodAttr := attribute.String("grpc.method", "grpc.testing.TestService/FullDuplexCall")
targetAttr := attribute.String("grpc.target", ss.Target)
otherMethodAttr := attribute.String("grpc.method", "other")
wantMetrics = []metricdata.Metrics{
{
Name: "grpc.client.attempt.started",
Description: "Number of client call attempts started.",
Unit: "{attempt}",
Data: metricdata.Sum[int64]{
DataPoints: []metricdata.DataPoint[int64]{
{
Attributes: attribute.NewSet(unaryMethodAttr, targetAttr),
Value: 1,
},
{
Attributes: attribute.NewSet(duplexMethodAttr, targetAttr),
Value: 2,
},
{
Attributes: attribute.NewSet(otherMethodAttr, targetAttr),
Value: 3,
},
},
Temporality: metricdata.CumulativeTemporality,
IsMonotonic: true,
},
},
{
Name: "grpc.server.call.started",
Description: "Number of server calls started.",
Unit: "{call}",
Data: metricdata.Sum[int64]{
DataPoints: []metricdata.DataPoint[int64]{
{
Attributes: attribute.NewSet(unaryMethodAttr),
Value: 1,
},
{
Attributes: attribute.NewSet(duplexMethodAttr),
Value: 2,
},
{
Attributes: attribute.NewSet(otherMethodAttr),
Value: 3,
},
},
Temporality: metricdata.CumulativeTemporality,
IsMonotonic: true,
},
},
}
for _, metric := range wantMetrics {
val, ok := gotMetrics[metric.Name]
if !ok {
t.Fatalf("Metric %v not present in recorded metrics", metric.Name)
}
if !metricdatatest.AssertEqual(t, metric, val, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars()) {
t.Fatalf("Metrics data type not equal for metric: %v", metric.Name)
}
}
}
// clusterWithLBConfiguration returns a cluster resource with the proto message
// passed Marshaled to an any and specified through the load_balancing_policy
// field.
func clusterWithLBConfiguration(t *testing.T, clusterName, edsServiceName string, secLevel e2e.SecurityLevel, m proto.Message) *v3clusterpb.Cluster {
cluster := e2e.DefaultCluster(clusterName, edsServiceName, secLevel)
cluster.LoadBalancingPolicy = &v3clusterpb.LoadBalancingPolicy{
Policies: []*v3clusterpb.LoadBalancingPolicy_Policy{
{
TypedExtensionConfig: &v3corepb.TypedExtensionConfig{
TypedConfig: itestutils.MarshalAny(t, m),
},
},
},
}
return cluster
}
func metricsDataFromReader(ctx context.Context, reader *metric.ManualReader) map[string]metricdata.Metrics {
rm := &metricdata.ResourceMetrics{}
reader.Collect(ctx, rm)
gotMetrics := map[string]metricdata.Metrics{}
for _, sm := range rm.ScopeMetrics {
for _, m := range sm.Metrics {
gotMetrics[m.Name] = m
}
}
return gotMetrics
}
// TestWRRMetrics tests the metrics emitted from the WRR LB Policy. It
// configures WRR as an endpoint picking policy through xDS on a ClientConn
// alongside an OpenTelemetry stats handler. It makes a few RPC's, and then
// sleeps for a bit to allow weight to expire. It then asserts OpenTelemetry
// metrics atoms are eventually present for all four WRR Metrics, alongside the
// correct target and locality label for each metric.
func (s) TestWRRMetrics(t *testing.T) {
cmr := orca.NewServerMetricsRecorder().(orca.CallMetricsRecorder)
backend1 := stubserver.StartTestService(t, &stubserver.StubServer{
EmptyCallF: func(ctx context.Context, _ *testpb.Empty) (*testpb.Empty, error) {
if r := orca.CallMetricsRecorderFromContext(ctx); r != nil {
// Copy metrics from what the test set in cmr into r.
sm := cmr.(orca.ServerMetricsProvider).ServerMetrics()
r.SetApplicationUtilization(sm.AppUtilization)
r.SetQPS(sm.QPS)
r.SetEPS(sm.EPS)
}
return &testpb.Empty{}, nil
},
}, orca.CallMetricsServerOption(nil))
port1 := itestutils.ParsePort(t, backend1.Address)
defer backend1.Stop()
cmr.SetQPS(10.0)
cmr.SetApplicationUtilization(1.0)
backend2 := stubserver.StartTestService(t, &stubserver.StubServer{
EmptyCallF: func(ctx context.Context, _ *testpb.Empty) (*testpb.Empty, error) {
if r := orca.CallMetricsRecorderFromContext(ctx); r != nil {
// Copy metrics from what the test set in cmr into r.
sm := cmr.(orca.ServerMetricsProvider).ServerMetrics()
r.SetApplicationUtilization(sm.AppUtilization)
r.SetQPS(sm.QPS)
r.SetEPS(sm.EPS)
}
return &testpb.Empty{}, nil
},
}, orca.CallMetricsServerOption(nil))
port2 := itestutils.ParsePort(t, backend2.Address)
defer backend2.Stop()
const serviceName = "my-service-client-side-xds"
// Start an xDS management server.
managementServer, nodeID, _, xdsResolver := setup.ManagementServerAndResolver(t)
wrrConfig := &v3wrrlocalitypb.WrrLocality{
EndpointPickingPolicy: &v3clusterpb.LoadBalancingPolicy{
Policies: []*v3clusterpb.LoadBalancingPolicy_Policy{
{
TypedExtensionConfig: &v3corepb.TypedExtensionConfig{
TypedConfig: itestutils.MarshalAny(t, &v3clientsideweightedroundrobinpb.ClientSideWeightedRoundRobin{
EnableOobLoadReport: &wrapperspb.BoolValue{
Value: false,
},
// BlackoutPeriod long enough to cause load report
// weight to trigger in the scope of test case.
// WeightExpirationPeriod will cause the load report
// weight for backend 1 to expire.
BlackoutPeriod: durationpb.New(5 * time.Millisecond),
WeightExpirationPeriod: durationpb.New(500 * time.Millisecond),
WeightUpdatePeriod: durationpb.New(time.Second),
ErrorUtilizationPenalty: &wrapperspb.FloatValue{Value: 1},
}),
},
},
},
},
}
routeConfigName := "route-" + serviceName
clusterName := "cluster-" + serviceName
endpointsName := "endpoints-" + serviceName
resources := e2e.UpdateOptions{
NodeID: nodeID,
Listeners: []*v3listenerpb.Listener{e2e.DefaultClientListener(serviceName, routeConfigName)},
Routes: []*v3routepb.RouteConfiguration{e2e.DefaultRouteConfig(routeConfigName, serviceName, clusterName)},
Clusters: []*v3clusterpb.Cluster{clusterWithLBConfiguration(t, clusterName, endpointsName, e2e.SecurityLevelNone, wrrConfig)},
Endpoints: []*v3endpointpb.ClusterLoadAssignment{e2e.EndpointResourceWithOptions(e2e.EndpointOptions{
ClusterName: endpointsName,
Host: "localhost",
Localities: []e2e.LocalityOptions{
{
Backends: []e2e.BackendOptions{{Ports: []uint32{port1}}, {Ports: []uint32{port2}}},
Weight: 1,
},
},
})},
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if err := managementServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
reader := metric.NewManualReader()
provider := metric.NewMeterProvider(metric.WithReader(reader))
mo := opentelemetry.MetricsOptions{
MeterProvider: provider,
Metrics: opentelemetry.DefaultMetrics().Add("grpc.lb.wrr.rr_fallback", "grpc.lb.wrr.endpoint_weight_not_yet_usable", "grpc.lb.wrr.endpoint_weight_stale", "grpc.lb.wrr.endpoint_weights"),
OptionalLabels: []string{"grpc.lb.locality", "grpc.lb.backend_service"},
}
target := fmt.Sprintf("xds:///%s", serviceName)
cc, err := grpc.NewClient(target, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithResolvers(xdsResolver), opentelemetry.DialOption(opentelemetry.Options{MetricsOptions: mo}))
if err != nil {
t.Fatalf("Failed to dial local test server: %v", err)
}
defer cc.Close()
client := testgrpc.NewTestServiceClient(cc)
// Make 100 RPC's. The two backends will send back load reports per call
// giving the two SubChannels weights which will eventually expire. Two
// backends needed as for only one backend, WRR does not recompute the
// scheduler.
receivedExpectedMetrics := grpcsync.NewEvent()
go func() {
for !receivedExpectedMetrics.HasFired() && ctx.Err() == nil {
client.EmptyCall(ctx, &testpb.Empty{})
time.Sleep(2 * time.Millisecond)
}
}()
targetAttr := attribute.String("grpc.target", target)
localityAttr := attribute.String("grpc.lb.locality", `{region="region-1", zone="zone-1", sub_zone="subzone-1"}`)
backendServiceAttr := attribute.String("grpc.lb.backend_service", clusterName)
wantMetrics := []metricdata.Metrics{
{
Name: "grpc.lb.wrr.rr_fallback",
Description: "EXPERIMENTAL. Number of scheduler updates in which there were not enough endpoints with valid weight, which caused the WRR policy to fall back to RR behavior.",
Unit: "{update}",
Data: metricdata.Sum[int64]{
DataPoints: []metricdata.DataPoint[int64]{
{
Attributes: attribute.NewSet(targetAttr, localityAttr, backendServiceAttr),
Value: 1, // value ignored
},
},
Temporality: metricdata.CumulativeTemporality,
IsMonotonic: true,
},
},
{
Name: "grpc.lb.wrr.endpoint_weight_not_yet_usable",
Description: "EXPERIMENTAL. Number of endpoints from each scheduler update that don't yet have usable weight information (i.e., either the load report has not yet been received, or it is within the blackout period).",
Unit: "{endpoint}",
Data: metricdata.Sum[int64]{
DataPoints: []metricdata.DataPoint[int64]{
{
Attributes: attribute.NewSet(targetAttr, localityAttr, backendServiceAttr),
Value: 1, // value ignored
},
},
Temporality: metricdata.CumulativeTemporality,
IsMonotonic: true,
},
},
{
Name: "grpc.lb.wrr.endpoint_weights",
Description: "EXPERIMENTAL. Weight of each endpoint, recorded on every scheduler update. Endpoints without usable weights will be recorded as weight 0.",
Unit: "{endpoint}",
Data: metricdata.Histogram[float64]{
DataPoints: []metricdata.HistogramDataPoint[float64]{
{
Attributes: attribute.NewSet(targetAttr, localityAttr, backendServiceAttr),
},
},
Temporality: metricdata.CumulativeTemporality,
},
},
}
if err := pollForWantMetrics(ctx, t, reader, wantMetrics); err != nil {
t.Fatal(err)
}
receivedExpectedMetrics.Fire()
// Poll for 5 seconds for weight expiration metric. No more RPC's are being
// made, so weight should expire on a subsequent scheduler update.
eventuallyWantMetric := metricdata.Metrics{
Name: "grpc.lb.wrr.endpoint_weight_stale",
Description: "EXPERIMENTAL. Number of endpoints from each scheduler update whose latest weight is older than the expiration period.",
Unit: "{endpoint}",
Data: metricdata.Sum[int64]{
DataPoints: []metricdata.DataPoint[int64]{
{
Attributes: attribute.NewSet(targetAttr, localityAttr, backendServiceAttr),
Value: 1, // value ignored
},
},
Temporality: metricdata.CumulativeTemporality,
IsMonotonic: true,
},
}
if err := pollForWantMetrics(ctx, t, reader, []metricdata.Metrics{eventuallyWantMetric}); err != nil {
t.Fatal(err)
}
}
// pollForWantMetrics polls for the wantMetrics to show up on reader. Returns an
// error if metric is present but not equal to expected, or if the wantMetrics
// do not show up during the context timeout.
func pollForWantMetrics(ctx context.Context, t *testing.T, reader *metric.ManualReader, wantMetrics []metricdata.Metrics) error {
for ; ctx.Err() == nil; <-time.After(time.Millisecond) {
gotMetrics := metricsDataFromReader(ctx, reader)
containsAllMetrics := true
for _, metric := range wantMetrics {
val, ok := gotMetrics[metric.Name]
if !ok {
containsAllMetrics = false
break
}
if !metricdatatest.AssertEqual(t, metric, val, metricdatatest.IgnoreValue(), metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars()) {
return fmt.Errorf("metrics data type not equal for metric: %v", metric.Name)
}
}
if containsAllMetrics {
return nil
}
time.Sleep(5 * time.Millisecond)
}
return fmt.Errorf("error waiting for metrics %v: %v", wantMetrics, ctx.Err())
}
// TestMetricsAndTracesOptionEnabled verifies the integration of metrics and traces
// emitted by the OpenTelemetry instrumentation in a gRPC environment. It sets up a
// stub server with both metrics and traces enabled, and tests the correct emission
// of metrics and traces during a Unary RPC and a Streaming RPC. The test ensures
// that the emitted metrics reflect the operations performed, including the size of
// the compressed message, and verifies that tracing information is correctly recorded.
func (s) TestMetricsAndTracesOptionEnabled(t *testing.T) {
// Create default metrics options
mo, reader := defaultMetricsOptions(t, nil)
// Create default trace options
to, exporter := defaultTraceOptions(t)
ss := setupStubServer(t, mo, to)
defer ss.Stop()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout*2)
defer cancel()
// Make two RPC's, a unary RPC and a streaming RPC. These should cause
// certain metrics and traces to be emitted which should be observed
// through metrics reader and span exporter respectively.
if _, err := ss.Client.UnaryCall(ctx, &testpb.SimpleRequest{Payload: &testpb.Payload{
Body: make([]byte, 10000),
}}, grpc.UseCompressor(gzip.Name)); err != nil { // Deterministic compression.
t.Fatalf("Unexpected error from UnaryCall: %v", err)
}
stream, err := ss.Client.FullDuplexCall(ctx)
if err != nil {
t.Fatalf("ss.Client.FullDuplexCall failed: %f", err)
}
stream.CloseSend()
if _, err = stream.Recv(); err != io.EOF {
t.Fatalf("stream.Recv received an unexpected error: %v, expected an EOF error", err)
}
// Verify metrics
rm := &metricdata.ResourceMetrics{}
reader.Collect(ctx, rm)
gotMetrics := map[string]metricdata.Metrics{}
for _, sm := range rm.ScopeMetrics {
for _, m := range sm.Metrics {
gotMetrics[m.Name] = m
}
}
compressedSize := testutils.GzipCompressedMessageSize(t, &testpb.SimpleRequest{Payload: &testpb.Payload{Body: make([]byte, 10000)}})
wantMetrics := testutils.MetricData(testutils.MetricDataOptions{
Target: ss.Target,
UnaryCompressedMessageSize: float64(compressedSize),
})
gotMetrics = testutils.WaitForServerMetrics(ctx, t, reader, gotMetrics, wantMetrics)
testutils.CompareMetrics(t, gotMetrics, wantMetrics)
wantSpanInfos := []traceSpanInfo{
{
name: "Recv.grpc.testing.TestService.UnaryCall",
spanKind: oteltrace.SpanKindServer.String(),
status: otelcodes.Ok,
attributes: nil,
events: []trace.Event{
{
Name: "Inbound message",
Attributes: []attribute.KeyValue{
{
Key: "sequence-number",
Value: attribute.IntValue(0),
},
{
Key: "message-size",
Value: attribute.IntValue(10006),
},
{
Key: "message-size-compressed",
Value: attribute.IntValue(compressedSize),
},
},
},
{
Name: "Outbound message",
Attributes: []attribute.KeyValue{
{
Key: "sequence-number",
Value: attribute.IntValue(0),
},
{
Key: "message-size",
Value: attribute.IntValue(10006),
},
{
Key: "message-size-compressed",
Value: attribute.IntValue(compressedSize),
},
},
},
},
},
{
name: "Attempt.grpc.testing.TestService.UnaryCall",
spanKind: oteltrace.SpanKindInternal.String(),
status: otelcodes.Ok,
attributes: []attribute.KeyValue{
{
Key: "previous-rpc-attempts",
Value: attribute.IntValue(0),
},
{
Key: "transparent-retry",
Value: attribute.BoolValue(false),
},
},
events: []trace.Event{
{
Name: "Outbound message",
Attributes: []attribute.KeyValue{
{
Key: "sequence-number",
Value: attribute.IntValue(0),
},
{
Key: "message-size",
Value: attribute.IntValue(10006),
},
{
Key: "message-size-compressed",
Value: attribute.IntValue(compressedSize),
},
},
},
{
Name: "Inbound message",
Attributes: []attribute.KeyValue{
{
Key: "sequence-number",
Value: attribute.IntValue(0),
},
{
Key: "message-size",
Value: attribute.IntValue(10006),
},
{
Key: "message-size-compressed",
Value: attribute.IntValue(compressedSize),
},
},
},
},
},
{
name: "Sent.grpc.testing.TestService.UnaryCall",
spanKind: oteltrace.SpanKindClient.String(),
status: otelcodes.Ok,
attributes: nil,
events: nil,
},
{
name: "Recv.grpc.testing.TestService.FullDuplexCall",
spanKind: oteltrace.SpanKindServer.String(),
status: otelcodes.Ok,
attributes: nil,
events: nil,
},
{
name: "Sent.grpc.testing.TestService.FullDuplexCall",
spanKind: oteltrace.SpanKindClient.String(),
status: otelcodes.Ok,
attributes: nil,
events: nil,
},
{
name: "Attempt.grpc.testing.TestService.FullDuplexCall",
spanKind: oteltrace.SpanKindInternal.String(),
status: otelcodes.Ok,
attributes: []attribute.KeyValue{
{
Key: "previous-rpc-attempts",
Value: attribute.IntValue(0),
},
{
Key: "transparent-retry",
Value: attribute.BoolValue(false),
},
},
events: nil,
},
}
spans, err := waitForTraceSpans(ctx, exporter, wantSpanInfos)
if err != nil {
t.Fatal(err)
}
validateTraces(t, spans, wantSpanInfos)
}
// TestTracingOnlyOptionEnabled verifies that tracing works correctly when only
// tracing is enabled (metrics are disabled). It ensures that the method name
// is correctly populated in both client and server spans.