-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
detector.go
187 lines (158 loc) · 5.41 KB
/
detector.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
// Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package insights
import (
"container/list"
"strings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/appstatspb"
"github.com/cockroachdb/cockroach/pkg/util/quantile"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
)
type detector interface {
enabled() bool
isSlow(*Statement) bool
}
var _ detector = &compositeDetector{}
var _ detector = &anomalyDetector{}
var _ detector = &latencyThresholdDetector{}
type compositeDetector struct {
detectors []detector
}
func (d *compositeDetector) enabled() bool {
for _, d := range d.detectors {
if d.enabled() {
return true
}
}
return false
}
func (d *compositeDetector) isSlow(statement *Statement) bool {
// Because some detectors may need to observe all statements to build up
// their baseline sense of what "normal" is, we avoid short-circuiting.
result := false
for _, d := range d.detectors {
result = d.isSlow(statement) || result
}
return result
}
var desiredQuantiles = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
type anomalyDetector struct {
settings *cluster.Settings
metrics Metrics
store *list.List
mu struct {
syncutil.RWMutex
index map[appstatspb.StmtFingerprintID]*list.Element
}
}
type latencySummaryEntry struct {
key appstatspb.StmtFingerprintID
value *quantile.Stream
}
func (d *anomalyDetector) enabled() bool {
return AnomalyDetectionEnabled.Get(&d.settings.SV)
}
func (d *anomalyDetector) isSlow(stmt *Statement) (decision bool) {
if !d.enabled() {
return
}
d.withFingerprintLatencySummary(stmt, func(latencySummary *quantile.Stream) {
latencySummary.Insert(stmt.LatencyInSeconds)
p50 := latencySummary.Query(0.5, true)
p99 := latencySummary.Query(0.99, true)
decision = stmt.LatencyInSeconds >= p99 &&
stmt.LatencyInSeconds >= 2*p50 &&
stmt.LatencyInSeconds >= AnomalyDetectionLatencyThreshold.Get(&d.settings.SV).Seconds()
})
return
}
func (d *anomalyDetector) GetPercentileValues(
id appstatspb.StmtFingerprintID, shouldFlush bool,
) PercentileValues {
// latencySummary.Query might modify its own state (Stream.flush), so a read-write lock is necessary.
d.mu.RLock()
defer d.mu.RUnlock()
latencies := PercentileValues{}
if entry, ok := d.mu.index[id]; ok {
latencySummary := entry.Value.(latencySummaryEntry).value
// If more percentiles are added, update the value of `desiredQuantiles` above
// to include the new keys.
latencies.P50 = latencySummary.Query(0.5, shouldFlush)
latencies.P90 = latencySummary.Query(0.9, shouldFlush)
latencies.P99 = latencySummary.Query(0.99, shouldFlush)
}
return latencies
}
func (d *anomalyDetector) withFingerprintLatencySummary(
stmt *Statement, consumer func(latencySummary *quantile.Stream),
) {
d.mu.Lock()
defer d.mu.Unlock()
var latencySummary *quantile.Stream
if element, ok := d.mu.index[stmt.FingerprintID]; ok {
// We are already tracking latencies for this fingerprint.
latencySummary = element.Value.(latencySummaryEntry).value
d.store.MoveToFront(element) // Mark this latency summary as recently used.
} else if stmt.LatencyInSeconds >= AnomalyDetectionLatencyThreshold.Get(&d.settings.SV).Seconds() {
// We want to start tracking latencies for this fingerprint.
latencySummary = quantile.NewTargeted(desiredQuantiles)
entry := latencySummaryEntry{key: stmt.FingerprintID, value: latencySummary}
d.mu.index[stmt.FingerprintID] = d.store.PushFront(entry)
d.metrics.Fingerprints.Inc(1)
d.metrics.Memory.Inc(latencySummary.ByteSize())
} else {
// We don't care about this fingerprint yet.
return
}
previousMemoryUsage := latencySummary.ByteSize()
consumer(latencySummary)
d.metrics.Memory.Inc(latencySummary.ByteSize() - previousMemoryUsage)
// To control our memory usage, possibly evict the latency summary for the least recently seen statement fingerprint.
if d.metrics.Memory.Value() > AnomalyDetectionMemoryLimit.Get(&d.settings.SV) {
element := d.store.Back()
entry := d.store.Remove(element).(latencySummaryEntry)
delete(d.mu.index, entry.key)
d.metrics.Evictions.Inc(1)
d.metrics.Fingerprints.Dec(1)
d.metrics.Memory.Dec(entry.value.ByteSize())
}
}
func newAnomalyDetector(settings *cluster.Settings, metrics Metrics) *anomalyDetector {
anomaly := &anomalyDetector{
settings: settings,
metrics: metrics,
store: list.New(),
}
anomaly.mu.index = make(map[appstatspb.StmtFingerprintID]*list.Element)
return anomaly
}
type latencyThresholdDetector struct {
st *cluster.Settings
}
func (d *latencyThresholdDetector) enabled() bool {
return LatencyThreshold.Get(&d.st.SV) > 0
}
func (d *latencyThresholdDetector) isSlow(s *Statement) bool {
return d.enabled() && s.LatencyInSeconds >= LatencyThreshold.Get(&d.st.SV).Seconds()
}
func isFailed(s *Statement) bool {
return s.Status == Statement_Failed
}
var prefixesToIgnore = []string{"SET "}
// shouldIgnoreStatement returns true if we don't want to analyze the statement.
func shouldIgnoreStatement(s *Statement) bool {
for _, start := range prefixesToIgnore {
if strings.HasPrefix(s.Query, start) {
return true
}
}
return false
}