The user wants me to engineer an "Incident Simulation Generator."
This is a complex system design and implementation task.
The goal is to create a tool that creates realistic "training scenarios" for engineers based on:
- Real production topology (e.g., Kubernetes clusters, VMs, regions).
- Dependency graphs (Service A calls Service B, DB C).
- Failure modes (Latency, CPU spike, Pod kill, Network partition).
The output should be a comprehensive design and a conceptual implementation (or a scaffold) that demonstrates how this works.
1. Deconstruct the Request:
- Core Function: Generate incident scenarios.
- Inputs: Topology, Dependencies, Failure Modes.
- Outputs: A scenario (narrative + technical injection steps) for training (Game Days).
- Key Features:
- Discovery (reading topology).
- Graph Analysis (finding blast radius).
- Randomization/Selection of failure modes.
- Output format (runbooks, Chaos Engineering experiments).
2. High-Level Architecture:
I need to design a modular system.
- Ingestion Layer: Pulls data from K8s, Service Mesh (Istio/Linkerd), APM (Datadog/New Relic), CMDB.
- Knowledge Graph (The Brain): Stores the topology and dependencies. Needs to support nodes (services, dbs, queues) and edges (sync calls, async events).
- Simulation Engine: The logic that picks a starting point, applies a failure, and calculates the downstream effects (blast radius).
- Generator: Formats the output into a usable format (e.g., Markdown runbook + Gremlin/ChaosBlade commands).
3. Detailed Component Design:
- Topology Ingestion: Let's assume a Kubernetes environment because it's standard. It reads Custom Resource Definitions (CRDs) or live API data.
- Dependency Graph: A directed graph. If Service A -> Service B, and B fails, A is impacted.
- Failure Modes:
- Resource: CPU/Mem exhaustion.
- Network: Packet loss, latency, DNS failure.
- State: Crash loop, disk full.
- Scenario Generation Logic:
- Random approach: Pick a random node, pick a random failure.
- Targeted approach: Pick a critical path node.
- Blast Radius Calculation: BFS/DFS from the failure point to see what gets hurt.
4. Implementation Strategy (The "Code" part):
Since I can't access the user's actual production environment, I must build a simulation framework that mocks these components but has the interfaces ready for real integration.
- Python is the best language here (great libraries for graphs - NetworkX).
- Structure:
Topology class (to load data).
FailureMode class (definitions).
Generator class (the main logic).
5. Refining the Output:
The user asked to "Engineer" it. This implies a full-stack view, not just a script.
I should provide:
- Architecture Diagram (Text-based/Mermaid).
- Data Models (Topology, Failure).
- Python Prototype (Core logic using NetworkX).
- Example Output (What the training scenario looks like).
6. Drafting the Content (Mental Sandbox):
- Scenario: "The Cart Service is down."
- Graph: Cart -> DB, Cart -> Inventory.
- Failure: Database lock.
- Symptom: Users can't checkout.
- Resolution: Restart DB, kill locks.
How do I generate this?
- Load graph.
- Select "Cart Service".
- Identify dependencies. It depends on "Postgres-Orders".
- Select failure mode: "High Latency" on the edge between Cart and Postgres.
- Predict Impact: Cart timeout -> User facing 504s.
7. Adding "Advanced" Features (To make it "Engineered"):
- Blast Radius Scoring: Calculate how critical the failure is based on the centrality of the node in the graph.
- Observability Hints: Tell the trainee where to look (e.g., "Check Grafana dashboard X").
- Difficulty Levels: Easy (Pod kill), Hard (Network partition in specific availability zone).
8. Writing the Code (Mental Check):
Need networkx.
Graph nodes: Services, Databases, Load Balancers.
Graph edges: Calls, Dependencies.
Attributes: criticality, owner, tech_stack.
Generator Function:
Input: Graph.
Process:
- Select target (weighted by criticality).
- Select failure (weighted by rarity).
- Simulate propagation (mark nodes as 'unhealthy').
- Construct narrative.
9. Structuring the Response:
- Phase 1: System Architecture: Define the modules.
- Phase 2: Data Model: Define how topology is represented.
- Phase 3: Python Implementation: The core logic.
- Phase 4: The Output: An example generated scenario.
- Phase 5: Integration Guide: How to hook this into real tools (Gremlin, Chaos Mesh, K8s).
This looks solid. I will focus on a Python implementation using networkx because it's the industry standard for graph manipulation and easy for a prototype.
Self-Correction during drafting: Make sure not to just write a chaos engineering tool (like Chaos Monkey). This is a Scenario Generator. It creates the plan and story for a human to execute or observe, distinct from just blindly breaking things. It needs to produce a "Facilitator Guide" and an "Inject Message".
Let's refine the "Blast Radius" logic.
If Node A fails:
- Immediate children (who call A) will receive 5xx errors.
- Parents (who A calls) might see a drop in traffic (or be the cause of the failure).
I'll stick to a simplified "downstream impact" model for the prototype to keep it understandable.
Let's build the code structure.
class IncidentGenerator:
load_topology()
calculate_blast_radius()
generate_scenario()
Okay, ready to generate the response.
This is a comprehensive design and Python implementation for an Incident Simulation Generator. This system is designed to bridge the gap between static documentation and dynamic production realities.
1. System Architecture
The system consists of four core layers:
- Topology Ingestion Layer: Interfaces with infrastructure-as-code (Terraform), container orchestrators (Kubernetes), or Service Meshes to map the Nodes (services, databases, load balancers).
- Dependency Graph Engine: Constructs a Directed Acyclic Graph (DAG) to map Edges (sync/async calls, shared infrastructure dependencies).
- Failure Mode Library: A catalog of atomic failures (CPU Saturation, Packet Loss, Disk Full, TLS Certificate Expiry) tagged with complexity levels.
- Scenario Orchestrator: The logic that combines a Topology Node + A Failure Mode + A Blast Radius to generate a training scenario.
2. Python Implementation
We will use networkx for graph modeling, as it allows for complex traversal algorithms required to calculate "blast radius" (impact analysis).
Prerequisites
pip install networkx faker
The Core Engine
import networkx as nx
import random
from faker import Faker
from datetime import datetime, timedelta
from typing import List, Dict, Optional
from enum import Enum
import json
# ==========================================
# 1. Data Models & Enums
# ==========================================
class NodeType(Enum):
SERVICE = "Service"
DATABASE = "Database"
CACHE = "Cache"
QUEUE = "Queue"
LOAD_BALANCER = "LoadBalancer"
EXTERNAL_API = "ExternalAPI"
class FailureSeverity(Enum):
LOW = "degraded"
MEDIUM = "partial_outage"
HIGH = "major_outage"
class FailureMode:
def __init__(self, name: str, description: str, inject_command: str, complexity: int):
self.name = name
self.description = description
self.inject_command = inject_command # e.g., a Chaos Mesh spec or Linux command
self.complexity = complexity # 1-5 scale
# ==========================================
# 2. Topology & Graph Builder
# ==========================================
class TopologyGraph:
def __init__(self):
self.graph = nx.DiGraph()
self.fake = Faker()
def add_node(self, node_id: str, node_type: NodeType, tier: str):
self.graph.add_node(node_id, type=node_type, tier=tier)
def add_dependency(self, source: str, target: str, dependency_type: str = "sync"):
# Edge represents: Source depends on Target
self.graph.add_edge(source, target, rel=dependency_type)
def get_critical_nodes(self) -> List[str]:
"""Returns nodes with the highest in-degree (most things depend on it)."""
return sorted(self.graph.nodes, key=lambda n: self.graph.in_degree(n), reverse=True)
def get_downstream_impact(self, node_id: str) -> List[str]:
"""Find all nodes that depend on the failed node (Blast Radius)."""
if node_id not in self.graph:
return []
# descendants are nodes reachable from node_id
return list(nx.descendants(self.graph, node_id))
# ==========================================
# 3. Failure Mode Library
# ==========================================
class FailureLibrary:
@staticmethod
def get_modes() -> List[FailureMode]:
return [
FailureMode(
"High Latency (Network)",
"Injects 500ms delay in TCP packets",
"tc qdisc add dev eth0 root netem delay 500ms",
complexity=2
),
FailureMode(
"Database Connection Pool Exhaustion",
"Maxes out DB connections",
"stress-ng --io 4 --timeout 60s",
complexity=4
),
FailureMode(
"Disk I/O Saturation",
"Read/Write heavy load causing blocking",
"fio --name=randrw --runtime=120",
complexity=3
),
FailureMode(
"Service Crash (OOM)",
"Process killed by OS",
"kill -9 $(pidof node)",
complexity=1
),
FailureMode(
"DNS Failure",
"Random DNS lookup failures",
"iptables -A OUTPUT -p udp --dport 53 -j DROP",
complexity=5
)
]
# ==========================================
# 4. Scenario Generator Engine
# ==========================================
class IncidentScenarioGenerator:
def __init__(self, topology: TopologyGraph):
self.topology = topology
self.failures = FailureLibrary.get_modes()
def generate_scenario(self, difficulty_target: int = 3) -> Dict:
"""
Generates a complete incident scenario.
Logic: Selects a victim node -> Selects a failure -> Calculates Blast Radius.
"""
# 1. Select a Target
# Logic: Bias selection towards critical nodes for higher impact training
if random.random() > 0.7:
target_node = random.choice(self.topology.get_critical_nodes()[:5])
else:
target_node = random.choice(list(self.topology.graph.nodes))
node_data = self.topology.graph.nodes[target_node]
# 2. Select Failure Mode appropriate for Node Type
# (Simplified logic: Don't crash a load balancer if the scenario is DB connection pool)
valid_failures = [f for f in self.failures if f.complexity <= difficulty_target + 1]
selected_failure = random.choice(valid_failures)
# 3. Calculate Blast Radius
impacted_services = self.topology.get_downstream_impact(target_node)
# 4. Construct Narrative
scenario_id = f"INC-{random.randint(10000, 99999)}"
narrative = self._generate_narrative(target_node, node_data, selected_failure)
return {
"scenario_id": scenario_id,
"difficulty": selected_failure.complexity,
"target_infrastructure": {
"node_id": target_node,
"node_type": node_data['type'].value,
"tier": node_data['tier']
},
"failure_mode": selected_failure.name,
"inject_command": selected_failure.inject_command,
"blast_radius": impacted_services,
"narrative": narrative,
"sre_objectives": self._generate_slos(impacted_services)
}
def _generate_narrative(self, node, data, failure) -> str:
time = datetime.now().strftime("%H:%M:%S")
return (
f"[{time}] PagerDuty triggered: High Error Rate detected on {data['tier']} tier. "
f"Users reporting intermittent failures. "
f"Initial telemetry suggests {node} is experiencing {failure.description}."
)
def _generate_slos(self, impacted) -> List[str]:
objectives = []
if len(impacted) > 3:
objectives.append("Minimize Blast Radius: Ensure critical path services remain available.")
objectives.append(f"Restore availability to impacted services: {', '.join(impacted[:3])}")
objectives.append("MTTR Target: Resolution within 15 minutes.")
return objectives
# ==========================================
# 5. Execution & Demo
# ==========================================
def setup_mock_production_env():
"""
Simulates a real production topology generation.
In a real system, this would query Kubernetes API or Service Mesh CRDs.
"""
topo = TopologyGraph()
# Tiers
topo.add_node("Frontend-LB", NodeType.LOAD_BALANCER, "Edge")
topo.add_node("Web-Client", NodeType.SERVICE, "Frontend")
topo.add_node("API-Gateway", NodeType.SERVICE, "Backend")
topo.add_node("Auth-Service", NodeType.SERVICE, "Backend")
topo.add_node("Inventory-Svc", NodeType.SERVICE, "Application")
topo.add_node("Payment-Svc", NodeType.SERVICE, "Application")
topo.add_node("Users-DB", NodeType.DATABASE, "Data")
topo.add_node("Inventory-Cache", NodeType.CACHE, "Data")
topo.add_node("Orders-Queue", NodeType.QUEUE, "Data")
# Dependencies (Source -> Target)
topo.add_dependency("Frontend-LB", "Web-Client")
topo.add_dependency("Web-Client", "API-Gateway")
topo.add_dependency("API-Gateway", "Auth-Service")
topo.add_dependency("API-Gateway", "Inventory-Svc")
topo.add_dependency("API-Gateway", "Payment-Svc")
topo.add_dependency("Auth-Service", "Users-DB")
topo.add_dependency("Inventory-Svc", "Inventory-Cache")
topo.add_dependency("Payment-Svc", "Orders-Queue")
topo.add_dependency("Payment-Svc", "Users-DB") # Shared DB dependency
return topo
if __name__ == "__main__":
# 1. Build Topology
prod_topology = setup_mock_production_env()
# 2. Initialize Generator
generator = IncidentScenarioGenerator(prod_topology)
# 3. Generate a Scenario
print("--- Generating Incident Simulation ---\n")
scenario = generator.generate_scenario(difficulty_target=3)
print(json.dumps(scenario, indent=4))
3. How It Works
A. Dependency Graph Logic
The script constructs a Directed Graph.
- Nodes: Represent infrastructure components (Services, DBs, LBs).
- Edges: Represent communication flow. An edge
A -> B means "A depends on B".
B. Blast Radius Calculation
The get_downstream_impact function uses the networkx library to traverse the graph. If Users-DB fails, the generator traverses the graph in reverse direction to find that Auth-Service and Payment-Svc (and subsequently API-Gateway and Frontend) will be impacted. This allows the generator to create "realistic" narratives where a small database failure causes a frontend outage.
C. Output Format
The generated JSON provides a structured training scenario:
- Narrative: The "story" given to the trainee (what the user sees).
- Target & Failure: The "answer key" (what is actually broken).
- Blast Radius: Which services the trainee should see alerting.
- SRE Objectives: Success criteria for the drill (e.g., did they stop the cascade?).
4. Integration Strategy (Real World)
To move this from a prototype to a production tool, you would implement the following adapters:
- Kubernetes Adapter: Use
kubernetes.client to scan Deployments and Services.
- Service Mesh Adapter: Read Istio
VirtualService configs to accurately map A -> B dependencies (edges).
- Chaos Integration: Replace
inject_command strings with actual Chaos Mesh or Litmus Chaos CRD specs.
- Example: Instead of printing the command, the Generator applies a
NetworkChaos resource to the cluster automatically to start the drill.
5. Example Output
Running the code above might produce:
{
"scenario_id": "INC-88234",
"difficulty": 2,
"target_infrastructure": {
"node_id": "Users-DB",
"node_type": "Database",
"tier": "Data"
},
"failure_mode": "High Latency (Network)",
"inject_command": "tc qdisc add dev eth0 root netem delay 500ms",
"blast_radius": [
"Auth-Service",
"Payment-Svc",
"API-Gateway",
"Web-Client",
"Frontend-LB"
],
"narrative": "[14:20:00] PagerDuty triggered: High Error Rate detected on Data tier. Users reporting intermittent failures. Initial telemetry suggests Users-DB is experiencing Injects 500ms delay in TCP packets.",
"sre_objectives": [
"Restore availability to impacted services: Auth-Service, Payment-Svc, API-Gateway",
"MTTR Target: Resolution within 15 minutes."
]
}