-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
driver.go
216 lines (173 loc) · 6.42 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
package otelsql
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"io"
"strconv"
"sync"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/metric"
semconv "go.opentelemetry.io/otel/semconv/v1.20.0"
"go.opentelemetry.io/otel/trace"
)
const _maxDriver = 150
const instrumentationName = "go.nhat.io/otelsql"
const (
dbSQLClientLatencyMs = "db.sql.client.latency"
dbSQLClientCalls = "db.sql.client.calls"
unitDimensionless = "1"
unitBytes = "By"
unitMilliseconds = "ms"
)
var regMu sync.Mutex
// Register initializes and registers our otelsql wrapped database driver identified by its driverName and using provided
// options. 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 options for
// different connections.
func Register(driverName string, options ...DriverOption) (string, error) {
return RegisterWithSource(driverName, "", options...)
}
// RegisterWithSource initializes and registers our otelsql wrapped database driver
// identified by its driverName, using provided options.
//
// source is useful if some drivers do not accept the empty string when opening the DB. 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 options for
// different connections.
func RegisterWithSource(driverName string, source string, options ...DriverOption) (string, error) {
// retrieve the driver implementation we need to wrap with instrumentation
db, err := sql.Open(driverName, source)
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 otelsql drivers to have different options, but potentially the same
// underlying database driver, we cycle through to find available driver names.
driverName += "-otelsql-"
for i := int64(0); i < _maxDriver; i++ {
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 OpenTelemetry instrumentation.
func Wrap(d driver.Driver, opts ...DriverOption) driver.Driver {
o := driverOptions{
meterProvider: otel.GetMeterProvider(),
tracerProvider: otel.GetTracerProvider(),
}
o.trace.spanNameFormatter = formatSpanName
o.trace.errorToSpanStatus = spanStatusFromError
o.trace.queryTracer = traceNoQuery
for _, option := range opts {
option.applyDriverOptions(&o)
}
return wrapDriver(d, o)
}
func wrapDriver(d driver.Driver, o driverOptions) driver.Driver {
drv := otDriver{
parent: d,
connConfig: newConnConfig(o),
close: func() error { return nil },
}
if _, ok := d.(driver.DriverContext); ok {
return struct {
driver.Driver
driver.DriverContext
}{drv, drv}
}
return struct{ driver.Driver }{drv}
}
func newConnConfig(opts driverOptions) connConfig {
meter := opts.meterProvider.Meter(instrumentationName)
tracer := newMethodTracer(
opts.tracerProvider.Tracer(instrumentationName,
trace.WithInstrumentationVersion(Version()),
trace.WithSchemaURL(semconv.SchemaURL),
),
traceWithAllowRoot(opts.trace.AllowRoot),
traceWithDefaultAttributes(opts.defaultAttributes...),
traceWithSpanNameFormatter(opts.trace.spanNameFormatter),
traceWithErrorToSpanStatus(opts.trace.errorToSpanStatus),
)
latencyMsHistogram, err := meter.Float64Histogram(dbSQLClientLatencyMs,
metric.WithUnit(unitMilliseconds),
metric.WithDescription(`The distribution of latencies of various calls in milliseconds`),
)
mustNoError(err)
callsCounter, err := meter.Int64Counter(dbSQLClientCalls,
metric.WithUnit(unitDimensionless),
metric.WithDescription(`The number of various calls of methods`),
)
mustNoError(err)
latencyRecorder := newMethodRecorder(latencyMsHistogram.Record, callsCounter.Add, opts.defaultAttributes...)
return connConfig{
pingFuncMiddlewares: makePingFuncMiddlewares(latencyRecorder, tracerOrNil(tracer, opts.trace.Ping)),
execContextFuncMiddlewares: makeExecContextFuncMiddlewares(latencyRecorder, tracer, newExecConfig(opts, metricMethodExec, traceMethodExec)),
queryContextFuncMiddlewares: makeQueryerContextMiddlewares(latencyRecorder, tracer, newQueryConfig(opts, metricMethodQuery, traceMethodQuery)),
beginFuncMiddlewares: makeBeginFuncMiddlewares(latencyRecorder, tracer),
prepareFuncMiddlewares: makePrepareContextFuncMiddlewares(latencyRecorder, tracer, prepareConfig{
traceQuery: opts.trace.queryTracer,
execFuncMiddlewares: makeExecContextFuncMiddlewares(latencyRecorder, tracerOrNil(tracer, opts.trace.AllowRoot), newExecConfig(opts, metricMethodStmtExec, traceMethodStmtExec)),
execContextFuncMiddlewares: makeExecContextFuncMiddlewares(latencyRecorder, tracer, newExecConfig(opts, metricMethodStmtExec, traceMethodStmtExec)),
queryFuncMiddlewares: makeQueryerContextMiddlewares(latencyRecorder, tracerOrNil(tracer, opts.trace.AllowRoot), newQueryConfig(opts, metricMethodStmtQuery, traceMethodStmtQuery)),
queryContextFuncMiddlewares: makeQueryerContextMiddlewares(latencyRecorder, tracer, newQueryConfig(opts, metricMethodStmtQuery, traceMethodStmtQuery)),
}),
}
}
var _ driver.Driver = (*otDriver)(nil)
type otDriver struct {
parent driver.Driver
connector driver.Connector
close func() error
connConfig connConfig
}
func (d otDriver) Open(name string) (driver.Conn, error) {
c, err := d.parent.Open(name)
if err != nil {
return nil, err
}
return wrapConn(c, d.connConfig), nil
}
func (d otDriver) Close() error {
return d.close()
}
func (d otDriver) OpenConnector(name string) (driver.Connector, error) {
var err error
d.connector, err = d.parent.(driver.DriverContext).OpenConnector(name)
if err != nil {
return nil, err
}
if c, ok := d.connector.(io.Closer); ok {
d.close = c.Close
}
return d, err
}
func (d otDriver) Connect(ctx context.Context) (driver.Conn, error) {
c, err := d.connector.Connect(ctx)
if err != nil {
return nil, err
}
return wrapConn(c, d.connConfig), nil
}
func (d otDriver) Driver() driver.Driver {
return d
}