-
Notifications
You must be signed in to change notification settings - Fork 8
/
response_time.go
287 lines (248 loc) · 8.27 KB
/
response_time.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Copyright 2022 Block, Inc.
package queryresponsetime
import (
"context"
"database/sql"
"fmt"
"math"
"time"
myerr "github.com/go-mysql/errors"
"github.com/cashapp/blip"
"github.com/cashapp/blip/errors"
"github.com/cashapp/blip/sqlutil"
)
const (
DOMAIN = "query.response-time"
OPT_REAL_PERCENTILES = "real-percentiles"
OPT_TRUNCATE_TABLE = "truncate-table"
OPT_TRUNCATE_TIMEOUT = "truncate-timeout"
ERR_NO_TABLE = "table-not-exist"
ERR_TRUNCATE_FAILED = "truncate-timeout"
BASE_QUERY = "SELECT ROUND(bucket_quantile * 100, 1) AS p, ROUND(bucket_timer_high / 1000000, 3) AS us FROM performance_schema.events_statements_histogram_global"
TRUNCATE_QUERY = "TRUNCATE TABLE performance_schema.events_statements_histogram_global"
LOCKWAIT_QUERY = "SET @@session.lock_wait_timeout=%d"
)
type percentile struct {
formatted string // p95
query string
}
type qrtConfig struct {
percentiles []percentile
setMeta bool
truncate bool
truncateTimeout time.Duration
stop bool
errPolicy map[string]*errors.Policy
truncateErrPolicy *errors.TruncateErrorPolicy
lockWaitQuery string
}
type ResponseTime struct {
db *sql.DB
// --
atLevel map[string]*qrtConfig // keyed on level
}
var _ blip.Collector = &ResponseTime{}
func NewResponseTime(db *sql.DB) *ResponseTime {
return &ResponseTime{
db: db,
atLevel: map[string]*qrtConfig{},
}
}
// Domain returns the Blip metric domain name (DOMAIN const).
func (c *ResponseTime) Domain() string {
return DOMAIN
}
// Help returns the output for blip --print-domains.
func (c *ResponseTime) Help() blip.CollectorHelp {
return blip.CollectorHelp{
Domain: DOMAIN,
Description: "Collect metrics for query response time",
Options: map[string]blip.CollectorHelpOption{
OPT_REAL_PERCENTILES: {
Name: OPT_REAL_PERCENTILES,
Desc: "If real percentiles are included in meta",
Default: "yes",
Values: map[string]string{
"yes": "Include real percentiles in meta",
"no": "Exclude real percentiles in meta",
},
},
OPT_TRUNCATE_TABLE: {
Name: OPT_TRUNCATE_TABLE,
Desc: "If the source table should be truncated to reset data after each retrieval",
Default: "yes",
Values: map[string]string{
"yes": "Truncate source table after each retrieval",
"no": "Do not truncate source table after each retrieval",
},
},
OPT_TRUNCATE_TIMEOUT: {
Name: OPT_TRUNCATE_TIMEOUT,
Desc: "The amount of time to attempt to truncate the source table before timing out",
Default: "250ms",
},
},
Metrics: []blip.CollectorMetric{
{
Name: "pN",
Type: blip.GAUGE,
Desc: "Percentile to collect where N between 1 and 999 (p99=99th, p999=99.9th)",
},
},
Errors: map[string]blip.CollectorHelpError{
ERR_NO_TABLE: {
Name: ERR_NO_TABLE,
Handles: "MySQL error 1146: Table 'performance_schema.events_statements_histogram_global' doesn't exist",
Default: errors.NewPolicy("").String(),
},
ERR_TRUNCATE_FAILED: {
Name: ERR_TRUNCATE_FAILED,
Handles: "Truncation failures on table 'performance_schema.events_statements_histogram_global'",
Default: errors.NewPolicy("").String(),
},
},
}
}
// Prepare prepares the collector for the given plan.
func (c *ResponseTime) Prepare(ctx context.Context, plan blip.Plan) (func(), error) {
LEVEL:
for _, level := range plan.Levels {
dom, ok := level.Collect[DOMAIN]
if !ok {
continue LEVEL // not collected at this level
}
config := &qrtConfig{}
if rp, ok := dom.Options[OPT_REAL_PERCENTILES]; ok && rp == "no" {
config.setMeta = false
} else {
config.setMeta = true // default
}
if truncate, ok := dom.Options[OPT_TRUNCATE_TABLE]; ok && truncate == "no" {
config.truncate = false
} else {
config.truncate = true // default
}
if truncateTimeout, ok := dom.Options[OPT_TRUNCATE_TIMEOUT]; ok && config.truncate {
if duration, err := time.ParseDuration(truncateTimeout); err != nil {
return nil, fmt.Errorf("Invalid truncate duration: %v", err)
} else {
config.truncateTimeout = duration
}
} else {
config.truncateTimeout = 250 * time.Millisecond // default
}
if config.truncate {
// Setup our lock wait timeout. It needs to be at least as long
// as our truncate timeout, but the granularity of the lock wait
// timeout is seconds, so we round up to the nearest second that is
// greater than our truncate timeout.
lockWaitTimeout := math.Ceil(config.truncateTimeout.Seconds())
if lockWaitTimeout < 1.0 {
lockWaitTimeout = 1
}
config.lockWaitQuery = fmt.Sprintf(LOCKWAIT_QUERY, int64(lockWaitTimeout))
}
// Process list of percentiles metrics into a list of names and values
p, err := sqlutil.PercentileMetrics(dom.Metrics)
if err != nil {
return nil, err
}
// For each percentile, save a query to fetch its (closest) value
config.percentiles = make([]percentile, len(p))
for i := range p {
config.percentiles[i] = percentile{
formatted: p[i].Name,
query: BASE_QUERY + fmt.Sprintf(" WHERE bucket_quantile >= %f ORDER BY bucket_quantile LIMIT 1", p[i].Value),
}
}
// Apply custom error policies, if any
config.errPolicy = map[string]*errors.Policy{}
config.errPolicy[ERR_NO_TABLE] = errors.NewPolicy(dom.Errors[ERR_NO_TABLE])
blip.Debug("error policy: %s=%s", ERR_NO_TABLE, config.errPolicy[ERR_NO_TABLE])
if config.truncate {
config.truncateErrPolicy = errors.NewTruncateErrorPolicy(dom.Errors[ERR_TRUNCATE_FAILED])
blip.Debug("error policy: %s=%s", ERR_TRUNCATE_FAILED, config.truncateErrPolicy.Policy)
}
c.atLevel[level.Name] = config
}
return nil, nil
}
// Collect collects metrics at the given level.
func (c *ResponseTime) Collect(ctx context.Context, levelName string) ([]blip.MetricValue, error) {
if c.atLevel[levelName].stop {
blip.Debug("stopped by previous error")
return nil, nil
}
var metrics []blip.MetricValue
for _, percentile := range c.atLevel[levelName].percentiles {
var p float64
var us float64
err := c.db.QueryRowContext(ctx, percentile.query).Scan(&p, &us)
if err != nil {
return c.collectError(err, levelName, percentile.formatted)
}
m := blip.MetricValue{
Type: blip.GAUGE,
Name: percentile.formatted,
Value: us,
}
if c.atLevel[levelName].setMeta {
m.Meta = map[string]string{
percentile.formatted: fmt.Sprintf("%.1f", p),
}
}
metrics = append(metrics, m)
}
if c.atLevel[levelName].truncate {
conn, err := c.db.Conn(ctx)
if err == nil {
defer conn.Close()
// Set `lock_wait_timeout` to prevent our query from begin blocked for too long
// due to metadata locking. We treat a failure to set the lock wait timeout
// the same as a truncate timeout, as not setting creates a risk of having a thread
// hang for an extended period of time.
_, err = conn.ExecContext(ctx, c.atLevel[levelName].lockWaitQuery)
if err == nil {
trCtx, cancelFn := context.WithTimeout(ctx, c.atLevel[levelName].truncateTimeout)
defer cancelFn()
_, err = conn.ExecContext(trCtx, TRUNCATE_QUERY)
}
}
// Process any errors (or lack thereof) with the TruncateErrorPolicy as there is special handling
// for the metric values that need to be applied, even if there is not an error. See comments
// in `TruncateErrorPolicy` for more details.
return c.atLevel[levelName].truncateErrPolicy.TruncateError(err, &c.atLevel[levelName].stop, metrics)
}
return metrics, nil
}
func (c *ResponseTime) collectError(err error, levelName string, metricName string) ([]blip.MetricValue, error) {
var ep *errors.Policy
switch myerr.MySQLErrorCode(err) {
case 1146:
ep = c.atLevel[levelName].errPolicy[ERR_NO_TABLE]
default:
return nil, err
}
// Stop trying to collect if error policy retry="stop". This affects
// future calls to Collect; don't return yet because we need to check
// the metric policy: drop or zero. If zero, we must report one zero val.
if ep.Retry == errors.POLICY_RETRY_NO {
c.atLevel[levelName].stop = true
}
// Report
var reportedErr error
if ep.ReportError() {
reportedErr = err
} else {
blip.Debug("error policy=ignore: %v", err)
}
var metrics []blip.MetricValue
if ep.Metric == errors.POLICY_METRIC_ZERO {
metrics = []blip.MetricValue{{
Type: blip.GAUGE,
Name: metricName,
Value: 0,
}}
}
return metrics, reportedErr
}