Debian Codegraph @

exporters/otlp/otlptrace/exporter.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otlptrace // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "sync"
11
12 "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform"
13 tracesdk "go.opentelemetry.io/otel/sdk/trace"
14 )
15
16 var errAlreadyStarted = errors.New("already started")
17
18 // Exporter exports trace data in the OTLP wire format.
19 type Exporter struct {
20 client Client
21
22 mu sync.RWMutex
23 started bool
24
25 startOnce sync.Once
26 stopOnce sync.Once
27 }
28
29 // ExportSpans exports a batch of spans.
30 func (e *Exporter) ExportSpans(ctx context.Context, ss []tracesdk.ReadOnlySpan) error {
31 protoSpans := tracetransform.Spans(ss)
32 if len(protoSpans) == 0 {
33 return nil
34 }
35
36 err := e.client.UploadTraces(ctx, protoSpans)
37 if err != nil {
38 return fmt.Errorf("traces export: %w", err)
39 }
40 return nil
41 }
42
43 // Start establishes a connection to the receiving endpoint.
44 func (e *Exporter) Start(ctx context.Context) error {
45 err := errAlreadyStarted
46 e.startOnce.Do(func() {
47 e.mu.Lock()
48 e.started = true
49 e.mu.Unlock()
50 err = e.client.Start(ctx)
51 })
52
53 return err
54 }
55
56 // Shutdown flushes all exports and closes all connections to the receiving endpoint.
57 func (e *Exporter) Shutdown(ctx context.Context) error {
58 e.mu.RLock()
59 started := e.started
60 e.mu.RUnlock()
61
62 if !started {
63 return nil
64 }
65
66 var err error
67
68 e.stopOnce.Do(func() {
69 err = e.client.Stop(ctx)
70 e.mu.Lock()
71 e.started = false
72 e.mu.Unlock()
73 })
74
75 return err
76 }
77
78 var _ tracesdk.SpanExporter = (*Exporter)(nil)
79
80 // New constructs a new Exporter and starts it.
81 func New(ctx context.Context, client Client) (*Exporter, error) {
82 exp := NewUnstarted(client)
83 if err := exp.Start(ctx); err != nil {
84 return nil, err
85 }
86 return exp, nil
87 }
88
89 // NewUnstarted constructs a new Exporter and does not start it.
90 func NewUnstarted(client Client) *Exporter {
91 return &Exporter{
92 client: client,
93 }
94 }
95
96 // MarshalLog is the marshaling function used by the logging system to represent this Exporter.
97 func (e *Exporter) MarshalLog() any {
98 return struct {
99 Type string
100 Client Client
101 }{
102 Type: "otlptrace",
103 Client: e.client,
104 }
105 }