argus/src/alert/tests/scripts/04_query_alerts.sh
xuxt 8fbe107ac9 dev_1.0.0_xuxt 完成web和alert模块开发,以及模块e2e测试 (#21)
Co-authored-by: xiuting.xu <xiutingxt.xu@gmail.com>
Reviewed-on: #21
Reviewed-by: huhy <husteryezi@163.com>
Reviewed-by: sundapeng <sundp@mail.zgclab.edu.cn>
Reviewed-by: yuyr <yuyr@zgclab.edu.cn>
2025-10-14 10:20:45 +08:00

72 lines
2.2 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
set -euo pipefail
# ==========================================================
# Alertmanager 测试脚本(含启动等待)
# ==========================================================
ALERTMANAGER_URL="http://localhost:9093"
TEST_ALERT_NAME_CRITICAL="NodeDown"
TEST_ALERT_NAME_WARNING="HighCPU"
TMP_LOG="/tmp/test-alertmanager.log"
# 等待参数
am_wait_attempts=30
am_wait_interval=2
GREEN="\033[1;32m"
RED="\033[1;31m"
YELLOW="\033[1;33m"
RESET="\033[0m"
# ==========================================================
# 函数定义
# ==========================================================
wait_for_alertmanager() {
local attempt=1
echo "[INFO] 等待 Alertmanager 启动中..."
while (( attempt <= am_wait_attempts )); do
if curl -fsS "${ALERTMANAGER_URL}/api/v2/status" >/dev/null 2>&1; then
echo -e "${GREEN}[OK] Alertmanager 已就绪 (attempt=${attempt}/${am_wait_attempts})${RESET}"
return 0
fi
echo "[..] Alertmanager 尚未就绪 (${attempt}/${am_wait_attempts})"
sleep "${am_wait_interval}"
(( attempt++ ))
done
echo -e "${RED}[ERROR] Alertmanager 在 ${am_wait_attempts} 次尝试后仍未就绪${RESET}"
return 1
}
log_step() {
echo -e "${YELLOW}==== $1 ====${RESET}"
}
# ==========================================================
# 主流程
# ==========================================================
log_step "查询 Alertmanager 当前告警列表开始"
echo "[INFO] Alertmanager 地址: $ALERTMANAGER_URL"
# Step 1: 等待 Alertmanager 启动
wait_for_alertmanager
# Step 2: 查询当前告警列表
echo "[INFO] 查询当前告警..."
sleep 1
curl -fsS "${ALERTMANAGER_URL}/api/v2/alerts" | jq '.' || {
echo -e "${RED}[WARN] 无法解析返回 JSON请检查 jq 是否安装${RESET}"
curl -s "${ALERTMANAGER_URL}/api/v2/alerts"
}
# Step 3: 检查告警是否包含 NodeDown
if curl -fsS "${ALERTMANAGER_URL}/api/v2/alerts" | grep -q "${TEST_ALERT_NAME_CRITICAL}"; then
echo -e "${GREEN}✅ 测试通过Alertmanager 已成功接收告警 ${TEST_ALERT_NAME_CRITICAL}${RESET}"
else
echo -e "${RED}❌ 测试失败:未检测到告警 ${TEST_ALERT_NAME_CRITICAL}${RESET}"
fi
log_step "测试结束"