-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathobservability_test.go
1088 lines (993 loc) · 33.9 KB
/
observability_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 2022 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 observability
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"go.opencensus.io/stats/view"
"go.opencensus.io/trace"
"google.golang.org/grpc/internal/envconfig"
"google.golang.org/grpc/internal/grpcsync"
"google.golang.org/grpc/internal/grpctest"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/internal/stubserver"
"google.golang.org/grpc/internal/testutils"
testgrpc "google.golang.org/grpc/interop/grpc_testing"
testpb "google.golang.org/grpc/interop/grpc_testing"
)
type s struct {
grpctest.Tester
}
func Test(t *testing.T) {
grpctest.RunSubTests(t, s{})
}
func init() {
// OpenCensus, once included in binary, will spawn a global goroutine
// recorder that is not controllable by application.
// https://github.com/census-instrumentation/opencensus-go/issues/1191
leakcheck.RegisterIgnoreGoroutine("go.opencensus.io/stats/view.(*worker).start")
// google-cloud-go leaks HTTP client. They are aware of this:
// https://github.com/googleapis/google-cloud-go/issues/1183
leakcheck.RegisterIgnoreGoroutine("internal/poll.runtime_pollWait")
}
var (
defaultTestTimeout = 10 * time.Second
testOkPayload = []byte{72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}
defaultRequestCount = 24
)
const (
TypeOpenCensusViewDistribution = "distribution"
TypeOpenCensusViewCount = "count"
TypeOpenCensusViewSum = "sum"
TypeOpenCensusViewLastValue = "last_value"
)
type fakeOpenCensusExporter struct {
// The map of the observed View name and type
SeenViews map[string]string
// Number of spans
SeenSpans int
idCh *testutils.Channel
t *testing.T
mu sync.RWMutex
}
func (fe *fakeOpenCensusExporter) ExportView(vd *view.Data) {
fe.mu.Lock()
defer fe.mu.Unlock()
for _, row := range vd.Rows {
fe.t.Logf("Metrics[%s]", vd.View.Name)
switch row.Data.(type) {
case *view.DistributionData:
fe.SeenViews[vd.View.Name] = TypeOpenCensusViewDistribution
case *view.CountData:
fe.SeenViews[vd.View.Name] = TypeOpenCensusViewCount
case *view.SumData:
fe.SeenViews[vd.View.Name] = TypeOpenCensusViewSum
case *view.LastValueData:
fe.SeenViews[vd.View.Name] = TypeOpenCensusViewLastValue
}
}
}
type traceAndSpanID struct {
spanName string
traceID trace.TraceID
spanID trace.SpanID
isSampled bool
spanKind int
}
type traceAndSpanIDString struct {
traceID string
spanID string
isSampled bool
// SpanKind is the type of span.
SpanKind int
}
// idsToString is a helper that converts from generated trace and span IDs to
// the string version stored in trace message events.
func (tasi *traceAndSpanID) idsToString(projectID string) traceAndSpanIDString {
return traceAndSpanIDString{
traceID: "projects/" + projectID + "/traces/" + tasi.traceID.String(),
spanID: tasi.spanID.String(),
isSampled: tasi.isSampled,
SpanKind: tasi.spanKind,
}
}
func (fe *fakeOpenCensusExporter) ExportSpan(vd *trace.SpanData) {
if fe.idCh != nil {
// This is what export span sees representing the trace/span ID which
// will populate different contexts throughout the system, convert in
// caller to string version as the logging code does.
fe.idCh.Send(traceAndSpanID{
spanName: vd.Name,
traceID: vd.TraceID,
spanID: vd.SpanID,
isSampled: vd.IsSampled(),
spanKind: vd.SpanKind,
})
}
fe.mu.Lock()
defer fe.mu.Unlock()
fe.SeenSpans++
fe.t.Logf("Span[%v]", vd.Name)
}
func (fe *fakeOpenCensusExporter) Flush() {}
func (fe *fakeOpenCensusExporter) Close() error {
return nil
}
func (s) TestRefuseStartWithInvalidPatterns(t *testing.T) {
invalidConfig := &config{
ProjectID: "fake",
CloudLogging: &cloudLogging{
ClientRPCEvents: []clientRPCEvents{
{
Methods: []string{":-)"},
MaxMetadataBytes: 30,
MaxMessageBytes: 30,
},
},
},
}
invalidConfigJSON, err := json.Marshal(invalidConfig)
if err != nil {
t.Fatalf("failed to convert config to JSON: %v", err)
}
oldObservabilityConfig := envconfig.ObservabilityConfig
oldObservabilityConfigFile := envconfig.ObservabilityConfigFile
envconfig.ObservabilityConfig = string(invalidConfigJSON)
envconfig.ObservabilityConfigFile = ""
defer func() {
envconfig.ObservabilityConfig = oldObservabilityConfig
envconfig.ObservabilityConfigFile = oldObservabilityConfigFile
}()
// If there is at least one invalid pattern, which should not be silently tolerated.
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if err := Start(ctx); err == nil {
t.Fatalf("Invalid patterns not triggering error")
}
}
// TestRefuseStartWithExcludeAndWildCardAll tests the scenario where an
// observability configuration is provided with client RPC event specifying to
// exclude, and which matches on the '*' wildcard (any). This should cause an
// error when trying to start the observability system.
func (s) TestRefuseStartWithExcludeAndWildCardAll(t *testing.T) {
invalidConfig := &config{
ProjectID: "fake",
CloudLogging: &cloudLogging{
ClientRPCEvents: []clientRPCEvents{
{
Methods: []string{"*"},
Exclude: true,
MaxMetadataBytes: 30,
MaxMessageBytes: 30,
},
},
},
}
invalidConfigJSON, err := json.Marshal(invalidConfig)
if err != nil {
t.Fatalf("failed to convert config to JSON: %v", err)
}
oldObservabilityConfig := envconfig.ObservabilityConfig
oldObservabilityConfigFile := envconfig.ObservabilityConfigFile
envconfig.ObservabilityConfig = string(invalidConfigJSON)
envconfig.ObservabilityConfigFile = ""
defer func() {
envconfig.ObservabilityConfig = oldObservabilityConfig
envconfig.ObservabilityConfigFile = oldObservabilityConfigFile
}()
// If there is at least one invalid pattern, which should not be silently tolerated.
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if err := Start(ctx); err == nil {
t.Fatalf("Invalid patterns not triggering error")
}
}
// createTmpConfigInFileSystem creates a random observability config at a random
// place in the temporary portion of the file system dependent on system. It
// also sets the environment variable GRPC_CONFIG_OBSERVABILITY_JSON to point to
// this created config.
func createTmpConfigInFileSystem(rawJSON string) (func(), error) {
configJSONFile, err := os.CreateTemp(os.TempDir(), "configJSON-")
if err != nil {
return nil, fmt.Errorf("cannot create file %v: %v", configJSONFile.Name(), err)
}
_, err = configJSONFile.Write(json.RawMessage(rawJSON))
if err != nil {
return nil, fmt.Errorf("cannot write marshalled JSON: %v", err)
}
oldObservabilityConfigFile := envconfig.ObservabilityConfigFile
envconfig.ObservabilityConfigFile = configJSONFile.Name()
return func() {
configJSONFile.Close()
envconfig.ObservabilityConfigFile = oldObservabilityConfigFile
}, nil
}
// TestJSONEnvVarSet tests a valid observability configuration specified by the
// GRPC_CONFIG_OBSERVABILITY_JSON environment variable, whose value represents a
// file path pointing to a JSON encoded config.
func (s) TestJSONEnvVarSet(t *testing.T) {
configJSON := `{
"project_id": "fake"
}`
cleanup, err := createTmpConfigInFileSystem(configJSON)
defer cleanup()
if err != nil {
t.Fatalf("failed to create config in file system: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if err := Start(ctx); err != nil {
t.Fatalf("error starting observability with valid config through file system: %v", err)
}
defer End()
}
// TestBothConfigEnvVarsSet tests the scenario where both configuration
// environment variables are set. The file system environment variable should
// take precedence, and an error should return in the case of the file system
// configuration being invalid, even if the direct configuration environment
// variable is set and valid.
func (s) TestBothConfigEnvVarsSet(t *testing.T) {
invalidConfig := &config{
ProjectID: "fake",
CloudLogging: &cloudLogging{
ClientRPCEvents: []clientRPCEvents{
{
Methods: []string{":-)"},
MaxMetadataBytes: 30,
MaxMessageBytes: 30,
},
},
},
}
invalidConfigJSON, err := json.Marshal(invalidConfig)
if err != nil {
t.Fatalf("failed to convert config to JSON: %v", err)
}
cleanup, err := createTmpConfigInFileSystem(string(invalidConfigJSON))
defer cleanup()
if err != nil {
t.Fatalf("failed to create config in file system: %v", err)
}
// This configuration should be ignored, as precedence 2.
validConfig := &config{
ProjectID: "fake",
CloudLogging: &cloudLogging{
ClientRPCEvents: []clientRPCEvents{
{
Methods: []string{"*"},
MaxMetadataBytes: 30,
MaxMessageBytes: 30,
},
},
},
}
validConfigJSON, err := json.Marshal(validConfig)
if err != nil {
t.Fatalf("failed to convert config to JSON: %v", err)
}
oldObservabilityConfig := envconfig.ObservabilityConfig
envconfig.ObservabilityConfig = string(validConfigJSON)
defer func() {
envconfig.ObservabilityConfig = oldObservabilityConfig
}()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if err := Start(ctx); err == nil {
t.Fatalf("Invalid patterns not triggering error")
}
}
// TestErrInFileSystemEnvVar tests the scenario where an observability
// configuration is specified with environment variable that specifies a
// location in the file system for configuration, and this location doesn't have
// a file (or valid configuration).
func (s) TestErrInFileSystemEnvVar(t *testing.T) {
oldObservabilityConfigFile := envconfig.ObservabilityConfigFile
envconfig.ObservabilityConfigFile = "/this-file/does-not-exist"
defer func() {
envconfig.ObservabilityConfigFile = oldObservabilityConfigFile
}()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if err := Start(ctx); err == nil {
t.Fatalf("Invalid file system path not triggering error")
}
}
func (s) TestNoEnvSet(t *testing.T) {
oldObservabilityConfig := envconfig.ObservabilityConfig
oldObservabilityConfigFile := envconfig.ObservabilityConfigFile
envconfig.ObservabilityConfig = ""
envconfig.ObservabilityConfigFile = ""
defer func() {
envconfig.ObservabilityConfig = oldObservabilityConfig
envconfig.ObservabilityConfigFile = oldObservabilityConfigFile
}()
// If there is no observability config set at all, the Start should return an error.
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if err := Start(ctx); err == nil {
t.Fatalf("Invalid patterns not triggering error")
}
}
func (s) TestOpenCensusIntegration(t *testing.T) {
defaultMetricsReportingInterval = time.Millisecond * 100
fe := &fakeOpenCensusExporter{SeenViews: make(map[string]string), t: t}
defer func(ne func(config *config) (tracingMetricsExporter, error)) {
newExporter = ne
}(newExporter)
newExporter = func(*config) (tracingMetricsExporter, error) {
return fe, nil
}
openCensusOnConfig := &config{
ProjectID: "fake",
CloudMonitoring: &cloudMonitoring{},
CloudTrace: &cloudTrace{
SamplingRate: 1.0,
},
}
cleanup, err := setupObservabilitySystemWithConfig(openCensusOnConfig)
if err != nil {
t.Fatalf("error setting up observability %v", err)
}
defer cleanup()
ss := &stubserver.StubServer{
UnaryCallF: func(context.Context, *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
return &testpb.SimpleResponse{}, nil
},
FullDuplexCallF: func(stream testgrpc.TestService_FullDuplexCallServer) error {
for {
_, err := stream.Recv()
if err == io.EOF {
return nil
}
}
},
}
if err := ss.Start(nil); err != nil {
t.Fatalf("Error starting endpoint server: %v", err)
}
defer ss.Stop()
for i := 0; i < defaultRequestCount; i++ {
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if _, err := ss.Client.UnaryCall(ctx, &testpb.SimpleRequest{Payload: &testpb.Payload{Body: testOkPayload}}); err != nil {
t.Fatalf("Unexpected error from UnaryCall: %v", err)
}
}
t.Logf("unary call passed count=%v", defaultRequestCount)
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
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("unexpected error: %v, expected an EOF error", err)
}
var errs []error
for ctx.Err() == nil {
errs = nil
fe.mu.RLock()
if value := fe.SeenViews["grpc.io/client/api_latency"]; value != TypeOpenCensusViewDistribution {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/client/api_latency: %s != %s", value, TypeOpenCensusViewDistribution))
}
if value := fe.SeenViews["grpc.io/client/started_rpcs"]; value != TypeOpenCensusViewCount {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/client/started_rpcs: %s != %s", value, TypeOpenCensusViewCount))
}
if value := fe.SeenViews["grpc.io/server/started_rpcs"]; value != TypeOpenCensusViewCount {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/server/started_rpcs: %s != %s", value, TypeOpenCensusViewCount))
}
if value := fe.SeenViews["grpc.io/client/completed_rpcs"]; value != TypeOpenCensusViewCount {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/client/completed_rpcs: %s != %s", value, TypeOpenCensusViewCount))
}
if value := fe.SeenViews["grpc.io/server/completed_rpcs"]; value != TypeOpenCensusViewCount {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/server/completed_rpcs: %s != %s", value, TypeOpenCensusViewCount))
}
if value := fe.SeenViews["grpc.io/client/roundtrip_latency"]; value != TypeOpenCensusViewDistribution {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/client/completed_rpcs: %s != %s", value, TypeOpenCensusViewDistribution))
}
if value := fe.SeenViews["grpc.io/server/server_latency"]; value != TypeOpenCensusViewDistribution {
errs = append(errs, fmt.Errorf("grpc.io/server/server_latency: %s != %s", value, TypeOpenCensusViewDistribution))
}
if value := fe.SeenViews["grpc.io/client/sent_compressed_message_bytes_per_rpc"]; value != TypeOpenCensusViewDistribution {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/client/sent_compressed_message_bytes_per_rpc: %s != %s", value, TypeOpenCensusViewDistribution))
}
if value := fe.SeenViews["grpc.io/client/received_compressed_message_bytes_per_rpc"]; value != TypeOpenCensusViewDistribution {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/client/received_compressed_message_bytes_per_rpc: %s != %s", value, TypeOpenCensusViewDistribution))
}
if value := fe.SeenViews["grpc.io/server/sent_compressed_message_bytes_per_rpc"]; value != TypeOpenCensusViewDistribution {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/server/sent_compressed_message_bytes_per_rpc: %s != %s", value, TypeOpenCensusViewDistribution))
}
if value := fe.SeenViews["grpc.io/server/received_compressed_message_bytes_per_rpc"]; value != TypeOpenCensusViewDistribution {
errs = append(errs, fmt.Errorf("unexpected type for grpc.io/server/received_compressed_message_bytes_per_rpc: %s != %s", value, TypeOpenCensusViewDistribution))
}
if fe.SeenSpans <= 0 {
errs = append(errs, fmt.Errorf("unexpected number of seen spans: %v <= 0", fe.SeenSpans))
}
fe.mu.RUnlock()
if len(errs) == 0 {
break
}
time.Sleep(100 * time.Millisecond)
}
if len(errs) != 0 {
t.Fatalf("Invalid OpenCensus export data: %v", errs)
}
}
// TestCustomTagsTracingMetrics verifies that the custom tags defined in our
// observability configuration and set to two hardcoded values are passed to the
// function to create an exporter.
func (s) TestCustomTagsTracingMetrics(t *testing.T) {
defer func(ne func(config *config) (tracingMetricsExporter, error)) {
newExporter = ne
}(newExporter)
fe := &fakeOpenCensusExporter{SeenViews: make(map[string]string), t: t}
newExporter = func(config *config) (tracingMetricsExporter, error) {
ct := config.Labels
if len(ct) < 1 {
t.Fatalf("less than 2 custom tags sent in")
}
if val, ok := ct["customtag1"]; !ok || val != "wow" {
t.Fatalf("incorrect custom tag: got %v, want %v", val, "wow")
}
if val, ok := ct["customtag2"]; !ok || val != "nice" {
t.Fatalf("incorrect custom tag: got %v, want %v", val, "nice")
}
return fe, nil
}
// This configuration present in file system and it's defined custom tags should make it
// to the created exporter.
configJSON := `{
"project_id": "fake",
"cloud_trace": {},
"cloud_monitoring": {"sampling_rate": 1.0},
"labels":{"customtag1":"wow","customtag2":"nice"}
}`
cleanup, err := createTmpConfigInFileSystem(configJSON)
if err != nil {
t.Fatalf("failed to create config in file system: %v", err)
}
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
err = Start(ctx)
defer End()
if err != nil {
t.Fatalf("Start() failed with err: %v", err)
}
}
// TestStartErrorsThenEnd tests that an End call after Start errors works
// without problems, as this is a possible codepath in the public observability
// API.
func (s) TestStartErrorsThenEnd(t *testing.T) {
invalidConfig := &config{
ProjectID: "fake",
CloudLogging: &cloudLogging{
ClientRPCEvents: []clientRPCEvents{
{
Methods: []string{":-)"},
MaxMetadataBytes: 30,
MaxMessageBytes: 30,
},
},
},
}
invalidConfigJSON, err := json.Marshal(invalidConfig)
if err != nil {
t.Fatalf("failed to convert config to JSON: %v", err)
}
oldObservabilityConfig := envconfig.ObservabilityConfig
oldObservabilityConfigFile := envconfig.ObservabilityConfigFile
envconfig.ObservabilityConfig = string(invalidConfigJSON)
envconfig.ObservabilityConfigFile = ""
defer func() {
envconfig.ObservabilityConfig = oldObservabilityConfig
envconfig.ObservabilityConfigFile = oldObservabilityConfigFile
}()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if err := Start(ctx); err == nil {
t.Fatalf("Invalid patterns not triggering error")
}
End()
}
// TestLoggingLinkedWithTraceClientSide tests that client side logs get the
// trace and span id corresponding to the created Call Level Span for the RPC.
func (s) TestLoggingLinkedWithTraceClientSide(t *testing.T) {
fle := &fakeLoggingExporter{
t: t,
}
oldNewLoggingExporter := newLoggingExporter
defer func() {
newLoggingExporter = oldNewLoggingExporter
}()
newLoggingExporter = func(context.Context, *config) (loggingExporter, error) {
return fle, nil
}
idCh := testutils.NewChannel()
fe := &fakeOpenCensusExporter{
t: t,
idCh: idCh,
}
oldNewExporter := newExporter
defer func() {
newExporter = oldNewExporter
}()
newExporter = func(*config) (tracingMetricsExporter, error) {
return fe, nil
}
const projectID = "project-id"
tracesAndLogsConfig := &config{
ProjectID: projectID,
CloudLogging: &cloudLogging{
ClientRPCEvents: []clientRPCEvents{
{
Methods: []string{"*"},
MaxMetadataBytes: 30,
MaxMessageBytes: 30,
},
},
},
CloudTrace: &cloudTrace{
SamplingRate: 1.0,
},
}
cleanup, err := setupObservabilitySystemWithConfig(tracesAndLogsConfig)
if err != nil {
t.Fatalf("error setting up observability %v", err)
}
defer cleanup()
ss := &stubserver.StubServer{
UnaryCallF: func(context.Context, *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
return &testpb.SimpleResponse{}, nil
},
FullDuplexCallF: func(stream testgrpc.TestService_FullDuplexCallServer) error {
_, err := stream.Recv()
if err != io.EOF {
return err
}
return nil
},
}
if err := ss.Start(nil); err != nil {
t.Fatalf("Error starting endpoint server: %v", err)
}
defer ss.Stop()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
// Spawn a goroutine to receive the trace and span ids received by the
// exporter corresponding to a Unary RPC.
readerErrCh := testutils.NewChannel()
unaryDone := grpcsync.NewEvent()
go func() {
var traceAndSpanIDs []traceAndSpanID
val, err := idCh.Receive(ctx)
if err != nil {
readerErrCh.Send(fmt.Errorf("error while waiting for IDs: %v", err))
}
tasi, ok := val.(traceAndSpanID)
if !ok {
readerErrCh.Send(fmt.Errorf("received wrong type from channel: %T", val))
}
traceAndSpanIDs = append(traceAndSpanIDs, tasi)
val, err = idCh.Receive(ctx)
if err != nil {
readerErrCh.Send(fmt.Errorf("error while waiting for IDs: %v", err))
}
tasi, ok = val.(traceAndSpanID)
if !ok {
readerErrCh.Send(fmt.Errorf("received wrong type from channel: %T", val))
}
traceAndSpanIDs = append(traceAndSpanIDs, tasi)
val, err = idCh.Receive(ctx)
if err != nil {
readerErrCh.Send(fmt.Errorf("error while waiting for IDs: %v", err))
}
tasi, ok = val.(traceAndSpanID)
if !ok {
readerErrCh.Send(fmt.Errorf("received wrong type from channel: %T", val))
}
traceAndSpanIDs = append(traceAndSpanIDs, tasi)
<-unaryDone.Done()
var tasiSent traceAndSpanIDString
for _, tasi := range traceAndSpanIDs {
if strings.HasPrefix(tasi.spanName, "grpc.") && tasi.spanKind == trace.SpanKindClient {
tasiSent = tasi.idsToString(projectID)
continue
}
}
fle.mu.Lock()
for _, tasiSeen := range fle.idsSeen {
if diff := cmp.Diff(tasiSeen, &tasiSent, cmp.AllowUnexported(traceAndSpanIDString{}), cmpopts.IgnoreFields(traceAndSpanIDString{}, "SpanKind")); diff != "" {
readerErrCh.Send(fmt.Errorf("got unexpected id, should be a client span (-got, +want): %v", diff))
}
}
fle.entries = nil
fle.mu.Unlock()
readerErrCh.Send(nil)
}()
if _, err := ss.Client.UnaryCall(ctx, &testpb.SimpleRequest{Payload: &testpb.Payload{Body: testOkPayload}}); err != nil {
t.Fatalf("Unexpected error from UnaryCall: %v", err)
}
unaryDone.Fire()
if chErr, err := readerErrCh.Receive(ctx); chErr != nil || err != nil {
if err != nil {
t.Fatalf("Should have received something from error channel: %v", err)
}
if chErr != nil {
t.Fatalf("Should have received a nil error from channel, instead received: %v", chErr)
}
}
}
// TestLoggingLinkedWithTraceServerSide tests that server side logs get the
// trace and span id corresponding to the created Server Span for the RPC.
func (s) TestLoggingLinkedWithTraceServerSide(t *testing.T) {
fle := &fakeLoggingExporter{
t: t,
}
oldNewLoggingExporter := newLoggingExporter
defer func() {
newLoggingExporter = oldNewLoggingExporter
}()
newLoggingExporter = func(context.Context, *config) (loggingExporter, error) {
return fle, nil
}
idCh := testutils.NewChannel()
fe := &fakeOpenCensusExporter{
t: t,
idCh: idCh,
}
oldNewExporter := newExporter
defer func() {
newExporter = oldNewExporter
}()
newExporter = func(*config) (tracingMetricsExporter, error) {
return fe, nil
}
const projectID = "project-id"
tracesAndLogsConfig := &config{
ProjectID: projectID,
CloudLogging: &cloudLogging{
ServerRPCEvents: []serverRPCEvents{
{
Methods: []string{"*"},
MaxMetadataBytes: 30,
MaxMessageBytes: 30,
},
},
},
CloudTrace: &cloudTrace{
SamplingRate: 1.0,
},
}
cleanup, err := setupObservabilitySystemWithConfig(tracesAndLogsConfig)
if err != nil {
t.Fatalf("error setting up observability %v", err)
}
defer cleanup()
ss := &stubserver.StubServer{
UnaryCallF: func(context.Context, *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
return &testpb.SimpleResponse{}, nil
},
FullDuplexCallF: func(stream testgrpc.TestService_FullDuplexCallServer) error {
_, err := stream.Recv()
if err != io.EOF {
return err
}
return nil
},
}
if err := ss.Start(nil); err != nil {
t.Fatalf("Error starting endpoint server: %v", err)
}
defer ss.Stop()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
// Spawn a goroutine to receive the trace and span ids received by the
// exporter corresponding to a Unary RPC.
readerErrCh := testutils.NewChannel()
unaryDone := grpcsync.NewEvent()
go func() {
var traceAndSpanIDs []traceAndSpanID
val, err := idCh.Receive(ctx)
if err != nil {
readerErrCh.Send(fmt.Errorf("error while waiting for IDs: %v", err))
}
tasi, ok := val.(traceAndSpanID)
if !ok {
readerErrCh.Send(fmt.Errorf("received wrong type from channel: %T", val))
}
traceAndSpanIDs = append(traceAndSpanIDs, tasi)
val, err = idCh.Receive(ctx)
if err != nil {
readerErrCh.Send(fmt.Errorf("error while waiting for IDs: %v", err))
}
tasi, ok = val.(traceAndSpanID)
if !ok {
readerErrCh.Send(fmt.Errorf("received wrong type from channel: %T", val))
}
traceAndSpanIDs = append(traceAndSpanIDs, tasi)
val, err = idCh.Receive(ctx)
if err != nil {
readerErrCh.Send(fmt.Errorf("error while waiting for IDs: %v", err))
}
tasi, ok = val.(traceAndSpanID)
if !ok {
readerErrCh.Send(fmt.Errorf("received wrong type from channel: %T", val))
}
traceAndSpanIDs = append(traceAndSpanIDs, tasi)
<-unaryDone.Done()
var tasiServer traceAndSpanIDString
for _, tasi := range traceAndSpanIDs {
if strings.HasPrefix(tasi.spanName, "grpc.") && tasi.spanKind == trace.SpanKindServer {
tasiServer = tasi.idsToString(projectID)
continue
}
}
fle.mu.Lock()
for _, tasiSeen := range fle.idsSeen {
if diff := cmp.Diff(tasiSeen, &tasiServer, cmp.AllowUnexported(traceAndSpanIDString{}), cmpopts.IgnoreFields(traceAndSpanIDString{}, "SpanKind")); diff != "" {
readerErrCh.Send(fmt.Errorf("got unexpected id, should be a server span (-got, +want): %v", diff))
}
}
fle.entries = nil
fle.mu.Unlock()
readerErrCh.Send(nil)
}()
if _, err := ss.Client.UnaryCall(ctx, &testpb.SimpleRequest{Payload: &testpb.Payload{Body: testOkPayload}}); err != nil {
t.Fatalf("Unexpected error from UnaryCall: %v", err)
}
unaryDone.Fire()
if chErr, err := readerErrCh.Receive(ctx); chErr != nil || err != nil {
if err != nil {
t.Fatalf("Should have received something from error channel: %v", err)
}
if chErr != nil {
t.Fatalf("Should have received a nil error from channel, instead received: %v", chErr)
}
}
}
// TestLoggingLinkedWithTrace tests that client and server side logs get the
// trace and span id corresponding to either the Call Level Span or Server Span
// (no determinism, so can only assert one or the other), for Unary and
// Streaming RPCs.
func (s) TestLoggingLinkedWithTrace(t *testing.T) {
fle := &fakeLoggingExporter{
t: t,
}
oldNewLoggingExporter := newLoggingExporter
defer func() {
newLoggingExporter = oldNewLoggingExporter
}()
newLoggingExporter = func(context.Context, *config) (loggingExporter, error) {
return fle, nil
}
idCh := testutils.NewChannel()
fe := &fakeOpenCensusExporter{
t: t,
idCh: idCh,
}
oldNewExporter := newExporter
defer func() {
newExporter = oldNewExporter
}()
newExporter = func(*config) (tracingMetricsExporter, error) {
return fe, nil
}
const projectID = "project-id"
tracesAndLogsConfig := &config{
ProjectID: projectID,
CloudLogging: &cloudLogging{
ClientRPCEvents: []clientRPCEvents{
{
Methods: []string{"*"},
MaxMetadataBytes: 30,
MaxMessageBytes: 30,
},
},
ServerRPCEvents: []serverRPCEvents{
{
Methods: []string{"*"},
MaxMetadataBytes: 30,
MaxMessageBytes: 30,
},
},
},
CloudTrace: &cloudTrace{
SamplingRate: 1.0,
},
}
cleanup, err := setupObservabilitySystemWithConfig(tracesAndLogsConfig)
if err != nil {
t.Fatalf("error setting up observability %v", err)
}
defer cleanup()
ss := &stubserver.StubServer{
UnaryCallF: func(context.Context, *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
return &testpb.SimpleResponse{}, nil
},
FullDuplexCallF: func(stream testgrpc.TestService_FullDuplexCallServer) error {
_, err := stream.Recv()
if err != io.EOF {
return err
}
return nil
},
}
if err := ss.Start(nil); err != nil {
t.Fatalf("Error starting endpoint server: %v", err)
}
defer ss.Stop()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
// Spawn a goroutine to receive the trace and span ids received by the
// exporter corresponding to a Unary RPC.
readerErrCh := testutils.NewChannel()
unaryDone := grpcsync.NewEvent()
go func() {
var traceAndSpanIDs []traceAndSpanID
val, err := idCh.Receive(ctx)
if err != nil {
readerErrCh.Send(fmt.Errorf("error while waiting for IDs: %v", err))
}
tasi, ok := val.(traceAndSpanID)
if !ok {
readerErrCh.Send(fmt.Errorf("received wrong type from channel: %T", val))
}
traceAndSpanIDs = append(traceAndSpanIDs, tasi)
val, err = idCh.Receive(ctx)
if err != nil {
readerErrCh.Send(fmt.Errorf("error while waiting for IDs: %v", err))
}
tasi, ok = val.(traceAndSpanID)
if !ok {
readerErrCh.Send(fmt.Errorf("received wrong type from channel: %T", val))
}
traceAndSpanIDs = append(traceAndSpanIDs, tasi)
val, err = idCh.Receive(ctx)
if err != nil {
readerErrCh.Send(fmt.Errorf("error while waiting for IDs: %v", err))
}
tasi, ok = val.(traceAndSpanID)
if !ok {
readerErrCh.Send(fmt.Errorf("received wrong type from channel: %T", val))
}
traceAndSpanIDs = append(traceAndSpanIDs, tasi)
<-unaryDone.Done()
var tasiSent traceAndSpanIDString
var tasiServer traceAndSpanIDString
for _, tasi := range traceAndSpanIDs {
if strings.HasPrefix(tasi.spanName, "grpc.") && tasi.spanKind == trace.SpanKindClient {
tasiSent = tasi.idsToString(projectID)
continue
}
if strings.HasPrefix(tasi.spanName, "grpc.") && tasi.spanKind == trace.SpanKindServer {
tasiServer = tasi.idsToString(projectID)
}
}
fle.mu.Lock()
for _, tasiSeen := range fle.idsSeen {
if diff := cmp.Diff(tasiSeen, &tasiSent, cmp.AllowUnexported(traceAndSpanIDString{}), cmpopts.IgnoreFields(traceAndSpanIDString{}, "SpanKind")); diff != "" {
if diff2 := cmp.Diff(tasiSeen, &tasiServer, cmp.AllowUnexported(traceAndSpanIDString{}), cmpopts.IgnoreFields(traceAndSpanIDString{}, "SpanKind")); diff2 != "" {
readerErrCh.Send(fmt.Errorf("got unexpected id, should be a client or server span (-got, +want): %v, %v", diff, diff2))
}
}
}
fle.entries = nil
fle.mu.Unlock()
readerErrCh.Send(nil)
}()
if _, err := ss.Client.UnaryCall(ctx, &testpb.SimpleRequest{Payload: &testpb.Payload{Body: testOkPayload}}); err != nil {
t.Fatalf("Unexpected error from UnaryCall: %v", err)
}
unaryDone.Fire()
if chErr, err := readerErrCh.Receive(ctx); chErr != nil || err != nil {
if err != nil {
t.Fatalf("Should have received something from error channel: %v", err)
}
if chErr != nil {
t.Fatalf("Should have received a nil error from channel, instead received: %v", chErr)
}
}