-
Notifications
You must be signed in to change notification settings - Fork 40
/
mongodb.go
174 lines (157 loc) · 4.87 KB
/
mongodb.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
package perf
import (
"context"
"fmt"
"strings"
"sync"
"sync/atomic"
"go.mongodb.org/mongo-driver/event"
"go.opencensus.io/trace"
"go.viam.com/utils/perf/statz"
"go.viam.com/utils/perf/statz/units"
)
// from https://github.com/entropyx/mongo-opencensus
type config struct {
sampler trace.Sampler
}
// MongoDBMonitorOption represents an option that can be passed to NewMongoDBMonitor.
type MongoDBMonitorOption func(*config)
// WithMongoDBMonitorSampler set a sampler for all started spans.
func WithMongoDBMonitorSampler(sampler trace.Sampler) MongoDBMonitorOption {
return func(cfg *config) {
cfg.sampler = sampler
}
}
type spanKey struct {
ConnectionID string
RequestID int64
}
type monitor struct {
sync.Mutex
spans map[spanKey]*trace.Span
cfg *config
}
func (m *monitor) Started(ctx context.Context, evt *event.CommandStartedEvent) {
connString := connectionString(evt)
attrs := []trace.Attribute{
trace.StringAttribute("db.system", "mongodb"),
trace.StringAttribute("db.name", evt.DatabaseName),
trace.StringAttribute("db.operation", evt.CommandName),
trace.StringAttribute("db.connection_string", connString),
}
var collStr string
if cmdVal, err := evt.Command.LookupErr(evt.CommandName); err == nil {
if str, ok := cmdVal.StringValueOK(); ok {
collStr = str
attrs = append(attrs, trace.StringAttribute("db.mongodb.collection", collStr))
}
}
var spanName string
if collStr == "" {
spanName = fmt.Sprintf("%s::%s", evt.DatabaseName, evt.CommandName)
} else {
spanName = fmt.Sprintf("%s::%s::%s", evt.DatabaseName, collStr, evt.CommandName)
}
_, span := trace.StartSpan(ctx, spanName, trace.WithSampler(m.cfg.sampler))
span.AddAttributes(attrs...)
key := spanKey{
ConnectionID: evt.ConnectionID,
RequestID: evt.RequestID,
}
m.Lock()
m.spans[key] = span
m.Unlock()
}
func (m *monitor) Succeeded(ctx context.Context, evt *event.CommandSucceededEvent) {
m.Finished(&evt.CommandFinishedEvent, nil)
}
func (m *monitor) Failed(ctx context.Context, evt *event.CommandFailedEvent) {
m.Finished(&evt.CommandFinishedEvent, fmt.Errorf("%s", evt.Failure))
}
func (m *monitor) Finished(evt *event.CommandFinishedEvent, err error) {
key := spanKey{
ConnectionID: evt.ConnectionID,
RequestID: evt.RequestID,
}
m.Lock()
span, ok := m.spans[key]
if ok {
delete(m.spans, key)
}
m.Unlock()
if !ok {
return
}
if err != nil {
span.AddAttributes(trace.StringAttribute("error.msg", err.Error()))
}
span.End()
}
// NewMongoDBMonitor creates a new mongodb event CommandMonitor.
func NewMongoDBMonitor(opts ...MongoDBMonitorOption) *event.CommandMonitor {
cfg := new(config)
for _, opt := range opts {
opt(cfg)
}
m := &monitor{
spans: make(map[spanKey]*trace.Span),
cfg: cfg,
}
return &event.CommandMonitor{
Started: m.Started,
Succeeded: m.Succeeded,
Failed: m.Failed,
}
}
func connectionString(evt *event.CommandStartedEvent) string {
hostname := evt.ConnectionID
port := "27017"
if idx := strings.IndexByte(hostname, '['); idx >= 0 {
hostname = hostname[:idx]
}
if idx := strings.IndexByte(hostname, ':'); idx >= 0 {
port = hostname[idx+1:]
hostname = hostname[:idx]
}
return hostname + ":" + port
}
// NewMongoDBPoolMonitor creates a new mongodb pool event PoolMonitor.
func NewMongoDBPoolMonitor() *event.PoolMonitor {
var totalWaitingToCheckOut atomic.Int64
var totalCheckedOut atomic.Int64
var totalCreated atomic.Int64
return &event.PoolMonitor{
Event: func(e *event.PoolEvent) {
switch e.Type {
case event.GetStarted:
totalWaitingToCheckOut.Add(1)
mongodbConnectionPoolStates.Set(e.Address, "total_waiting_to_check_out", totalWaitingToCheckOut.Load())
case event.GetSucceeded:
totalCheckedOut.Add(1)
totalWaitingToCheckOut.Add(-1)
mongodbConnectionPoolStates.Set(e.Address, "total_checked_out", totalCheckedOut.Load())
mongodbConnectionPoolStates.Set(e.Address, "total_waiting_to_check_out", totalWaitingToCheckOut.Load())
case event.GetFailed:
totalWaitingToCheckOut.Add(-1)
mongodbConnectionPoolStates.Set(e.Address, "total_waiting_to_check_out", totalWaitingToCheckOut.Load())
case event.ConnectionReturned:
totalCheckedOut.Add(-1)
mongodbConnectionPoolStates.Set(e.Address, "total_checked_out", totalCheckedOut.Load())
case event.ConnectionCreated:
totalCreated.Add(1)
mongodbConnectionPoolStates.Set(e.Address, "total_created", totalCreated.Load())
case event.ConnectionClosed:
totalCreated.Add(-1)
mongodbConnectionPoolStates.Set(e.Address, "total_created", totalCreated.Load())
}
},
}
}
var mongodbConnectionPoolStates = statz.NewGauge2[string, string]("mongodb/connections", statz.MetricConfig{
Description: "The number of waiting requests for connection check out.",
Unit: units.Dimensionless,
Labels: []statz.Label{
{Name: "connection_string", Description: "MongoDB Connection String"},
{Name: "state", Description: "Pool State"},
},
})