#!/bin/bash
#====================================================================
# Description: CDN Node Check Script
#              检查CDN节点各项指标和服务状态，包括：
#              - 系统基础信息（IP地址）
#              - 服务层检查：
#                * OpenResty/Nginx 状态
#                * Prometheus 数据采集
#                * Logstash 服务和日志
#                * Young Agent 服务状态
#                * 域名配置文件
#              - 系统层检查：
#                * 内存使用情况
#                * CPU 使用状态
#                * 磁盘使用情况
#                * 系统运行时间
# Author: Liu YanHao
# Create Time: 2024-10-13
# Updated by: Zhang Jinwei
# Last Modified: 2025-08-11
# Version: 1.4
# Usage: ./check_cdn_node.sh
# Example: ./check_cdn_node.sh
#====================================================================

# 定义颜色变量
if [ -t 1 ]; then
    GREEN="\033[1;32m"
    CYAN="\033[1;36m"
    RED="\033[1;31m"
    PURPLE="\033[1;35m"
    RESET="\033[0m"
else
    GREEN=""
    CYAN=""
    RED=""
    PURPLE=""
    RESET=""
fi

INTERFACE=$(ip -o link show | awk -F ": " '{print $2}' | grep -E '^(eth0|ens192)$')
IP=$(ip -4 a show $INTERFACE | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
echo -e "${GREEN}【1】IP地址如下：${RESET}"
echo "IP地址: ${IP}"

# 检查环境变量
function check_value() {
    if [ -f /etc/profile.d/CDN_DOMAIN_CONF.sh ]; then
        echo ""
        echo -e "${GREEN}【2】环境变量如下：${RESET}"
        echo -e "${CYAN}$CDN_DOMAIN_CONF${RESET}"
        echo ""
        echo -e "${GREEN}【3】服务运行情况：${RESET}"
    fi
}

# 检查服务状态
function check_service_status() {
    local service_name=$1
    local status=$(systemctl status $service_name | grep -w running)
    if [ $? -eq 0 ]; then
        echo -e "${CYAN}$service_name 服务运行正常${RESET}"
    else
        echo -e "${RED}$service_name 服务运行失败${RESET}"
    fi
}

# 检查logstash
function check_logstash() {
    echo ""
    echo -e "${GREEN}【4】服务数据访问情况：${RESET}"
    cd /root/
    curl -s http://localhost:8085/logstash/metrics >/root/test_logstash.txt
    cat test_logstash.txt | grep -w 403
    if [ $? -eq 1 ]; then
        echo -e "${CYAN}logstash成功访问日志${RESET}"
    else
        echo -e "${RED}logstash访问日志失败${RESET}"
    fi
    rm -rf /root/test_logstash.txt
}

# 检查prometheus
function check_prometheus() {
    curl -s http://localhost:8085/status/format/prometheus >/root/test_prometheus.txt
    cat test_prometheus.txt | grep -w nginx_vts_info >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo -e "${CYAN}prometheus抓取到数据成功${RESET}"
    else
        echo -e "${RED}prometheus抓取到数据失败${RESET}"
    fi
    rm -rf /root/test_prometheus.txt
}

# 检查系统状态
function check_system() {
    echo ""
    echo -e "${GREEN}【5】内存情况：${RESET}"
    Total_MEM=$(awk '/MemTotal:/{print $2}' /proc/meminfo)
    Available_MEM=$(awk '/MemAvailable:/{print $2}' /proc/meminfo)
    Percentage=$((100 * Available_MEM / Total_MEM))
    if [ $Percentage -lt 9 ]; then
        echo "警告：系统内存快要用尽！当前可用内存占总内存的$Percentage%"
    else
        echo "系统内存状态良好，当前可用内存占总内存的$Percentage%"
    fi

    echo ""
    echo -e "${GREEN}【6】CPU情况：${RESET}"
    cpu_num=$(grep -c "model name" /proc/cpuinfo)
    echo "cpu总核数：$cpu_num"
    cpu_idle=$(top -b -n 1 | grep Cpu | awk '{print $8}')
    echo "空闲CPU百分比：$cpu_idle%"
    cpu_interrupt=$(vmstat -n 1 1 | sed -n 3p | awk '{print $11}')
    echo "CPU中断次数：$cpu_interrupt"
    cpu_context_switch=$(vmstat -n 1 1 | sed -n 3p | awk '{print $12}')
    echo "CPU上下文切换次数：$cpu_context_switch"

    echo ""
    echo -e "${GREEN}【7】磁盘情况：${RESET}"
    df -h | awk '/^\/dev/ {printf "磁盘 -> 挂载点：%s\t总数：%s\t已用：%s\t可用：%s\t使用率：%s\n", $NF, $2, $3, $4, $5}'

    echo ""
    echo -e "${GREEN}【8】系统运行时长：${RESET}"
    RTIME=$(/usr/bin/uptime | awk '{print $3}') && echo $RTIME"天"
}

# 检查节点返回状态码是否正常
function check_http() {
    echo ""
    echo -e "${GREEN}【9】节点访问域名情况：${RESET}"

    if systemctl is-active --quiet salt-minion.service; then
        host="www.agc.cloud"
    else
        host="zjwtest.agc.cloud"
    fi

    status_code=$(curl -s -o /dev/null -I -H "Host: $host" -k https://127.0.0.1 -w "%{http_code}")


    # 判断状态码范围
    if [ "$status_code" -ge 200 ] && [ "$status_code" -lt 400 ]; then
        echo -e "${CYAN}节点状态正常 (HTTP状态码: $status_code)${RESET}"
    else
        echo -e "${RED}节点状态异常 (HTTP状态码: $status_code)${RESET}"
    fi
}

function check_all() {
    check_value
    check_service_status "young_agent"
    check_service_status "nginx"
    check_service_status "logstash"
    check_service_status "logstash-exporter"
    check_logstash
    check_prometheus
    check_system
    check_http
}

check_all
exit 0
