深色模式
爆炸半径控制
摘要:控制爆炸半径的能力决定混沌实验能做多大。本文用"选谁(选择器)→ 选多少(百分比/数量)→ 影响多久(时长)"三层收敛,配合 Chaos Mesh 的 selector 与 duration 字段落地。
适用环境
bash
kubectl get ns
kubectl get pod -l app=demo --show-labels | head
# Chaos Mesh 已安装时
kubectl -n chaos-mesh get pod | head1
2
3
4
2
3
4
操作步骤
第 1 步:第一层——限定目标(selector)
yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
name: kill-one-demo
namespace: test
spec:
action: pod-kill
mode: one # one / all / fixed / fixed-percent / random-max-percent
selector:
namespaces: [test] # 只作用于 test 命名空间
labelSelectors:
app: demo # 只作用于 demo
duration: '30s'1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
bash
kubectl apply -f kill-one-demo.yaml
kubectl -n test get podchaos1
2
2
第 2 步:第二层——限定数量(mode)
yaml
# 只影响 10% 的 Pod,且至少保留可用副本
spec:
mode: fixed-percent
value: '10'
selector:
namespaces: [test]
labelSelectors: { app: demo }1
2
3
4
5
6
7
2
3
4
5
6
7
bash
# 用 random-max-percent 更保守:随机取不超过 X%
kubectl explain podchaos.spec.mode 2>/dev/null || kubectl explain --api-version=chaos-mesh.org/v1alpha1 podchaos.spec1
2
2
第 3 步:第三层——限定时长与自动停止
yaml
spec:
duration: '60s' # 到点自动结束,无需人工干预
# 周期性实验务必同时设置 scheduler 与 duration
scheduler:
cron: '@every 1h'1
2
3
4
5
2
3
4
5
第 4 步:为生产环境加保护罩
bash
# 用命名空间隔离 + RBAC 限制谁能创建实验
cat > chaos-rbac.yaml <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: chaos-operator
namespace: test
rules:
- apiGroups: ['chaos-mesh.org']
resources: ['podchaos', 'networkchaos', 'stresschaos']
verbs: ['create', 'get', 'list', 'delete']
EOF
kubectl apply -f chaos-rbac.yaml1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
第 5 步:实验前预检清单
bash
cat > precheck.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
ns=${1:-test}; app=${2:-demo}
echo "副本: $(kubectl -n $ns get deploy $app -o jsonpath='{.spec.replicas}')"
echo "可用: $(kubectl -n $ns get deploy $app -o jsonpath='{.status.readyReplicas}')"
echo "PDB : $(kubectl -n $ns get pdb -o name | wc -l)"
echo "当前告警: $(curl -s http://127.0.0.1:9093/api/v2/alerts | jq 'length')"
EOF
chmod +x precheck.sh && ./precheck.sh test demo1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
验证
bash
# 1. 实验对象数量符合预期(不是全量)
kubectl -n test get podchaos kill-one-demo -o yaml | grep -A2 'mode'
# 2. 未命中目标标签的 Pod 未受影响
kubectl -n test get pod -l app!=demo --no-headers | wc -l
# 3. duration 到期后实验自动结束
kubectl -n test get podchaos kill-one-demo -o jsonpath='{.status.phase}{"\n"}'1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
常见坑
selector 写错变成全命名空间生效
labelSelectors 拼写错误会匹配为空或退化为全选。实验前先用 kubectl get pod -l ... 验证选择器命中数。
忘记设置 duration
无 duration 的实验会一直生效,直到手动删除。任何实验都必须带明确结束时间。
在副本数为 1 的服务上做 pod-kill
直接造成服务中断,这不是实验而是事故。实验前检查副本数与 PDB,不足则先扩容。