自己开发的MYMON工具监控MYSQL运行状态帮助文档

原创 MySQL gaopengtttt 2017-01-23 16:46:04

本工具为采集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. }


作者微信:

               







上一篇:MYSQL的CHAR和VARCHAR注意事项 以及binary和varbinary存储方式
下一篇:解析MYSQL BINLOG 二进制格式(1)--准备工作

文章评论

请使用浏览器的分享功能分享到微信等