-
Notifications
You must be signed in to change notification settings - Fork 415
/
conn.go
265 lines (241 loc) · 8.52 KB
/
conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
package sql // import "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"
import (
"context"
"database/sql/driver"
"fmt"
"math"
"time"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
)
var _ driver.Conn = (*tracedConn)(nil)
type queryType string
const (
queryTypeConnect queryType = "Connect"
queryTypeQuery = "Query"
queryTypePing = "Ping"
queryTypePrepare = "Prepare"
queryTypeExec = "Exec"
queryTypeBegin = "Begin"
queryTypeClose = "Close"
queryTypeCommit = "Commit"
queryTypeRollback = "Rollback"
)
type tracedConn struct {
driver.Conn
*traceParams
}
func (tc *tracedConn) BeginTx(ctx context.Context, opts driver.TxOptions) (tx driver.Tx, err error) {
start := time.Now()
if connBeginTx, ok := tc.Conn.(driver.ConnBeginTx); ok {
tx, err = connBeginTx.BeginTx(ctx, opts)
tc.tryTrace(ctx, queryTypeBegin, "", start, err)
if err != nil {
return nil, err
}
return &tracedTx{tx, tc.traceParams, ctx}, nil
}
tx, err = tc.Conn.Begin()
tc.tryTrace(ctx, queryTypeBegin, "", start, err)
if err != nil {
return nil, err
}
return &tracedTx{tx, tc.traceParams, ctx}, nil
}
func (tc *tracedConn) PrepareContext(ctx context.Context, query string) (stmt driver.Stmt, err error) {
start := time.Now()
if connPrepareCtx, ok := tc.Conn.(driver.ConnPrepareContext); ok {
cquery, spanID := tc.withSQLCommentsInjected(ctx, query, true)
stmt, err := connPrepareCtx.PrepareContext(ctx, cquery)
if spanID > 0 {
tc.tryTrace(ctx, queryTypePrepare, query, start, err, tracer.WithSpanID(spanID))
} else {
tc.tryTrace(ctx, queryTypePrepare, query, start, err)
}
if err != nil {
return nil, err
}
return &tracedStmt{Stmt: stmt, traceParams: tc.traceParams, ctx: ctx, query: query}, nil
}
cquery, spanID := tc.withSQLCommentsInjected(ctx, query, true)
stmt, err = tc.Prepare(cquery)
if spanID > 0 {
tc.tryTrace(ctx, queryTypePrepare, query, start, err, tracer.WithSpanID(spanID))
} else {
tc.tryTrace(ctx, queryTypePrepare, query, start, err)
}
if err != nil {
return nil, err
}
return &tracedStmt{Stmt: stmt, traceParams: tc.traceParams, ctx: ctx, query: query}, nil
}
func (tc *tracedConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (r driver.Result, err error) {
start := time.Now()
if execContext, ok := tc.Conn.(driver.ExecerContext); ok {
cquery, spanID := tc.withSQLCommentsInjected(ctx, query, false)
r, err := execContext.ExecContext(ctx, cquery, args)
if spanID > 0 {
tc.tryTrace(ctx, queryTypeExec, query, start, err, tracer.WithSpanID(spanID))
} else {
tc.tryTrace(ctx, queryTypeExec, query, start, err)
}
return r, err
}
if execer, ok := tc.Conn.(driver.Execer); ok {
dargs, err := namedValueToValue(args)
if err != nil {
return nil, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
cquery, spanID := tc.withSQLCommentsInjected(ctx, query, false)
r, err = execer.Exec(cquery, dargs)
if spanID > 0 {
tc.tryTrace(ctx, queryTypeExec, query, start, err, tracer.WithSpanID(spanID))
} else {
tc.tryTrace(ctx, queryTypeExec, query, start, err)
}
return r, err
}
return nil, driver.ErrSkip
}
// tracedConn has a Ping method in order to implement the pinger interface
func (tc *tracedConn) Ping(ctx context.Context) (err error) {
start := time.Now()
if pinger, ok := tc.Conn.(driver.Pinger); ok {
err = pinger.Ping(ctx)
tc.tryTrace(ctx, queryTypePing, "", start, err)
if err != nil {
return err
}
}
return err
}
func (tc *tracedConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (rows driver.Rows, err error) {
start := time.Now()
if queryerContext, ok := tc.Conn.(driver.QueryerContext); ok {
cquery, spanID := tc.withSQLCommentsInjected(ctx, query, false)
rows, err := queryerContext.QueryContext(ctx, cquery, args)
if spanID > 0 {
tc.tryTrace(ctx, queryTypeQuery, query, start, err, tracer.WithSpanID(spanID))
} else {
tc.tryTrace(ctx, queryTypeQuery, query, start, err)
}
return rows, err
}
if queryer, ok := tc.Conn.(driver.Queryer); ok {
dargs, err := namedValueToValue(args)
if err != nil {
return nil, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
cquery, spanID := tc.withSQLCommentsInjected(ctx, query, true)
rows, err = queryer.Query(cquery, dargs)
if spanID > 0 {
tc.tryTrace(ctx, queryTypeQuery, query, start, err, tracer.WithSpanID(spanID))
} else {
tc.tryTrace(ctx, queryTypeQuery, query, start, err)
}
return rows, err
}
return nil, driver.ErrSkip
}
func (tc *tracedConn) CheckNamedValue(value *driver.NamedValue) error {
if checker, ok := tc.Conn.(driver.NamedValueChecker); ok {
return checker.CheckNamedValue(value)
}
return driver.ErrSkip
}
var _ driver.SessionResetter = (*tracedConn)(nil)
// ResetSession implements driver.SessionResetter
func (tc *tracedConn) ResetSession(ctx context.Context) error {
if resetter, ok := tc.Conn.(driver.SessionResetter); ok {
return resetter.ResetSession(ctx)
}
// If driver doesn't implement driver.SessionResetter there's nothing to do
return nil
}
// traceParams stores all information related to tracing the driver.Conn
type traceParams struct {
cfg *config
driverName string
meta map[string]string
}
type contextKey int
const spanTagsKey contextKey = 0 // map[string]string
// WithSpanTags creates a new context containing the given set of tags. They will be added
// to any query created with the returned context.
func WithSpanTags(ctx context.Context, tags map[string]string) context.Context {
return context.WithValue(ctx, spanTagsKey, tags)
}
// withSQLCommentsInjected will return the query with sql comments injected according to the comment injection mode along
// with a span id injected into sql comments. If a span ID is returned, the caller should make sure to use it when creating
// the span following the traced database call.
func (tp *traceParams) withSQLCommentsInjected(ctx context.Context, query string, discardDynamicTags bool) (cquery string, injectedSpanID uint64) {
// The sql span only gets created after the call to the database because we need to be able to skip spans
// when a driver returns driver.ErrSkip. In order to work with those constraints, the parent span is used
// during SQL comment injection and a new span ID is generated for the sql span and used later when/if the span
// gets created.
var spanContext ddtrace.SpanContext
if span, ok := tracer.SpanFromContext(ctx); ok {
spanContext = span.Context()
}
sqlCommentCarrier := tracer.NewSQLCommentCarrier(tracer.SQLCommentWithDynamicTagsDiscarded(discardDynamicTags))
err := tracer.Inject(spanContext, sqlCommentCarrier)
if err != nil {
// this should never happen
log.Warn("contrib/database/sql: failed to inject query comments: %v", err)
}
return sqlCommentCarrier.CommentQuery(query)
}
// tryTrace will create a span using the given arguments, but will act as a no-op when err is driver.ErrSkip.
func (tp *traceParams) tryTrace(ctx context.Context, qtype queryType, query string, startTime time.Time, err error, spanOpts ...ddtrace.StartSpanOption) {
if err == driver.ErrSkip {
// Not a user error: driver is telling sql package that an
// optional interface method is not implemented. There is
// nothing to trace here.
// See: https://github.com/DataDog/dd-trace-go/issues/270
return
}
if _, exists := tracer.SpanFromContext(ctx); tp.cfg.childSpansOnly && !exists {
return
}
name := fmt.Sprintf("%s.query", tp.driverName)
opts := append(spanOpts,
tracer.ServiceName(tp.cfg.serviceName),
tracer.SpanType(ext.SpanTypeSQL),
tracer.StartTime(startTime),
)
if !math.IsNaN(tp.cfg.analyticsRate) {
opts = append(opts, tracer.Tag(ext.EventSampleRate, tp.cfg.analyticsRate))
}
span, _ := tracer.StartSpanFromContext(ctx, name, opts...)
resource := string(qtype)
if query != "" {
resource = query
}
span.SetTag("sql.query_type", string(qtype))
span.SetTag(ext.ResourceName, resource)
for k, v := range tp.meta {
span.SetTag(k, v)
}
if meta, ok := ctx.Value(spanTagsKey).(map[string]string); ok {
for k, v := range meta {
span.SetTag(k, v)
}
}
span.Finish(tracer.WithError(err))
}