自己開發的MYMON工具監控MYSQL執行狀態幫助文件

gaopengtttt發表於2017-01-23

本工具為採集show global status 實時輸出的一個監控工具,工具原始碼大約1000行程式碼

本文主要為說明文件,並且帶有核心原始碼。


一、此工具展示方式: 
    工具將show global status中一些重要的值按照使用者輸入的描述和次數不斷的列印到前臺或者列印到
指定檔案中,用於幫助DBA進行效能診斷或者瓶頸判斷。
二、此工具執行原理:
   將show global status的值根據使用者輸入的秒數記錄,前一次的值為oldvalue,新的值為newvalue,儲存
在記憶體中,然後判斷是否為累計值還是當前值,如果是累計值則newvalue-oldvalue,如果為當前值則
輸出,這樣則保證了輸出的正確性
三、工具特點:
1、監控賬號低許可權只需要useage許可權
2、遠端連線功能
3、根據使用者需要將資料寫入到指定檔案
4、執行日誌記錄,檢測出錯輸入日誌
5、5.6 5.7支援、沒有測試5.5
6、核心原始碼開源
7、可以根據需求隨時定製輸出,當然需要聯絡本人

注意:
WINDOWS不支援,編譯版本只有LINUX 64BIT.
並且此工具依賴MYSQL連線動態庫檔案


四、、工具使用幫助
[root@testmy 6]# ./mymon 
Author: gaopeng QQ:22389860 Mail: gaopp_200217@163.com 
Info:This tool collect data from 'show global status' and show interval (-t) seconds data change
help DBA to diagnose performance problem,when error or (-d) run log is at current dir name 
is mymon.log.
WIN32 platform is not support
Useage:./mymon [-u username] [-p password] -S socketfile/{-h hosname -P port} -t seconds -n times [-l logfile] [-d]
[-?]           :help info;
[-u username]  :connect to mysqld username,when no username requisite is optional;
[-p password]  :connect to mysqld password,when no password requisite is optional;
[-S socketfile]:connect to mysqld socket file;
[-h hostname]  :connect to mysqld host;
[-P port]      :connect to mysqld port;
                socketfile or [hostname port]  must;
[-t seconds]   :seconds of interval,this is necessary;
[-n times]     :how many times you watch,this is necessary;
[-l logfile]   :when you want to write information to a logfile provide a logfile name
                when a logfile provide no information at foreground,is optional;
[-d]           :more running log at logfile,otherwise error log in mymon.log;


   注意本地連線用-S連線指定socketfile即可,遠端使用 -h -P連線 使用IP和埠連線 ,-l 可以直接把輸出寫入到指定的檔案,
-d就是debug模式一般不用本工具會記錄一個日誌在當前目錄下名字為:mymon.log,這是執行日誌如果有錯誤會記錄到日誌,
開啟-d 會計入更多的資訊,但是一般不需要用,主要是我除錯程式碼的時候用的.當然-t 和 -n就像幫助說的是間隔的秒數和
持續的次數,使用中如果輸出有值為-1則代表值沒有采集到.
   一般只需要線上上一臺伺服器上放上本工具,使用遠端連線連線到如何伺服器即可,如:
   ./mymon -h 192.168.190.91 -P3306 -t 5 -n 100 -ummon2 -pgelc123 -l /root/mysqlog/20170123mysql.log
   表示連線到伺服器192.168.190.91 3306埠 5秒輸出一次 輸出100次,輸出保留到檔案/root/mysqlog/20170123mysql.log
   但是注意SysTime: Sun Jan 22 16:13:30 2017 輸出是執行程式系統的當前時間,但是Uptime當然就是MYSQLD伺服器的時間


四、如果獲得和使用
獲取:
我一共編譯好了4個版本
5.7 社群版本      mymon5.7c
5.7 percona版本  mymon5.7p
5.6 社群版本       mymon5.6c
5.6 perconna版本 mymon5.6p
百度雲盤如下:
http://pan.baidu.com/s/1jIa6OfG


如果要使用更老的版本,請聯絡我。


使用:
下載後上傳到 LINUX作業系統,
mkdir mon
cp mymon5.7p ./mon/
chmod 755 mymon5.7p
然後必須找到相應的庫檔案位置一般在安裝位置的lib目錄下,如:
[root@testmy 9]# ./mymon5.7c
./mymon5.7c: error while loading shared libraries: libmysqlclient.so.20: cannot open shared object file: No such file or directory
[root@testmy 9]# export LD_LIBRARY_PATH=/mysqldata/mysql5.7/lib
[root@testmy 9]# ./mymon5.7c
Author: gaopeng QQ:22389860 Mail: gaopp_200217@163.com 
就可以正常執行,順便說一下5.6為 so.18 5.7為so.20跟老的為5.6以前版本


關於MYSQL監控使用者許可權:監控部需要什麼許可權,只要建立一個使用者即可
mysql> create user moni@'%' identified by 'gelc123';
Query OK, 0 rows affected (0.22 sec)
mysql> show grants for  moni@'%' ;
+----------------------------------+
| Grants for moni@%                |
+----------------------------------+
| GRANT USAGE ON *.* TO 'moni'@'%' |
+----------------------------------+
1 row in set (0.06 sec)


這也最小化了顧慮,因為這個賬戶基本沒有什麼許可權,如果不放心程式,可以將程式放到遠端連線到線上資料庫如:
./mymon5.6c -umoni -pgelc123 -h192.168.190.93 -P3307 -n 1 -t 1 -l /tmp/mysqlmon.log


這樣這個程式既不會有許可權而且也不線上上資料庫伺服器,而且可以集中管理,但是一點注意:
SysTime: Sun Jan 22 16:13:30 2017 輸出是執行程式系統的當前時間,但是Uptime當然就是MYSQLD伺服器的時間




五、此工具展示內容:
展示的內容並不是固定,後期根據需求可以進行簡單的加入指標即可,當前輸出為如下:
------------------------------------------MYMON--------------------------------------------
SysTime: Sun Jan 22 16:13:30 2017
Uptime:6963226    Connections:1       Aborted_clients:0       Max_used_connections:1319    
--------------------------------------MYSQLINFO-------------------------------------------
[###Threads info and qc  and :]
Threads_connected:252         Threads_running:4             Qcache_free_memory:0            
Qcache_hits:0                 Qcache_not_cached:0           Qcache_inserts:0                
[###Table read info:]
Handler_read_first:211        Handler_read_key:8804         Handler_read_next:42346         
Handler_read_last:0           Handler_read_rnd:73           Handler_read_rnd_next:717694
[###Sorts and temp tables info:]
Sort_rows:0                   Sort_merge_passes:0
Created_tmp_tables:163        Created_tmp_disk_tables:152
[###Table join info:]
Select_full_join:1            Select_scan:207
[###Open table cache and binlog cache info:]
Table_open_cache_hits:4938    Table_open_cache_misses:0
Binlog_cache_use:820          Binlog_cache_disk_use:0
[###Hanler_xxx and Com_xxx info:]
Handler_delete:34574          Handler_update:675            Handler_write:1364
Handler_commit:5833           Handler_rollback:10
Com_commit:156                Com_rollback:5
U(counts):631     D(counts):159     I(counts):47      S(counts):4955    
--------------------------------------INNODBINFO------------------------------------------
[###Innodb_lock info:]
Innodb_row_lock_time:0                Innodb_row_lock_waits:0
Innodb_row_lock_current_waits:38
[###Innodb_buffer_pool info:]
Innodb_buf_pool_pages_total:1965840   Innodb_buf_pool_pages_dirty:19154
Innodb_buf_pages_data:1940433         Innodb_buf_pages_free:8116
Innodb_buffer_pool_wait_free:0        Innodb_buffer_pool_pages_misc:17291
Innodb_dblwr_pages_written:1188       Innodb_dblwr_writes:80
Innodb_buffer_pool_pages_flushed:2249
read_ahead:0          ahead_evict:0          ahead_rnd:0   
[###Innodb_log info:]
Innodb_log_writes:796                 Innodb_log_waits:0
Innodb_os_log_pending_fsyncs:0        Innodb_os_log_pending_writes:0
Innodb_os_log_written:44073472
[###Innodb_data read/writes info:]
Innodb_data_reads:684                 Innodb_data_read:11206656
Innodb_data_writes:2067               Innodb_data_written:63603200
Innodb_data_fsyncs:1017               Innodb_data_pending_fsyncs:0
Innodb_buffer_pool_reads(physics reads):423
Innodb_buffer_pool_read_requests(logic reads):2869823
[###Innodb_data rows info:]
U(rows):675     D(rows):34575   I(rows):194     S(rows):767094  
---------------------------------------TOTALINFO------------------------------------------
Bytes_received:911280         Bytes_sent:8653956


六、監控值說明:
(本部分,帶有作者自己的理解,如果有誤請指出)


文中
當前值輸出:保持show global status的當前值輸出
累計值相減輸出:用上一次的值減去下一次的值輸出,間隔為使用者指定的秒數


第一部分:
SysTime: Sun Jan 22 16:13:30 2017
Uptime:6963226    Connections:1       Aborted_clients:0       Max_used_connections:1319    


Uptime:The number of seconds the MySQL server has been running.(當前值輸出 單位秒)
Connections:The number of connection attempts (successful or not) to the MySQL server.(累計值相減輸出 單位次數)
Aborted_clients:The number of connections that were aborted because the client died without closing the connection
                properly.(累計值相減輸出,單位連線數)
Max_used_connections:The maximum number of connections that have been in use simultaneously since the server started.
                     (當前值輸出,單位連線數)
第二部分:
[###Threads info and qc  and :]
Threads_connected:252         Threads_running:4             Qcache_free_memory:0            
Qcache_hits:0                 Qcache_not_cached:0           Qcache_inserts:0        


Threads_connected:The number of currently open connections.(當前值輸出 單位連線數)
Threads_running:The number of threads that are not sleeping.(當前值輸出 單位連線數)
Qcache_free_memory:The amount of free memory for the query cache.(當前值輸出 單位位元組數)
Qcache_hits:The number of query cache hits.(累計值相減輸出 單位次數)
Qcache_not_cached:The number of noncached queries.(累計值相減輸出 單位次數)
Qcache_inserts:The number of queries added to the query cache.(累計值相減輸出 單位次數)


第三部分:
本部分全部是(累計值相減輸出 單位次數)
[###Table read info:]
Handler_read_first:211        Handler_read_key:8804         Handler_read_next:42346         
Handler_read_last:0           Handler_read_rnd:73           Handler_read_rnd_next:717694


Handler_read_first:
         /*索引中第一條記錄被讀的次數。如果較高,它表明伺服器正執行大量全索引掃描;例如,SELECT * order by id,假定id列有索引。
         * eg:
         * +----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------+
         * | id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra |
         * +----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------+
         * |  1 | SIMPLE      | testj | NULL       | index | NULL          | PRIMARY | 276     | NULL |   19 |   100.00 | NULL  |
         * +----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------+
         */
Handler_read_key:
         /*根據索引讀一行的請求數。如果較高,說明查詢和表的索引正確。本值可能是ref或者const也可能是range,只是代表索引KEY命中使用了索引
         * eg:
         * mysql> explain select * from testshared3 where id>1;
         * +----+-------------+-------------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
         * | id | select_type | table       | partitions | type  | possible_keys | key  | key_len | ref  | rows | filtered | Extra                 |
         * +----+-------------+-------------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
         * |  1 | SIMPLE      | testshared3 | NULL       | range | id            | id   | 5       | NULL |    1 |   100.00 | Using index condition |
         * +----+-------------+-------------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
         */
Handler_read_next:
         /*按照索引順序讀下一行的請求數,如果索引不唯一或者使用唯一索引的字首或者範圍都會觸發這個值,簡單的說只有唯一命中不觸發這個值
         * 這個值如果比較大說明需要連續訪問下一個key的次數非常多
         *
         *eg:
         *mysql> explain select * from testshared3 where id=1;
         *+----+-------------+-------------+------------+------+---------------+------+---------+-------+--------+----------+-------+
         *| id | select_type | table       | partitions | type | possible_keys | key  | key_len | ref   | rows   | filtered | Extra |
         *+----+-------------+-------------+------------+------+---------------+------+---------+-------+--------+----------+-------+
         *|  1 | SIMPLE      | testshared3 | NULL       | ref  | id            | id   | 5       | const | 523260 |   100.00 | NULL  |
         *+----+-------------+-------------+------------+------+---------------+------+---------+-------+--------+----------+-------+
         *
         *| Handler_read_key      | 49      |
         *| Handler_read_next     | 897698  |
         */
Handler_read_last:
        /*
         * 查詢讀索引最後一個索引鍵的請求數。當使用ORDER BY時,伺服器優先發出使用第一個索引的請求,之後順序往後掃描索引。當使用ORDER BY DESC時,
         * 伺服器優先發出使用最後一個索引的請求, 之後向前掃描索引。
         * 例如:select … order by id desc limit 10;
         */


Handler_read_rnd,Handler_read_rnd_next:這兩個值較大則可能遇到了全表掃描及type=ALL


這一部分則可以大體掌握當前資料庫全表掃描和索引使用的大概情況  
第四部分:
[###Sorts and temp tables info:]
Sort_rows:0                   Sort_merge_passes:0
Created_tmp_tables:163        Created_tmp_disk_tables:152


Sort_rows:The number of sorted rows.(累計值相減輸出 單位行數)
Sort_merge_passes:The number of merge passes that the sort algorithm has had to do.(累計值相減輸出 單位次數)
Created_tmp_tables:The number of internal temporary tables created by the server while executing statements.(累計值相減輸出 單位次數)
Created_tmp_disk_tables:The number of internal on-disk temporary tables created by the server while executing statements.(累計值相減輸出 單位次數)


很明顯這一部分說明了排序和臨時表使用情況,可以幫助DBA進行判斷


第五部分:
[###Table join info:]
Select_full_join:1            Select_scan:207

Select_full_join:The number of joins that perform table scans because they do not use indexes. 
                 If this value is not 0, you should carefully check the indexes of your tables
                 (累計值相減輸出 單位次數)
Select_scan:The number of joins that did a full scan of the first table. (累計值相減輸出 單位次數)

這兩個值則說明了jion的時候是否使用到了索引,特別是Select_full_join,應該比較低,否則說明被驅動表沒有使用到索引
應該引起重視,優化語句,一般來講Select_scan比較高是正常的因為驅動表如果沒有謂詞條件使用全表掃描是正常的方式


第六部分:
[###Open table cache and binlog cache info:]
Table_open_cache_hits:4938    Table_open_cache_misses:0
Binlog_cache_use:820          Binlog_cache_disk_use:0


Table_open_cache_hits:The number of hits for open tables cache lookups.(累計值相減輸出 單位次數)
Table_open_cache_misses:The number of misses for open tables cache lookups. (累計值相減輸出 單位次數)
Binlog_cache_use: The number of transactions that used the binary log cache. (累計值相減輸出 單位事物數)
Binlog_cache_disk_use:The number of transactions that used the temporary binary log cache but that exceeded the value 
                                 of binlog_cache_size and used a temporary file to store statements from the transaction.(累計值相減輸出 單位事物數)
明顯這部分說明了binlog_cache_size和 table_open_cache是否合適


第七部分:
本部分全部是(累計值相減輸出 單位次數)
[###Hanler_xxx and Com_xxx info:]
Handler_delete:34574          Handler_update:675            Handler_write:1364
Handler_commit:5833           Handler_rollback:10
Com_commit:156                Com_rollback:5
U(counts):631     D(counts):159     I(counts):47      S(counts):4955    

U(counts):631     D(counts):159     I(counts):47      S(counts):4955  
這一行是Com_update\Com_delete\Com_insert\Com_select的簡寫

Handler_xxx:這一批值說明的是相應操作處理的次數
Com_xxx:這一批值說明是相應操作對應語句發出的次數

比如Handler_commit 和 Com_commit這不同,如果是隱含提交和自動提交不用發起commit,但是
commit是處理了的,那麼Handler_commit增加而Com_rollback不變,又比如手動執行一個commit
Com_commit增加Handler_commit不變,因為雖然發起了commit命令並不需要處理實驗如下:


mysql> show status like '%commit%';
+----------------+-------+
| Variable_name  | Value |
+----------------+-------+
| Com_commit     | 1     |
| Com_xa_commit  | 0     |
| Handler_commit | 4     |
+----------------+-------+
3 rows in set (0.01 sec)


mysql> commit;
Query OK, 0 rows affected (0.00 sec)


mysql> show status like '%commit%';
+----------------+-------+
| Variable_name  | Value |
+----------------+-------+
| Com_commit     | 2     |
| Com_xa_commit  | 0     |
| Handler_commit | 4     |
+----------------+-------+
3 rows in set (0.00 sec)


第八部分:
[###Innodb_lock info:]
Innodb_row_lock_time:0                Innodb_row_lock_waits:0
Innodb_row_lock_current_waits:38


Innodb_row_lock_time:The total time spent in acquiring row locks for InnoDBtables, in milliseconds.(累計值相減輸出 單位毫秒)
Innodb_row_lock_waits:The number of times operations on InnoDB tables had to wait for a row lock.(累計值相減輸出 單位次數)
Innodb_row_lock_current_waits:The number of row lockscurrently being waited for by operations on InnoDB tables.(當前值輸出 單位個數)


明顯這一部分是對innodb 鎖的狀態的監控


第九部分:


[###Innodb_buffer_pool info:]
Innodb_buf_pool_pages_total:1965840   Innodb_buf_pool_pages_dirty:19154
Innodb_buf_pages_data:1940433         Innodb_buf_pages_free:8116
Innodb_buffer_pool_wait_free:0        Innodb_buffer_pool_pages_misc:17291
Innodb_dblwr_pages_written:1188       Innodb_dblwr_writes:80
Innodb_buffer_pool_pages_flushed:2249
read_ahead:0          ahead_evict:0          ahead_rnd:0       


Innodb_buf_pool_pages_total:及Innodb_buffer_pool_pages_data The total size of the InnoDB buffer pool, in pages.(當前值輸出 單位頁)
Innodb_buf_pool_pages_dirty:及Innodb_buffer_pool_pages_dirty The current number of dirty pagesin the InnoDB buffer pool.(當前值輸出 單位頁)
Innodb_buf_pages_data:及Innodb_buffer_pool_pages_data The number of pagesin the InnoDB buffer poolcontaining data. The number includes both dirtyand
                      clean pages.(當前值輸出 單位頁)
Innodb_buf_pages_free:及Innodb_buffer_pool_pages_free The number of free pagesin the InnoDB buffer pool.(當前值輸出 單位頁)
Innodb_buffer_pool_wait_free:Normally, writes to the InnoDB buffer poolhappen in the background. When InnoDBneeds to read or
                             create a pageand no clean pages are available, InnoDBflushes some dirty pagesfirst and waits for that
                             operation to finish. This counter counts instances of these waits.(累計值相減輸出 單位次數)


Innodb_buffer_pool_pages_misc:The number of pages in the InnoDB buffer pool that are busy because they have
                              been allocated for administrative overhead, such as row locks or the adaptive hash
                              index. This value can also be calculated as Innodb_buffer_pool_pages_total ?
                              Innodb_buffer_pool_pages_free ? Innodb_buffer_pool_pages_data.(當前值輸出 單位頁)


Innodb_dblwr_pages_written:The number of pages that have been written to the doublewrite buffer.(累計值相減輸出 單位頁)
Innodb_dblwr_writes:The number of doublewrite operations that have been performed. (累計值相減輸出 單位次數)
Innodb_buffer_pool_pages_flushed:The number of requests to flush pages from the InnoDB buffer pool.(累計值相減輸出 單位次數)


這部分是innodb_buffer_pool的重點包含了髒頁,資料頁,空閒頁等資訊,以及刷磁碟的次數


第十部分:
[###Innodb_log info:]
Innodb_log_writes:796                 Innodb_log_waits:0
Innodb_os_log_pending_fsyncs:0        Innodb_os_log_pending_writes:0
Innodb_os_log_written:44073472




Innodb_log_writes:The number of physical writes to the InnoDB redo logfile.(累計值相減輸出 單位次數)
Innodb_log_waits:The number of times that the log buffer was too small and a wait was required for it to be flushed before
                               continuing.(累計值相減輸出 單位次數)
Innodb_os_log_pending_fsyncs:The number of pending fsync() operations for the InnoDB redo logfiles.(累計值相減輸出 單位次數)
Innodb_os_log_pending_writes:The number of pending writes to the InnoDB redo logfiles.(累計值相減輸出 單位次數)
Innodb_os_log_written:The number of bytes written to the InnoDB redo logfiles.(累計值相減輸出 單位位元組)


這部分說明了 innodb redo 寫的資訊,如寫了多少資料,多少次等待,如果Innodb_os_log_pending_writes和Innodb_os_log_pending_fsyncs
不為0則說明遭遇了I/O等待。而Innodb_log_waits不為0則考慮innodb_log_buffer_size 是否過小。
注意:不管innodb_flush_method設定如何 redo始終使用kernel buffer。


第十一部分:
[###Innodb_data read/writes info:]
Innodb_data_reads:684                 Innodb_data_read:11206656
Innodb_data_writes:2067               Innodb_data_written:63603200
Innodb_data_fsyncs:1017               Innodb_data_pending_fsyncs:0
Innodb_buffer_pool_reads(physics reads):423
Innodb_buffer_pool_read_requests(logic reads):2869823


Innodb_data_reads:The total number of data reads.(累計值相減輸出 單位次數)
Innodb_data_read:The amount of data read since the server was started(累計值相減輸出 單位位元組數)
Innodb_data_writes:The total number of data writes.(累計值相減輸出 單位次數)
Innodb_data_written:The amount of data written so far, in bytes.(累計值相減輸出 單位位元組數)
Innodb_data_fsyncs:The number of fsync()operations so far. The frequency of fsync()calls is influenced by the setting
                            of the innodb_flush_method configuration option.(累計值相減輸出 單位次數)
Innodb_data_pending_fsyncs:The current number of pending fsync()operations. The frequency of fsync()calls is influenced by
                           the setting of the innodb_flush_method configuration option.(累計值相減輸出 單位次數)
Innodb_buffer_pool_reads(physics reads):The number of logical reads that InnoDB could not satisfy from the buffer pool, and had to read 
                                                        directly from disk.(累計值相減輸出 單位次數)
Innodb_buffer_pool_read_requests(logic reads):The number of logical read requests.(累計值相減輸出 單位次數)
read_ahead:及Innodb_buffer_pool_read_ahead:The number of pages read into the InnoDB buffer pool by the read-ahead background thread.(累計值相減輸出 單位頁)
ahead_evict:及Innodb_buffer_pool_read_ahead_evicted:The number of pagesread into the InnoDB buffer poolby the read-aheadbackground thread that were
                                                                                subsequently evictedwithout having been accessed by queries.(累計值相減輸出 單位頁)
ahead_rnd:及Innodb_buffer_pool_read_ahead_rnd:The number of “random”read-aheads initiated by InnoDB. This happens when a query scans a large
                                                                        portion of a table but in random order.(累計值相減輸出 單位次數)


這一部分可以看出邏輯讀取的命中率,預讀效率等,注意Innodb_data_pending_fsyncs和Innodb_data_fsyncs如果開啟了O_DIRECT,那麼innodb_buffer的記憶體
資料不會出現在kernel buffer,那麼fsyncs pending的情況會少得多。如果這兩個值較大注意磁碟I/O


第十二部分:
本部分全部是(累計值相減輸出 單位行數)
U(rows):675     D(rows):34575   I(rows):194     S(rows):767094  


U:Innodb_rows_updated
D:Innodb_rows_deleted
I:Innodb_rows_inserted
S:Innodb_rows_read


這部分真正的反應了DML和SELECT的行數,注意和Com_xxx和Handler_xxx的區別


第十三部分:
Bytes_received:911280         Bytes_sent:8653956


沒什麼好說的自己查文件


七、記憶體溢位檢測
    使用:
valgrind --tool=memcheck --leak-check=full  ./mymon5.7c -S/mysqldata/mysql5.7sla/mysqld3307.sock -t 1 -n 10
    
==5120== LEAK SUMMARY:
==5120==      definitely lost: 0 bytes in 0 blocks
==5120==      indirectly lost: 0 bytes in 0 blocks
==5120==      possibly lost: 232 bytes in 2 blocks
==5120==      still reachable: 8,176 bytes in 2 blocks
==5120==      suppressed: 0 bytes in 0 blocks
==5120== Reachable blocks (those to which a pointer was found) are not shown.
==5120== To see them, rerun with: --leak-check=full --show-reachable=yes
==5120== 
==5120== For counts of detected and suppressed errors, rerun with: -v
==5120== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 6 from 6)
可以看到沒有記憶體溢位


八、核心原始碼


點選(此處)摺疊或開啟

  1. main主調函式:
  2. /*************************************************************************
  3.   > File Name: main.c
  4.   > Author: gaopeng QQ:22389860 all right reserved
  5.   > Mail: gaopp_200217@163.com
  6.   > Created Time: Wed 08 Feb 2017 08:01:58 AM CST
  7.  ************************************************************************/

  8. #include"type.h"

  9. int useage(void)
  10. {
  11.         printf(
  12.             "Author: gaopeng QQ:22389860 Mail: gaopp_200217@163.com \n"
  13.                         "Info:This tool collect data from 'show global status' and show interval (-t) seconds data change\n"
  14.                         "help DBA to diagnose performance problem,when error or (-d) run log is at current dir name \n"
  15.                         "is mymon.log.\n"
  16.                         "WIN32 platform is not support\n"
  17.                         "Useage:./mymon [-u username] [-p password] -S socketfile/{-h hosname -P port} -t seconds -n times [-l logfile] [-d]\n"
  18.                         "[-?] :help info;\n"
  19.                         "[-u username] :connect to mysqld username,when no username requisite is optional;\n"
  20.                         "[-p password] :connect to mysqld password,when no password requisite is optional;\n"
  21.                         "[-S socketfile]:connect to mysqld socket file;\n"
  22.                         "[-h hostname] :connect to mysqld host;\n"
  23.                         "[-P port] :connect to mysqld port;\n"
  24.                         " socketfile or [hostname port] must;\n"
  25.                         "[-t seconds] :seconds of interval,this is necessary;\n"
  26.                         "[-n times] :how many times you watch,this is necessary;\n"
  27.                         "[-l logfile] :when you want to write information to a logfile provide a logfile name\n"
  28.                         " when a logfile provide no information at foreground,is optional;\n"
  29.                         "[-d] :more running log at logfile,otherwise error log in mymon.log;\n"
  30.                 );
  31.         return 0;
  32. }


  33. int wel(void)
  34. {
  35.         printf(
  36.             "welcome used this mysql monitor tool\n"
  37.                   "Author: gaopeng QQ:22389860 Mail: gaopp_200217@163.com \n"
  38.                         "Info:This tool collect data from 'show global status' and show interval (-t) seconds data change\n"
  39.                         "help DBA to diagnose performance problem,when error or (-d) run log is at current dir name \n"
  40.                         "is mymon.log.\n"
  41.                         "WIN32 platform is not support\n"
  42.                         "Useage:./mymon [-u username] [-p password] -S socketfile/{-h hosname -P port} -t seconds -n times [-l logfile] [-d]\n"
  43.                         "more help info in ./mymon -h\n"
  44.                         );
  45.         return 0;
  46. }

  47. int getpar( char (*par)[500],int n)
  48. {
  49.         int i;
  50.         for(i=0;i<4;i++)
  51.         {
  52.                 printf("your parameter is %s\n",*(par+i));
  53.         }
  54. }

  55. int checkpar(char (*par)[500],int t,int n)
  56. {
  57.         if(strlen(*(par+2)) == 0 && (strlen(*(par+4)) == 0 || strlen(*(par+5)) == 0 ))
  58.         {

  59.                 useage();
  60.                 return -1;
  61.         }

  62.         if(t==0||n==0)
  63.         {
  64.                 useage();
  65.                 return -1;
  66.         }
  67.         return 0;
  68. }

  69. int main(int argc,char* argv[])
  70. {
  71.         int ch;
  72.         int t = 0; //t how long
  73.         int n = 0;//n count
  74.         FILE* fd = 0;//log file fs
  75.         unsigned int mport = 0;//mysql connect port

  76.         debug = 0;
  77.         write_file = 0;
  78.         PAR par;
  79.         setbuf(stdout,NULL);//stdio buffer disable
  80.         memset(par,0,sizeof(PAR));
  81.         if(argc<2)
  82.         {
  83.                 useage();
  84.                 return -1;
  85.         }
  86.         while ((ch = getopt(argc, argv, "u:p:S:t:n:l:h:P:d?")) != -1)
  87.         {
  88.                 switch (ch)
  89.                 {
  90.                         case 'u':
  91.                                 if(strlen(optarg)>MAX_PAR_LEN)
  92.                                 {
  93.                                         printf("MYMON:username max length more than 500 bytes\n");
  94.                                         return -1;
  95.                                 }
  96.                                 strcpy(par[0],optarg);
  97.                                 break;
  98.                         case 'h':
  99.                                 if(strlen(optarg)>MAX_PAR_LEN)
  100.                                 {
  101.                                         printf("MYMON:hostname max length more than 500 bytes\n");
  102.                                         return -1;
  103.                                 }
  104.                                 strcpy(par[4],optarg);
  105.                                 break;
  106.                         case 'P':
  107.                                 if(strlen(optarg)>MAX_PAR_LEN)
  108.                                 {
  109.                                         printf("MYMON:port max length more than 500 bytes\n");
  110.                                         return -1;
  111.                                 }
  112.                                 strcpy(par[5],optarg);
  113.                                 sscanf (par[5],"%u",&mport);
  114.                                 break;
  115.                         case 'p':
  116.                                 if(strlen(optarg)>MAX_PAR_LEN)
  117.                                 {
  118.                                         printf("MYMON:password max length more than 500 bytes\n");
  119.                                         return -1;
  120.                                 }
  121.                                 strcpy(par[1],optarg);
  122.                                 break;
  123.                         case 'S':
  124.                                 if(strlen(optarg)>MAX_PAR_LEN)
  125.                                 {
  126.                                         printf("MYMON:socket max length more than 500 bytes\n");
  127.                                         return -1;
  128.                                 }
  129.                                 strcpy(par[2],optarg);
  130.                                 break;
  131.                         case 't':
  132.                                 sscanf (optarg,"%d",&t);
  133.                                 break;
  134.                         case 'n':
  135.                                 sscanf (optarg,"%d",&n);
  136.                                 break;
  137.                         case 'l':
  138.                                 if(strlen(optarg)>MAX_PAR_LEN)
  139.                                 {
  140.                                         printf("MYMON:logfile name max length more than 500 bytes\n");
  141.                                         return -1;
  142.                                 }
  143.                                 strcpy(par[3],optarg);
  144.                                 if((fd = fopen(par[3],OPENFLAG)) == NULL)
  145.                                 {
  146.                                         perror("MYMON:");
  147.                                         return -1;
  148.                                 }
  149.                                 write_file = 1;
  150.                                 setbuf(fd,NULL);//stdio buffer disable
  151.                                 break;
  152.                         case 'd':
  153.                                 debug = 1;
  154.                                 break;
  155.                         default:
  156.                         case '?':
  157.                                 useage();
  158.                                 return -1;
  159.                 }
  160.         }

  161.         if(checkpar(par,t,n) == -1)
  162.         {
  163.                 printf("MYMON:must parameter error\n");
  164.                 return -1;
  165.         }
  166.         wel();
  167.         if(conn(par,t,n+1,fd,mport) !=0)
  168.                 {
  169.                         printf("MYMON:error pelase check log\n");
  170.                         return -1;
  171.                 }
  172.         if(write_file == 1)
  173.                 {
  174.                         fclose(fd);
  175.                 }
  176.         return 0;
  177. }


點選(此處)摺疊或開啟

  1. fun.c功能實現介面函式
  2. /*************************************************************************
  3.   > File Name: fun.c
  4.   > Author: gaopeng QQ:22389860 all right reserved
  5.   > Mail: gaopp_200217@163.com
  6.   > Created Time: Wed 08 Feb 2017 10:08:56 AM CST
  7.  ************************************************************************/
  8.  /*
  9.         This file frist store new and old data to one data struct
  10.         **struct->*struct->struct
  11.         struct have three pointer
  12.         statname
  13.         olddata
  14.         newdata

  15.         Then sub new and old data to one struct array
  16.         Last use array to print data
  17. */

  18.  

  19. #include"type.h"
  20. #include"fun.h"

  21. /*
  22.  * field pointer to status name
  23.  * olddata pointer to prev data
  24.  * newdata pointer to now data
  25.  */


  26. typedef struct MDATA
  27. {
  28.         char* statname;
  29.         char* olddata;
  30.         char* newdata;
  31. } MDATA;

  32. typedef struct D_STROE
  33. {
  34.         char statname[MAXSTATNAME];
  35.         int64_t data;
  36. } D_STROE;


  37. /* ret=0 is sucss ret<0 is false*/
  38. int handle_data(MYSQL_RES *result/*in*/,uint64_t row_count,unsigned int row_field,FILE* fd,MDATA* *datap/*in*/,int i);
  39. /* ret=0 is sucss ret<0 is false*/
  40. int memaloc(MDATA** *datap/*out*/,uint64_t row_count);
  41. /* ret=0 is sucss ret<0 is false*/
  42. int sub_store_data(MDATA* *datap,D_STROE* *last_data/*out*/,uint64_t row_count,int* lenth/*in*/);
  43. /* ret=0 is sucss ret<0 is false*/
  44. int print_data(D_STROE* last_data,int lenth,FILE* fd) ;
  45. /* ret=-1 is no data return >=0 and -65535 is data return */
  46. int64_t findva(const char* ins,D_STROE* last_data,int lenth);
  47. /* no retrun value*/
  48. int freedatap(MDATA* *datap,uint64_t row_count);

  49. static freecouti=0;

  50. void test(void)
  51. {
  52.         ;
  53. }


  54. int mprintf(FILE* outfile,const char *format,...)
  55. {
  56.     va_list args;
  57.     va_start(args,format);
  58.     if( vfprintf(outfile,format,args) <0 )
  59.         {
  60.                 GET_LOG(LogLevel[4],ERROR,"ERROR:mprintf() error:%d\n",ERROR);
  61.                         printf("MYMON: mprintf() error:%d\n",ERROR);
  62.                         exit(-1);
  63.         }
  64.     va_end(args);
  65.         return 0;
  66. }



  67. int xfree(void* p)
  68. {
  69.         if(p==NULL)
  70.         {
  71.                 freecouti++;
  72.                 if(debug == 3)
  73.                 {
  74.                         GET_LOG(LogLevel[1],DEBUG,"DEBUG:xfree(NULL) debug:%d\n",freecouti);
  75.                 }
  76.                 return 0;
  77.         }
  78.         free(p);
  79.         p=NULL;
  80.         return 0;
  81. }

  82. int conn(char (*par)[500]/*in*/,int t,int n,FILE* fd,unsigned int myport)
  83. {
  84.         MYSQL conn_ptr;
  85.         MYSQL_RES *query_res =NULL;
  86.         MYSQL_ROW sqlrow_data;
  87.         int ret = 0;
  88.         uint64_t row_count = 0;
  89.         unsigned int row_field = 0;
  90.         MDATA* *datap =NULL;
  91.         int i=0;//used to check frist time no old data


  92.         /*
  93.          *MYSQL *mysql_init(MYSQL *mysql)
  94.          *An initialized MYSQL*handle. NULLif there was insufficient memory to allocate a new object.
  95.          */
  96.         if(mysql_init(&conn_ptr) == NULL)
  97.         {
  98.                 ret = -1;
  99.                 GET_LOG(LogLevel[4],ERROR,"ERROR:mysql_init() error:%d\n",ERROR);
  100.                 printf("MYMON: mysql_init() error\n");
  101.                 return ret;
  102.         }
  103.         /*
  104.          *MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user,
  105.          *const char *passwd, const char *db, unsigned int port, const char *unix_socket,
  106.          *unsigned long client_flag)
  107.          *A MYSQL*connection handle if the connection was successful, NULLif the connection was unsuccessful.
  108.          *For a successful connection, the return value is the same as the value of the first parameter
  109.          */
  110.         if(mysql_real_connect(&conn_ptr,*(par+4),*par,*(par+1),NULL,myport,*(par+2),0)==NULL)
  111.         {
  112.                 ret = -2;
  113.                 GET_LOG(LogLevel[4],ERROR,"ERROR:mysql_real_connect() error:%d\n",ERROR);
  114.                 printf("MYMON: mysql_real_connect() error\n");
  115.                 if(mysql_errno(&conn_ptr))
  116.                 {
  117.                         GET_LOG(LogLevel[4],ERROR,"ERROR:mysql_real_connect() error:%s\n",mysql_error(&conn_ptr));
  118.                         printf("MYMON: mysql_real_connect() error:%s\n",mysql_error(&conn_ptr));
  119.                 }
  120.                 return ret;
  121.         }

  122.         while(n--)
  123.         {
  124.                 /*
  125.                  *int mysql_query(MYSQL *mysql, const char *stmt_str)
  126.                  *Zero for success. Nonzero if an error occurred.
  127.                  */
  128.                 if((mysql_query(&conn_ptr,"show global status")) != 0)
  129.                 {
  130.                         ret = -3;
  131.                         GET_LOG(LogLevel[4],ERROR,"ERROR:mysql_query() error:%s\n",mysql_error(&conn_ptr));
  132.                         printf("MYMON: mysql_query() error:%s\n",mysql_error(&conn_ptr));
  133.                         return ret;
  134.                 }
  135.                 /*
  136.                  * MYSQL give memory out
  137.                  * MYSQL_RES *mysql_store_result(MYSQL *mysql)
  138.                  * A MYSQL_RESresult structure with the results. NULL(0) if an error occurred
  139.                  */

  140.                 if((query_res=mysql_store_result(&conn_ptr)) == NULL)
  141.                 {
  142.                         ret = -4;
  143.                         GET_LOG(LogLevel[4],ERROR,"ERROR:mysql_store_result() error:%s\n",mysql_error(&conn_ptr));
  144.                         printf("MYMON: mysql_store_result() error:%s\n",mysql_error(&conn_ptr));
  145.                         return ret;
  146.                 }
  147.                 /*
  148.                  * my_ulonglong mysql_num_rows(MYSQL_RES *result)
  149.                  * The number of rows in the result set.
  150.                  * unsigned int mysql_num_fields(MYSQL_RES *result)
  151.                  * An unsigned integer representing the number of columns in a result set
  152.                  */
  153.                 row_count = mysql_num_rows(query_res);
  154.                 row_field = mysql_field_count(&conn_ptr);
  155.                 if(debug == 1)
  156.                 {
  157.                         GET_LOG(LogLevel[2],INFO,"INFO:mysql_num_rows() rows is %llu\n",row_count);
  158.                         GET_LOG(LogLevel[2],INFO,"INFO:mysql_field_count() fileds is %ld\n",row_field);
  159.                         printf("MYMON: mysql_num_rows() rows is %llu\n",row_count);
  160.                         printf("MYMON: mysql_field_count() fileds is %ld\n",row_field);
  161.                 }
  162.                 if(i == 0)
  163.                 {
  164.                         if((memaloc(&datap,row_count)) !=0)
  165.                         {
  166.                                 ret = -6;
  167.                                 GET_LOG(LogLevel[4],ERROR,"ERROR:memaloc() error:%s\n","ERROR");
  168.                                 printf("MYMON: memaloc() error:%s\n","ERROR");
  169.                                 return ret;
  170.                         }
  171.                 }
  172.                 if(handle_data(query_res,row_count,row_field,fd,datap,i)!=0)
  173.                 {
  174.                         ret = -5;
  175.                         GET_LOG(LogLevel[4],ERROR,"ERROR:handle_data() error:%s\n","ERROR");
  176.                         printf("MYMON: handle_data() error:%s\n","ERROR");
  177.                         return ret;
  178.                 }

  179.                 /*
  180.                  * void mysql_free_result(MYSQL_RES *result)
  181.                  * no result
  182.                  */
  183.                 mysql_free_result(query_res);
  184.                 sleep(t);
  185.                 i++;
  186.         }
  187.         /*
  188.          * void mysql_close(MYSQL *mysql)
  189.          * no result
  190.          */

  191.         /*hear free datap*/
  192.                 {
  193.                         freedatap(datap,row_count);
  194.                 }
  195.         mysql_close(&conn_ptr);
  196.         return ret;
  197. }


  198. int freedatap(MDATA* *datap,uint64_t row_count)
  199. {
  200.         int ret = 0;
  201.         uint64_t i = 0;
  202.         if(datap == NULL)
  203.                 {
  204.                         return ret;
  205.                 }
  206.         GET_LOG(LogLevel[3],INFO,"INFO:freedatap() check previous line is error?:%d\n",ret);
  207.         for(i=0;i<row_count;i++)
  208.                 {
  209.                         xfree ((*(datap+i))->statname);
  210.                         xfree((*(datap+i))->newdata);
  211.                         xfree((*(datap+i))->olddata);
  212.                         xfree(*(datap+i));
  213.                 }
  214.         xfree(datap);
  215.         return ret;
  216. }
  217. int memaloc(MDATA** *datap,uint64_t row_count)
  218. {
  219.         int ret=0;
  220.         MDATA* *mp=NULL;
  221.         uint64_t i=0;

  222.         if(datap == NULL)
  223.         {
  224.                 ret = -5;
  225.                 GET_LOG(LogLevel[4],ERROR,"ERROR:memaloc() datap=NULL?:%d\n",ret);
  226.                 printf("MYMON: memaloc() datap=NULL?:%d\n",ret);
  227.                 return ret;
  228.         }
  229.         if((mp = (MDATA**)calloc(1,row_count*sizeof(MDATA*))) == NULL)
  230.         {
  231.                 ret = -3;
  232.                 GET_LOG(LogLevel[4],ERROR,"ERROR:memaloc() memory malloc **p error:%d\n",ret);
  233.                 printf("MYMON: memaloc() memory malloc **p error:%d\n",ret);
  234.                 return ret;
  235.         }
  236.         for(i=0;i<row_count;i++)
  237.         {
  238.                 if((*(mp+i)=(MDATA*)calloc(1,sizeof(MDATA))) == NULL)
  239.                 {
  240.                         ret=-4;
  241.                         GET_LOG(LogLevel[4],ERROR,"ERROR:handle_data() memory malloc *p error:%d\n",ret);
  242.                         printf("MYMON: MYMON:handle_data() memory malloc *p error:%d\n",ret);
  243.                         freedatap(mp,row_count);
  244.                         return ret;
  245.                 }
  246.         }
  247.         *datap = mp;
  248.         return ret;

  249. }


  250. int handle_data(MYSQL_RES *result,uint64_t row_count,unsigned int row_field,FILE* fd,MDATA* *datap,int seq)
  251. {
  252.         uint64_t i = 0;
  253.         MYSQL_ROW sqlrow_data;
  254.         int ret = 0;
  255.         D_STROE* last_data=NULL;//used last data store
  256.         int lenth=0;//last data lenth

  257.         //tmp
  258.         int tmp = 0;
  259.     D_STROE* tmp_last_data = NULL;

  260.         if(result == NULL||datap == NULL)
  261.         {
  262.                 ret = -2;
  263.                 GET_LOG(LogLevel[4],ERROR,"ERROR:handle_data() result == NULL datap == NULL :%s\n","ERROR");
  264.                 printf("MYMON:handle_data() result == NULL datap == NULL :%s\n","ERROR");
  265.                 return ret;
  266.         }

  267.         for(i=0;i<row_count;i++)//control true result return
  268.         {
  269.                 /*
  270.                  * MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
  271.                  * A MYSQL_ROW structure for the next row. NULL if there are no more rows to retrieve or if an error occurred
  272.                  */
  273.                 if((sqlrow_data=mysql_fetch_row(result)) == NULL) //control mysql_fetch_row error
  274.                 {
  275.                         ret = -1;
  276.                         GET_LOG(LogLevel[4],ERROR,"ERROR:mysql_fetch_row() error:%s\n","ERROR");
  277.                         printf("MYMON: mysql_fetch_row() error:%s\n","ERROR");
  278.                         return ret;
  279.                 }
  280.                 {
  281.                         unsigned long *lengths;
  282.                         lengths = mysql_fetch_lengths(result);
  283.                         xfree((*(datap+i))->statname);
  284.                         if(((*(datap+i))->statname = (char*)calloc(1,lengths[0]+10)) == NULL)
  285.                         {
  286.                                 ret = -4;
  287.                                 GET_LOG(LogLevel[4],ERROR,"ERROR:handle_data() statname loop mem alloc error:%s\n","ERROR");
  288.                                 printf("MYMON: handle_data() statname loop mem alloc error:%s\n","ERROR");
  289.                                 return ret;

  290.                         }
  291.                         strcpy((*(datap+i))->statname,sqlrow_data[0] ? sqlrow_data[0] : "NULL");
  292.                         xfree((*(datap+i))->olddata);
  293.                         (*(datap+i))->olddata = (*(datap+i))->newdata;
  294.                         //no free newdata pointer
  295.                         if(((*(datap+i))->newdata = (char*)calloc(1,lengths[1]+10)) == NULL)
  296.                         {
  297.                                 ret = -5;
  298.                                 GET_LOG(LogLevel[4],ERROR,"ERROR:handle_data() newdata loop mem alloc error:%s\n","ERROR");
  299.                                 printf("MYMON: handle_data() newdata loop mem alloc error:%s\n","ERROR");
  300.                                 return ret;
  301.                         }
  302.                         strcpy((*(datap+i))->newdata,sqlrow_data[1] ? sqlrow_data[1] : "NULL");
  303.                         if(debug == 1)
  304.                                 {
  305.                                if((!strcmp((*(datap+i))->statname,"NULL")) || (!strcmp((*(datap+i))->newdata,"NULL")) )
  306.                                 {
  307.                                         GET_LOG(LogLevel[1],DEBUG,"DEBUG:handle_data() statname or data IS NULL:[%s]\n",(*(datap+i))->statname);
  308.                                                 GET_LOG(LogLevel[1],DEBUG,"DEBUG:handle_data() statname or data IS NULL:[%s]\n",(*(datap+i))->newdata);
  309.                                 }
  310.                                 }
  311.                 }

  312.         }
  313.         if(seq == 0)//olddata have no data
  314.                 {
  315.                         if(debug == 1)
  316.                                 {
  317.                         GET_LOG(LogLevel[1],DEBUG,"DEBUG:handle_data() first time is info %s\n","no old data");
  318.                         printf("MYMON: handle_data() first time is info %s\n","no old data");
  319.                                 }
  320.                 }
  321.         if(seq != 0 ) //newdata and olddata have data
  322.                 {
  323.                         if(sub_store_data(datap,&last_data,row_count,&lenth) != 0 ) //store data to array
  324.                                 {
  325.                                         ret = -6;
  326.                                         GET_LOG(LogLevel[4],ERROR,"ERROR:handle_data() sub_store_data() error:%s\n","ERROR");
  327.                                         printf("MYMON: handle_data() sub_store_data() error %s\n","ERROR");
  328.                                         return ret;
  329.                                 }
  330.                 if(debug == 1)
  331.                         {
  332.                         tmp_last_data = last_data;
  333.                         for(tmp =0;tmp<lenth;tmp++)
  334.                                 {
  335.                                         GET_LOG(LogLevel[1],DEBUG,"DEBUG:handle_data() find data is [%s]",(tmp_last_data)->statname);
  336.                                         GET_LOG(LogLevel[1],DEBUG,"[%lld] \n",(tmp_last_data)->data);
  337.                                         tmp_last_data++;
  338.                                 }
  339.                         }



  340.                         if(print_data(last_data,lenth,fd) != 0) //store data from array
  341.                                 {
  342.                                         ret = -7;
  343.                                         GET_LOG(LogLevel[4],ERROR,"ERROR:handle_data() print_data() error:%s\n","ERROR");
  344.                                         printf("MYMON: handle_data() print_data() error %s\n","ERROR");
  345.                                         return ret;
  346.                                 }

  347.                 }
  348.         //used end free last data array
  349.         xfree(last_data);
  350.         return ret;
  351. }


  352. int sub_store_data(MDATA* *datap,D_STROE* *last_data,uint64_t row_count,int* lenth)
  353. {
  354.         D_STROE* tmp_p = NULL;
  355.         int ret = 0;
  356.         uint64_t i = 0;

  357.         char* *dyd_d = NULL;
  358.         char* *std_d = NULL;
  359.         int64_t a = 0;
  360.         int64_t b = 0;

  361.         if(datap == NULL || last_data == NULL )
  362.                 {
  363.                     ret = -1;
  364.                         GET_LOG(LogLevel[4],ERROR,"ERROR:sub_store_data() datap == NULL || fail_data == NULL %s\n","ERROR");
  365.                         printf("MYMON: sub_store_data() datap == NULL || fail_data == NULL %s\n","ERROR");
  366.                         return ret;
  367.                 }

  368.         if((tmp_p = (D_STROE*)calloc(1,(sizeof(stdata)+sizeof(dydata))*sizeof(D_STROE))) == NULL)
  369.                 {
  370.                         ret = -2;
  371.                         GET_LOG(LogLevel[4],ERROR,"ERROR:sub_store_data() mem alloc error:%s\n","ERROR");
  372.                         printf("MYMON: sub_store_data() mem alloc error:%s\n","ERROR");
  373.                         return ret;
  374.                 }
  375.         *last_data = tmp_p;

  376.         for(i=0;i<row_count;i++)
  377.                 {
  378.                         dyd_d = dydata; //re pointer to dydata
  379.                 std_d = stdata; //re pointer to dydata
  380.                         if(strlen((*(datap+i))->statname)>MAXSTATNAME)
  381.                                 {
  382.                                         ret = -3;
  383.                                         GET_LOG(LogLevel[4],ERROR,"ERROR:sub_store_data() statname>MAXSTATNAME:%s\n","ERROR");
  384.                                         printf("MYMON: sub_store_data() statname>MAXSTATNAME:%s\n","ERROR");
  385.                                         goto er;
  386.                                 }
  387.                         while(*dyd_d)
  388.                                 {
  389.                                         if(debug == 3)
  390.                                                 {
  391.                                                         printf("dyd [%s] [%s] [%d] [%d]\n",*dyd_d,(*(datap+i))->statname,strlen(*dyd_d),strlen((*(datap+i))->statname));
  392.                                                 }
  393.                                         if(!strcmp(*dyd_d,(*(datap+i))->statname))
  394.                                                 {

  395.                                                         if(debug == 1)
  396.                                                                 {
  397.                                                                         GET_LOG(LogLevel[1],DEBUG,"DEBUG:sub_store_data() find data is %s \n",*dyd_d);
  398.                                                                 }
  399.                                                         strcpy(tmp_p->statname,*dyd_d);
  400.                                                         if( !strcmp((*(datap+i))->olddata,"NULL") || !strcmp((*(datap+i))->newdata,"NULL")) //check "NULL" DATA ?
  401.                                                                 {
  402.                                                                         GET_LOG(LogLevel[2],INFO,"INFO:sub_store_data() data %s is [NULL] \n",*dyd_d);
  403.                                                                         tmp_p->data = ERRORDATA;
  404.                                                                 }
  405.                                                         if(sscanf((*(datap+i))->olddata,"%lld",&a) == EOF || sscanf((*(datap+i))->newdata,"%lld",&b) == EOF)
  406.                                                                 {
  407.                                                                         ret = -4;
  408.                                                                         GET_LOG(LogLevel[4],ERROR,"ERROR:sub_store_data() sscanf() error %s\n","ERROR");
  409.                                                                         printf("MYMON: sub_store_data() sscanf() error:%s\n","ERROR");
  410.                                                                         goto er;
  411.                                                                 }
  412.                                                         tmp_p->data = b-a; //new - old
  413.                                                         tmp_p++;
  414.                                                         (*lenth)++;
  415.                                                         break;
  416.                                                 }
  417.                                         dyd_d++;
  418.                                 }
  419.                         while(*std_d)
  420.                                 {
  421.                                         if(debug == 3)
  422.                                                 {
  423.                                                         printf("std [%s] [%s] [%d] [%d]\n",*std_d,(*(datap+i))->statname,strlen(*std_d),strlen((*(datap+i))->statname));
  424.                                                 }
  425.                                         if(!strcmp(*std_d,(*(datap+i))->statname))
  426.                                                 {

  427.                                                      if(debug == 1)
  428.                                                                 {
  429.                                                                         GET_LOG(LogLevel[1],DEBUG,"DEBUG:sub_store_data() find data is %s \n",*std_d);
  430.                                                                 }
  431.                                                         strcpy(tmp_p->statname,*std_d);
  432.                                                         if(!strcmp((*(datap+i))->newdata,"NULL")) //check "NULL" DATA ?
  433.                                                                 {
  434.                                                                         GET_LOG(LogLevel[2],INFO,"INFO:sub_store_data() data %s is [NULL] \n",*std_d);
  435.                                                                         tmp_p->data = ERRORDATA;
  436.                                                                 }
  437.                                                         if(sscanf((*(datap+i))->olddata,"%lld",&tmp_p->data) == EOF)
  438.                                                                 {
  439.                                                                         ret = -4;
  440.                                                                         GET_LOG(LogLevel[4],ERROR,"ERROR:sub_store_data() sscanf() error %s\n","ERROR");
  441.                                                                         printf("MYMON: sub_store_data() sscanf() error:%s\n","ERROR");
  442.                                                                         goto er;
  443.                                                                 }
  444.                                                         tmp_p++;
  445.                                                         (*lenth)++;
  446.                                                         break;
  447.                                                 }
  448.                                 std_d++;
  449.                                 }
  450.                 }
  451.         return ret;

  452.         er:
  453.                 xfree(tmp_p);
  454.                 *last_data= NULL;
  455.                 return ret;
  456. }

  457. int print_data(D_STROE* last_data,int lenth,FILE* fd)
  458. {
  459.         time_t rawtime;
  460.         struct tm * timeinfo = NULL;
  461.         int ret = 0;
  462.         FILE* outfile = NULL;
  463.         if(write_file == 1)
  464.                 {
  465.                         outfile=fd;
  466.                 }
  467.         else
  468.                 {
  469.                         outfile=stdout;
  470.                 }

  471.         if(time (&rawtime) == -1)
  472.                 {
  473.                         ret = -2;
  474.                         GET_LOG(LogLevel[4],ERROR,"ERROR:print_data() time() error %s\n","ERROR");
  475.             printf("MYMON: ERROR:print_data() time() error:%s\n","ERROR");
  476.                         return ret;
  477.                 }
  478.         timeinfo = localtime ( &rawtime );
  479.         if (timeinfo == NULL )
  480.                 {
  481.                         ret = -1;
  482.                         GET_LOG(LogLevel[4],ERROR,"ERROR:print_data() localtime () error %s\n","ERROR");
  483.                         printf("MYMON: ERROR:print_data() localtime () error:%s\n","ERROR");
  484.                         return ret;
  485.                 }
  486.         mprintf(outfile,"------------------------------------------MYMON--------------------------------------------\n");
  487.         mprintf(outfile,"SysTime: %s",asctime (timeinfo));
  488.         mprintf(outfile,
  489.                     "%s%-11ld%s%-8ld%s%-8ld%s%-8ld\n",
  490.                         "Uptime:",findva("Uptime",last_data,lenth),
  491.                         "Connections:",findva("Connections",last_data,lenth) ,
  492.                         "Aborted_clients:",findva("Aborted_clients",last_data,lenth),
  493.                         "Max_used_connections:",findva("Max_used_connections",last_data,lenth));
  494.         mprintf(outfile,"--------------------------------------MYSQLINFO-------------------------------------------\n");
  495.         mprintf(outfile,"[###Threads info and qc info:]\n");
  496.         mprintf(outfile,
  497.                     "%s%-12ld%s%-14ld%s%-13ld\n",
  498.                    "Threads_connected:",findva("Threads_connected",last_data,lenth),
  499.            "Threads_running:",findva("Threads_running",last_data,lenth),
  500.            "Qcache_free_memory:",findva("Qcache_free_memory",last_data,lenth)
  501.                         );
  502.         mprintf(outfile,
  503.                     "%s%-18ld%s%-12ld%s%-17ld\n",
  504.                    "Qcache_hits:",findva("Qcache_hits",last_data,lenth),
  505.                    "Qcache_not_cached:",findva("Qcache_not_cached",last_data,lenth),
  506.                    "Qcache_inserts:",findva("Qcache_inserts",last_data,lenth)
  507.                   );
  508.         mprintf(outfile,"[###Table read info:]\n");
  509.         mprintf(outfile,
  510.                     "%s%-11ld%s%-13ld%s%-14ld\n",
  511.                         "Handler_read_first:",findva("Handler_read_first",last_data,lenth),
  512.                         "Handler_read_key:",findva("Handler_read_key",last_data,lenth),
  513.                         "Handler_read_next:",findva("Handler_read_next",last_data,lenth)
  514.                         );

  515.         mprintf(outfile,
  516.                     "%s%-12ld%s%-13ld%s%ld\n",
  517.                         "Handler_read_last:",findva("Handler_read_last",last_data,lenth),
  518.                         "Handler_read_rnd:",findva("Handler_read_rnd",last_data,lenth),
  519.                         "Handler_read_rnd_next:",findva("Handler_read_rnd_next",last_data,lenth)
  520.                         );
  521.         mprintf(outfile,"[###Sorts and temp tables info:]\n");
  522.         mprintf(outfile,
  523.                     "%s%-20ld%s%ld\n",
  524.                     "Sort_rows:",findva("Sort_rows",last_data,lenth),
  525.                         "Sort_merge_passes:",findva("Sort_merge_passes",last_data,lenth)
  526.                         );
  527.         mprintf(outfile,
  528.                     "%s%-11ld%s%ld\n",
  529.                         "Created_tmp_tables:",findva("Created_tmp_tables",last_data,lenth),
  530.                         "Created_tmp_disk_tables:",findva("Created_tmp_disk_tables",last_data,lenth)
  531.                         );
  532.         mprintf(outfile,"[###Table join info:]\n");
  533.     mprintf(outfile,
  534.                     "%s%-13ld%s%ld\n",
  535.                         "Select_full_join:",findva("Select_full_join",last_data,lenth),
  536.                         "Select_scan:",findva("Select_scan",last_data,lenth)
  537.                         );
  538.          
  539.           mprintf(outfile,"[###Open table cache and binlog cache info:]\n");
  540.           mprintf(outfile,
  541.                     "%s%-8ld%s%ld\n",
  542.                         "Table_open_cache_hits:",findva("Table_open_cache_hits",last_data,lenth),
  543.                         "Table_open_cache_misses:",findva("Table_open_cache_misses",last_data,lenth)
  544.                         );
  545.           mprintf(outfile,
  546.                     "%s%-13ld%s%ld\n",
  547.                         "Binlog_cache_use:",findva("Binlog_cache_use",last_data,lenth),
  548.                         "Binlog_cache_disk_use:",findva("Binlog_cache_disk_use",last_data,lenth)
  549.                         );
  550.          mprintf(outfile,"[###Hanler_xxx and Com_xxx info:]\n");

  551.          mprintf(outfile,
  552.                     "%s%-15ld%s%-15ld%s%ld\n",
  553.                         "Handler_delete:",findva("Handler_delete",last_data,lenth),
  554.                         "Handler_update:",findva("Handler_update",last_data,lenth),
  555.                         "Handler_write:",findva("Handler_write",last_data,lenth)
  556.                         );
  557.          mprintf(outfile,
  558.                     "%s%-15ld%s%-ld\n",
  559.                         "Handler_commit:",findva("Handler_commit",last_data,lenth),
  560.                         "Handler_rollback:",findva("Handler_rollback",last_data,lenth)
  561.                         );
  562.           mprintf(outfile,
  563.                          "%s%-19ld%s%ld\n",
  564.                          "Com_commit:",findva("Com_commit",last_data,lenth),
  565.                          "Com_rollback:",findva("Com_rollback",last_data,lenth)
  566.                          );
  567.         mprintf(outfile,
  568.                     "%s%-8ld%s%-8ld%s%-8ld%s%-8ld\n",
  569.                         "U(counts):",findva("Com_update",last_data,lenth),
  570.                         "D(counts):",findva("Com_delete",last_data,lenth),
  571.                         "I(counts):",findva("Com_insert",last_data,lenth),
  572.                         "S(counts):",findva("Com_select",last_data,lenth)
  573.                         );
  574.     mprintf(outfile,
  575.                    "--------------------------------------INNODBINFO------------------------------------------\n");
  576.     mprintf(outfile,"[###Innodb_lock info:]\n");
  577.         mprintf(outfile,
  578.                     "%s%-17ld%s%ld\n",
  579.                         "Innodb_row_lock_time:",findva("Innodb_row_lock_time",last_data,lenth),
  580.                         "Innodb_row_lock_waits:",findva("Innodb_row_lock_waits",last_data,lenth)
  581.                         );
  582.         mprintf(outfile,
  583.                     "%s%ld\n",
  584.                         "Innodb_row_lock_current_waits:",findva("Innodb_row_lock_current_waits",last_data,lenth)
  585.                         );
  586.     mprintf(outfile,"[###Innodb_buffer_pool info:]\n");

  587.         mprintf(outfile,"%s%-10ld%s%ld\n","Innodb_buf_pool_pages_total:",findva("Innodb_buffer_pool_pages_total",last_data,lenth)
  588.                     ,"Innodb_buf_pool_pages_dirty:",findva("Innodb_buffer_pool_pages_dirty",last_data,lenth));

  589.         mprintf(outfile,"%s%-16ld%s%ld\n","Innodb_buf_pages_data:",findva("Innodb_buffer_pool_pages_data",last_data,lenth)
  590.                     ,"Innodb_buf_pages_free:",findva("Innodb_buffer_pool_pages_free",last_data,lenth));

  591.         mprintf(outfile,
  592.                     "%s%-9ld%s%ld\n",
  593.                         "Innodb_buffer_pool_wait_free:",findva("Innodb_buffer_pool_wait_free",last_data,lenth),
  594.                         "Innodb_buffer_pool_pages_misc:",findva("Innodb_buffer_pool_pages_misc",last_data,lenth)
  595.                         );
  596.         mprintf(outfile,
  597.                     "%s%-11ld%s%ld\n",
  598.                         "Innodb_dblwr_pages_written:",findva("Innodb_dblwr_pages_written",last_data,lenth),
  599.                         "Innodb_dblwr_writes:",findva("Innodb_dblwr_writes",last_data,lenth)
  600.                         );

  601.         mprintf(outfile,
  602.                     "%s%ld\n",
  603.                         "Innodb_buffer_pool_pages_flushed:",findva("Innodb_buffer_pool_pages_flushed",last_data,lenth)
  604.                         );
  605.         mprintf(outfile,
  606.                      "%s%-10ld %s%-10ld %s%-10ld\n",
  607.                      "read_ahead:",findva("Innodb_buffer_pool_read_ahead",last_data,lenth),
  608.                      "ahead_evict:",findva("Innodb_buffer_pool_read_ahead_evicted",last_data,lenth),
  609.                      "ahead_rnd:",findva("Innodb_buffer_pool_read_ahead_rnd",last_data,lenth));
  610.         mprintf(outfile,"[###Innodb_log info:]\n");
  611.         mprintf(outfile,
  612.                      "%s%-20ld%s%ld\n",
  613.                         "Innodb_log_writes:",findva("Innodb_log_writes",last_data,lenth),
  614.                         "Innodb_log_waits:",findva("Innodb_log_waits",last_data,lenth)
  615.                         );
  616.         mprintf(outfile,
  617.                     "%s%-9ld%s%ld\n",
  618.                         "Innodb_os_log_pending_fsyncs:",findva("Innodb_os_log_pending_fsyncs",last_data,lenth),
  619.                         "Innodb_os_log_pending_writes:",findva("Innodb_os_log_pending_writes",last_data,lenth)
  620.                         );
  621.         mprintf(outfile,
  622.                     "%s%ld\n",
  623.                         "Innodb_os_log_written:",findva("Innodb_os_log_written",last_data,lenth)
  624.                    );
  625.         mprintf(outfile,"[###Innodb_data read/writes info:]\n");
  626.     mprintf(outfile,
  627.                     "%s%-20ld%s%ld\n",
  628.                         "Innodb_data_reads:",findva("Innodb_data_reads",last_data,lenth),
  629.                         "Innodb_data_read:",findva("Innodb_data_read",last_data,lenth)
  630.                         );
  631.     mprintf(outfile,
  632.                     "%s%-19ld%s%ld\n",
  633.                         "Innodb_data_writes:",findva("Innodb_data_writes",last_data,lenth),
  634.                         "Innodb_data_written:",findva("Innodb_data_written",last_data,lenth)
  635.                         );
  636.         mprintf(outfile,
  637.                     "%s%-19ld%s%ld\n",
  638.                     "Innodb_data_fsyncs:",findva("Innodb_data_fsyncs",last_data,lenth),
  639.                     "Innodb_data_pending_fsyncs:",findva("Innodb_data_pending_fsyncs",last_data,lenth)
  640.                     );
  641.         mprintf(outfile,
  642.                     "%s%ld\n",
  643.                         "Innodb_buffer_pool_reads(physics reads):",findva("Innodb_buffer_pool_reads",last_data,lenth)
  644.                    );
  645.         mprintf(outfile,
  646.                     "%s%ld\n",
  647.                         "Innodb_buffer_pool_read_requests(logic reads):",findva("Innodb_buffer_pool_read_requests",last_data,lenth)
  648.                    );

  649.         mprintf(outfile,"[###Innodb_data rows info:]\n");
  650.         mprintf(outfile,
  651.                     "%s%-8ld%s%-8ld%s%-8ld%s%-8ld\n",
  652.                         "U(rows):",findva("Innodb_rows_updated",last_data,lenth),
  653.                         "D(rows):",findva("Innodb_rows_deleted",last_data,lenth),
  654.                         "I(rows):",findva("Innodb_rows_inserted",last_data,lenth),
  655.                         "S(rows):",findva("Innodb_rows_read",last_data,lenth)
  656.                         );

  657.         mprintf(outfile,"---------------------------------------TOTALINFO------------------------------------------\n");
  658.         mprintf(outfile,
  659.                     "%s%-15ld%s%ld\n",
  660.                         "Bytes_received:",findva("Bytes_received",last_data,lenth),
  661.                         "Bytes_sent:",findva("Bytes_sent",last_data,lenth)
  662.                         );
  663.         return ret;
  664. }

  665. int64_t findva(const char* ins,D_STROE* last_data,int lenth)
  666. {
  667.         int i=0;
  668.         for(i=0;i<lenth;i++)
  669.                 {
  670.                         if(!strcmp(last_data->statname,ins))
  671.                                 {
  672.                                         return last_data->data;
  673.                                         break;
  674.                                 }
  675.                         last_data++;
  676.                 }
  677.         return (int64_t)(-1);
  678. }


作者微信:

               







來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/7728585/viewspace-2132851/,如需轉載,請註明出處,否則將追究法律責任。

相關文章