import time
import random
import json
from dataclasses import dataclass, field
from typing import Dict, Any
from datetime import datetime
# --- System Simulation Models ---
@dataclass
class SystemSnapshot:
"""Represents a restore point."""
id: str
timestamp: str
config: Dict[str, Any]
code_version: str
data_hash: str
@dataclass
class SystemState:
"""Simulates the live environment."""
config: Dict[str, Any] = field(default_factory=lambda: {"feature_flags": {"new_ui": False}, "timeout": 30})
code_version: str = "v1.0.0-stable"
data_hash: str = "a1b2c3d4" # Represents a DB state hash
is_healthy: bool = True
def apply_update(self, new_config: dict, new_version: str):
print(f"!!! DEPLOYING {new_version} !!!")
self.code_version = new_version
self.config.update(new_config)
# Simulate a 20% chance of deployment failure
if random.random() < 0.2:
self.is_healthy = False
self.data_hash = "err_corrupt"
print("!!! CRITICAL FAILURE DETECTED DURING DEPLOYMENT !!!")
else:
print(">>> Deployment Successful.")
class RollbackOrchestrator:
def __init__(self):
self.metrics = {
"start_time": 0,
"end_time": 0,
"steps": [],
"success": False
}
self.backup_snapshot = None
def take_snapshot(self, system: SystemState) -> SystemSnapshot:
"""Simulates taking a backup before an operation."""
snapshot = SystemSnapshot(
id=f"snap-{int(time.time())}",
timestamp=datetime.now().isoformat(),
config=system.config.copy(),
code_version=system.code_version,
data_hash=system.data_hash
)
self.backup_snapshot = snapshot
print(f"[PREP] Snapshot taken: {snapshot.id} (Code: {snapshot.code_version})")
return snapshot
def _log_step(self, step_name: str, duration: float, status: str):
self.metrics["steps"].append({
"step": step_name,
"duration_sec": round(duration, 2),
"status": status
})
# --- Simulation Actions ---
def rollback_configuration(self, system: SystemState):
step_start = time.time()
print("\n--> [ROLLBACK] Reverting Configuration...")
# Simulate work
time.sleep(random.uniform(0.1, 0.5))
system.config = self.backup_snapshot.config
print(f"--> [ROLLBACK] Config reverted to: {system.config}")
self._log_step("Config Revert", time.time() - step_start, "SUCCESS")
def rollback_code(self, system: SystemState):
step_start = time.time()
print("\n--> [ROLLBACK] Reverting Binary/Code...")
# Simulate redeploying previous artifact
time.sleep(random.uniform(0.5, 1.5))
system.code_version = self.backup_snapshot.code_version
print(f"--> [ROLLBACK] Code reverted to: {system.code_version}")
self._log_step("Code Redeploy", time.time() - step_start, "SUCCESS")
def rollback_data(self, system: SystemState):
step_start = time.time()
print("\n--> [ROLLBACK] Restoring Data...")
# Simulate Database restore
restore_duration = random.uniform(1.0, 2.5)
time.sleep(restore_duration)
original_hash = self.backup_snapshot.data_hash
system.data_hash = original_hash
print(f"--> [ROLLBACK] Data restored. Integrity Hash: {system.data_hash}")
self._log_step("Data Restore", time.time() - step_start, "SUCCESS")
def verify_system(self, system: SystemState):
step_start = time.time()
print("\n--> [VERIFY] Running Smoke Tests...")
time.sleep(0.5)
# Check if current state matches snapshot state
is_config_match = system.config == self.backup_snapshot.config
is_code_match = system.code_version == self.backup_snapshot.code_version
is_data_match = system.data_hash == self.backup_snapshot.data_hash
if is_config_match and is_code_match and is_data_match:
system.is_healthy = True
print("--> [VERIFY] System Healthy. Rollback Complete.")
self._log_step("Smoke Test", time.time() - step_start, "PASSED")
return True
else:
print("--> [VERIFY] FAILED: State mismatch!")
self._log_step("Smoke Test", time.time() - step_start, "FAILED")
return False
# --- Main Runner ---
def execute_rehearsal(self):
live_system = SystemState()
print("--- STARTING ROLLBACK REHEARSAL PROGRAM ---")
# 1. Preparation
self.take_snapshot(live_system)
# 2. Simulate "Bad" Deployment
bad_config = {"feature_flags": {"new_ui": True}, "timeout": 10}
live_system.apply_update(bad_config, "v1.1.0-beta")
if live_system.is_healthy:
print("\nNo failure simulated. Ending rehearsal early.")
return
# 3. Execute Rollback
print("\n*** INITIATING ROLLBACK PROCEDURE ***")
self.metrics["start_time"] = time.time()
try:
# Order matters: Data first (usually), then Code, then Config (opinionated sequence)
self.rollback_data(live_system)
self.rollback_code(live_system)
self.rollback_configuration(live_system)
# 4. Verification
self.metrics["success"] = self.verify_system(live_system)
except Exception as e:
print(f"!!! EXCEPTION DURING ROLLBACK: {e} !!!")
self.metrics["success"] = False
self.metrics["end_time"] = time.time()
self.generate_report()
def generate_report(self):
total_duration = self.metrics["end_time"] - self.metrics["start_time"]
print("\n" + "="*40)
print(" ROLLBACK REHEARSAL METRICS ")
print("="*40)
print(f"Overall Status: {'SUCCESS' if self.metrics['success'] else 'FAILURE'}")
print(f"Total RTO (Recovery Time Objective): {total_duration:.2f} seconds")
print("-" * 40)
print("Step Breakdown:")
for step in self.metrics["steps"]:
print(f" - {step['step']}: {step['duration_sec']}s ({step['status']})")
print("="*40)
# Output JSON for ingestion by external monitoring tools
report_json = {
"rehearsal_type": "Rollback",
"timestamp": datetime.now().isoformat(),
"rto_seconds": total_duration,
"success": self.metrics["success"],
"steps": self.metrics["steps"]
}
# with open('rollback_report.json', 'w') as f:
# json.dump(report_json, f, indent=2)
if __name__ == "__main__":
orchestrator = RollbackOrchestrator()
orchestrator.execute_rehearsal()