-
Notifications
You must be signed in to change notification settings - Fork 36
/
actiontech_mysql_monitor.go
1533 lines (1379 loc) · 53.3 KB
/
actiontech_mysql_monitor.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
package main
import (
"database/sql"
"encoding/json"
"flag"
"fmt"
_ "github.com/go-sql-driver/mysql"
"io/ioutil"
"log"
"os"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"syscall"
"time"
)
const (
SHOW_STATUS = iota
SHOW_VARIABLES
SHOW_SLAVE_STATUS
SHOW_MASTER_LOGS
SHOW_PROCESSLIST
SHOW_INNODB_STATUS
SELECT_FROM_QUERY_RESPONSE_TIME_PERCONA
SELECT_FROM_QUERY_RESPONSE_TIME_MYSQL
SELECT_FROM_UNCOMMITTED_TRX_DURATION_MYSQL
)
// pre key
const (
SHOW_PROCESSLIST_STATE_PRE = "show_processlist_state_"
SHOW_PROCESSLIST_TIME_PRE = "show_processlist_time_"
SELECT_FROM_UNCOMMITTED_TRX_DURATION_MYSQL_PRE = "select_from_uncommitted_trx_duration_"
)
var (
mysqlSsl = false // Whether to use SSL to connect to MySQL.
// TODO:support ssl conn
/* mysqlSslKey = "/etc/pki/tls/certs/mysql/client-key.pem"
mysqlSslCert = "/etc/pki/tls/certs/mysql/client-cert.pem"
mysqlSslCa = "/etc/pki/tls/certs/mysql/ca-cert.pem"*/
host = flag.String("host", "127.0.0.1", "`MySQL host`")
user = flag.String("user", "", "`MySQL username` (default: no default)")
pass = flag.String("pass", "", "`MySQL password` (default: no default)")
port = flag.String("port", "3306", "`MySQL port`")
pollTime = flag.Int("poll_time", 30, "Adjust to match your `polling interval`.if change, make sure change the wrapper.sh file too.")
nocache = flag.Bool("nocache", false, "Do not cache results in a file (default: false)")
items = flag.String("items", "", "-items <`item`,...> Comma-separated list of the items whose data you want (default: no default)")
debugLog = flag.String("debug_log", "", "If `debuglog` is a filename, it'll be used. (default: no default)")
cacheDir = flag.String("cache_dir", "/tmp", "A `path` for saving cache. if change, make sure change the wrapper.sh file too.")
heartbeat = flag.Bool("heartbeat", false, "Whether to use pt-heartbeat table for repl. delay calculation. (default: false)")
heartbeatUtc = flag.Bool("heartbeat_utc", false, "Whether pt-heartbeat is run with --utc option. (default: false)")
heartbeatServerId = flag.String("heartbeat_server_id", "0", "`Server id` to associate with a heartbeat. Leave 0 if no preference. (default: 0)")
heartbeatTable = flag.String("heartbeat_table", "percona.heartbeat", "`db.tbl`.")
innodb = flag.Bool("innodb", true, "Whether to check InnoDB statistics")
master = flag.Bool("master", true, "Whether to check binary logging")
slave = flag.Bool("slave", true, "Whether to check slave status")
procs = flag.Bool("procs", true, "Whether to check SHOW PROCESSLIST")
getQrtPercona = flag.Bool("get_qrt_percona", true, "Whether to get response times from Percona Server or MariaDB")
getQrtMysql = flag.Bool("get_qrt_mysql", false, "Whether to get response times from MySQL (default: false)")
getUcTrxDurMysql = flag.Bool("get_uctrx_dur_mysql", true, "Whether to get uncommitted transaction duration from MySQL (default: true)")
discoveryPort = flag.Bool("discovery_port", false, "`discovery mysqld port`, print in json format (default: false)")
useSudo = flag.Bool("sudo", true, "Use `sudo netstat...`")
version = flag.Bool("version", false, "print version")
// log
debugLogFile *os.File
//regexps
regSpaces = regexp.MustCompile("\\s+")
regNumbers = regexp.MustCompile("\\d+")
regIndividual = regexp.MustCompile("(?s)INDIVIDUAL BUFFER POOL INFO.*ROW OPERATIONS")
Version string
)
func main() {
flag.Parse()
if *version {
fmt.Println("version:", Version)
os.Exit(1)
}
//debug file
{
if *debugLog != "" {
var err error
debugLogFile, err = os.OpenFile(*debugLog, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if nil != err {
fmt.Printf("Can not create file using (%s as path), err: %s", *debugLog, err)
}
defer debugLogFile.Close()
debugLogFile.Truncate(0)
}
log.SetOutput(debugLogFile)
}
if *discoveryPort {
discoveryMysqldPort()
log.Fatalln("discovery Mysqld Port done, exit.")
}
if *items == "mysqld_port_listen" {
// default port: 3306
if verifyMysqldPort(*port) {
fmt.Println(*port, ":", 1)
} else {
fmt.Println(*port, ":", 0)
}
log.Fatalln("verify Mysqld Port done, exit.")
}
//param preprocessing
{
if *user == "" || *pass == "" {
fmt.Fprintln(os.Stderr, "Please set mysql user and password use --user= --pass= !")
log.Fatalln("flag user or pass is empty, exit !")
}
*host = strings.Replace(*host, ":", "", -1)
*host = strings.Replace(*host, "/", "_", -1)
}
// check cache
var cacheFile *os.File
{
cacheFilePath := *cacheDir + "/actiontech_" + *host + "_" + *port + "-mysql_zabbix_stats.txt"
log.Printf("cacheFilePath = %s\n", cacheFilePath)
if !(*nocache) {
var err error
cacheFile, err = checkCache(cacheFilePath)
if nil != err {
log.Fatalf("checkCache err:%s\n", err)
}
defer cacheFile.Close()
} else {
log.Println("Caching is disabled.")
}
// print item
if !(*nocache) && (*items != "") && (cacheFile == nil) {
printItemFromCacheFile(*items, cacheFilePath)
log.Fatalln("read from cache file done.")
}
}
collectionExist, collectionInfo := collect()
result := parse(collectionExist, collectionInfo)
print(result, cacheFile)
}
func collect() ([]bool, []map[string]string) {
// Connect to MySQL.
var db *sql.DB
if mysqlSsl {
log.Println("// TODO: Use mysql ssl")
} else {
var err error
log.Printf("Connecting mysql: user %s, pass %s, host %s, port %s", *user, *pass, *host, *port)
db, err = sql.Open("mysql", *user+":"+*pass+"@tcp("+*host+":"+*port+")/")
if nil != err {
log.Fatalf("sql.Open err:(%s) exit !", err)
}
defer db.Close()
if err := db.Ping(); nil != err {
log.Fatalf("db.Ping err:(%s) exit !", err)
}
}
// Collecting ...
collectionInfo := make([]map[string]string, 9)
collectionExist := []bool{true, true, false, false, false, false, false, false, false}
collectionInfo[SHOW_STATUS] = collectAllRowsToMap("variable_name", "value", db, "SHOW /*!50002 GLOBAL */ STATUS")
collectionInfo[SHOW_VARIABLES] = collectAllRowsToMap("variable_name", "value", db, "SHOW VARIABLES")
if *slave {
collectionExist[SHOW_SLAVE_STATUS] = true
collectionInfo[SHOW_SLAVE_STATUS] = make(map[string]string)
// Leverage lock-free SHOW SLAVE STATUS if available
queryResult := tryQueryIfAvailable(db, "SHOW SLAVE STATUS NONBLOCKING", "SHOW SLAVE STATUS NOLOCK", "SHOW SLAVE STATUS")
log.Println("get slave status: ", queryResult)
if 0 == len(queryResult) {
log.Println("show slave empty, assume it is a master")
} else {
queryResult[0] = changeKeyCase(queryResult[0])
if 1 < len(queryResult) {
// Multi source replication
log.Println("show slave multi rows, assume it is a multi source replication")
var maxLag int64 = -1
var totalRelayLogSpace int64 = 0
for i, resultMap := range queryResult {
resultMap = changeKeyCase(resultMap)
if resultMap["slave_io_running"] != "Yes" {
log.Printf("%dth row slave_io_running != Yes", i)
queryResult[0]["slave_io_running"] = "No"
}
if resultMap["slave_sql_running"] != "Yes" {
log.Printf("%dth row slave_sql_running != Yes", i)
queryResult[0]["slave_sql_running"] = "No"
}
// get max slave_lag
if resultMap["seconds_behind_master"] != "NULL" && convStrToInt64(resultMap["seconds_behind_master"]) > maxLag {
log.Printf("%dth row seconds_behind_master may be max", i)
maxLag = convStrToInt64(resultMap["seconds_behind_master"])
queryResult[0]["seconds_behind_master"] = resultMap["seconds_behind_master"]
}
//get total relay_log_space
log.Printf("%dth row relay_log_space is %s", i, resultMap["relay_log_space"])
totalRelayLogSpace += convStrToInt64(resultMap["relay_log_space"])
}
queryResult[0]["relay_log_space"] = strconv.FormatInt(totalRelayLogSpace, 10)
}
stringMapAdd(collectionInfo[SHOW_SLAVE_STATUS], queryResult[0])
/* stringMapAdd(collectionInfo[SHOW_SLAVE_STATUS], collectFirstRowAsMapValue("relay_log_space", "relay_log_space", db, "SHOW SLAVE STATUS NONBLOCKING", "SHOW SLAVE STATUS NOLOCK", "SHOW SLAVE STATUS"))
stringMapAdd(collectionInfo[SHOW_SLAVE_STATUS], collectFirstRowAsMapValue("seconds_behind_master", "seconds_behind_master", db, "SHOW SLAVE STATUS NONBLOCKING", "SHOW SLAVE STATUS NOLOCK", "SHOW SLAVE STATUS"))
*/
//Check replication heartbeat, if present.
stringMapAdd(collectionInfo[SHOW_SLAVE_STATUS], getDelayFromHeartbeat(db))
}
log.Println("collectionInfo slave: ", collectionInfo[SHOW_SLAVE_STATUS])
}
// Get SHOW MASTER STATUS
if *master && collectionInfo[SHOW_VARIABLES]["log_bin"] == "ON" {
collectionExist[SHOW_MASTER_LOGS] = true
// See issue percona #8
collectionInfo[SHOW_MASTER_LOGS] = collectAllRowsAsMapValue("show_master_logs_value_", "file_size", db, "SHOW MASTER LOGS")
log.Println("collectionInfo master : ", collectionInfo[SHOW_MASTER_LOGS])
}
// Get SHOW PROCESSLIST and aggregate it by state, sort by time with filter
if *procs {
collectionExist[SHOW_PROCESSLIST] = true
collectionInfo[SHOW_PROCESSLIST] = make(map[string]string)
stateCollection := collectMultiColumnAllRowsAsMapValue([]string{SHOW_PROCESSLIST_STATE_PRE},
[]string{"state"}, db, "SHOW PROCESSLIST")
timeCollection := collectMultiColumnAllRowsAsMapValue([]string{SHOW_PROCESSLIST_TIME_PRE},
[]string{"time"}, db, "SELECT time FROM INFORMATION_SCHEMA.PROCESSLIST WHERE state NOT IN ('','sleep') AND user != 'root' AND db != 'NULL'")
stringMapAdd(collectionInfo[SHOW_PROCESSLIST], stateCollection)
stringMapAdd(collectionInfo[SHOW_PROCESSLIST], timeCollection)
log.Println("collectionInfo show processlist:", collectionInfo[SHOW_PROCESSLIST])
}
// Get SHOW INNODB STATUS and extract the desired metrics from it
if *innodb {
collectionExist[SHOW_INNODB_STATUS] = true
engineMap := collectAllRowsToMap("engine", "support", db, "SHOW ENGINES")
if value, ok := engineMap["InnoDB"]; ok && (value == "YES" || value == "DEFAULT") {
collectionInfo[SHOW_INNODB_STATUS] = collectFirstRowAsMapValue("innodb_status_text", "status", db, "SHOW /*!50000 ENGINE*/ INNODB STATUS")
// Get response time histogram from Percona Server or MariaDB if enabled.
if !*getQrtPercona {
log.Println("Not getting time histogram percona because it is not enabled")
} else if collectionInfo[SHOW_VARIABLES]["have_response_time_distribution"] == "YES" || collectionInfo[SHOW_VARIABLES]["query_response_time_stats"] == "ON" {
collectionExist[SELECT_FROM_QUERY_RESPONSE_TIME_PERCONA] = true
collectionInfo[SELECT_FROM_QUERY_RESPONSE_TIME_PERCONA] = make(map[string]string)
log.Println("Getting query time histogram percona")
stringMapAdd(collectionInfo[SELECT_FROM_QUERY_RESPONSE_TIME_PERCONA], collectRowsAsMapValue("Query_time_count_", "count", 14, db, "SELECT `count`, ROUND(total * 1000000) AS total FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME WHERE `time` <> 'TOO LONG'"))
stringMapAdd(collectionInfo[SELECT_FROM_QUERY_RESPONSE_TIME_PERCONA], collectRowsAsMapValue("Query_time_total_", "total", 14, db, "SELECT `count`, ROUND(total * 1000000) AS total FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME WHERE `time` <> 'TOO LONG'"))
}
}
}
// Get Query Response Time histogram from MySQL if enable.
if (!*getQrtMysql) || (collectionInfo[SHOW_VARIABLES]["performance_schema"] != "ON") {
log.Println("Not getting time histogram mysql because it is not enabled")
} else {
collectionExist[SELECT_FROM_QUERY_RESPONSE_TIME_MYSQL] = true
collectionInfo[SELECT_FROM_QUERY_RESPONSE_TIME_MYSQL] = make(map[string]string)
query := `SELECT 'query_rt100s' as rt, ifnull(sum(COUNT_STAR),0) as cnt FROM performance_schema.events_statements_summary_by_digest WHERE AVG_TIMER_WAIT >= 100000000000000 UNION
SELECT 'query_rt10s', ifnull(sum(COUNT_STAR),0) as cnt FROM performance_schema.events_statements_summary_by_digest WHERE AVG_TIMER_WAIT BETWEEN 10000000000000 AND 10000000000000 UNION
SELECT 'query_rt1s', ifnull(sum(COUNT_STAR),0) as cnt FROM performance_schema.events_statements_summary_by_digest WHERE AVG_TIMER_WAIT BETWEEN 1000000000000 AND 10000000000000 UNION
SELECT 'query_rt100ms', ifnull(sum(COUNT_STAR),0) as cnt FROM performance_schema.events_statements_summary_by_digest WHERE AVG_TIMER_WAIT BETWEEN 100000000000 AND 1000000000000 UNION
SELECT 'query_rt10ms', ifnull(sum(COUNT_STAR),0) as cnt FROM performance_schema.events_statements_summary_by_digest WHERE AVG_TIMER_WAIT BETWEEN 10000000000 AND 100000000000 UNION
SELECT 'query_rt1ms', ifnull(sum(COUNT_STAR),0) as cnt FROM performance_schema.events_statements_summary_by_digest WHERE AVG_TIMER_WAIT BETWEEN 1000000000 AND 10000000000 UNION
SELECT 'query_rt100us', ifnull(sum(COUNT_STAR),0) as cnt FROM performance_schema.events_statements_summary_by_digest WHERE AVG_TIMER_WAIT <= 1000000000`
stringMapAdd(collectionInfo[SELECT_FROM_QUERY_RESPONSE_TIME_MYSQL], collectAllRowsToMap("rt", "cnt", db, query))
stringMapAdd(collectionInfo[SELECT_FROM_QUERY_RESPONSE_TIME_MYSQL], collectFirstRowAsMapValue("query_avgrt", "avgrt", db, "select round(avg(AVG_TIMER_WAIT)/1000/1000/1000,2) as avgrt from performance_schema.events_statements_summary_by_digest"))
}
if *getUcTrxDurMysql {
collectionExist[SELECT_FROM_UNCOMMITTED_TRX_DURATION_MYSQL] = true
collectionInfo[SELECT_FROM_UNCOMMITTED_TRX_DURATION_MYSQL] = collectMultiColumnAllRowsAsMapValue([]string{SELECT_FROM_UNCOMMITTED_TRX_DURATION_MYSQL_PRE}, []string{"time"}, db, "SELECT p.time FROM information_schema.innodb_trx t INNER JOIN information_schema.processlist p ON t.trx_mysql_thread_id = p.id WHERE t.trx_state = 'RUNNING' AND p.time > 10 AND p.command = 'Sleep'")
log.Println("collectionInfo uncommitted trx duration:", collectionInfo[SELECT_FROM_UNCOMMITTED_TRX_DURATION_MYSQL])
}
return collectionExist, collectionInfo
}
func parse(collectionExist []bool, collectionInfo []map[string]string) map[string]string {
// Holds the result of SHOW STATUS, SHOW INNODB STATUS, etc
stat := make(map[string]string)
stringMapAdd(stat, collectionInfo[SHOW_STATUS])
stringMapAdd(stat, collectionInfo[SHOW_VARIABLES])
// Make table_open_cache backwards-compatible (issue 63).
if val, ok := stat["table_open_cache"]; ok {
stat["table_cache"] = val
}
// Compute how much of the key buffer is used and unflushed (issue 127).
if val1, err := strconv.ParseInt(stat["key_buffer_size"], 10, 64); err == nil {
if val2, err := strconv.ParseInt(stat["Key_blocks_unused"], 10, 64); err == nil {
if val3, err := strconv.ParseInt(stat["key_cache_block_size"], 10, 64); err == nil {
if val4, err := strconv.ParseInt(stat["Key_blocks_not_flushed"], 10, 64); err == nil {
log.Println("calc Key_buf_bytes_used, Key_buf_bytes_unflushed...")
stat["Key_buf_bytes_used"] = strconv.FormatInt(val1-(val2*val3), 10)
stat["Key_buf_bytes_unflushed"] = strconv.FormatInt(val4*val3, 10)
}
}
}
}
if collectionExist[SHOW_SLAVE_STATUS] {
if 0 == len(collectionInfo[SHOW_SLAVE_STATUS]) {
// it is a master, set running_slave = 1 to avoid "slave stop" trigger
log.Println("it is a master!set running_slave = 1")
stat["running_slave"] = "1"
stat["slave_lag"] = "0"
} else if collectionInfo[SHOW_SLAVE_STATUS]["slave_io_running"] == "Yes" && collectionInfo[SHOW_SLAVE_STATUS]["slave_sql_running"] == "Yes" {
stat["running_slave"] = "1"
} else {
stat["running_slave"] = "0"
}
if v, ok := collectionInfo[SHOW_SLAVE_STATUS]["relay_log_space"]; ok {
stat["relay_log_space"] = v
}
if v, ok := collectionInfo[SHOW_SLAVE_STATUS]["seconds_behind_master"]; ok {
stat["slave_lag"] = v
}
if v, ok := collectionInfo[SHOW_SLAVE_STATUS]["delay_from_heartbeat"]; ok {
stat["slave_lag"] = v
}
//Scale slave_running and slave_stopped relative to the slave lag.
if collectionInfo[SHOW_SLAVE_STATUS]["slave_sql_running"] == "Yes" {
stat["slave_running"] = stat["slave_lag"]
stat["slave_stopped"] = "0"
} else {
stat["slave_running"] = "0"
stat["slave_stopped"] = stat["slave_lag"]
}
}
if collectionExist[SHOW_MASTER_LOGS] {
var binaryLogSpace int64 = 0
// Older versions of MySQL may not have the File_size column in the
// results of the command. Zero-size files indicate the user is
// deleting binlogs manually from disk (bad user! bad!).
for _, value := range collectionInfo[SHOW_MASTER_LOGS] {
if size, err := strconv.ParseInt(value, 10, 64); nil != err {
log.Println("convert file_size to int fail:", err)
} else if size > 0 {
binaryLogSpace += size
}
}
if binaryLogSpace > 0 {
stat["binary_log_space"] = strconv.FormatInt(binaryLogSpace, 10)
} else {
stat["binary_log_space"] = "NULL"
}
}
{
procsStateMap := map[string]int64{
// Values for the 'State' column from SHOW PROCESSLIST (converted to
// lowercase, with spaces replaced by underscores)
"State_closing_tables": 0,
"State_copying_to_tmp_table": 0,
"State_end": 0,
"State_freeing_items": 0,
"State_init": 0,
"State_locked": 0,
"State_login": 0,
"State_preparing": 0,
"State_reading_from_net": 0,
"State_sending_data": 0,
"State_sorting_result": 0,
"State_statistics": 0,
"State_updating": 0,
"State_writing_to_net": 0,
"State_none": 0,
"State_other": 0, // Everything not listed above
}
procsTimeMap := map[string]int64{
"Time_top_1": 0,
"Time_top_2": 0,
"Time_top_3": 0,
"Time_top_4": 0,
"Time_top_5": 0,
"Time_top_6": 0,
"Time_top_7": 0,
"Time_top_8": 0,
"Time_top_9": 0,
"Time_top_10": 0,
}
procsTimeSort := []int{}
if collectionExist[SHOW_PROCESSLIST] {
var state string
reg := regexp.MustCompile("^(Table lock|Waiting for .*lock)$")
for key, value := range collectionInfo[SHOW_PROCESSLIST] {
if strings.HasPrefix(key, SHOW_PROCESSLIST_STATE_PRE) {
if value == "" {
value = "none"
}
// MySQL 5.5 replaces the 'Locked' state with a variety of "Waiting for
// X lock" types of statuses. Wrap these all back into "Locked" because
// we don't really care about the type of locking it is.
state = reg.ReplaceAllString(value, "locked")
state = strings.Replace(strings.ToLower(value), " ", "_", -1)
if _, ok := procsStateMap["State_"+state]; ok {
procsStateMap["State_"+state]++
} else {
procsStateMap["State_other"]++
}
} else if strings.HasPrefix(key, SHOW_PROCESSLIST_TIME_PRE) {
time, err := strconv.Atoi(value)
if nil != err {
log.Printf("show processlist: convert time %v error %v\n", value, err)
}
procsTimeSort = append(procsTimeSort, time)
} else {
log.Printf("show processlist: unexpect show processlist pre key %v\n", key)
}
}
}
putTopInfoIntoMap("Time_top_", procsTimeSort, procsTimeMap)
intMapAdd(stat, procsStateMap)
intMapAdd(stat, procsTimeMap)
}
if value, ok := collectionInfo[SHOW_INNODB_STATUS]["innodb_status_text"]; ok {
result := parseInnodbStatusWithRule(value)
// percona comments:
// TODO: I'm not sure what the deal is here; need to debug this. But the
// unflushed log bytes spikes a lot sometimes and it's impossible for it to
// be more than the log buffer.
log.Println("Unflushed log: ", result["unflushed_log"])
val := convStrToInt64(stat["innodb_log_buffer_size"])
if result["unflushed_log"] > 0 && result["unflushed_log"] < val {
result["unflushed_log"] = val
}
// Now copy the values into stat.
intMapAdd(stat, result)
// Override values from InnoDB parsing with values from SHOW STATUS,
// because InnoDB status might not have everything and the SHOW STATUS is
// to be preferred where possible.
overrides := map[string]string{
"Innodb_buffer_pool_pages_data": "database_pages",
"Innodb_buffer_pool_pages_dirty": "modified_pages",
"Innodb_buffer_pool_pages_free": "free_pages",
"Innodb_buffer_pool_pages_total": "pool_size",
"Innodb_data_fsyncs": "file_fsyncs",
"Innodb_data_pending_reads": "pending_normal_aio_reads",
"Innodb_data_pending_writes": "pending_normal_aio_writes",
"Innodb_os_log_pending_fsyncs": "pending_log_flushes",
"Innodb_pages_created": "pages_created",
"Innodb_pages_read": "pages_read",
"Innodb_pages_written": "pages_written",
"Innodb_rows_deleted": "rows_deleted",
"Innodb_rows_inserted": "rows_inserted",
"Innodb_rows_read": "rows_read",
"Innodb_rows_updated": "rows_updated",
"Innodb_buffer_pool_reads": "pool_reads",
"Innodb_buffer_pool_read_requests": "pool_read_requests",
}
// If the SHOW STATUS value exists, override...
for k, v := range overrides {
if val, ok := stat[k]; ok {
log.Println("Override " + k)
stat[v] = val
}
}
}
if collectionExist[SELECT_FROM_QUERY_RESPONSE_TIME_PERCONA] {
stringMapAdd(stat, collectionInfo[SELECT_FROM_QUERY_RESPONSE_TIME_PERCONA])
}
if collectionExist[SELECT_FROM_QUERY_RESPONSE_TIME_MYSQL] {
stringMapAdd(stat, collectionInfo[SELECT_FROM_QUERY_RESPONSE_TIME_MYSQL])
}
if collectionExist[SELECT_FROM_UNCOMMITTED_TRX_DURATION_MYSQL] {
timeMap := map[string]int64{
"uncommitted_trx_duration_top_1": 0,
"uncommitted_trx_duration_top_2": 0,
"uncommitted_trx_duration_top_3": 0,
}
timeSort := []int{}
for _, value := range collectionInfo[SELECT_FROM_UNCOMMITTED_TRX_DURATION_MYSQL] {
time, err := strconv.Atoi(value)
if nil != err {
log.Printf("select from uncommitted transaction duration: convert time %v error %v\n", value, err)
}
timeSort = append(timeSort, time)
}
putTopInfoIntoMap("uncommitted_trx_duration_top_", timeSort, timeMap)
intMapAdd(stat, timeMap)
}
return stat
}
func putTopInfoIntoMap(keyPrefix string, srcInfo []int, targetMap map[string]int64) {
sort.Sort(sort.Reverse(sort.IntSlice(srcInfo)))
for i, t := range srcInfo {
if _, ok := targetMap[keyPrefix+strconv.Itoa(i+1)]; ok {
targetMap[keyPrefix+strconv.Itoa(i+1)] = int64(t)
}
}
}
func print(result map[string]string, fp *os.File) {
// Define the variables to output.
key := []string{
"Key_read_requests",
"Key_reads",
"Key_write_requests",
"Key_writes",
"history_list",
"innodb_transactions",
"read_views",
"current_transactions",
"locked_transactions",
"active_transactions",
"pool_size",
"free_pages",
"database_pages",
"modified_pages",
"pages_read",
"pages_created",
"pages_written",
"file_fsyncs",
"file_reads",
"file_writes",
"log_writes",
"pending_aio_log_ios",
"pending_aio_sync_ios",
"pending_buf_pool_flushes",
"pending_chkp_writes",
"pending_ibuf_aio_reads",
"pending_log_flushes",
"pending_log_writes",
"pending_normal_aio_reads",
"pending_normal_aio_writes",
"ibuf_inserts",
"ibuf_merged",
"ibuf_merges",
"spin_waits",
"spin_rounds",
"os_waits",
"rows_inserted",
"rows_updated",
"rows_deleted",
"rows_read",
"Table_locks_waited",
"Table_locks_immediate",
"Slow_queries",
"Open_files",
"Open_tables",
"Opened_tables",
"innodb_open_files",
"open_files_limit",
"table_cache",
"Aborted_clients",
"Aborted_connects",
"Max_used_connections",
"Slow_launch_threads",
"Threads_cached",
"Threads_connected",
"Threads_created",
"Threads_running",
"max_connections",
"thread_cache_size",
"Connections",
"slave_running",
"slave_stopped",
"Slave_retried_transactions",
"slave_lag",
"Slave_open_temp_tables",
"Qcache_free_blocks",
"Qcache_free_memory",
"Qcache_hits",
"Qcache_inserts",
"Qcache_lowmem_prunes",
"Qcache_not_cached",
"Qcache_queries_in_cache",
"Qcache_total_blocks",
"query_cache_size",
"Questions",
"Com_update",
"Com_insert",
"Com_select",
"Com_delete",
"Com_replace",
"Com_load",
"Com_update_multi",
"Com_insert_select",
"Com_delete_multi",
"Com_replace_select",
"Select_full_join",
"Select_full_range_join",
"Select_range",
"Select_range_check",
"Select_scan",
"Sort_merge_passes",
"Sort_range",
"Sort_rows",
"Sort_scan",
"Created_tmp_tables",
"Created_tmp_disk_tables",
"Created_tmp_files",
"Bytes_sent",
"Bytes_received",
"innodb_log_buffer_size",
"unflushed_log",
"log_bytes_flushed",
"log_bytes_written",
"relay_log_space",
"binlog_cache_size",
"Binlog_cache_disk_use",
"Binlog_cache_use",
"binary_log_space",
"innodb_locked_tables",
"innodb_lock_structs",
"State_closing_tables",
"State_copying_to_tmp_table",
"State_end",
"State_freeing_items",
"State_init",
"State_locked",
"State_login",
"State_preparing",
"State_reading_from_net",
"State_sending_data",
"State_sorting_result",
"State_statistics",
"State_updating",
"State_writing_to_net",
"State_none",
"State_other",
"Time_top_1",
"Time_top_2",
"Time_top_3",
"Time_top_4",
"Time_top_5",
"Time_top_6",
"Time_top_7",
"Time_top_8",
"Time_top_9",
"Time_top_10",
"Handler_commit",
"Handler_delete",
"Handler_discover",
"Handler_prepare",
"Handler_read_first",
"Handler_read_key",
"Handler_read_next",
"Handler_read_prev",
"Handler_read_rnd",
"Handler_read_rnd_next",
"Handler_rollback",
"Handler_savepoint",
"Handler_savepoint_rollback",
"Handler_update",
"Handler_write",
"innodb_tables_in_use",
"innodb_lock_wait_secs",
"hash_index_cells_total",
"hash_index_cells_used",
"total_mem_alloc",
"additional_pool_alloc",
"uncheckpointed_bytes",
"ibuf_used_cells",
"ibuf_free_cells",
"ibuf_cell_count",
"adaptive_hash_memory",
"page_hash_memory",
"dictionary_cache_memory",
"file_system_memory",
"lock_system_memory",
"recovery_system_memory",
"thread_hash_memory",
"innodb_sem_waits",
"innodb_sem_wait_time_ms",
"Key_buf_bytes_unflushed",
"Key_buf_bytes_used",
"key_buffer_size",
"Innodb_row_lock_time",
"Innodb_row_lock_waits",
"Query_time_count_00",
"Query_time_count_01",
"Query_time_count_02",
"Query_time_count_03",
"Query_time_count_04",
"Query_time_count_05",
"Query_time_count_06",
"Query_time_count_07",
"Query_time_count_08",
"Query_time_count_09",
"Query_time_count_10",
"Query_time_count_11",
"Query_time_count_12",
"Query_time_count_13",
"Query_time_total_00",
"Query_time_total_01",
"Query_time_total_02",
"Query_time_total_03",
"Query_time_total_04",
"Query_time_total_05",
"Query_time_total_06",
"Query_time_total_07",
"Query_time_total_08",
"Query_time_total_09",
"Query_time_total_10",
"Query_time_total_11",
"Query_time_total_12",
"Query_time_total_13",
"wsrep_replicated_bytes",
"wsrep_received_bytes",
"wsrep_replicated",
"wsrep_received",
"wsrep_local_cert_failures",
"wsrep_local_bf_aborts",
"wsrep_local_send_queue",
"wsrep_local_recv_queue",
"wsrep_cluster_size",
"wsrep_cert_deps_distance",
"wsrep_apply_window",
"wsrep_commit_window",
"wsrep_flow_control_paused",
"wsrep_flow_control_sent",
"wsrep_flow_control_recv",
"pool_reads",
"pool_read_requests",
"running_slave",
"query_rt100s",
"query_rt10s",
"query_rt1s",
"query_rt100ms",
"query_rt10ms",
"query_rt1ms",
"query_rtavg",
"query_avgrt",
"read_only",
"server_id",
"uncommitted_trx_duration_top_1",
"uncommitted_trx_duration_top_2",
"uncommitted_trx_duration_top_3",
}
// Return the output.
output := make(map[string]string)
for _, v := range key {
// If the value isn't defined, return -1 which is lower than (most graphs')
// minimum value of 0, so it'll be regarded as a missing value.
if val, ok := result[v]; ok {
output[v] = val
} else {
output[v] = "-1"
}
}
if fp != nil {
log.Println("write file:")
enc := json.NewEncoder(fp)
enc.Encode(output)
/* for k, v := range output {
fmt.Fprintf(fp, "%v:%v ", k, v)
}*/
}
if *items != "" {
fields := strings.Split(*items, ",")
for _, field := range fields {
if val, ok := output[field]; ok {
fmt.Println(field, ":", val)
} else {
fmt.Println(field + " do not exist")
}
}
}
}
func printItemFromCacheFile(items string, filename string) {
var data map[string]string
f, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalln("printItemFromCacheFile ReadFile err:", err)
}
if err := json.Unmarshal(f, &data); err != nil {
log.Fatalln("printItemFromCacheFile decode json err:", err)
}
fields := strings.Split(items, ",")
for _, field := range fields {
if val, ok := data[field]; ok {
fmt.Println(field, ":", val)
} else {
fmt.Println(field + " do not exist")
}
}
}
func getDelayFromHeartbeat(db *sql.DB) map[string]string {
result := make(map[string]string)
if !*heartbeat {
return result
}
var nowFunc string
if *heartbeatUtc {
nowFunc = "UNIX_TIMESTAMP(UTC_TIMESTAMP)"
} else {
nowFunc = "UNIX_TIMESTAMP()"
}
query := fmt.Sprintf("SELECT MAX(%s - ROUND(UNIX_TIMESTAMP(ts))) AS delay FROM %s WHERE %s = 0 OR server_id = %s", nowFunc, *heartbeatTable, *heartbeatServerId, *heartbeatServerId)
result = collectFirstRowAsMapValue("delay_from_heartbeat", "delay", db, query)
return result
}
func query(db *sql.DB, query string) []map[string]string {
log.Println("exec query:", query)
result := make([]map[string]string, 0, 500)
rows, err := db.Query(query)
if nil != err {
log.Println("db.Query err:", err)
return result
}
defer func(rows *sql.Rows) {
if rows != nil {
rows.Close()
}
}(rows)
columnsName, err := rows.Columns()
if nil != err {
log.Println("rows.Columns err:", err)
return result
}
// Make a slice for the values
values := make([]sql.RawBytes, len(columnsName))
// rows.Scan wants '[]interface{}' as an argument, so we must copy the
// references into such a slice
// See http://code.google.com/p/go-wiki/wiki/InterfaceSlice for details
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
for rows.Next() {
// get RawBytes from data
err = rows.Scan(scanArgs...)
if nil != err {
log.Println("rows.Next err:", err)
}
// Now do something with the data.
row_map := make(map[string]string)
for i, col := range values {
if col == nil {
row_map[columnsName[i]] = "NULL"
} else {
row_map[columnsName[i]] = string(col)
}
}
result = append(result, row_map)
}
err = rows.Err()
if nil != err {
log.Println("rows.Err:", err)
}
return result
}
func tryQueryIfAvailable(db *sql.DB, querys ...string) []map[string]string {
result := make([]map[string]string, 0, 500)
for _, q := range querys {
result = query(db, q)
if 0 == len(result) {
log.Println("tryQueryIfAvailable:Got nothing from sql: ", q)
continue
}
return result
}
return result
}
// collect two columns value to map
func collectAllRowsToMap(keyColName string, valueColName string, db *sql.DB, querys ...string) map[string]string {
result := make(map[string]string)
for _, mp := range tryQueryIfAvailable(db, querys...) {
// Must lowercase keys because different MySQL versions have different lettercase.
mp = changeKeyCase(mp)
result[mp[keyColName]] = mp[valueColName]
}
return result
}
// collect one column value as mapValue in the first row
func collectFirstRowAsMapValue(key string, valueColName string, db *sql.DB, querys ...string) map[string]string {
result := make(map[string]string)
queryResult := tryQueryIfAvailable(db, querys...)
if 0 == len(queryResult) {
log.Println("collectFirstRowAsMapValue:Got nothing from query: ", querys)
return result
}
mp := changeKeyCase(queryResult[0])
if _, ok := mp[valueColName]; !ok {
log.Printf("collectFirstRowAsMapValue:Couldn't get %s from %s\n", valueColName, querys)
return result
}
result[key] = mp[valueColName]
return result
}
// collect one column value as mapValue in all rows
func collectAllRowsAsMapValue(preKey string, valueColName string, db *sql.DB, querys ...string) map[string]string {
result := make(map[string]string)
for i, mp := range tryQueryIfAvailable(db, querys...) {
mp = changeKeyCase(mp)
if _, ok := mp[valueColName]; !ok {
log.Printf("collectAllRowsAsMapValue:Couldn't get %s from %s\n", valueColName, querys)
return result
}
result[preKey+strconv.Itoa(i)] = mp[valueColName]
}
return result
}
// collect multi column value as mapValue in all rows
func collectMultiColumnAllRowsAsMapValue(preKeys []string, valueColNames []string, db *sql.DB, querys ...string) map[string]string {
result := make(map[string]string)
if len(preKeys) != len(valueColNames) {
log.Printf("collectMultiColumnAllRowsAsMapValue:prekey length is not match with valueColName length\n")
return result
}
for i, mp := range tryQueryIfAvailable(db, querys...) {
mp = changeKeyCase(mp)
for j, preKey := range preKeys {
valueColName := valueColNames[j]
if _, ok := mp[valueColName]; !ok {
log.Printf("collectMultiColumnAllRowsAsMapValue:Couldn't get %s from %s\n", valueColName, querys)
return result
}
result[preKey+strconv.Itoa(i)] = mp[valueColName]
}
}
return result
}
// collect one column value as mapValue in pre lines rows
func collectRowsAsMapValue(preKey string, valueColName string, lines int, db *sql.DB, querys ...string) map[string]string {
result := make(map[string]string)
line := 0
resultMap := tryQueryIfAvailable(db, querys...)
for i, mp := range resultMap {
if i >= lines {
// It's possible that the number of rows returned isn't lines.
// Don't add extra status counters.
break
}
mp = changeKeyCase(mp)
if _, ok := mp[valueColName]; !ok {
log.Printf("collectRowsAsMapValue: Couldn't get %s from %s\n", valueColName, querys)
return result
}
result[fmt.Sprintf("%s%02d", preKey, i)] = mp[valueColName]
line++
}
// It's also possible that the number of rows returned is too few.
// Don't leave any status counters unassigned; it will break graphs.