Debian Codegraph @

exporter/otlphttpexporter/otlp.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otlphttpexporter // import "go.opentelemetry.io/collector/exporter/otlphttpexporter"
5
6 import (
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "io"
12 "net/http"
13 "net/url"
14 "runtime"
15 "strconv"
16 "time"
17
18 "go.uber.org/zap"
19 "google.golang.org/genproto/googleapis/rpc/status"
20 "google.golang.org/protobuf/proto"
21
22 "go.opentelemetry.io/collector/component"
23 "go.opentelemetry.io/collector/consumer/consumererror"
24 "go.opentelemetry.io/collector/exporter"
25 "go.opentelemetry.io/collector/exporter/exporterhelper"
26 "go.opentelemetry.io/collector/internal/statusutil"
27 "go.opentelemetry.io/collector/pdata/plog"
28 "go.opentelemetry.io/collector/pdata/plog/plogotlp"
29 "go.opentelemetry.io/collector/pdata/pmetric"
30 "go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
31 "go.opentelemetry.io/collector/pdata/pprofile"
32 "go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp"
33 "go.opentelemetry.io/collector/pdata/ptrace"
34 "go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
35 )
36
37 type baseExporter struct {
38 // Input configuration.
39 config *Config
40 client *http.Client
41 tracesURL string
42 metricsURL string
43 logsURL string
44 profilesURL string
45 logger *zap.Logger
46 settings component.TelemetrySettings
47 // Default user-agent header.
48 userAgent string
49 }
50
51 const (
52 headerRetryAfter = "Retry-After"
53 maxHTTPResponseReadBytes = 64 * 1024
54
55 jsonContentType = "application/json"
56 protobufContentType = "application/x-protobuf"
57 )
58
59 // Create new exporter.
60 func newExporter(cfg component.Config, set exporter.Settings) (*baseExporter, error) {
61 oCfg := cfg.(*Config)
62
63 if oCfg.ClientConfig.Endpoint != "" {
64 _, err := url.Parse(oCfg.ClientConfig.Endpoint)
65 if err != nil {
66 return nil, errors.New("endpoint must be a valid URL")
67 }
68 }
69
70 userAgent := fmt.Sprintf("%s/%s (%s/%s)",
71 set.BuildInfo.Description, set.BuildInfo.Version, runtime.GOOS, runtime.GOARCH)
72
73 // client construction is deferred to start
74 return &baseExporter{
75 config: oCfg,
76 logger: set.Logger,
77 userAgent: userAgent,
78 settings: set.TelemetrySettings,
79 }, nil
80 }
81
82 // start actually creates the HTTP client. The client construction is deferred till this point as this
83 // is the only place we get hold of Extensions which are required to construct auth round tripper.
84 func (e *baseExporter) start(ctx context.Context, host component.Host) error {
85 client, err := e.config.ClientConfig.ToClient(ctx, host.GetExtensions(), e.settings)
86 if err != nil {
87 return err
88 }
89 e.client = client
90 return nil
91 }
92
93 func (e *baseExporter) pushTraces(ctx context.Context, td ptrace.Traces) error {
94 tr := ptraceotlp.NewExportRequestFromTraces(td)
95
96 var err error
97 var request []byte
98 switch e.config.Encoding {
99 case EncodingJSON:
100 request, err = tr.MarshalJSON()
101 case EncodingProto:
102 request, err = tr.MarshalProto()
103 default:
104 err = fmt.Errorf("invalid encoding: %s", e.config.Encoding)
105 }
106
107 if err != nil {
108 return consumererror.NewPermanent(err)
109 }
110
111 return e.export(ctx, e.tracesURL, request, e.tracesPartialSuccessHandler)
112 }
113
114 func (e *baseExporter) pushMetrics(ctx context.Context, md pmetric.Metrics) error {
115 tr := pmetricotlp.NewExportRequestFromMetrics(md)
116
117 var err error
118 var request []byte
119 switch e.config.Encoding {
120 case EncodingJSON:
121 request, err = tr.MarshalJSON()
122 case EncodingProto:
123 request, err = tr.MarshalProto()
124 default:
125 err = fmt.Errorf("invalid encoding: %s", e.config.Encoding)
126 }
127
128 if err != nil {
129 return consumererror.NewPermanent(err)
130 }
131 return e.export(ctx, e.metricsURL, request, e.metricsPartialSuccessHandler)
132 }
133
134 func (e *baseExporter) pushLogs(ctx context.Context, ld plog.Logs) error {
135 tr := plogotlp.NewExportRequestFromLogs(ld)
136
137 var err error
138 var request []byte
139 switch e.config.Encoding {
140 case EncodingJSON:
141 request, err = tr.MarshalJSON()
142 case EncodingProto:
143 request, err = tr.MarshalProto()
144 default:
145 err = fmt.Errorf("invalid encoding: %s", e.config.Encoding)
146 }
147
148 if err != nil {
149 return consumererror.NewPermanent(err)
150 }
151
152 return e.export(ctx, e.logsURL, request, e.logsPartialSuccessHandler)
153 }
154
155 func (e *baseExporter) pushProfiles(ctx context.Context, td pprofile.Profiles) error {
156 tr := pprofileotlp.NewExportRequestFromProfiles(td)
157
158 var err error
159 var request []byte
160 switch e.config.Encoding {
161 case EncodingJSON:
162 request, err = tr.MarshalJSON()
163 case EncodingProto:
164 request, err = tr.MarshalProto()
165 default:
166 err = fmt.Errorf("invalid encoding: %s", e.config.Encoding)
167 }
168
169 if err != nil {
170 return consumererror.NewPermanent(err)
171 }
172
173 return e.export(ctx, e.profilesURL, request, e.profilesPartialSuccessHandler)
174 }
175
176 func (e *baseExporter) export(ctx context.Context, url string, request []byte, partialSuccessHandler partialSuccessHandler) error {
177 e.logger.Debug("Preparing to make HTTP request", zap.String("url", url))
178 req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(request))
179 if err != nil {
180 return consumererror.NewPermanent(err)
181 }
182
183 switch e.config.Encoding {
184 case EncodingJSON:
185 req.Header.Set("Content-Type", jsonContentType)
186 case EncodingProto:
187 req.Header.Set("Content-Type", protobufContentType)
188 default:
189 return fmt.Errorf("invalid encoding: %s", e.config.Encoding)
190 }
191
192 req.Header.Set("User-Agent", e.userAgent)
193
194 resp, err := e.client.Do(req)
195 if err != nil {
196 return fmt.Errorf("failed to make an HTTP request: %w", err)
197 }
198
199 defer func() {
200 // Discard any remaining response body when we are done reading.
201 _, _ = io.CopyN(io.Discard, resp.Body, maxHTTPResponseReadBytes)
202 resp.Body.Close()
203 }()
204
205 if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
206 return handlePartialSuccessResponse(resp, partialSuccessHandler)
207 }
208
209 respStatus := readResponseStatus(resp)
210
211 // Format the error message. Use the status if it is present in the response.
212 var errString string
213 var formattedErr error
214 if respStatus != nil {
215 errString = fmt.Sprintf(
216 "error exporting items, request to %s responded with HTTP Status Code %d, Message=%s, Details=%v",
217 url, resp.StatusCode, respStatus.Message, respStatus.Details)
218 } else {
219 errString = fmt.Sprintf(
220 "error exporting items, request to %s responded with HTTP Status Code %d",
221 url, resp.StatusCode)
222 }
223 formattedErr = statusutil.NewStatusFromMsgAndHTTPCode(errString, resp.StatusCode).Err()
224
225 if !isRetryableStatusCode(resp.StatusCode) {
226 return consumererror.NewPermanent(formattedErr)
227 }
228
229 // Check if the server is overwhelmed.
230 // See spec https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#otlphttp-throttling
231 isThrottleError := resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable
232 if isThrottleError {
233 // Use Values to check if the header is present, and if present even if it is empty return ThrottleRetry.
234 values := resp.Header.Values(headerRetryAfter)
235 if len(values) == 0 {
236 return formattedErr
237 }
238 // The value of Retry-After field can be either an HTTP-date or a number of
239 // seconds to delay after the response is received. See https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.3
240 //
241 // Retry-After = HTTP-date / delay-seconds
242 //
243 // First try to parse delay-seconds, since that is what the receiver will send.
244 if seconds, err := strconv.Atoi(values[0]); err == nil {
245 return exporterhelper.NewThrottleRetry(formattedErr, time.Duration(seconds)*time.Second)
246 }
247 if date, err := time.Parse(time.RFC1123, values[0]); err == nil {
248 return exporterhelper.NewThrottleRetry(formattedErr, time.Until(date))
249 }
250 }
251 return formattedErr
252 }
253
254 // Determine if the status code is retryable according to the specification.
255 // For more, see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#failures-1
256 func isRetryableStatusCode(code int) bool {
257 switch code {
258 case http.StatusTooManyRequests:
259 return true
260 case http.StatusBadGateway:
261 return true
262 case http.StatusServiceUnavailable:
263 return true
264 case http.StatusGatewayTimeout:
265 return true
266 default:
267 return false
268 }
269 }
270
271 func readResponseBody(resp *http.Response) ([]byte, error) {
272 if resp.ContentLength == 0 {
273 return nil, nil
274 }
275
276 maxRead := resp.ContentLength
277
278 // if maxRead == -1, the ContentLength header has not been sent, so read up to
279 // the maximum permitted body size. If it is larger than the permitted body
280 // size, still try to read from the body in case the value is an error. If the
281 // body is larger than the maximum size, proto unmarshaling will likely fail.
282 if maxRead == -1 || maxRead > maxHTTPResponseReadBytes {
283 maxRead = maxHTTPResponseReadBytes
284 }
285 protoBytes := make([]byte, maxRead)
286 n, err := io.ReadFull(resp.Body, protoBytes)
287
288 // No bytes read and an EOF error indicates there is no body to read.
289 if n == 0 && (err == nil || errors.Is(err, io.EOF)) {
290 return nil, nil
291 }
292
293 // io.ReadFull will return io.ErrorUnexpectedEOF if the Content-Length header
294 // wasn't set, since we will try to read past the length of the body. If this
295 // is the case, the body will still have the full message in it, so we want to
296 // ignore the error and parse the message.
297 if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
298 return nil, err
299 }
300
301 return protoBytes[:n], nil
302 }
303
304 // Read the response and decode the status.Status from the body.
305 // Returns nil if the response is empty or cannot be decoded.
306 func readResponseStatus(resp *http.Response) *status.Status {
307 var respStatus *status.Status
308 if resp.StatusCode >= 400 && resp.StatusCode <= 599 {
309 // Request failed. Read the body. OTLP spec says:
310 // "Response body for all HTTP 4xx and HTTP 5xx responses MUST be a
311 // Protobuf-encoded Status message that describes the problem."
312 respBytes, err := readResponseBody(resp)
313 if err != nil {
314 return nil
315 }
316
317 // Decode it as Status struct. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#failures
318 respStatus = &status.Status{}
319 err = proto.Unmarshal(respBytes, respStatus)
320 if err != nil {
321 return nil
322 }
323 }
324
325 return respStatus
326 }
327
328 func handlePartialSuccessResponse(resp *http.Response, partialSuccessHandler partialSuccessHandler) error {
329 bodyBytes, err := readResponseBody(resp)
330 if err != nil {
331 return err
332 }
333
334 return partialSuccessHandler(bodyBytes, resp.Header.Get("Content-Type"))
335 }
336
337 type partialSuccessHandler func(bytes []byte, contentType string) error
338
339 func (e *baseExporter) tracesPartialSuccessHandler(protoBytes []byte, contentType string) error {
340 if protoBytes == nil {
341 return nil
342 }
343 exportResponse := ptraceotlp.NewExportResponse()
344 switch contentType {
345 case protobufContentType:
346 err := exportResponse.UnmarshalProto(protoBytes)
347 if err != nil {
348 return fmt.Errorf("error parsing protobuf response: %w", err)
349 }
350 case jsonContentType:
351 err := exportResponse.UnmarshalJSON(protoBytes)
352 if err != nil {
353 return fmt.Errorf("error parsing json response: %w", err)
354 }
355 default:
356 return nil
357 }
358
359 partialSuccess := exportResponse.PartialSuccess()
360 if partialSuccess.ErrorMessage() != "" || partialSuccess.RejectedSpans() != 0 {
361 e.logger.Warn("Partial success response",
362 zap.String("message", exportResponse.PartialSuccess().ErrorMessage()),
363 zap.Int64("dropped_spans", exportResponse.PartialSuccess().RejectedSpans()),
364 )
365 }
366 return nil
367 }
368
369 func (e *baseExporter) metricsPartialSuccessHandler(protoBytes []byte, contentType string) error {
370 if protoBytes == nil {
371 return nil
372 }
373 exportResponse := pmetricotlp.NewExportResponse()
374 switch contentType {
375 case protobufContentType:
376 err := exportResponse.UnmarshalProto(protoBytes)
377 if err != nil {
378 return fmt.Errorf("error parsing protobuf response: %w", err)
379 }
380 case jsonContentType:
381 err := exportResponse.UnmarshalJSON(protoBytes)
382 if err != nil {
383 return fmt.Errorf("error parsing json response: %w", err)
384 }
385 default:
386 return nil
387 }
388
389 partialSuccess := exportResponse.PartialSuccess()
390 if partialSuccess.ErrorMessage() != "" || partialSuccess.RejectedDataPoints() != 0 {
391 e.logger.Warn("Partial success response",
392 zap.String("message", exportResponse.PartialSuccess().ErrorMessage()),
393 zap.Int64("dropped_data_points", exportResponse.PartialSuccess().RejectedDataPoints()),
394 )
395 }
396 return nil
397 }
398
399 func (e *baseExporter) logsPartialSuccessHandler(protoBytes []byte, contentType string) error {
400 if protoBytes == nil {
401 return nil
402 }
403 exportResponse := plogotlp.NewExportResponse()
404 switch contentType {
405 case protobufContentType:
406 err := exportResponse.UnmarshalProto(protoBytes)
407 if err != nil {
408 return fmt.Errorf("error parsing protobuf response: %w", err)
409 }
410 case jsonContentType:
411 err := exportResponse.UnmarshalJSON(protoBytes)
412 if err != nil {
413 return fmt.Errorf("error parsing json response: %w", err)
414 }
415 default:
416 return nil
417 }
418
419 partialSuccess := exportResponse.PartialSuccess()
420 if partialSuccess.ErrorMessage() != "" || partialSuccess.RejectedLogRecords() != 0 {
421 e.logger.Warn("Partial success response",
422 zap.String("message", exportResponse.PartialSuccess().ErrorMessage()),
423 zap.Int64("dropped_log_records", exportResponse.PartialSuccess().RejectedLogRecords()),
424 )
425 }
426 return nil
427 }
428
429 func (e *baseExporter) profilesPartialSuccessHandler(protoBytes []byte, contentType string) error {
430 if protoBytes == nil {
431 return nil
432 }
433 exportResponse := pprofileotlp.NewExportResponse()
434 switch contentType {
435 case protobufContentType:
436 err := exportResponse.UnmarshalProto(protoBytes)
437 if err != nil {
438 return fmt.Errorf("error parsing protobuf response: %w", err)
439 }
440 case jsonContentType:
441 err := exportResponse.UnmarshalJSON(protoBytes)
442 if err != nil {
443 return fmt.Errorf("error parsing json response: %w", err)
444 }
445 default:
446 return nil
447 }
448
449 partialSuccess := exportResponse.PartialSuccess()
450 if partialSuccess.ErrorMessage() != "" || partialSuccess.RejectedProfiles() != 0 {
451 e.logger.Warn("Partial success response",
452 zap.String("message", exportResponse.PartialSuccess().ErrorMessage()),
453 zap.Int64("dropped_samples", exportResponse.PartialSuccess().RejectedProfiles()),
454 )
455 }
456 return nil
457 }