Debian Codegraph @

exporters/otlp/otlpmetric/otlpmetricgrpc/client_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otlpmetricgrpc
5
6 import (
7 "context"
8 "testing"
9 "time"
10
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 "google.golang.org/genproto/googleapis/rpc/errdetails"
14 "google.golang.org/grpc"
15 "google.golang.org/grpc/codes"
16 "google.golang.org/grpc/metadata"
17 "google.golang.org/grpc/status"
18 "google.golang.org/protobuf/types/known/durationpb"
19
20 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/oconf"
21 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/otest"
22 "go.opentelemetry.io/otel/sdk/metric"
23 "go.opentelemetry.io/otel/sdk/metric/metricdata"
24 )
25
26 func TestThrottleDelay(t *testing.T) {
27 c := codes.ResourceExhausted
28 testcases := []struct {
29 status *status.Status
30 wantOK bool
31 wantDuration time.Duration
32 }{
33 {
34 status: status.New(c, "NoRetryInfo"),
35 wantOK: false,
36 wantDuration: 0,
37 },
38 {
39 status: func() *status.Status {
40 s, err := status.New(c, "SingleRetryInfo").WithDetails(
41 &errdetails.RetryInfo{
42 RetryDelay: durationpb.New(15 * time.Millisecond),
43 },
44 )
45 require.NoError(t, err)
46 return s
47 }(),
48 wantOK: true,
49 wantDuration: 15 * time.Millisecond,
50 },
51 {
52 status: func() *status.Status {
53 s, err := status.New(c, "ErrorInfo").WithDetails(
54 &errdetails.ErrorInfo{Reason: "no throttle detail"},
55 )
56 require.NoError(t, err)
57 return s
58 }(),
59 wantOK: false,
60 wantDuration: 0,
61 },
62 {
63 status: func() *status.Status {
64 s, err := status.New(c, "ErrorAndRetryInfo").WithDetails(
65 &errdetails.ErrorInfo{Reason: "with throttle detail"},
66 &errdetails.RetryInfo{
67 RetryDelay: durationpb.New(13 * time.Minute),
68 },
69 )
70 require.NoError(t, err)
71 return s
72 }(),
73 wantOK: true,
74 wantDuration: 13 * time.Minute,
75 },
76 {
77 status: func() *status.Status {
78 s, err := status.New(c, "DoubleRetryInfo").WithDetails(
79 &errdetails.RetryInfo{
80 RetryDelay: durationpb.New(13 * time.Minute),
81 },
82 &errdetails.RetryInfo{
83 RetryDelay: durationpb.New(15 * time.Minute),
84 },
85 )
86 require.NoError(t, err)
87 return s
88 }(),
89 wantOK: true,
90 wantDuration: 13 * time.Minute,
91 },
92 }
93
94 for _, tc := range testcases {
95 t.Run(tc.status.Message(), func(t *testing.T) {
96 ok, d := throttleDelay(tc.status)
97 assert.Equal(t, tc.wantOK, ok)
98 assert.Equal(t, tc.wantDuration, d)
99 })
100 }
101 }
102
103 func TestRetryable(t *testing.T) {
104 retryableCodes := map[codes.Code]bool{
105 codes.OK: false,
106 codes.Canceled: true,
107 codes.Unknown: false,
108 codes.InvalidArgument: false,
109 codes.DeadlineExceeded: true,
110 codes.NotFound: false,
111 codes.AlreadyExists: false,
112 codes.PermissionDenied: false,
113 codes.ResourceExhausted: false,
114 codes.FailedPrecondition: false,
115 codes.Aborted: true,
116 codes.OutOfRange: true,
117 codes.Unimplemented: false,
118 codes.Internal: false,
119 codes.Unavailable: true,
120 codes.DataLoss: true,
121 codes.Unauthenticated: false,
122 }
123
124 for c, want := range retryableCodes {
125 got, _ := retryable(status.Error(c, ""))
126 assert.Equalf(t, want, got, "evaluate(%s)", c)
127 }
128 }
129
130 func TestRetryableGRPCStatusResourceExhaustedWithRetryInfo(t *testing.T) {
131 delay := 15 * time.Millisecond
132 s, err := status.New(codes.ResourceExhausted, "WithRetryInfo").WithDetails(
133 &errdetails.RetryInfo{
134 RetryDelay: durationpb.New(delay),
135 },
136 )
137 require.NoError(t, err)
138
139 ok, d := retryableGRPCStatus(s)
140 assert.True(t, ok)
141 assert.Equal(t, delay, d)
142 }
143
144 type clientShim struct {
145 *client
146 }
147
148 func (clientShim) Temporality(metric.InstrumentKind) metricdata.Temporality {
149 return metricdata.CumulativeTemporality
150 }
151
152 func (clientShim) Aggregation(metric.InstrumentKind) metric.Aggregation {
153 return nil
154 }
155
156 func (clientShim) ForceFlush(ctx context.Context) error {
157 return ctx.Err()
158 }
159
160 func TestClient(t *testing.T) {
161 factory := func(rCh <-chan otest.ExportResult) (otest.Client, otest.Collector) {
162 coll, err := otest.NewGRPCCollector("", rCh)
163 require.NoError(t, err)
164
165 ctx := t.Context()
166 addr := coll.Addr().String()
167 opts := []Option{WithEndpoint(addr), WithInsecure()}
168 cfg := oconf.NewGRPCConfig(asGRPCOptions(opts)...)
169 client, err := newClient(ctx, cfg)
170 require.NoError(t, err)
171 return clientShim{client}, coll
172 }
173
174 t.Run("Integration", otest.RunClientTests(factory))
175 }
176
177 func TestConfig(t *testing.T) {
178 factoryFunc := func(rCh <-chan otest.ExportResult, o ...Option) (metric.Exporter, *otest.GRPCCollector) {
179 coll, err := otest.NewGRPCCollector("", rCh)
180 require.NoError(t, err)
181
182 ctx := t.Context()
183 opts := append([]Option{
184 WithEndpoint(coll.Addr().String()),
185 WithInsecure(),
186 }, o...)
187 exp, err := New(ctx, opts...)
188 require.NoError(t, err)
189 return exp, coll
190 }
191
192 t.Run("WithEndpointURL", func(t *testing.T) {
193 coll, err := otest.NewGRPCCollector("", nil)
194 require.NoError(t, err)
195 t.Cleanup(coll.Shutdown)
196
197 ctx := context.Background() //nolint:usetesting // required to avoid getting a canceled context at cleanup.
198 exp, err := New(ctx, WithEndpointURL("http://"+coll.Addr().String()))
199 require.NoError(t, err)
200 t.Cleanup(func() { require.NoError(t, exp.Shutdown(ctx)) })
201
202 assert.NoError(t, exp.Export(ctx, &metricdata.ResourceMetrics{}))
203 assert.Len(t, coll.Collect().Dump(), 1)
204 })
205
206 t.Run("WithHeaders", func(t *testing.T) {
207 key := "my-custom-header"
208 headers := map[string]string{key: "custom-value"}
209 exp, coll := factoryFunc(nil, WithHeaders(headers))
210 t.Cleanup(coll.Shutdown)
211
212 ctx := t.Context()
213 additionalKey := "additional-custom-header"
214 ctx = metadata.AppendToOutgoingContext(ctx, additionalKey, "additional-value")
215 require.NoError(t, exp.Export(ctx, &metricdata.ResourceMetrics{}))
216 // Ensure everything is flushed.
217 require.NoError(t, exp.Shutdown(ctx))
218
219 got := coll.Headers()
220 require.Regexp(t, "OTel Go OTLP over gRPC metrics exporter/[01]\\..*", got)
221 require.Contains(t, got, key)
222 require.Contains(t, got, additionalKey)
223 assert.Equal(t, []string{headers[key]}, got[key])
224 })
225
226 t.Run("WithTimeout", func(t *testing.T) {
227 // Do not send on rCh so the Collector never responds to the client.
228 rCh := make(chan otest.ExportResult)
229 t.Cleanup(func() { close(rCh) })
230 exp, coll := factoryFunc(
231 rCh,
232 WithTimeout(time.Millisecond),
233 WithRetry(RetryConfig{Enabled: false}),
234 )
235 t.Cleanup(coll.Shutdown)
236 ctx := context.Background() //nolint:usetesting // required to avoid getting a canceled context at cleanup.
237 t.Cleanup(func() { require.NoError(t, exp.Shutdown(ctx)) })
238 err := exp.Export(ctx, &metricdata.ResourceMetrics{})
239 assert.ErrorContains(t, err, "DeadlineExceeded")
240 })
241
242 t.Run("WithCustomUserAgent", func(t *testing.T) {
243 key := "user-agent"
244 customerUserAgent := "custom-user-agent"
245 exp, coll := factoryFunc(nil, WithDialOption(grpc.WithUserAgent(customerUserAgent)))
246 t.Cleanup(coll.Shutdown)
247 ctx := t.Context()
248 require.NoError(t, exp.Export(ctx, &metricdata.ResourceMetrics{}))
249 // Ensure everything is flushed.
250 require.NoError(t, exp.Shutdown(ctx))
251
252 got := coll.Headers()
253 assert.Contains(t, got[key][0], customerUserAgent)
254 })
255 }