#!/bin/bash
#
#*****************************************************
#File Name    : install_redis_6.2.4.sh
#Author       : guokai
#Mail         : xxx@163.com
#Create Time  : 2022-04-22 16:49:14
#Description  : The test script
#*****************************************************
SRC_DIR=/usr/local/src
REDIS_FILE=redis-6.2.4
TAR=.tar.gz
REDIS_INSTALL_DIR=/home/redis
NEIBU_URL=http://download.redis.io/releases/
CPUS=`lscpu | awk '/^CPU\(s\)/{print $2}'`



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
}

system_optimize () {
	#内核设置
MEMORY=`cat /proc/sys/vm/overcommit_memory`
	if [ $MEMORY == 1 ] ;then 
		color 0 "vm.overcommit_memory = 1 正常!"
	else
	color 1 "vm.overcommit_memory 数值为 $MEMORY ,修改为1"
	echo "vm.overcommit_memory = 1" >> /etc/sysctl.conf
	sysctl -p
	color 0 "vm.overcommit_memory 已修改为1!"
	fi
	
#关闭THP
	echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.d/rc.local
	chmod +x /etc/rc.d/rc.local
	/etc/rc.d/rc.local
	
	SOMAXCONN_VALUE=`cat /proc/sys/net/core/somaxconn`
	if [ $SOMAXCONN_VALUE == "128" ] ;then
		color 1 "net.core.somaxconn 参数是默认值128,需要调大!"
		echo "net.core.somaxconn = 65535" >> /etc/sysctl.conf
		sysctl -p
		color 0 "net.core.somaxconn 参数已调整为65535!"
	elif [ $SOMAXCONN_VALUE == "65535" ] ;then
        color 0 "net.core.somaxconn 参数现在为65535!,继续安装"
	else
		{ color 0 "net.core.somaxconn 参数不是默认值128,现在的值为$SOMAXCONN_VALUE,"; exit ; }
	fi

}

check_gcc5 () {
    dnf -y install gcc tcl 
    
    # 初始化变量
    GCC_VERSION_VALUE=$(gcc -dumpversion | cut -d'.' -f1)
    GCC_NEWVERSION=$GCC_VERSION_VALUE  # 默认使用原版本
    
    if [ "$GCC_VERSION_VALUE" -ge 9 ]; then
        color 0 "gcc版本大于等于9 继续安装"
    elif [ "$GCC_VERSION_VALUE" -lt 9 ]; then
        color 1 "gcc版本小于9，尝试更新"
        mv /usr/bin/gcc /usr/bin/gcc-$GCC_VERSION_VALUE
        ln -s /opt/rh/devtoolset-9/root/bin/gcc /usr/bin/gcc
        GCC_NEWVERSION=$(gcc -dumpversion | cut -d'.' -f1)
        color 0 "gcc 版本已更新为 $GCC_NEWVERSION"
    else
        color 1 "gcc 安装失败" ; exit ;
    fi

    # 统一使用 GCC_NEWVERSION 进行检查
    if [ "$GCC_NEWVERSION" -ge 9 ]; then
        color 0 "检测到gcc最新版本大于等于9 继续安装"
    else
        color 1 "gcc 版本不匹配 重新执行脚本" ; exit ;
    fi
}
check_redis () {
	[ -e ${REDIS_INSTALL_DIR} ] && { color 1 "redis 已安装,请卸载后再安装" ; exit; }
	cd ${SRC_DIR}
	if [ -e ${REDIS_FILE}${TAR} ];then
		color 0 "相关文件已准备好"
	else
		color 0 "开始下载 redis 源码包"
		wget ${NEIBU_URL}${REDIS_FILE}${TAR} 
		[ $? -ne 0 ] && { color 1 "下载 ${REDIS_FILE}${TAR}文件失败" ; exit ; }
	fi
}
install_redis () {
	color 0 "开始安装 redis"
	cd ${SRC_DIR}
	tar xzf ${REDIS_FILE}${TAR} || { color 1 "tar命令未安装" ; exit; }
	cd ${REDIS_FILE}
	
	#make MALLOC=jemalloc 
	make install PREFIX=${REDIS_INSTALL_DIR} 
	ln -s ${REDIS_INSTALL_DIR}/bin/redis-* /usr/bin/
	#echo "PATH=${REDIS_INSTALL_DIR}/bin:\$PATH" > /etc/profile.d/redis.sh
	#. /etc/profile.d/redis.sh
}

start_redis(){
	color 0 "开始启动 redis"
	if id redis &> /dev/null ;then
		color 1 "redis 用户已存在"
	else
		useradd -r -s /sbin/nologin redis
		color 0 "redis 用户创建成功"
	fi
	mkdir -pv ${REDIS_INSTALL_DIR}/{logs,data,pid,cluster}
	chown -R redis.redis ${REDIS_INSTALL_DIR}

PORT=9100
PASSWORD=cqt!010@Redis
#配置文件
cat > ${REDIS_INSTALL_DIR}/cluster/redis-cluster-$PORT.conf << EOF
daemonize yes
tcp-backlog 1024
timeout 0
tcp-keepalive 60
loglevel notice
databases 16
dir ${REDIS_INSTALL_DIR}/data
stop-writes-on-bgsave-error no
repl-timeout 60
repl-disable-tcp-nodelay no
repl-backlog-size 64000000
repl-backlog-ttl 7200
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-entries 512
list-max-ziplist-value 64
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
activerehashing yes
client-output-buffer-limit normal 256mb 128mb 60
client-output-buffer-limit replica 512mb 256mb 60
hz 10
save ""
port $PORT
maxmemory 7gb
maxmemory-policy volatile-lfu
appendonly no
appendfsync everysec
appendfilename "appendonly-8001.aof"
dbfilename dump-$PORT.rdb
aof-rewrite-incremental-fsync yes
no-appendfsync-on-rewrite yes
auto-aof-rewrite-min-size 62500kb
auto-aof-rewrite-percentage 100
aof-load-truncated yes
maxclients 10000
protected-mode yes
bind 0.0.0.0
list-max-ziplist-size -2
list-compress-depth 0
always-show-logo yes
pidfile "${REDIS_INSTALL_DIR}/pid/redis-$PORT.pid"
logfile "${REDIS_INSTALL_DIR}/logs/redis-$PORT.log"
lazyfree-lazy-eviction yes
lazyfree-lazy-expire yes
lazyfree-lazy-server-del yes
aof-use-rdb-preamble no
activedefrag yes
active-defrag-threshold-lower 10
active-defrag-threshold-upper 100
active-defrag-ignore-bytes 300mb
active-defrag-cycle-min 10
active-defrag-cycle-max 30
active-defrag-max-scan-fields 1000
replica-serve-stale-data yes
replica-priority 100
replica-read-only yes
replica-lazy-flush yes
client-output-buffer-limit pubsub 32mb 8mb 60
replica-ignore-maxmemory yes
stream-node-max-bytes 4kb
stream-node-max-entries 100
dynamic-hz yes
rdb-save-incremental-fsync yes
repl-ping-replica-period 10
latency-monitor-threshold 30
cluster-enabled yes
cluster-node-timeout 5000
cluster-migration-barrier 1
cluster-config-file nodes-$PORT.conf
cluster-require-full-coverage no
cluster-replica-validity-factor 10
requirepass $PASSWORD
masterauth $PASSWORD
EOF


#service文件
cat > /usr/lib/systemd/system/redis.service  << EOF
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=${REDIS_INSTALL_DIR}/bin/redis-server ${REDIS_INSTALL_DIR}/cluster/redis-cluster-$PORT.conf
ExecStop=${REDIS_INSTALL_DIR}/bin/redis-cli -p $PORT -a $PASSWORD shutdown
Type=forking
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target

EOF

	systemctl daemon-reload
	systemctl enable --now redis && color 0 "redis 启动成功 ,redis 信息如下:" || { color 1 "redis 启动失败" ; exit; }
	#nohup redis-server  ${REDIS_INSTALL_DIR}/cluster/redis-cluster-$PORT.conf > /dev/null 2>&1
	${REDIS_INSTALL_DIR}/bin/redis-cli -p $PORT -a $PASSWORD info server 2> /dev/null
	
}

#system_optimize
#check_gcc5
#check_redis
install_redis
start_redis