forked from opencensus-integrations/ocsql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
741 lines (650 loc) · 17.5 KB
/
driver.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
package ocsql
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
"strconv"
"sync"
"go.opencensus.io/trace"
)
var (
regMu sync.Mutex
attrMissingContext = trace.StringAttribute("ocsql.warning", "missing upstream context")
attrDeprecated = trace.StringAttribute("ocsql.warning", "database driver uses deprecated features")
)
// Register initializes and registers our ocsql wrapped database driver
// identified by its driverName and using provided TraceOptions. On success it
// returns the generated driverName to use when calling sql.Open.
// It is possible to register multiple wrappers for the same database driver if
// needing different TraceOptions for different connections.
func Register(driverName string, options ...TraceOption) (string, error) {
// retrieve the driver implementation we need to wrap with instrumentation
db, err := sql.Open(driverName, "")
if err != nil {
return "", err
}
dri := db.Driver()
if err = db.Close(); err != nil {
return "", err
}
regMu.Lock()
defer regMu.Unlock()
// Since we might want to register multiple ocsql drivers to have different
// TraceOptions, but potentially the same underlying database driver, we
// cycle through to find available driver names.
driverName = driverName + "-ocsql-"
for i := int64(0); i < 100; i++ {
var (
found = false
regName = driverName + strconv.FormatInt(i, 10)
)
for _, name := range sql.Drivers() {
if name == regName {
found = true
}
}
if !found {
sql.Register(regName, Wrap(dri, options...))
return regName, nil
}
}
return "", errors.New("unable to register driver, all slots have been taken")
}
// Wrap takes a SQL driver and wraps it with OpenCensus instrumentation.
func Wrap(d driver.Driver, options ...TraceOption) driver.Driver {
o := TraceOptions{}
for _, option := range options {
option(&o)
}
if o.QueryParams && !o.Query {
o.QueryParams = false
}
return ocDriver{parent: d, options: o}
}
// ocDriver implements driver.Driver
type ocDriver struct {
parent driver.Driver
options TraceOptions
}
func (d ocDriver) Open(name string) (driver.Conn, error) {
c, err := d.parent.Open(name)
if err != nil {
return nil, err
}
return &ocConn{parent: c, options: d.options}, nil
}
// ocConn implements driver.Conn
type ocConn struct {
parent driver.Conn
options TraceOptions
}
func (c ocConn) Ping(ctx context.Context) (err error) {
if c.options.Ping && (c.options.AllowRoot || trace.FromContext(ctx) != nil) {
var span *trace.Span
ctx, span = trace.StartSpan(ctx, "sql:ping")
span.AddAttributes(c.options.DefaultAttributes...)
defer func() {
if err != nil {
span.SetStatus(trace.Status{
Code: trace.StatusCodeUnavailable,
Message: err.Error(),
})
} else {
span.SetStatus(trace.Status{Code: trace.StatusCodeOK})
}
span.End()
}()
}
if pinger, ok := c.parent.(driver.Pinger); ok {
err = pinger.Ping(ctx)
}
return
}
func (c ocConn) Exec(query string, args []driver.Value) (res driver.Result, err error) {
if exec, ok := c.parent.(driver.Execer); ok {
if !c.options.AllowRoot {
return exec.Exec(query, args)
}
ctx, span := trace.StartSpan(context.Background(), "sql:exec")
attrs := append(
c.options.DefaultAttributes,
attrDeprecated,
trace.StringAttribute(
"ocsql.deprecated", "driver does not support ExecerContext",
),
)
if c.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", query))
if c.options.QueryParams {
attrs = append(attrs, paramsAttr(args)...)
}
}
span.AddAttributes(attrs...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
if res, err = exec.Exec(query, args); err != nil {
return nil, err
}
return ocResult{parent: res, ctx: ctx, options: c.options}, nil
}
return nil, driver.ErrSkip
}
func (c ocConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (res driver.Result, err error) {
if execCtx, ok := c.parent.(driver.ExecerContext); ok {
parentSpan := trace.FromContext(ctx)
if !c.options.AllowRoot && parentSpan == nil {
return execCtx.ExecContext(ctx, query, args)
}
var span *trace.Span
if parentSpan == nil {
ctx, span = trace.StartSpan(ctx, "sql:exec")
} else {
_, span = trace.StartSpan(ctx, "sql:exec")
}
attrs := c.options.DefaultAttributes
if c.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", query))
if c.options.QueryParams {
attrs = append(attrs, namedParamsAttr(args)...)
}
}
span.AddAttributes(attrs...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
if res, err = execCtx.ExecContext(ctx, query, args); err != nil {
return nil, err
}
return ocResult{parent: res, ctx: ctx, options: c.options}, nil
}
return nil, driver.ErrSkip
}
func (c ocConn) Query(query string, args []driver.Value) (rows driver.Rows, err error) {
if queryer, ok := c.parent.(driver.Queryer); ok {
if !c.options.AllowRoot {
return queryer.Query(query, args)
}
ctx, span := trace.StartSpan(context.Background(), "sql:query")
attrs := append(
c.options.DefaultAttributes,
attrDeprecated,
trace.StringAttribute(
"ocsql.deprecated", "driver does not support QueryerContext",
),
)
if c.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", query))
if c.options.QueryParams {
attrs = append(attrs, paramsAttr(args)...)
}
}
span.AddAttributes(attrs...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
rows, err = queryer.Query(query, args)
if err != nil {
return nil, err
}
return ocRows{parent: rows, ctx: ctx, options: c.options}, nil
}
return nil, driver.ErrSkip
}
func (c ocConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (rows driver.Rows, err error) {
if queryerCtx, ok := c.parent.(driver.QueryerContext); ok {
parentSpan := trace.FromContext(ctx)
if !c.options.AllowRoot && parentSpan == nil {
return queryerCtx.QueryContext(ctx, query, args)
}
var span *trace.Span
if parentSpan == nil {
ctx, span = trace.StartSpan(ctx, "sql:query")
} else {
_, span = trace.StartSpan(ctx, "sql:query")
}
attrs := c.options.DefaultAttributes
if c.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", query))
if c.options.QueryParams {
attrs = append(attrs, namedParamsAttr(args)...)
}
}
span.AddAttributes(attrs...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
rows, err = queryerCtx.QueryContext(ctx, query, args)
if err != nil {
return nil, err
}
return ocRows{parent: rows, ctx: ctx, options: c.options}, nil
}
return nil, driver.ErrSkip
}
func (c ocConn) Prepare(query string) (stmt driver.Stmt, err error) {
if c.options.AllowRoot {
_, span := trace.StartSpan(context.Background(), "sql:prepare")
attrs := append(c.options.DefaultAttributes, attrMissingContext)
if c.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", query))
}
span.AddAttributes(attrs...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
}
stmt, err = c.parent.Prepare(query)
if err != nil {
return nil, err
}
stmt = wrapStmt(stmt, query, c.options)
return
}
func (c *ocConn) Close() error {
return c.parent.Close()
}
func (c *ocConn) Begin() (driver.Tx, error) {
return c.BeginTx(context.TODO(), driver.TxOptions{})
}
func (c *ocConn) PrepareContext(ctx context.Context, query string) (stmt driver.Stmt, err error) {
var span *trace.Span
attrs := c.options.DefaultAttributes
if c.options.AllowRoot || trace.FromContext(ctx) != nil {
ctx, span = trace.StartSpan(ctx, "sql:prepare")
if c.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", query))
}
defer func() {
setSpanStatus(span, err)
span.End()
}()
}
if prepCtx, ok := c.parent.(driver.ConnPrepareContext); ok {
stmt, err = prepCtx.PrepareContext(ctx, query)
} else {
if span != nil {
attrs = append(attrs, attrMissingContext)
}
stmt, err = c.parent.Prepare(query)
}
span.AddAttributes(attrs...)
if err != nil {
return nil, err
}
stmt = wrapStmt(stmt, query, c.options)
return
}
func (c *ocConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
if !c.options.AllowRoot && trace.FromContext(ctx) == nil {
if connBeginTx, ok := c.parent.(driver.ConnBeginTx); ok {
return connBeginTx.BeginTx(ctx, opts)
}
return c.parent.Begin()
}
var span *trace.Span
attrs := c.options.DefaultAttributes
defer span.AddAttributes(attrs...)
if ctx == nil || ctx == context.TODO() {
ctx = context.Background()
_, span = trace.StartSpan(ctx, "sql:begin_transaction")
attrs = append(attrs, attrMissingContext)
} else {
_, span = trace.StartSpan(ctx, "sql:begin_transaction")
}
defer span.End()
if connBeginTx, ok := c.parent.(driver.ConnBeginTx); ok {
tx, err := connBeginTx.BeginTx(ctx, opts)
setSpanStatus(span, err)
if err != nil {
return nil, err
}
return ocTx{parent: tx, ctx: ctx}, nil
}
attrs = append(
attrs,
attrDeprecated,
trace.StringAttribute(
"ocsql.deprecated", "driver does not support ConnBeginTx",
),
)
tx, err := c.parent.Begin()
setSpanStatus(span, err)
if err != nil {
return nil, err
}
return ocTx{parent: tx, ctx: ctx}, nil
}
// ocResult implements driver.Result
type ocResult struct {
parent driver.Result
ctx context.Context
options TraceOptions
}
func (r ocResult) LastInsertId() (id int64, err error) {
if r.options.LastInsertID {
_, span := trace.StartSpan(r.ctx, "sql:last_insert_id")
span.AddAttributes(r.options.DefaultAttributes...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
}
id, err = r.parent.LastInsertId()
return
}
func (r ocResult) RowsAffected() (cnt int64, err error) {
if r.options.RowsAffected {
_, span := trace.StartSpan(r.ctx, "sql:rows_affected")
span.AddAttributes(r.options.DefaultAttributes...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
}
cnt, err = r.parent.RowsAffected()
return
}
// ocStmt implements driver.Stmt
type ocStmt struct {
parent driver.Stmt
query string
options TraceOptions
}
func (s ocStmt) Exec(args []driver.Value) (res driver.Result, err error) {
if !s.options.AllowRoot {
return s.parent.Exec(args)
}
ctx, span := trace.StartSpan(context.Background(), "sql:exec")
attrs := append(
s.options.DefaultAttributes,
attrDeprecated,
trace.StringAttribute(
"ocsql.deprecated", "driver does not support StmtExecContext",
),
)
if s.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", s.query))
if s.options.QueryParams {
attrs = append(attrs, paramsAttr(args)...)
}
}
span.AddAttributes(attrs...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
res, err = s.parent.Exec(args)
if err != nil {
return nil, err
}
res, err = ocResult{parent: res, ctx: ctx, options: s.options}, nil
return
}
func (s ocStmt) Close() error {
return s.parent.Close()
}
func (s ocStmt) NumInput() int {
return s.parent.NumInput()
}
func (s ocStmt) Query(args []driver.Value) (rows driver.Rows, err error) {
if !s.options.AllowRoot {
return s.parent.Query(args)
}
ctx, span := trace.StartSpan(context.Background(), "sql:query")
attrs := append(
s.options.DefaultAttributes,
attrDeprecated,
trace.StringAttribute(
"ocsql.deprecated", "driver does not support StmtQueryContext",
),
)
if s.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", s.query))
if s.options.QueryParams {
attrs = append(attrs, paramsAttr(args)...)
}
}
span.AddAttributes(attrs...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
rows, err = s.parent.Query(args)
if err != nil {
return nil, err
}
rows, err = ocRows{parent: rows, ctx: ctx, options: s.options}, nil
return
}
func (s ocStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (res driver.Result, err error) {
parentSpan := trace.FromContext(ctx)
if !s.options.AllowRoot && parentSpan == nil {
// we already tested driver to implement StmtExecContext
return s.parent.(driver.StmtExecContext).ExecContext(ctx, args)
}
var span *trace.Span
if parentSpan == nil {
ctx, span = trace.StartSpan(ctx, "sql:exec")
} else {
_, span = trace.StartSpan(ctx, "sql:exec")
}
attrs := s.options.DefaultAttributes
if s.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", s.query))
if s.options.QueryParams {
attrs = append(attrs, namedParamsAttr(args)...)
}
}
span.AddAttributes(attrs...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
// we already tested driver to implement StmtExecContext
execContext := s.parent.(driver.StmtExecContext)
res, err = execContext.ExecContext(ctx, args)
if err != nil {
return nil, err
}
res, err = ocResult{parent: res, ctx: ctx, options: s.options}, nil
return
}
func (s ocStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (rows driver.Rows, err error) {
parentSpan := trace.FromContext(ctx)
if !s.options.AllowRoot && parentSpan == nil {
// we already tested driver to implement StmtQueryContext
return s.parent.(driver.StmtQueryContext).QueryContext(ctx, args)
}
var span *trace.Span
if parentSpan == nil {
ctx, span = trace.StartSpan(ctx, "sql:query")
} else {
_, span = trace.StartSpan(ctx, "sql:query")
}
attrs := s.options.DefaultAttributes
if s.options.Query {
attrs = append(attrs, trace.StringAttribute("sql.query", s.query))
if s.options.QueryParams {
attrs = append(attrs, namedParamsAttr(args)...)
}
}
span.AddAttributes(attrs...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
// we already tested driver to implement StmtQueryContext
queryContext := s.parent.(driver.StmtQueryContext)
rows, err = queryContext.QueryContext(ctx, args)
if err != nil {
return nil, err
}
rows, err = ocRows{parent: rows, ctx: ctx, options: s.options}, nil
return
}
// ocRows implements driver.Rows.
type ocRows struct {
parent driver.Rows
ctx context.Context
options TraceOptions
}
func (r ocRows) Columns() []string {
return r.parent.Columns()
}
func (r ocRows) Close() (err error) {
if r.options.RowsClose {
_, span := trace.StartSpan(r.ctx, "sql:rows_close")
span.AddAttributes(r.options.DefaultAttributes...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
}
err = r.parent.Close()
return
}
func (r ocRows) Next(dest []driver.Value) (err error) {
if r.options.RowsNext {
_, span := trace.StartSpan(r.ctx, "sql:rows_next")
span.AddAttributes(r.options.DefaultAttributes...)
defer func() {
if err == io.EOF {
// not an error; expected to happen during iteration
setSpanStatus(span, nil)
} else {
setSpanStatus(span, err)
}
span.End()
}()
}
err = r.parent.Next(dest)
return
}
// ocTx implemens driver.Tx
type ocTx struct {
parent driver.Tx
ctx context.Context
options TraceOptions
}
func (t ocTx) Commit() (err error) {
_, span := trace.StartSpan(t.ctx, "sql:commit")
span.AddAttributes(t.options.DefaultAttributes...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
err = t.parent.Commit()
return
}
func (t ocTx) Rollback() (err error) {
_, span := trace.StartSpan(t.ctx, "sql:rollback")
span.AddAttributes(t.options.DefaultAttributes...)
defer func() {
setSpanStatus(span, err)
span.End()
}()
err = t.parent.Rollback()
return
}
func wrapStmt(stmt driver.Stmt, query string, options TraceOptions) driver.Stmt {
s := ocStmt{parent: stmt, query: query, options: options}
_, hasExeCtx := stmt.(driver.StmtExecContext)
_, hasQryCtx := stmt.(driver.StmtQueryContext)
switch {
case !hasExeCtx && !hasQryCtx:
return struct {
driver.Stmt
}{s}
case !hasExeCtx && hasQryCtx:
return struct {
driver.Stmt
driver.StmtQueryContext
}{s, s}
case hasExeCtx && !hasQryCtx:
return struct {
driver.Stmt
driver.StmtExecContext
}{s, s}
case hasExeCtx && hasQryCtx:
return struct {
driver.Stmt
driver.StmtExecContext
driver.StmtQueryContext
}{s, s, s}
}
panic("unreachable")
}
func paramsAttr(args []driver.Value) []trace.Attribute {
attrs := make([]trace.Attribute, 0, len(args))
for i, arg := range args {
key := "sql.arg" + strconv.Itoa(i)
attrs = append(attrs, argToAttr(key, arg))
}
return attrs
}
func namedParamsAttr(args []driver.NamedValue) []trace.Attribute {
attrs := make([]trace.Attribute, 0, len(args))
for _, arg := range args {
var key string
if arg.Name != "" {
key = arg.Name
} else {
key = "sql.arg." + strconv.Itoa(arg.Ordinal)
}
attrs = append(attrs, argToAttr(key, arg.Value))
}
return attrs
}
func argToAttr(key string, val interface{}) trace.Attribute {
switch v := val.(type) {
case nil:
return trace.StringAttribute(key, "")
case int64:
return trace.Int64Attribute(key, v)
case float64:
return trace.StringAttribute(key, fmt.Sprintf("%f", v))
case bool:
return trace.BoolAttribute(key, v)
case []byte:
if len(v) > 256 {
v = v[0:256]
}
return trace.StringAttribute(key, fmt.Sprintf("%s", v))
default:
s := fmt.Sprintf("%v", v)
if len(s) > 256 {
s = s[0:256]
}
return trace.StringAttribute(key, s)
}
}
func setSpanStatus(span *trace.Span, err error) {
var status trace.Status
switch err {
case nil:
status.Code = trace.StatusCodeOK
span.SetStatus(status)
return
case context.Canceled:
status.Code = trace.StatusCodeCancelled
case context.DeadlineExceeded:
status.Code = trace.StatusCodeDeadlineExceeded
case sql.ErrNoRows:
status.Code = trace.StatusCodeNotFound
case sql.ErrTxDone, sql.ErrConnDone:
status.Code = trace.StatusCodeFailedPrecondition
default:
status.Code = trace.StatusCodeUnknown
}
status.Message = err.Error()
span.SetStatus(status)
}