-
Notifications
You must be signed in to change notification settings - Fork 2k
/
util.go
410 lines (372 loc) · 14.4 KB
/
util.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/*
Copyright 2023 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package throttler
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"vitess.io/vitess/go/protoutil"
"vitess.io/vitess/go/test/endtoend/cluster"
"vitess.io/vitess/go/vt/concurrency"
"vitess.io/vitess/go/vt/log"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
"vitess.io/vitess/go/vt/vttablet/tabletserver/throttle/base"
"vitess.io/vitess/go/vt/vttablet/tabletserver/throttle/throttlerapp"
)
type Config struct {
Query string
Threshold float64
}
const (
DefaultQuery = "select unix_timestamp(now(6))-max(ts/1000000000) as replication_lag from _vt.heartbeat"
DefaultThreshold = 5 * time.Second
ConfigTimeout = 60 * time.Second
)
var DefaultConfig = &Config{
Query: DefaultQuery,
Threshold: DefaultThreshold.Seconds(),
}
// UpdateThrottlerTopoConfig runs vtctlclient UpdateThrottlerConfig.
// This retries the command until it succeeds or times out as the
// SrvKeyspace record may not yet exist for a newly created
// Keyspace that is still initializing before it becomes serving.
func UpdateThrottlerTopoConfigRaw(vtctldProcess *cluster.VtctldClientProcess, keyspaceName string, enable bool, disable bool, threshold float64, metricsQuery string, appRule *topodatapb.ThrottledAppRule) (result string, err error) {
args := []string{}
args = append(args, "UpdateThrottlerConfig")
if enable {
args = append(args, "--enable")
}
if disable {
args = append(args, "--disable")
}
if threshold > 0 {
args = append(args, "--threshold", fmt.Sprintf("%f", threshold))
}
args = append(args, "--custom-query", metricsQuery)
if metricsQuery != "" {
args = append(args, "--check-as-check-self")
} else {
args = append(args, "--check-as-check-shard")
}
if appRule != nil {
args = append(args, "--throttle-app", appRule.Name)
args = append(args, "--throttle-app-duration", time.Until(protoutil.TimeFromProto(appRule.ExpiresAt).UTC()).String())
args = append(args, "--throttle-app-ratio", fmt.Sprintf("%f", appRule.Ratio))
if appRule.Exempt {
args = append(args, "--throttle-app-exempt")
}
}
args = append(args, keyspaceName)
ctx, cancel := context.WithTimeout(context.Background(), ConfigTimeout)
defer cancel()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
result, err = vtctldProcess.ExecuteCommandWithOutput(args...)
if err == nil {
return result, nil
}
select {
case <-ctx.Done():
return "", fmt.Errorf("timed out waiting for UpdateThrottlerConfig to succeed after %v; last seen value: %+v, error: %v", ConfigTimeout, result, err)
case <-ticker.C:
}
}
}
// UpdateThrottlerTopoConfig runs vtctlclient UpdateThrottlerConfig.
// This retries the command until it succeeds or times out as the
// SrvKeyspace record may not yet exist for a newly created
// Keyspace that is still initializing before it becomes serving.
func UpdateThrottlerTopoConfig(clusterInstance *cluster.LocalProcessCluster, enable bool, disable bool, threshold float64, metricsQuery string, appRule *topodatapb.ThrottledAppRule) (string, error) {
rec := concurrency.AllErrorRecorder{}
var (
err error
res strings.Builder
)
for _, ks := range clusterInstance.Keyspaces {
ires, err := UpdateThrottlerTopoConfigRaw(&clusterInstance.VtctldClientProcess, ks.Name, enable, disable, threshold, metricsQuery, appRule)
if err != nil {
rec.RecordError(err)
}
res.WriteString(ires)
}
if rec.HasErrors() {
err = rec.Error()
}
return res.String(), err
}
// WaitForSrvKeyspace waits until the given srvkeyspace entry is found in the given cell
func WaitForSrvKeyspace(clusterInstance *cluster.LocalProcessCluster, cell, keyspace string) error {
args := []string{"GetSrvKeyspaceNames", cell}
ctx, cancel := context.WithTimeout(context.Background(), ConfigTimeout)
defer cancel()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
result, err := clusterInstance.VtctldClientProcess.ExecuteCommandWithOutput(args...)
if err != nil {
return err
}
if strings.Contains(result, `"`+keyspace+`"`) {
return nil
}
select {
case <-ctx.Done():
return fmt.Errorf("timed out waiting for GetSrvKeyspaceNames to contain '%v'", keyspace)
case <-ticker.C:
}
}
}
// throttleAppRaw runs vtctlclient UpdateThrottlerConfig with --throttle-app flags
// This retries the command until it succeeds or times out as the
// SrvKeyspace record may not yet exist for a newly created
// Keyspace that is still initializing before it becomes serving.
func throttleAppRaw(vtctldProcess *cluster.VtctldClientProcess, keyspaceName string, throttlerApp throttlerapp.Name, throttle bool) (result string, err error) {
args := []string{}
args = append(args, "UpdateThrottlerConfig")
if throttle {
args = append(args, "--throttle-app", throttlerApp.String())
args = append(args, "--throttle-app-duration", "1h")
} else {
args = append(args, "--unthrottle-app", throttlerApp.String())
}
args = append(args, keyspaceName)
ctx, cancel := context.WithTimeout(context.Background(), ConfigTimeout)
defer cancel()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
result, err = vtctldProcess.ExecuteCommandWithOutput(args...)
if err == nil {
return result, nil
}
select {
case <-ctx.Done():
return "", fmt.Errorf("timed out waiting for UpdateThrottlerConfig to succeed after %v; last seen value: %+v, error: %v", ConfigTimeout, result, err)
case <-ticker.C:
}
}
}
// throttleApp throttles or unthrottles an app
func throttleApp(clusterInstance *cluster.LocalProcessCluster, throttlerApp throttlerapp.Name, throttle bool) (string, error) {
rec := concurrency.AllErrorRecorder{}
var (
err error
res strings.Builder
)
for _, ks := range clusterInstance.Keyspaces {
ires, err := throttleAppRaw(&clusterInstance.VtctldClientProcess, ks.Name, throttlerApp, throttle)
if err != nil {
rec.RecordError(err)
}
res.WriteString(ires)
}
if rec.HasErrors() {
err = rec.Error()
}
return res.String(), err
}
// ThrottleApp throttles given app name for the next hour
func ThrottleApp(clusterInstance *cluster.LocalProcessCluster, throttlerApp throttlerapp.Name) (string, error) {
return throttleApp(clusterInstance, throttlerApp, true)
}
// ThrottleApp unthrottles given app name
func UnthrottleApp(clusterInstance *cluster.LocalProcessCluster, throttlerApp throttlerapp.Name) (string, error) {
return throttleApp(clusterInstance, throttlerApp, false)
}
func WaitUntilTabletsConfirmThrottledApp(t *testing.T, clusterInstance *cluster.LocalProcessCluster, throttlerApp throttlerapp.Name, expectThrottled bool) {
for _, ks := range clusterInstance.Keyspaces {
for _, shard := range ks.Shards {
for _, tablet := range shard.Vttablets {
WaitForThrottledApp(t, tablet, throttlerApp, expectThrottled, ConfigTimeout)
}
}
}
}
// ThrottleAppAndWaitUntilTabletsConfirm
func ThrottleAppAndWaitUntilTabletsConfirm(t *testing.T, clusterInstance *cluster.LocalProcessCluster, throttlerApp throttlerapp.Name) (string, error) {
res, err := throttleApp(clusterInstance, throttlerApp, true)
if err != nil {
return res, err
}
WaitUntilTabletsConfirmThrottledApp(t, clusterInstance, throttlerApp, true)
return res, nil
}
// UnthrottleAppAndWaitUntilTabletsConfirm
func UnthrottleAppAndWaitUntilTabletsConfirm(t *testing.T, clusterInstance *cluster.LocalProcessCluster, throttlerApp throttlerapp.Name) (string, error) {
res, err := throttleApp(clusterInstance, throttlerApp, false)
if err != nil {
return res, err
}
WaitUntilTabletsConfirmThrottledApp(t, clusterInstance, throttlerApp, false)
return res, nil
}
// WaitForThrottlerStatusEnabled waits for a tablet to report its throttler status as
// enabled/disabled and have the provided config (if any) until the specified timeout.
func WaitForThrottlerStatusEnabled(t *testing.T, tablet *cluster.Vttablet, enabled bool, config *Config, timeout time.Duration) {
enabledJSONPath := "IsEnabled"
queryJSONPath := "Query"
thresholdJSONPath := "Threshold"
throttlerURL := fmt.Sprintf("http://localhost:%d/throttler/status", tablet.HTTPPort)
tabletURL := fmt.Sprintf("http://localhost:%d/debug/status_details", tablet.HTTPPort)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
throttlerBody := getHTTPBody(throttlerURL)
isEnabled := gjson.Get(throttlerBody, enabledJSONPath).Bool()
if isEnabled == enabled {
if config == nil {
return
}
query := gjson.Get(throttlerBody, queryJSONPath).String()
threshold := gjson.Get(throttlerBody, thresholdJSONPath).Float()
if query == config.Query && threshold == config.Threshold {
return
}
}
// If the tablet is Not Serving due to e.g. being involved in a
// Reshard where its QueryService is explicitly disabled, then
// we should not fail the test as the throttler will not be Open.
tabletBody := getHTTPBody(tabletURL)
class := strings.ToLower(gjson.Get(tabletBody, "0.Class").String())
value := strings.ToLower(gjson.Get(tabletBody, "0.Value").String())
if class == "unhappy" && strings.Contains(value, "not serving") {
log.Infof("tablet %s is Not Serving, so ignoring throttler status as the throttler will not be Opened", tablet.Alias)
return
}
select {
case <-ctx.Done():
t.Errorf("timed out waiting for the %s tablet's throttler status enabled to be %t with the correct config after %v; last seen value: %s",
tablet.Alias, enabled, timeout, throttlerBody)
return
case <-ticker.C:
}
}
}
// WaitForThrottlerStatusEnabled waits for a tablet to report its throttler status as
// enabled/disabled and have the provided config (if any) until the specified timeout.
func WaitForThrottledApp(t *testing.T, tablet *cluster.Vttablet, throttlerApp throttlerapp.Name, expectThrottled bool, timeout time.Duration) {
throttledAppsURL := fmt.Sprintf("http://localhost:%d/throttler/throttled-apps", tablet.HTTPPort)
tabletURL := fmt.Sprintf("http://localhost:%d/debug/status_details", tablet.HTTPPort)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
throttledAppsBody := getHTTPBody(throttledAppsURL)
var throttledApps []base.AppThrottle
err := json.Unmarshal([]byte(throttledAppsBody), &throttledApps)
assert.NoError(t, err)
require.NotEmpty(t, throttledApps) // "always-throttled-app" is always there.
appFoundThrottled := false
for _, throttledApp := range throttledApps {
if throttledApp.AppName == throttlerApp.String() && throttledApp.ExpireAt.After(time.Now()) {
appFoundThrottled = true
break
}
}
if appFoundThrottled == expectThrottled {
return
}
// If the tablet is Not Serving due to e.g. being involved in a
// Reshard where its QueryService is explicitly disabled, then
// we should not fail the test as the throttler will not be Open.
tabletBody := getHTTPBody(tabletURL)
class := strings.ToLower(gjson.Get(tabletBody, "0.Class").String())
value := strings.ToLower(gjson.Get(tabletBody, "0.Value").String())
if class == "unhappy" && strings.Contains(value, "not serving") {
log.Infof("tablet %s is Not Serving, so ignoring throttler status as the throttler will not be Opened", tablet.Alias)
return
}
select {
case <-ctx.Done():
t.Errorf("timed out waiting for the %s tablet's throttled apps with the correct config (expecting %s to be %v) after %v; last seen value: %s",
tablet.Alias, throttlerApp.String(), expectThrottled, timeout, throttledAppsBody)
return
case <-ticker.C:
}
}
}
// EnableLagThrottlerAndWaitForStatus is a utility function to enable the throttler at the beginning of an endtoend test.
// The throttler is configued to use the standard replication lag metric. The function waits until the throttler is confirmed
// to be running on all tablets.
func EnableLagThrottlerAndWaitForStatus(t *testing.T, clusterInstance *cluster.LocalProcessCluster, lag time.Duration) {
_, err := UpdateThrottlerTopoConfig(clusterInstance, true, false, lag.Seconds(), "", nil)
require.NoError(t, err)
for _, ks := range clusterInstance.Keyspaces {
for _, shard := range ks.Shards {
for _, tablet := range shard.Vttablets {
WaitForThrottlerStatusEnabled(t, tablet, true, nil, time.Minute)
}
}
}
}
func getHTTPBody(url string) string {
resp, err := http.Get(url)
if err != nil {
log.Infof("http Get returns %+v", err)
return ""
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Infof("http Get returns status %d", resp.StatusCode)
return ""
}
respByte, _ := io.ReadAll(resp.Body)
body := string(respByte)
return body
}
// WaitForValidData waits for a tablet's checks to return a non 500 http response
// which indicates that it's not able to provide valid results. This is most
// commonly caused by the throttler still gathering the initial results for
// the given configuration.
func WaitForValidData(t *testing.T, tablet *cluster.Vttablet, timeout time.Duration) {
checkURL := fmt.Sprintf("http://localhost:%d/throttler/check", tablet.HTTPPort)
selfCheckURL := fmt.Sprintf("http://localhost:%d/throttler/check-self", tablet.HTTPPort)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
checkResp, checkErr := http.Get(checkURL)
if checkErr != nil {
defer checkResp.Body.Close()
}
selfCheckResp, selfCheckErr := http.Get(selfCheckURL)
if selfCheckErr != nil {
defer selfCheckResp.Body.Close()
}
if checkErr == nil && selfCheckErr == nil &&
checkResp.StatusCode != http.StatusInternalServerError &&
selfCheckResp.StatusCode != http.StatusInternalServerError {
return
}
select {
case <-ctx.Done():
t.Errorf("timed out waiting for %s tablet's throttler to return a valid result after %v; last seen value: %+v",
tablet.Alias, timeout, checkResp)
return
case <-ticker.C:
}
}
}