Debian Codegraph @

instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo/mongo.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelmongo // import "go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo"
5
6 import (
7 "context"
8 "errors"
9 "net"
10 "strconv"
11 "sync"
12
13 "go.mongodb.org/mongo-driver/v2/bson"
14 "go.mongodb.org/mongo-driver/v2/event"
15 "go.opentelemetry.io/otel"
16 "go.opentelemetry.io/otel/attribute"
17 "go.opentelemetry.io/otel/codes"
18 "go.opentelemetry.io/otel/metric"
19 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
20 "go.opentelemetry.io/otel/semconv/v1.40.0/dbconv"
21 "go.opentelemetry.io/otel/trace"
22 )
23
24 type spanKey struct {
25 ConnectionID string
26 RequestID int64
27 }
28
29 type monitor struct {
30 ClientOperationDuration *dbconv.ClientOperationDuration
31
32 sync.Mutex
33 spans map[spanKey]trace.Span
34 cfg config
35 }
36
37 func (m *monitor) Started(ctx context.Context, evt *event.CommandStartedEvent) {
38 hostname, port := peerInfo(evt.ConnectionID)
39
40 attrs := []attribute.KeyValue{
41 semconv.DBSystemNameMongoDB,
42 semconv.DBOperationName(evt.CommandName),
43 semconv.DBNamespace(evt.DatabaseName),
44 semconv.NetworkPeerAddress(hostname),
45 semconv.NetworkPeerPort(port),
46 semconv.NetworkTransportTCP,
47 }
48 if !m.cfg.CommandAttributeDisabled {
49 attrs = append(attrs, semconv.DBQueryText(sanitizeCommand(evt.Command)))
50 }
51
52 collection, err := extractCollection(evt)
53 if err == nil && collection != "" {
54 attrs = append(attrs, semconv.DBCollectionName(collection))
55 }
56
57 spanName := m.cfg.SpanNameFormatter(evt)
58
59 opts := []trace.SpanStartOption{
60 trace.WithSpanKind(trace.SpanKindClient),
61 trace.WithAttributes(attrs...),
62 }
63 _, span := m.cfg.Tracer.Start(ctx, spanName, opts...)
64 key := spanKey{
65 ConnectionID: evt.ConnectionID,
66 RequestID: evt.RequestID,
67 }
68 m.Lock()
69 m.spans[key] = span
70 m.Unlock()
71 }
72
73 func (m *monitor) Succeeded(ctx context.Context, evt *event.CommandSucceededEvent) {
74 m.Finished(&evt.CommandFinishedEvent, nil)
75 if m.ClientOperationDuration == nil {
76 return
77 }
78
79 hostname, port := peerInfo(evt.ConnectionID)
80 attrs := attribute.NewSet(
81 semconv.DBSystemNameMongoDB,
82 // No need to add semconv.DBSystemMongoDB, it will be added by metrics recorder.
83 semconv.DBOperationName(evt.CommandName),
84 semconv.DBNamespace(evt.DatabaseName),
85 semconv.NetworkPeerAddress(hostname),
86 semconv.NetworkPeerPort(port),
87 semconv.NetworkTransportTCP,
88 // `db.response.status_code` is excluded for succeeded events.
89 // Succeeded processes an [go.mongodb.org/mongo-driver/v2/event.CommandSucceededEvent] for OTel,
90 // including collecting metrics. The status code metric is excluded since MongoDB server indicates
91 // a successful operation with {ok: 1}, which doesn't map to a traditional status code.
92 )
93 // TODO: db.query.text attribute is currently disabled by default.
94 // Because event does not provide the query text directly.
95 // command := m.extractCommand(evt)
96 // attrs = append(attrs, semconv.DBQueryText(sanitizeCommand(evt.Command)))
97
98 m.ClientOperationDuration.RecordSet(
99 ctx,
100 evt.Duration.Seconds(),
101 attrs,
102 )
103 }
104
105 func (m *monitor) Failed(ctx context.Context, evt *event.CommandFailedEvent) {
106 m.Finished(&evt.CommandFinishedEvent, evt.Failure)
107 if m.ClientOperationDuration == nil {
108 return
109 }
110
111 hostname, port := peerInfo(evt.ConnectionID)
112 attrs := attribute.NewSet(
113 semconv.DBSystemNameMongoDB,
114 semconv.DBOperationName(evt.CommandName),
115 semconv.NetworkPeerAddress(hostname),
116 semconv.NetworkPeerPort(port),
117 semconv.NetworkTransportTCP,
118 // TODO: The status code should not be static, but reflect server behavior.
119 // Assert the error as [go.mongodb.org/mongo-driver/v2/x/mongo/driver.Error] and pull the code from there.
120 // ref. https://jira.mongodb.org/browse/GODRIVER-3690
121 semconv.ErrorType(evt.Failure),
122 )
123 // TODO: db.query.text attribute is currently disabled by default.
124 // Because event does not provide the query text directly.
125 // command := m.extractCommand(evt)
126 // attrs = append(attrs, semconv.DBQueryText(sanitizeCommand(evt.Command)))
127
128 m.ClientOperationDuration.RecordSet(
129 ctx,
130 evt.Duration.Seconds(),
131 attrs,
132 )
133 }
134
135 func (m *monitor) Finished(evt *event.CommandFinishedEvent, err error) {
136 key := spanKey{
137 ConnectionID: evt.ConnectionID,
138 RequestID: evt.RequestID,
139 }
140 m.Lock()
141 span, ok := m.spans[key]
142 if ok {
143 delete(m.spans, key)
144 }
145 m.Unlock()
146 if !ok {
147 return
148 }
149
150 if err != nil {
151 span.SetStatus(codes.Error, err.Error())
152 }
153
154 span.End()
155 }
156
157 // TODO sanitize values where possible, then re-enable `db.statement` span attributes default.
158 // TODO limit maximum size.
159 func sanitizeCommand(command bson.Raw) string {
160 b, _ := bson.MarshalExtJSON(command, false, false)
161 return string(b)
162 }
163
164 // extractCollection extracts the collection for the given mongodb command event.
165 // For CRUD operations, this is the first key/value string pair in the bson
166 // document where key == "<operation>" (e.g. key == "insert").
167 // For database meta-level operations, such a key may not exist.
168 // This function returns the collection name or an error if no collection can be determined.
169 func extractCollection(evt *event.CommandStartedEvent) (string, error) {
170 elt, err := evt.Command.IndexErr(0)
171 if err != nil {
172 return "", err
173 }
174 if key, err := elt.KeyErr(); err == nil && key == evt.CommandName {
175 var v bson.RawValue
176 if v, err = elt.ValueErr(); err != nil || v.Type != bson.TypeString {
177 return "", err
178 }
179 return v.StringValue(), nil
180 }
181 return "", errors.New("collection name not found")
182 }
183
184 // NewMonitor creates a new mongodb event CommandMonitor.
185 func NewMonitor(opts ...Option) *event.CommandMonitor {
186 cfg := newConfig(opts...)
187 var clientOperationDuration *dbconv.ClientOperationDuration
188 operationDuration, err := dbconv.NewClientOperationDuration(
189 cfg.Meter,
190 metric.WithExplicitBucketBoundaries(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10),
191 )
192 if err != nil {
193 clientOperationDuration = nil
194 otel.Handle(err)
195 } else {
196 clientOperationDuration = &operationDuration
197 }
198
199 m := &monitor{
200 spans: make(map[spanKey]trace.Span),
201 cfg: cfg,
202
203 ClientOperationDuration: clientOperationDuration,
204 }
205 return &event.CommandMonitor{
206 Started: m.Started,
207 Succeeded: m.Succeeded,
208 Failed: m.Failed,
209 }
210 }
211
212 // peerInfo will parse the hostname and port from the mongo connection ID.
213 func peerInfo(connectionID string) (hostname string, port int) {
214 defaultMongoPort := 27017
215 hostname, portStr, err := net.SplitHostPort(connectionID)
216 if err != nil {
217 // If parsing fails, assume default MongoDB port and return the entire ConnectionID as hostname
218 hostname = connectionID
219 port = defaultMongoPort
220 return hostname, port
221 }
222
223 port, err = strconv.Atoi(portStr)
224 if err != nil || port < 1 {
225 // If port parsing fails, fallback to default MongoDB port
226 port = defaultMongoPort
227 }
228
229 return hostname, port
230 }