K8s-Event-Alerter基于Kind集群的端到端测试指南
本文档基于 macOS (Apple Silicon) 环境实测验证,记录从零搭建 Kind 集群到完成全部测试用例的完整流程。
一、前置准备
1.1 工具要求
kind version # >= 0.25.0
kubectl version # >= 1.28
helm version # >= 3.12
docker version # Docker Desktop 运行中
go version # >= 1.24
macOS 安装:
brew install kind kubectl helm go
1.2 项目源码
cd /path/to/k8s-event-alerter
二、创建 Kind 集群
2.1 集群配置
创建 kind-config.yaml:
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
2.2 创建集群
kind create cluster --name alerter-test --config kind-config.yaml
2.3 导出 kubeconfig
Kind 可能无法写入默认 kubeconfig,建议导出到独立文件:
kind get kubeconfig --name alerter-test > /tmp/alerter-kubeconfig
export KUBECONFIG=/tmp/alerter-kubeconfig
后续所有
kubectl/helm命令均依赖此环境变量,请确保每个终端窗口都已 export。
验证集群就绪:
kubectl get nodes
# NAME STATUS ROLES AGE VERSION
# alerter-test-control-plane Ready control-plane 30s v1.31.2
# alerter-test-worker Ready <none> 20s v1.31.2
三、构建镜像并加载到 Kind
Kind 集群使用独立的容器运行时,不能直接访问宿主机 Docker 镜像,需要显式加载。
3.1 构建 Docker 镜像
由于 Dockerfile 默认使用阿里云 registry(在本地可能无法访问),推荐先本地编译再打包:
# 本地交叉编译 (Apple Silicon → linux/arm64)
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o /tmp/manager cmd/main.go
# 用最小化 Dockerfile 打包
mkdir -p /tmp/docker-build-ctx
cp /tmp/manager /tmp/docker-build-ctx/
cat <<'EOF' > /tmp/docker-build-ctx/Dockerfile
FROM alpine:latest
ENV TZ=Asia/Shanghai
RUN adduser -D -u 65532 nonroot
WORKDIR /
COPY manager .
USER 65532:65532
ENTRYPOINT ["/manager"]
EOF
docker build -t k8s-event-alerter:test /tmp/docker-build-ctx
amd64 环境:将
GOARCH=arm64改为GOARCH=amd64。如果 Docker Hub 可访问,也可以直接用项目 Dockerfile(需替换阿里云 registry 为 Docker Hub):
docker build -t k8s-event-alerter:test .
3.2 加载到 Kind 集群
kind load docker-image k8s-event-alerter:test --name alerter-test
四、部署 K8s Event Alerter
4.1 Helm 安装
helm upgrade --install k8s-event-alerter chart/ \
--namespace alerter-system \
--create-namespace \
--set image.repository=k8s-event-alerter \
--set image.tag=test \
--set image.pullPolicy=Never \
--set leaderElection.enabled=false
pullPolicy=Never确保使用 Kind 中预加载的本地镜像。
leaderElection.enabled=false单副本测试无需 Leader Election。
4.2 验证部署
# 检查 Pod 状态
kubectl get pods -n alerter-system
# NAME READY STATUS RESTARTS AGE
# k8s-event-alerter-xxxxx 1/1 Running 0 30s
# 检查 CRD 已注册
kubectl get crd podalertrules.alert.k8seventalerter.io
# NAME CREATED AT
# podalertrules.alert.k8seventalerter.io 2026-09-10T06:52:36Z
# 检查 shortName 可用
kubectl get par
# No resources found
如果 Pod 未就绪,排查:
kubectl logs -n alerter-system -l app.kubernetes.io/name=k8s-event-alerter
kubectl get events -n alerter-system --sort-by='.lastTimestamp'
4.3 确认 Controller 正常启动
kubectl logs -n alerter-system -l app.kubernetes.io/name=k8s-event-alerter
预期输出:
INFO setup starting manager
INFO Starting EventSource {"controller": "podalertrule", "source": "kind source: *v1.Pod"}
INFO Starting EventSource {"controller": "podalertrule", "source": "kind source: *v1alpha1.PodAlertRule"}
INFO Starting Controller {"controller": "podalertrule"}
INFO Starting workers {"controller": "podalertrule", "worker count": 1}
关键确认:Controller 同时 Watch 了 Pod 和 PodAlertRule 两种资源。
五、创建测试 namespace 和规则
5.1 创建目标 namespace
kubectl create namespace test-alert
5.2 创建测试用 PodAlertRule
cat <<'EOF' | kubectl apply -f -
apiVersion: alert.k8seventalerter.io/v1alpha1
kind: PodAlertRule
metadata:
name: test-pending-rule
spec:
namespaces:
- test-alert
alertTypes:
- type: Pending
threshold: "30s"
- type: Evicted
- type: ImagePullBackOff
- type: Failed
threshold: "30s"
webhooks:
- type: feishu
url: "https://httpbin.org/post"
severity: warning
maxPodAge: "1h"
EOF
验证规则创建:
kubectl get par
# NAME SEVERITY ALERTSSENT AGE
# test-pending-rule warning 5s
六、测试用例
6.1 测试一:Pending Pod 检测
创建一个因 nodeSelector 无法调度的 Pod:
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: test-pending-pod
namespace: test-alert
spec:
containers:
- name: app
image: busybox
command: ["sleep", "3600"]
nodeSelector:
non-existent-label: "true"
EOF
# 确认 Pod 处于 Pending 状态
kubectl get pod test-pending-pod -n test-alert
# NAME READY STATUS RESTARTS AGE
# test-pending-pod 0/1 Pending 0 5s
等待超过 threshold (30s) 后检查:
sleep 35
# 检查规则状态
kubectl get par test-pending-rule -o jsonpath='{.status}' | python3 -m json.tool
# {
# "alertsSent": 1,
# "lastCheckTime": "2026-09-10T07:16:44Z"
# }
预期结果:alertsSent 从 0 变为 1,Pending 超过 30s 后成功触发告警。
6.2 测试二:ImagePullBackOff 检测
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: test-imagepull-pod
namespace: test-alert
spec:
containers:
- name: app
image: nonexistent-registry.example.com/no-such-image:v999
EOF
sleep 15
kubectl get pod test-imagepull-pod -n test-alert
# NAME READY STATUS RESTARTS AGE
# test-imagepull-pod 0/1 ImagePullBackOff 0 15s
kubectl get par test-pending-rule -o jsonpath='{.status.alertsSent}'
# 2 ← 新增一条 ImagePullBackOff 告警
预期结果:alertsSent 增加,ImagePullBackOff 立即触发(无需等待 threshold)。
6.3 测试三:非目标 namespace 不受影响
kubectl create namespace test-other
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: test-other-ns-pod
namespace: test-other
spec:
containers:
- name: app
image: nonexistent-registry.example.com/no-such-image:v999
EOF
通过 Prometheus 指标验证 namespace 隔离:
kubectl exec -n alerter-system deploy/k8s-event-alerter -- wget -qO- http://localhost:8080/metrics | grep k8seventalerter_alerts_sent
预期结果:所有 alerts_sent_total 指标的 namespace 标签均为 test-alert,没有 test-other。
6.4 测试四:告警去重(Annotation 标记)
验证 annotation 去重机制:同一异常只告警一次。
# 检查 Pod annotation 标记
kubectl get pod test-pending-pod -n test-alert -o jsonpath='{.metadata.annotations}' | python3 -m json.tool
# {
# "alert.k8seventalerter.io/alerted-Pending": "test-pending-rule",
# ...
# }
# 检查 skipped 指标(因已有 annotation 而跳过的告警)
kubectl exec -n alerter-system deploy/k8s-event-alerter -- wget -qO- http://localhost:8080/metrics | grep skipped
# k8seventalerter_alerts_skipped_total{alert_type="Pending",namespace="test-alert",rule="test-pending-rule"} 105
预期结果:Pod 上有 alert.k8seventalerter.io/alerted-{Type} annotation,skipped_total 持续增长但 sent_total 不变,证明 annotation 去重正常。
6.5 测试五:异常恢复检测
验证 Pod 异常恢复后 annotation 自动移除。
# 先确认 Pod 有 Pending annotation
kubectl get pod test-pending-pod -n test-alert -o jsonpath='{.metadata.annotations.alert\.k8seventalerter\.io/alerted-Pending}'
# test-pending-rule
# 删除异常 Pod,重新创建为可调度的 Pod
kubectl delete pod test-pending-pod -n test-alert
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: test-pending-pod
namespace: test-alert
spec:
containers:
- name: app
image: busybox
command: ["sleep", "3600"]
EOF
sleep 15
# Pod 变为 Running 后,annotation 应被移除
kubectl get pod test-pending-pod -n test-alert
# NAME READY STATUS RESTARTS AGE
# test-pending-pod 1/1 Running 0 15s
kubectl get pod test-pending-pod -n test-alert -o jsonpath='{.metadata.annotations}' | python3 -m json.tool
# 只剩 kubectl.kubernetes.io/last-applied-configuration,无 alerted-Pending
# 检查 Controller 日志确认恢复检测
kubectl logs -n alerter-system -l app.kubernetes.io/name=k8s-event-alerter --tail=10 | grep recovered
# INFO anomaly recovered, annotation removed {"pod": "test-pending-pod", "namespace": "test-alert", "type": "Pending"}
预期结果:Pod 恢复为 Running 后,alerted-Pending annotation 被自动移除,Controller 日志记录 "anomaly recovered"。如果 Pod 再次异常,会重新告警。
6.6 测试六:多规则 + 多 Webhook 类型
cat <<'EOF' | kubectl apply -f -
apiVersion: alert.k8seventalerter.io/v1alpha1
kind: PodAlertRule
metadata:
name: test-critical-rule
spec:
namespaces:
- test-alert
alertTypes:
- type: ImagePullBackOff
webhooks:
- type: dingtalk
url: "https://httpbin.org/post"
- type: wecom
url: "https://httpbin.org/post"
severity: critical
EOF
sleep 5
kubectl get par
# NAME SEVERITY ALERTSSENT AGE
# test-critical-rule critical 1 6s
# test-pending-rule warning 15 18m
预期结果:新规则独立运行,同一个 ImagePullBackOff Pod 同时被两条规则检测到,各自发送告警。
6.7 测试七:maxPodAge 过滤历史 Pod
cat <<'EOF' | kubectl apply -f -
apiVersion: alert.k8seventalerter.io/v1alpha1
kind: PodAlertRule
metadata:
name: test-maxage-rule
spec:
namespaces:
- test-alert
alertTypes:
- type: Pending
threshold: "1s"
- type: ImagePullBackOff
webhooks:
- type: feishu
url: "https://httpbin.org/post"
severity: info
maxPodAge: "5s"
EOF
sleep 10
kubectl get par test-maxage-rule -o jsonpath='{.status.alertsSent}'
# (空,即 0)
预期结果:alertsSent 为 0。maxPodAge: "5s" 把所有超过 5 秒的 Pod 过滤掉,现有的异常 Pod 都已超龄,不触发告警。
6.8 测试八:Label Selector 筛选
cat <<'EOF' | kubectl apply -f -
apiVersion: alert.k8seventalerter.io/v1alpha1
kind: PodAlertRule
metadata:
name: test-selector-rule
spec:
namespaces:
- test-alert
podSelector:
matchLabels:
app: specific-app
alertTypes:
- type: ImagePullBackOff
webhooks:
- type: feishu
url: "https://httpbin.org/post"
severity: info
EOF
sleep 5
kubectl get par test-selector-rule -o jsonpath='{.status.alertsSent}'
# (空,即 0)
预期结果:alertsSent 为 0。现有 Pod 没有 app=specific-app label,不匹配规则。
6.9 测试九:Prometheus 指标完整性
kubectl exec -n alerter-system deploy/k8s-event-alerter -- wget -qO- http://localhost:8080/metrics | grep -E "^k8seventalerter_" | sort
预期结果:
k8seventalerter_alerts_sent_total— 按 rule/namespace/alert_type/severity 细分k8seventalerter_anomalies_detected_total— 按 rule/namespace/alert_type 细分k8seventalerter_alerts_skipped_total— 按 rule/namespace/alert_type 细分k8seventalerter_check_duration_seconds_*— 按 rule 细分的直方图
6.10 测试十:健康的 Pod 不触发告警
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: test-healthy-pod
namespace: test-alert
spec:
containers:
- name: app
image: busybox
command: ["sleep", "3600"]
EOF
sleep 10
kubectl get pod test-healthy-pod -n test-alert
# NAME READY STATUS RESTARTS AGE
# test-healthy-pod 1/1 Running 0 10s
预期结果:Running 状态的 Pod 不会增加任何规则的 alertsSent。
七、检查日志
kubectl logs -n alerter-system -l app.kubernetes.io/name=k8s-event-alerter --tail=50
Controller 日志以 controller-runtime 标准格式输出,关注以下信息:
| 日志关键词 | 含义 |
|---|---|
Starting workers | Controller 启动完成 |
failed to dispatch alert | Webhook 发送失败(测试中因 httpbin 超时是正常的) |
failed to update status | Status 更新冲突(偶发,自动重试) |
八、排障指南
8.1 Pod 无法启动
kubectl describe pod -n alerter-system -l app.kubernetes.io/name=k8s-event-alerter
kubectl get events -n alerter-system --sort-by='.lastTimestamp'
常见原因:
- 镜像未加载到 Kind(
kind load docker-image是否成功) pullPolicy不是Never(尝试从远程拉取不存在的 tag)
8.2 CRD 不存在
kubectl get crd | grep k8seventalerter
CRD 由 Helm chart 的 crd.yaml 模板自动创建。如果缺失,检查 chart/templates/crd.yaml 是否完整。
8.3 规则创建后 alertsSent 一直为 0
- 检查 namespace 是否匹配:
kubectl get par <name> -o yaml | grep namespaces - 检查 maxPodAge 是否太短:已有 Pod 可能已超龄
- 检查 threshold:Pending/Failed 需要等待超过阈值时间
- 检查 Pod 是否真的处于异常状态:
kubectl get pods -n <ns>
8.4 Docker 镜像构建环境问题
本地构建时如果 Docker Hub / 阿里云 registry 不可达,使用本地交叉编译方案:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o /tmp/manager cmd/main.go
然后用 alpine:latest 本地缓存打包。
九、清理
# 删除测试 Pod
kubectl delete pod --all -n test-alert
kubectl delete pod --all -n test-other
# 删除测试规则
kubectl delete par --all
# 卸载 controller
helm uninstall k8s-event-alerter -n alerter-system
# 删除 namespace
kubectl delete namespace test-alert test-other alerter-system
# 删除 Kind 集群
kind delete cluster --name alerter-test
十、测试 Checklist
| # | 测试项 | 预期结果 | 通过 |
|---|---|---|---|
| 1 | Pending Pod 超过阈值后触发告警 | alertsSent 从 0 变为 1 | ✅ |
| 2 | ImagePullBackOff 立即触发告警 | alertsSent 增加 | ✅ |
| 3 | 非目标 namespace 不受影响 | metrics 中无 test-other namespace | ✅ |
| 4 | Annotation 去重正常 | Pod 有 alerted annotation,skipped_total > 0,sent_total 不变 | ✅ |
| 5 | 异常恢复后 annotation 自动移除 | Pod Running 后无 alerted annotation,日志记录 recovered | ✅ |
| 6 | 多规则独立运行 | 两条规则各自计数 | ✅ |
| 7 | maxPodAge 过滤历史 Pod | maxPodAge=5s 时 alertsSent=0 | ✅ |
| 8 | Label Selector 正确筛选 | 无匹配 label 时 alertsSent=0 | ✅ |
| 9 | Prometheus 4 项指标均有数据 | alerts_sent, anomalies_detected, skipped, check_duration | ✅ |
| 10 | 健康 Pod 不触发告警 | Running Pod 不增加 alertsSent | ✅ |