forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspection_result.go
1299 lines (1216 loc) · 41 KB
/
inspection_result.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 PingCAP, Inc.
//
// 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 executor
import (
"context"
"fmt"
"math"
"sort"
"strconv"
"strings"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/infoschema"
plannercore "github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/set"
"github.com/pingcap/tidb/util/sqlexec"
)
type (
// inspectionResult represents a abnormal diagnosis result
inspectionResult struct {
tp string
instance string
statusAddress string
// represents the diagnostics item, e.g: `ddl.lease` `raftstore.cpuusage`
item string
// diagnosis result value base on current cluster status
actual string
expected string
severity string
detail string
// degree only used for sort.
degree float64
}
inspectionName string
inspectionFilter struct {
set set.StringSet
timeRange plannercore.QueryTimeRange
}
inspectionRule interface {
name() string
inspect(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult
}
)
func (n inspectionName) name() string {
return string(n)
}
func (f inspectionFilter) enable(name string) bool {
return len(f.set) == 0 || f.set.Exist(name)
}
type (
// configInspection is used to check whether a same configuration item has a
// different value between different instance in the cluster
configInspection struct{ inspectionName }
// versionInspection is used to check whether the same component has different
// version in the cluster
versionInspection struct{ inspectionName }
// nodeLoadInspection is used to check the node load of memory/disk/cpu
// have reached a high-level threshold
nodeLoadInspection struct{ inspectionName }
// criticalErrorInspection is used to check are there some critical errors
// occurred in the past
criticalErrorInspection struct{ inspectionName }
// thresholdCheckInspection is used to check some threshold value, like CPU usage, leader count change.
thresholdCheckInspection struct{ inspectionName }
)
var inspectionRules = []inspectionRule{
&configInspection{inspectionName: "config"},
&versionInspection{inspectionName: "version"},
&nodeLoadInspection{inspectionName: "node-load"},
&criticalErrorInspection{inspectionName: "critical-error"},
&thresholdCheckInspection{inspectionName: "threshold-check"},
}
type inspectionResultRetriever struct {
dummyCloser
retrieved bool
extractor *plannercore.InspectionResultTableExtractor
timeRange plannercore.QueryTimeRange
instanceToStatusAddress map[string]string
statusToInstanceAddress map[string]string
}
func (e *inspectionResultRetriever) retrieve(ctx context.Context, sctx sessionctx.Context) ([][]types.Datum, error) {
if e.retrieved || e.extractor.SkipInspection {
return nil, nil
}
e.retrieved = true
// Some data of cluster-level memory tables will be retrieved many times in different inspection rules,
// and the cost of retrieving some data is expensive. We use the `TableSnapshot` to cache those data
// and obtain them lazily, and provide a consistent view of inspection tables for each inspection rules.
// All cached snapshots should be released at the end of retrieving.
sctx.GetSessionVars().InspectionTableCache = map[string]variable.TableSnapshot{}
defer func() { sctx.GetSessionVars().InspectionTableCache = nil }()
failpoint.InjectContext(ctx, "mockMergeMockInspectionTables", func() {
// Merge mock snapshots injected from failpoint for test purpose
mockTables, ok := ctx.Value("__mockInspectionTables").(map[string]variable.TableSnapshot)
if ok {
for name, snap := range mockTables {
sctx.GetSessionVars().InspectionTableCache[strings.ToLower(name)] = snap
}
}
})
if e.instanceToStatusAddress == nil {
// Get cluster info.
e.instanceToStatusAddress = make(map[string]string)
e.statusToInstanceAddress = make(map[string]string)
var rows []chunk.Row
exec := sctx.(sqlexec.RestrictedSQLExecutor)
stmt, err := exec.ParseWithParams(ctx, "select instance,status_address from information_schema.cluster_info;")
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("get cluster info failed: %v", err))
}
for _, row := range rows {
if row.Len() < 2 {
continue
}
e.instanceToStatusAddress[row.GetString(0)] = row.GetString(1)
e.statusToInstanceAddress[row.GetString(1)] = row.GetString(0)
}
}
rules := inspectionFilter{set: e.extractor.Rules}
items := inspectionFilter{set: e.extractor.Items, timeRange: e.timeRange}
var finalRows [][]types.Datum
for _, r := range inspectionRules {
name := r.name()
if !rules.enable(name) {
continue
}
results := r.inspect(ctx, sctx, items)
if len(results) == 0 {
continue
}
// make result stable
sort.Slice(results, func(i, j int) bool {
if results[i].degree != results[j].degree {
return results[i].degree > results[j].degree
}
if lhs, rhs := results[i].item, results[j].item; lhs != rhs {
return lhs < rhs
}
if results[i].actual != results[j].actual {
return results[i].actual < results[j].actual
}
if lhs, rhs := results[i].tp, results[j].tp; lhs != rhs {
return lhs < rhs
}
return results[i].instance < results[j].instance
})
for _, result := range results {
if len(result.instance) == 0 {
result.instance = e.statusToInstanceAddress[result.statusAddress]
}
if len(result.statusAddress) == 0 {
result.statusAddress = e.instanceToStatusAddress[result.instance]
}
finalRows = append(finalRows, types.MakeDatums(
name,
result.item,
result.tp,
result.instance,
result.statusAddress,
result.actual,
result.expected,
result.severity,
result.detail,
))
}
}
return finalRows, nil
}
func (c configInspection) inspect(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
var results []inspectionResult
results = append(results, c.inspectDiffConfig(ctx, sctx, filter)...)
results = append(results, c.inspectCheckConfig(ctx, sctx, filter)...)
return results
}
func (configInspection) inspectDiffConfig(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
// check the configuration consistent
ignoreConfigKey := []string{
// TiDB
"port",
"status.status-port",
"host",
"path",
"advertise-address",
"status.status-port",
"log.file.filename",
"log.slow-query-file",
"tmp-storage-path",
// PD
"advertise-client-urls",
"advertise-peer-urls",
"client-urls",
"data-dir",
"log-file",
"log.file.filename",
"metric.job",
"name",
"peer-urls",
// TiKV
"server.addr",
"server.advertise-addr",
"server.advertise-status-addr",
"server.status-addr",
"log-file",
"raftstore.raftdb-path",
"storage.data-dir",
"storage.block-cache.capacity",
}
var rows []chunk.Row
exec := sctx.(sqlexec.RestrictedSQLExecutor)
stmt, err := exec.ParseWithParams(ctx, "select type, `key`, count(distinct value) as c from information_schema.cluster_config where `key` not in (%?) group by type, `key` having c > 1", ignoreConfigKey)
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("check configuration consistency failed: %v", err))
}
generateDetail := func(tp, item string) string {
var rows []chunk.Row
stmt, err := exec.ParseWithParams(ctx, "select value, instance from information_schema.cluster_config where type=%? and `key`=%?;", tp, item)
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("check configuration consistency failed: %v", err))
return fmt.Sprintf("the cluster has different config value of %[2]s, execute the sql to see more detail: select * from information_schema.cluster_config where type='%[1]s' and `key`='%[2]s'",
tp, item)
}
m := make(map[string][]string)
for _, row := range rows {
value := row.GetString(0)
instance := row.GetString(1)
m[value] = append(m[value], instance)
}
groups := make([]string, 0, len(m))
for k, v := range m {
sort.Strings(v)
groups = append(groups, fmt.Sprintf("%s config value is %s", strings.Join(v, ","), k))
}
sort.Strings(groups)
return strings.Join(groups, "\n")
}
var results []inspectionResult
for _, row := range rows {
if filter.enable(row.GetString(1)) {
detail := generateDetail(row.GetString(0), row.GetString(1))
results = append(results, inspectionResult{
tp: row.GetString(0),
instance: "",
item: row.GetString(1), // key
actual: "inconsistent",
expected: "consistent",
severity: "warning",
detail: detail,
})
}
}
return results
}
func (c configInspection) inspectCheckConfig(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
// check the configuration in reason.
cases := []struct {
table string
tp string
key string
expect string
cond string
detail string
}{
{
table: "cluster_config",
key: "log.slow-threshold",
expect: "> 0",
cond: "type = 'tidb' and `key` = 'log.slow-threshold' and value = '0'",
detail: "slow-threshold = 0 will record every query to slow log, it may affect performance",
},
{
table: "cluster_config",
key: "raftstore.sync-log",
expect: "true",
cond: "type = 'tikv' and `key` = 'raftstore.sync-log' and value = 'false'",
detail: "sync-log should be true to avoid recover region when the machine breaks down",
},
{
table: "cluster_systeminfo",
key: "transparent_hugepage_enabled",
expect: "always madvise [never]",
cond: "system_name = 'kernel' and name = 'transparent_hugepage_enabled' and value not like '%[never]%'",
detail: "Transparent HugePages can cause memory allocation delays during runtime, TiDB recommends that you disable Transparent HugePages on all TiDB servers",
},
}
var results []inspectionResult
var rows []chunk.Row
sql := new(strings.Builder)
exec := sctx.(sqlexec.RestrictedSQLExecutor)
for _, cas := range cases {
if !filter.enable(cas.key) {
continue
}
sql.Reset()
fmt.Fprintf(sql, "select type,instance,value from information_schema.%s where %s", cas.table, cas.cond)
stmt, err := exec.ParseWithParams(ctx, sql.String())
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("check configuration in reason failed: %v", err))
}
for _, row := range rows {
results = append(results, inspectionResult{
tp: row.GetString(0),
instance: row.GetString(1),
item: cas.key,
actual: row.GetString(2),
expected: cas.expect,
severity: "warning",
detail: cas.detail,
})
}
}
results = append(results, c.checkTiKVBlockCacheSizeConfig(ctx, sctx, filter)...)
return results
}
func (c configInspection) checkTiKVBlockCacheSizeConfig(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
item := "storage.block-cache.capacity"
if !filter.enable(item) {
return nil
}
var rows []chunk.Row
exec := sctx.(sqlexec.RestrictedSQLExecutor)
stmt, err := exec.ParseWithParams(ctx, "select instance,value from information_schema.cluster_config where type='tikv' and `key` = 'storage.block-cache.capacity'")
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("check configuration in reason failed: %v", err))
}
extractIP := func(addr string) string {
if idx := strings.Index(addr, ":"); idx > -1 {
return addr[0:idx]
}
return addr
}
ipToBlockSize := make(map[string]uint64)
ipToCount := make(map[string]int)
for _, row := range rows {
ip := extractIP(row.GetString(0))
size, err := c.convertReadableSizeToByteSize(row.GetString(1))
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("check TiKV block-cache configuration in reason failed: %v", err))
return nil
}
ipToBlockSize[ip] += size
ipToCount[ip]++
}
stmt, err = exec.ParseWithParams(ctx, "select instance, value from metrics_schema.node_total_memory where time=now()")
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("check configuration in reason failed: %v", err))
}
ipToMemorySize := make(map[string]float64)
for _, row := range rows {
ip := extractIP(row.GetString(0))
size := row.GetFloat64(1)
ipToMemorySize[ip] += size
}
var results []inspectionResult
for ip, blockSize := range ipToBlockSize {
if memorySize, ok := ipToMemorySize[ip]; ok {
if float64(blockSize) > memorySize*0.45 {
detail := fmt.Sprintf("There are %v TiKV server in %v node, the total 'storage.block-cache.capacity' of TiKV is more than (0.45 * total node memory)",
ipToCount[ip], ip)
results = append(results, inspectionResult{
tp: "tikv",
instance: ip,
item: item,
actual: fmt.Sprintf("%v", blockSize),
expected: fmt.Sprintf("< %.0f", memorySize*0.45),
severity: "warning",
detail: detail,
})
}
}
}
return results
}
func (configInspection) convertReadableSizeToByteSize(sizeStr string) (uint64, error) {
const KB = uint64(1024)
const MB = KB * 1024
const GB = MB * 1024
const TB = GB * 1024
const PB = TB * 1024
rate := uint64(1)
if strings.HasSuffix(sizeStr, "KiB") {
rate = KB
} else if strings.HasSuffix(sizeStr, "MiB") {
rate = MB
} else if strings.HasSuffix(sizeStr, "GiB") {
rate = GB
} else if strings.HasSuffix(sizeStr, "TiB") {
rate = TB
} else if strings.HasSuffix(sizeStr, "PiB") {
rate = PB
}
if rate != 1 && len(sizeStr) > 3 {
sizeStr = sizeStr[:len(sizeStr)-3]
}
size, err := strconv.Atoi(sizeStr)
if err != nil {
return 0, errors.Trace(err)
}
return uint64(size) * rate, nil
}
func (versionInspection) inspect(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
exec := sctx.(sqlexec.RestrictedSQLExecutor)
var rows []chunk.Row
// check the configuration consistent
stmt, err := exec.ParseWithParams(ctx, "select type, count(distinct git_hash) as c from information_schema.cluster_info group by type having c > 1;")
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("check version consistency failed: %v", err))
}
const name = "git_hash"
var results []inspectionResult
for _, row := range rows {
if filter.enable(name) {
results = append(results, inspectionResult{
tp: row.GetString(0),
instance: "",
item: name,
actual: "inconsistent",
expected: "consistent",
severity: "critical",
detail: fmt.Sprintf("the cluster has %[1]v different %[2]s versions, execute the sql to see more detail: select * from information_schema.cluster_info where type='%[2]s'", row.GetUint64(1), row.GetString(0)),
})
}
}
return results
}
func (c nodeLoadInspection) inspect(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
var rules = []ruleChecker{
inspectCPULoad{item: "load1", tbl: "node_load1"},
inspectCPULoad{item: "load5", tbl: "node_load5"},
inspectCPULoad{item: "load15", tbl: "node_load15"},
inspectVirtualMemUsage{},
inspectSwapMemoryUsed{},
inspectDiskUsage{},
}
return checkRules(ctx, sctx, filter, rules)
}
type inspectVirtualMemUsage struct{}
func (inspectVirtualMemUsage) genSQL(timeRange plannercore.QueryTimeRange) string {
sql := fmt.Sprintf("select instance, max(value) as max_usage from metrics_schema.node_memory_usage %s group by instance having max_usage >= 70", timeRange.Condition())
return sql
}
func (i inspectVirtualMemUsage) genResult(sql string, row chunk.Row) inspectionResult {
return inspectionResult{
tp: "node",
instance: row.GetString(0),
item: i.getItem(),
actual: fmt.Sprintf("%.1f%%", row.GetFloat64(1)),
expected: "< 70%",
severity: "warning",
detail: "the memory-usage is too high",
}
}
func (inspectVirtualMemUsage) getItem() string {
return "virtual-memory-usage"
}
type inspectSwapMemoryUsed struct{}
func (inspectSwapMemoryUsed) genSQL(timeRange plannercore.QueryTimeRange) string {
sql := fmt.Sprintf("select instance, max(value) as max_used from metrics_schema.node_memory_swap_used %s group by instance having max_used > 0", timeRange.Condition())
return sql
}
func (i inspectSwapMemoryUsed) genResult(sql string, row chunk.Row) inspectionResult {
return inspectionResult{
tp: "node",
instance: row.GetString(0),
item: i.getItem(),
actual: fmt.Sprintf("%.1f", row.GetFloat64(1)),
expected: "0",
severity: "warning",
}
}
func (inspectSwapMemoryUsed) getItem() string {
return "swap-memory-used"
}
type inspectDiskUsage struct{}
func (inspectDiskUsage) genSQL(timeRange plannercore.QueryTimeRange) string {
sql := fmt.Sprintf("select instance, device, max(value) as max_usage from metrics_schema.node_disk_usage %v and device like '/%%' group by instance, device having max_usage >= 70", timeRange.Condition())
return sql
}
func (i inspectDiskUsage) genResult(sql string, row chunk.Row) inspectionResult {
return inspectionResult{
tp: "node",
instance: row.GetString(0),
item: i.getItem(),
actual: fmt.Sprintf("%.1f%%", row.GetFloat64(2)),
expected: "< 70%",
severity: "warning",
detail: "the disk-usage of " + row.GetString(1) + " is too high",
}
}
func (inspectDiskUsage) getItem() string {
return "disk-usage"
}
type inspectCPULoad struct {
item string
tbl string
}
func (i inspectCPULoad) genSQL(timeRange plannercore.QueryTimeRange) string {
sql := fmt.Sprintf(`select t1.instance, t1.max_load , 0.7*t2.cpu_count from
(select instance,max(value) as max_load from metrics_schema.%[1]s %[2]s group by instance) as t1 join
(select instance,max(value) as cpu_count from metrics_schema.node_virtual_cpus %[2]s group by instance) as t2
on t1.instance=t2.instance where t1.max_load>(0.7*t2.cpu_count);`, i.tbl, timeRange.Condition())
return sql
}
func (i inspectCPULoad) genResult(sql string, row chunk.Row) inspectionResult {
return inspectionResult{
tp: "node",
instance: row.GetString(0),
item: "cpu-" + i.item,
actual: fmt.Sprintf("%.1f", row.GetFloat64(1)),
expected: fmt.Sprintf("< %.1f", row.GetFloat64(2)),
severity: "warning",
detail: i.getItem() + " should less than (cpu_logical_cores * 0.7)",
}
}
func (i inspectCPULoad) getItem() string {
return "cpu-" + i.item
}
func (c criticalErrorInspection) inspect(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
results := c.inspectError(ctx, sctx, filter)
results = append(results, c.inspectForServerDown(ctx, sctx, filter)...)
return results
}
func (criticalErrorInspection) inspectError(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
var rules = []struct {
tp string
item string
tbl string
}{
{tp: "tikv", item: "critical-error", tbl: "tikv_critical_error_total_count"},
{tp: "tidb", item: "panic-count", tbl: "tidb_panic_count_total_count"},
{tp: "tidb", item: "binlog-error", tbl: "tidb_binlog_error_total_count"},
{tp: "tikv", item: "scheduler-is-busy", tbl: "tikv_scheduler_is_busy_total_count"},
{tp: "tikv", item: "coprocessor-is-busy", tbl: "tikv_coprocessor_is_busy_total_count"},
{tp: "tikv", item: "channel-is-full", tbl: "tikv_channel_full_total_count"},
{tp: "tikv", item: "tikv_engine_write_stall", tbl: "tikv_engine_write_stall"},
}
condition := filter.timeRange.Condition()
var results []inspectionResult
var rows []chunk.Row
exec := sctx.(sqlexec.RestrictedSQLExecutor)
sql := new(strings.Builder)
for _, rule := range rules {
if filter.enable(rule.item) {
def, found := infoschema.MetricTableMap[rule.tbl]
if !found {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("metrics table: %s not found", rule.tbl))
continue
}
sql.Reset()
fmt.Fprintf(sql, "select `%[1]s`,sum(value) as total from `%[2]s`.`%[3]s` %[4]s group by `%[1]s` having total>=1.0",
strings.Join(def.Labels, "`,`"), util.MetricSchemaName.L, rule.tbl, condition)
stmt, err := exec.ParseWithParams(ctx, sql.String())
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("execute '%s' failed: %v", sql, err))
continue
}
for _, row := range rows {
var actual, detail string
var degree float64
if rest := def.Labels[1:]; len(rest) > 0 {
values := make([]string, 0, len(rest))
// `i+1` and `1+len(rest)` means skip the first field `instance`
for i := range rest {
values = append(values, row.GetString(i+1))
}
// TODO: find a better way to construct the `actual` field
actual = fmt.Sprintf("%.2f(%s)", row.GetFloat64(1+len(rest)), strings.Join(values, ", "))
degree = row.GetFloat64(1 + len(rest))
} else {
actual = fmt.Sprintf("%.2f", row.GetFloat64(1))
degree = row.GetFloat64(1)
}
detail = fmt.Sprintf("the total number of errors about '%s' is too many", rule.item)
result := inspectionResult{
tp: rule.tp,
// NOTE: all tables which can be inspected here whose first label must be `instance`
statusAddress: row.GetString(0),
item: rule.item,
actual: actual,
expected: "0",
severity: "critical",
detail: detail,
degree: degree,
}
results = append(results, result)
}
}
}
return results
}
func (criticalErrorInspection) inspectForServerDown(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
item := "server-down"
if !filter.enable(item) {
return nil
}
condition := filter.timeRange.Condition()
exec := sctx.(sqlexec.RestrictedSQLExecutor)
sql := new(strings.Builder)
fmt.Fprintf(sql, `select t1.job,t1.instance, t2.min_time from
(select instance,job from metrics_schema.up %[1]s group by instance,job having max(value)-min(value)>0) as t1 join
(select instance,min(time) as min_time from metrics_schema.up %[1]s and value=0 group by instance,job) as t2 on t1.instance=t2.instance order by job`, condition)
var rows []chunk.Row
stmt, err := exec.ParseWithParams(ctx, sql.String())
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("execute '%s' failed: %v", sql, err))
}
var results []inspectionResult
for _, row := range rows {
if row.Len() < 3 {
continue
}
detail := fmt.Sprintf("%s %s disconnect with prometheus around time '%s'", row.GetString(0), row.GetString(1), row.GetTime(2))
result := inspectionResult{
tp: row.GetString(0),
statusAddress: row.GetString(1),
item: item,
actual: "",
expected: "",
severity: "critical",
detail: detail,
degree: 10000 + float64(len(results)),
}
results = append(results, result)
}
// Check from log.
sql.Reset()
fmt.Fprintf(sql, "select type,instance,time from information_schema.cluster_log %s and level = 'info' and message like '%%Welcome to'", condition)
stmt, err = exec.ParseWithParams(ctx, sql.String())
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("execute '%s' failed: %v", sql, err))
}
for _, row := range rows {
if row.Len() < 3 {
continue
}
detail := fmt.Sprintf("%s %s restarted at time '%s'", row.GetString(0), row.GetString(1), row.GetString(2))
result := inspectionResult{
tp: row.GetString(0),
instance: row.GetString(1),
item: item,
actual: "",
expected: "",
severity: "critical",
detail: detail,
degree: 10000 + float64(len(results)),
}
results = append(results, result)
}
return results
}
func (c thresholdCheckInspection) inspect(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
inspects := []func(context.Context, sessionctx.Context, inspectionFilter) []inspectionResult{
c.inspectThreshold1,
c.inspectThreshold2,
c.inspectThreshold3,
c.inspectForLeaderDrop,
}
var results []inspectionResult
for _, inspect := range inspects {
re := inspect(ctx, sctx, filter)
results = append(results, re...)
}
return results
}
func (thresholdCheckInspection) inspectThreshold1(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
var rules = []struct {
item string
component string
configKey string
threshold float64
}{
{
item: "coprocessor-normal-cpu",
component: "cop_normal%",
configKey: "readpool.coprocessor.normal-concurrency",
threshold: 0.9},
{
item: "coprocessor-high-cpu",
component: "cop_high%",
configKey: "readpool.coprocessor.high-concurrency",
threshold: 0.9,
},
{
item: "coprocessor-low-cpu",
component: "cop_low%",
configKey: "readpool.coprocessor.low-concurrency",
threshold: 0.9,
},
{
item: "grpc-cpu",
component: "grpc%",
configKey: "server.grpc-concurrency",
threshold: 0.9,
},
{
item: "raftstore-cpu",
component: "raftstore_%",
configKey: "raftstore.store-pool-size",
threshold: 0.8,
},
{
item: "apply-cpu",
component: "apply_%",
configKey: "raftstore.apply-pool-size",
threshold: 0.8,
},
{
item: "storage-readpool-normal-cpu",
component: "store_read_norm%",
configKey: "readpool.storage.normal-concurrency",
threshold: 0.9,
},
{
item: "storage-readpool-high-cpu",
component: "store_read_high%",
configKey: "readpool.storage.high-concurrency",
threshold: 0.9,
},
{
item: "storage-readpool-low-cpu",
component: "store_read_low%",
configKey: "readpool.storage.low-concurrency",
threshold: 0.9,
},
{
item: "scheduler-worker-cpu",
component: "sched_%",
configKey: "storage.scheduler-worker-pool-size",
threshold: 0.85,
},
{
item: "split-check-cpu",
component: "split_check",
threshold: 0.9,
},
}
condition := filter.timeRange.Condition()
var results []inspectionResult
var rows []chunk.Row
exec := sctx.(sqlexec.RestrictedSQLExecutor)
sql := new(strings.Builder)
for _, rule := range rules {
if !filter.enable(rule.item) {
continue
}
sql.Reset()
if len(rule.configKey) > 0 {
fmt.Fprintf(sql, `select t1.status_address, t1.cpu, (t2.value * %[2]f) as threshold, t2.value from
(select status_address, max(sum_value) as cpu from (select instance as status_address, sum(value) as sum_value from metrics_schema.tikv_thread_cpu %[4]s and name like '%[1]s' group by instance, time) as tmp group by tmp.status_address) as t1 join
(select instance, value from information_schema.cluster_config where type='tikv' and %[5]s = '%[3]s') as t2 join
(select instance,status_address from information_schema.cluster_info where type='tikv') as t3
on t1.status_address=t3.status_address and t2.instance=t3.instance where t1.cpu > (t2.value * %[2]f)`, rule.component, rule.threshold, rule.configKey, condition, "`key`")
} else {
fmt.Fprintf(sql, `select t1.instance, t1.cpu, %[2]f from
(select instance, max(value) as cpu from metrics_schema.tikv_thread_cpu %[3]s and name like '%[1]s' group by instance) as t1
where t1.cpu > %[2]f;`, rule.component, rule.threshold, condition)
}
stmt, err := exec.ParseWithParams(ctx, sql.String())
if err == nil {
rows, _, err = exec.ExecRestrictedStmt(ctx, stmt)
}
if err != nil {
sctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("execute '%s' failed: %v", sql, err))
continue
}
for _, row := range rows {
actual := fmt.Sprintf("%.2f", row.GetFloat64(1))
degree := math.Abs(row.GetFloat64(1)-row.GetFloat64(2)) / math.Max(row.GetFloat64(1), row.GetFloat64(2))
expected := ""
if len(rule.configKey) > 0 {
expected = fmt.Sprintf("< %.2f, config: %v=%v", row.GetFloat64(2), rule.configKey, row.GetString(3))
} else {
expected = fmt.Sprintf("< %.2f", row.GetFloat64(2))
}
detail := fmt.Sprintf("the '%s' max cpu-usage of %s tikv is too high", rule.item, row.GetString(0))
result := inspectionResult{
tp: "tikv",
statusAddress: row.GetString(0),
item: rule.item,
actual: actual,
expected: expected,
severity: "warning",
detail: detail,
degree: degree,
}
results = append(results, result)
}
}
return results
}
func (thresholdCheckInspection) inspectThreshold2(ctx context.Context, sctx sessionctx.Context, filter inspectionFilter) []inspectionResult {
var rules = []struct {
tp string
item string
tbl string
condition string
threshold float64
factor float64
isMin bool
detail string
}{
{
tp: "tidb",
item: "tso-duration",
tbl: "pd_tso_wait_duration",
condition: "quantile=0.999",
threshold: 0.05,
},
{
tp: "tidb",
item: "get-token-duration",
tbl: "tidb_get_token_duration",
condition: "quantile=0.999",
threshold: 0.001,
factor: 10e5, // the unit is microsecond
},
{
tp: "tidb",
item: "load-schema-duration",
tbl: "tidb_load_schema_duration",
condition: "quantile=0.99",
threshold: 1,
},
{
tp: "tikv",
item: "scheduler-cmd-duration",
tbl: "tikv_scheduler_command_duration",
condition: "quantile=0.99",
threshold: 0.1,
},
{
tp: "tikv",
item: "handle-snapshot-duration",
tbl: "tikv_handle_snapshot_duration",
threshold: 30,
},
{
tp: "tikv",
item: "storage-write-duration",
tbl: "tikv_storage_async_request_duration",
condition: "type='write'",
threshold: 0.1,
},
{
tp: "tikv",
item: "storage-snapshot-duration",
tbl: "tikv_storage_async_request_duration",
condition: "type='snapshot'",
threshold: 0.05,
},
{
tp: "tikv",
item: "rocksdb-write-duration",
tbl: "tikv_engine_write_duration",
condition: "type='write_max'",
threshold: 0.1,
factor: 10e5, // the unit is microsecond
},
{
tp: "tikv",
item: "rocksdb-get-duration",
tbl: "tikv_engine_max_get_duration",
condition: "type='get_max'",
threshold: 0.05,
factor: 10e5,
},
{
tp: "tikv",
item: "rocksdb-seek-duration",
tbl: "tikv_engine_max_seek_duration",
condition: "type='seek_max'",
threshold: 0.05,
factor: 10e5, // the unit is microsecond
},
{
tp: "tikv",
item: "scheduler-pending-cmd-count",
tbl: "tikv_scheduler_pending_commands",
threshold: 1000,
detail: " %s tikv scheduler has too many pending commands",
},
{
tp: "tikv",
item: "index-block-cache-hit",
tbl: "tikv_block_index_cache_hit",
condition: "value > 0",
threshold: 0.95,
isMin: true,
},
{
tp: "tikv",