-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathreport.go
2412 lines (2264 loc) · 87.8 KB
/
report.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 2020 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package diagnose
import (
"bytes"
"fmt"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/jinzhu/gorm"
"github.com/pingcap-incubator/tidb-dashboard/pkg/dbstore"
)
type TableDef struct {
Category []string // The category of the table, such as [TiDB]
Title string
Comment string // English Comment
joinColumns []int
compareColumns []int
Column []string // Column name
Rows []TableRowDef
}
type TableRowDef struct {
Values []string
SubValues [][]string // SubValues need fold default.
ratio float64
Comment string
}
func (t TableDef) ColumnWidth() []int {
fieldLen := make([]int, 0, len(t.Column))
if len(t.Rows) == 0 {
return fieldLen
}
for i := 0; i < len(t.Column); i++ {
l := 0
for _, row := range t.Rows {
if l < len(row.Values[i]) {
l = len(row.Values[i])
}
for _, subRow := range row.SubValues {
if l < len(subRow[i]) {
l = len(subRow[i])
}
}
}
for _, col := range t.Column {
if l < len(col) {
l = len(col)
}
}
fieldLen = append(fieldLen, l)
}
return fieldLen
}
const (
// Category names.
CategoryHeader = "header"
CategoryDiagnose = "diagnose"
CategoryLoad = "load"
CategoryOverview = "overview"
CategoryTiDB = "TiDB"
CategoryPD = "PD"
CategoryTiKV = "TiKV"
CategoryConfig = "config"
CategoryError = "error"
)
func GetReportTablesForDisplay(startTime, endTime string, db *gorm.DB, sqliteDB *dbstore.DB, reportID string) []*TableDef {
errRows := checkBeforeReport(db)
if len(errRows) > 0 {
return []*TableDef{GenerateReportError(errRows)}
}
tables := GetReportTables(startTime, endTime, db, sqliteDB, reportID)
lastCategory := ""
for _, tbl := range tables {
if tbl == nil {
continue
}
category := strings.Join(tbl.Category, ",")
if category != lastCategory {
lastCategory = category
} else {
tbl.Category = []string{""}
}
}
return tables
}
func checkBeforeReport(db *gorm.DB) (errRows []TableRowDef) {
command := "you can use this shell command to set the config: `curl -X POST -d '{\"metric-storage\":\"http://{PROMETHEUS_ADDRESS}\"}' http://{PD_ADDRESS}/pd/api/v1/config`, \n" +
"PROMETHEUS_ADDRESS is the prometheus address, It's used for query metric data; PD_ADDRESS is the HTTP API address of PD server, all PD servers need to set this config. \n" +
"Here is an example: `curl -X POST -d '{\"metric-storage\":\"http://127.0.0.1:9090\"}' http://127.0.0.1:2379/pd/api/v1/config`"
// Check for query metric.
sql := "select count(*) from metrics_schema.up;"
_, err := querySQL(db, sql)
if err != nil {
errRows = append(errRows, TableRowDef{
Values: []string{
"check before report",
"metrics_schema.up",
err.Error() + ", \n" +
"Currently, the PD config `pd-server.metric-storage` value should be prometheus address, please check whether the config value is correct, you can use below sql check the value: \n" +
"select * from information_schema.cluster_config where type='pd' and `key` ='pd-server.metric-storage'; , \n" + command,
},
})
return
}
return nil
}
type getTableFunc = func(string, string, *gorm.DB) (TableDef, error)
func GetReportTables(startTime, endTime string, db *gorm.DB, sqliteDB *dbstore.DB, reportID string) []*TableDef {
funcs := []getTableFunc{
// Header
GetHeaderTimeTable,
GetClusterHardwareInfoTable,
GetClusterInfoTable,
// Diagnose
GetDiagnoseReport,
// Load
GetLoadTable,
GetCPUUsageTable,
GetProcessMemUsageTable,
GetTiKVThreadCPUTable,
GetGoroutinesCountTable,
// Overview
GetTotalTimeConsumeTable,
GetTotalErrorTable,
// TiDB
GetTiDBTimeConsumeTable,
GetTiDBConnectionCountTable,
GetTiDBTxnTableData,
GetTiDBStatisticsInfo,
GetTiDBDDLOwner,
GetTiDBTopNSlowQuery,
GetTiDBTopNSlowQueryGroupByDigest,
GetTiDBSlowQueryWithDiffPlan,
// PD
GetPDTimeConsumeTable,
GetPDSchedulerInfo,
GetPDClusterStatusTable,
GetStoreStatusTable,
GetPDEtcdStatusTable,
// TiKV
GetTiKVTotalTimeConsumeTable,
GetTiKVRocksDBTimeConsumeTable,
GetTiKVErrorTable,
GetTiKVStoreInfo,
GetTiKVRegionSizeInfo,
GetTiKVCopInfo,
GetTiKVSchedulerInfo,
GetTiKVRaftInfo,
GetTiKVSnapshotInfo,
GetTiKVGCInfo,
GetTiKVTaskInfo,
GetTiKVCacheHitTable,
// Config
GetPDConfigInfo,
GetPDConfigChangeInfo,
GetTiDBGCConfigInfo,
GetTiDBGCConfigChangeInfo,
GetTiKVRocksDBConfigInfo,
GetTiKVRocksDBConfigChangeInfo,
GetTiKVRaftStoreConfigInfo,
GetTiKVRaftStoreConfigChangeInfo,
GetTiDBCurrentConfig,
GetPDCurrentConfig,
GetTiKVCurrentConfig,
}
var progress int32
totalTableCount := int32(len(funcs))
tables, errRows := getTablesParallel(startTime, endTime, db, funcs, sqliteDB, reportID, &progress, &totalTableCount)
tables = append(tables, GenerateReportError(errRows))
return tables
}
func getTablesParallel(startTime, endTime string, db *gorm.DB, funcs []getTableFunc, sqliteDB *dbstore.DB, reportID string, progress, totalTableCount *int32) ([]*TableDef, []TableRowDef) {
// get the local CPU count for concurrence
conc := runtime.NumCPU()
if conc > 20 {
conc = 20
}
if conc > len(funcs) {
conc = len(funcs)
}
taskChan := func2task(funcs)
resChan := make(chan *tblAndErr, len(funcs))
var wg sync.WaitGroup
//get table concurrently
for i := 0; i < conc; i++ {
wg.Add(1)
go doGetTable(taskChan, resChan, &wg, startTime, endTime, db, sqliteDB, reportID, progress, totalTableCount)
}
wg.Wait()
// all task done, close the resChan
close(resChan)
tblAndErrSlice := make([]tblAndErr, 0, cap(resChan))
for tblAndErr := range resChan {
tblAndErrSlice = append(tblAndErrSlice, *tblAndErr)
}
sort.Slice(tblAndErrSlice, func(i, j int) bool {
return tblAndErrSlice[i].taskID < tblAndErrSlice[j].taskID
})
tables := make([]*TableDef, 0, len(tblAndErrSlice)+1)
errRows := make([]TableRowDef, 0, len(tblAndErrSlice))
for _, v := range tblAndErrSlice {
if v.tbl != nil {
tables = append(tables, v.tbl)
}
if v.err != nil {
errRows = append(errRows, *v.err)
}
}
return tables, errRows
}
type tblAndErr struct {
tbl *TableDef
err *TableRowDef
taskID int
}
// 1.doGetTable gets the task from taskChan,and close the taskChan if taskChan is empty.
// 2.doGetTable puts the tblAndErr result to resChan.
// 3.if taskChan is empty, put a true in doneChan.
func doGetTable(taskChan chan *task, resChan chan *tblAndErr, wg *sync.WaitGroup, startTime, endTime string, db *gorm.DB, sqliteDB *dbstore.DB, reportID string, progress, totalTableCount *int32) {
defer wg.Done()
for task := range taskChan {
f := task.t
var tbl TableDef
var err error
func() {
defer func() {
if r := recover(); r != nil {
tbl.Title = fmt.Sprintf("panic_in_table_%v", task.taskID)
err = fmt.Errorf("panic: %v", r)
}
}()
tbl, err = f(startTime, endTime, db)
}()
newProgress := atomic.AddInt32(progress, 1)
tblAndErr := tblAndErr{}
if err != nil {
category := strings.Join(tbl.Category, ",")
tblAndErr.err = &TableRowDef{Values: []string{category, tbl.Title, err.Error()}}
}
if tbl.Rows != nil {
tblAndErr.tbl = &tbl
}
tblAndErr.taskID = task.taskID
resChan <- &tblAndErr
if sqliteDB != nil {
_ = UpdateReportProgress(sqliteDB, reportID, int((newProgress*100)/atomic.LoadInt32(totalTableCount)))
}
}
}
type task struct {
t getTableFunc
taskID int // taskID for arrange the tables in order
}
//change the get-Table-func to task
func func2task(funcs []getTableFunc) chan *task {
taskChan := make(chan *task, len(funcs))
for i := 0; i < len(funcs); i++ {
taskChan <- &task{funcs[i], i}
}
close(taskChan)
return taskChan
}
func GenerateReportError(errRows []TableRowDef) *TableDef {
return &TableDef{
Category: []string{CategoryError},
Title: "generate_report_error",
Comment: "",
Column: []string{"CATEGORY", "TABLE", "ERROR"},
Rows: errRows,
}
}
func GetHeaderTimeTable(startTime, endTime string, db *gorm.DB) (TableDef, error) {
return TableDef{
Category: []string{CategoryHeader},
Title: "report_time_range",
Comment: "",
Column: []string{"START_TIME", "END_TIME"},
Rows: []TableRowDef{
{Values: []string{startTime, endTime}},
},
}, nil
}
func GetDiagnoseReport(startTime, endTime string, db *gorm.DB) (TableDef, error) {
table := TableDef{
Category: []string{CategoryDiagnose},
Title: "diagnose",
Comment: "",
Column: []string{"RULE", "ITEM", "TYPE", "INSTANCE", "STATUS_ADDRESS", "VALUE", "REFERENCE", "SEVERITY", "DETAILS"},
}
sql := fmt.Sprintf("select /*+ time_range('%s','%s') */ %s from information_schema.INSPECTION_RESULT", startTime, endTime, strings.Join(table.Column, ","))
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
newRows := make([]TableRowDef, 0, len(rows))
rowIdxMap := make(map[string]int)
for _, row := range rows {
if len(row.Values) < len(table.Column) {
continue
}
// rule + item
name := row.Values[0] + row.Values[1]
idx, ok := rowIdxMap[name]
if ok && idx < len(newRows) {
newRows[idx].SubValues = append(newRows[idx].SubValues, row.Values)
continue
}
newRows = append(newRows, row)
rowIdxMap[name] = len(newRows) - 1
}
table.Rows = newRows
return table, nil
}
func GetTotalTimeConsumeTable(startTime, endTime string, db *gorm.DB) (TableDef, error) {
defs1 := []totalTimeByLabelsTableDef{
{name: "tidb_query", tbl: "tidb_query", labels: []string{"sql_type"}},
{name: "tidb_get_token(us)", tbl: "tidb_get_token", labels: []string{"instance"}},
{name: "tidb_parse", tbl: "tidb_parse", labels: []string{"sql_type"}},
{name: "tidb_compile", tbl: "tidb_compile", labels: []string{"sql_type"}},
{name: "tidb_execute", tbl: "tidb_execute", labels: []string{"sql_type"}},
{name: "tidb_distsql_execution", tbl: "tidb_distsql_execution", labels: []string{"type"}},
{name: "tidb_cop", tbl: "tidb_cop", labels: []string{"instance"}},
{name: "tidb_transaction", tbl: "tidb_transaction", labels: []string{"sql_type"}},
{name: "tidb_transaction_local_latch_wait", tbl: "tidb_transaction_local_latch_wait", labels: []string{"instance"}},
{name: "tidb_kv_backoff", tbl: "tidb_kv_backoff", labels: []string{"type"}},
{name: "tidb_kv_request", tbl: "tidb_kv_request", labels: []string{"type"}},
{name: "tidb_slow_query", tbl: "tidb_slow_query", labels: []string{"instance"}},
{name: "tidb_slow_query_cop_process", tbl: "tidb_slow_query_cop_process", labels: []string{"instance"}},
{name: "tidb_slow_query_cop_wait", tbl: "tidb_slow_query_cop_wait", labels: []string{"instance"}},
{name: "tidb_ddl_handle_job", tbl: "tidb_ddl", labels: []string{"type"}},
{name: "tidb_ddl_worker", tbl: "tidb_ddl_worker", labels: []string{"action"}},
{name: "tidb_ddl_update_self_version", tbl: "tidb_ddl_update_self_version", labels: []string{"result"}},
{name: "tidb_owner_handle_syncer", tbl: "tidb_owner_handle_syncer", labels: []string{"type"}},
{name: "tidb_ddl_batch_add_index", tbl: "tidb_ddl_batch_add_index", labels: []string{"type"}},
{name: "tidb_ddl_deploy_syncer", tbl: "tidb_ddl_deploy_syncer", labels: []string{"type"}},
{name: "tidb_load_schema", tbl: "tidb_load_schema", labels: []string{"instance"}},
{name: "tidb_meta_operation", tbl: "tidb_meta_operation", labels: []string{"type"}},
{name: "tidb_auto_id_request", tbl: "tidb_auto_id_request", labels: []string{"type"}},
{name: "tidb_statistics_auto_analyze", tbl: "tidb_statistics_auto_analyze", labels: []string{"instance"}},
{name: "tidb_gc", tbl: "tidb_gc", labels: []string{"instance"}},
{name: "tidb_gc_push_task", tbl: "tidb_gc_push_task", labels: []string{"type"}},
{name: "tidb_batch_client_unavailable", tbl: "tidb_batch_client_unavailable", labels: []string{"instance"}},
{name: "tidb_batch_client_wait", tbl: "tidb_batch_client_wait", labels: []string{"instance"}},
// PD
{name: "pd_tso_rpc", tbl: "pd_tso_rpc", labels: []string{"instance"}},
{name: "pd_tso_wait", tbl: "pd_tso_wait", labels: []string{"instance"}},
{name: "pd_client_cmd", tbl: "pd_client_cmd", labels: []string{"type"}},
{name: "pd_client_request_rpc", tbl: "pd_request_rpc", labels: []string{"type"}},
{name: "pd_grpc_completed_commands", tbl: "pd_grpc_completed_commands", labels: []string{"grpc_method"}},
{name: "pd_operator_finish", tbl: "pd_operator_finish", labels: []string{"type"}},
{name: "pd_operator_step_finish", tbl: "pd_operator_step_finish", labels: []string{"type"}},
{name: "pd_handle_transactions", tbl: "pd_handle_transactions", labels: []string{"result"}},
{name: "pd_region_heartbeat", tbl: "pd_region_heartbeat", labels: []string{"address"}},
{name: "etcd_wal_fsync", tbl: "etcd_wal_fsync", labels: []string{"instance"}},
{name: "pd_peer_round_trip", tbl: "pd_peer_round_trip", labels: []string{"To"}},
// TiKV
{name: "tikv_grpc_messge", tbl: "tikv_grpc_messge", labels: []string{"type"}},
{name: "tikv_cop_request", tbl: "tikv_cop_request", labels: []string{"req"}},
{name: "tikv_cop_handle", tbl: "tikv_cop_handle", labels: []string{"req"}},
{name: "tikv_cop_wait", tbl: "tikv_cop_wait", labels: []string{"req"}},
{name: "tikv_scheduler_command", tbl: "tikv_scheduler_command", labels: []string{"type"}},
{name: "tikv_scheduler_latch_wait", tbl: "tikv_scheduler_latch_wait", labels: []string{"type"}},
{name: "tikv_storage_async_request", tbl: "tikv_storage_async_request", labels: []string{"type"}},
{name: "tikv_raft_propose_wait", tbl: "tikv_propose_wait", labels: []string{"instance"}},
{name: "tikv_raft_process", tbl: "tikv_process", labels: []string{"type"}},
{name: "tikv_raft_append_log", tbl: "tikv_append_log", labels: []string{"instance"}},
{name: "tikv_raft_commit_log", tbl: "tikv_commit_log", labels: []string{"instance"}},
{name: "tikv_raft_apply_wait", tbl: "tikv_apply_wait", labels: []string{"instance"}},
{name: "tikv_raft_apply_log", tbl: "tikv_apply_log", labels: []string{"instance"}},
{name: "tikv_raft_store_events", tbl: "tikv_raft_store_events", labels: []string{"type"}},
{name: "tikv_handle_snapshot", tbl: "tikv_handle_snapshot", labels: []string{"type"}},
{name: "tikv_send_snapshot", tbl: "tikv_send_snapshot", labels: []string{"instance"}},
{name: "tikv_check_split", tbl: "tikv_check_split", labels: []string{"instance"}},
{name: "tikv_ingest_sst", tbl: "tikv_ingest_sst", labels: []string{"instance"}},
{name: "tikv_gc_tasks", tbl: "tikv_gc_tasks", labels: []string{"task"}},
{name: "tikv_pd_request", tbl: "tikv_pd_request", labels: []string{"type"}},
{name: "tikv_lock_manager_deadlock_detect", tbl: "tikv_lock_manager_deadlock_detect", labels: []string{"instance"}},
{name: "tikv_lock_manager_waiter_lifetime", tbl: "tikv_lock_manager_waiter_lifetime", labels: []string{"instance"}},
{name: "tikv_backup_range", tbl: "tikv_backup_range", labels: []string{"type"}},
{name: "tikv_backup", tbl: "tikv_backup", labels: []string{"instance"}},
}
defs := make([]rowQuery, 0, len(defs1))
for i := range defs1 {
defs = append(defs, defs1[i])
}
table := TableDef{
Category: []string{CategoryOverview},
Title: "total_time_consume",
Comment: ``,
joinColumns: []int{0, 1},
compareColumns: []int{3, 4, 5},
Column: []string{"METRIC_NAME", "LABEL", "TIME_RATIO", "TOTAL_TIME", "TOTAL_COUNT", "P999", "P99", "P90", "P80"},
}
resultRows := make([]TableRowDef, 0, len(defs))
arg := newQueryArg(startTime, endTime)
specialHandle := func(row []string) []string {
if arg.totalTime == 0 && len(row[3]) > 0 {
totalTime, err := strconv.ParseFloat(row[3], 64)
if err == nil {
arg.totalTime = totalTime
}
}
return row
}
appendRows := func(row TableRowDef) {
row.Values = specialHandle(row.Values)
for i := range row.SubValues {
row.SubValues[i] = specialHandle(row.SubValues[i])
}
resultRows = append(resultRows, row)
}
err := getTableRows(defs, arg, db, appendRows)
if err != nil {
return table, err
}
table.Rows = resultRows
return table, nil
}
func GetTotalErrorTable(startTime, endTime string, db *gorm.DB) (TableDef, error) {
defs1 := []sumValueQuery{
{tbl: "tidb_binlog_error_total_count", labels: []string{"instance"}},
{tbl: "tidb_handshake_error_total_count", labels: []string{"instance"}},
{tbl: "tidb_transaction_retry_error_total_count", labels: []string{"sql_type"}},
{tbl: "tidb_kv_region_error_total_count", labels: []string{"type"}},
{tbl: "tidb_schema_lease_error_total_count", labels: []string{"instance"}},
{tbl: "tikv_grpc_error_total_count", labels: []string{"type"}},
{tbl: "tikv_critical_error_total_count", labels: []string{"type"}},
{tbl: "tikv_scheduler_is_busy_total_count", labels: []string{"type"}},
{tbl: "tikv_channel_full_total_count", labels: []string{"type"}},
{tbl: "tikv_coprocessor_request_error_total_count", labels: []string{"reason"}},
{tbl: "tikv_engine_write_stall", labels: []string{"instance"}},
{tbl: "tikv_server_report_failures_total_count", labels: []string{"instance"}},
{name: "tikv_storage_async_request_error", tbl: "tikv_storage_async_requests_total_count", labels: []string{"type"}, condition: "status not in ('all','success')"},
{tbl: "tikv_lock_manager_detect_error_total_count", labels: []string{"type"}},
{tbl: "tikv_backup_errors_total_count", labels: []string{"error"}},
{tbl: "node_network_in_errors_total_count", labels: []string{"instance"}},
{tbl: "node_network_out_errors_total_count", labels: []string{"instance"}},
}
table := TableDef{
Category: []string{CategoryOverview},
Title: "total_error",
Comment: ``,
joinColumns: []int{0, 1},
compareColumns: []int{2},
Column: []string{"METRIC_NAME", "LABEL", "TOTAL_COUNT"},
}
rows, err := getSumValueTableData(defs1, startTime, endTime, db)
if err != nil {
return table, err
}
table.Rows = rows
return table, nil
}
func GetTiDBTimeConsumeTable(startTime, endTime string, db *gorm.DB) (TableDef, error) {
defs1 := []totalTimeByLabelsTableDef{
{name: "tidb_query", tbl: "tidb_query", labels: []string{"instance", "sql_type"}},
{name: "tidb_get_token(us)", tbl: "tidb_get_token", labels: []string{"instance"}},
{name: "tidb_parse", tbl: "tidb_parse", labels: []string{"instance", "sql_type"}},
{name: "tidb_compile", tbl: "tidb_compile", labels: []string{"instance", "sql_type"}},
{name: "tidb_execute", tbl: "tidb_execute", labels: []string{"instance", "sql_type"}},
{name: "tidb_distsql_execution", tbl: "tidb_distsql_execution", labels: []string{"instance", "type"}},
{name: "tidb_cop", tbl: "tidb_cop", labels: []string{"instance"}},
{name: "tidb_transaction", tbl: "tidb_transaction", labels: []string{"instance", "sql_type", "type"}},
{name: "tidb_transaction_local_latch_wait", tbl: "tidb_transaction_local_latch_wait", labels: []string{"instance"}},
{name: "tidb_kv_backoff", tbl: "tidb_kv_backoff", labels: []string{"instance", "type"}},
{name: "tidb_kv_request", tbl: "tidb_kv_request", labels: []string{"instance", "store", "type"}},
{name: "tidb_slow_query", tbl: "tidb_slow_query", labels: []string{"instance"}},
{name: "tidb_slow_query_cop_process", tbl: "tidb_slow_query_cop_process", labels: []string{"instance"}},
{name: "tidb_slow_query_cop_wait", tbl: "tidb_slow_query_cop_wait", labels: []string{"instance"}},
{name: "tidb_ddl_handle_job", tbl: "tidb_ddl", labels: []string{"instance", "type"}},
{name: "tidb_ddl_worker", tbl: "tidb_ddl_worker", labels: []string{"instance", "type", "result", "action"}},
{name: "tidb_ddl_update_self_version", tbl: "tidb_ddl_update_self_version", labels: []string{"instance", "result"}},
{name: "tidb_owner_handle_syncer", tbl: "tidb_owner_handle_syncer", labels: []string{"instance", "type", "result"}},
{name: "tidb_ddl_batch_add_index", tbl: "tidb_ddl_batch_add_index", labels: []string{"instance", "type"}},
{name: "tidb_ddl_deploy_syncer", tbl: "tidb_ddl_deploy_syncer", labels: []string{"instance", "type", "result"}},
{name: "tidb_load_schema", tbl: "tidb_load_schema", labels: []string{"instance"}},
{name: "tidb_meta_operation", tbl: "tidb_meta_operation", labels: []string{"instance", "type", "result"}},
{name: "tidb_auto_id_request", tbl: "tidb_auto_id_request", labels: []string{"instance", "type"}},
{name: "tidb_statistics_auto_analyze", tbl: "tidb_statistics_auto_analyze", labels: []string{"instance"}},
{name: "tidb_gc", tbl: "tidb_gc", labels: []string{"instance"}},
{name: "tidb_gc_push_task", tbl: "tidb_gc_push_task", labels: []string{"instance", "type"}},
{name: "tidb_batch_client_unavailable", tbl: "tidb_batch_client_unavailable", labels: []string{"instance"}},
{name: "tidb_batch_client_wait", tbl: "tidb_batch_client_wait", labels: []string{"instance"}},
{name: "pd_tso_rpc", tbl: "pd_tso_rpc", labels: []string{"instance"}},
{name: "pd_tso_wait", tbl: "pd_tso_wait", labels: []string{"instance"}},
}
defs := make([]rowQuery, 0, len(defs1))
for i := range defs1 {
defs = append(defs, defs1[i])
}
table := TableDef{
Category: []string{CategoryTiDB},
Title: "tidb_time_consume",
Comment: ``,
joinColumns: []int{0, 1},
compareColumns: []int{3, 4, 5},
Column: []string{"METRIC_NAME", "LABEL", "TIME_RATIO", "TOTAL_TIME", "TOTAL_COUNT", "P999", "P99", "P90", "P80"},
}
resultRows := make([]TableRowDef, 0, len(defs))
arg := newQueryArg(startTime, endTime)
specialHandle := func(row []string) []string {
if arg.totalTime == 0 && len(row[3]) > 0 {
totalTime, err := strconv.ParseFloat(row[3], 64)
if err == nil {
arg.totalTime = totalTime
}
}
return row
}
appendRows := func(row TableRowDef) {
row.Values = specialHandle(row.Values)
for i := range row.SubValues {
row.SubValues[i] = specialHandle(row.SubValues[i])
}
resultRows = append(resultRows, row)
}
err := getTableRows(defs, arg, db, appendRows)
if err != nil {
return table, err
}
table.Rows = resultRows
return table, nil
}
func GetTiDBTxnTableData(startTime, endTime string, db *gorm.DB) (TableDef, error) {
defs1 := []totalValueAndTotalCountTableDef{
{name: "tidb_transaction_retry_num", tbl: "tidb_transaction_retry_num", sumTbl: "tidb_transaction_retry_total_num", countTbl: "tidb_transaction_retry_num_total_count", labels: []string{"instance"}},
{name: "tidb_transaction_statement_num", tbl: "tidb_transaction_statement_num", sumTbl: "tidb_transaction_statement_total_num", countTbl: "tidb_transaction_statement_num_total_count", labels: []string{"sql_type"}},
{name: "tidb_txn_region_num", tbl: "tidb_txn_region_num", sumTbl: "tidb_txn_region_total_num", countTbl: "tidb_txn_region_num_total_count", labels: []string{"instance"}},
{name: "tidb_txn_kv_write_num", tbl: "tidb_kv_write_num", sumTbl: "tidb_kv_write_total_num", countTbl: "tidb_kv_write_num_total_count", labels: []string{"instance"}},
{name: "tidb_txn_kv_write_size", tbl: "tidb_kv_write_size", sumTbl: "tidb_kv_write_total_size", countTbl: "tidb_kv_write_size_total_count", labels: []string{"instance"}},
}
defs2 := []sumValueQuery{
{name: "tidb_load_safepoint_total_num", tbl: "tidb_load_safepoint_total_num", labels: []string{"type"}},
{name: "tidb_lock_resolver_total_num", tbl: "tidb_lock_resolver_total_num", labels: []string{"type"}},
}
defs := make([]rowQuery, 0, len(defs1)+len(defs2))
for i := range defs1 {
defs = append(defs, defs1[i])
}
for i := range defs2 {
defs = append(defs, defs2[i])
}
resultRows := make([]TableRowDef, 0, len(defs))
quantiles := []float64{0.999, 0.99, 0.90, 0.80}
table := TableDef{
Category: []string{CategoryTiDB},
Title: "transaction",
Comment: ``,
joinColumns: []int{0, 1},
compareColumns: []int{2, 3, 4, 5},
Column: []string{"METRIC_NAME", "LABEL", "TOTAL_VALUE", "TOTAL_COUNT", "P999", "P99", "P90", "P80"},
}
specialHandle := func(row []string) []string {
for len(row) < 8 {
row = append(row, "")
}
for i := 2; i < len(row); i++ {
if len(row[i]) == 0 {
continue
}
if row[0] == "tidb_txn_kv_write_size" && i != 3 {
row[i] = convertFloatToSize(row[i])
} else {
row[i] = convertFloatToInt(row[i])
}
}
return row
}
appendRows := func(row TableRowDef) {
row.Values = specialHandle(row.Values)
for i := range row.SubValues {
row.SubValues[i] = specialHandle(row.SubValues[i])
}
resultRows = append(resultRows, row)
}
arg := &queryArg{
startTime: startTime,
endTime: endTime,
quantiles: quantiles,
}
err := getTableRows(defs, arg, db, appendRows)
if err != nil {
return table, err
}
table.Rows = resultRows
return table, nil
}
func GetTiDBConnectionCountTable(startTime, endTime string, db *gorm.DB) (TableDef, error) {
sql := fmt.Sprintf("select instance, avg(value), max(value), min(value) from metrics_schema.tidb_connection_count where time >= '%s' and time < '%s' group by instance order by avg(value) desc",
startTime, endTime)
table := TableDef{
Category: []string{CategoryTiDB},
Title: "tidb_connection_count",
Comment: "",
joinColumns: []int{0},
compareColumns: []int{1, 2, 3},
Column: []string{"INSTANCE", "AVG", "MAX", "MIN"},
}
rows, err := getSQLRoundRows(db, sql, []int{1, 2, 3}, "")
if err != nil {
return table, err
}
table.Rows = rows
return table, nil
}
func GetTiDBStatisticsInfo(startTime, endTime string, db *gorm.DB) (TableDef, error) {
defs1 := []sumValueQuery{
{name: "pseudo_estimation_total_count", tbl: "tidb_statistics_pseudo_estimation_total_count", labels: []string{"instance"}},
{name: "dump_feedback_total_count", tbl: "tidb_statistics_dump_feedback_total_count", labels: []string{"instance", "type"}},
{name: "store_query_feedback_total_count", tbl: "tidb_statistics_store_query_feedback_total_count", labels: []string{"instance", "type"}},
{name: "update_stats_total_count", tbl: "tidb_statistics_update_stats_total_count", labels: []string{"instance", "type"}},
}
table := TableDef{
Category: []string{CategoryTiDB},
Title: "statistics_info",
Comment: "",
joinColumns: []int{0, 1},
compareColumns: []int{2},
Column: []string{"METRIC_NAME", "LABEL", "TOTAL_COUNT"},
}
rows, err := getSumValueTableData(defs1, startTime, endTime, db)
if err != nil {
return table, err
}
table.Rows = rows
return table, err
}
func GetTiDBDDLOwner(startTime, endTime string, db *gorm.DB) (TableDef, error) {
sql := fmt.Sprintf("select min(time),instance from metrics_schema.tidb_ddl_worker_total_count where time>='%s' and time<'%s' and value>0 and type='run_job' group by instance order by min(time);",
startTime, endTime)
table := TableDef{
Category: []string{CategoryTiDB},
Title: "ddl_owner",
Comment: "",
joinColumns: []int{1},
Column: []string{"MIN_TIME", "DDL OWNER"},
}
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
table.Rows = rows
return table, nil
}
func GetPDConfigInfo(startTime, endTime string, db *gorm.DB) (TableDef, error) {
table := TableDef{
Category: []string{CategoryConfig},
Title: "scheduler_initial_config",
Comment: "",
joinColumns: []int{0, 2},
compareColumns: []int{1},
Column: []string{"CONFIG_ITEM", "VALUE", "CURRENT_VALUE", "DIFF_WITH_CURRENT"},
}
sql := fmt.Sprintf(`select t1.type,t1.value,t2.value,t1.value!=t2.value from
(select distinct type,value from metrics_schema.pd_scheduler_config where time = '%[1]s' and value>0) as t1 join
(select distinct type,value from metrics_schema.pd_scheduler_config where time = now() and value>0) as t2
where t1.type=t2.type order by abs(t2.value-t1.value) desc`, startTime)
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
if len(rows) > 0 {
table.Rows = rows
}
return table, nil
}
func GetPDConfigChangeInfo(startTime, endTime string, db *gorm.DB) (TableDef, error) {
sql := fmt.Sprintf(`select t1.* from
(select min(time) as time,type,value from metrics_schema.pd_scheduler_config where time>='%[1]s' and time<'%[2]s' group by type,value order by type) as t1 join
(select type, count(distinct value) as count from metrics_schema.pd_scheduler_config where time>='%[1]s' and time<'%[2]s' group by type order by count desc) as t2
where t1.type=t2.type and t2.count > 1 order by t2.count desc, t1.time;`, startTime, endTime)
table := TableDef{
Category: []string{CategoryConfig},
Title: "scheduler_change_config",
Comment: "",
joinColumns: []int{1},
compareColumns: []int{2},
Column: []string{"APPROXIMATE_CHANGE_TIME", "CONFIG_ITEM", "VALUE"},
}
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
table.Rows = rows
return table, nil
}
func GetTiDBGCConfigInfo(startTime, endTime string, db *gorm.DB) (TableDef, error) {
table := TableDef{
Category: []string{CategoryConfig},
Title: "tidb_gc_initial_config",
Comment: "",
joinColumns: []int{0, 2},
compareColumns: []int{1},
Column: []string{"CONFIG_ITEM", "VALUE", "CURRENT_VALUE", "DIFF_WITH_CURRENT"},
}
sql := fmt.Sprintf(`select t1.type,t1.value,t2.value,t1.value!=t2.value from
(select distinct type,value from metrics_schema.tidb_gc_config where time = '%[1]s' and value>0) as t1 join
(select distinct type,value from metrics_schema.tidb_gc_config where time = now() and value>0) as t2
where t1.type=t2.type order by abs(t2.value-t1.value) desc`, startTime)
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
table.Rows = rows
return table, nil
}
func GetTiDBGCConfigChangeInfo(startTime, endTime string, db *gorm.DB) (TableDef, error) {
sql := fmt.Sprintf(`select t1.* from
(select min(time) as time,type,value from metrics_schema.tidb_gc_config where time>='%[1]s' and time<'%[2]s' and value > 0 group by type,value order by type) as t1 join
(select type, count(distinct value) as count from metrics_schema.tidb_gc_config where time>='%[1]s' and time<'%[2]s' and value > 0 group by type order by count desc) as t2
where t1.type=t2.type and t2.count>1 order by t2.count desc, t1.time;`, startTime, endTime)
table := TableDef{
Category: []string{CategoryConfig},
Title: "tidb_gc_change_config",
Comment: ``,
joinColumns: []int{1},
compareColumns: []int{2},
Column: []string{"APPROXIMATE_CHANGE_TIME", "CONFIG_ITEM", "VALUE"},
}
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
table.Rows = rows
return table, nil
}
func GetTiKVRocksDBConfigInfo(startTime, endTime string, db *gorm.DB) (TableDef, error) {
table := TableDef{
Category: []string{CategoryConfig},
Title: "tikv_rocksdb_initial_config",
Comment: "",
joinColumns: []int{0, 1, 3},
compareColumns: []int{2},
Column: []string{"CONFIG_ITEM", "INSTANCE", "VALUE", "CURRENT_VALUE", "DIFF_WITH_CURRENT", "DISTINCT_VALUES_IN_INSTANCE"},
}
sql := fmt.Sprintf(`select t1.name,'', t1.value,t2.value,t1.value!=t2.value, t1.count from
(select concat(name,' , ',cf) as name, min(value) as value, count(distinct value) as count from metrics_schema.tikv_config_rocksdb where time = '%[1]s' group by cf, name) as t1 join
(select concat(name,' , ',cf) as name, min(value) as value from metrics_schema.tikv_config_rocksdb where time = now() group by cf, name) as t2
where t1.name=t2.name order by abs(t2.value-t1.value) desc,t1.count desc, t1.name`, startTime)
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
//var subRows []TableRowDef
subRowsMap := make(map[string][][]string)
for i, row := range rows {
if len(row.Values) < 6 {
continue
}
if row.Values[5] == "1" {
continue
}
if len(subRowsMap) == 0 {
sql = fmt.Sprintf(`select t1.name,t1.instance,t1.value,t2.value,t1.value!=t2.value, '' from
(select concat(name,' , ',cf) as name,instance, value from metrics_schema.tikv_config_rocksdb where time = '%[1]s' group by cf, name, instance, value) as t1 join
(select concat(name,' , ',cf) as name,instance, value from metrics_schema.tikv_config_rocksdb where time = now() group by cf, name, instance, value) as t2
where t1.name=t2.name and t1.instance = t2.instance order by abs(t2.value-t1.value) desc, t1.name`, startTime)
subRows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
for _, subRow := range subRows {
if len(subRow.Values) < 6 {
continue
}
subRowsMap[subRow.Values[0]] = append(subRowsMap[subRow.Values[0]], subRow.Values)
}
}
rows[i].SubValues = subRowsMap[row.Values[0]]
if len(rows[i].SubValues) > 0 && row.Values[4] == "0" {
for _, subRow := range rows[i].SubValues {
if row.Values[4] != "0" {
break
}
if len(subRow) != 6 {
continue
}
rows[i].Values[4] = subRow[4]
}
}
}
table.Rows = rows
return table, nil
}
func GetTiKVRocksDBConfigChangeInfo(startTime, endTime string, db *gorm.DB) (TableDef, error) {
sql := fmt.Sprintf(`select t1.* from
(select min(time) as time,concat(name,' , ',cf) as name,instance,value from metrics_schema.tikv_config_rocksdb where time>='%[1]s' and time<'%[2]s' group by name,cf,instance,value order by name) as t1 join
(select concat(name,' , ',cf) as name,instance, count(distinct value) as count from metrics_schema.tikv_config_rocksdb where time>='%[1]s' and time<'%[2]s' group by name,cf,instance order by count desc) as t2
where t1.name=t2.name and t1.instance = t2.instance and t2.count>1 order by t1.name,instance, t2.count desc, t1.time;`, startTime, endTime)
table := TableDef{
Category: []string{CategoryConfig},
Title: "tikv_rocksdb_change_config",
Comment: ``,
joinColumns: []int{1, 2},
compareColumns: []int{3},
Column: []string{"APPROXIMATE_CHANGE_TIME", "CONFIG_ITEM", "INSTANCE", "VALUE"},
}
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
table.Rows = rows
return table, nil
}
func GetTiKVRaftStoreConfigInfo(startTime, endTime string, db *gorm.DB) (TableDef, error) {
table := TableDef{
Category: []string{CategoryConfig},
Title: "tikv_raftstore_initial_config",
Comment: "",
joinColumns: []int{0, 1, 3},
compareColumns: []int{2},
Column: []string{"CONFIG_ITEM", "INSTANCE", "VALUE", "CURRENT_VALUE", "DIFF_WITH_CURRENT", "DISTINCT_VALUES_IN_INSTANCE"},
}
sql := fmt.Sprintf(`select t1.name,'', t1.value,t2.value,t1.value!=t2.value, t1.count from
(select name, min(value) as value, count(distinct value) as count from metrics_schema.tikv_config_raftstore where time = '%[1]s' group by name) as t1 join
(select name, min(value) as value from metrics_schema.tikv_config_raftstore where time = now() group by name) as t2
where t1.name=t2.name order by abs(t2.value-t1.value) desc,t1.count desc, t1.name`, startTime)
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
//var subRows []TableRowDef
subRowsMap := make(map[string][][]string)
for i, row := range rows {
if len(row.Values) < 6 {
continue
}
if row.Values[5] == "1" {
continue
}
if len(subRowsMap) == 0 {
sql = fmt.Sprintf(`select t1.name,t1.instance,t1.value,t2.value,t1.value!=t2.value, '' from
(select name,instance, value from metrics_schema.tikv_config_raftstore where time = '%[1]s' group by name, instance, value) as t1 join
(select name,instance, value from metrics_schema.tikv_config_raftstore where time = now() group by name, instance, value) as t2
where t1.name=t2.name and t1.instance = t2.instance order by abs(t2.value-t1.value) desc, t1.name`, startTime)
subRows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
for _, subRow := range subRows {
if len(subRow.Values) < 6 {
continue
}
subRowsMap[subRow.Values[0]] = append(subRowsMap[subRow.Values[0]], subRow.Values)
}
}
rows[i].SubValues = subRowsMap[row.Values[0]]
if len(rows[i].SubValues) > 0 && row.Values[4] == "0" {
for _, subRow := range rows[i].SubValues {
if row.Values[4] != "0" {
break
}
if len(subRow) != 6 {
continue
}
rows[i].Values[4] = subRow[4]
}
}
}
table.Rows = rows
return table, nil
}
func GetTiKVRaftStoreConfigChangeInfo(startTime, endTime string, db *gorm.DB) (TableDef, error) {
sql := fmt.Sprintf(`select t1.* from
(select min(time) as time,name,instance,value from metrics_schema.tikv_config_raftstore where time>='%[1]s' and time<'%[2]s' group by name,instance,value order by name) as t1 join
(select name,instance, count(distinct value) as count from metrics_schema.tikv_config_raftstore where time>='%[1]s' and time<'%[2]s' group by name,instance order by count desc) as t2
where t1.name=t2.name and t1.instance = t2.instance and t2.count>1 order by t1.name,instance,t2.count desc, t1.time;`, startTime, endTime)
table := TableDef{
Category: []string{CategoryConfig},
Title: "tikv_raftstore_change_config",
Comment: ``,
joinColumns: []int{1, 2},
compareColumns: []int{3},
Column: []string{"APPROXIMATE_CHANGE_TIME", "CONFIG_ITEM", "INSTANCE", "VALUE"},
}
rows, err := getSQLRows(db, sql)
if err != nil {
return table, err
}
table.Rows = rows
return table, nil
}
func GetPDTimeConsumeTable(startTime, endTime string, db *gorm.DB) (TableDef, error) {
defs1 := []totalTimeByLabelsTableDef{
{name: "pd_client_cmd", tbl: "pd_client_cmd", labels: []string{"instance", "type"}},
{name: "pd_client_request_rpc", tbl: "pd_request_rpc", labels: []string{"instance", "type"}},
{name: "pd_grpc_completed_commands", tbl: "pd_grpc_completed_commands", labels: []string{"instance", "grpc_method"}},
{name: "pd_operator_finish", tbl: "pd_operator_finish", labels: []string{"type"}},
{name: "pd_operator_step_finish", tbl: "pd_operator_step_finish", labels: []string{"type"}},
{name: "pd_handle_transactions", tbl: "pd_handle_transactions", labels: []string{"instance", "result"}},
{name: "pd_region_heartbeat", tbl: "pd_region_heartbeat", labels: []string{"address", "store"}},
{name: "etcd_wal_fsync", tbl: "etcd_wal_fsync", labels: []string{"instance"}},
{name: "pd_peer_round_trip", tbl: "pd_peer_round_trip", labels: []string{"instance", "To"}},
}
defs := make([]rowQuery, 0, len(defs1))
for i := range defs1 {
defs = append(defs, defs1[i])
}
table := TableDef{
Category: []string{CategoryPD},
Title: "pd_time_consume",
Comment: ``,
joinColumns: []int{0, 1},
compareColumns: []int{3, 4, 5},
Column: []string{"METRIC_NAME", "LABEL", "TIME_RATIO", "TOTAL_TIME", "TOTAL_COUNT", "P999", "P99", "P90", "P80"},
}
resultRows := make([]TableRowDef, 0, len(defs))
arg := newQueryArg(startTime, endTime)
appendRows := func(row TableRowDef) {
resultRows = append(resultRows, row)
arg.totalTime = 0