1. Understand the Goal: The user wants a "network chaos lab." This is a practical, hands-on guide/lab exercise. Key requirements are:
* Safe: Needs to be contained (e.g., a local environment or specific namespace) to avoid breaking the host or production.
* Capabilities: Packet drops, latency injection, routing perturbations.
* Observability: Automated correlation (logs, metrics, traces) to see the impact of the chaos.
2. Choose the Stack:
* Orchestration: Kubernetes (Minikube or Kind) is the standard for chaos engineering. It's isolated and declarative.
* Chaos Tool: Chaos Mesh or LitmusChaos. Chaos Mesh is very user-friendly for network chaos (NetworkChaos CRD). Let's go with Chaos Mesh because its NetworkChaos CRD supports all three requested features (drop, delay, duplicate/corrupt/modify) and works well with CNI plugins.
* Target Application: Needs to be something network-heavy. A simple microservice demo like Sock Shop or Online Boutique is good, but maybe a custom simple ping/pong or client/server setup is clearer for a specific lab. Let's use a simple "podinfo" or a custom multi-tier app to keep dependencies low. Actually, the standard Online Boutique (microservices-demo) is complex enough to show real correlation but might be overkill to deploy. Let's stick to a simple client-server setup within K8s for clarity, or maybe Nginx as the target. Let's go with a custom lightweight setup: A "Client" pod calling a "Server" pod. This makes the "directionality" of the chaos easy to understand.
* Observability: Prometheus (metrics), Grafana (visualization), and maybe Jaeger (tracing). To satisfy "automated correlation," I need to show how the chaos event maps to the metric spike.
3. Lab Structure:
* Prerequisites: Docker, Kind/Minikube, kubectl, Helm.
* Step 1: Setup Environment: Create the cluster and install Chaos Mesh + Monitoring stack.
* Step 2: Deploy Target: Deploy a resilient app.
* Step 3: Observability Baseline: Look at the happy path.
* Step 4: Experiment 1 - Latency (The "Slow Down"): Apply NetworkChaos for delay. View correlation.
* Step 5: Experiment 2 - Packet Loss (The "Broken Pipe"): Apply NetworkChaos for drop. View correlation.
* Step 6: Experiment 3 - Routing Perturbation (The "Detour"): This is tricky. Strictly speaking, Chaos Mesh supports "duplicate," "corrupt," or "reorder". "Routing perturbation" implies changing where packets go. A "partition" (blackhole) acts like a route cut. Or, using IP tables to redirect. Chaos Mesh NetworkChaos acts mostly on tc (traffic control). Let's interpret "routing perturbation" as Packet Corruption/Duplication or Partition. I'll use Partition (total isolation) as it simulates a routing failure/route flap effectively.
4. Refining the Content - The "Lab" Feel:
* Needs commands to copy-paste.
* Needs explanations of why we are doing this.
* Needs specific "Checkpoints" (what to look for).
5. Drafting the Solution (Iterative refinement):
* *Environment:* I'll use `kind` (Kubernetes in Docker) because it's lightweight and easy to reset.
* *App:* I'll create a simple Kubernetes manifest with a "Hello" server and a "Loadgen" (curl loop) client. This creates traffic logs.
* *Observability:* Installing the full Prometheus stack is heavy for a quick lab. Maybe just a lightweight metrics server? No, the prompt asks for *correlation*. I need metrics. I'll use the `kube-prometheus-stack` helm chart but note that it takes a while to start. Alternatively, just use the Chaos Mesh Dashboard which has basic monitoring built-in, but that's weak on "correlation". Let's stick to the Chaos Mesh Dashboard *plus* a simple script that logs HTTP codes to stdout (which `kubectl logs` can see) to keep the lab self-contained and fast, while mentioning Prometheus integration for advanced users.
* *Wait, actually:* The prompt asks for "Automated Observability Correlation." The best way to show this is to label the chaos events in the metrics.
* *Revised Observability Strategy:* I will use the **Chaos Mesh Dashboard**. It actually visualizes the experiment status. But to make it a "lab," I should probably include a sidecar or simple curl script that generates logs. I will provide a `curl` loop that prints timestamps.
6. Step-by-Step Detail Generation:
* *Step 0:* Prereqs.
* *Step 1:* Create Cluster (`kind create cluster`).
* *Step 2:* Install Chaos Mesh (`helm install`).
* *Step 3:* Deploy "Vulnerable App". I'll write a simple `deployment.yaml` for an Nginx server and a Busybox client sending requests every second.
* *Step 4 (Latency):* Define `NetworkChaos` yaml. `action: delay`. `latency: "10ms"`.
* *Correlation:* Show the client logs timing out or taking longer.
* *Step 5 (Drop):* `action: loss`. `loss: "50"`.
* *Correlation:* Show connection errors.
* *Step 6 (Routing/Partition):* `action: partition`.
* *Correlation:* Show total unreachability.
7. Safety Checks:
* Ensure the NetworkChaos has a duration so it stops automatically.
* Ensure direction is specified (e.g., to or from) to limit blast radius.
8. Refining the "Routing Perturbation":
* Real routing perturbation is hard in a simple K8s lab without BGP. But action: partition in Chaos Mesh simulates a network partition, effectively acting as a "blackhole route". I will clarify this interpretation.
9. Writing the response:
* Use code blocks for all commands/YAML.
* Use bold text for emphasis.
* Add a "Clean Up" section.
(Self-Correction during drafting):
- Issue: Installing Prometheus/Grafana is too slow for a quick text-based lab.
- Fix: I will focus on Log Correlation and the Chaos Mesh Dashboard for immediate visual feedback, but I will provide the architecture for a Prometheus-based setup as an "Advanced" step.
- Actually, let's include a lightweight observability setup. Just a simple Python script or shell loop that logs "Time | Status | Latency" is enough to prove correlation in a lab context without waiting 5 minutes for CRDs to install.
10. Final Polish:
* Title: "The Fractured Pipeline: A Network Chaos Lab".
* Structure: Setup -> Deploy -> Experiment 1 (Latency) -> Experiment 2 (Loss) -> Experiment 3 (Partition) -> Cleanup.
Let's write the actual YAMLs.
- Scenario:
client talks to server.
- Chaos: Target
server (or link between client and server).
Let's go.
This lab guide creates a controlled "Chaos Engineering" environment using Kubernetes (KinD), Chaos Mesh (for fault injection), and a lightweight observability stack.
The goal is to safely inject network failures into a sample application and visually correlate the impact on latency and error rates.
Lab Prerequisites
- Docker (running daemon)
- kubectl (installed)
- Helm (installed)
Phase 1: Environment Setup
We will create a local Kubernetes cluster using KinD (Kubernetes in Docker) to ensure total isolation from your host network.
1. Create the Cluster Configuration
Save this as kind-config.yaml. It sets up a cluster with port mappings so we can access the observability tools locally.
# kind-config.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
extraPortMappings:
- containerPort: 30000 # Grafana
hostPort: 30000
- containerPort: 30001 # Chaos Mesh Dashboard
hostPort: 30001
2. Provision the Cluster
kind create cluster --config kind-config.yaml --name chaos-lab
kubectl config use-context kind-chaos-lab
3. Install Chaos Mesh
We will install Chaos Mesh with the Dashboard enabled.
helm repo add chaos-mesh https://charts.chaos-mesh.org
helm repo update
kubectl create ns chaos-testing
helm install chaos-mesh chaos-mesh/chaos-mesh \
--namespace=chaos-testing \
--set dashboard.create=true \
--set dashboard.service.type=NodePort \
--set dashboard.service.nodePort=30001 \
--set chaosDaemon.runtime=containerd \
--set chaosDaemon.socketPath=/run/containerd/containerd.sock
Phase 2: Deploy the Target Application
We need a "System Under Test" (SUT). We will deploy a simple Nginx server and a Load Generator that constantly hits the Nginx server to generate traffic metrics.
1. Deploy Nginx & Load Generator
Save and apply this manifest as app.yaml.
# app.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-server
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
resources:
requests:
cpu: "50m"
---
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- port: 80
---
# A simple load generator that curls the nginx service in a loop
apiVersion: batch/v1
kind: Job
metadata:
name: load-generator
spec:
template:
spec:
containers:
- name: curler
image: curlimages/curl:latest
command: ["/bin/sh", "-c"]
# We use 'time' to output latency in the logs for correlation
args:
- |
while true; do
echo "--- $(date) ---";
time curl -s -o /dev/null -w "HTTP Status: %{http_code}\n" http://nginx-service;
sleep 1;
done
restartPolicy: Never
backoffLimit: 0
kubectl apply -f app.yaml
Phase 3: Network Chaos Experiments
We will define three specific chaos scenarios. Save these into a folder named scenarios/.
Scenario A: Latency Injection (The "Lag")
This simulates a noisy network or overloaded router. It adds 2 seconds of delay to all traffic.
File: scenarios/latency.yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: network-latency
spec:
action: delay
mode: one
selector:
namespaces:
- default
labelSelectors:
app: nginx
delay:
latency: "2000ms"
duration: "60s"
Scenario B: Packet Drops (The "Flaky Connection")
This simulates failing hardware or congestion. It drops 50% of packets.
File: scenarios/drop.yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: network-drop
spec:
action: loss
mode: one
selector:
namespaces:
- default
labelSelectors:
app: nginx
loss:
loss: "50"
correlation: "25" # Correlation creates bursty patterns, more realistic
direction: to
duration: "60s"
Scenario C: Bandwidth throttling (The "Bottleneck")
This simulates a routing perturbation where bandwidth is suddenly restricted.
File: scenarios/bandwidth.yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: network-bandwidth
spec:
action: bandwidth
mode: one
selector:
namespaces:
- default
labelSelectors:
app: nginx
bandwidth:
rate: "1kbits" # Very slow
limit: 1000
buffer: 1000
duration: "60s"
Phase 4: Execution & Observability Correlation
In this lab, we use Standard Output (Logs) as our observable metric to correlate the exact timing of the failure.
1. Start the Observation Terminal
Open a terminal window and watch the logs of the load generator. This is your "Live Dashboard."
# Get the pod name dynamically
POD=$(kubectl get pods -l job-name=load-generator -o jsonpath='{.items[0].metadata.name}')
# Stream logs
kubectl logs -f $POD
Note: You should see HTTP Status: 200 roughly every second.
2. Run Experiment A (Latency)
In a separate terminal, apply the latency chaos:
kubectl apply -f scenarios/latency.yaml
- Correlation:
- Immediately look at your Observation Terminal.
- You will see the loop pause.
- After ~3 seconds (1s sleep + 2s delay), the log will appear.
- The
time command in the script will report real 0m2.XXs.
- Safety: This automatically reverts after 60s.
3. Clean up and Run Experiment B (Packet Drop)
Wait for the first experiment to finish (or kubectl delete -f scenarios/latency.yaml), then:
kubectl apply -f scenarios/drop.yaml
- Correlation:
- Watch the logs.
curl might still connect occasionally, but you will start seeing connection timeouts or errors if the loss rate is high enough (curl usually has a timeout).
- You will see the loop become erratic (fast, then stuck, then fast).
4. Visual Verification (Optional)
Access the Chaos Mesh Dashboard to see the timeline visually.
- Run
kubectl port-forward -n chaos-testing svc/chaos-dashboard 30001:2333 (If not using NodePort).
- Open browser to
http://localhost:30001.
- You will see the "Archive" of experiments with their start/end timestamps, which perfectly aligns with the glitches seen in your terminal logs.
Phase 5: Automated "Blast Radius" Check (Safety Script)
To make this lab enterprise-ready, we need a script that ensures we don't destroy the cluster if things go wrong. This script monitors the application health and automatically terminates the chaos if the error rate gets too high.
Save as safety-monitor.sh:
#!/bin/bash
# Checks the Nginx pod status. If it crashes or enters an unknown state
# during chaos, we assume something went wrong and kill the chaos experiments.
echo "Starting Safety Monitor..."
while true; do
STATUS=$(kubectl get pods -l app=nginx -o jsonpath='{.items[0].status.phase}')
if [ "$STATUS" != "Running" ]; then
echo "ALERT: Application State is $STATUS. Killing chaos..."
kubectl delete networkchaos --all
exit 1
fi
# Optional: Check for high latency using curl timeouts
if ! curl -s --max-time 5 http://localhost:8080 > /dev/null 2>&1; then
# In a real lab, you might trigger an alert here
echo "Endpoint unreachable (expected in chaos, or fatal error)"
fi
sleep 5
done
Summary of Correlation
By running this lab, you have established a clear causal link:
- Action:
kubectl apply -f latency.yaml
- Mechanism: Chaos Mesh injects
tc (traffic control) rules into the container network interface.
- Observable Effect: The
curl command in the logs reports real 0m2.0XXs.
- Safety: The
duration field ensures the chaos self-destructs.
Teardown
kind delete cluster --name chaos-lab