-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmeter.go
233 lines (199 loc) · 8.81 KB
/
meter.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
package otelpgx
import (
"context"
"fmt"
"sync"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
semconv "go.opentelemetry.io/otel/semconv/v1.27.0"
)
const (
// defaultMinimumReadDBStatsInterval is the default minimum interval between calls to db.Stats().
defaultMinimumReadDBStatsInterval = time.Second
)
var (
pgxPoolAcquireCount = "pgxpool.acquires"
pgxPoolAcquireDuration = "pgxpool.acquire_duration"
pgxPoolAcquiredConnections = "pgxpool.acquired_connections"
pgxPoolCancelledAcquires = "pgxpool.canceled_acquires"
pgxPoolConstructingConnections = "pgxpool.constructing_connections"
pgxPoolEmptyAcquire = "pgxpool.empty_acquire"
pgxPoolIdleConnections = "pgxpool.idle_connections"
pgxPoolMaxConnections = "pgxpool.max_connections"
pgxPoolMaxIdleDestroyCount = "pgxpool.max_idle_destroys"
pgxPoolMaxLifetimeDestroyCount = "pgxpool.max_lifetime_destroys"
pgxPoolNewConnectionsCount = "pgxpool.new_connections"
pgxPoolTotalConnections = "pgxpool.total_connections"
)
// RecordStats records database statistics for provided pgxpool.Pool at a default 1 second interval
// unless otherwise specified by the WithMinimumReadDBStatsInterval StatsOption.
func RecordStats(db *pgxpool.Pool, opts ...StatsOption) error {
o := statsOptions{
meterProvider: otel.GetMeterProvider(),
minimumReadDBStatsInterval: defaultMinimumReadDBStatsInterval,
defaultAttributes: []attribute.KeyValue{
semconv.DBSystemPostgreSQL,
},
}
for _, opt := range opts {
opt.applyStatsOptions(&o)
}
meter := o.meterProvider.Meter(meterName, metric.WithInstrumentationVersion(findOwnImportedVersion()))
return recordStats(meter, db, o.minimumReadDBStatsInterval, o.defaultAttributes...)
}
func recordStats(
meter metric.Meter,
db *pgxpool.Pool,
minimumReadDBStatsInterval time.Duration,
attrs ...attribute.KeyValue,
) error {
var (
err error
// Asynchronous Observable Metrics
acquireCount metric.Int64ObservableCounter
acquireDuration metric.Int64ObservableCounter
acquiredConns metric.Int64ObservableUpDownCounter
cancelledAcquires metric.Int64ObservableCounter
constructingConns metric.Int64ObservableUpDownCounter
emptyAcquires metric.Int64ObservableCounter
idleConns metric.Int64ObservableUpDownCounter
maxConns metric.Int64ObservableGauge
maxIdleDestroyCount metric.Int64ObservableCounter
maxLifetimeDestroyCount metric.Int64ObservableCounter
newConnsCount metric.Int64ObservableCounter
totalConns metric.Int64ObservableUpDownCounter
observeOptions []metric.ObserveOption
dbStats *pgxpool.Stat
lastDBStats time.Time
// lock prevents a race between batch observer and instrument registration.
lock sync.Mutex
)
serverAddress := semconv.ServerAddress(db.Config().ConnConfig.Host)
serverPort := semconv.ServerPort(int(db.Config().ConnConfig.Port))
dbNamespace := semconv.DBNamespace(db.Config().ConnConfig.Database)
poolName := fmt.Sprintf("%s:%d/%s", serverAddress.Value.AsString(), serverPort.Value.AsInt64(), dbNamespace.Value.AsString())
dbClientConnectionPoolName := semconv.DBClientConnectionPoolName(poolName)
lock.Lock()
defer lock.Unlock()
if acquireCount, err = meter.Int64ObservableCounter(
pgxPoolAcquireCount,
metric.WithDescription("Cumulative count of successful acquires from the pool."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolAcquireCount, err)
}
if acquireDuration, err = meter.Int64ObservableCounter(
pgxPoolAcquireDuration,
metric.WithDescription("Total duration of all successful acquires from the pool in nanoseconds."),
metric.WithUnit("ns"),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolAcquireDuration, err)
}
if acquiredConns, err = meter.Int64ObservableUpDownCounter(
pgxPoolAcquiredConnections,
metric.WithDescription("Number of currently acquired connections in the pool."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolAcquiredConnections, err)
}
if cancelledAcquires, err = meter.Int64ObservableCounter(
pgxPoolCancelledAcquires,
metric.WithDescription("Cumulative count of acquires from the pool that were canceled by a context."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolCancelledAcquires, err)
}
if constructingConns, err = meter.Int64ObservableUpDownCounter(
pgxPoolConstructingConnections,
metric.WithUnit("ms"),
metric.WithDescription("Number of connections with construction in progress in the pool."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolConstructingConnections, err)
}
if emptyAcquires, err = meter.Int64ObservableCounter(
pgxPoolEmptyAcquire,
metric.WithDescription("Cumulative count of successful acquires from the pool that waited for a resource to be released or constructed because the pool was empty."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolEmptyAcquire, err)
}
if idleConns, err = meter.Int64ObservableUpDownCounter(
pgxPoolIdleConnections,
metric.WithDescription("Number of currently idle connections in the pool."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolIdleConnections, err)
}
if maxConns, err = meter.Int64ObservableGauge(
pgxPoolMaxConnections,
metric.WithDescription("Maximum size of the pool."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolMaxConnections, err)
}
if maxIdleDestroyCount, err = meter.Int64ObservableCounter(
pgxPoolMaxIdleDestroyCount,
metric.WithDescription("Cumulative count of connections destroyed because they exceeded MaxConnectionsIdleTime."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolMaxIdleDestroyCount, err)
}
if maxLifetimeDestroyCount, err = meter.Int64ObservableCounter(
pgxPoolMaxLifetimeDestroyCount,
metric.WithDescription("Cumulative count of connections destroyed because they exceeded MaxConnectionsLifetime."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolMaxLifetimeDestroyCount, err)
}
if newConnsCount, err = meter.Int64ObservableCounter(
pgxPoolNewConnectionsCount,
metric.WithDescription("Cumulative count of new connections opened."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolNewConnectionsCount, err)
}
if totalConns, err = meter.Int64ObservableUpDownCounter(
pgxPoolTotalConnections,
metric.WithDescription("Total number of resources currently in the pool. The value is the sum of ConstructingConnections, AcquiredConnections, and IdleConnections."),
); err != nil {
return fmt.Errorf("failed to create asynchronous metric: %s with error: %w", pgxPoolTotalConnections, err)
}
attrs = append(attrs, []attribute.KeyValue{
semconv.DBSystemPostgreSQL,
dbClientConnectionPoolName,
}...)
observeOptions = []metric.ObserveOption{
metric.WithAttributes(attrs...),
}
_, err = meter.RegisterCallback(
func(ctx context.Context, o metric.Observer) error {
lock.Lock()
defer lock.Unlock()
now := time.Now()
if now.Sub(lastDBStats) >= minimumReadDBStatsInterval {
dbStats = db.Stat()
lastDBStats = now
}
o.ObserveInt64(acquireCount, dbStats.AcquireCount(), observeOptions...)
o.ObserveInt64(acquireDuration, dbStats.AcquireDuration().Nanoseconds(), observeOptions...)
o.ObserveInt64(acquiredConns, int64(dbStats.AcquiredConns()), observeOptions...)
o.ObserveInt64(cancelledAcquires, dbStats.CanceledAcquireCount(), observeOptions...)
o.ObserveInt64(constructingConns, int64(dbStats.ConstructingConns()), observeOptions...)
o.ObserveInt64(emptyAcquires, dbStats.EmptyAcquireCount(), observeOptions...)
o.ObserveInt64(idleConns, int64(dbStats.IdleConns()), observeOptions...)
o.ObserveInt64(maxConns, int64(dbStats.MaxConns()), observeOptions...)
o.ObserveInt64(maxIdleDestroyCount, dbStats.MaxIdleDestroyCount(), observeOptions...)
o.ObserveInt64(maxLifetimeDestroyCount, dbStats.MaxLifetimeDestroyCount(), observeOptions...)
o.ObserveInt64(newConnsCount, dbStats.NewConnsCount(), observeOptions...)
o.ObserveInt64(totalConns, int64(dbStats.TotalConns()), observeOptions...)
return nil
},
acquireCount,
acquireDuration,
acquiredConns,
cancelledAcquires,
constructingConns,
emptyAcquires,
idleConns,
maxConns,
maxIdleDestroyCount,
maxLifetimeDestroyCount,
newConnsCount,
totalConns,
)
return err
}