Skip to content

Commit d368279

Browse files
authored
Merge pull request #38 from vearutop/db-instance-name
Add InstanceName trace option
2 parents e766b83 + 80c62ed commit d368279

File tree

5 files changed

+65
-24
lines changed

5 files changed

+65
-24
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ var (
3232
)
3333

3434
// Register our ocsql wrapper for the provided SQLite3 driver.
35-
driverName, err = ocsql.Register("sqlite3", ocsql.WithAllTraceOptions())
35+
driverName, err = ocsql.Register("sqlite3", ocsql.WithAllTraceOptions(), ocsql.WithInstanceName("resources"))
3636
if err != nil {
3737
log.Fatalf("unable to register our ocsql driver: %v\n", err)
3838
}

driver.go

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,11 @@ func Wrap(d driver.Driver, options ...TraceOption) driver.Driver {
9292
for _, option := range options {
9393
option(&o)
9494
}
95+
if o.InstanceName == "" {
96+
o.InstanceName = defaultInstanceName
97+
} else {
98+
o.DefaultAttributes = append(o.DefaultAttributes, trace.StringAttribute("sql.instance", o.InstanceName))
99+
}
95100
if o.QueryParams && !o.Query {
96101
o.QueryParams = false
97102
}
@@ -113,6 +118,11 @@ func WrapConn(c driver.Conn, options ...TraceOption) driver.Conn {
113118
for _, option := range options {
114119
option(&o)
115120
}
121+
if o.InstanceName == "" {
122+
o.InstanceName = defaultInstanceName
123+
} else {
124+
o.DefaultAttributes = append(o.DefaultAttributes, trace.StringAttribute("sql.instance", o.InstanceName))
125+
}
116126
return wrapConn(c, o)
117127
}
118128

@@ -123,7 +133,7 @@ type ocConn struct {
123133
}
124134

125135
func (c ocConn) Ping(ctx context.Context) (err error) {
126-
defer recordCallStats(ctx, "go.sql.ping")(err)
136+
defer recordCallStats(ctx, "go.sql.ping", c.options.InstanceName)(err)
127137

128138
if c.options.Ping && (c.options.AllowRoot || trace.FromContext(ctx) != nil) {
129139
var span *trace.Span
@@ -154,7 +164,7 @@ func (c ocConn) Ping(ctx context.Context) (err error) {
154164
}
155165

156166
func (c ocConn) Exec(query string, args []driver.Value) (res driver.Result, err error) {
157-
defer recordCallStats(context.Background(), "go.sql.exec")(err)
167+
defer recordCallStats(context.Background(), "go.sql.exec", c.options.InstanceName)(err)
158168

159169
if exec, ok := c.parent.(driver.Execer); ok {
160170
if !c.options.AllowRoot {
@@ -198,7 +208,7 @@ func (c ocConn) Exec(query string, args []driver.Value) (res driver.Result, err
198208
}
199209

200210
func (c ocConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (res driver.Result, err error) {
201-
defer recordCallStats(ctx, "go.sql.exec")(err)
211+
defer recordCallStats(ctx, "go.sql.exec", c.options.InstanceName)(err)
202212

203213
if execCtx, ok := c.parent.(driver.ExecerContext); ok {
204214
parentSpan := trace.FromContext(ctx)
@@ -243,7 +253,7 @@ func (c ocConn) ExecContext(ctx context.Context, query string, args []driver.Nam
243253
}
244254

245255
func (c ocConn) Query(query string, args []driver.Value) (rows driver.Rows, err error) {
246-
defer recordCallStats(context.Background(), "go.sql.query")(err)
256+
defer recordCallStats(context.Background(), "go.sql.query", c.options.InstanceName)(err)
247257

248258
if queryer, ok := c.parent.(driver.Queryer); ok {
249259
if !c.options.AllowRoot {
@@ -288,7 +298,7 @@ func (c ocConn) Query(query string, args []driver.Value) (rows driver.Rows, err
288298
}
289299

290300
func (c ocConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (rows driver.Rows, err error) {
291-
defer recordCallStats(ctx, "go.sql.query")(err)
301+
defer recordCallStats(ctx, "go.sql.query", c.options.InstanceName)(err)
292302

293303
if queryerCtx, ok := c.parent.(driver.QueryerContext); ok {
294304
parentSpan := trace.FromContext(ctx)
@@ -334,7 +344,7 @@ func (c ocConn) QueryContext(ctx context.Context, query string, args []driver.Na
334344
}
335345

336346
func (c ocConn) Prepare(query string) (stmt driver.Stmt, err error) {
337-
defer recordCallStats(context.Background(), "go.sql.prepare")(err)
347+
defer recordCallStats(context.Background(), "go.sql.prepare", c.options.InstanceName)(err)
338348

339349
if c.options.AllowRoot {
340350
_, span := trace.StartSpan(context.Background(), "sql:prepare",
@@ -373,7 +383,7 @@ func (c *ocConn) Begin() (driver.Tx, error) {
373383
}
374384

375385
func (c *ocConn) PrepareContext(ctx context.Context, query string) (stmt driver.Stmt, err error) {
376-
defer recordCallStats(ctx, "go.sql.prepare")(err)
386+
defer recordCallStats(ctx, "go.sql.prepare", c.options.InstanceName)(err)
377387

378388
var span *trace.Span
379389
attrs := append([]trace.Attribute(nil), c.options.DefaultAttributes...)
@@ -409,7 +419,7 @@ func (c *ocConn) PrepareContext(ctx context.Context, query string) (stmt driver.
409419
}
410420

411421
func (c *ocConn) BeginTx(ctx context.Context, opts driver.TxOptions) (tx driver.Tx, err error) {
412-
defer recordCallStats(ctx, "go.sql.begin")(err)
422+
defer recordCallStats(ctx, "go.sql.begin", c.options.InstanceName)(err)
413423

414424
if !c.options.AllowRoot && trace.FromContext(ctx) == nil {
415425
if connBeginTx, ok := c.parent.(driver.ConnBeginTx); ok {
@@ -518,7 +528,7 @@ type ocStmt struct {
518528
}
519529

520530
func (s ocStmt) Exec(args []driver.Value) (res driver.Result, err error) {
521-
defer recordCallStats(context.Background(), "go.sql.stmt.exec")(err)
531+
defer recordCallStats(context.Background(), "go.sql.stmt.exec", s.options.InstanceName)(err)
522532

523533
if !s.options.AllowRoot {
524534
return s.parent.Exec(args)
@@ -568,7 +578,7 @@ func (s ocStmt) NumInput() int {
568578
}
569579

570580
func (s ocStmt) Query(args []driver.Value) (rows driver.Rows, err error) {
571-
defer recordCallStats(context.Background(), "go.sql.stmt.query")(err)
581+
defer recordCallStats(context.Background(), "go.sql.stmt.query", s.options.InstanceName)(err)
572582

573583
if !s.options.AllowRoot {
574584
return s.parent.Query(args)
@@ -609,7 +619,7 @@ func (s ocStmt) Query(args []driver.Value) (rows driver.Rows, err error) {
609619
}
610620

611621
func (s ocStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (res driver.Result, err error) {
612-
defer recordCallStats(ctx, "go.sql.stmt.exec")(err)
622+
defer recordCallStats(ctx, "go.sql.stmt.exec", s.options.InstanceName)(err)
613623

614624
parentSpan := trace.FromContext(ctx)
615625
if !s.options.AllowRoot && parentSpan == nil {
@@ -654,7 +664,7 @@ func (s ocStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (res
654664
}
655665

656666
func (s ocStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (rows driver.Rows, err error) {
657-
defer recordCallStats(ctx, "go.sql.stmt.query")(err)
667+
defer recordCallStats(ctx, "go.sql.stmt.query", s.options.InstanceName)(err)
658668

659669
parentSpan := trace.FromContext(ctx)
660670
if !s.options.AllowRoot && parentSpan == nil {
@@ -863,7 +873,7 @@ type ocTx struct {
863873
}
864874

865875
func (t ocTx) Commit() (err error) {
866-
defer recordCallStats(context.Background(), "go.sql.commit")(err)
876+
defer recordCallStats(context.Background(), "go.sql.commit", t.options.InstanceName)(err)
867877

868878
_, span := trace.StartSpan(t.ctx, "sql:commit",
869879
trace.WithSpanKind(trace.SpanKindClient),
@@ -882,7 +892,7 @@ func (t ocTx) Commit() (err error) {
882892
}
883893

884894
func (t ocTx) Rollback() (err error) {
885-
defer recordCallStats(context.Background(), "go.sql.rollback")(err)
895+
defer recordCallStats(context.Background(), "go.sql.rollback", t.options.InstanceName)(err)
886896

887897
_, span := trace.StartSpan(t.ctx, "sql:rollback",
888898
trace.WithSpanKind(trace.SpanKindClient),

driver_go1.10.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"context"
77
"database/sql"
88
"database/sql/driver"
9+
10+
"go.opencensus.io/trace"
911
)
1012

1113
var errConnDone = sql.ErrConnDone
@@ -19,15 +21,20 @@ var (
1921
// WrapConnector allows wrapping a database driver.Connector which eliminates
2022
// the need to register ocsql as an available driver.Driver.
2123
func WrapConnector(dc driver.Connector, options ...TraceOption) driver.Connector {
22-
opts := TraceOptions{}
23-
for _, o := range options {
24-
o(&opts)
24+
o := TraceOptions{}
25+
for _, option := range options {
26+
option(&o)
27+
}
28+
if o.InstanceName == "" {
29+
o.InstanceName = defaultInstanceName
30+
} else {
31+
o.DefaultAttributes = append(o.DefaultAttributes, trace.StringAttribute("sql.instance", o.InstanceName))
2532
}
2633

2734
return &ocDriver{
2835
parent: dc.Driver(),
2936
connector: dc,
30-
options: opts,
37+
options: o,
3138
}
3239
}
3340

observability.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import (
1111

1212
// The following tags are applied to stats recorded by this package.
1313
var (
14+
// GoSQLInstance is the SQL instance name.
15+
GoSQLInstance, _ = tag.NewKey("go_sql_instance")
1416
// GoSQLMethod is the SQL method called.
1517
GoSQLMethod, _ = tag.NewKey("go_sql_method")
1618
// GoSQLError is the error received while calling a SQL method.
@@ -79,64 +81,71 @@ var (
7981
Description: "The distribution of latencies of various calls in milliseconds",
8082
Measure: MeasureLatencyMs,
8183
Aggregation: DefaultMillisecondsDistribution,
82-
TagKeys: []tag.Key{GoSQLMethod, GoSQLError, GoSQLStatus},
84+
TagKeys: []tag.Key{GoSQLInstance, GoSQLMethod, GoSQLError, GoSQLStatus},
8385
}
8486

8587
SQLClientCallsView = &view.View{
8688
Name: "go.sql/client/calls",
8789
Description: "The number of various calls of methods",
8890
Measure: MeasureLatencyMs,
8991
Aggregation: view.Count(),
90-
TagKeys: []tag.Key{GoSQLMethod, GoSQLError, GoSQLStatus},
92+
TagKeys: []tag.Key{GoSQLInstance, GoSQLMethod, GoSQLError, GoSQLStatus},
9193
}
9294

9395
SQLClientOpenConnectionsView = &view.View{
9496
Name: "go.sql/db/connections/open",
9597
Description: "The number of open connections",
9698
Measure: MeasureOpenConnections,
9799
Aggregation: view.LastValue(),
100+
TagKeys: []tag.Key{GoSQLInstance},
98101
}
99102

100103
SQLClientIdleConnectionsView = &view.View{
101104
Name: "go.sql/db/connections/idle",
102105
Description: "The number of idle connections",
103106
Measure: MeasureIdleConnections,
104107
Aggregation: view.LastValue(),
108+
TagKeys: []tag.Key{GoSQLInstance},
105109
}
106110

107111
SQLClientActiveConnectionsView = &view.View{
108112
Name: "go.sql/db/connections/active",
109113
Description: "The number of active connections",
110114
Measure: MeasureActiveConnections,
111115
Aggregation: view.LastValue(),
116+
TagKeys: []tag.Key{GoSQLInstance},
112117
}
113118

114119
SQLClientWaitCountView = &view.View{
115120
Name: "go.sql/db/connections/wait_count",
116121
Description: "The total number of connections waited for",
117122
Measure: MeasureWaitCount,
118123
Aggregation: view.LastValue(),
124+
TagKeys: []tag.Key{GoSQLInstance},
119125
}
120126

121127
SQLClientWaitDurationView = &view.View{
122128
Name: "go.sql/db/connections/wait_duration",
123129
Description: "The total time blocked waiting for a new connection",
124130
Measure: MeasureWaitDuration,
125131
Aggregation: view.LastValue(),
132+
TagKeys: []tag.Key{GoSQLInstance},
126133
}
127134

128135
SQLClientIdleClosedView = &view.View{
129136
Name: "go.sql/db/connections/idle_closed_count",
130137
Description: "The total number of connections closed due to SetMaxIdleConns",
131138
Measure: MeasureIdleClosed,
132139
Aggregation: view.LastValue(),
140+
TagKeys: []tag.Key{GoSQLInstance},
133141
}
134142

135143
SQLClientLifetimeClosedView = &view.View{
136144
Name: "go.sql/db/connections/lifetime_closed_count",
137145
Description: "The total number of connections closed due to SetConnMaxLifetime",
138146
Measure: MeasureLifetimeClosed,
139147
Aggregation: view.LastValue(),
148+
TagKeys: []tag.Key{GoSQLInstance},
140149
}
141150

142151
DefaultViews = []*view.View{
@@ -154,7 +163,7 @@ func RegisterAllViews() {
154163
}
155164
}
156165

157-
func recordCallStats(ctx context.Context, method string) func(err error) {
166+
func recordCallStats(ctx context.Context, method, instanceName string) func(err error) {
158167
var tags []tag.Mutator
159168
startTime := time.Now()
160169

@@ -163,11 +172,14 @@ func recordCallStats(ctx context.Context, method string) func(err error) {
163172

164173
if err != nil {
165174
tags = []tag.Mutator{
166-
tag.Insert(GoSQLMethod, method), valueErr, tag.Insert(GoSQLError, err.Error()),
175+
tag.Insert(GoSQLMethod, method),
176+
valueErr,
177+
tag.Insert(GoSQLError, err.Error()),
178+
tag.Insert(GoSQLInstance, instanceName),
167179
}
168180
} else {
169181
tags = []tag.Mutator{
170-
tag.Insert(GoSQLMethod, method), valueOK,
182+
tag.Insert(GoSQLMethod, method), valueOK, tag.Insert(GoSQLInstance, instanceName),
171183
}
172184
}
173185

options.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
// TraceOption allows for managing ocsql configuration using functional options.
88
type TraceOption func(o *TraceOptions)
99

10+
const defaultInstanceName = "default"
11+
1012
// TraceOptions holds configuration of our ocsql tracing middleware.
1113
// By default all options are set to false intentionally when creating a wrapped
1214
// driver and provide the most sensible default with both performance and
@@ -51,6 +53,9 @@ type TraceOptions struct {
5153
// DefaultAttributes will be set to each span as default.
5254
DefaultAttributes []trace.Attribute
5355

56+
// InstanceName identifies database.
57+
InstanceName string
58+
5459
// DisableErrSkip, if set to true, will suppress driver.ErrSkip errors in spans.
5560
DisableErrSkip bool
5661

@@ -176,3 +181,10 @@ func WithSampler(sampler trace.Sampler) TraceOption {
176181
o.Sampler = sampler
177182
}
178183
}
184+
185+
// WithInstanceName sets database instance name.
186+
func WithInstanceName(instanceName string) TraceOption {
187+
return func(o *TraceOptions) {
188+
o.InstanceName = instanceName
189+
}
190+
}

0 commit comments

Comments
 (0)