#!/bin/bash
#
#*****************************************************
#File Name    : install_haproxy.sh
#Author       : guokai
#Mail         : xxx@163.com
#Create Time  : 2022-04-12 12:17:04
#Description  : haproxy-2.4.15
#*****************************************************



color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$2" && $MOVE_TO_COL
    echo -n "["
    if [ $1 = "success" -o $1 = "0" ] ;then ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "
    elif [ $1 = "failure" -o $1 = "1" ] ;then ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo
}


check_install_haproxy () {
	if [ $(rpm -qa | grep -c haproxy) -gt 1 ]; then
    	color 1 "haproxy 已安装,请卸载后再安装"
		exit
	else
    	color 0 "开始安装haproxy-2.4.22"
        dnf install -y gcc openssl-devel pcre-devel systemd-devel
		dnf install haproxy-2.4.22-4.el9.x86_64 -y
        haproxy -v && color 0 "HAPROXY 安装完成"
	fi
}

LOG_DIR="/home/logs/haproxy"
RSYSLOG_CONF="/etc/rsyslog.d/haproxy.conf"

#设置日志
log () {
    color 0 "→ 创建日志目录: $LOG_DIR"
    mkdir -p $LOG_DIR
    chown haproxy:haproxy $LOG_DIR
    chmod 755 $LOG_DIR
    color 0 "→ 配置 rsyslog systemd override: ProtectHome=no"
    mkdir -p /etc/systemd/system/rsyslog.service.d
    rm -f /etc/systemd/system/rsyslog.service.d/override.conf
cat > /etc/systemd/system/rsyslog.service.d/override.conf <<EOF
[Service]
ProtectHome=no
ReadWritePaths=/home
EOF

    
    color 0 "→ 配置 rsyslog 接收 HAProxy 日志"
cat > $RSYSLOG_CONF <<EOF
# HAProxy logs via local1
local1.*    $LOG_DIR/haproxy.log
& stop
EOF
    color 0 "→ 确保 imuxsock 模块启用 (SysSock.Use=on)"
    if grep -q "module(load=\"imuxsock\"" /etc/rsyslog.conf; then
        sed -i 's/module(load="imuxsock".*/module(load="imuxsock" SysSock.Use="on")/' /etc/rsyslog.conf
    elif grep -q "#module(load=\"imuxsock\"" /etc/rsyslog.conf; then
        sed -i 's/#module(load="imuxsock".*/module(load="imuxsock" SysSock.Use="on")/' /etc/rsyslog.conf
    else
        # 若没有，则添加
        echo 'module(load="imuxsock" SysSock.Use="on")' >> /etc/rsyslog.conf
    fi

    color 0 "→ 启用 rsyslog imudp 模块和 UDP 514 监听"

    # enable module(load="imudp")
    if grep -qE '^module\(load="imudp"' /etc/rsyslog.conf; then
        color 0 "  - imudp 模块已启用"
    elif grep -qE '^#module\(load="imudp"' /etc/rsyslog.conf; then
        sed -i 's/#module(load="imudp")/module(load="imudp")/' /etc/rsyslog.conf
    else
        echo 'module(load="imudp")' >> /etc/rsyslog.conf
    fi

    # enable input(type="imudp" port="514")
    if grep -qE '^input\(type="imudp" port="514"' /etc/rsyslog.conf; then
        color 0 "  - UDP 514 已启用"
    elif grep -qE '^#input\(type="imudp" port="514"' /etc/rsyslog.conf; then
        sed -i 's/#input(type="imudp" port="514")/input(type="imudp" port="514")/' /etc/rsyslog.conf
    else
        echo 'input(type="imudp" port="514")' >> /etc/rsyslog.conf
    fi

    color 0 "→ 配置 logrotate: /etc/logrotate.d/haproxy"
cat > /etc/logrotate.d/haproxy <<EOF
$LOG_DIR/haproxy.log {
	su root root 
    daily
    rotate 10
    missingok
    notifempty
    compress
    delaycompress
    sharedscripts
    postrotate
	systemctl kill -s HUP rsyslog.service >/dev/null 2>&1 || true
    endscript
}

EOF
}

config_haproxy () {

mkdir -pv /etc/haproxy
cat > /etc/haproxy/haproxy.cfg <<EOF
global
 log /dev/log local1 #默认info   
 #log 127.0.0.1   local1 notice
 maxconn 65535
 user haproxy
 group haproxy
 daemon
 #debug
 #quiet
 pidfile /usr/local/haproxy/haproxy.pid
 stats socket /var/run/haproxy.sock mode 600 expose-fd listeners level user
 ulimit-n 1000000 ##这里增大文件打开数
 max-spread-checks  1000ms
 #tune.ssl.default-dh-param 2048
 spread-checks 20
 #nbproc 8
 #cpu-map 1 0
 #cpu-map 2 1
 #cpu-map 3 2
 #cpu-map 4 3
 #cpu-map 5 4
 #cpu-map 6 5
 #cpu-map 7 6
 #cpu-map 8 7

defaults
 log     global
 mode    tcp
 option  tcplog
 option  dontlognull
 retries 3 #连接失败3次，即为失败。
 #option httpclose #每次请求完毕后主动关闭http通道,haproxy不支持keep-alive,只能模拟这种模式的实现
 balance roundrobin
 option clitcpka
 option srvtcpka
 frontend http-in
 option redispatch  #当serverId对应的服务器挂掉后，强制定向到其他健康的服务器，以后将不支持
 option forwardfor #透传客户端真实IP至后端web服务器方便访问日志统计
 option abortonclose #当服务器负载很高的时候，自动结束掉当前队列处理比较久的链接
 maxconn         65535
 timeout connect 5000ms #连接超时
 timeout client 1800000ms #客户端超时
 timeout server 1800000ms #服务器超时
 timeout queue 5000ms
 timeout server-fin 90000ms
 timeout client-fin 90000ms
 timeout tunnel 1h
# timeout server-fin 90000ms
# timeout client-fin 90000ms
# timeout tunnel 1h


###########20210828 mysql########################################################################
listen  mysql
 bind *:3300   
 mode tcp             
 #option mysql-check user haproxy   #mysql健康检查  root为mysql登录用户名
 balance roundrobin            #调度算法:轮询
 server mysql72154 172.16.72.154:3300 weight 1 check  inter 1s rise 2 fall 2
 server mysql72155 172.16.72.155:3300 weight 1 check  inter 1s rise 2 fall 2
###########20210828  tengine#####################
listen tengine
 bind *:80
 mode http
 option httplog
 #log global
 option logasap #能够在服务器发送complete首部时即时记录日志，只不过，此时将不记录整体传输时长和字节数
 option forwardfor except 127.0.0.0/8
log-format {\"haproxy_clientIP\":\"%ci\",\"haproxy_clientPort\":\"%cp\",\"haproxy_dateTime\":\"%t\",\"haproxy_frontendNameTransport\":\"%ft\",\"haproxy_backend\":\"%b\",\"haproxy_serverName\":\"%s\",\"haproxy_serverIp\":\"%si\",\"haproxy_Tw\":\"%Tw\",\"haproxy_Tc\":\"%Tc\",\"haproxy_Tt\":\"%Tt\",\"haproxy_bytesRead\":\"%B\",\"haproxy_terminationState\":\"%ts\",\"haproxy_actconn\":\"%ac\",\"haproxy_FrontendCurrentConn\":\"%fc\",\"haproxy_backendCurrentConn\":\"%bc\",\"haproxy_serverConcurrentConn\":\"%sc\",\"haproxy_retries\":\"%rc\",\"haproxy_srvQueue\":\"%sq\",\"haproxy_backendQueue\":\"%bq\",\"haproxy_backendSourceIP\":\"%bi\",\"haproxy_backendSourcePort\":\"%bp\",\"http_request\":\"%r\",\"request_headers\":\"%hrl\",\"response_headers\":\"%hsl\",\"status_code\":\"%ST\"}
 balance roundrobin
 server tengine01_172.16.72.166_80  172.16.72.166:80 check inter 1000 rise 2 fall 2
 server tengine02_172.16.23.167_80  172.16.72.167:80 check inter 1000 rise 2 fall 2
#########################################################################################
listen stats     #监控
 mode http
 bind 0.0.0.0:8888
 option httplog #采用http日志格式
 stats refresh 30s #统计页面自动刷新时间
 stats enable
 stats uri /dbs
 stats realm Global\ statistics
 stats auth admin:admin
 stats hide-version #隐藏统计页面上HAProxy的版本信息
 stats admin if TRUE #设置手工启动/禁用，后端服务器(haproxy-1.4.9以后版本
EOF


	systemctl daemon-reload
	systemctl enable --now haproxy && color 0 "haproxy 启动成功" || { color 1 "haproxy 启动失败"; exit ; }

    color 0 "重启rsyslog haproxy服务"
    systemctl restart rsyslog haproxy
    color 0 "haproxy.cfg配置文件前部分请保留！！！根据业务新增负载"

}


check_install_haproxy
log
config_haproxy