Debian Codegraph @

exporters/otlp/otlpmetric/otlpmetricgrpc/client.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otlpmetricgrpc // import "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
5
6 import (
7 "context"
8 "errors"
9 "time"
10
11 colmetricpb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
12 metricpb "go.opentelemetry.io/proto/otlp/metrics/v1"
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
19 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal"
20 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/oconf"
21 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/retry"
22 )
23
24 type client struct {
25 metadata metadata.MD
26 exportTimeout time.Duration
27 requestFunc retry.RequestFunc
28
29 // ourConn keeps track of where conn was created: true if created here in
30 // NewClient, or false if passed with an option. This is important on
31 // Shutdown as the conn should only be closed if we created it. Otherwise,
32 // it is up to the processes that passed the conn to close it.
33 ourConn bool
34 conn *grpc.ClientConn
35 msc colmetricpb.MetricsServiceClient
36 }
37
38 // newClient creates a new gRPC metric client.
39 func newClient(_ context.Context, cfg oconf.Config) (*client, error) {
40 c := &client{
41 exportTimeout: cfg.Metrics.Timeout,
42 requestFunc: cfg.RetryConfig.RequestFunc(retryable),
43 conn: cfg.GRPCConn,
44 }
45
46 if len(cfg.Metrics.Headers) > 0 {
47 c.metadata = metadata.New(cfg.Metrics.Headers)
48 }
49
50 if c.conn == nil {
51 // If the caller did not provide a ClientConn when the client was
52 // created, create one using the configuration they did provide.
53 userAgent := "OTel Go OTLP over gRPC metrics exporter/" + Version()
54 dialOpts := []grpc.DialOption{grpc.WithUserAgent(userAgent)}
55 dialOpts = append(dialOpts, cfg.DialOptions...)
56
57 conn, err := grpc.NewClient(cfg.Metrics.Endpoint, dialOpts...)
58 if err != nil {
59 return nil, err
60 }
61 // Keep track that we own the lifecycle of this conn and need to close
62 // it on Shutdown.
63 c.ourConn = true
64 c.conn = conn
65 }
66
67 c.msc = colmetricpb.NewMetricsServiceClient(c.conn)
68
69 return c, nil
70 }
71
72 // Shutdown shuts down the client, freeing all resource.
73 //
74 // Any active connections to a remote endpoint are closed if they were created
75 // by the client. Any gRPC connection passed during creation using
76 // WithGRPCConn will not be closed. It is the caller's responsibility to
77 // handle cleanup of that resource.
78 func (c *client) Shutdown(ctx context.Context) error {
79 // The otlpmetric.Exporter synchronizes access to client methods and
80 // ensures this is called only once. The only thing that needs to be done
81 // here is to release any computational resources the client holds.
82
83 c.metadata = nil
84 c.requestFunc = nil
85 c.msc = nil
86
87 err := ctx.Err()
88 if c.ourConn {
89 closeErr := c.conn.Close()
90 // A context timeout error takes precedence over this error.
91 if err == nil && closeErr != nil {
92 err = closeErr
93 }
94 }
95 c.conn = nil
96 return err
97 }
98
99 // UploadMetrics sends protoMetrics to connected endpoint.
100 //
101 // Retryable errors from the server will be handled according to any
102 // RetryConfig the client was created with.
103 func (c *client) UploadMetrics(ctx context.Context, protoMetrics *metricpb.ResourceMetrics) (uploadErr error) {
104 // The otlpmetric.Exporter synchronizes access to client methods, and
105 // ensures this is not called after the Exporter is shutdown. Only thing
106 // to do here is send data.
107
108 select {
109 case <-ctx.Done():
110 // Do not upload if the context is already expired.
111 return ctx.Err()
112 default:
113 }
114
115 ctx, cancel := c.exportContext(ctx)
116 defer cancel()
117
118 return errors.Join(uploadErr, c.requestFunc(ctx, func(iCtx context.Context) error {
119 resp, err := c.msc.Export(iCtx, &colmetricpb.ExportMetricsServiceRequest{
120 ResourceMetrics: []*metricpb.ResourceMetrics{protoMetrics},
121 })
122 if resp != nil && resp.PartialSuccess != nil {
123 msg := resp.PartialSuccess.GetErrorMessage()
124 n := resp.PartialSuccess.GetRejectedDataPoints()
125 if n != 0 || msg != "" {
126 e := internal.MetricPartialSuccessError(n, msg)
127 uploadErr = errors.Join(uploadErr, e)
128 }
129 }
130 // nil is converted to OK.
131 if status.Code(err) == codes.OK {
132 // Success.
133 return nil
134 }
135 return err
136 }))
137 }
138
139 // exportContext returns a copy of parent with an appropriate deadline and
140 // cancellation function based on the clients configured export timeout.
141 //
142 // It is the callers responsibility to cancel the returned context once its
143 // use is complete, via the parent or directly with the returned CancelFunc, to
144 // ensure all resources are correctly released.
145 func (c *client) exportContext(parent context.Context) (context.Context, context.CancelFunc) {
146 var (
147 ctx context.Context
148 cancel context.CancelFunc
149 )
150
151 if c.exportTimeout > 0 {
152 ctx, cancel = context.WithTimeoutCause(parent, c.exportTimeout, errors.New("exporter export timeout"))
153 } else {
154 ctx, cancel = context.WithCancel(parent) //nolint:gosec // cancel is handled by the caller.
155 }
156
157 if c.metadata.Len() > 0 {
158 md := c.metadata
159 if outMD, ok := metadata.FromOutgoingContext(ctx); ok {
160 md = metadata.Join(md, outMD)
161 }
162
163 ctx = metadata.NewOutgoingContext(ctx, md)
164 }
165
166 return ctx, cancel
167 }
168
169 // retryable returns if err identifies a request that can be retried and a
170 // duration to wait for if an explicit throttle time is included in err.
171 func retryable(err error) (bool, time.Duration) {
172 s := status.Convert(err)
173 return retryableGRPCStatus(s)
174 }
175
176 func retryableGRPCStatus(s *status.Status) (bool, time.Duration) {
177 switch s.Code() {
178 case codes.Canceled,
179 codes.DeadlineExceeded,
180 codes.Aborted,
181 codes.OutOfRange,
182 codes.Unavailable,
183 codes.DataLoss:
184 // Additionally, handle RetryInfo.
185 _, d := throttleDelay(s)
186 return true, d
187 case codes.ResourceExhausted:
188 // Retry only if the server signals that the recovery from resource exhaustion is possible.
189 return throttleDelay(s)
190 }
191
192 // Not a retry-able error.
193 return false, 0
194 }
195
196 // throttleDelay returns if the status is RetryInfo
197 // and the duration to wait for if an explicit throttle time is included.
198 func throttleDelay(s *status.Status) (bool, time.Duration) {
199 for _, detail := range s.Details() {
200 if t, ok := detail.(*errdetails.RetryInfo); ok {
201 return true, t.RetryDelay.AsDuration()
202 }
203 }
204 return false, 0
205 }