Anemometer安装



SELinux 不让 httpd 访问外网,mysql连接失败,由此可知SELinux的利害了

关闭selinux模块
方法一(推荐):
/etc/selinux/config
将SELINUX=enforcing改为SELINUX=disabled
重启机器即可

方法二:
1.    getenforce查看selinux的状态为:enforcing
2.    键入:getsebool -a | grep httpd查看httpd的布尔状态;可以看到httpd_can_network_connect --> off;
3.    键入:setsebool httpd_can_network_connect 1  开启;
4.    重启mysql:  service mysqld  restart即可;根据具体情况确定,也可以不重启。


1,安装lamp环境:
yum -y install httpd*
yum -y install php 
yum -y install php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-bcmath
#yum install -y mysql* #不推荐,版本不确定。
yum install -y curl-devel gcc.x86_64 libgcc.x86_64 make net-snmp.x86_64 net-snmp-devel.x86_64 net-snmp-utils.x86_64 wget ntp vim 
yum install -y libxml2*
yum install -y git 

vim /var/www/html/index.php  输入如下内容:
<?php 
phpinfo(); 
?> 
vim /etc/httpd/conf/httpd.conf
搜索关键字:ServerName,修改为自己的ip,如下:
ServerName 192.168.1.148:80

service httpd restart 

用IE访问http://192.168.1.148/ 如果输出了phpinfo信息说明你的php安装成功了。

安装软件:
cd /var/www/html/
git clone https://github.com/box/Anemometer.git anemometer

service httpd restart 
http://192.168.1.148/anemometer/index.php #会提示需要配置conf/config.inc.php
cp /var/www/html/anemometer/conf/sample.config.inc.php /var/www/html/anemometer/conf/config.inc.php
cd /var/www/html/anemometer/
mysql -uroot -p < mysql56-install.sql

mysql -uroot -p < install.sql

如果要添加sql自动审核扩展功能,需增加一个字段,如下:

ALTER TABLE `global_query_review` ADD  audit_status VARCHAR(255) NOT NULL DEFAULT 'refuse' comment 'sql审计的状态 refuse未通过 pass审核通过';


如提示:ERROR 1067 (42000) at line 15: Invalid default value for 'FIRST_SEEN' (针对mysql5.7),

修改mysql56-install.sql, install.sql脚本内容即可: '0000-00-00 00:00:00'  -->  '1990-01-01 00:00:00'


yum install -y http://www.percona.com/downloads/percona-release/redhat/0.1-3/percona-release-0.1-3.noarch.rpm
yum install percona-toolkit -y

单独打开一个窗口,执行:
tail -f /var/log/httpd/error_log

http://192.168.1.148/anemometer/index.php #进行访问测试:

如出现如下关键字:
 Timezone ID 'CST' is invalid in /var/www/html/anemometer/lib/Anemometer.php on line 47
处理方式:
vim /etc/php.ini
;date.timezone =   ==> date.timezone = Asia/Shanghai
重启进行查看,如果还有问题,追加执行下面:
vim /var/www/html/anemometer/lib/Anemometer.php
$timezone = ini_get('date.timezone'); ==> $timezone = ini_get('date.timezone','Asia/Shanghai');
$timezone = date_default_timezone_get(); ==>  $timezone = date_default_timezone_get('PRC');

修改1:
vim /var/www/html/anemometer/conf/config.inc.php
修改35-40行的数据库配置,连接到anemometer的数据库,当然,你数据库也需要授权.
位置1:

$conf['datasources']['localhost'] = array(
'host' => 'localhost',
'port' => 3306,
'db' => 'slow_query_log',
'user' => 'root',
'password' => '123456',
'tables' => array(
'global_query_review' => 'fact',
'global_query_review_history' => 'dimension'
),
'source_type' => 'slow_query_log'


);


$conf['datasources']['192.168.11.28'] = array(
'host'  => '192.168.11.28',
'port'  => 3306,
'db'    => 'slow_query_log',
'user'  => 'root',
'password' => '123456',
'tables' => array(
'global_query_review' => 'fact',
'global_query_review_history' => 'dimension'
),
'source_type' => 'slow_query_log'
);

位置2:(针对执行explain命令,如连接230数据库,需要修改为230的密码。如果要再看本地的,则需要从新输入)
        $conn = array();


                if (!array_key_exists('hostname_max',$sample) or strlen($sample['hostname_max']) < 5)
                {
                        return;
                }


                $pos = strpos($sample['hostname_max'], ':');
                if ($pos === false)
                {
                        $conn['port'] = 3306;
                        $conn['host'] = $sample['hostname_max'];
                }
                else
                {
                        $parts = preg_split("/:/", $sample['hostname_max']);
                        $conn['host'] = $parts[0];
                        $conn['port'] = $parts[1];
                }


                $conn['db'] = 'mysql';
                if ($sample['db_max'] != '')
                {
                        $conn['db'] = $sample['db_max'];
                }


                $conn['user'] = 'root';
                $conn['password'] = '123456';

位置3:(视情况添加)

vim /etc/hosts

192,168.1.230 mysql    #当跨服务器查询其他数据库时,可能出现找不到主机名而导致连接失败的情况。


修改2:(也可以不修改)
vim /etc/php.ini

[MySQLi]
; Maximum number of links.  -1 means no limit.
; http://www.php.net/manual/en/mysqli.configuration.php#ini.mysqli.max-links
mysqli.max_links = -1  #下添加 (不添加也可以)
extension = php_mysqli.dll
extension = mysqli.so


观察mysql错误日志,如提示sock连接丢失,修改mysql配置文件:
vim /etc/my.cnf
[mysqld]
socket = /var/lib/mysql/mysql.sock
[mysql]
socket = /var/lib/mysql/mysql.sock
service mysql restart

service httpd restart 
http://192.168.1.148/anemometer/index.php 
如访问正常,anemometer安装完成。

anemometer表数据导入:
 pt-query-digest --user=root --password=123456  --review h=127.0.0.1,D=slow_query_log,t=global_query_review --history h=127.0.0.1,D=slow_query_log,t=global_query_review_history  --no-report --limit=0% --filter=" \$event->{Bytes} = length(\$event->{arg}) and \$event->{hostname}=\"$HOSTNAME\""  /data/server/mysql5.7.16/data/mysql-slow.log
注意:

h=127.0.0.1 尽量用具体ip,不要用localhost,可能导致socket连接错误。

Anemometer软件安装并导入数据完成。


优化配置:

现在的环境是,有多台MySQL服务器的slow log需要监控.
我们有三种方案.

1、手工导入的install.sql里面的global_query_review_history表包含了hostname_max和db_max,通过hostname_max区分把多个数据源存放到一个表里.

pt-query-digest --user=root --password=123456  --review h=127.0.0.1,D=slow_query_log,t=global_query_review --history h=127.0.0.1,D=slow_query_log,t=global_query_review_history  --no-report --limit=0% --filter=" \$event->{Bytes} = length(\$event->{arg}) and \$event->{hostname}=\"$HOSTNAME\""  /data/server/mysql5.7.16/data/mysql-slow.log
注意:
1,h=127.0.0.1 尽量用具体ip,不要用localhost,可能导致socket连接错误。
2,$HOSTNAME主机名是当前服务器主机名,如果传输到remove数据库时,无法通过plung插件进行解析(需要再remove服务器的hosts文件中映射该主机名ip).建议对该$HOSTNAME进行优化,必要时可以考虑写成固定的本地ip,如192.168.1.230,这样远程服务器可执行explan等告警分析
2、每台mysql把处理后的binlog数据放到当前服务器,然后anemometer连接对应的服务器获取数据.数据保存到每个服务器的本地数据库。
优点:这样可以避免Anemometer服务器数据量过大。
缺点:生产环境不建议这样做,定时调度会产生IO以外的额外开销。


3、所有的mysql把处理后的binlog数据统一存放到一台anemometer所在的数据库上,然后通过数据库名字区分,
推荐方式。


第二种或者第三种方案,需要定义多个数据源,并且anemometer_collect.sh.里面对应的history_db_name要对应.
所有MySQL服务器上需要安装percona-toolkit的工具箱.


在anemometer_collect.sh当前目录下增加下面两个配置文件.连接到本地MySQL服务器的账号,因为要执行set global long_query_time等语句,故需要super权限.


[root@localhost scripts]# cat anemometer-localhost.cnf

[client]
user=root
password=
host=localhost
socket=/tmp/mysql.sock


连接到anemometer服务器数据库的账号,需要对anemometer_collect.sh脚本中history_db_name对应的数据库有all privileges权限.
[root@localhost scripts]# cat anemometer-server.cnf

[client]
user=anemometer
password=123456


使用下面命令调试脚本.
 sh -x ./anemometer_collect.bak.sh --interval 30 --history-db-host 192.168.1.148 --defaults-file ./anemometer-localhost.cnf  --history-defaults-file ./anemometer-server.cnf --killFlag on --killUser uei

注释:killFlag表示是否执行kill用户命令,执行后统计更准确,但可能打断事务操作。

killUser表示具体kill 的用户,一般为非root用户。


调试通过以后,在crontab添加如下命令,实现定期采集慢查询日志到数据库存储.间隔可以根据自己的需求设置,我的设置基本上是采集所有的慢查询日志.*/1 * * * */opt/anemometer_collect.sh -interval 59 -history-db-host 192.168.11.28 -defaults-file /opt/anemometer-localhost.cnf -history-defaults-file /opt/anemometer-server.cnf


因为项目自带的脚本存在历史文件无法保存、执行后无法恢复到执行前状态等问题,以下是后改后的脚本

#/usr/bin/env bash

#霍元申
#2017/6/14 
# anemometer collection script to gather and digest slow query logs
#该脚本用来收集和整理slow_query_log;
# this is a quick draft script so please give feedback!
#这是一个快速定制脚本,所以请发给我反馈。
# basic usage would be to add this to cron like this:
# */5 * * * * anemometer_collect.sh --interval 15 --history-db-host anemometer-db.example.com
#简单用法可以将如下代码添加到cron:
# This will have to run as a user which has write privileges to the mysql slow log
#对mysql慢日志有写权限的用户才能运行该脚本。
# Additionally there are two sets of permissions to worry about:  The local mysql instance, and the remote digest storage instance
#额外两个权限设置注意事项为:本地实例和远程整理存储的实例。
# These are handled through defaults files, just create a file in the: my.cnf format such as:
#通过默认文件指针创建文件如my.cnf格式,如下:
# [client]
# user=
# password=
# use --defaults-file for permissions to the local mysql instance
# 用--defaults-file定义本地实例权限
# and use --history-defaults-file for permissions to the remote digest storage instance
#用--history-defaults-file定义远程整理存储实例权限
#




#执行样例: sh -x ./anemometer_collect.bak.sh --interval 30 --history-db-host 192.168.1.148 --defaults-file ./anemometer-localhost.cnf  --history-defaults-file ./anemometer-server.cnf --killFlag=on --killUser=uei












socket= defaults_file= rate_limit= mysqlopts=
interval=30 #数据收集时间
digest='/usr/bin/pt-query-digest'




default_db=uei      #默认被监控数据库名,关联global_query_review_history的db_max字段
#set log prefix
LOG_PREFIX='/tmp/msyql/log/' #历史慢日志备份目录
long_query_time=0#定制慢查询时长,0.0会记录所有语句.因为是定期监控所有语句,推荐0.0




killFlag=off  #'on/off' 设置生效时是否kill掉非root用户使变量立即生效。建议非生产环境开启,生产环境谨慎使用
killUser='' #killFlag=on时希望kill掉的连接用户




#SET IP
HOSTNAME=`/sbin/ifconfig | grep 'inet addr'  | egrep '172.|192.' | awk '{print $2}' | awk -F ":" '{print $2}'`
history_db_host=
history_db_port=3306
history_db_name='slow_query_log'
history_defaults_file=








help () {
	cat <<EOF




Usage: $0 --interval <seconds>




Options:
    --socket -S              mysql  scoket
    --defaults-file          本地默认配置文件
    --interval -i            收集时序时间,默认30s
    --rate                   Set log_slow_rate_limit (For Percona MySQL Only) 仅对Percona MySQL版本数据库有效




    --history-db-host        anemometer database server 主机地址
    --history-db-port        anemometer database server 端口
    --history-db-name        anemometer database server 数据库名(Default slow_query_log)
    --history-defaults-file  默认pt-query-digest连接远程anemometer database的配置文件
    --killFlag               'on/off' 设置生效时是否kill掉非root用户使变量立即生效。建议非生产环境开启,生产环境谨慎使用
    --killUser               killFlag=on时希望kill掉的连接用户 
    --LOG_PREFIX             历史慢日志存放目录,默认:/tmp/msyql/log/
    --default_db             默认被监控数据库名,关联global_query_review_history的db_max字段
EOF
}




#遍历参数
while test $# -gt 0
do
    case $1 in
        --socket|-S)
            socket=$2
            shift
            ;;
        --defaults-file|-f)
            defaults_file=$2
            shift
            ;;
        --interval|-i)
            interval=$2
            shift
            ;;
	--rate|r)
	    rate=$2
	    shift
	    ;;
	--pt-query-digest|-d)
	    digest=$2
	    shift
	    ;;
	--help)
	    help
	    exit 0
	    ;;
	--history-db-host)
	    history_db_host=$2
	    shift
	    ;;
        --history-db-port)
            history_db_port=$2
	    shift
	    ;;
	--history-db-name)
	    history_db_name=$2
	    shift
	    ;;
	--history-defaults-file)
	    history_defaults_file=$2
	    shift
	    ;;
    --killFlag)
	    killFlag=$2
	    shift
	    ;;
    --killUser)
	    killUser=$2
	    shift
	    ;;
    --default_db)
	    default_db=$2
	    shift
	    ;;
        *)
            echo >&2 "Invalid argument: $1"
            ;;
    esac
    shift
done




if [ ! -e "${digest}" ];
then
	echo "Error: cannot find digest script at: ${digest}"
	exit 1
fi




if [ ! -z "${defaults_file}" ]; #判断${defaults_file}是不是空字符串。z为空的意思
then
	mysqlopts="--defaults-file=${defaults_file}"
fi




# 匹配慢查询日志路径
LOG=$( mysql $mysqlopts -e " show global variables like 'slow_query_log_file'" -B  | tail -n1 | awk '{ print $2 }' )
if [ $? -ne 0 ]; #如果上一行代码执行失败(不等于0)
then
	echo "Error getting slow log file location"
	exit 1
fi




# process the log
if [[ ! -e "$LOG" ]] #如果慢查询日志不存在
then
	echo "No slow log to process";
	exit 1
fi
mkdir -p ${LOG_PREFIX}
cp "$LOG" ${LOG_PREFIX}old_slow_query_log`date +%Y%m%d%H:%M:%S`.log




LOG_ifon=$( mysql $mysqlopts -e " show global variables like 'slow_query_log'" -B  | tail -n1 | awk '{ print $2 }' )
if [ $? -ne 0 ]; 
then
	echo "Error getting mysql varialbe slow_query_log "
	exit 1
fi




old_long_query_time=$( mysql $mysqlopts -e " show global variables like 'long_query_time'" -B  | tail -n1 | awk '{ print $2 }' )
if [ $? -ne 0 ]; 
then
	echo "Error getting mysql varialbe long_query_time "
	exit 1
fi


old_log_queries_not_using_indexes=$( mysql $mysqlopts -e " show global variables like 'log_queries_not_using_indexes'" -B  | tail -n1 | awk '{ print $2 }' )
if [ $? -ne 0 ]; 
then
	echo "Error getting mysql varialbe log_queries_not_using_indexes "
	exit 1
fi


echo "Collecting from slow query log file: ${LOG}"




# simple 30 second collection 收集30秒
if [ ! -z "${rate}" ];
then
	mysql $mysqlopts -e "SET GLOBAL log_slow_rate_limit=${rate}"
fi




mysql $mysqlopts -e "SET GLOBAL long_query_time=${long_query_time}"
mysql $mysqlopts -e "SET GLOBAL slow_query_log=1"
if [ $? -ne 0 ];
then
	echo "Error: cannot enable slow log. Aborting"
	exit 1
fi
echo "Slow log enabled; sleeping for ${interval} seconds"




if [ $killFlag == "on" ];
then
    mysqladmin $mysqlopts processlist|awk -v user=$killUser -F "|" '{sub("^ *","",$3);sub(" *$","",$3);} {if($3 == user) print $2}'| xargs -n 1 mysqladmin $mysqlopts kill
fi




sleep "${interval}"


mysql $mysqlopts -e "SET GLOBAL slow_query_log=${LOG_ifon}"
mysql $mysqlopts -e "SET GLOBAL long_query_time=${old_long_query_time}"
mysql $mysqlopts -e "SET GLOBAL slow_query_log=${old_log_queries_not_using_indexes}"


if [ $killFlag == "on" ];
then
    mysqladmin $mysqlopts processlist|awk -v user=$killUser -F "|" '{sub("^ *","",$3);sub(" *$","",$3);} {if($3 == user) print $2}'| xargs -n 1 mysqladmin $mysqlopts kill
    mysqladmin $mysqlopts processlist|awk -v user=$killUser -F "|" '{sub("^ *","",$3);sub(" *$","",$3);} {if($3 == user) print $2}'| xargs -n 1 mysqladmin $mysqlopts kill
    mysqladmin $mysqlopts processlist|awk -v user=$killUser -F "|" '{sub("^ *","",$3);sub(" *$","",$3);} {if($3 == user) print $2}'| xargs -n 1 mysqladmin $mysqlopts kill
fi




echo "Done.  Processing log and saving to ${history_db_host}:${history_db_port}/${history_db_name}"




cp "$LOG" /tmp/tmp_slow_log
true > "$LOG"
 cat >> "$LOG" <<EOF
/disk3/data/server/mysql5.7.15/bin/mysqld, Version: 5.7.15-log (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
# Time: 2017-06-15T11:02:20.010757+08:00
# User@Host: uei[uei] @ localhost [127.0.0.1]  Id:   559
# Query_time: 0.000073  Lock_time: 0.000000 Rows_sent: 0  Rows_examined: 0
use $default_db;
SET timestamp=1497495740;
commit;
EOF




if [ ! -z "${history_defaults_file}" ];
then
	pass_opt="--defaults-file=${history_defaults_file}"
fi
"${digest}" $pass_opt \
  --review h="${history_db_host}",D="$history_db_name",t=global_query_review \
  --history h="${history_db_host}",D="$history_db_name",t=global_query_review_history \
  --no-report --limit=0\% \
  --filter="\$event->{Bytes} = length(\$event->{arg}) and \$event->{hostname}=\"$HOSTNAME\" " \
  "/tmp/tmp_slow_log"




rm /tmp/tmp_slow_log





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值